context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Data; using Csla; using Csla.Data; using SelfLoad.DataAccess; using SelfLoad.DataAccess.ERCLevel; namespace SelfLoad.Business.ERCLevel { /// <summary> /// D11_CityRoadColl (editable child list).<br/> /// This is a generated base class of <see cref="D11_CityRoadColl"/> business object. /// </summary> /// <remarks> /// This class is child of <see cref="D10_City"/> editable child object.<br/> /// The items of the collection are <see cref="D12_CityRoad"/> objects. /// </remarks> [Serializable] public partial class D11_CityRoadColl : BusinessListBase<D11_CityRoadColl, D12_CityRoad> { #region Collection Business Methods /// <summary> /// Removes a <see cref="D12_CityRoad"/> item from the collection. /// </summary> /// <param name="cityRoad_ID">The CityRoad_ID of the item to be removed.</param> public void Remove(int cityRoad_ID) { foreach (var d12_CityRoad in this) { if (d12_CityRoad.CityRoad_ID == cityRoad_ID) { Remove(d12_CityRoad); break; } } } /// <summary> /// Determines whether a <see cref="D12_CityRoad"/> item is in the collection. /// </summary> /// <param name="cityRoad_ID">The CityRoad_ID of the item to search for.</param> /// <returns><c>true</c> if the D12_CityRoad is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int cityRoad_ID) { foreach (var d12_CityRoad in this) { if (d12_CityRoad.CityRoad_ID == cityRoad_ID) { return true; } } return false; } /// <summary> /// Determines whether a <see cref="D12_CityRoad"/> item is in the collection's DeletedList. /// </summary> /// <param name="cityRoad_ID">The CityRoad_ID of the item to search for.</param> /// <returns><c>true</c> if the D12_CityRoad is a deleted collection item; otherwise, <c>false</c>.</returns> public bool ContainsDeleted(int cityRoad_ID) { foreach (var d12_CityRoad in DeletedList) { if (d12_CityRoad.CityRoad_ID == cityRoad_ID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="D12_CityRoad"/> item of the <see cref="D11_CityRoadColl"/> collection, based on a given CityRoad_ID. /// </summary> /// <param name="cityRoad_ID">The CityRoad_ID.</param> /// <returns>A <see cref="D12_CityRoad"/> object.</returns> public D12_CityRoad FindD12_CityRoadByCityRoad_ID(int cityRoad_ID) { for (var i = 0; i < this.Count; i++) { if (this[i].CityRoad_ID.Equals(cityRoad_ID)) { return this[i]; } } return null; } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="D11_CityRoadColl"/> collection. /// </summary> /// <returns>A reference to the created <see cref="D11_CityRoadColl"/> collection.</returns> internal static D11_CityRoadColl NewD11_CityRoadColl() { return DataPortal.CreateChild<D11_CityRoadColl>(); } /// <summary> /// Factory method. Loads a <see cref="D11_CityRoadColl"/> collection, based on given parameters. /// </summary> /// <param name="parent_City_ID">The Parent_City_ID parameter of the D11_CityRoadColl to fetch.</param> /// <returns>A reference to the fetched <see cref="D11_CityRoadColl"/> collection.</returns> internal static D11_CityRoadColl GetD11_CityRoadColl(int parent_City_ID) { return DataPortal.FetchChild<D11_CityRoadColl>(parent_City_ID); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="D11_CityRoadColl"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public D11_CityRoadColl() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = true; AllowEdit = true; AllowRemove = true; RaiseListChangedEvents = rlce; } #endregion #region Data Access /// <summary> /// Loads a <see cref="D11_CityRoadColl"/> collection from the database, based on given criteria. /// </summary> /// <param name="parent_City_ID">The Parent City ID.</param> protected void Child_Fetch(int parent_City_ID) { var args = new DataPortalHookArgs(parent_City_ID); OnFetchPre(args); using (var dalManager = DalFactorySelfLoad.GetManager()) { var dal = dalManager.GetProvider<ID11_CityRoadCollDal>(); var data = dal.Fetch(parent_City_ID); LoadCollection(data); } OnFetchPost(args); } private void LoadCollection(IDataReader data) { using (var dr = new SafeDataReader(data)) { Fetch(dr); } } /// <summary> /// Loads all <see cref="D11_CityRoadColl"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; while (dr.Read()) { Add(D12_CityRoad.GetD12_CityRoad(dr)); } RaiseListChangedEvents = rlce; } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); #endregion } }
using System; using Android.App; using Android.Content; using Android.Content.PM; using Android.OS; using Android.Support.V7.App; using Android.Views; using Android.Widget; using System.Collections.Generic; using System.Linq; using Android; using Android.Support.V4.App; using Android.Support.V4.Content; using Android.Support.V4.Widget; using FtApp.Droid.Activities.About; using FtApp.Droid.Activities.AppRating; using FtApp.Droid.Activities.ControlInterface; using FtApp.Droid.Activities.Help; using FtApp.Fischertechnik; using AlertDialog = Android.Support.V7.App.AlertDialog; using BluetoothAdapter = Android.Bluetooth.BluetoothAdapter; using Toolbar = Android.Support.V7.Widget.Toolbar; namespace FtApp.Droid.Activities.SelectDevice { [Activity(Label = "Ft App", MainLauncher = true, Icon = "@drawable/icon", Theme = "@style/FtApp.Base", ScreenOrientation = ScreenOrientation.Portrait)] // ReSharper disable once ClassNeverInstantiated.Global public class SelectDeviceActivity : AppCompatActivity { private const int EnableBluetoothRequestId = 1; private const int PermissionRequestAccessCoarseLocationId = 1; private ListView _listViewDevices; private FoundDevicesListAdapter _foundDevicesListAdapter; private ProgressBar _progressBarScanning; private LinearLayout _layoutListEmpty; private SwipeRefreshLayout _listRefreshLayout; private InterfaceSearchAsyncTask _interfaceSearchAsyncTask; private readonly List<InterfaceViewModel> _foundDevices; private bool _searching; public SelectDeviceActivity() { _foundDevices = new List<InterfaceViewModel>(); } protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.ActivitySelectDeviceLayout); _foundDevices.Clear(); _listViewDevices = FindViewById<ListView>(Resource.Id.devicesListView); _progressBarScanning = FindViewById<ProgressBar>(Resource.Id.progressBarScanning); _layoutListEmpty = FindViewById<LinearLayout>(Resource.Id.layoutInterfaceListEmpty); _listRefreshLayout = FindViewById<SwipeRefreshLayout>(Resource.Id.listInterfacesRefresh); _layoutListEmpty.Visibility = ViewStates.Gone; _listRefreshLayout.SetColorSchemeResources(new[] { Resource.Color.accentColor, Resource.Color.primaryColor }); _listRefreshLayout.Refresh += ListRefreshLayoutOnRefresh; if (savedInstanceState == null) { RatingDialog.RequestRatingReminder(this); } SetupToolbar(); SetupListView(); } private void ListRefreshLayoutOnRefresh(object sender, EventArgs eventArgs) { if (!_searching) { CancelSearch(); SearchForInterfaces(); } } protected override void OnStart() { base.OnStart(); _foundDevices.Clear(); SearchForInterfaces(); } protected override void OnPause() { base.OnPause(); CancelSearch(); } protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (requestCode == EnableBluetoothRequestId) { if (resultCode == Result.Ok) { SearchForInterfaces(); } if (resultCode == Result.Canceled) { Toast.MakeText(this, Resource.String.SelectDeviceActivity_bluetoothHasToBeEnabled, ToastLength.Short).Show(); SearchForInterfaces(); } } } public override bool OnPrepareOptionsMenu(IMenu menu) { if (menu.Size() == 0) { MenuInflater.Inflate(Resource.Menu.SelectDeviceOptionsMenu, menu); } return true; } public override bool OnOptionsItemSelected(IMenuItem item) { switch (item.ItemId) { case Resource.Id.optionsMenuItemSimulate: OpenControlActivity(".", GetString(Resource.String.ControlInterfaceActivity_simulatedInterfaceName), ControllerType.Simulate); return true; case Resource.Id.optionsMenuItemAbout: OpenAboutActivity(); return true; case Resource.Id.optionsMenuItemHelp: OpenHelpActivity(); return true; } return base.OnOptionsItemSelected(item); } private void SetupListView() { _listViewDevices.Divider = null; _listViewDevices.DividerHeight = 0; _listViewDevices.ItemClick += ListViewDevicesOnItemClick; _foundDevicesListAdapter = new FoundDevicesListAdapter(this, _foundDevices); _listViewDevices.Adapter = _foundDevicesListAdapter; } private void SetupToolbar() { var toolbar = FindViewById<Toolbar>(Resource.Id.toolbar); SetSupportActionBar(toolbar); SupportActionBar.Title = Resources.GetString(Resource.String.SelectDeviceActivity_toolbarTitle); } private void ListViewDevicesOnItemClick(object sender, AdapterView.ItemClickEventArgs itemClickEventArgs) { if (_foundDevices.Count > itemClickEventArgs.Id) { var clickedItem = _foundDevices[(int)itemClickEventArgs.Id]; OpenControlActivity(clickedItem.Address, clickedItem.Name, clickedItem.ControllerType); } } private void OpenControlActivity(string address, string name, ControllerType type) { CancelSearch(); // Open the control activity and pass the extra data Intent intent = new Intent(this, typeof(ControlInterfaceActivity)); intent.PutExtra(ControlInterfaceActivity.AddressExtraDataId, address); intent.PutExtra(ControlInterfaceActivity.ControllerNameExtraDataId, name); intent.PutExtra(ControlInterfaceActivity.ControllerTypeExtraDataId, (int)type); StartActivity(intent); } private void OpenAboutActivity() { _interfaceSearchAsyncTask?.CancelSearch(); Intent intent = new Intent(this, typeof(AboutActivity)); StartActivity(intent); OverridePendingTransition(Android.Resource.Animation.FadeIn, Android.Resource.Animation.FadeOut); } private void OpenHelpActivity() { _interfaceSearchAsyncTask?.CancelSearch(); Intent intent = new Intent(this, typeof(HelpActivity)); StartActivity(intent); OverridePendingTransition(Android.Resource.Animation.FadeIn, Android.Resource.Animation.FadeOut); } private void SearchForInterfaces() { if (BluetoothAdapter.DefaultAdapter != null) { if (!BluetoothAdapter.DefaultAdapter.IsEnabled) { Toast.MakeText(this, Resource.String.SelectDeviceActivity_bluetoothHasToBeEnabled, ToastLength.Short).Show(); } } else { Toast.MakeText(this, Resource.String.SelectDeviceActivity_noBluetooth, ToastLength.Short).Show(); } HideEmptyStateImage(); _interfaceSearchAsyncTask = new InterfaceSearchAsyncTask(this); _interfaceSearchAsyncTask.ProgressUpdated += InterfaceSearchAsyncTaskOnProgressUpdated; _interfaceSearchAsyncTask.SearchFinished += InterfaceSearchAsyncTaskOnSearchFinished; _interfaceSearchAsyncTask.Execute(string.Empty); _progressBarScanning.Visibility = ViewStates.Visible; _searching = true; _foundDevices.Clear(); _foundDevicesListAdapter.NotifyDataSetChanged(); } private void CancelSearch() { _interfaceSearchAsyncTask?.CancelSearch(); _searching = false; _listRefreshLayout.Refreshing = false; } private void InterfaceSearchAsyncTaskOnSearchFinished(object sender, InterfaceSearchAsyncTask.SearchFinishedEventArgs eventArgs) { if (_foundDevices.Count > 0) { HideEmptyStateImage(); } else { ShowEmptyStateImage(); } _listRefreshLayout.Refreshing = false; _searching = false; _progressBarScanning.Visibility = ViewStates.Invisible; _foundDevicesListAdapter.NotifyDataSetChanged(); } private void InterfaceSearchAsyncTaskOnProgressUpdated(object sender, InterfaceSearchAsyncTask.ProgressUpdatedEventArgs eventArgs) { RunOnUiThread(() => { if (_foundDevices.Count(model => model.Address == eventArgs.Interface.Address) == 0) { _foundDevices.Add(eventArgs.Interface); _foundDevicesListAdapter.NotifyDataSetChanged(); } }); } private void ShowEmptyStateImage() { _layoutListEmpty.Alpha = 0; _layoutListEmpty.Visibility = ViewStates.Visible; _layoutListEmpty.Animate().Alpha(1).SetDuration(225).SetListener(null).Start(); } private void HideEmptyStateImage() { _layoutListEmpty.Alpha = 1; _layoutListEmpty.Animate().Alpha(0).SetDuration(225).SetListener(new HideOnFinishedAnimationListener(_layoutListEmpty)).Start(); } } }
#region Apache Notice /***************************************************************************** * $Header: $ * $Revision: 469233 $ * $Date: 2006-10-30 12:09:11 -0700 (Mon, 30 Oct 2006) $ * Author : Gilles Bayon * iBATIS.NET Data Mapper * Copyright (C) 2004 - Apache Fondation * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************************/ #endregion #region Using using System; using System.Collections; using System.Collections.Specialized; using System.Xml.Serialization; using IBatisNet.DataMapper.MappedStatements.PropertyStrategy; using IBatisNet.DataMapper.Scope; #endregion namespace IBatisNet.DataMapper.Configuration.ResultMapping { /// <summary> /// Summary description for Discriminator. /// </summary> [Serializable] [XmlRoot("discriminator", Namespace="http://ibatis.apache.org/mapping")] public class Discriminator { #region Fields [NonSerialized] private ResultProperty _mapping = null; /// <summary> /// (discriminatorValue (string), ResultMap) /// </summary> [NonSerialized] private HybridDictionary _resultMaps = null; /// <summary> /// The subMaps name who used this discriminator /// </summary> [NonSerialized] private ArrayList _subMaps = null; [NonSerialized] private string _nullValue = string.Empty; [NonSerialized] private string _columnName = string.Empty; [NonSerialized] private int _columnIndex = ResultProperty.UNKNOWN_COLUMN_INDEX; [NonSerialized] private string _dbType = string.Empty; [NonSerialized] private string _clrType = string.Empty; [NonSerialized] private string _callBackName= string.Empty; #endregion #region Properties /// <summary> /// Specify the custom type handlers to used. /// </summary> /// <remarks>Will be an alias to a class wchic implement ITypeHandlerCallback</remarks> [XmlAttribute("typeHandler")] public string CallBackName { get { return _callBackName; } set { _callBackName = value; } } /// <summary> /// Give an entry in the 'DbType' enumeration /// </summary> /// <example > /// For Sql Server, give an entry of SqlDbType : Bit, Decimal, Money... /// <br/> /// For Oracle, give an OracleType Enumeration : Byte, Int16, Number... /// </example> [XmlAttribute("dbType")] public string DbType { get { return _dbType; } set { _dbType = value; } } /// <summary> /// Specify the CLR type of the result. /// </summary> /// <remarks> /// The type attribute is used to explicitly specify the property type of the property to be set. /// Normally this can be derived from a property through reflection, but certain mappings such as /// HashTable cannot provide the type to the framework. /// </remarks> [XmlAttribute("type")] public string CLRType { get { return _clrType; } set { _clrType = value; } } /// <summary> /// Column Index /// </summary> [XmlAttribute("columnIndex")] public int ColumnIndex { get { return _columnIndex; } set { _columnIndex = value; } } /// <summary> /// Column Name /// </summary> [XmlAttribute("column")] public string ColumnName { get { return _columnName; } set { _columnName = value; } } /// <summary> /// Null value replacement. /// </summary> /// <example>"no_email@provided.com"</example> [XmlAttribute("nullValue")] public string NullValue { get { return _nullValue; } set { _nullValue = value; } } /// <summary> /// Th underlying ResultProperty /// </summary> [XmlIgnore] public ResultProperty ResultProperty { get { return _mapping; } } #endregion #region Constructor /// <summary> /// Constructor /// </summary> public Discriminator() { _resultMaps = new HybridDictionary(); _subMaps = new ArrayList(); } #endregion #region Methods /// <summary> /// Initilaize the underlying mapping /// </summary> /// <param name="configScope"></param> /// <param name="resultClass"></param> public void SetMapping(ConfigurationScope configScope, Type resultClass) { configScope.ErrorContext.MoreInfo = "Initialize discriminator mapping"; _mapping = new ResultProperty(); _mapping.ColumnName = _columnName; _mapping.ColumnIndex = _columnIndex; _mapping.CLRType = _clrType; _mapping.CallBackName = _callBackName; _mapping.DbType = _dbType; _mapping.NullValue = _nullValue; _mapping.Initialize( configScope, resultClass ); } /// <summary> /// Initialize the Discriminator /// </summary> /// <param name="configScope"></param> public void Initialize(ConfigurationScope configScope) { // Set the ResultMaps int count = _subMaps.Count; for(int index=0; index<count; index++) { SubMap subMap = _subMaps[index] as SubMap; _resultMaps.Add(subMap.DiscriminatorValue, configScope.SqlMapper.GetResultMap( subMap.ResultMapName ) ); } } /// <summary> /// Add a subMap that the discrimator must treat /// </summary> /// <param name="subMap">A subMap</param> public void Add(SubMap subMap) { _subMaps.Add(subMap); } /// <summary> /// Find the SubMap to use. /// </summary> /// <param name="discriminatorValue">the discriminator value</param> /// <returns>The find ResultMap</returns> public IResultMap GetSubMap(string discriminatorValue) { return _resultMaps[discriminatorValue] as ResultMap; } #endregion } }
using System.Collections.Generic; using Content.Client.GameObjects.Components.Research; using Content.Shared.Research; using Robust.Client.Graphics; using Robust.Client.UserInterface.Controls; using Robust.Client.UserInterface.CustomControls; using Robust.Client.Utility; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Maths; using Robust.Shared.Prototypes; namespace Content.Client.Research { public class ResearchConsoleMenu : SS14Window { public ResearchConsoleBoundUserInterface Owner { get; set; } protected override Vector2? CustomSize => (800, 400); private List<TechnologyPrototype> _unlockedTechnologyPrototypes = new List<TechnologyPrototype>(); private List<TechnologyPrototype> _unlockableTechnologyPrototypes = new List<TechnologyPrototype>(); private List<TechnologyPrototype> _futureTechnologyPrototypes = new List<TechnologyPrototype>(); private Label _pointLabel; private Label _pointsPerSecondLabel; private Label _technologyName; private Label _technologyDescription; private Label _technologyRequirements; private TextureRect _technologyIcon; private ItemList _unlockedTechnologies; private ItemList _unlockableTechnologies; private ItemList _futureTechnologies; public Button UnlockButton { get; private set; } public Button ServerSelectionButton { get; private set; } public Button ServerSyncButton { get; private set; } public TechnologyPrototype TechnologySelected; public ResearchConsoleMenu(ResearchConsoleBoundUserInterface owner = null) { IoCManager.InjectDependencies(this); Title = Loc.GetString("R&D Console"); Owner = owner; _unlockedTechnologies = new ItemList() { SelectMode = ItemList.ItemListSelectMode.Button, SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsVertical = SizeFlags.FillExpand, }; _unlockedTechnologies.OnItemSelected += UnlockedTechnologySelected; _unlockableTechnologies = new ItemList() { SelectMode = ItemList.ItemListSelectMode.Button, SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsVertical = SizeFlags.FillExpand, }; _unlockableTechnologies.OnItemSelected += UnlockableTechnologySelected; _futureTechnologies = new ItemList() { SelectMode = ItemList.ItemListSelectMode.Button, SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsVertical = SizeFlags.FillExpand, }; _futureTechnologies.OnItemSelected += FutureTechnologySelected; var vbox = new VBoxContainer() { SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsVertical = SizeFlags.FillExpand, }; var hboxTechnologies = new HBoxContainer() { SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsVertical = SizeFlags.FillExpand, SizeFlagsStretchRatio = 2, SeparationOverride = 10, }; var hboxSelected = new HBoxContainer() { SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsVertical = SizeFlags.FillExpand, SizeFlagsStretchRatio = 1 }; var vboxPoints = new VBoxContainer() { SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsVertical = SizeFlags.FillExpand, SizeFlagsStretchRatio = 1, }; var vboxTechInfo = new VBoxContainer() { SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsVertical = SizeFlags.FillExpand, SizeFlagsStretchRatio = 3, }; _pointLabel = new Label() { Text = Loc.GetString("Research Points") + ": 0" }; _pointsPerSecondLabel = new Label() { Text = Loc.GetString("Points per Second") + ": 0" }; var vboxPointsButtons = new VBoxContainer() { Align = BoxContainer.AlignMode.End, SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsVertical = SizeFlags.FillExpand, }; ServerSelectionButton = new Button() { Text = Loc.GetString("Server list") }; ServerSyncButton = new Button() { Text = Loc.GetString("Sync")}; UnlockButton = new Button() { Text = Loc.GetString("Unlock"), Disabled = true }; vboxPointsButtons.AddChild(ServerSelectionButton); vboxPointsButtons.AddChild(ServerSyncButton); vboxPointsButtons.AddChild(UnlockButton); vboxPoints.AddChild(_pointLabel); vboxPoints.AddChild(_pointsPerSecondLabel); vboxPoints.AddChild(vboxPointsButtons); _technologyIcon = new TextureRect() { SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsVertical = SizeFlags.FillExpand, SizeFlagsStretchRatio = 1, Stretch = TextureRect.StretchMode.KeepAspectCentered, }; _technologyName = new Label(); _technologyDescription = new Label(); _technologyRequirements = new Label(); vboxTechInfo.AddChild(_technologyName); vboxTechInfo.AddChild(_technologyDescription); vboxTechInfo.AddChild(_technologyRequirements); hboxSelected.AddChild(_technologyIcon); hboxSelected.AddChild(vboxTechInfo); hboxSelected.AddChild(vboxPoints); hboxTechnologies.AddChild(_unlockedTechnologies); hboxTechnologies.AddChild(_unlockableTechnologies); hboxTechnologies.AddChild(_futureTechnologies); vbox.AddChild(hboxTechnologies); vbox.AddChild(hboxSelected); Contents.AddChild(vbox); UnlockButton.OnPressed += (args) => { CleanSelectedTechnology(); }; Populate(); } /// <summary> /// Cleans the selected technology controls to blank. /// </summary> private void CleanSelectedTechnology() { UnlockButton.Disabled = true; _technologyIcon.Texture = Texture.Transparent; _technologyName.Text = ""; _technologyDescription.Text = ""; _technologyRequirements.Text = ""; } /// <summary> /// Called when an unlocked technology is selected. /// </summary> private void UnlockedTechnologySelected(ItemList.ItemListSelectedEventArgs obj) { TechnologySelected = _unlockedTechnologyPrototypes[obj.ItemIndex]; UnlockButton.Disabled = true; PopulateSelectedTechnology(); } /// <summary> /// Called when an unlockable technology is selected. /// </summary> private void UnlockableTechnologySelected(ItemList.ItemListSelectedEventArgs obj) { TechnologySelected = _unlockableTechnologyPrototypes[obj.ItemIndex]; UnlockButton.Disabled = Owner.Points < TechnologySelected.RequiredPoints; PopulateSelectedTechnology(); } /// <summary> /// Called when a future technology is selected /// </summary> private void FutureTechnologySelected(ItemList.ItemListSelectedEventArgs obj) { TechnologySelected = _futureTechnologyPrototypes[obj.ItemIndex]; UnlockButton.Disabled = true; PopulateSelectedTechnology(); } /// <summary> /// Populate all technologies in the ItemLists. /// </summary> public void PopulateItemLists() { _unlockedTechnologies.Clear(); _unlockableTechnologies.Clear(); _futureTechnologies.Clear(); _unlockedTechnologyPrototypes.Clear(); _unlockableTechnologyPrototypes.Clear(); _futureTechnologyPrototypes.Clear(); var prototypeMan = IoCManager.Resolve<IPrototypeManager>(); // For now, we retrieve all technologies. In the future, this should be changed. foreach (var tech in prototypeMan.EnumeratePrototypes<TechnologyPrototype>()) { if (Owner.IsTechnologyUnlocked(tech)) { _unlockedTechnologies.AddItem(tech.Name, tech.Icon.Frame0()); _unlockedTechnologyPrototypes.Add(tech); } else if (Owner.CanUnlockTechnology(tech)) { _unlockableTechnologies.AddItem(tech.Name, tech.Icon.Frame0()); _unlockableTechnologyPrototypes.Add(tech); } else { _futureTechnologies.AddItem(tech.Name, tech.Icon.Frame0()); _futureTechnologyPrototypes.Add(tech); } } } /// <summary> /// Fills the selected technology controls with details. /// </summary> public void PopulateSelectedTechnology() { if (TechnologySelected == null) { _technologyName.Text = ""; _technologyDescription.Text = ""; _technologyRequirements.Text = ""; return; } _technologyIcon.Texture = TechnologySelected.Icon.Frame0(); _technologyName.Text = TechnologySelected.Name; _technologyDescription.Text = TechnologySelected.Description+$"\n{TechnologySelected.RequiredPoints} " + Loc.GetString("research points"); _technologyRequirements.Text = Loc.GetString("No technology requirements."); var prototypeMan = IoCManager.Resolve<IPrototypeManager>(); for (var i = 0; i < TechnologySelected.RequiredTechnologies.Count; i++) { var requiredId = TechnologySelected.RequiredTechnologies[i]; if (!prototypeMan.TryIndex(requiredId, out TechnologyPrototype prototype)) continue; if (i == 0) _technologyRequirements.Text = Loc.GetString("Requires") + $": {prototype.Name}"; else _technologyRequirements.Text += $", {prototype.Name}"; } } /// <summary> /// Updates the research point labels. /// </summary> public void PopulatePoints() { _pointLabel.Text = Loc.GetString("Research Points") + $": {Owner.Points}"; _pointsPerSecondLabel.Text = Loc.GetString("Points per second") + $": {Owner.PointsPerSecond}"; } /// <summary> /// Updates the whole user interface. /// </summary> public void Populate() { PopulatePoints(); PopulateSelectedTechnology(); PopulateItemLists(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: A representation of an IEEE double precision ** floating point number. ** ** ===========================================================*/ using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct Double : IComparable, IConvertible, IFormattable, IComparable<Double>, IEquatable<Double> { private double m_value; // Do not rename (binary serialization) // // Public Constants // public const double MinValue = -1.7976931348623157E+308; public const double MaxValue = 1.7976931348623157E+308; // Note Epsilon should be a double whose hex representation is 0x1 // on little endian machines. public const double Epsilon = 4.9406564584124654E-324; public const double NegativeInfinity = (double)-1.0 / (double)(0.0); public const double PositiveInfinity = (double)1.0 / (double)(0.0); public const double NaN = (double)0.0 / (double)0.0; // We use this explicit definition to avoid the confusion between 0.0 and -0.0. internal const double NegativeZero = -0.0; /// <summary>Determines whether the specified value is finite (zero, subnormal, or normal).</summary> [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsFinite(double d) { var bits = BitConverter.DoubleToInt64Bits(d); return (bits & 0x7FFFFFFFFFFFFFFF) < 0x7FF0000000000000; } /// <summary>Determines whether the specified value is infinite.</summary> [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsInfinity(double d) { var bits = BitConverter.DoubleToInt64Bits(d); return (bits & 0x7FFFFFFFFFFFFFFF) == 0x7FF0000000000000; } /// <summary>Determines whether the specified value is NaN.</summary> [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsNaN(double d) { var bits = BitConverter.DoubleToInt64Bits(d); return (bits & 0x7FFFFFFFFFFFFFFF) > 0x7FF0000000000000; } /// <summary>Determines whether the specified value is negative.</summary> [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsNegative(double d) { var bits = unchecked((ulong)BitConverter.DoubleToInt64Bits(d)); return (bits & 0x8000000000000000) == 0x8000000000000000; } /// <summary>Determines whether the specified value is negative infinity.</summary> [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNegativeInfinity(double d) { return (d == double.NegativeInfinity); } /// <summary>Determines whether the specified value is normal.</summary> [Pure] [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called public unsafe static bool IsNormal(double d) { var bits = BitConverter.DoubleToInt64Bits(d); bits &= 0x7FFFFFFFFFFFFFFF; return (bits < 0x7FF0000000000000) && (bits != 0) && ((bits & 0x7FF0000000000000) != 0); } /// <summary>Determines whether the specified value is positive infinity.</summary> [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsPositiveInfinity(double d) { return (d == double.PositiveInfinity); } /// <summary>Determines whether the specified value is subnormal.</summary> [Pure] [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called public unsafe static bool IsSubnormal(double d) { var bits = BitConverter.DoubleToInt64Bits(d); bits &= 0x7FFFFFFFFFFFFFFF; return (bits < 0x7FF0000000000000) && (bits != 0) && ((bits & 0x7FF0000000000000) == 0); } // Compares this object to another object, returning an instance of System.Relation. // Null is considered less than any instance. // // If object is not of type Double, this method throws an ArgumentException. // // Returns a value less than zero if this object // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is Double) { double d = (double)value; if (m_value < d) return -1; if (m_value > d) return 1; if (m_value == d) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(d) ? 0 : -1); else return 1; } throw new ArgumentException(SR.Arg_MustBeDouble); } public int CompareTo(Double value) { if (m_value < value) return -1; if (m_value > value) return 1; if (m_value == value) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(value) ? 0 : -1); else return 1; } // True if obj is another Double with the same value as the current instance. This is // a method of object equality, that only returns true if obj is also a double. public override bool Equals(Object obj) { if (!(obj is Double)) { return false; } double temp = ((Double)obj).m_value; // This code below is written this way for performance reasons i.e the != and == check is intentional. if (temp == m_value) { return true; } return IsNaN(temp) && IsNaN(m_value); } [NonVersionable] public static bool operator ==(Double left, Double right) { return left == right; } [NonVersionable] public static bool operator !=(Double left, Double right) { return left != right; } [NonVersionable] public static bool operator <(Double left, Double right) { return left < right; } [NonVersionable] public static bool operator >(Double left, Double right) { return left > right; } [NonVersionable] public static bool operator <=(Double left, Double right) { return left <= right; } [NonVersionable] public static bool operator >=(Double left, Double right) { return left >= right; } public bool Equals(Double obj) { if (obj == m_value) { return true; } return IsNaN(obj) && IsNaN(m_value); } //The hashcode for a double is the absolute value of the integer representation //of that double. // public unsafe override int GetHashCode() { double d = m_value; if (d == 0) { // Ensure that 0 and -0 have the same hash code return 0; } long value = *(long*)(&d); return unchecked((int)value) ^ ((int)(value >> 32)); } public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatDouble(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatDouble(m_value, format, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatDouble(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatDouble(m_value, format, NumberFormatInfo.GetInstance(provider)); } public static double Parse(String s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDouble(s.AsSpan(), NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo); } public static double Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDouble(s.AsSpan(), style, NumberFormatInfo.CurrentInfo); } public static double Parse(String s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDouble(s.AsSpan(), NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider)); } public static double Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDouble(s.AsSpan(), style, NumberFormatInfo.GetInstance(provider)); } // Parses a double from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // // This method will not throw an OverflowException, but will return // PositiveInfinity or NegativeInfinity for a number that is too // large or too small. public static double Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Number.ParseDouble(s, style, NumberFormatInfo.GetInstance(provider)); } public static bool TryParse(String s, out double result) { if (s == null) { result = 0; return false; } return TryParse(s.AsSpan(), NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out double result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) { result = 0; return false; } return TryParse(s.AsSpan(), style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan<char> s, out double result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out double result) { bool success = Number.TryParseDouble(s, style, info, out result); if (!success) { ReadOnlySpan<char> sTrim = StringSpanHelpers.Trim(s); if (StringSpanHelpers.Equals(sTrim, info.PositiveInfinitySymbol)) { result = PositiveInfinity; } else if (StringSpanHelpers.Equals(sTrim, info.NegativeInfinitySymbol)) { result = NegativeInfinity; } else if (StringSpanHelpers.Equals(sTrim, info.NaNSymbol)) { result = NaN; } else { return false; // We really failed } } return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Double; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Double", "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider provider) { return m_value; } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Double", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
using System.Collections.Generic; using System.IO; using Xe.BinaryMapper; using OpenKh.Common.Utils; namespace OpenKh.Bbs { public class Olo { private const int MagicCode = 0x4F4C4F40; // Always @OLO public class Header { [Data] public int MagicCode { get; set; } [Data] public ushort FileVersion { get; set; } [Data] public ushort Flag { get; set; } [Data] public uint SpawnObjectsCount { get; set; } [Data] public uint SpawnObjectsOffset { get; set; } [Data] public uint FilePathCount { get; set; } [Data] public uint FilePathOffset { get; set; } [Data] public uint ScriptPathCount { get; set; } [Data] public uint ScriptPathOffset { get; set; } [Data] public uint MissionNameCount { get; set; } [Data] public uint MissionNameOffset { get; set; } [Data] public uint TriggerDataCount { get; set; } [Data] public uint TriggerDataOffset { get; set; } [Data] public uint GroupDataCount { get; set; } [Data] public uint GroupDataOffset { get; set; } [Data] public uint padding1 { get; set; } [Data] public uint padding2 { get; set; } } public enum OLOFlag { FLAG_NONE = 0, FLAG_ENEMY = 1, FLAG_GIMMICK = 2, FLAG_NPC = 4, FLAG_PLAYER = 8, FLAG_EVENT_TRIGGER = 16, } public class ObjectName { [Data(Count = 16)] public string Name { get; set; } } public class PathName { [Data (Count = 32)] public string Name { get; set; } } public class TriggerData { [Data] public float PositionX { get; set; } [Data] public float PositionY { get; set; } [Data] public float PositionZ { get; set; } [Data] public float ScaleX { get; set; } [Data] public float ScaleY { get; set; } [Data] public float ScaleZ { get; set; } [Data] public uint ID { get; set; } [Data] public uint Behavior { get; set; } [Data] public ushort Param1 { get; set; } [Data] public ushort Param2 { get; set; } [Data] public uint CTDid { get; set; } [Data] public uint TypeRef { get; set; } [Data] public float Yaw { get; set; } } public enum TriggerType { SCENE_JUMP, APPEAR_ENEMY, BEGIN_GIMMICK, BEGIN_EVENT, DESTINATION, MESSAGE, MISSION } public enum TriggerShape { SHAPE_BOX, SHAPE_SPHERE, SHAPE_CYLINDER } public class TriggerBehavior { [Data] public TriggerType Type { get; set; } [Data] public TriggerShape Shape { get; set; } [Data] public bool Fire { get; set; } [Data] public bool Stop { get; set; } [Data] public uint Padding { get; set; } } public static TriggerBehavior GetTriggerBehavior(uint value) { TriggerBehavior behavior = new TriggerBehavior(); behavior.Type = (TriggerType)BitsUtil.Int.GetBits((int)value, 0, 4); behavior.Shape = (TriggerShape)BitsUtil.Int.GetBits((int)value, 4, 4); behavior.Fire = BitsUtil.Int.GetBit((int)value, 8); behavior.Stop = BitsUtil.Int.GetBit((int)value, 9); return behavior; } public static uint MakeTriggerBehavior(TriggerType type, TriggerShape shape, bool Fire, bool Stop) { uint val = 0; val = BitsUtil.Int.SetBits(val, 0, 4, (uint)type); val = BitsUtil.Int.SetBits(val, 4, 4, (uint)shape); val = BitsUtil.Int.SetBit(val, 8, Fire); val = BitsUtil.Int.SetBit(val, 9, Stop); return val; } public class GroupData { [Data] public float CenterX { get; set; } [Data] public float CenterY { get; set; } [Data] public float CenterZ { get; set; } [Data] public float Radius { get; set; } [Data] public uint TriggerID { get; set; } [Data] public uint Flag { get; set; } [Data] public float AppearParameter { get; set; } [Data] public uint NextGroupDataOffset { get; set; } [Data] public float DeadRate { get; set; } [Data] public ushort GameTrigger { get; set; } [Data] public byte MissionParameter { get; set; } [Data] public byte UnkParameter { get; set; } [Data] public uint ObjectLayoutDataCount { get; set; } [Data] public uint ObjectLayoutDataOffset { get; set; } } public enum AppearType { APPEAR_NONE, APPEAR_TYPE_PLAYER_DISTANCE, APPEAR_TYPE_SPECIFIED, APPEAR_TYPE_NPC_DISTANCE } public class GroupFlag { [Data] public AppearType Type { get; set; } [Data] public bool Linked { get; set; } [Data] public bool AppearOK { get; set; } [Data] public bool LinkInvoke { get; set; } [Data] public byte Step { get; set; } [Data] public bool Fire { get; set; } [Data] public byte ID { get; set; } [Data] public bool Specified { get; set; } [Data] public bool GameTriggerFire { get; set; } [Data] public bool MissionFire { get; set; } [Data] public bool AllDeadNoAppear { get; set; } [Data] public byte GroupID { get; set; } } public static GroupFlag GetGroupFlag(uint value) { GroupFlag flag = new GroupFlag(); flag.Type = (AppearType)BitsUtil.Int.GetBits((int)value, 0, 4); flag.Linked = BitsUtil.Int.GetBit((int)value, 4); flag.AppearOK = BitsUtil.Int.GetBit((int)value, 5); flag.LinkInvoke = BitsUtil.Int.GetBit((int)value, 6); flag.Step = (byte)BitsUtil.Int.GetBits((int)value, 7, 4); flag.Fire = BitsUtil.Int.GetBit((int)value, 11); flag.ID = (byte)BitsUtil.Int.GetBits((int)value, 12, 8); flag.Specified = BitsUtil.Int.GetBit((int)value, 20); flag.GameTriggerFire = BitsUtil.Int.GetBit((int)value, 21); flag.MissionFire = BitsUtil.Int.GetBit((int)value, 22); flag.AllDeadNoAppear = BitsUtil.Int.GetBit((int)value, 23); flag.GroupID = (byte)BitsUtil.Int.GetBits((int)value, 24, 5); return flag; } public static uint MakeGroupFlag(AppearType Type, bool Linked, bool AppearOK, bool LinkInvoke, byte Step, bool Fire, byte ID, bool Specified, bool GameTriggerFire, bool MissionFire, bool AllDeadNoAppear, byte GroupID) { uint val = 0; val = BitsUtil.Int.SetBits(val, 0, 4, (uint)Type); val = BitsUtil.Int.SetBit(val, 4, Linked); val = BitsUtil.Int.SetBit(val, 5, AppearOK); val = BitsUtil.Int.SetBit(val, 6, LinkInvoke); val = BitsUtil.Int.SetBits(val, 7, 4, Step); val = BitsUtil.Int.SetBit(val, 11, Fire); val = BitsUtil.Int.SetBits(val, 12, 8, ID); val = BitsUtil.Int.SetBit(val, 20, Specified); val = BitsUtil.Int.SetBit(val, 21, GameTriggerFire); val = BitsUtil.Int.SetBit(val, 22, MissionFire); val = BitsUtil.Int.SetBit(val, 23, AllDeadNoAppear); val = BitsUtil.Int.SetBits(val, 24, 5, GroupID); return val; } public class LayoutData { [Data] public uint ObjectNameOffset { get; set; } [Data] public float PositionX { get; set; } [Data] public float PositionY { get; set; } [Data] public float PositionZ { get; set; } [Data] public float RotationX { get; set; } [Data] public float RotationY { get; set; } [Data] public float RotationZ { get; set; } [Data] public float Height { get; set; } [Data] public uint LayoutInfo { get; set; } [Data] public uint UniqueID { get; set; } [Data] public ushort Parameter1 { get; set; } [Data] public ushort Parameter2 { get; set; } [Data] public ushort Parameter3 { get; set; } [Data] public ushort Trigger { get; set; } [Data] public float Parameter5 { get; set; } [Data] public float Parameter6 { get; set; } [Data] public float Parameter7 { get; set; } [Data] public float Parameter8 { get; set; } [Data] public int MessageID { get; set; } [Data] public uint PathNameOffset { get; set; } [Data] public uint ScriptNameOffset { get; set; } [Data] public uint MissionLabelOffset { get; set; } } public class LayoutInfo { [Data] public bool Appear { get; set; } [Data] public bool LoadOnly { get; set; } [Data] public bool Dead { get; set; } [Data] public byte ID { get; set; } [Data] public bool ModelDisplayOff { get; set; } [Data] public byte GroupID { get; set; } [Data] public bool NoLoad { get; set; } [Data] public byte NetworkID { get; set; } } public static LayoutInfo GetLayoutInfo(uint value) { LayoutInfo flag = new LayoutInfo(); flag.Appear = BitsUtil.Int.GetBit((int)value, 0); flag.LoadOnly = BitsUtil.Int.GetBit((int)value, 1); flag.Dead = BitsUtil.Int.GetBit((int)value, 2); flag.ID = (byte)BitsUtil.Int.GetBits((int)value, 3, 8); flag.ModelDisplayOff = BitsUtil.Int.GetBit((int)value, 11); flag.GroupID = (byte)BitsUtil.Int.GetBits((int)value, 12, 8); flag.NoLoad = BitsUtil.Int.GetBit((int)value, 20); flag.NetworkID = (byte)BitsUtil.Int.GetBits((int)value, 21, 8); return flag; } public static uint MakeLayoutInfo(bool Appear, bool LoadOnly, bool Dead, byte ID, bool ModelDisplayOff, byte GroupID, bool NoLoad, byte NetworkID) { uint val = 0; val = BitsUtil.Int.SetBit(val, 0, Appear); val = BitsUtil.Int.SetBit(val, 1, LoadOnly); val = BitsUtil.Int.SetBit(val, 2, Dead); val = BitsUtil.Int.SetBits(val, 3, 8, ID); val = BitsUtil.Int.SetBit(val, 11, ModelDisplayOff); val = BitsUtil.Int.SetBits(val, 12, 8, GroupID); val = BitsUtil.Int.SetBit(val, 20, NoLoad); val = BitsUtil.Int.SetBits(val, 21, 8, NetworkID); return val; } public Header header; public List<ObjectName> ObjectList = new List<ObjectName>(); public List<PathName> FileList = new List<PathName>(); public List<PathName> ScriptList = new List<PathName>(); public List<ObjectName> MissionNameList = new List<ObjectName>(); public List<TriggerData> TriggerList = new List<TriggerData>(); public List<GroupData> GroupList = new List<GroupData>(); public List<LayoutData> LayoutList = new List<LayoutData>(); public static bool IsValid(Stream stream) { var prevPosition = stream.Position; var magicCode = new BinaryReader(stream).ReadInt32(); stream.Position = prevPosition; return magicCode == MagicCode; } public static Olo Read(Stream stream) { Olo olo = new Olo(); olo.header = BinaryMapping.ReadObject<Header>(stream); olo.ObjectList = new List<ObjectName>(); stream.Seek(olo.header.SpawnObjectsOffset, SeekOrigin.Begin); for(int i = 0; i < olo.header.SpawnObjectsCount; i++) { olo.ObjectList.Add(BinaryMapping.ReadObject<ObjectName>(stream)); } olo.FileList = new List<PathName>(); stream.Seek(olo.header.FilePathOffset, SeekOrigin.Begin); for (int i = 0; i < olo.header.FilePathCount; i++) { olo.FileList.Add(BinaryMapping.ReadObject<PathName>(stream)); } olo.ScriptList = new List<PathName>(); stream.Seek(olo.header.ScriptPathOffset, SeekOrigin.Begin); for (int i = 0; i < olo.header.ScriptPathCount; i++) { olo.FileList.Add(BinaryMapping.ReadObject<PathName>(stream)); } olo.MissionNameList = new List<ObjectName>(); stream.Seek(olo.header.MissionNameOffset, SeekOrigin.Begin); for (int i = 0; i < olo.header.MissionNameCount; i++) { olo.MissionNameList.Add(BinaryMapping.ReadObject<ObjectName>(stream)); } olo.TriggerList = new List<TriggerData>(); stream.Seek(olo.header.TriggerDataOffset, SeekOrigin.Begin); for (int i = 0; i < olo.header.TriggerDataCount; i++) { olo.TriggerList.Add(BinaryMapping.ReadObject<TriggerData>(stream)); } olo.GroupList = new List<GroupData>(); stream.Seek(olo.header.GroupDataOffset, SeekOrigin.Begin); olo.LayoutList = new List<LayoutData>(); for (int i = 0; i < olo.header.GroupDataCount; i++) { stream.Seek(olo.header.GroupDataOffset + (i * 0x30), SeekOrigin.Begin); GroupData data = BinaryMapping.ReadObject<GroupData>(stream); stream.Seek(data.ObjectLayoutDataOffset, SeekOrigin.Begin); for (int j = 0; j < data.ObjectLayoutDataCount; j++) { olo.LayoutList.Add(BinaryMapping.ReadObject<LayoutData>(stream)); } olo.GroupList.Add(data); } return olo; } public static void Write(Stream stream, Olo olo) { BinaryMapping.WriteObject<Header>(stream, olo.header); for (int i = 0; i < olo.header.SpawnObjectsCount; i++) { BinaryMapping.WriteObject<ObjectName>(stream, olo.ObjectList[i]); } for (int i = 0; i < olo.header.FilePathCount; i++) { BinaryMapping.WriteObject<PathName>(stream, olo.FileList[i]); } for (int i = 0; i < olo.header.ScriptPathCount; i++) { BinaryMapping.WriteObject<PathName>(stream, olo.ScriptList[i]); } for (int i = 0; i < olo.header.MissionNameCount; i++) { BinaryMapping.WriteObject<ObjectName>(stream, olo.MissionNameList[i]); } for (int i = 0; i < olo.header.TriggerDataCount; i++) { BinaryMapping.WriteObject<TriggerData>(stream, olo.TriggerList[i]); } for (int i = 0; i < olo.header.GroupDataCount; i++) { BinaryMapping.WriteObject<GroupData>(stream, olo.GroupList[i]); } for (int j = 0; j < olo.LayoutList.Count; j++) { BinaryMapping.WriteObject<LayoutData>(stream, olo.LayoutList[j]); } } } }
using System.Collections.Generic; using System.Linq; using DependencyMap.Analysis; using DependencyMap.Scanning; using FluentAssertions; using NuGet; using NUnit.Framework; namespace DependencyMap.Tests.Analysis { [TestFixture] public class GroupedByServiceTests { [Test] public void SimpleDependency_ShouldReturnServicesAsExpected() { var input = new ServiceDependency { ServiceId = "Service0", DependencyId = "Dependency0", DependencyVersion = new SemanticVersion(1, 0, 0, 0) }; var analyser = new ServiceDependenciesAnalyser(new[] { input }); var output = analyser.GroupByService(); output.ShouldBeEquivalentTo( new Dictionary<string, DependencyStaleness[]> { { "Service0", new[] { new DependencyStaleness { DependencyId = "Dependency0", LatestKnownVersion = new SemanticVersion(1, 0, 0, 0), Version = new SemanticVersion(1, 0, 0, 0), StalenessRating = 0 } } } }); } [Test] public void DifferentVersions_ShouldReturnDifferentStalenesses() { var input = new[] { new ServiceDependency { ServiceId = "Service0", DependencyId = "Dependency0", DependencyVersion = new SemanticVersion(1, 0, 0, 0) }, new ServiceDependency { ServiceId = "Service1", DependencyId = "Dependency0", DependencyVersion = new SemanticVersion(1, 0, 0, 0) }, new ServiceDependency { ServiceId = "Service1", DependencyId = "Dependency0", DependencyVersion = new SemanticVersion(1, 1, 0, 0) }, new ServiceDependency { ServiceId = "Service2", DependencyId = "Dependency0", DependencyVersion = new SemanticVersion(2, 0, 0, 0) } }; var analyser = new ServiceDependenciesAnalyser(input); var output = analyser.GroupByService(); output.ShouldBeEquivalentTo( new Dictionary<string, DependencyStaleness[]> { { "Service0", new[] { new DependencyStaleness { DependencyId = "Dependency0", LatestKnownVersion = new SemanticVersion(2, 0, 0, 0), Version = new SemanticVersion(1, 0, 0, 0), StalenessRating = 2 } } }, { "Service1", new[] { new DependencyStaleness { DependencyId = "Dependency0", LatestKnownVersion = new SemanticVersion(2, 0, 0, 0), Version = new SemanticVersion(1, 0, 0, 0), StalenessRating = 2 }, new DependencyStaleness { DependencyId = "Dependency0", LatestKnownVersion = new SemanticVersion(2, 0, 0, 0), Version = new SemanticVersion(1, 1, 0, 0), StalenessRating = 1 } } }, { "Service2", new[] { new DependencyStaleness { DependencyId = "Dependency0", LatestKnownVersion = new SemanticVersion(2, 0, 0, 0), Version = new SemanticVersion(2, 0, 0, 0), StalenessRating = 0 } } } }); } [Test] public void InputDependenciesNotOrdered_ShouldReturnOutputOrderedByDependencyId() { var serviceId = "Service0"; var version = new SemanticVersion(1, 0, 0, 0); var input = new[] { new ServiceDependency { ServiceId = serviceId, DependencyId = "Charlie", DependencyVersion = version }, new ServiceDependency { ServiceId = serviceId, DependencyId = "Bravo", DependencyVersion = version }, new ServiceDependency { ServiceId = serviceId, DependencyId = "Alpha", DependencyVersion = version } }; var analyser = new ServiceDependenciesAnalyser(input); var output = analyser.GroupByService(); // Should.Equal also asserts order output[serviceId].Select(x => x.DependencyId).Should().Equal( input.Select(x => x.DependencyId).OrderBy(x => x)); } [Test] public void InputServicesNotOrdered_ShouldReturnOutputOrderedByServiceId() { var dependencyId = "Dependency0"; var version = new SemanticVersion(1, 0, 0, 0); var input = new[] { new ServiceDependency { ServiceId = "Charlie", DependencyId = dependencyId, DependencyVersion = version }, new ServiceDependency { ServiceId = "Bravo", DependencyId = dependencyId, DependencyVersion = version }, new ServiceDependency { ServiceId = "Alpha", DependencyId = dependencyId, DependencyVersion = version } }; var analyser = new ServiceDependenciesAnalyser(input); var output = analyser.GroupByService(); // Should.Equal also asserts order output.Select(x => x.Key).Should().Equal( input.Select(x => x.ServiceId).OrderBy(x => x)); } [Test] public void HighestVersionIsPreRelease_ShouldNotBeUsedAsLatestKnownVersion() { var input = new[] { new ServiceDependency { ServiceId = "Service0", DependencyId = "Dependency0", DependencyVersion = new SemanticVersion(2, 0, 0, "alpha") }, new ServiceDependency { ServiceId = "Service0", DependencyId = "Dependency0", DependencyVersion = new SemanticVersion(1, 0, 0, 0) } }; var analyser = new ServiceDependenciesAnalyser(input); var output = analyser.GroupByService(); output.ShouldBeEquivalentTo( new Dictionary<string, DependencyStaleness[]> { { "Service0", new[] { new DependencyStaleness { DependencyId = "Dependency0", LatestKnownVersion = new SemanticVersion(1, 0, 0, 0), Version = new SemanticVersion(2, 0, 0, "alpha"), StalenessRating = 0 }, new DependencyStaleness { DependencyId = "Dependency0", LatestKnownVersion = new SemanticVersion(1, 0, 0, 0), Version = new SemanticVersion(1, 0, 0, 0), StalenessRating = 0 } } } }); } [Test] public void OnlyVersionIsPreRelease_ShouldBeUsedAsLatestKnownVersion() { var input = new[] { new ServiceDependency { ServiceId = "Service0", DependencyId = "Dependency0", DependencyVersion = new SemanticVersion(2, 0, 0, "alpha") } }; var analyser = new ServiceDependenciesAnalyser(input); var output = analyser.GroupByService(); output.ShouldBeEquivalentTo( new Dictionary<string, DependencyStaleness[]> { { "Service0", new[] { new DependencyStaleness { DependencyId = "Dependency0", LatestKnownVersion = new SemanticVersion(2, 0, 0, "alpha"), Version = new SemanticVersion(2, 0, 0, "alpha"), StalenessRating = 0 } } } }); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Metadata.ManagedReference { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.CodeAnalysis.VisualBasic.Syntax; using Microsoft.DocAsCode.DataContracts.ManagedReference; public class VBYamlModelGenerator : SimpleYamlModelGenerator { #region Fields private static readonly Regex EndRegex = new Regex(@"\s+End\s*\w*\s*$", RegexOptions.Compiled); #endregion public VBYamlModelGenerator() : base(SyntaxLanguage.VB) { } #region Overrides public override void DefaultVisit(ISymbol symbol, MetadataItem item, SymbolVisitorAdapter adapter) { item.DisplayNames[SyntaxLanguage.VB] = NameVisitorCreator.GetVB(NameOptions.WithGenericParameter | NameOptions.WithParameter).GetName(symbol); item.DisplayNamesWithType[SyntaxLanguage.VB] = NameVisitorCreator.GetVB(NameOptions.WithType | NameOptions.WithGenericParameter | NameOptions.WithParameter).GetName(symbol); item.DisplayQualifiedNames[SyntaxLanguage.VB] = NameVisitorCreator.GetVB(NameOptions.Qualified | NameOptions.WithGenericParameter | NameOptions.WithParameter).GetName(symbol); } public override void GenerateNamedType(INamedTypeSymbol symbol, MetadataItem item, SymbolVisitorAdapter adapter) { base.GenerateNamedType(symbol, item, adapter); var modifiers = new List<string>(); var visiblity = GetVisiblity(symbol.DeclaredAccessibility); if (visiblity != null) { modifiers.Add(visiblity); } if (symbol.TypeKind == TypeKind.Class) { if (symbol.IsAbstract) { modifiers.Add("MustInherit"); } else if (symbol.IsSealed) { modifiers.Add("NotInheritable"); } } switch (symbol.TypeKind) { case TypeKind.Module: modifiers.Add("Module"); break; case TypeKind.Class: if (symbol.IsStatic) { modifiers.Add("Module"); } else { modifiers.Add("Class"); } break; case TypeKind.Delegate: modifiers.Add("Delegate"); break; case TypeKind.Enum: modifiers.Add("Enum"); break; case TypeKind.Interface: modifiers.Add("Interface"); break; case TypeKind.Struct: modifiers.Add("Structure"); break; default: break; } item.Modifiers[SyntaxLanguage.VB] = modifiers; } public override void GenerateMethod(IMethodSymbol symbol, MetadataItem item, SymbolVisitorAdapter adapter) { base.GenerateMethod(symbol, item, adapter); var modifiers = new List<string>(); if (symbol.ContainingType.TypeKind != TypeKind.Interface) { var visiblity = GetVisiblity(symbol.DeclaredAccessibility); if (visiblity != null) { modifiers.Add(visiblity); } if (symbol.IsStatic) { modifiers.Add("Shared"); } if (symbol.IsAbstract) { modifiers.Add("MustOverride"); } if (symbol.IsOverride) { modifiers.Add("Overrides"); } if (symbol.IsVirtual && symbol.IsSealed) { } else if (symbol.IsVirtual) { modifiers.Add("Overridable"); } else if (symbol.IsSealed) { modifiers.Add("NotOverridable"); } } item.Modifiers[SyntaxLanguage.VB] = modifiers; } public override void GenerateField(IFieldSymbol symbol, MetadataItem item, SymbolVisitorAdapter adapter) { base.GenerateField(symbol, item, adapter); var modifiers = new List<string>(); var visiblity = GetVisiblity(symbol.DeclaredAccessibility); if (visiblity != null) { modifiers.Add(visiblity); } if (symbol.IsConst) { modifiers.Add("Const"); } else if (symbol.IsStatic) { modifiers.Add("Shared"); } if (symbol.IsReadOnly) { modifiers.Add("ReadOnly"); } if (symbol.IsVolatile) { // no modifier for volatile in vb } item.Modifiers[SyntaxLanguage.VB] = modifiers; } public override void GenerateProperty(IPropertySymbol symbol, MetadataItem item, SymbolVisitorAdapter adapter) { base.GenerateProperty(symbol, item, adapter); var modifiers = new List<string>(); var propertyVisiblity = GetVisiblity(symbol.DeclaredAccessibility); if (symbol.ContainingType.TypeKind != TypeKind.Interface) { if (propertyVisiblity != null) { modifiers.Add(propertyVisiblity); } if (symbol.IsStatic) { modifiers.Add("Shared"); } if (symbol.IsAbstract) { modifiers.Add("MustOverride"); } if (symbol.IsOverride) { modifiers.Add("Overrides"); } if (symbol.IsVirtual && symbol.IsSealed) { } else if (symbol.IsVirtual) { modifiers.Add("Overridable"); } else if (symbol.IsSealed) { modifiers.Add("NotOverridable"); } } bool hasGetMethod = symbol.GetMethod != null; bool hasSetMethod = symbol.SetMethod != null; var getMethodVisiblity = hasGetMethod ? GetVisiblity(symbol.GetMethod.DeclaredAccessibility) : null; var setMethodVisiblity = hasSetMethod ? GetVisiblity(symbol.SetMethod.DeclaredAccessibility) : null; if (hasGetMethod ^ hasSetMethod) { if (hasGetMethod) { modifiers.Add("ReadOnly"); } else { modifiers.Add("WriteOnly"); } } else if (propertyVisiblity != null && (getMethodVisiblity == null ^ setMethodVisiblity == null)) { if (setMethodVisiblity == null) { modifiers.Add("ReadOnly"); } if (getMethodVisiblity == null) { modifiers.Add("WriteOnly"); } } else if (getMethodVisiblity != propertyVisiblity || setMethodVisiblity != propertyVisiblity) { if (getMethodVisiblity != propertyVisiblity) { modifiers.Add($"{getMethodVisiblity} Get"); } else { modifiers.Add("Get"); } if (setMethodVisiblity != propertyVisiblity) { modifiers.Add($"{setMethodVisiblity} Set"); } else { modifiers.Add("Set"); } } item.Modifiers[SyntaxLanguage.VB] = modifiers; } public override void GenerateEvent(IEventSymbol symbol, MetadataItem item, SymbolVisitorAdapter adapter) { base.GenerateEvent(symbol, item, adapter); var modifiers = new List<string>(); if (symbol.ContainingType.TypeKind != TypeKind.Interface) { var visiblity = GetVisiblity(symbol.DeclaredAccessibility); if (visiblity != null) { modifiers.Add(visiblity); } if (symbol.IsStatic) { modifiers.Add("Shared"); } if (symbol.IsAbstract) { modifiers.Add("MustOverride"); } if (symbol.IsOverride) { modifiers.Add("Overrides"); } if (symbol.IsVirtual && symbol.IsSealed) { } else if (symbol.IsVirtual) { modifiers.Add("Overridable"); } else if (symbol.IsSealed) { modifiers.Add("NotOverridable"); } } item.Modifiers[SyntaxLanguage.VB] = modifiers; } protected override string GetSyntaxContent(MemberType typeKind, ISymbol symbol, SymbolVisitorAdapter adapter) { switch (typeKind) { case MemberType.Class: return GetClassSyntax((INamedTypeSymbol)symbol, adapter.FilterVisitor); case MemberType.Enum: return GetEnumSyntax((INamedTypeSymbol)symbol, adapter.FilterVisitor); case MemberType.Interface: return GetInterfaceSyntax((INamedTypeSymbol)symbol, adapter.FilterVisitor); case MemberType.Struct: return GetStructSyntax((INamedTypeSymbol)symbol, adapter.FilterVisitor); case MemberType.Delegate: return GetDelegateSyntax((INamedTypeSymbol)symbol, adapter.FilterVisitor); case MemberType.Method: return GetMethodSyntax((IMethodSymbol)symbol, adapter.FilterVisitor); case MemberType.Operator: return GetOperatorSyntax((IMethodSymbol)symbol, adapter.FilterVisitor); case MemberType.Constructor: return GetConstructorSyntax((IMethodSymbol)symbol, adapter.FilterVisitor); case MemberType.Field: return GetFieldSyntax((IFieldSymbol)symbol, adapter.FilterVisitor); case MemberType.Event: return GetEventSyntax((IEventSymbol)symbol, adapter.FilterVisitor); case MemberType.Property: return GetPropertySyntax((IPropertySymbol)symbol, adapter.FilterVisitor); default: return null; } } protected override void GenerateReference(ISymbol symbol, ReferenceItem reference, SymbolVisitorAdapter adapter, bool asOverload) { symbol.Accept(new VBReferenceItemVisitor(reference, asOverload)); } #endregion #region Private Methods #region Syntax private string GetClassSyntax(INamedTypeSymbol symbol, IFilterVisitor filterVisitor) { string syntaxStr; if (symbol.TypeKind == TypeKind.Module || symbol.IsStatic) { syntaxStr = SyntaxFactory.ModuleBlock( SyntaxFactory.ModuleStatement( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetTypeModifiers(symbol) ), SyntaxFactory.Identifier(symbol.Name), GetTypeParameters(symbol) ), GetInheritsList(symbol), GetImplementsList(symbol), new SyntaxList<StatementSyntax>() ).NormalizeWhitespace().ToString(); } else { syntaxStr = SyntaxFactory.ClassBlock( SyntaxFactory.ClassStatement( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetTypeModifiers(symbol) ), SyntaxFactory.Token(SyntaxKind.ClassKeyword), SyntaxFactory.Identifier(symbol.Name), GetTypeParameters(symbol) ), GetInheritsList(symbol), GetImplementsList(symbol), new SyntaxList<StatementSyntax>(), SyntaxFactory.EndClassStatement() ).NormalizeWhitespace().ToString(); } return RemoveEnd(syntaxStr); } private string GetEnumSyntax(INamedTypeSymbol symbol, IFilterVisitor filterVisitor) { var syntaxStr = SyntaxFactory.EnumBlock( SyntaxFactory.EnumStatement( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetTypeModifiers(symbol) ), SyntaxFactory.Token(SyntaxKind.EnumKeyword), SyntaxFactory.Identifier(symbol.Name), GetEnumUnderlyingType(symbol) ) ).NormalizeWhitespace().ToString(); return RemoveEnd(syntaxStr); } private string GetInterfaceSyntax(INamedTypeSymbol symbol, IFilterVisitor filterVisitor) { var syntaxStr = SyntaxFactory.InterfaceBlock( SyntaxFactory.InterfaceStatement( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetTypeModifiers(symbol) ), SyntaxFactory.Token(SyntaxKind.InterfaceKeyword), SyntaxFactory.Identifier(symbol.Name), GetTypeParameters(symbol) ), GetInheritsList(symbol), new SyntaxList<ImplementsStatementSyntax>(), new SyntaxList<StatementSyntax>(), SyntaxFactory.EndInterfaceStatement() ).NormalizeWhitespace().ToString(); return RemoveEnd(syntaxStr); } private string GetStructSyntax(INamedTypeSymbol symbol, IFilterVisitor filterVisitor) { string syntaxStr = SyntaxFactory.StructureBlock( SyntaxFactory.StructureStatement( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetTypeModifiers(symbol) ), SyntaxFactory.Token(SyntaxKind.StructureKeyword), SyntaxFactory.Identifier(symbol.Name), GetTypeParameters(symbol) ), new SyntaxList<InheritsStatementSyntax>(), GetImplementsList(symbol), new SyntaxList<StatementSyntax>(), SyntaxFactory.EndStructureStatement() ).NormalizeWhitespace().ToString(); return RemoveEnd(syntaxStr); } private string GetDelegateSyntax(INamedTypeSymbol symbol, IFilterVisitor filterVisitor) { string syntaxStr = SyntaxFactory.DelegateStatement( symbol.DelegateInvokeMethod.ReturnsVoid ? SyntaxKind.DelegateSubStatement : SyntaxKind.DelegateFunctionStatement, GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetTypeModifiers(symbol) ), symbol.DelegateInvokeMethod.ReturnsVoid ? SyntaxFactory.Token(SyntaxKind.SubKeyword) : SyntaxFactory.Token(SyntaxKind.FunctionKeyword), SyntaxFactory.Identifier(symbol.Name), GetTypeParameters(symbol), GetParamerterList(symbol.DelegateInvokeMethod), GetReturnAsClause(symbol.DelegateInvokeMethod) ).NormalizeWhitespace().ToString(); return RemoveEnd(syntaxStr); } private string GetMethodSyntax(IMethodSymbol symbol, IFilterVisitor filterVisitor) { string syntaxStr = SyntaxFactory.MethodStatement( symbol.ReturnsVoid ? SyntaxKind.SubStatement : SyntaxKind.FunctionStatement, GetAttributes(symbol, filterVisitor, isExtensionMethod: symbol.IsExtensionMethod), SyntaxFactory.TokenList( GetMemberModifiers(symbol) ), symbol.ReturnsVoid ? SyntaxFactory.Token(SyntaxKind.SubKeyword) : SyntaxFactory.Token(SyntaxKind.FunctionKeyword), SyntaxFactory.Identifier(symbol.Name), GetTypeParameters(symbol), GetParamerterList(symbol), GetReturnAsClause(symbol), null, GetImplementsClause(symbol, filterVisitor) ).NormalizeWhitespace().ToString(); return RemoveEnd(syntaxStr); } private string GetOperatorSyntax(IMethodSymbol symbol, IFilterVisitor filterVisitor) { var operatorToken = GetOperatorToken(symbol); if (operatorToken == null) { return "VB cannot support this operator."; } return SyntaxFactory.OperatorStatement( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetMemberModifiers(symbol) ), SyntaxFactory.Token(SyntaxKind.OperatorKeyword), operatorToken.Value, GetParamerterList(symbol), GetReturnAsClause(symbol) ).NormalizeWhitespace().ToString(); } private string GetConstructorSyntax(IMethodSymbol symbol, IFilterVisitor filterVisitor) { var syntaxStr = SyntaxFactory.SubNewStatement( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetMemberModifiers(symbol) ), GetParamerterList(symbol) ).NormalizeWhitespace().ToString(); return RemoveEnd(syntaxStr); } private string GetFieldSyntax(IFieldSymbol symbol, IFilterVisitor filterVisitor) { string syntaxStr; if (symbol.ContainingType.TypeKind == TypeKind.Enum) { syntaxStr = SyntaxFactory.EnumMemberDeclaration( GetAttributes(symbol, filterVisitor), SyntaxFactory.Identifier(symbol.Name), GetDefaultValue(symbol) ).NormalizeWhitespace().ToString(); } else { syntaxStr = SyntaxFactory.FieldDeclaration( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList(GetMemberModifiers(symbol)), SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator( SyntaxFactory.SingletonSeparatedList( SyntaxFactory.ModifiedIdentifier(symbol.Name) ), SyntaxFactory.SimpleAsClause( GetTypeSyntax(symbol.Type) ), GetDefaultValue(symbol) ) ) ).NormalizeWhitespace().ToString(); } return RemoveEnd(syntaxStr); } private string GetEventSyntax(IEventSymbol symbol, IFilterVisitor filterVisitor) { return SyntaxFactory.EventStatement( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetMemberModifiers(symbol) ), SyntaxFactory.Identifier(symbol.Name), null, SyntaxFactory.SimpleAsClause( GetTypeSyntax(symbol.Type) ), GetImplementsClause(symbol, filterVisitor) ).NormalizeWhitespace().ToString(); } private string GetPropertySyntax(IPropertySymbol symbol, IFilterVisitor filterVisitor) { return SyntaxFactory.PropertyStatement( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetMemberModifiers(symbol) ), SyntaxFactory.Identifier(symbol.MetadataName), GetParamerterList(symbol), SyntaxFactory.SimpleAsClause( GetTypeSyntax(symbol.Type) ), null, GetImplementsClause(symbol, filterVisitor) ).NormalizeWhitespace().ToString(); } #endregion private static SyntaxList<AttributeListSyntax> GetAttributes(ISymbol symbol, IFilterVisitor filterVisitor, bool inOneLine = false, bool isExtensionMethod = false) { var attrs = symbol.GetAttributes(); List<AttributeSyntax> attrList = null; if (attrs.Length > 0) { attrList = (from attr in attrs where !(attr.AttributeClass is IErrorTypeSymbol) where attr?.AttributeConstructor != null where filterVisitor.CanVisitAttribute(attr.AttributeConstructor) select GetAttributeSyntax(attr)).ToList(); } if (isExtensionMethod) { attrList = attrList ?? new List<AttributeSyntax>(); attrList.Add( SyntaxFactory.Attribute( SyntaxFactory.ParseName(nameof(System.Runtime.CompilerServices.ExtensionAttribute)))); } if (attrList?.Count > 0) { if (inOneLine) { return SyntaxFactory.SingletonList( SyntaxFactory.AttributeList( SyntaxFactory.SeparatedList(attrList))); } return SyntaxFactory.List( from attr in attrList select SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList(attr))); } return new SyntaxList<AttributeListSyntax>(); } private static AttributeSyntax GetAttributeSyntax(AttributeData attr) { var attrTypeName = NameVisitorCreator.GetCSharp(NameOptions.None).GetName(attr.AttributeClass); if (attrTypeName.EndsWith(nameof(Attribute), StringComparison.Ordinal)) { attrTypeName = attrTypeName.Remove(attrTypeName.Length - nameof(Attribute).Length); } if (attr.ConstructorArguments.Length == 0 && attr.NamedArguments.Length == 0) { return SyntaxFactory.Attribute(SyntaxFactory.ParseName(attrTypeName)); } return SyntaxFactory.Attribute( null, SyntaxFactory.ParseName(attrTypeName), SyntaxFactory.ArgumentList( SyntaxFactory.SeparatedList( (from item in attr.ConstructorArguments select GetLiteralExpression(item) into expr where expr != null select (ArgumentSyntax)SyntaxFactory.SimpleArgument(expr) ).Concat( from item in attr.NamedArguments let expr = GetLiteralExpression(item.Value) where expr != null select (ArgumentSyntax)SyntaxFactory.SimpleArgument( SyntaxFactory.NameColonEquals( SyntaxFactory.IdentifierName(item.Key) ), expr ) ) ) ) ); } private static IEnumerable<SyntaxToken> GetTypeModifiers(INamedTypeSymbol symbol) { switch (symbol.DeclaredAccessibility) { case Accessibility.Protected: case Accessibility.ProtectedOrFriend: yield return SyntaxFactory.Token(SyntaxKind.ProtectedKeyword); break; case Accessibility.Public: yield return SyntaxFactory.Token(SyntaxKind.PublicKeyword); break; default: break; } if (symbol.TypeKind == TypeKind.Class) { if (symbol.IsAbstract && symbol.IsSealed) { yield return SyntaxFactory.Token(SyntaxKind.NotInheritableKeyword); } else { if (symbol.IsAbstract) { yield return SyntaxFactory.Token(SyntaxKind.MustInheritKeyword); } if (symbol.IsSealed) { yield return SyntaxFactory.Token(SyntaxKind.NotInheritableKeyword); } } } } private IEnumerable<SyntaxToken> GetMemberModifiers(IMethodSymbol symbol) { if (symbol.ContainingType.TypeKind != TypeKind.Interface) { switch (symbol.DeclaredAccessibility) { case Accessibility.Protected: case Accessibility.ProtectedOrFriend: yield return SyntaxFactory.Token(SyntaxKind.ProtectedKeyword); break; case Accessibility.Public: yield return SyntaxFactory.Token(SyntaxKind.PublicKeyword); break; default: break; } } if (symbol.IsStatic) { yield return SyntaxFactory.Token(SyntaxKind.SharedKeyword); } if (symbol.IsAbstract && symbol.ContainingType.TypeKind != TypeKind.Interface) { yield return SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword); } if (symbol.IsVirtual) { yield return SyntaxFactory.Token(SyntaxKind.OverridableKeyword); } if (symbol.IsSealed) { yield return SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword); } if (symbol.IsOverride) { yield return SyntaxFactory.Token(SyntaxKind.OverridesKeyword); } if (symbol.MethodKind == MethodKind.Conversion) { if (symbol.Name == "op_Implicit") { yield return SyntaxFactory.Token(SyntaxKind.WideningKeyword); } else if (symbol.Name == "op_Explicit") { yield return SyntaxFactory.Token(SyntaxKind.NarrowingKeyword); } } } private IEnumerable<SyntaxToken> GetMemberModifiers(IFieldSymbol symbol) { if (symbol.ContainingType.TypeKind != TypeKind.Interface) { switch (symbol.DeclaredAccessibility) { case Accessibility.Protected: case Accessibility.ProtectedOrFriend: yield return SyntaxFactory.Token(SyntaxKind.ProtectedKeyword); break; case Accessibility.Public: yield return SyntaxFactory.Token(SyntaxKind.PublicKeyword); break; default: break; } } if (symbol.IsConst) { yield return SyntaxFactory.Token(SyntaxKind.ConstKeyword); } else { if (symbol.IsStatic) { yield return SyntaxFactory.Token(SyntaxKind.SharedKeyword); } if (symbol.IsReadOnly) { yield return SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword); } } } private IEnumerable<SyntaxToken> GetMemberModifiers(IEventSymbol symbol) { if (symbol.ContainingType.TypeKind != TypeKind.Interface) { switch (symbol.DeclaredAccessibility) { case Accessibility.Protected: case Accessibility.ProtectedOrFriend: yield return SyntaxFactory.Token(SyntaxKind.ProtectedKeyword); break; case Accessibility.Public: yield return SyntaxFactory.Token(SyntaxKind.PublicKeyword); break; default: break; } } if (symbol.IsStatic) { yield return SyntaxFactory.Token(SyntaxKind.SharedKeyword); } if (symbol.IsAbstract && symbol.ContainingType.TypeKind != TypeKind.Interface) { yield return SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword); } if (symbol.IsVirtual) { yield return SyntaxFactory.Token(SyntaxKind.OverridableKeyword); } if (symbol.IsSealed) { yield return SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword); } if (symbol.IsOverride) { yield return SyntaxFactory.Token(SyntaxKind.OverridesKeyword); } } private IEnumerable<SyntaxToken> GetMemberModifiers(IPropertySymbol symbol) { if (symbol.ContainingType.TypeKind != TypeKind.Interface) { switch (symbol.DeclaredAccessibility) { case Accessibility.Protected: case Accessibility.ProtectedOrFriend: yield return SyntaxFactory.Token(SyntaxKind.ProtectedKeyword); break; case Accessibility.Public: yield return SyntaxFactory.Token(SyntaxKind.PublicKeyword); break; default: break; } } if (symbol.IsStatic) { yield return SyntaxFactory.Token(SyntaxKind.SharedKeyword); } if (symbol.IsAbstract && symbol.ContainingType.TypeKind != TypeKind.Interface) { yield return SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword); } if (symbol.IsVirtual) { yield return SyntaxFactory.Token(SyntaxKind.OverridableKeyword); } if (symbol.IsSealed) { yield return SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword); } if (symbol.IsOverride) { yield return SyntaxFactory.Token(SyntaxKind.OverridesKeyword); } if (symbol.IsReadOnly || symbol.SetMethod == null) { yield return SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword); } else { switch (symbol.SetMethod.DeclaredAccessibility) { case Accessibility.Private: case Accessibility.ProtectedAndInternal: case Accessibility.Internal: yield return SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword); break; default: break; } } if (symbol.IsWriteOnly || symbol.GetMethod == null) { yield return SyntaxFactory.Token(SyntaxKind.WriteOnlyKeyword); } else { switch (symbol.GetMethod.DeclaredAccessibility) { case Accessibility.Private: case Accessibility.ProtectedAndInternal: case Accessibility.Internal: yield return SyntaxFactory.Token(SyntaxKind.WriteOnlyKeyword); break; default: break; } } } private static TypeParameterListSyntax GetTypeParameters(INamedTypeSymbol symbol) { if (symbol.TypeArguments.Length == 0) { return null; } return SyntaxFactory.TypeParameterList( SyntaxFactory.SeparatedList( from ITypeParameterSymbol t in symbol.TypeArguments select SyntaxFactory.TypeParameter( GetVarianceToken(t), SyntaxFactory.Identifier(t.Name), GetTypeParameterConstraintClauseSyntax(t)))); } private static TypeParameterListSyntax GetTypeParameters(IMethodSymbol symbol) { if (symbol.TypeArguments.Length == 0) { return null; } return SyntaxFactory.TypeParameterList( SyntaxFactory.SeparatedList( from ITypeParameterSymbol t in symbol.TypeArguments select SyntaxFactory.TypeParameter( GetVarianceToken(t), SyntaxFactory.Identifier(t.Name), GetTypeParameterConstraintClauseSyntax(t)))); } private static SyntaxToken GetVarianceToken(ITypeParameterSymbol t) { if (t.Variance == VarianceKind.In) return SyntaxFactory.Token(SyntaxKind.InKeyword); if (t.Variance == VarianceKind.Out) return SyntaxFactory.Token(SyntaxKind.OutKeyword); return new SyntaxToken(); } private static TypeParameterConstraintClauseSyntax GetTypeParameterConstraintClauseSyntax(ITypeParameterSymbol symbol) { var contraints = GetConstraintSyntaxes(symbol).ToList(); if (contraints.Count == 0) { return null; } if (contraints.Count == 1) { return SyntaxFactory.TypeParameterSingleConstraintClause(contraints[0]); } return SyntaxFactory.TypeParameterMultipleConstraintClause(contraints.ToArray()); } private static IEnumerable<ConstraintSyntax> GetConstraintSyntaxes(ITypeParameterSymbol symbol) { if (symbol.HasReferenceTypeConstraint) { yield return SyntaxFactory.ClassConstraint(SyntaxFactory.Token(SyntaxKind.ClassKeyword)); } if (symbol.HasValueTypeConstraint) { yield return SyntaxFactory.StructureConstraint(SyntaxFactory.Token(SyntaxKind.StructureKeyword)); } if (symbol.ConstraintTypes.Length > 0) { for (int i = 0; i < symbol.ConstraintTypes.Length; i++) { yield return SyntaxFactory.TypeConstraint(GetTypeSyntax(symbol.ConstraintTypes[i])); } } if (symbol.HasConstructorConstraint) { yield return SyntaxFactory.NewConstraint(SyntaxFactory.Token(SyntaxKind.NewKeyword)); } } private SyntaxList<InheritsStatementSyntax> GetInheritsList(INamedTypeSymbol symbol) { if (symbol.TypeKind == TypeKind.Class && symbol.BaseType != null && symbol.BaseType.GetDocumentationCommentId() != "T:System.Object") { return SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(GetTypeSyntax(symbol.BaseType))); } if (symbol.TypeKind == TypeKind.Interface && symbol.Interfaces.Length > 0) { return SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement( (from t in symbol.Interfaces select GetTypeSyntax(t)).ToArray())); } return new SyntaxList<InheritsStatementSyntax>(); } private SyntaxList<ImplementsStatementSyntax> GetImplementsList(INamedTypeSymbol symbol) { if (symbol.AllInterfaces.Any()) { return SyntaxFactory.SingletonList(SyntaxFactory.ImplementsStatement( (from t in symbol.AllInterfaces select GetTypeSyntax(t)).ToArray())); } return new SyntaxList<ImplementsStatementSyntax>(); } private AsClauseSyntax GetEnumUnderlyingType(INamedTypeSymbol symbol) { if (symbol.EnumUnderlyingType.GetDocumentationCommentId() == "T:System.Int32") { return null; } return SyntaxFactory.SimpleAsClause(GetTypeSyntax(symbol.EnumUnderlyingType)); } private ParameterListSyntax GetParamerterList(IMethodSymbol symbol) { if (symbol.Parameters.Length == 0) { return null; } return SyntaxFactory.ParameterList( SyntaxFactory.SeparatedList( from p in symbol.Parameters select SyntaxFactory.Parameter( new SyntaxList<AttributeListSyntax>(), SyntaxFactory.TokenList(GetParameterModifiers(p)), SyntaxFactory.ModifiedIdentifier(p.Name), SyntaxFactory.SimpleAsClause(GetTypeSyntax(p.Type)), GetDefaultValue(p)))); } private ParameterListSyntax GetParamerterList(IPropertySymbol symbol) { if (symbol.Parameters.Length == 0) { return null; } return SyntaxFactory.ParameterList( SyntaxFactory.SeparatedList( from p in symbol.Parameters select SyntaxFactory.Parameter( new SyntaxList<AttributeListSyntax>(), SyntaxFactory.TokenList(GetParameterModifiers(p)), SyntaxFactory.ModifiedIdentifier(p.Name), SyntaxFactory.SimpleAsClause(GetTypeSyntax(p.Type)), GetDefaultValue(p)))); } private IEnumerable<SyntaxToken> GetParameterModifiers(IParameterSymbol symbol) { if (symbol.RefKind == RefKind.None) { } else { yield return SyntaxFactory.Token(SyntaxKind.ByRefKeyword); } if (symbol.IsParams) { yield return SyntaxFactory.Token(SyntaxKind.ParamArrayKeyword); } } private ImplementsClauseSyntax GetImplementsClause(IMethodSymbol symbol, IFilterVisitor filterVisitor) { if (symbol.ExplicitInterfaceImplementations.Length == 0) { return null; } var list = (from eii in symbol.ExplicitInterfaceImplementations where filterVisitor.CanVisitApi(eii) select SyntaxFactory.QualifiedName(GetQualifiedNameSyntax(eii.ContainingType), SyntaxFactory.IdentifierName(eii.Name))).ToList(); if (list.Count == 0) { return null; } return SyntaxFactory.ImplementsClause(SyntaxFactory.SeparatedList(list.ToArray())); } private ImplementsClauseSyntax GetImplementsClause(IEventSymbol symbol, IFilterVisitor filterVisitor) { if (symbol.ExplicitInterfaceImplementations.Length == 0) { return null; } var list = (from eii in symbol.ExplicitInterfaceImplementations where filterVisitor.CanVisitApi(eii) select SyntaxFactory.QualifiedName(GetQualifiedNameSyntax(eii.ContainingType), SyntaxFactory.IdentifierName(eii.Name))).ToList(); if (list.Count == 0) { return null; } return SyntaxFactory.ImplementsClause(SyntaxFactory.SeparatedList(list.ToArray())); } private ImplementsClauseSyntax GetImplementsClause(IPropertySymbol symbol, IFilterVisitor filterVisitor) { if (symbol.ExplicitInterfaceImplementations.Length == 0) { return null; } var list = (from eii in symbol.ExplicitInterfaceImplementations where filterVisitor.CanVisitApi(eii) select SyntaxFactory.QualifiedName(GetQualifiedNameSyntax(eii.ContainingType), (SimpleNameSyntax)SyntaxFactory.IdentifierName(eii.Name))).ToList(); if (list.Count == 0) { return null; } return SyntaxFactory.ImplementsClause(SyntaxFactory.SeparatedList(list.ToArray())); } private EqualsValueSyntax GetDefaultValue(IParameterSymbol symbol) { if (symbol.HasExplicitDefaultValue) { return GetDefaultValueCore(symbol.ExplicitDefaultValue, symbol.Type); } return null; } private EqualsValueSyntax GetDefaultValue(IFieldSymbol symbol) { if (symbol.IsConst) { if (symbol.ContainingType.TypeKind == TypeKind.Enum) { return GetDefaultValueCore(symbol.ConstantValue, ((INamedTypeSymbol)symbol.Type).EnumUnderlyingType); } return GetDefaultValueCore(symbol.ConstantValue, symbol.Type); } return null; } //private EqualsValueSyntax GetDefaultValueCore(object value) //{ // if (value == null) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NothingLiteralExpression, // SyntaxFactory.Token(SyntaxKind.NothingKeyword))); // } // if (value is bool) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // (bool)value ? SyntaxKind.TrueLiteralExpression : SyntaxKind.FalseLiteralExpression, // SyntaxFactory.Token( // (bool)value ? SyntaxKind.TrueKeyword : SyntaxKind.FalseKeyword))); // } // if (value is long) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((long)value))); // } // if (value is ulong) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((ulong)value))); // } // if (value is int) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((int)value))); // } // if (value is uint) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((uint)value))); // } // if (value is short) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((short)value))); // } // if (value is ushort) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((ushort)value))); // } // if (value is byte) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((byte)value))); // } // if (value is sbyte) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((sbyte)value))); // } // if (value is double) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((double)value))); // } // if (value is float) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((float)value))); // } // if (value is decimal) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((decimal)value))); // } // if (value is char) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.CharacterLiteralExpression, // SyntaxFactory.Literal((char)value))); // } // if (value is string) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.StringLiteralExpression, // SyntaxFactory.Literal((string)value))); // } // Debug.Fail("Unknown default value!"); // return null; //} private static EqualsValueSyntax GetDefaultValueCore(object value, ITypeSymbol type) { var expr = GetLiteralExpression(value, type); if (expr != null) { return SyntaxFactory.EqualsValue(expr); } return null; } private static ExpressionSyntax GetLiteralExpression(TypedConstant constant) { if (constant.Type.TypeKind == TypeKind.Array) { if (constant.Values == null) { return GetLiteralExpression(null, constant.Type); } var items = (from value in constant.Values select GetLiteralExpression(value)).ToList(); if (items.TrueForAll(x => x != null)) { return SyntaxFactory.ArrayCreationExpression( SyntaxFactory.Token(SyntaxKind.NewKeyword), default(SyntaxList<AttributeListSyntax>), GetTypeSyntax( ((IArrayTypeSymbol)constant.Type).ElementType ), null, SyntaxFactory.SingletonList( SyntaxFactory.ArrayRankSpecifier() ), SyntaxFactory.CollectionInitializer( SyntaxFactory.SeparatedList( from value in constant.Values select GetLiteralExpression(value) ) ) ); } return SyntaxFactory.ArrayCreationExpression( SyntaxFactory.Token(SyntaxKind.NewKeyword), default(SyntaxList<AttributeListSyntax>), GetTypeSyntax( ((IArrayTypeSymbol)constant.Type).ElementType ), null, new SyntaxList<ArrayRankSpecifierSyntax>(), SyntaxFactory.CollectionInitializer() ); } var expr = GetLiteralExpression(constant.Value, constant.Type); if (expr == null) { return null; } switch (constant.Type.SpecialType) { case SpecialType.System_SByte: return SyntaxFactory.CTypeExpression( expr, SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.SByteKeyword))); case SpecialType.System_Byte: return SyntaxFactory.CTypeExpression( expr, SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.ByteKeyword))); case SpecialType.System_Int16: return SyntaxFactory.CTypeExpression( expr, SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.ShortKeyword))); case SpecialType.System_UInt16: return SyntaxFactory.CTypeExpression( expr, SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.UShortKeyword))); default: return expr; } } private static ExpressionSyntax GetLiteralExpression(object value, ITypeSymbol type) { if (value == null) { return SyntaxFactory.LiteralExpression( SyntaxKind.NothingLiteralExpression, SyntaxFactory.Token(SyntaxKind.NothingKeyword)); } var result = GetLiteralExpressionCore(value, type); if (result != null) { return result; } if (type.TypeKind == TypeKind.Enum) { var namedType = (INamedTypeSymbol)type; var enumType = GetTypeSyntax(namedType); var isFlags = namedType.GetAttributes().Any(attr => attr.AttributeClass.GetDocumentationCommentId() == "T:System.FlagsAttribute"); var pairs = from member in namedType.GetMembers().OfType<IFieldSymbol>() where member.IsConst && member.HasConstantValue select new { member.Name, member.ConstantValue }; if (isFlags) { var exprs = (from pair in pairs where HasFlag(namedType.EnumUnderlyingType, value, pair.ConstantValue) select SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, enumType, SyntaxFactory.Token(SyntaxKind.DotToken), SyntaxFactory.IdentifierName(pair.Name))).ToList(); if (exprs.Count > 0) { return exprs.Aggregate<ExpressionSyntax>(SyntaxFactory.OrExpression); } } else { var expr = (from pair in pairs where object.Equals(value, pair.ConstantValue) select SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, enumType, SyntaxFactory.Token(SyntaxKind.DotToken), SyntaxFactory.IdentifierName(pair.Name))).FirstOrDefault(); if (expr != null) { return expr; } } return SyntaxFactory.CTypeExpression( GetLiteralExpressionCore( value, namedType.EnumUnderlyingType), enumType); } if (value is ITypeSymbol) { return SyntaxFactory.GetTypeExpression( GetTypeSyntax((ITypeSymbol)value)); } Debug.Fail("Unknown default value!"); return null; } private static bool HasFlag(ITypeSymbol type, object value, object constantValue) { switch (type.SpecialType) { case SpecialType.System_SByte: { var v = (sbyte)value; var cv = (sbyte)constantValue; if (cv == 0) { return v == 0; } return (v & cv) == cv; } case SpecialType.System_Byte: { var v = (byte)value; var cv = (byte)constantValue; if (cv == 0) { return v == 0; } return (v & cv) == cv; } case SpecialType.System_Int16: { var v = (short)value; var cv = (short)constantValue; if (cv == 0) { return v == 0; } return (v & cv) == cv; } case SpecialType.System_UInt16: { var v = (ushort)value; var cv = (ushort)constantValue; if (cv == 0) { return v == 0; } return (v & cv) == cv; } case SpecialType.System_Int32: { var v = (int)value; var cv = (int)constantValue; if (cv == 0) { return v == 0; } return (v & cv) == cv; } case SpecialType.System_UInt32: { var v = (uint)value; var cv = (uint)constantValue; if (cv == 0) { return v == 0; } return (v & cv) == cv; } case SpecialType.System_Int64: { var v = (long)value; var cv = (long)constantValue; if (cv == 0) { return v == 0; } return (v & cv) == cv; } case SpecialType.System_UInt64: { var v = (ulong)value; var cv = (ulong)constantValue; if (cv == 0) { return v == 0; } return (v & cv) == cv; } default: return false; } } private static ExpressionSyntax GetLiteralExpressionCore(object value, ITypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_Boolean: if ((bool)value) { return SyntaxFactory.TrueLiteralExpression(SyntaxFactory.Token(SyntaxKind.TrueKeyword)); } else { return SyntaxFactory.FalseLiteralExpression(SyntaxFactory.Token(SyntaxKind.FalseKeyword)); } case SpecialType.System_Char: var ch = (char)value; var category = char.GetUnicodeCategory(ch); switch (category) { case System.Globalization.UnicodeCategory.Surrogate: return SyntaxFactory.LiteralExpression( SyntaxKind.CharacterLiteralExpression, SyntaxFactory.Literal("\"\\u" + ((int)ch).ToString("X4") + "\"c", ch)); default: return SyntaxFactory.LiteralExpression( SyntaxKind.CharacterLiteralExpression, SyntaxFactory.Literal((char)value)); } case SpecialType.System_SByte: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((sbyte)value)); case SpecialType.System_Byte: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((byte)value)); case SpecialType.System_Int16: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((short)value)); case SpecialType.System_UInt16: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((ushort)value)); case SpecialType.System_Int32: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((int)value)); case SpecialType.System_UInt32: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((uint)value)); case SpecialType.System_Int64: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((long)value)); case SpecialType.System_UInt64: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((ulong)value)); case SpecialType.System_Decimal: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((decimal)value)); case SpecialType.System_Single: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((float)value)); case SpecialType.System_Double: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((double)value)); case SpecialType.System_String: return SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal((string)value)); default: return null; } } private SimpleAsClauseSyntax GetReturnAsClause(IMethodSymbol symbol) { if (symbol.ReturnsVoid) { return null; } return SyntaxFactory.SimpleAsClause(GetTypeSyntax(symbol.ReturnType)); } private static SyntaxToken? GetOperatorToken(IMethodSymbol symbol) { switch (symbol.Name) { // unary case "op_UnaryPlus": return SyntaxFactory.Token(SyntaxKind.PlusToken); case "op_UnaryNegation": return SyntaxFactory.Token(SyntaxKind.MinusToken); case "op_OnesComplement": return SyntaxFactory.Token(SyntaxKind.NotKeyword); case "op_True": return SyntaxFactory.Token(SyntaxKind.IsTrueKeyword); case "op_False": return SyntaxFactory.Token(SyntaxKind.IsFalseKeyword); // binary case "op_Addition": return SyntaxFactory.Token(SyntaxKind.PlusToken); case "op_Subtraction": return SyntaxFactory.Token(SyntaxKind.MinusToken); case "op_Multiply": return SyntaxFactory.Token(SyntaxKind.AsteriskToken); case "op_Division": return SyntaxFactory.Token(SyntaxKind.SlashToken); case "op_Modulus": return SyntaxFactory.Token(SyntaxKind.ModKeyword); case "op_BitwiseAnd": return SyntaxFactory.Token(SyntaxKind.AndKeyword); case "op_BitwiseOr": return SyntaxFactory.Token(SyntaxKind.OrKeyword); case "op_ExclusiveOr": return SyntaxFactory.Token(SyntaxKind.XorKeyword); case "op_RightShift": return SyntaxFactory.Token(SyntaxKind.GreaterThanGreaterThanToken); case "op_LeftShift": return SyntaxFactory.Token(SyntaxKind.LessThanLessThanToken); // comparision case "op_Equality": return SyntaxFactory.Token(SyntaxKind.EqualsToken); case "op_Inequality": return SyntaxFactory.Token(SyntaxKind.LessThanGreaterThanToken); case "op_GreaterThan": return SyntaxFactory.Token(SyntaxKind.GreaterThanToken); case "op_LessThan": return SyntaxFactory.Token(SyntaxKind.LessThanToken); case "op_GreaterThanOrEqual": return SyntaxFactory.Token(SyntaxKind.GreaterThanEqualsToken); case "op_LessThanOrEqual": return SyntaxFactory.Token(SyntaxKind.LessThanEqualsToken); // conversion case "op_Implicit": case "op_Explicit": return SyntaxFactory.Token(SyntaxKind.CTypeKeyword); // not supported: //case "op_LogicalNot": //case "op_Increment": //case "op_Decrement": //case "op_Assign": default: return null; } } private static TypeSyntax GetTypeSyntax(ITypeSymbol type) { var name = NameVisitorCreator.GetVB(NameOptions.UseAlias | NameOptions.WithGenericParameter).GetName(type); return SyntaxFactory.ParseTypeName(name); } private static SyntaxToken GetIdentifier(ITypeSymbol type) { var name = NameVisitorCreator.GetVB(NameOptions.UseAlias | NameOptions.WithGenericParameter).GetName(type); return SyntaxFactory.Identifier(name); } private static NameSyntax GetQualifiedNameSyntax(ITypeSymbol type) { var name = NameVisitorCreator.GetVB(NameOptions.UseAlias | NameOptions.WithGenericParameter).GetName(type); return SyntaxFactory.ParseName(name); } private static string RemoveEnd(string code) { return EndRegex.Replace(code, string.Empty); } private static string GetVisiblity(Accessibility accessibility) { switch (accessibility) { case Accessibility.Protected: case Accessibility.ProtectedOrInternal: return "Protected"; case Accessibility.Public: return "Public"; default: return null; } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Security; namespace System.IO { public sealed partial class DriveInfo { private static string NormalizeDriveName(string driveName) { if (driveName.Contains("\0")) { throw new ArgumentException(SR.Format(SR.Arg_InvalidDriveChars, driveName), "driveName"); } if (driveName.Length == 0) { throw new ArgumentException(SR.Arg_MustBeNonEmptyDriveName, "driveName"); } return driveName; } public DriveType DriveType { [SecuritySafeCritical] get { Interop.libc.statfs data; Interop.ErrorInfo errorInfo; if (Interop.libc.TryGetStatFsForDriveName(Name, out data, out errorInfo)) { return GetDriveType(Interop.libc.GetMountPointFsType(data)); } // This is one of the few properties that doesn't throw on failure, // instead returning a value from the enum. switch (errorInfo.Error) { case Interop.Error.ELOOP: case Interop.Error.ENAMETOOLONG: case Interop.Error.ENOENT: case Interop.Error.ENOTDIR: return DriveType.NoRootDirectory; default: return DriveType.Unknown; } } } public string DriveFormat { [SecuritySafeCritical] get { Interop.libc.statfs data = Interop.libc.GetStatFsForDriveName(Name); return Interop.libc.GetMountPointFsType(data); } } public long AvailableFreeSpace { [SecuritySafeCritical] get { Interop.libc.statfs data = Interop.libc.GetStatFsForDriveName(Name); return (long)data.f_bsize * (long)data.f_bavail; } } public long TotalFreeSpace { [SecuritySafeCritical] get { Interop.libc.statfs data = Interop.libc.GetStatFsForDriveName(Name); return (long)data.f_bsize * (long)data.f_bfree; } } public long TotalSize { [SecuritySafeCritical] get { Interop.libc.statfs data = Interop.libc.GetStatFsForDriveName(Name); return (long)data.f_bsize * (long)data.f_blocks; } } public String VolumeLabel { [SecuritySafeCritical] get { return Name; } [SecuritySafeCritical] set { throw new PlatformNotSupportedException(); } } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary>Categorizes a file system name into a drive type.</summary> /// <param name="fileSystemName">The name to categorize.</param> /// <returns>The recognized drive type.</returns> private static DriveType GetDriveType(string fileSystemName) { // This list is based primarily on "man fs", "man mount", "mntent.h", "/proc/filesystems", // and "wiki.debian.org/FileSystem". It can be extended over time as we // find additional file systems that should be recognized as a particular drive type. switch (fileSystemName) { case "iso": case "isofs": case "iso9660": case "fuseiso": case "fuseiso9660": case "umview-mod-umfuseiso9660": return DriveType.CDRom; case "adfs": case "affs": case "befs": case "bfs": case "btrfs": case "ecryptfs": case "efs": case "ext": case "ext2": case "ext2_old": case "ext3": case "ext4": case "ext4dev": case "fat": case "fuseblk": case "fuseext2": case "fusefat": case "hfs": case "hfsplus": case "hpfs": case "jbd": case "jbd2": case "jfs": case "jffs": case "jffs2": case "minix": case "minix_old": case "minix2": case "minix2v2": case "msdos": case "ocfs2": case "omfs": case "openprom": case "ntfs": case "qnx4": case "reiserfs": case "squashfs": case "swap": case "sysv": case "ubifs": case "udf": case "ufs": case "umsdos": case "umview-mod-umfuseext2": case "xenix": case "xfs": case "xiafs": case "xmount": case "zfs-fuse": return DriveType.Fixed; case "9p": case "autofs": case "autofs4": case "beaglefs": case "cifs": case "coda": case "coherent": case "curlftpfs": case "davfs2": case "dlm": case "flickrfs": case "fusedav": case "fusesmb": case "gfs2": case "glusterfs-client": case "gmailfs": case "kafs": case "ltspfs": case "ncpfs": case "nfs": case "nfs4": case "obexfs": case "s3ql": case "smb": case "smbfs": case "sshfs": case "sysfs": case "sysv2": case "sysv4": case "vxfs": case "wikipediafs": return DriveType.Network; case "anon_inodefs": case "aptfs": case "avfs": case "bdev": case "binfmt_misc": case "cgroup": case "configfs": case "cramfs": case "cryptkeeper": case "cpuset": case "debugfs": case "devfs": case "devpts": case "devtmpfs": case "encfs": case "fuse": case "fuse.gvfsd-fuse": case "fusectl": case "hugetlbfs": case "libpam-encfs": case "ibpam-mount": case "mtpfs": case "mythtvfs": case "mqueue": case "pipefs": case "plptools": case "proc": case "pstore": case "pytagsfs": case "ramfs": case "rofs": case "romfs": case "rootfs": case "securityfs": case "sockfs": case "tmpfs": return DriveType.Ram; case "gphotofs": case "usbfs": case "usbdevice": case "vfat": return DriveType.Removable; case "aufs": // marking all unions as unknown case "funionfs": case "unionfs-fuse": case "mhddfs": default: return DriveType.Unknown; } } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Channels { using System.Xml; using System.ServiceModel; using System.ServiceModel.Description; using System.ServiceModel.Security; using System.Xml.Schema; using System.Collections.ObjectModel; using System.Collections.Generic; using WsdlNS = System.Web.Services.Description; // implemented by Indigo Transports interface ITransportPolicyImport { void ImportPolicy(MetadataImporter importer, PolicyConversionContext policyContext); } public class TransportBindingElementImporter : IWsdlImportExtension, IPolicyImportExtension { void IWsdlImportExtension.BeforeImport(WsdlNS.ServiceDescriptionCollection wsdlDocuments, XmlSchemaSet xmlSchemas, ICollection<XmlElement> policy) { WsdlImporter.SoapInPolicyWorkaroundHelper.InsertAdHocTransportPolicy(wsdlDocuments); } void IWsdlImportExtension.ImportContract(WsdlImporter importer, WsdlContractConversionContext context) { } void IWsdlImportExtension.ImportEndpoint(WsdlImporter importer, WsdlEndpointConversionContext context) { if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); } #pragma warning suppress 56506 // [....], these properties cannot be null in this context if (context.Endpoint.Binding == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context.Endpoint.Binding"); } #pragma warning suppress 56506 // [....], CustomBinding.Elements never be null TransportBindingElement transportBindingElement = GetBindingElements(context).Find<TransportBindingElement>(); bool transportHandledExternaly = (transportBindingElement != null) && !StateHelper.IsRegisteredTransportBindingElement(importer, context); if (transportHandledExternaly) return; #pragma warning suppress 56506 // [....], these properties cannot be null in this context WsdlNS.SoapBinding soapBinding = (WsdlNS.SoapBinding)context.WsdlBinding.Extensions.Find(typeof(WsdlNS.SoapBinding)); if (soapBinding != null && transportBindingElement == null) { CreateLegacyTransportBindingElement(importer, soapBinding, context); } // Try to import WS-Addressing address from the port if (context.WsdlPort != null) { ImportAddress(context, transportBindingElement); } } static BindingElementCollection GetBindingElements(WsdlEndpointConversionContext context) { Binding binding = context.Endpoint.Binding; BindingElementCollection elements = binding is CustomBinding ? ((CustomBinding)binding).Elements : binding.CreateBindingElements(); return elements; } static CustomBinding ConvertToCustomBinding(WsdlEndpointConversionContext context) { CustomBinding customBinding = context.Endpoint.Binding as CustomBinding; if (customBinding == null) { customBinding = new CustomBinding(context.Endpoint.Binding); context.Endpoint.Binding = customBinding; } return customBinding; } static void ImportAddress(WsdlEndpointConversionContext context, TransportBindingElement transportBindingElement) { EndpointAddress address = context.Endpoint.Address = WsdlImporter.WSAddressingHelper.ImportAddress(context.WsdlPort); if (address != null) { context.Endpoint.Address = address; // Replace the http BE with https BE only if the uri scheme is https and the transport binding element is a HttpTransportBindingElement but not HttpsTransportBindingElement if (address.Uri.Scheme == Uri.UriSchemeHttps && transportBindingElement is HttpTransportBindingElement && !(transportBindingElement is HttpsTransportBindingElement)) { BindingElementCollection elements = ConvertToCustomBinding(context).Elements; elements.Remove(transportBindingElement); elements.Add(CreateHttpsFromHttp(transportBindingElement as HttpTransportBindingElement)); } } } static void CreateLegacyTransportBindingElement(WsdlImporter importer, WsdlNS.SoapBinding soapBinding, WsdlEndpointConversionContext context) { // We create a transportBindingElement based on the SoapBinding's Transport TransportBindingElement transportBindingElement = CreateTransportBindingElements(soapBinding.Transport, null); if (transportBindingElement != null) { ConvertToCustomBinding(context).Elements.Add(transportBindingElement); StateHelper.RegisterTransportBindingElement(importer, context); } } static HttpsTransportBindingElement CreateHttpsFromHttp(HttpTransportBindingElement http) { if (http == null) return new HttpsTransportBindingElement(); HttpsTransportBindingElement https = HttpsTransportBindingElement.CreateFromHttpBindingElement(http); return https; } void IPolicyImportExtension.ImportPolicy(MetadataImporter importer, PolicyConversionContext policyContext) { XmlQualifiedName wsdlBindingQName; string transportUri = WsdlImporter.SoapInPolicyWorkaroundHelper.FindAdHocTransportPolicy(policyContext, out wsdlBindingQName); if (transportUri != null && !policyContext.BindingElements.Contains(typeof(TransportBindingElement))) { TransportBindingElement transportBindingElement = CreateTransportBindingElements(transportUri, policyContext); if (transportBindingElement != null) { ITransportPolicyImport transportPolicyImport = transportBindingElement as ITransportPolicyImport; if (transportPolicyImport != null) transportPolicyImport.ImportPolicy(importer, policyContext); policyContext.BindingElements.Add(transportBindingElement); StateHelper.RegisterTransportBindingElement(importer, wsdlBindingQName); } } } static TransportBindingElement CreateTransportBindingElements(string transportUri, PolicyConversionContext policyContext) { TransportBindingElement transportBindingElement = null; // Try and Create TransportBindingElement switch (transportUri) { case TransportPolicyConstants.HttpTransportUri: transportBindingElement = GetHttpTransportBindingElement(policyContext); break; case TransportPolicyConstants.TcpTransportUri: transportBindingElement = new TcpTransportBindingElement(); break; case TransportPolicyConstants.NamedPipeTransportUri: transportBindingElement = new NamedPipeTransportBindingElement(); break; case TransportPolicyConstants.MsmqTransportUri: transportBindingElement = new MsmqTransportBindingElement(); break; case TransportPolicyConstants.PeerTransportUri: #pragma warning disable 0618 transportBindingElement = new PeerTransportBindingElement(); #pragma warning restore 0618 break; case TransportPolicyConstants.WebSocketTransportUri: HttpTransportBindingElement httpTransport = GetHttpTransportBindingElement(policyContext); httpTransport.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always; httpTransport.WebSocketSettings.SubProtocol = WebSocketTransportSettings.SoapSubProtocol; transportBindingElement = httpTransport; break; default: // There may be another registered converter that can handle this transport. break; } return transportBindingElement; } static HttpTransportBindingElement GetHttpTransportBindingElement(PolicyConversionContext policyContext) { if (policyContext != null) { WSSecurityPolicy sp = null; ICollection<XmlElement> policyCollection = policyContext.GetBindingAssertions(); if (WSSecurityPolicy.TryGetSecurityPolicyDriver(policyCollection, out sp) && sp.ContainsWsspHttpsTokenAssertion(policyCollection)) { HttpsTransportBindingElement httpsBinding = new HttpsTransportBindingElement(); httpsBinding.MessageSecurityVersion = sp.GetSupportedMessageSecurityVersion(SecurityVersion.WSSecurity11); return httpsBinding; } } return new HttpTransportBindingElement(); } } internal static class StateHelper { readonly static object StateBagKey = new object(); static Dictionary<XmlQualifiedName, XmlQualifiedName> GetGeneratedTransportBindingElements(MetadataImporter importer) { object retValue; if (!importer.State.TryGetValue(StateHelper.StateBagKey, out retValue)) { retValue = new Dictionary<XmlQualifiedName, XmlQualifiedName>(); importer.State.Add(StateHelper.StateBagKey, retValue); } return (Dictionary<XmlQualifiedName, XmlQualifiedName>)retValue; } internal static void RegisterTransportBindingElement(MetadataImporter importer, XmlQualifiedName wsdlBindingQName) { GetGeneratedTransportBindingElements(importer)[wsdlBindingQName] = wsdlBindingQName; } internal static void RegisterTransportBindingElement(MetadataImporter importer, WsdlEndpointConversionContext context) { XmlQualifiedName wsdlBindingQName = new XmlQualifiedName(context.WsdlBinding.Name, context.WsdlBinding.ServiceDescription.TargetNamespace); GetGeneratedTransportBindingElements(importer)[wsdlBindingQName] = wsdlBindingQName; } internal static bool IsRegisteredTransportBindingElement(WsdlImporter importer, WsdlEndpointConversionContext context) { XmlQualifiedName key = new XmlQualifiedName(context.WsdlBinding.Name, context.WsdlBinding.ServiceDescription.TargetNamespace); return GetGeneratedTransportBindingElements(importer).ContainsKey(key); } } static class TransportPolicyConstants { public const string BasicHttpAuthenticationName = "BasicAuthentication"; public const string CompositeDuplex = "CompositeDuplex"; public const string CompositeDuplexNamespace = "http://schemas.microsoft.com/net/2006/06/duplex"; public const string CompositeDuplexPrefix = "cdp"; public const string DigestHttpAuthenticationName = "DigestAuthentication"; public const string DotNetFramingNamespace = FramingEncodingString.NamespaceUri + "/policy"; public const string DotNetFramingPrefix = "msf"; public const string HttpTransportNamespace = "http://schemas.microsoft.com/ws/06/2004/policy/http"; public const string HttpTransportPrefix = "http"; public const string HttpTransportUri = "http://schemas.xmlsoap.org/soap/http"; public const string MsmqBestEffort = "MsmqBestEffort"; public const string MsmqSession = "MsmqSession"; public const string MsmqTransportNamespace = "http://schemas.microsoft.com/ws/06/2004/mspolicy/msmq"; public const string MsmqTransportPrefix = "msmq"; public const string MsmqTransportUri = "http://schemas.microsoft.com/soap/msmq"; public const string MsmqVolatile = "MsmqVolatile"; public const string MsmqAuthenticated = "Authenticated"; public const string MsmqWindowsDomain = "WindowsDomain"; public const string NamedPipeTransportUri = "http://schemas.microsoft.com/soap/named-pipe"; public const string NegotiateHttpAuthenticationName = "NegotiateAuthentication"; public const string NtlmHttpAuthenticationName = "NtlmAuthentication"; public const string PeerTransportUri = "http://schemas.microsoft.com/soap/peer"; public const string ProtectionLevelName = "ProtectionLevel"; public const string RequireClientCertificateName = "RequireClientCertificate"; public const string SslTransportSecurityName = "SslTransportSecurity"; public const string StreamedName = "Streamed"; public const string TcpTransportUri = "http://schemas.microsoft.com/soap/tcp"; public const string WebSocketPolicyPrefix = "mswsp"; public const string WebSocketPolicyNamespace = "http://schemas.microsoft.com/soap/websocket/policy"; public const string WebSocketTransportUri = "http://schemas.microsoft.com/soap/websocket"; public const string WebSocketEnabled = "WebSocketEnabled"; public const string WindowsTransportSecurityName = "WindowsTransportSecurity"; } }
// 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; using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; using System.Text.RegularExpressions; using System.Xml.Extensions; #if !FEATURE_SERIALIZATION_UAPAOT namespace System.Xml.Serialization { internal class SourceInfo { //a[ia] //((global::System.Xml.Serialization.XmlSerializerNamespaces)p[0]) private static Regex s_regex = new Regex("([(][(](?<t>[^)]+)[)])?(?<a>[^[]+)[[](?<ia>.+)[]][)]?"); //((global::Microsoft.CFx.Test.Common.TypeLibrary.IXSType_9)o), @"IXSType_9", @"", true, true); private static Regex s_regex2 = new Regex("[(][(](?<cast>[^)]+)[)](?<arg>[^)]+)[)]"); private static readonly Lazy<MethodInfo> s_iListGetItemMethod = new Lazy<MethodInfo>( () => { return typeof(IList).GetMethod( "get_Item", new Type[] { typeof(int) } ); }); public string Source; public readonly string Arg; public readonly MemberInfo MemberInfo; public readonly Type Type; public readonly CodeGenerator ILG; public SourceInfo(string source, string arg, MemberInfo memberInfo, Type type, CodeGenerator ilg) { this.Source = source; this.Arg = arg ?? source; this.MemberInfo = memberInfo; this.Type = type; this.ILG = ilg; } public SourceInfo CastTo(TypeDesc td) { return new SourceInfo("((" + td.CSharpName + ")" + Source + ")", Arg, MemberInfo, td.Type, ILG); } public void LoadAddress(Type elementType) { InternalLoad(elementType, asAddress: true); } public void Load(Type elementType) { InternalLoad(elementType); } private void InternalLoad(Type elementType, bool asAddress = false) { Match match = s_regex.Match(Arg); if (match.Success) { object varA = ILG.GetVariable(match.Groups["a"].Value); Type varType = ILG.GetVariableType(varA); object varIA = ILG.GetVariable(match.Groups["ia"].Value); if (varType.IsArray) { ILG.Load(varA); ILG.Load(varIA); Type eType = varType.GetElementType(); if (CodeGenerator.IsNullableGenericType(eType)) { ILG.Ldelema(eType); ConvertNullableValue(eType, elementType); } else { if (eType.IsValueType) { ILG.Ldelema(eType); if (!asAddress) { ILG.Ldobj(eType); } } else ILG.Ldelem(eType); if (elementType != null) ILG.ConvertValue(eType, elementType); } } else { ILG.Load(varA); ILG.Load(varIA); MethodInfo get_Item = varType.GetMethod( "get_Item", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(int) } ); if (get_Item == null && typeof(IList).IsAssignableFrom(varType)) { get_Item = s_iListGetItemMethod.Value; } Debug.Assert(get_Item != null); ILG.Call(get_Item); Type eType = get_Item.ReturnType; if (CodeGenerator.IsNullableGenericType(eType)) { LocalBuilder localTmp = ILG.GetTempLocal(eType); ILG.Stloc(localTmp); ILG.Ldloca(localTmp); ConvertNullableValue(eType, elementType); } else if ((elementType != null) && !(eType.IsAssignableFrom(elementType) || elementType.IsAssignableFrom(eType))) { throw new CodeGeneratorConversionException(eType, elementType, asAddress, "IsNotAssignableFrom"); } else { Convert(eType, elementType, asAddress); } } } else if (Source == "null") { ILG.Load(null); } else { object var; Type varType; if (Arg.StartsWith("o.@", StringComparison.Ordinal) || MemberInfo != null) { var = ILG.GetVariable(Arg.StartsWith("o.@", StringComparison.Ordinal) ? "o" : Arg); varType = ILG.GetVariableType(var); if (varType.IsValueType) ILG.LoadAddress(var); else ILG.Load(var); } else { var = ILG.GetVariable(Arg); varType = ILG.GetVariableType(var); if (CodeGenerator.IsNullableGenericType(varType) && varType.GetGenericArguments()[0] == elementType) { ILG.LoadAddress(var); ConvertNullableValue(varType, elementType); } else { if (asAddress) ILG.LoadAddress(var); else ILG.Load(var); } } if (MemberInfo != null) { Type memberType = (MemberInfo is FieldInfo) ? ((FieldInfo)MemberInfo).FieldType : ((PropertyInfo)MemberInfo).PropertyType; if (CodeGenerator.IsNullableGenericType(memberType)) { ILG.LoadMemberAddress(MemberInfo); ConvertNullableValue(memberType, elementType); } else { ILG.LoadMember(MemberInfo); Convert(memberType, elementType, asAddress); } } else { match = s_regex2.Match(Source); if (match.Success) { Debug.Assert(match.Groups["arg"].Value == Arg); Debug.Assert(match.Groups["cast"].Value == CodeIdentifier.GetCSharpName(Type)); if (asAddress) ILG.ConvertAddress(varType, Type); else ILG.ConvertValue(varType, Type); varType = Type; } Convert(varType, elementType, asAddress); } } } private void Convert(Type sourceType, Type targetType, bool asAddress) { if (targetType != null) { if (asAddress) ILG.ConvertAddress(sourceType, targetType); else ILG.ConvertValue(sourceType, targetType); } } private void ConvertNullableValue(Type nullableType, Type targetType) { System.Diagnostics.Debug.Assert(targetType == nullableType || targetType.IsAssignableFrom(nullableType.GetGenericArguments()[0])); if (targetType != nullableType) { MethodInfo Nullable_get_Value = nullableType.GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Array.Empty<Type>() ); ILG.Call(Nullable_get_Value); if (targetType != null) { ILG.ConvertValue(Nullable_get_Value.ReturnType, targetType); } } } public static implicit operator string (SourceInfo source) { return source.Source; } public static bool operator !=(SourceInfo a, SourceInfo b) { if ((object)a != null) return !a.Equals(b); return (object)b != null; } public static bool operator ==(SourceInfo a, SourceInfo b) { if ((object)a != null) return a.Equals(b); return (object)b == null; } public override bool Equals(object obj) { if (obj == null) return Source == null; SourceInfo info = obj as SourceInfo; if (info != null) return Source == info.Source; return false; } public override int GetHashCode() { return (Source == null) ? 0 : Source.GetHashCode(); } } } #endif
// Copyright (C) 2014 dot42 // // Original filename: BackgroundWorker.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Threading; using Android.OS; namespace System.ComponentModel { /// <summary> /// Executes an action on a background thread. /// </summary> public class BackgroundWorker : Component { public event EventHandler<DoWorkEventArgs> DoWork; public event EventHandler<ProgressChangedEventArgs> ProgressChanged; public event EventHandler<RunWorkerCompletedEventArgs> RunWorkerCompleted; private WorkerTask task; /// <summary> /// Has cancellation been requested? /// </summary> public bool CancellationPending { get; private set; } /// <summary> /// Is this worker running a background operation? /// </summary> public bool IsBusy { get { return (task != null); } } /// <summary> /// Can this worker report progress updates? /// </summary> public bool WorkerReportsProgress { get; set; } /// <summary> /// Does this worker support cancellation? /// </summary> public bool WorkerSupportsCancellation { get; set; } /// <summary> /// Request cancellation of the background operation. /// </summary> /// <exception cref="InvalidOperationException">When <see cref="WorkerSupportsCancellation"/> is false.</exception> public void CancelAsync() { if (!WorkerSupportsCancellation) throw new InvalidOperationException(); CancellationPending = true; } /// <summary> /// Raises the ProgresChanged event. /// </summary> /// <exception cref="InvalidOperationException">When <see cref="WorkerReportsProgress"/> is false.</exception> public void ReportProgress(int percentProgress) { if (!WorkerReportsProgress) throw new InvalidOperationException(); var theTask = task; if (theTask != null) theTask.ReportProgress(percentProgress, null); } /// <summary> /// Raises the ProgresChanged event. /// </summary> /// <exception cref="InvalidOperationException">When <see cref="WorkerReportsProgress"/> is false.</exception> public void ReportProgress(int percentProgress, object userState) { if (!WorkerReportsProgress) throw new InvalidOperationException(); var theTask = task; if (theTask != null) theTask.ReportProgress(percentProgress, userState); } /// <summary> /// Start the background operation. /// </summary> /// <exception cref="InvalidOperationException">When <see cref="IsBusy"/> is true.</exception> public void RunWorkerAsync() { if (IsBusy) throw new InvalidOperationException(); task = new WorkerTask(this, null); } /// <summary> /// Start the background operation. /// </summary> /// <exception cref="InvalidOperationException">When <see cref="IsBusy"/> is true.</exception> public void RunWorkerAsync(object argument) { if (IsBusy) throw new InvalidOperationException(); task = new WorkerTask(this, argument); } /// <summary> /// Raises the DoWork event /// </summary> protected virtual void OnDoWork(DoWorkEventArgs e) { if (DoWork != null) { DoWork(this, e); } } /// <summary> /// Raises the ProgressChanged event. /// </summary> protected virtual void OnProgressChanged(ProgressChangedEventArgs e) { if (ProgressChanged != null) { ProgressChanged(this, e); } } /// <summary> /// Raises the RunWorkerCompleted event. /// </summary> protected virtual void OnRunWorkerCompleted(RunWorkerCompletedEventArgs e) { if (RunWorkerCompleted != null) { RunWorkerCompleted(this, e); } } internal void OnDone() { task = null; } /// <summary> /// Background task. /// </summary> private sealed class WorkerTask { private readonly BackgroundWorker worker; private readonly object argument; private object result; private readonly Handler resultHandler; private readonly Handler progressHandler; private Exception error; /// <summary> /// Default ctor /// </summary> public WorkerTask(BackgroundWorker worker, object argument) { this.worker = worker; this.argument = argument; resultHandler = new Handler(HandleWorkCompleted); progressHandler = new Handler(HandleProgress); // Start background thread var thread = new Thread(DoWork); thread.Start(); } /// <summary> /// Report progress back to the initial thread. /// </summary> internal void ReportProgress(int percentProgress, object userState) { var m = progressHandler.ObtainMessage(0, percentProgress); progressHandler.SendMessage(m); } /// <summary> /// Perform the background work. /// </summary> private void DoWork() { // Perform work try { var args = new DoWorkEventArgs(argument); worker.OnDoWork(args); result = args.Result; } catch (Exception ex) { error = ex; } // Invoke result handler resultHandler.SendEmptyMessage(0); } /// <summary> /// The background work has been completed. /// This method is called on the initial thread. /// </summary> private bool HandleWorkCompleted(Message message) { try { worker.OnRunWorkerCompleted(new RunWorkerCompletedEventArgs(result, error, false)); } finally { worker.OnDone(); } return true; } /// <summary> /// The background thread and notified us of some progress. /// This method is called on the initial thread. /// </summary> private bool HandleProgress(Message message) { worker.OnProgressChanged(new ProgressChangedEventArgs(message.Arg1, null)); return true; } } } }
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Localization; using Newtonsoft.Json.Linq; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Display; using OrchardCore.ContentManagement.Metadata; using OrchardCore.ContentManagement.Metadata.Settings; using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.DisplayManagement.Notify; using OrchardCore.Taxonomies.Models; using YesSql; namespace OrchardCore.Taxonomies.Controllers { public class AdminController : Controller { private readonly IContentManager _contentManager; private readonly IAuthorizationService _authorizationService; private readonly IContentItemDisplayManager _contentItemDisplayManager; private readonly IContentDefinitionManager _contentDefinitionManager; private readonly ISession _session; private readonly IHtmlLocalizer H; private readonly INotifier _notifier; private readonly IUpdateModelAccessor _updateModelAccessor; public AdminController( ISession session, IContentManager contentManager, IAuthorizationService authorizationService, IContentItemDisplayManager contentItemDisplayManager, IContentDefinitionManager contentDefinitionManager, INotifier notifier, IHtmlLocalizer<AdminController> localizer, IUpdateModelAccessor updateModelAccessor) { _contentManager = contentManager; _authorizationService = authorizationService; _contentItemDisplayManager = contentItemDisplayManager; _contentDefinitionManager = contentDefinitionManager; _session = session; _notifier = notifier; _updateModelAccessor = updateModelAccessor; H = localizer; } public async Task<IActionResult> Create(string id, string taxonomyContentItemId, string taxonomyItemId) { if (String.IsNullOrWhiteSpace(id)) { return NotFound(); } if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTaxonomies)) { return Forbid(); } var contentItem = await _contentManager.NewAsync(id); contentItem.Weld<TermPart>(); contentItem.Alter<TermPart>(t => t.TaxonomyContentItemId = taxonomyContentItemId); dynamic model = await _contentItemDisplayManager.BuildEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, true); model.TaxonomyContentItemId = taxonomyContentItemId; model.TaxonomyItemId = taxonomyItemId; return View(model); } [HttpPost] [ActionName("Create")] public async Task<IActionResult> CreatePost(string id, string taxonomyContentItemId, string taxonomyItemId) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTaxonomies)) { return Forbid(); } ContentItem taxonomy; var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition("Taxonomy"); if (!contentTypeDefinition.GetSettings<ContentTypeSettings>().Draftable) { taxonomy = await _contentManager.GetAsync(taxonomyContentItemId, VersionOptions.Latest); } else { taxonomy = await _contentManager.GetAsync(taxonomyContentItemId, VersionOptions.DraftRequired); } if (taxonomy == null) { return NotFound(); } var contentItem = await _contentManager.NewAsync(id); contentItem.Weld<TermPart>(); contentItem.Alter<TermPart>(t => t.TaxonomyContentItemId = taxonomyContentItemId); dynamic model = await _contentItemDisplayManager.UpdateEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, true); if (!ModelState.IsValid) { model.TaxonomyContentItemId = taxonomyContentItemId; model.TaxonomyItemId = taxonomyItemId; return View(model); } if (taxonomyItemId == null) { // Use the taxonomy as the parent if no target is specified taxonomy.Alter<TaxonomyPart>(part => part.Terms.Add(contentItem)); } else { // Look for the target taxonomy item in the hierarchy var parentTaxonomyItem = FindTaxonomyItem(taxonomy.As<TaxonomyPart>().Content, taxonomyItemId); // Couldn't find targeted taxonomy item if (parentTaxonomyItem == null) { return NotFound(); } var taxonomyItems = parentTaxonomyItem?.Terms as JArray; if (taxonomyItems == null) { parentTaxonomyItem["Terms"] = taxonomyItems = new JArray(); } taxonomyItems.Add(JObject.FromObject(contentItem)); } _session.Save(taxonomy); return RedirectToAction("Edit", "Admin", new { area = "OrchardCore.Contents", contentItemId = taxonomyContentItemId }); } public async Task<IActionResult> Edit(string taxonomyContentItemId, string taxonomyItemId) { var taxonomy = await _contentManager.GetAsync(taxonomyContentItemId, VersionOptions.Latest); if (taxonomy == null) { return NotFound(); } if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTaxonomies, taxonomy)) { return Forbid(); } // Look for the target taxonomy item in the hierarchy JObject taxonomyItem = FindTaxonomyItem(taxonomy.As<TaxonomyPart>().Content, taxonomyItemId); // Couldn't find targeted taxonomy item if (taxonomyItem == null) { return NotFound(); } var contentItem = taxonomyItem.ToObject<ContentItem>(); contentItem.Weld<TermPart>(); contentItem.Alter<TermPart>(t => t.TaxonomyContentItemId = taxonomyContentItemId); dynamic model = await _contentItemDisplayManager.BuildEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, false); model.TaxonomyContentItemId = taxonomyContentItemId; model.TaxonomyItemId = taxonomyItemId; return View(model); } [HttpPost] [ActionName("Edit")] public async Task<IActionResult> EditPost(string taxonomyContentItemId, string taxonomyItemId) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTaxonomies)) { return Forbid(); } ContentItem taxonomy; var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition("Taxonomy"); if (!contentTypeDefinition.GetSettings<ContentTypeSettings>().Draftable) { taxonomy = await _contentManager.GetAsync(taxonomyContentItemId, VersionOptions.Latest); } else { taxonomy = await _contentManager.GetAsync(taxonomyContentItemId, VersionOptions.DraftRequired); } if (taxonomy == null) { return NotFound(); } // Look for the target taxonomy item in the hierarchy JObject taxonomyItem = FindTaxonomyItem(taxonomy.As<TaxonomyPart>().Content, taxonomyItemId); // Couldn't find targeted taxonomy item if (taxonomyItem == null) { return NotFound(); } var contentItem = taxonomyItem.ToObject<ContentItem>(); contentItem.Weld<TermPart>(); contentItem.Alter<TermPart>(t => t.TaxonomyContentItemId = taxonomyContentItemId); dynamic model = await _contentItemDisplayManager.UpdateEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, false); if (!ModelState.IsValid) { model.TaxonomyContentItemId = taxonomyContentItemId; model.TaxonomyItemId = taxonomyItemId; return View(model); } taxonomyItem.Merge(contentItem.Content, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace, MergeNullValueHandling = MergeNullValueHandling.Merge }); // Merge doesn't copy the properties taxonomyItem[nameof(ContentItem.DisplayText)] = contentItem.DisplayText; _session.Save(taxonomy); return RedirectToAction("Edit", "Admin", new { area = "OrchardCore.Contents", contentItemId = taxonomyContentItemId }); } [HttpPost] public async Task<IActionResult> Delete(string taxonomyContentItemId, string taxonomyItemId) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTaxonomies)) { return Forbid(); } ContentItem taxonomy; var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition("Taxonomy"); if (!contentTypeDefinition.GetSettings<ContentTypeSettings>().Draftable) { taxonomy = await _contentManager.GetAsync(taxonomyContentItemId, VersionOptions.Latest); } else { taxonomy = await _contentManager.GetAsync(taxonomyContentItemId, VersionOptions.DraftRequired); } if (taxonomy == null) { return NotFound(); } // Look for the target taxonomy item in the hierarchy var taxonomyItem = FindTaxonomyItem(taxonomy.As<TaxonomyPart>().Content, taxonomyItemId); // Couldn't find targeted taxonomy item if (taxonomyItem == null) { return NotFound(); } taxonomyItem.Remove(); _session.Save(taxonomy); _notifier.Success(H["Taxonomy item deleted successfully"]); return RedirectToAction("Edit", "Admin", new { area = "OrchardCore.Contents", contentItemId = taxonomyContentItemId }); } private JObject FindTaxonomyItem(JObject contentItem, string taxonomyItemId) { if (contentItem["ContentItemId"]?.Value<string>() == taxonomyItemId) { return contentItem; } if (contentItem.GetValue("Terms") == null) { return null; } var taxonomyItems = (JArray)contentItem["Terms"]; JObject result; foreach (JObject taxonomyItem in taxonomyItems) { // Search in inner taxonomy items result = FindTaxonomyItem(taxonomyItem, taxonomyItemId); if (result != null) { return result; } } return null; } } }
using System; using UnityEngine.Events; using UnityEngine.EventSystems; namespace UnityEngine.UI { [AddComponentMenu("UI/Scroll Rect", 33)] [SelectionBase] [ExecuteInEditMode] [RequireComponent(typeof(RectTransform))] public class ScrollRect : UIBehaviour, IInitializePotentialDragHandler, IBeginDragHandler, IEndDragHandler, IDragHandler, IScrollHandler, ICanvasElement { public enum MovementType { Unrestricted, // Unrestricted movement -- can scroll forever Elastic, // Restricted but flexible -- can go past the edges, but springs back in place Clamped, // Restricted movement where it's not possible to go past the edges } [Serializable] public class ScrollRectEvent : UnityEvent<Vector2> { } [SerializeField] private RectTransform m_Content; public RectTransform content { get { return m_Content; } set { m_Content = value; } } [SerializeField] private bool m_Horizontal = true; public bool horizontal { get { return m_Horizontal; } set { m_Horizontal = value; } } [SerializeField] private bool m_Vertical = true; public bool vertical { get { return m_Vertical; } set { m_Vertical = value; } } [SerializeField] private MovementType m_MovementType = MovementType.Elastic; public MovementType movementType { get { return m_MovementType; } set { m_MovementType = value; } } [SerializeField] private float m_Elasticity = 0.1f; // Only used for MovementType.Elastic public float elasticity { get { return m_Elasticity; } set { m_Elasticity = value; } } [SerializeField] private bool m_Inertia = true; public bool inertia { get { return m_Inertia; } set { m_Inertia = value; } } [SerializeField] private float m_DecelerationRate = 0.135f; // Only used when inertia is enabled public float decelerationRate { get { return m_DecelerationRate; } set { m_DecelerationRate = value; } } [SerializeField] private float m_ScrollSensitivity = 1.0f; public float scrollSensitivity { get { return m_ScrollSensitivity; } set { m_ScrollSensitivity = value; } } [SerializeField] private Scrollbar m_HorizontalScrollbar; public Scrollbar horizontalScrollbar { get { return m_HorizontalScrollbar; } set { if (m_HorizontalScrollbar) m_HorizontalScrollbar.onValueChanged.RemoveListener(SetHorizontalNormalizedPosition); m_HorizontalScrollbar = value; if (m_HorizontalScrollbar) m_HorizontalScrollbar.onValueChanged.AddListener(SetHorizontalNormalizedPosition); } } [SerializeField] private Scrollbar m_VerticalScrollbar; public Scrollbar verticalScrollbar { get { return m_VerticalScrollbar; } set { if (m_VerticalScrollbar) m_VerticalScrollbar.onValueChanged.RemoveListener(SetVerticalNormalizedPosition); m_VerticalScrollbar = value; if (m_VerticalScrollbar) m_VerticalScrollbar.onValueChanged.AddListener(SetVerticalNormalizedPosition); } } [SerializeField] private ScrollRectEvent m_OnValueChanged = new ScrollRectEvent(); public ScrollRectEvent onValueChanged { get { return m_OnValueChanged; } set { m_OnValueChanged = value; } } // The offset from handle position to mouse down position private Vector2 m_PointerStartLocalCursor = Vector2.zero; private Vector2 m_ContentStartPosition = Vector2.zero; private RectTransform m_ViewRect; protected RectTransform viewRect { get { if (m_ViewRect == null) m_ViewRect = (RectTransform)transform; return m_ViewRect; } } private Bounds m_ContentBounds; private Bounds m_ViewBounds; private Vector2 m_Velocity; public Vector2 velocity { get { return m_Velocity; } set { m_Velocity = value; } } private bool m_Dragging; private Vector2 m_PrevPosition = Vector2.zero; private Bounds m_PrevContentBounds; private Bounds m_PrevViewBounds; [NonSerialized] private bool m_HasRebuiltLayout = false; protected ScrollRect() { } public virtual void Rebuild(CanvasUpdate executing) { if (executing != CanvasUpdate.PostLayout) return; UpdateBounds(); UpdateScrollbars(Vector2.zero); UpdatePrevData(); m_HasRebuiltLayout = true; } protected override void OnEnable() { base.OnEnable(); if (m_HorizontalScrollbar) m_HorizontalScrollbar.onValueChanged.AddListener(SetHorizontalNormalizedPosition); if (m_VerticalScrollbar) m_VerticalScrollbar.onValueChanged.AddListener(SetVerticalNormalizedPosition); CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this); } protected override void OnDisable() { if (m_HorizontalScrollbar) m_HorizontalScrollbar.onValueChanged.RemoveListener(SetHorizontalNormalizedPosition); if (m_VerticalScrollbar) m_VerticalScrollbar.onValueChanged.RemoveListener(SetVerticalNormalizedPosition); m_HasRebuiltLayout = false; base.OnDisable(); } public override bool IsActive() { return base.IsActive() && m_Content != null; } private void EnsureLayoutHasRebuilt() { if (!m_HasRebuiltLayout && !CanvasUpdateRegistry.IsRebuildingLayout()) Canvas.ForceUpdateCanvases(); } public virtual void StopMovement() { m_Velocity = Vector2.zero; } public virtual void OnScroll(PointerEventData data) { if (!IsActive()) return; EnsureLayoutHasRebuilt(); UpdateBounds(); Vector2 delta = data.scrollDelta; // Down is positive for scroll events, while in UI system up is positive. delta.y *= -1; if (vertical && !horizontal) { if (Mathf.Abs(delta.x) > Mathf.Abs(delta.y)) delta.y = delta.x; delta.x = 0; } if (horizontal && !vertical) { if (Mathf.Abs(delta.y) > Mathf.Abs(delta.x)) delta.x = delta.y; delta.y = 0; } Vector2 position = m_Content.anchoredPosition; position += delta * m_ScrollSensitivity; if (m_MovementType == MovementType.Clamped) position += CalculateOffset(position - m_Content.anchoredPosition); SetContentAnchoredPosition(position); UpdateBounds(); } public virtual void OnInitializePotentialDrag(PointerEventData eventData) { m_Velocity = Vector2.zero; } public virtual void OnBeginDrag(PointerEventData eventData) { if (eventData.button != PointerEventData.InputButton.Left) return; if (!IsActive()) return; UpdateBounds(); m_PointerStartLocalCursor = Vector2.zero; RectTransformUtility.ScreenPointToLocalPointInRectangle(viewRect, eventData.position, eventData.pressEventCamera, out m_PointerStartLocalCursor); m_ContentStartPosition = m_Content.anchoredPosition; m_Dragging = true; } public virtual void OnEndDrag(PointerEventData eventData) { if (eventData.button != PointerEventData.InputButton.Left) return; m_Dragging = false; } public virtual void OnDrag(PointerEventData eventData) { if (eventData.button != PointerEventData.InputButton.Left) return; if (!IsActive()) return; Vector2 localCursor; if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(viewRect, eventData.position, eventData.pressEventCamera, out localCursor)) return; UpdateBounds(); var pointerDelta = localCursor - m_PointerStartLocalCursor; Vector2 position = m_ContentStartPosition + pointerDelta; // Offset to get content into place in the view. Vector2 offset = CalculateOffset(position - m_Content.anchoredPosition); position += offset; if (m_MovementType == MovementType.Elastic) { if (offset.x != 0) position.x = position.x - RubberDelta(offset.x, m_ViewBounds.size.x); if (offset.y != 0) position.y = position.y - RubberDelta(offset.y, m_ViewBounds.size.y); } SetContentAnchoredPosition(position); } protected virtual void SetContentAnchoredPosition(Vector2 position) { if (!m_Horizontal) position.x = m_Content.anchoredPosition.x; if (!m_Vertical) position.y = m_Content.anchoredPosition.y; if (position != m_Content.anchoredPosition) { m_Content.anchoredPosition = position; UpdateBounds(); } } protected virtual void LateUpdate() { if (!m_Content) return; EnsureLayoutHasRebuilt(); UpdateBounds(); float deltaTime = Time.unscaledDeltaTime; Vector2 offset = CalculateOffset(Vector2.zero); if (!m_Dragging && (offset != Vector2.zero || m_Velocity != Vector2.zero)) { Vector2 position = m_Content.anchoredPosition; for (int axis = 0; axis < 2; axis++) { // Apply spring physics if movement is elastic and content has an offset from the view. if (m_MovementType == MovementType.Elastic && offset[axis] != 0) { float speed = m_Velocity[axis]; position[axis] = Mathf.SmoothDamp(m_Content.anchoredPosition[axis], m_Content.anchoredPosition[axis] + offset[axis], ref speed, m_Elasticity, Mathf.Infinity, deltaTime); m_Velocity[axis] = speed; } // Else move content according to velocity with deceleration applied. else if (m_Inertia) { m_Velocity[axis] *= Mathf.Pow(m_DecelerationRate, deltaTime); if (Mathf.Abs(m_Velocity[axis]) < 1) m_Velocity[axis] = 0; position[axis] += m_Velocity[axis] * deltaTime; } // If we have neither elaticity or friction, there shouldn't be any velocity. else { m_Velocity[axis] = 0; } } if (m_Velocity != Vector2.zero) { if (m_MovementType == MovementType.Clamped) { offset = CalculateOffset(position - m_Content.anchoredPosition); position += offset; } SetContentAnchoredPosition(position); } } if (m_Dragging && m_Inertia) { Vector3 newVelocity = (m_Content.anchoredPosition - m_PrevPosition) / deltaTime; m_Velocity = Vector3.Lerp(m_Velocity, newVelocity, deltaTime * 10); } if (m_ViewBounds != m_PrevViewBounds || m_ContentBounds != m_PrevContentBounds || m_Content.anchoredPosition != m_PrevPosition) { UpdateScrollbars(offset); m_OnValueChanged.Invoke(normalizedPosition); UpdatePrevData(); } } private void UpdatePrevData() { if (m_Content == null) m_PrevPosition = Vector2.zero; else m_PrevPosition = m_Content.anchoredPosition; m_PrevViewBounds = m_ViewBounds; m_PrevContentBounds = m_ContentBounds; } private void UpdateScrollbars(Vector2 offset) { if (m_HorizontalScrollbar) { m_HorizontalScrollbar.size = Mathf.Clamp01((m_ViewBounds.size.x - Mathf.Abs(offset.x)) / m_ContentBounds.size.x); m_HorizontalScrollbar.value = horizontalNormalizedPosition; } if (m_VerticalScrollbar) { m_VerticalScrollbar.size = Mathf.Clamp01((m_ViewBounds.size.y - Mathf.Abs(offset.y)) / m_ContentBounds.size.y); m_VerticalScrollbar.value = verticalNormalizedPosition; } } public Vector2 normalizedPosition { get { return new Vector2(horizontalNormalizedPosition, verticalNormalizedPosition); } set { SetNormalizedPosition(value.x, 0); SetNormalizedPosition(value.y, 1); } } public float horizontalNormalizedPosition { get { UpdateBounds(); if (m_ContentBounds.size.x <= m_ViewBounds.size.x) return (m_ViewBounds.min.x > m_ContentBounds.min.x) ? 1 : 0; return (m_ViewBounds.min.x - m_ContentBounds.min.x) / (m_ContentBounds.size.x - m_ViewBounds.size.x); } set { SetNormalizedPosition(value, 0); } } public float verticalNormalizedPosition { get { UpdateBounds(); if (m_ContentBounds.size.y <= m_ViewBounds.size.y) return (m_ViewBounds.min.y > m_ContentBounds.min.y) ? 1 : 0; ; return (m_ViewBounds.min.y - m_ContentBounds.min.y) / (m_ContentBounds.size.y - m_ViewBounds.size.y); } set { SetNormalizedPosition(value, 1); } } private void SetHorizontalNormalizedPosition(float value) { SetNormalizedPosition(value, 0); } private void SetVerticalNormalizedPosition(float value) { SetNormalizedPosition(value, 1); } private void SetNormalizedPosition(float value, int axis) { EnsureLayoutHasRebuilt(); UpdateBounds(); // How much the content is larger than the view. float hiddenLength = m_ContentBounds.size[axis] - m_ViewBounds.size[axis]; // Where the position of the lower left corner of the content bounds should be, in the space of the view. float contentBoundsMinPosition = m_ViewBounds.min[axis] - value * hiddenLength; // The new content localPosition, in the space of the view. float newLocalPosition = m_Content.localPosition[axis] + contentBoundsMinPosition - m_ContentBounds.min[axis]; Vector3 localPosition = m_Content.localPosition; if (Mathf.Abs(localPosition[axis] - newLocalPosition) > 0.01f) { localPosition[axis] = newLocalPosition; m_Content.localPosition = localPosition; m_Velocity[axis] = 0; UpdateBounds(); } } private static float RubberDelta(float overStretching, float viewSize) { return (1 - (1 / ((Mathf.Abs(overStretching) * 0.55f / viewSize) + 1))) * viewSize * Mathf.Sign(overStretching); } private void UpdateBounds() { m_ViewBounds = new Bounds(viewRect.rect.center, viewRect.rect.size); m_ContentBounds = GetBounds(); if (m_Content == null) return; // Make sure content bounds are at least as large as view by adding padding if not. // One might think at first that if the content is smaller than the view, scrolling should be allowed. // However, that's not how scroll views normally work. // Scrolling is *only* possible when content is *larger* than view. // We use the pivot of the content rect to decide in which directions the content bounds should be expanded. // E.g. if pivot is at top, bounds are expanded downwards. // This also works nicely when ContentSizeFitter is used on the content. Vector3 contentSize = m_ContentBounds.size; Vector3 contentPos = m_ContentBounds.center; Vector3 excess = m_ViewBounds.size - contentSize; if (excess.x > 0) { contentPos.x -= excess.x * (m_Content.pivot.x - 0.5f); contentSize.x = m_ViewBounds.size.x; } if (excess.y > 0) { contentPos.y -= excess.y * (m_Content.pivot.y - 0.5f); contentSize.y = m_ViewBounds.size.y; } m_ContentBounds.size = contentSize; m_ContentBounds.center = contentPos; } private readonly Vector3[] m_Corners = new Vector3[4]; private Bounds GetBounds() { if (m_Content == null) return new Bounds(); var vMin = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); var vMax = new Vector3(float.MinValue, float.MinValue, float.MinValue); var toLocal = viewRect.worldToLocalMatrix; m_Content.GetWorldCorners(m_Corners); for (int j = 0; j < 4; j++) { Vector3 v = toLocal.MultiplyPoint3x4(m_Corners[j]); vMin = Vector3.Min(v, vMin); vMax = Vector3.Max(v, vMax); } var bounds = new Bounds(vMin, Vector3.zero); bounds.Encapsulate(vMax); return bounds; } private Vector2 CalculateOffset(Vector2 delta) { Vector2 offset = Vector2.zero; if (m_MovementType == MovementType.Unrestricted) return offset; Vector2 min = m_ContentBounds.min; Vector2 max = m_ContentBounds.max; if (m_Horizontal) { min.x += delta.x; max.x += delta.x; if (min.x > m_ViewBounds.min.x) offset.x = m_ViewBounds.min.x - min.x; else if (max.x < m_ViewBounds.max.x) offset.x = m_ViewBounds.max.x - max.x; } if (m_Vertical) { min.y += delta.y; max.y += delta.y; if (max.y < m_ViewBounds.max.y) offset.y = m_ViewBounds.max.y - max.y; else if (min.y > m_ViewBounds.min.y) offset.y = m_ViewBounds.min.y - min.y; } return offset; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.Reflection; namespace System.ComponentModel.DataAnnotations { /// <summary> /// Base class for all validation attributes. /// <para>Override <see cref="IsValid(object, ValidationContext)" /> to implement validation logic.</para> /// </summary> /// <remarks> /// The properties <see cref="ErrorMessageResourceType" /> and <see cref="ErrorMessageResourceName" /> are used to /// provide /// a localized error message, but they cannot be set if <see cref="ErrorMessage" /> is also used to provide a /// non-localized /// error message. /// </remarks> public abstract class ValidationAttribute : Attribute { #region Member Fields private string _errorMessage; private Func<string> _errorMessageResourceAccessor; private string _errorMessageResourceName; private Type _errorMessageResourceType; private volatile bool _hasBaseIsValid; private string _defaultErrorMessage; #endregion #region All Constructors /// <summary> /// Default constructor for any validation attribute. /// </summary> /// <remarks> /// This constructor chooses a very generic validation error message. /// Developers subclassing ValidationAttribute should use other constructors /// or supply a better message. /// </remarks> protected ValidationAttribute() : this(() => SR.ValidationAttribute_ValidationError) { } /// <summary> /// Constructor that accepts a fixed validation error message. /// </summary> /// <param name="errorMessage">A non-localized error message to use in <see cref="ErrorMessageString" />.</param> protected ValidationAttribute(string errorMessage) : this(() => errorMessage) { } /// <summary> /// Allows for providing a resource accessor function that will be used by the <see cref="ErrorMessageString" /> /// property to retrieve the error message. An example would be to have something like /// CustomAttribute() : base( () =&gt; MyResources.MyErrorMessage ) {}. /// </summary> /// <param name="errorMessageAccessor">The <see cref="Func{T}" /> that will return an error message.</param> protected ValidationAttribute(Func<string> errorMessageAccessor) { // If null, will later be exposed as lack of error message to be able to construct accessor _errorMessageResourceAccessor = errorMessageAccessor; } #endregion #region Internal Properties /// <summary> /// Sets the default error message string. /// This message will be used if the user has not set <see cref="ErrorMessage"/> /// or the <see cref="ErrorMessageResourceType"/> and <see cref="ErrorMessageResourceName"/> pair. /// This property was added after the public contract for DataAnnotations was created. /// It is internal to avoid changing the DataAnnotations contract. /// </summary> internal string DefaultErrorMessage { set { _defaultErrorMessage = value; _errorMessageResourceAccessor = null; CustomErrorMessageSet = true; } } #endregion #region Protected Properties /// <summary> /// Gets the localized error message string, coming either from <see cref="ErrorMessage" />, or from evaluating the /// <see cref="ErrorMessageResourceType" /> and <see cref="ErrorMessageResourceName" /> pair. /// </summary> protected string ErrorMessageString { get { SetupResourceAccessor(); return _errorMessageResourceAccessor(); } } /// <summary> /// A flag indicating whether a developer has customized the attribute's error message by setting any one of /// ErrorMessage, ErrorMessageResourceName, ErrorMessageResourceType or DefaultErrorMessage. /// </summary> internal bool CustomErrorMessageSet { get; private set; } /// <summary> /// A flag indicating that the attribute requires a non-null /// <see cref="ValidationContext" /> to perform validation. /// Base class returns false. Override in child classes as appropriate. /// </summary> public virtual bool RequiresValidationContext => false; #endregion #region Public Properties /// <summary> /// Gets or sets the explicit error message string. /// </summary> /// <value> /// This property is intended to be used for non-localizable error messages. Use /// <see cref="ErrorMessageResourceType" /> and <see cref="ErrorMessageResourceName" /> for localizable error messages. /// </value> public string ErrorMessage { // If _errorMessage is not set, return the default. This is done to preserve // behavior prior to the fix where ErrorMessage showed the non-null message to use. get => _errorMessage ?? _defaultErrorMessage; set { _errorMessage = value; _errorMessageResourceAccessor = null; CustomErrorMessageSet = true; // Explicitly setting ErrorMessage also sets DefaultErrorMessage if null. // This prevents subsequent read of ErrorMessage from returning default. if (value == null) { _defaultErrorMessage = null; } } } /// <summary> /// Gets or sets the resource name (property name) to use as the key for lookups on the resource type. /// </summary> /// <value> /// Use this property to set the name of the property within <see cref="ErrorMessageResourceType" /> /// that will provide a localized error message. Use <see cref="ErrorMessage" /> for non-localized error messages. /// </value> public string ErrorMessageResourceName { get => _errorMessageResourceName; set { _errorMessageResourceName = value; _errorMessageResourceAccessor = null; CustomErrorMessageSet = true; } } /// <summary> /// Gets or sets the resource type to use for error message lookups. /// </summary> /// <value> /// Use this property only in conjunction with <see cref="ErrorMessageResourceName" />. They are /// used together to retrieve localized error messages at runtime. /// <para> /// Use <see cref="ErrorMessage" /> instead of this pair if error messages are not localized. /// </para> /// </value> public Type ErrorMessageResourceType { get => _errorMessageResourceType; set { _errorMessageResourceType = value; _errorMessageResourceAccessor = null; CustomErrorMessageSet = true; } } #endregion #region Private Methods /// <summary> /// Validates the configuration of this attribute and sets up the appropriate error string accessor. /// This method bypasses all verification once the ResourceAccessor has been set. /// </summary> /// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception> private void SetupResourceAccessor() { if (_errorMessageResourceAccessor == null) { string localErrorMessage = ErrorMessage; bool resourceNameSet = !string.IsNullOrEmpty(_errorMessageResourceName); bool errorMessageSet = !string.IsNullOrEmpty(_errorMessage); bool resourceTypeSet = _errorMessageResourceType != null; bool defaultMessageSet = !string.IsNullOrEmpty(_defaultErrorMessage); // The following combinations are illegal and throw InvalidOperationException: // 1) Both ErrorMessage and ErrorMessageResourceName are set, or // 2) None of ErrorMessage, ErrorMessageResourceName, and DefaultErrorMessage are set. if ((resourceNameSet && errorMessageSet) || !(resourceNameSet || errorMessageSet || defaultMessageSet)) { throw new InvalidOperationException( SR.ValidationAttribute_Cannot_Set_ErrorMessage_And_Resource); } // Must set both or neither of ErrorMessageResourceType and ErrorMessageResourceName if (resourceTypeSet != resourceNameSet) { throw new InvalidOperationException( SR.ValidationAttribute_NeedBothResourceTypeAndResourceName); } // If set resource type (and we know resource name too), then go setup the accessor if (resourceNameSet) { SetResourceAccessorByPropertyLookup(); } else { // Here if not using resource type/name -- the accessor is just the error message string, // which we know is not empty to have gotten this far. _errorMessageResourceAccessor = delegate { // We captured error message to local in case it changes before accessor runs return localErrorMessage; }; } } } private void SetResourceAccessorByPropertyLookup() { Debug.Assert(_errorMessageResourceType != null); Debug.Assert(!string.IsNullOrEmpty(_errorMessageResourceName)); var property = _errorMessageResourceType .GetTypeInfo().GetDeclaredProperty(_errorMessageResourceName); if (property != null && !ValidationAttributeStore.IsStatic(property)) { property = null; } if (property != null) { var propertyGetter = property.GetMethod; // We only support internal and public properties if (propertyGetter == null || (!propertyGetter.IsAssembly && !propertyGetter.IsPublic)) { // Set the property to null so the exception is thrown as if the property wasn't found property = null; } } if (property == null) { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, SR.ValidationAttribute_ResourceTypeDoesNotHaveProperty, _errorMessageResourceType.FullName, _errorMessageResourceName)); } if (property.PropertyType != typeof(string)) { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, SR.ValidationAttribute_ResourcePropertyNotStringType, property.Name, _errorMessageResourceType.FullName)); } _errorMessageResourceAccessor = delegate { return (string)property.GetValue(null, null); }; } #endregion #region Protected & Public Methods /// <summary> /// Formats the error message to present to the user. /// </summary> /// <remarks> /// The error message will be re-evaluated every time this function is called. /// It applies the <paramref name="name" /> (for example, the name of a field) to the formated error message, resulting /// in something like "The field 'name' has an incorrect value". /// <para> /// Derived classes can override this method to customize how errors are generated. /// </para> /// <para> /// The base class implementation will use <see cref="ErrorMessageString" /> to obtain a localized /// error message from properties within the current attribute. If those have not been set, a generic /// error message will be provided. /// </para> /// </remarks> /// <param name="name">The user-visible name to include in the formatted message.</param> /// <returns>The localized string describing the validation error</returns> /// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception> public virtual string FormatErrorMessage(string name) => string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name); /// <summary> /// Gets the value indicating whether or not the specified <paramref name="value" /> is valid /// with respect to the current validation attribute. /// <para> /// Derived classes should not override this method as it is only available for backwards compatibility. /// Instead, implement <see cref="IsValid(object, ValidationContext)" />. /// </para> /// </summary> /// <remarks> /// The preferred public entry point for clients requesting validation is the <see cref="GetValidationResult" /> /// method. /// </remarks> /// <param name="value">The value to validate</param> /// <returns><c>true</c> if the <paramref name="value" /> is acceptable, <c>false</c> if it is not acceptable</returns> /// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception> /// <exception cref="NotImplementedException"> /// is thrown when neither overload of IsValid has been implemented /// by a derived class. /// </exception> public virtual bool IsValid(object value) { if (!_hasBaseIsValid) { // track that this method overload has not been overridden. _hasBaseIsValid = true; } // call overridden method. return IsValid(value, null) == ValidationResult.Success; } /// <summary> /// Protected virtual method to override and implement validation logic. /// <para> /// Derived classes should override this method instead of <see cref="IsValid(object)" />, which is deprecated. /// </para> /// </summary> /// <param name="value">The value to validate.</param> /// <param name="validationContext"> /// A <see cref="ValidationContext" /> instance that provides /// context about the validation operation, such as the object and member being validated. /// </param> /// <returns> /// When validation is valid, <see cref="ValidationResult.Success" />. /// <para> /// When validation is invalid, an instance of <see cref="ValidationResult" />. /// </para> /// </returns> /// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception> /// <exception cref="NotImplementedException"> /// is thrown when <see cref="IsValid(object, ValidationContext)" /> /// has not been implemented by a derived class. /// </exception> protected virtual ValidationResult IsValid(object value, ValidationContext validationContext) { if (_hasBaseIsValid) { // this means neither of the IsValid methods has been overridden, throw. throw NotImplemented.ByDesignWithMessage( SR.ValidationAttribute_IsValid_NotImplemented); } var result = ValidationResult.Success; // call overridden method. if (!IsValid(value)) { string[] memberNames = validationContext.MemberName != null ? new string[] { validationContext.MemberName } : null; result = new ValidationResult(FormatErrorMessage(validationContext.DisplayName), memberNames); } return result; } /// <summary> /// Tests whether the given <paramref name="value" /> is valid with respect to the current /// validation attribute without throwing a <see cref="ValidationException" /> /// </summary> /// <remarks> /// If this method returns <see cref="ValidationResult.Success" />, then validation was successful, otherwise /// an instance of <see cref="ValidationResult" /> will be returned with a guaranteed non-null /// <see cref="ValidationResult.ErrorMessage" />. /// </remarks> /// <param name="value">The value to validate</param> /// <param name="validationContext"> /// A <see cref="ValidationContext" /> instance that provides /// context about the validation operation, such as the object and member being validated. /// </param> /// <returns> /// When validation is valid, <see cref="ValidationResult.Success" />. /// <para> /// When validation is invalid, an instance of <see cref="ValidationResult" />. /// </para> /// </returns> /// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception> /// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception> /// <exception cref="NotImplementedException"> /// is thrown when <see cref="IsValid(object, ValidationContext)" /> /// has not been implemented by a derived class. /// </exception> public ValidationResult GetValidationResult(object value, ValidationContext validationContext) { if (validationContext == null) { throw new ArgumentNullException(nameof(validationContext)); } var result = IsValid(value, validationContext); // If validation fails, we want to ensure we have a ValidationResult that guarantees it has an ErrorMessage if (result != null) { if (string.IsNullOrEmpty(result.ErrorMessage)) { var errorMessage = FormatErrorMessage(validationContext.DisplayName); result = new ValidationResult(errorMessage, result.MemberNames); } } return result; } /// <summary> /// Validates the specified <paramref name="value" /> and throws <see cref="ValidationException" /> if it is not. /// <para> /// The overloaded <see cref="Validate(object, ValidationContext)" /> is the recommended entry point as it /// can provide additional context to the <see cref="ValidationAttribute" /> being validated. /// </para> /// </summary> /// <remarks> /// This base method invokes the <see cref="IsValid(object)" /> method to determine whether or not the /// <paramref name="value" /> is acceptable. If <see cref="IsValid(object)" /> returns <c>false</c>, this base /// method will invoke the <see cref="FormatErrorMessage" /> to obtain a localized message describing /// the problem, and it will throw a <see cref="ValidationException" /> /// </remarks> /// <param name="value">The value to validate</param> /// <param name="name">The string to be included in the validation error message if <paramref name="value" /> is not valid</param> /// <exception cref="ValidationException"> /// is thrown if <see cref="IsValid(object)" /> returns <c>false</c>. /// </exception> /// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception> public void Validate(object value, string name) { if (!IsValid(value)) { throw new ValidationException(FormatErrorMessage(name), this, value); } } /// <summary> /// Validates the specified <paramref name="value" /> and throws <see cref="ValidationException" /> if it is not. /// </summary> /// <remarks> /// This method invokes the <see cref="IsValid(object, ValidationContext)" /> method /// to determine whether or not the <paramref name="value" /> is acceptable given the /// <paramref name="validationContext" />. /// If that method doesn't return <see cref="ValidationResult.Success" />, this base method will throw /// a <see cref="ValidationException" /> containing the <see cref="ValidationResult" /> describing the problem. /// </remarks> /// <param name="value">The value to validate</param> /// <param name="validationContext">Additional context that may be used for validation. It cannot be null.</param> /// <exception cref="ValidationException"> /// is thrown if <see cref="IsValid(object, ValidationContext)" /> /// doesn't return <see cref="ValidationResult.Success" />. /// </exception> /// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception> /// <exception cref="NotImplementedException"> /// is thrown when <see cref="IsValid(object, ValidationContext)" /> /// has not been implemented by a derived class. /// </exception> public void Validate(object value, ValidationContext validationContext) { if (validationContext == null) { throw new ArgumentNullException(nameof(validationContext)); } ValidationResult result = GetValidationResult(value, validationContext); if (result != null) { // Convenience -- if implementation did not fill in an error message, throw new ValidationException(result, this, value); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.Net; using System.Net.Http; using System.Net.Security; using System.Runtime; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel.Security; using System.ServiceModel.Security.Tokens; using System.Threading; using System.Threading.Tasks; namespace System.ServiceModel.Channels { internal static class TransportSecurityHelpers { // used for HTTP (from HttpChannelUtilities.GetCredential) public static async Task<NetworkCredential> GetSspiCredentialAsync(SecurityTokenProviderContainer tokenProvider, OutWrapper<TokenImpersonationLevel> impersonationLevelWrapper, OutWrapper<AuthenticationLevel> authenticationLevelWrapper, CancellationToken cancellationToken) { OutWrapper<bool> dummyExtractWindowsGroupClaimsWrapper = new OutWrapper<bool>(); OutWrapper<bool> allowNtlmWrapper = new OutWrapper<bool>(); NetworkCredential result = await GetSspiCredentialAsync(tokenProvider.TokenProvider as SspiSecurityTokenProvider, dummyExtractWindowsGroupClaimsWrapper, impersonationLevelWrapper, allowNtlmWrapper, cancellationToken); authenticationLevelWrapper.Value = allowNtlmWrapper.Value ? AuthenticationLevel.MutualAuthRequested : AuthenticationLevel.MutualAuthRequired; return result; } // used by client WindowsStream security (from InitiateUpgrade) public static Task<NetworkCredential> GetSspiCredentialAsync(SspiSecurityTokenProvider tokenProvider, OutWrapper<TokenImpersonationLevel> impersonationLevel, OutWrapper<bool> allowNtlm, CancellationToken cancellationToken) { OutWrapper<bool> dummyExtractWindowsGroupClaimsWrapper = new OutWrapper<bool>(); return GetSspiCredentialAsync(tokenProvider, dummyExtractWindowsGroupClaimsWrapper, impersonationLevel, allowNtlm, cancellationToken); } // used by server WindowsStream security (from Open) public static NetworkCredential GetSspiCredential(SecurityTokenManager credentialProvider, SecurityTokenRequirement sspiTokenRequirement, TimeSpan timeout, out bool extractGroupsForWindowsAccounts) { extractGroupsForWindowsAccounts = TransportDefaults.ExtractGroupsForWindowsAccounts; NetworkCredential result = null; if (credentialProvider != null) { SecurityTokenProvider tokenProvider = credentialProvider.CreateSecurityTokenProvider(sspiTokenRequirement); if (tokenProvider != null) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); SecurityUtils.OpenTokenProviderIfRequired(tokenProvider, timeoutHelper.RemainingTime()); bool success = false; try { OutWrapper<TokenImpersonationLevel> dummyImpersonationLevelWrapper = new OutWrapper<TokenImpersonationLevel>(); OutWrapper<bool> dummyAllowNtlmWrapper = new OutWrapper<bool>(); OutWrapper<bool> extractGroupsForWindowsAccountsWrapper = new OutWrapper<bool>(); result = GetSspiCredentialAsync((SspiSecurityTokenProvider)tokenProvider, extractGroupsForWindowsAccountsWrapper, dummyImpersonationLevelWrapper, dummyAllowNtlmWrapper, timeoutHelper.GetCancellationToken()).GetAwaiter().GetResult(); success = true; } finally { if (!success) { SecurityUtils.AbortTokenProviderIfRequired(tokenProvider); } } SecurityUtils.CloseTokenProviderIfRequired(tokenProvider, timeoutHelper.RemainingTime()); } } return result; } // core Cred lookup code public static async Task<NetworkCredential> GetSspiCredentialAsync(SspiSecurityTokenProvider tokenProvider, OutWrapper<bool> extractGroupsForWindowsAccounts, OutWrapper<TokenImpersonationLevel> impersonationLevelWrapper, OutWrapper<bool> allowNtlmWrapper, CancellationToken cancellationToken) { NetworkCredential credential = null; extractGroupsForWindowsAccounts.Value = TransportDefaults.ExtractGroupsForWindowsAccounts; impersonationLevelWrapper.Value = TokenImpersonationLevel.Identification; allowNtlmWrapper.Value = ConnectionOrientedTransportDefaults.AllowNtlm; if (tokenProvider != null) { SspiSecurityToken token = await TransportSecurityHelpers.GetTokenAsync<SspiSecurityToken>(tokenProvider, cancellationToken); if (token != null) { extractGroupsForWindowsAccounts.Value = token.ExtractGroupsForWindowsAccounts; impersonationLevelWrapper.Value = token.ImpersonationLevel; allowNtlmWrapper.Value = token.AllowNtlm; if (token.NetworkCredential != null) { credential = token.NetworkCredential; SecurityUtils.FixNetworkCredential(ref credential); } } } // Initialize to the default value if no token provided. A partial trust app should not have access to the // default network credentials but should be able to provide credentials. The DefaultNetworkCredentials // getter will throw under partial trust. if (credential == null) { credential = CredentialCache.DefaultNetworkCredentials; } return credential; } internal static SecurityTokenRequirement CreateSspiTokenRequirement(string transportScheme, Uri listenUri) { RecipientServiceModelSecurityTokenRequirement tokenRequirement = new RecipientServiceModelSecurityTokenRequirement(); tokenRequirement.TransportScheme = transportScheme; tokenRequirement.RequireCryptographicToken = false; tokenRequirement.ListenUri = listenUri; tokenRequirement.TokenType = ServiceModelSecurityTokenTypes.SspiCredential; return tokenRequirement; } internal static SecurityTokenRequirement CreateSspiTokenRequirement(EndpointAddress target, Uri via, string transportScheme) { InitiatorServiceModelSecurityTokenRequirement sspiTokenRequirement = new InitiatorServiceModelSecurityTokenRequirement(); sspiTokenRequirement.TokenType = ServiceModelSecurityTokenTypes.SspiCredential; sspiTokenRequirement.RequireCryptographicToken = false; sspiTokenRequirement.TransportScheme = transportScheme; sspiTokenRequirement.TargetAddress = target; sspiTokenRequirement.Via = via; return sspiTokenRequirement; } public static SspiSecurityTokenProvider GetSspiTokenProvider( SecurityTokenManager tokenManager, EndpointAddress target, Uri via, string transportScheme, AuthenticationSchemes authenticationScheme, ChannelParameterCollection channelParameters) { if (tokenManager != null) { SecurityTokenRequirement sspiRequirement = CreateSspiTokenRequirement(target, via, transportScheme); sspiRequirement.Properties[ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty] = authenticationScheme; if (channelParameters != null) { sspiRequirement.Properties[ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty] = channelParameters; } SspiSecurityTokenProvider tokenProvider = tokenManager.CreateSecurityTokenProvider(sspiRequirement) as SspiSecurityTokenProvider; return tokenProvider; } return null; } public static SspiSecurityTokenProvider GetSspiTokenProvider( SecurityTokenManager tokenManager, EndpointAddress target, Uri via, string transportScheme, out IdentityVerifier identityVerifier) { identityVerifier = null; if (tokenManager != null) { SspiSecurityTokenProvider tokenProvider = tokenManager.CreateSecurityTokenProvider(CreateSspiTokenRequirement(target, via, transportScheme)) as SspiSecurityTokenProvider; if (tokenProvider != null) { identityVerifier = IdentityVerifier.CreateDefault(); } return tokenProvider; } return null; } public static SecurityTokenProvider GetDigestTokenProvider( SecurityTokenManager tokenManager, EndpointAddress target, Uri via, string transportScheme, AuthenticationSchemes authenticationScheme, ChannelParameterCollection channelParameters) { if (tokenManager != null) { InitiatorServiceModelSecurityTokenRequirement digestTokenRequirement = new InitiatorServiceModelSecurityTokenRequirement(); digestTokenRequirement.TokenType = ServiceModelSecurityTokenTypes.SspiCredential; digestTokenRequirement.TargetAddress = target; digestTokenRequirement.Via = via; digestTokenRequirement.RequireCryptographicToken = false; digestTokenRequirement.TransportScheme = transportScheme; digestTokenRequirement.Properties[ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty] = authenticationScheme; if (channelParameters != null) { digestTokenRequirement.Properties[ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty] = channelParameters; } return tokenManager.CreateSecurityTokenProvider(digestTokenRequirement) as SspiSecurityTokenProvider; } return null; } public static SecurityTokenProvider GetCertificateTokenProvider( SecurityTokenManager tokenManager, EndpointAddress target, Uri via, string transportScheme, ChannelParameterCollection channelParameters) { if (tokenManager != null) { InitiatorServiceModelSecurityTokenRequirement certificateTokenRequirement = new InitiatorServiceModelSecurityTokenRequirement(); certificateTokenRequirement.TokenType = SecurityTokenTypes.X509Certificate; certificateTokenRequirement.TargetAddress = target; certificateTokenRequirement.Via = via; certificateTokenRequirement.RequireCryptographicToken = false; certificateTokenRequirement.TransportScheme = transportScheme; if (channelParameters != null) { certificateTokenRequirement.Properties[ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty] = channelParameters; } return tokenManager.CreateSecurityTokenProvider(certificateTokenRequirement); } return null; } private static async Task<T> GetTokenAsync<T>(SecurityTokenProvider tokenProvider, CancellationToken cancellationToken) where T : SecurityToken { SecurityToken result = await tokenProvider.GetTokenAsync(cancellationToken); if ((result != null) && !(result is T)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format( SR.InvalidTokenProvided, tokenProvider.GetType(), typeof(T)))); } return result as T; } public static async Task<NetworkCredential> GetUserNameCredentialAsync(SecurityTokenProviderContainer tokenProvider, CancellationToken cancellationToken) { NetworkCredential result = null; if (tokenProvider != null && tokenProvider.TokenProvider != null) { UserNameSecurityToken token = await GetTokenAsync<UserNameSecurityToken>(tokenProvider.TokenProvider, cancellationToken); if (token != null) { result = new NetworkCredential(token.UserName, token.Password); } } if (result == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.NoUserNameTokenProvided)); } return result; } public static SecurityTokenProvider GetUserNameTokenProvider( SecurityTokenManager tokenManager, EndpointAddress target, Uri via, string transportScheme, AuthenticationSchemes authenticationScheme, ChannelParameterCollection channelParameters) { SecurityTokenProvider result = null; if (tokenManager != null) { SecurityTokenRequirement usernameRequirement = CreateUserNameTokenRequirement(target, via, transportScheme); usernameRequirement.Properties[ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty] = authenticationScheme; if (channelParameters != null) { usernameRequirement.Properties[ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty] = channelParameters; } result = tokenManager.CreateSecurityTokenProvider(usernameRequirement); } return result; } public static Uri GetListenUri(Uri baseAddress, string relativeAddress) { Uri fullUri = baseAddress; // Ensure that baseAddress Path does end with a slash if we have a relative address if (!string.IsNullOrEmpty(relativeAddress)) { if (!baseAddress.AbsolutePath.EndsWith("/", StringComparison.Ordinal)) { UriBuilder uriBuilder = new UriBuilder(baseAddress); FixIpv6Hostname(uriBuilder, baseAddress); uriBuilder.Path = uriBuilder.Path + "/"; baseAddress = uriBuilder.Uri; } fullUri = new Uri(baseAddress, relativeAddress); } return fullUri; } private static InitiatorServiceModelSecurityTokenRequirement CreateUserNameTokenRequirement( EndpointAddress target, Uri via, string transportScheme) { InitiatorServiceModelSecurityTokenRequirement usernameRequirement = new InitiatorServiceModelSecurityTokenRequirement(); usernameRequirement.RequireCryptographicToken = false; usernameRequirement.TokenType = SecurityTokenTypes.UserName; usernameRequirement.TargetAddress = target; usernameRequirement.Via = via; usernameRequirement.TransportScheme = transportScheme; return usernameRequirement; } // Originally: TcpChannelListener.FixIpv6Hostname private static void FixIpv6Hostname(UriBuilder uriBuilder, Uri originalUri) { if (originalUri.HostNameType == UriHostNameType.IPv6) { string ipv6Host = originalUri.DnsSafeHost; uriBuilder.Host = string.Concat("[", ipv6Host, "]"); } } } internal static class HttpTransportSecurityHelpers { private static Dictionary<string, int> s_targetNameCounter = new Dictionary<string, int>(); public static bool AddIdentityMapping(Uri via, EndpointAddress target) { // On Desktop, we do mutual auth when the EndpointAddress has an identity. We need // support from HttpClient before any functionality can be added here. return false; } public static void RemoveIdentityMapping(Uri via, EndpointAddress target, bool validateState) { // On Desktop, we do mutual auth when the EndpointAddress has an identity. We need // support from HttpClient before any functionality can be added here. } private static Dictionary<HttpRequestMessage, string> s_serverCertMap = new Dictionary<HttpRequestMessage, string>(); public static void AddServerCertMapping(HttpRequestMessage request, EndpointAddress to) { Fx.Assert(request.RequestUri.Scheme == UriEx.UriSchemeHttps, "Wrong URI scheme for AddServerCertMapping()."); X509CertificateEndpointIdentity remoteCertificateIdentity = to.Identity as X509CertificateEndpointIdentity; if (remoteCertificateIdentity != null) { // The following condition should have been validated when the channel was created. Fx.Assert(remoteCertificateIdentity.Certificates.Count <= 1, "HTTPS server certificate identity contains multiple certificates"); AddServerCertMapping(request, remoteCertificateIdentity.Certificates[0].Thumbprint); } } private static void AddServerCertMapping(HttpRequestMessage request, string thumbprint) { lock (s_serverCertMap) { s_serverCertMap.Add(request, thumbprint); } } public static void SetServerCertificateValidationCallback(HttpClientHandler handler) { handler.ServerCertificateCustomValidationCallback = ChainValidator(handler.ServerCertificateCustomValidationCallback); } private static Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ChainValidator(Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> previousValidator) { if (previousValidator == null) { return OnValidateServerCertificate; } Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> chained = (request, certificate, chain, sslPolicyErrors) => { bool valid = OnValidateServerCertificate(request, certificate, chain, sslPolicyErrors); if (valid) { return previousValidator(request, certificate, chain, sslPolicyErrors); } return false; }; return chained; } private static bool OnValidateServerCertificate(HttpRequestMessage request, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (request != null) { string thumbprint; lock (s_serverCertMap) { s_serverCertMap.TryGetValue(request, out thumbprint); } if (thumbprint != null) { try { ValidateServerCertificate(certificate, thumbprint); } catch (SecurityNegotiationException) { return false; } } } return (sslPolicyErrors == SslPolicyErrors.None); } public static void RemoveServerCertMapping(HttpRequestMessage request) { lock (s_serverCertMap) { s_serverCertMap.Remove(request); } } private static void ValidateServerCertificate(X509Certificate2 certificate, string thumbprint) { string certHashString = certificate.Thumbprint; if (!thumbprint.Equals(certHashString)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityNegotiationException(SR.Format(SR.HttpsServerCertThumbprintMismatch, certificate.Subject, certHashString, thumbprint))); } } } internal static class AuthenticationLevelHelper { internal static string ToString(AuthenticationLevel authenticationLevel) { if (authenticationLevel == AuthenticationLevel.MutualAuthRequested) { return "mutualAuthRequested"; } if (authenticationLevel == AuthenticationLevel.MutualAuthRequired) { return "mutualAuthRequired"; } if (authenticationLevel == AuthenticationLevel.None) { return "none"; } Fx.Assert("unknown authentication level"); return authenticationLevel.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using Newtonsoft.Json; using DocuSign.eSign.Api; using DocuSign.eSign.Model; using DocuSign.eSign.Client; namespace TestProj { class CoreRecipes { // Integrator Key (aka API key) is needed to authenticate your API calls. This is an application-wide key private string INTEGRATOR_KEY = "[INTEGRATOR_KEY]"; ////////////////////////////////////////////////////////// // Main() ////////////////////////////////////////////////////////// static void Main(string[] args) { CoreRecipes recipes = new CoreRecipes(); //*** TEST 1 - Request Signature (on local document) EnvelopeSummary envSummary = recipes.requestSignatureOnDocumentTest(); //*** TEST 2 - Request Signature (from Template) //EnvelopeSummary envSummary = recipes.requestSignatureFromTemplateTest(); //*** TEST 3 - Get Envelope Information //Envelope env = recipes.getEnvelopeInformationTest(); //*** TEST 4 - Get Recipient Information //Recipients recips = recipes.listRecipientsTest(); //*** TEST 5 - List Envelopes //EnvelopesInformation envelopes = recipes.listEnvelopesTest(); //*** TEST 6 - Download Envelope Documents //recipes.listDocumentsAndDownloadTest(); //*** TEST 7 - Embedded Sending //ViewUrl senderView = recipes.createEmbeddedSendingViewTest(); //*** TEST 8 - Embedded Signing //ViewUrl recipientView = recipes.createEmbeddedSigningViewTest(); //*** TEST 9 - Embedded DocuSign Console //ViewUrl consoleView = recipes.createEmbeddedConsoleViewTest(); Console.Read(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public EnvelopeSummary requestSignatureOnDocumentTest() { // Enter your DocuSign credentials below. Note: You only need a DocuSign account to SEND documents, // signing is always free and signers do not need an account. string username = "[EMAIL]"; string password = "[PASSWORD]"; // Enter recipient (signer) name and email address string recipientName = "[RECIPIENT_NAME]"; string recipientEmail = "[RECIPIENT_EMAIL]"; // the document (file) we want signed const string SignTest1File = @"[PATH/TO/DOCUMENT/TEST.PDF]"; // instantiate api client with appropriate environment (for production change to www.docusign.net/restapi) configureApiClient("https://demo.docusign.net/restapi"); //=========================================================== // Step 1: Login() //=========================================================== // call the Login() API which sets the user's baseUrl and returns their accountId string accountId = loginApi(username, password); //=========================================================== // Step 2: Signature Request (AKA create & send Envelope) //=========================================================== // Read a file from disk to use as a document. byte[] fileBytes = File.ReadAllBytes(SignTest1File); EnvelopeDefinition envDef = new EnvelopeDefinition(); envDef.EmailSubject = "[DocuSign C# SDK] - Please sign this doc"; // Add a document to the envelope Document doc = new Document(); doc.DocumentBase64 = System.Convert.ToBase64String(fileBytes); doc.Name = "TestFile.pdf"; doc.DocumentId = "1"; envDef.Documents = new List<Document>(); envDef.Documents.Add(doc); // Add a recipient to sign the documeent Signer signer = new Signer(); signer.Email = recipientEmail; signer.Name = recipientName; signer.RecipientId = "1"; // Create a |SignHere| tab somewhere on the document for the recipient to sign signer.Tabs = new Tabs(); signer.Tabs.SignHereTabs = new List<SignHere>(); SignHere signHere = new SignHere(); signHere.DocumentId = "1"; signHere.PageNumber = "1"; signHere.RecipientId = "1"; signHere.XPosition = "100"; signHere.YPosition = "100"; signer.Tabs.SignHereTabs.Add(signHere); envDef.Recipients = new Recipients(); envDef.Recipients.Signers = new List<Signer>(); envDef.Recipients.Signers.Add(signer); // set envelope status to "sent" to immediately send the signature request envDef.Status = "sent"; // |EnvelopesApi| contains methods related to creating and sending Envelopes (aka signature requests) EnvelopesApi envelopesApi = new EnvelopesApi(); EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef); // print the JSON response Console.WriteLine("EnvelopeSummary:\n{0}", JsonConvert.SerializeObject(envelopeSummary)); return envelopeSummary; } // end requestSignatureTest() //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public EnvelopeSummary requestSignatureFromTemplateTest() { // Enter your DocuSign credentials below. Note: You only need a DocuSign account to SEND documents, // signing is always free and signers do not need an account. string username = "[EMAIL]"; string password = "[PASSWORD]"; // Enter recipient (signer) name and email address string recipientName = "[RECIPIENT_NAME]"; string recipientEmail = "[RECIPIENT_EMAIL]"; // the document (file) we want signed string templateId = "[TEMPLATE_ID]"; string templateRoleName = "[TEMPLATE_ROLE_NAME]"; // instantiate api client with appropriate environment (for production change to www.docusign.net/restapi) configureApiClient("https://demo.docusign.net/restapi"); //=========================================================== // Step 1: Login() //=========================================================== // call the Login() API which sets the user's baseUrl and returns their accountId string accountId = loginApi(username, password); //=========================================================== // Step 2: Signature Request from Template //=========================================================== EnvelopeDefinition envDef = new EnvelopeDefinition(); envDef.EmailSubject = "[DocuSign C# SDK] - Please sign this doc"; // assign recipient to template role by setting name, email, and role name. Note that the // template role name must match the placeholder role name saved in your account template. TemplateRole tRole = new TemplateRole(); tRole.Email = recipientEmail; tRole.Name = recipientName; tRole.RoleName = templateRoleName; List<TemplateRole> rolesList = new List<TemplateRole>() { tRole }; // add the role to the envelope and assign valid templateId from your account envDef.TemplateRoles = rolesList; envDef.TemplateId = templateId; // set envelope status to "sent" to immediately send the signature request envDef.Status = "sent"; // |EnvelopesApi| contains methods related to creating and sending Envelopes (aka signature requests) EnvelopesApi envelopesApi = new EnvelopesApi(); EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef); // print the JSON response Console.WriteLine("EnvelopeSummary:\n{0}", JsonConvert.SerializeObject(envelopeSummary)); return envelopeSummary; } // end requestSignatureFromTemplateTest() //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public Envelope getEnvelopeInformationTest() { // Enter your DocuSign credentials below. Note: You only need a DocuSign account to SEND documents, // signing is always free and signers do not need an account. string username = "[EMAIL]"; string password = "[PASSWORD]"; // provide a valid envelope ID from your account. string envelopeId = "[ENVELOPE_ID]]"; // instantiate api client with appropriate environment (for production change to www.docusign.net/restapi) configureApiClient("https://demo.docusign.net/restapi"); //=========================================================== // Step 1: Login() //=========================================================== // call the Login() API which sets the user's baseUrl and returns their accountId string accountId = loginApi(username, password); //=========================================================== // Step 2: Get Envelope Information //=========================================================== // |EnvelopesApi| contains methods related to creating and sending Envelopes including status calls EnvelopesApi envelopesApi = new EnvelopesApi(); Envelope envInfo = envelopesApi.GetEnvelope(accountId, envelopeId); // print the JSON response Console.WriteLine("EnvelopeInformation:\n{0}", JsonConvert.SerializeObject(envInfo)); return envInfo; } // end requestSignatureFromTemplateTest() //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public Recipients listRecipientsTest() { // Enter your DocuSign credentials below. Note: You only need a DocuSign account to SEND documents, // signing is always free and signers do not need an account. string username = "[EMAIL]"; string password = "[PASSWORD]"; // provide a valid envelope ID from your account. string envelopeId = "[ENVELOPE_ID]"; // instantiate api client with appropriate environment (for production change to www.docusign.net/restapi) configureApiClient("https://demo.docusign.net/restapi"); //=========================================================== // Step 1: Login() //=========================================================== // call the Login() API which sets the user's baseUrl and returns their accountId string accountId = loginApi(username, password); //=========================================================== // Step 2: List Envelope Recipients //=========================================================== // |EnvelopesApi| contains methods related to envelopes and envelope recipients EnvelopesApi envelopesApi = new EnvelopesApi(); Recipients recips = envelopesApi.ListRecipients(accountId, envelopeId); // print the JSON response Console.WriteLine("Recipients:\n{0}", JsonConvert.SerializeObject(recips)); return recips; } // end getRecipientInformationTest() //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public EnvelopesInformation listEnvelopesTest() { // Enter your DocuSign credentials below. Note: You only need a DocuSign account to SEND documents, // signing is always free and signers do not need an account. string username = "[EMAIL]"; string password = "[PASSWORD]"; // instantiate api client with appropriate environment (for production change to www.docusign.net/restapi) configureApiClient("https://demo.docusign.net/restapi"); //=========================================================== // Step 1: Login() //=========================================================== // call the Login() API which sets the user's baseUrl and returns their accountId string accountId = loginApi(username, password); //=========================================================== // Step 2: List Envelopes (using filters) //=========================================================== // This example gets statuses of all envelopes in your account going back 1 full month... DateTime fromDate = DateTime.UtcNow; fromDate = fromDate.AddDays(-30); string fromDateStr = fromDate.ToString("o"); // set a filter for the envelopes we want returned using the fromDate and count properties EnvelopesApi.ListStatusChangesOptions options = new EnvelopesApi.ListStatusChangesOptions() { count = "10", fromDate = fromDateStr }; // |EnvelopesApi| contains methods related to envelopes and envelope recipients EnvelopesApi envelopesApi = new EnvelopesApi(); EnvelopesInformation envelopes = envelopesApi.ListStatusChanges(accountId, options); // print the JSON response Console.WriteLine("Envelopes:\n{0}", JsonConvert.SerializeObject(envelopes)); return envelopes; } // end listEnvelopesTest() //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public void listDocumentsAndDownloadTest() { // Enter your DocuSign credentials below. Note: You only need a DocuSign account to SEND documents, // signing is always free and signers do not need an account. string username = "[EMAIL]"; string password = "[PASSWORD]"; // provide a valid envelope ID from your account. string envelopeId = "[ENVELOPE_ID]]"; // instantiate api client with appropriate environment (for production change to www.docusign.net/restapi) configureApiClient("https://demo.docusign.net/restapi"); //=========================================================== // Step 1: Login() //=========================================================== // call the Login() API which sets the user's baseUrl and returns their accountId string accountId = loginApi(username, password); //=========================================================== // Step 2: List Envelope Document(s) //=========================================================== // |EnvelopesApi| contains methods related to envelopes and envelope recipients EnvelopesApi envelopesApi = new EnvelopesApi(); EnvelopeDocumentsResult docsList = envelopesApi.ListDocuments(accountId, envelopeId); // print the JSON response Console.WriteLine("EnvelopeDocumentsResult:\n{0}", JsonConvert.SerializeObject(docsList)); //=========================================================== // Step 3: Download Envelope Document(s) //=========================================================== // read how many documents are in the envelope int docCount = docsList.EnvelopeDocuments.Count; string filePath = null; FileStream fs = null; // loop through the envelope's documents and download each doc for (int i = 0; i < docCount; i++) { // GetDocument() API call returns a MemoryStream MemoryStream docStream = (MemoryStream)envelopesApi.GetDocument(accountId, envelopeId, docsList.EnvelopeDocuments[i].DocumentId); // let's save the document to local file system filePath = Path.GetTempPath() + Path.GetRandomFileName() + ".pdf"; fs = new FileStream(filePath, FileMode.Create); docStream.Seek(0, SeekOrigin.Begin); docStream.CopyTo(fs); fs.Close(); Console.WriteLine("Envelope Document {0} has been downloaded to: {1}", i, filePath); } } // end listDocumentsAndDownloadTest() //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public ViewUrl createEmbeddedSendingViewTest() { // Enter your DocuSign credentials below. Note: You only need a DocuSign account to SEND documents, // signing is always free and signers do not need an account. string username = "[EMAIL]"; string password = "[PASSWORD]"; // Enter recipient (signer) name and email address string recipientName = "[RECIPIENT_NAME]"; string recipientEmail = "[RECIPIENT_EMAIL]"; // the document (file) we want signed const string SignTest1File = @"[PATH/TO/DOCUMENT/TEST.PDF]"; // instantiate api client with appropriate environment (for production change to www.docusign.net/restapi) configureApiClient("https://demo.docusign.net/restapi"); //=========================================================== // Step 1: Login() //=========================================================== // call the Login() API which sets the user's baseUrl and returns their accountId string accountId = loginApi(username, password); //=========================================================== // Step 2: Create A Draft Envelope //=========================================================== // Read a file from disk to use as a document. byte[] fileBytes = File.ReadAllBytes(SignTest1File); EnvelopeDefinition envDef = new EnvelopeDefinition(); envDef.EmailSubject = "[DocuSign C# SDK] - Please sign this doc"; // Add a document to the envelope Document doc = new Document(); doc.DocumentBase64 = System.Convert.ToBase64String(fileBytes); doc.Name = "TestFile.pdf"; doc.DocumentId = "1"; envDef.Documents = new List<Document>(); envDef.Documents.Add(doc); // Add a recipient to sign the documeent Signer signer = new Signer(); signer.Email = recipientEmail; signer.Name = recipientName; signer.RecipientId = "1"; // Create a |SignHere| tab somewhere on the document for the recipient to sign signer.Tabs = new Tabs(); signer.Tabs.SignHereTabs = new List<SignHere>(); SignHere signHere = new SignHere(); signHere.DocumentId = "1"; signHere.PageNumber = "1"; signHere.RecipientId = "1"; signHere.XPosition = "100"; signHere.YPosition = "100"; signer.Tabs.SignHereTabs.Add(signHere); envDef.Recipients = new Recipients(); envDef.Recipients.Signers = new List<Signer>(); envDef.Recipients.Signers.Add(signer); // must set status to "created" since we cannot open Sender View on an Envelope that has already been sent, only on draft envelopes envDef.Status = "created"; // |EnvelopesApi| contains methods related to creating and sending Envelopes (aka signature requests) EnvelopesApi envelopesApi = new EnvelopesApi(); EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef); //=========================================================== // Step 3: Create Embedded Sending View (URL) //=========================================================== ReturnUrlRequest options = new ReturnUrlRequest(); options.ReturnUrl = "https://www.docusign.com/devcenter"; // generate the embedded sending URL ViewUrl senderView = envelopesApi.CreateSenderView(accountId, envelopeSummary.EnvelopeId, options); // print the JSON response Console.WriteLine("ViewUrl:\n{0}", JsonConvert.SerializeObject(senderView)); // Start the embedded sending session System.Diagnostics.Process.Start(senderView.Url); return senderView; } // end createEmbeddedSendingViewTest() //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public ViewUrl createEmbeddedSigningViewTest() { // Enter your DocuSign credentials below. Note: You only need a DocuSign account to SEND documents, // signing is always free and signers do not need an account. string username = "[EMAIL]"; string password = "[PASSWORD]"; // Enter recipient (signer) name and email address string recipientName = "[RECIPIENT_NAME]"; string recipientEmail = "[RECIPIENT_EMAIL]"; // the document (file) we want signed const string SignTest1File = @"[PATH/TO/DOCUMENT/TEST.PDF]"; // instantiate api client with appropriate environment (for production change to www.docusign.net/restapi) configureApiClient("https://demo.docusign.net/restapi"); //=========================================================== // Step 1: Login() //=========================================================== // call the Login() API which sets the user's baseUrl and returns their accountId string accountId = loginApi(username, password); //=========================================================== // Step 2: Create and Send an Envelope with Embedded Recipient //=========================================================== // Read a file from disk to use as a document. byte[] fileBytes = File.ReadAllBytes(SignTest1File); EnvelopeDefinition envDef = new EnvelopeDefinition(); envDef.EmailSubject = "[DocuSign C# SDK] - Please sign this doc"; // Add a document to the envelope Document doc = new Document(); doc.DocumentBase64 = System.Convert.ToBase64String(fileBytes); doc.Name = "TestFile.pdf"; doc.DocumentId = "1"; envDef.Documents = new List<Document>(); envDef.Documents.Add(doc); // Add a recipient to sign the documeent Signer signer = new Signer(); signer.Email = recipientEmail; signer.Name = recipientName; signer.RecipientId = "1"; signer.ClientUserId = "1234"; // must set |clientUserId| to embed the recipient! // Create a |SignHere| tab somewhere on the document for the recipient to sign signer.Tabs = new Tabs(); signer.Tabs.SignHereTabs = new List<SignHere>(); SignHere signHere = new SignHere(); signHere.DocumentId = "1"; signHere.PageNumber = "1"; signHere.RecipientId = "1"; signHere.XPosition = "100"; signHere.YPosition = "100"; signer.Tabs.SignHereTabs.Add(signHere); envDef.Recipients = new Recipients(); envDef.Recipients.Signers = new List<Signer>(); envDef.Recipients.Signers.Add(signer); // set envelope status to "sent" to immediately send the signature request envDef.Status = "sent"; // |EnvelopesApi| contains methods related to creating and sending Envelopes (aka signature requests) EnvelopesApi envelopesApi = new EnvelopesApi(); EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef); //=========================================================== // Step 3: Create Embedded Signing View (URL) //=========================================================== RecipientViewRequest viewOptions = new RecipientViewRequest() { ReturnUrl = "https://www.docusign.com/devcenter", ClientUserId = "1234", // must match clientUserId set in step #2! AuthenticationMethod = "email", UserName = envDef.Recipients.Signers[0].Name, Email = envDef.Recipients.Signers[0].Email }; // create the recipient view (aka signing URL) ViewUrl recipientView = envelopesApi.CreateRecipientView(accountId, envelopeSummary.EnvelopeId, viewOptions); // print the JSON response Console.WriteLine("ViewUrl:\n{0}", JsonConvert.SerializeObject(recipientView)); // Start the embedded signing session System.Diagnostics.Process.Start(recipientView.Url); return recipientView; } // end createEmbeddedSigningViewTest() //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public ViewUrl createEmbeddedConsoleViewTest() { // Enter your DocuSign credentials below. Note: You only need a DocuSign account to SEND documents, // signing is always free and signers do not need an account. string username = "[EMAIL]"; string password = "[PASSWORD]"; // instantiate api client with appropriate environment (for production change to www.docusign.net/restapi) configureApiClient("https://demo.docusign.net/restapi"); //=========================================================== // Step 1: Login() //=========================================================== // call the Login() API which sets the user's baseUrl and returns their accountId string accountId = loginApi(username, password); //=========================================================== // Step 2: Create Embedded Console View (URL) //=========================================================== ReturnUrlRequest urlRequest = new ReturnUrlRequest(); urlRequest.ReturnUrl = "https://www.docusign.com/devcenter"; // Adding the envelopeId start sthe console with the envelope open EnvelopesApi envelopesApi = new EnvelopesApi(); ViewUrl viewUrl = envelopesApi.CreateConsoleView(accountId, null); // Start the embedded signing session. System.Diagnostics.Process.Start(viewUrl.Url); return viewUrl; } // end createEmbeddedConsoleViewTest() //********************************************************************************************************************** //********************************************************************************************************************** //* HELPER FUNCTIONS //********************************************************************************************************************** //********************************************************************************************************************** public void configureApiClient(string basePath) { // instantiate a new api client ApiClient apiClient = new ApiClient(basePath); // set client in global config so we don't need to pass it to each API object. Configuration.Default.ApiClient = apiClient; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public string loginApi(string usr, string pwd) { // we set the api client in global config when we configured the client ApiClient apiClient = Configuration.Default.ApiClient; string authHeader = "{\"Username\":\"" + usr + "\", \"Password\":\"" + pwd + "\", \"IntegratorKey\":\"" + INTEGRATOR_KEY + "\"}"; Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader); // we will retrieve this from the login() results string accountId = null; // the authentication api uses the apiClient (and X-DocuSign-Authentication header) that are set in Configuration object AuthenticationApi authApi = new AuthenticationApi(); LoginInformation loginInfo = authApi.Login(); // find the default account for this user foreach (LoginAccount loginAcct in loginInfo.LoginAccounts) { if (loginAcct.IsDefault == "true") { accountId = loginAcct.AccountId; break; } } if (accountId == null) { // if no default found set to first account accountId = loginInfo.LoginAccounts[0].AccountId; } return accountId; } } // end class } // end namespace
/* * 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 CookComputing.XmlRpc; namespace XenAPI { /// <summary> /// DR task /// First published in XenServer 6.0. /// </summary> public partial class DR_task : XenObject<DR_task> { public DR_task() { } public DR_task(string uuid, List<XenRef<SR>> introduced_SRs) { this.uuid = uuid; this.introduced_SRs = introduced_SRs; } /// <summary> /// Creates a new DR_task from a Proxy_DR_task. /// </summary> /// <param name="proxy"></param> public DR_task(Proxy_DR_task proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(DR_task update) { uuid = update.uuid; introduced_SRs = update.introduced_SRs; } internal void UpdateFromProxy(Proxy_DR_task proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; introduced_SRs = proxy.introduced_SRs == null ? null : XenRef<SR>.Create(proxy.introduced_SRs); } public Proxy_DR_task ToProxy() { Proxy_DR_task result_ = new Proxy_DR_task(); result_.uuid = (uuid != null) ? uuid : ""; result_.introduced_SRs = (introduced_SRs != null) ? Helper.RefListToStringArray(introduced_SRs) : new string[] {}; return result_; } /// <summary> /// Creates a new DR_task from a Hashtable. /// </summary> /// <param name="table"></param> public DR_task(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); introduced_SRs = Marshalling.ParseSetRef<SR>(table, "introduced_SRs"); } public bool DeepEquals(DR_task other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._introduced_SRs, other._introduced_SRs); } public override string SaveChanges(Session session, string opaqueRef, DR_task 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 DR_task. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_dr_task">The opaque_ref of the given dr_task</param> public static DR_task get_record(Session session, string _dr_task) { return new DR_task((Proxy_DR_task)session.proxy.dr_task_get_record(session.uuid, (_dr_task != null) ? _dr_task : "").parse()); } /// <summary> /// Get a reference to the DR_task instance with the specified UUID. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<DR_task> get_by_uuid(Session session, string _uuid) { return XenRef<DR_task>.Create(session.proxy.dr_task_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse()); } /// <summary> /// Get the uuid field of the given DR_task. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_dr_task">The opaque_ref of the given dr_task</param> public static string get_uuid(Session session, string _dr_task) { return (string)session.proxy.dr_task_get_uuid(session.uuid, (_dr_task != null) ? _dr_task : "").parse(); } /// <summary> /// Get the introduced_SRs field of the given DR_task. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_dr_task">The opaque_ref of the given dr_task</param> public static List<XenRef<SR>> get_introduced_SRs(Session session, string _dr_task) { return XenRef<SR>.Create(session.proxy.dr_task_get_introduced_srs(session.uuid, (_dr_task != null) ? _dr_task : "").parse()); } /// <summary> /// Create a disaster recovery task which will query the supplied list of devices /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_type">The SR driver type of the SRs to introduce</param> /// <param name="_device_config">The device configuration of the SRs to introduce</param> /// <param name="_whitelist">The devices to use for disaster recovery</param> public static XenRef<DR_task> create(Session session, string _type, Dictionary<string, string> _device_config, string[] _whitelist) { return XenRef<DR_task>.Create(session.proxy.dr_task_create(session.uuid, (_type != null) ? _type : "", Maps.convert_to_proxy_string_string(_device_config), _whitelist).parse()); } /// <summary> /// Create a disaster recovery task which will query the supplied list of devices /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_type">The SR driver type of the SRs to introduce</param> /// <param name="_device_config">The device configuration of the SRs to introduce</param> /// <param name="_whitelist">The devices to use for disaster recovery</param> public static XenRef<Task> async_create(Session session, string _type, Dictionary<string, string> _device_config, string[] _whitelist) { return XenRef<Task>.Create(session.proxy.async_dr_task_create(session.uuid, (_type != null) ? _type : "", Maps.convert_to_proxy_string_string(_device_config), _whitelist).parse()); } /// <summary> /// Destroy the disaster recovery task, detaching and forgetting any SRs introduced which are no longer required /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_dr_task">The opaque_ref of the given dr_task</param> public static void destroy(Session session, string _dr_task) { session.proxy.dr_task_destroy(session.uuid, (_dr_task != null) ? _dr_task : "").parse(); } /// <summary> /// Destroy the disaster recovery task, detaching and forgetting any SRs introduced which are no longer required /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_dr_task">The opaque_ref of the given dr_task</param> public static XenRef<Task> async_destroy(Session session, string _dr_task) { return XenRef<Task>.Create(session.proxy.async_dr_task_destroy(session.uuid, (_dr_task != null) ? _dr_task : "").parse()); } /// <summary> /// Return a list of all the DR_tasks known to the system. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<DR_task>> get_all(Session session) { return XenRef<DR_task>.Create(session.proxy.dr_task_get_all(session.uuid).parse()); } /// <summary> /// Get all the DR_task Records at once, in a single XML RPC call /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<DR_task>, DR_task> get_all_records(Session session) { return XenRef<DR_task>.Create<Proxy_DR_task>(session.proxy.dr_task_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// All SRs introduced by this appliance /// </summary> public virtual List<XenRef<SR>> introduced_SRs { get { return _introduced_SRs; } set { if (!Helper.AreEqual(value, _introduced_SRs)) { _introduced_SRs = value; Changed = true; NotifyPropertyChanged("introduced_SRs"); } } } private List<XenRef<SR>> _introduced_SRs; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.Configuration; using Orleans.Providers.Streams.Common; using Orleans.Runtime; using Orleans.Streams; using Orleans.ServiceBus.Providers.Testing; using Azure.Messaging.EventHubs; namespace Orleans.ServiceBus.Providers { /// <summary> /// Event Hub Partition settings /// </summary> public class EventHubPartitionSettings { /// <summary> /// Eventhub settings /// </summary> public EventHubOptions Hub { get; set; } public EventHubReceiverOptions ReceiverOptions { get; set; } /// <summary> /// Partition name /// </summary> public string Partition { get; set; } } internal class EventHubAdapterReceiver : IQueueAdapterReceiver, IQueueCache { public const int MaxMessagesPerRead = 1000; private static readonly TimeSpan ReceiveTimeout = TimeSpan.FromSeconds(5); private readonly EventHubPartitionSettings settings; private readonly Func<string, IStreamQueueCheckpointer<string>, ILoggerFactory, ITelemetryProducer, IEventHubQueueCache> cacheFactory; private readonly Func<string, Task<IStreamQueueCheckpointer<string>>> checkpointerFactory; private readonly ILoggerFactory loggerFactory; private readonly ILogger logger; private readonly IQueueAdapterReceiverMonitor monitor; private readonly ITelemetryProducer telemetryProducer; private readonly LoadSheddingOptions loadSheddingOptions; private IEventHubQueueCache cache; private IEventHubReceiver receiver; private Func<EventHubPartitionSettings, string, ILogger, ITelemetryProducer, IEventHubReceiver> eventHubReceiverFactory; private IStreamQueueCheckpointer<string> checkpointer; private AggregatedQueueFlowController flowController; // Receiver life cycle private int receiverState = ReceiverShutdown; private const int ReceiverShutdown = 0; private const int ReceiverRunning = 1; public int GetMaxAddCount() { return this.flowController.GetMaxAddCount(); } public EventHubAdapterReceiver(EventHubPartitionSettings settings, Func<string, IStreamQueueCheckpointer<string>, ILoggerFactory, ITelemetryProducer, IEventHubQueueCache> cacheFactory, Func<string, Task<IStreamQueueCheckpointer<string>>> checkpointerFactory, ILoggerFactory loggerFactory, IQueueAdapterReceiverMonitor monitor, LoadSheddingOptions loadSheddingOptions, ITelemetryProducer telemetryProducer, Func<EventHubPartitionSettings, string, ILogger, ITelemetryProducer, IEventHubReceiver> eventHubReceiverFactory = null) { this.settings = settings ?? throw new ArgumentNullException(nameof(settings)); this.cacheFactory = cacheFactory ?? throw new ArgumentNullException(nameof(cacheFactory)); this.checkpointerFactory = checkpointerFactory ?? throw new ArgumentNullException(nameof(checkpointerFactory)); this.loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); this.logger = this.loggerFactory.CreateLogger($"{this.GetType().FullName}.{settings.Hub.Path}.{settings.Partition}"); this.monitor = monitor ?? throw new ArgumentNullException(nameof(monitor)); this.telemetryProducer = telemetryProducer ?? throw new ArgumentNullException(nameof(telemetryProducer)); this.loadSheddingOptions = loadSheddingOptions ?? throw new ArgumentNullException(nameof(loadSheddingOptions)); this.eventHubReceiverFactory = eventHubReceiverFactory == null ? EventHubAdapterReceiver.CreateReceiver : eventHubReceiverFactory; } public Task Initialize(TimeSpan timeout) { this.logger.Info("Initializing EventHub partition {0}-{1}.", this.settings.Hub.Path, this.settings.Partition); // if receiver was already running, do nothing return ReceiverRunning == Interlocked.Exchange(ref this.receiverState, ReceiverRunning) ? Task.CompletedTask : Initialize(); } /// <summary> /// Initialization of EventHub receiver is performed at adapter receiver initialization, but if it fails, /// it will be retried when messages are requested /// </summary> /// <returns></returns> private async Task Initialize() { var watch = Stopwatch.StartNew(); try { this.checkpointer = await this.checkpointerFactory(this.settings.Partition); if(this.cache != null) { this.cache.Dispose(); this.cache = null; } this.cache = this.cacheFactory(this.settings.Partition, this.checkpointer, this.loggerFactory, this.telemetryProducer); this.flowController = new AggregatedQueueFlowController(MaxMessagesPerRead) { this.cache, LoadShedQueueFlowController.CreateAsPercentOfLoadSheddingLimit(this.loadSheddingOptions) }; string offset = await this.checkpointer.Load(); this.receiver = this.eventHubReceiverFactory(this.settings, offset, this.logger, this.telemetryProducer); watch.Stop(); this.monitor?.TrackInitialization(true, watch.Elapsed, null); } catch (Exception ex) { watch.Stop(); this.monitor?.TrackInitialization(false, watch.Elapsed, ex); throw; } } public async Task<IList<IBatchContainer>> GetQueueMessagesAsync(int maxCount) { if (this.receiverState == ReceiverShutdown || maxCount <= 0) { return new List<IBatchContainer>(); } // if receiver initialization failed, retry if (this.receiver == null) { this.logger.Warn(OrleansServiceBusErrorCode.FailedPartitionRead, "Retrying initialization of EventHub partition {0}-{1}.", this.settings.Hub.Path, this.settings.Partition); await Initialize(); if (this.receiver == null) { // should not get here, should throw instead, but just incase. return new List<IBatchContainer>(); } } var watch = Stopwatch.StartNew(); List<EventData> messages; try { messages = (await this.receiver.ReceiveAsync(maxCount, ReceiveTimeout))?.ToList(); watch.Stop(); this.monitor?.TrackRead(true, watch.Elapsed, null); } catch (Exception ex) { watch.Stop(); this.monitor?.TrackRead(false, watch.Elapsed, ex); this.logger.Warn(OrleansServiceBusErrorCode.FailedPartitionRead, "Failed to read from EventHub partition {0}-{1}. : Exception: {2}.", this.settings.Hub.Path, this.settings.Partition, ex); throw; } var batches = new List<IBatchContainer>(); if (messages == null || messages.Count == 0) { this.monitor?.TrackMessagesReceived(0, null, null); return batches; } // monitor message age var dequeueTimeUtc = DateTime.UtcNow; DateTime oldestMessageEnqueueTime = messages[0].EnqueuedTime.UtcDateTime; DateTime newestMessageEnqueueTime = messages[messages.Count - 1].EnqueuedTime.UtcDateTime; this.monitor?.TrackMessagesReceived(messages.Count, oldestMessageEnqueueTime, newestMessageEnqueueTime); List<StreamPosition> messageStreamPositions = this.cache.Add(messages, dequeueTimeUtc); foreach (var streamPosition in messageStreamPositions) { batches.Add(new StreamActivityNotificationBatch(streamPosition)); } if (!this.checkpointer.CheckpointExists) { this.checkpointer.Update( messages[0].Offset.ToString(), DateTime.UtcNow); } return batches; } public void AddToCache(IList<IBatchContainer> messages) { // do nothing, we add data directly into cache. No need for agent involvement } public bool TryPurgeFromCache(out IList<IBatchContainer> purgedItems) { purgedItems = null; //if not under pressure, signal the cache to do a time based purge //if under pressure, which means consuming speed is less than producing speed, then shouldn't purge, and don't read more message into the cache if (!this.IsUnderPressure()) this.cache.SignalPurge(); return false; } public IQueueCacheCursor GetCacheCursor(StreamId streamId, StreamSequenceToken token) { return new Cursor(this.cache, streamId, token); } public bool IsUnderPressure() { return this.GetMaxAddCount() <= 0; } public Task MessagesDeliveredAsync(IList<IBatchContainer> messages) { return Task.CompletedTask; } public async Task Shutdown(TimeSpan timeout) { var watch = Stopwatch.StartNew(); try { // if receiver was already shutdown, do nothing if (ReceiverShutdown == Interlocked.Exchange(ref this.receiverState, ReceiverShutdown)) { return; } this.logger.Info("Stopping reading from EventHub partition {0}-{1}", this.settings.Hub.Path, this.settings.Partition); // clear cache and receiver IEventHubQueueCache localCache = Interlocked.Exchange(ref this.cache, null); var localReceiver = Interlocked.Exchange(ref this.receiver, null); // start closing receiver Task closeTask = Task.CompletedTask; if (localReceiver != null) { closeTask = localReceiver.CloseAsync(); } // dispose of cache localCache?.Dispose(); // finish return receiver closing task await closeTask; watch.Stop(); this.monitor?.TrackShutdown(true, watch.Elapsed, null); } catch (Exception ex) { watch.Stop(); this.monitor?.TrackShutdown(false, watch.Elapsed, ex); throw; } } private static IEventHubReceiver CreateReceiver(EventHubPartitionSettings partitionSettings, string offset, ILogger logger, ITelemetryProducer telemetryProducer) { return new EventHubReceiverProxy(partitionSettings, offset, logger); } /// <summary> /// For test purpose. ConfigureDataGeneratorForStream will configure a data generator for the stream /// </summary> /// <param name="streamId"></param> internal void ConfigureDataGeneratorForStream(StreamId streamId) { (this.receiver as EventHubPartitionGeneratorReceiver)?.ConfigureDataGeneratorForStream(streamId); } internal void StopProducingOnStream(StreamId streamId) { (this.receiver as EventHubPartitionGeneratorReceiver)?.StopProducingOnStream(streamId); } [GenerateSerializer] internal class StreamActivityNotificationBatch : IBatchContainer { [Id(0)] public StreamPosition Position { get; } public StreamId StreamId => this.Position.StreamId; public StreamSequenceToken SequenceToken => this.Position.SequenceToken; public StreamActivityNotificationBatch(StreamPosition position) { this.Position = position; } public IEnumerable<Tuple<T, StreamSequenceToken>> GetEvents<T>() { throw new NotSupportedException(); } public bool ImportRequestContext() { throw new NotSupportedException(); } } private class Cursor : IQueueCacheCursor { private readonly IEventHubQueueCache cache; private readonly object cursor; private IBatchContainer current; public Cursor(IEventHubQueueCache cache, StreamId streamId, StreamSequenceToken token) { this.cache = cache; this.cursor = cache.GetCursor(streamId, token); } public void Dispose() { } public IBatchContainer GetCurrent(out Exception exception) { exception = null; return this.current; } public bool MoveNext() { IBatchContainer next; if (!this.cache.TryGetNextMessage(this.cursor, out next)) { return false; } this.current = next; return true; } public void Refresh(StreamSequenceToken token) { } public void RecordDeliveryFailure() { } } } }
// // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. //using System; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Couchbase.Lite; using Couchbase.Lite.Internal; using Couchbase.Lite.Replicator; using Couchbase.Lite.Support; using Couchbase.Lite.Util; using Sharpen; using System.Threading; namespace Couchbase.Lite.Replicator { internal class BulkDownloader : RemoteRequest, IMultipartReaderDelegate { const string Tag = "BulkDownloader"; private MultipartReader _topReader; private MultipartDocumentReader _docReader; private int _docCount; public event EventHandler<BulkDownloadEventArgs> DocumentDownloaded { add { _documentDownloaded = (EventHandler<BulkDownloadEventArgs>)Delegate.Combine(_documentDownloaded, value); } remove { _documentDownloaded = (EventHandler<BulkDownloadEventArgs>)Delegate.Remove(_documentDownloaded, value); } } private EventHandler<BulkDownloadEventArgs> _documentDownloaded; /// <exception cref="System.Exception"></exception> public BulkDownloader(TaskFactory workExecutor, IHttpClientFactory clientFactory, Uri dbURL, IList<RevisionInternal> revs, Database database, IDictionary<string, object> requestHeaders, CancellationTokenSource tokenSource = null) : base(workExecutor, clientFactory, "POST", new Uri(AppendRelativeURLString(dbURL, "/_bulk_get?revs=true&attachments=true")), HelperMethod(revs, database), database, requestHeaders, tokenSource) { } public override void Run() { HttpClient httpClient = null; try { httpClient = clientFactory.GetHttpClient(false); requestMessage.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("multipart/related")); var authHeader = AuthUtils.GetAuthenticationHeaderValue(Authenticator, requestMessage.RequestUri); if (authHeader != null) { httpClient.DefaultRequestHeaders.Authorization = authHeader; } //TODO: implement gzip support for server response see issue #172 //request.addHeader("X-Accept-Part-Encoding", "gzip"); AddRequestHeaders(requestMessage); SetBody(requestMessage); ExecuteRequest(httpClient, requestMessage); } finally { if (httpClient != null) { httpClient.Dispose(); } } } private string Description() { return this.GetType().FullName + "[" + url.AbsolutePath + "]"; } protected override internal void ExecuteRequest(HttpClient httpClient, HttpRequestMessage request) { object fullBody = null; Exception error = null; HttpResponseMessage response = null; try { if (_tokenSource.IsCancellationRequested) { RespondWithResult(fullBody, new Exception(string.Format("{0}: Request {1} has been aborted", this, request)), response); return; } Log.D(Tag + ".ExecuteRequest", "Sending request: {0}", request); var requestTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_tokenSource.Token); var responseTask = httpClient.SendAsync(request, requestTokenSource.Token); if (!responseTask.Wait((Int32)ManagerOptions.Default.RequestTimeout.TotalMilliseconds, requestTokenSource.Token)) { Log.E(Tag, "Response task timed out: {0}, {1}, {2}", responseTask, TaskScheduler.Current, Description()); throw new HttpResponseException(HttpStatusCode.RequestTimeout); } requestTokenSource.Dispose(); response = responseTask.Result; } catch (Exception e) { var err = (e is AggregateException) ? ((AggregateException)e).InnerException : e; Log.E(Tag, "Unhandled Exception", err); error = err; RespondWithResult(fullBody, err, response); return; } try { if (response == null) { Log.E(Tag, "Didn't get response for {0}", request); error = new HttpRequestException(); RespondWithResult(fullBody, error, response); } else if (!response.IsSuccessStatusCode) { HttpStatusCode status = response.StatusCode; Log.E(Tag, "Got error status: {0} for {1}. Reason: {2}", status.GetStatusCode(), request, response.ReasonPhrase); error = new HttpResponseException(status); RespondWithResult(fullBody, error, response); } else { Log.D(Tag, "Processing response: {0}", response); var entity = response.Content; var contentTypeHeader = entity.Headers.ContentType; Stream inputStream = null; if (contentTypeHeader != null && contentTypeHeader.ToString().Contains("multipart/")) { Log.V(Tag, "contentTypeHeader = {0}", contentTypeHeader.ToString()); try { _topReader = new MultipartReader(contentTypeHeader.ToString(), this); inputStream = entity.ReadAsStreamAsync().Result; const int bufLen = 1024; var buffer = new byte[bufLen]; var numBytesRead = 0; while ((numBytesRead = inputStream.Read(buffer, 0, bufLen)) > 0) { if (numBytesRead != bufLen) { var bufferToAppend = new Couchbase.Lite.Util.ArraySegment<byte>(buffer, 0, numBytesRead).ToArray(); _topReader.AppendData(bufferToAppend); } else { _topReader.AppendData(buffer); } } _topReader.Finished(); RespondWithResult(fullBody, error, response); } finally { try { inputStream.Close(); } catch (IOException) { } } } else { Log.V(Tag, "contentTypeHeader is not multipart = {0}", contentTypeHeader.ToString()); if (entity != null) { try { inputStream = entity.ReadAsStreamAsync().Result; fullBody = Manager.GetObjectMapper().ReadValue<object>(inputStream); RespondWithResult(fullBody, error, response); } finally { try { inputStream.Close(); } catch (IOException) { } } } } } } catch (AggregateException e) { var err = e.InnerException; Log.E(Tag, "Unhandled Exception", err); error = err; RespondWithResult(fullBody, err, response); } catch (IOException e) { Log.E(Tag, "IO Exception", e); error = e; RespondWithResult(fullBody, e, response); } catch (Exception e) { Log.E(Tag, "ExecuteRequest Exception: ", e); error = e; RespondWithResult(fullBody, e, response); } } /// <summary>This method is called when a part's headers have been parsed, before its data is parsed. /// </summary> /// <remarks>This method is called when a part's headers have been parsed, before its data is parsed. /// </remarks> public void StartedPart(IDictionary<string, string> headers) { if (_docReader != null) { throw new InvalidOperationException("_docReader is already defined"); } Log.V(Tag, "{0}: Starting new document; headers ={1}", this, headers); Log.V(Tag, "{0}: Starting new document; ID={1}".Fmt(this, headers.Get("X-Doc-Id"))); _docReader = new MultipartDocumentReader(db); _docReader.SetContentType(headers.Get ("Content-Type")); _docReader.StartedPart(headers); } /// <summary>This method is called to append data to a part's body.</summary> /// <remarks>This method is called to append data to a part's body.</remarks> public void AppendToPart (IEnumerable<byte> data) { if (_docReader == null) { throw new InvalidOperationException("_docReader is not defined"); } _docReader.AppendData(data); } /// <summary>This method is called when a part is complete.</summary> /// <remarks>This method is called when a part is complete.</remarks> public virtual void FinishedPart() { Log.V(Tag, "{0}: Finished document".Fmt(this)); if (_docReader == null) { throw new InvalidOperationException("_docReader is not defined"); } _docReader.Finish(); ++_docCount; OnDocumentDownloaded(_docReader.GetDocumentProperties()); _docReader = null; } protected virtual void OnDocumentDownloaded (IDictionary<string, object> props) { var handler = _documentDownloaded; if (handler != null) handler (this, new BulkDownloadEventArgs(props)); } private static IDictionary<string, object> HelperMethod(IEnumerable<RevisionInternal> revs, Database database) { Func<RevisionInternal, IDictionary<String, Object>> invoke = source => { var attsSince = database.Storage.GetPossibleAncestors(source, Puller.MAX_ATTS_SINCE, true); var mapped = new Dictionary<string, object> (); mapped.Put ("id", source.GetDocId ()); mapped.Put ("rev", source.GetRevId ()); mapped.Put ("atts_since", attsSince); return mapped; }; // Build up a JSON body describing what revisions we want: IEnumerable<IDictionary<string, object>> keys = null; try { keys = revs.Select(invoke); } catch (Exception ex) { Log.E(Tag, "Error generating bulk request data.", ex); } var retval = new Dictionary<string, object>(); retval.Put("docs", keys); return retval; } private static string AppendRelativeURLString(Uri remote, string relativePath) { var uri = remote.AppendPath(relativePath); return uri.AbsoluteUri; } } }
using System; using NUnit.Framework; using Whois.Parsers; namespace Whois.Parsing.Whois.Nic.Coop.Coop { [TestFixture] public class CoopParsingTests : ParsingTests { private WhoisParser parser; [SetUp] public void SetUp() { SerilogConfig.Init(); parser = new WhoisParser(); } [Test] public void Test_found() { var sample = SampleReader.Read("whois.nic.coop", "coop", "found.txt"); var response = parser.Parse("whois.nic.coop", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.coop/coop/Found", response.TemplateName); Assert.AreEqual("moscowfood.coop", response.DomainName.ToString()); Assert.AreEqual("5662D-COOP", response.RegistryDomainId); // Registrar Details Assert.AreEqual("Domain Bank Inc.", response.Registrar.Name); Assert.AreEqual("31", response.Registrar.IanaId); Assert.AreEqual(new DateTime(2001, 10, 09, 04, 36, 36, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2013, 01, 30, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("71764C-COOP", response.Registrant.RegistryId); Assert.AreEqual("Kenna Eaton", response.Registrant.Name); Assert.AreEqual("Moscow Food Co-op", response.Registrant.Organization); Assert.AreEqual("+1.2088828537", response.Registrant.TelephoneNumber); Assert.AreEqual("+1.2088828082", response.Registrant.FaxNumber); Assert.AreEqual("kenna@moscowfood.coop", response.Registrant.Email); // Registrant Address Assert.AreEqual(5, response.Registrant.Address.Count); Assert.AreEqual("P. O. Box 9485", response.Registrant.Address[0]); Assert.AreEqual("Moscow", response.Registrant.Address[1]); Assert.AreEqual("ID", response.Registrant.Address[2]); Assert.AreEqual("83843", response.Registrant.Address[3]); Assert.AreEqual("United States", response.Registrant.Address[4]); // AdminContact Details Assert.AreEqual("74326C-COOP", response.AdminContact.RegistryId); Assert.AreEqual("Carol Spurling", response.AdminContact.Name); Assert.AreEqual("Moscow Food Co-op", response.AdminContact.Organization); Assert.AreEqual("+1.2086690763", response.AdminContact.TelephoneNumber); Assert.AreEqual("outreach@moscowfood.coop", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(5, response.AdminContact.Address.Count); Assert.AreEqual("P. O. Box 9485", response.AdminContact.Address[0]); Assert.AreEqual("Moscow", response.AdminContact.Address[1]); Assert.AreEqual("ID", response.AdminContact.Address[2]); Assert.AreEqual("83843", response.AdminContact.Address[3]); Assert.AreEqual("United States", response.AdminContact.Address[4]); // BillingContact Details Assert.AreEqual("75003C-COOP", response.BillingContact.RegistryId); Assert.AreEqual("Sandy Hughes", response.BillingContact.Name); Assert.AreEqual("Moscow Food Co-op", response.BillingContact.Organization); Assert.AreEqual("+1.2088828537", response.BillingContact.TelephoneNumber); Assert.AreEqual("+1.2088828082", response.BillingContact.FaxNumber); Assert.AreEqual("payable@moscowfood.coop", response.BillingContact.Email); // BillingContact Address Assert.AreEqual(5, response.BillingContact.Address.Count); Assert.AreEqual("P. O. Box 9485", response.BillingContact.Address[0]); Assert.AreEqual("Moscow", response.BillingContact.Address[1]); Assert.AreEqual("ID", response.BillingContact.Address[2]); Assert.AreEqual("83843", response.BillingContact.Address[3]); Assert.AreEqual("United States", response.BillingContact.Address[4]); // TechnicalContact Details Assert.AreEqual("75916C-COOP", response.TechnicalContact.RegistryId); Assert.AreEqual("Joseph Erhard-Hudson", response.TechnicalContact.Name); Assert.AreEqual("Moscow Food Co-op", response.TechnicalContact.Organization); Assert.AreEqual("+1.2088828537", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("+1.2088828082", response.TechnicalContact.FaxNumber); Assert.AreEqual("joseph@moscowfood.coop", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(5, response.TechnicalContact.Address.Count); Assert.AreEqual("P. O. Box 9485", response.TechnicalContact.Address[0]); Assert.AreEqual("Moscow", response.TechnicalContact.Address[1]); Assert.AreEqual("ID", response.TechnicalContact.Address[2]); Assert.AreEqual("83843", response.TechnicalContact.Address[3]); Assert.AreEqual("United States", response.TechnicalContact.Address[4]); // Nameservers Assert.AreEqual(2, response.NameServers.Count); Assert.AreEqual("ns2.west-datacenter.net", response.NameServers[0]); Assert.AreEqual("ns1.west-datacenter.net", response.NameServers[1]); // Domain Status Assert.AreEqual(3, response.DomainStatus.Count); Assert.AreEqual("clientDeleteProhibited", response.DomainStatus[0]); Assert.AreEqual("clientTransferProhibited", response.DomainStatus[1]); Assert.AreEqual("clientUpdateProhibited", response.DomainStatus[2]); Assert.AreEqual(59, response.FieldsParsed); } [Test] public void Test_other_status_single() { var sample = SampleReader.Read("whois.nic.coop", "coop", "other_status_single.txt"); var response = parser.Parse("whois.nic.coop", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.coop/coop/Found", response.TemplateName); Assert.AreEqual("calgary.coop", response.DomainName.ToString()); Assert.AreEqual("7441D-COOP", response.RegistryDomainId); // Registrar Details Assert.AreEqual("domains.coop", response.Registrar.Name); Assert.AreEqual("465", response.Registrar.IanaId); Assert.AreEqual(new DateTime(2002, 01, 31, 22, 12, 44, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2012, 01, 31, 22, 12, 44, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("54100C-COOP", response.Registrant.RegistryId); Assert.AreEqual("Net Admin", response.Registrant.Name); Assert.AreEqual("Calgary Co operative Association Limited", response.Registrant.Organization); Assert.AreEqual("+1.4032196025", response.Registrant.TelephoneNumber); Assert.AreEqual("+1.4032995416", response.Registrant.FaxNumber); Assert.AreEqual("netadmin@calgarycoop.com", response.Registrant.Email); // Registrant Address Assert.AreEqual(5, response.Registrant.Address.Count); Assert.AreEqual("2735 39 Avenue NE", response.Registrant.Address[0]); Assert.AreEqual("Calgary", response.Registrant.Address[1]); Assert.AreEqual("AB", response.Registrant.Address[2]); Assert.AreEqual("T1Y 7C7", response.Registrant.Address[3]); Assert.AreEqual("Canada", response.Registrant.Address[4]); // AdminContact Details Assert.AreEqual("54100C-COOP", response.AdminContact.RegistryId); Assert.AreEqual("Net Admin", response.AdminContact.Name); Assert.AreEqual("Calgary Co operative Association Limited", response.AdminContact.Organization); Assert.AreEqual("+1.4032196025", response.AdminContact.TelephoneNumber); Assert.AreEqual("+1.4032995416", response.AdminContact.FaxNumber); Assert.AreEqual("netadmin@calgarycoop.com", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(5, response.AdminContact.Address.Count); Assert.AreEqual("2735 39 Avenue NE", response.AdminContact.Address[0]); Assert.AreEqual("Calgary", response.AdminContact.Address[1]); Assert.AreEqual("AB", response.AdminContact.Address[2]); Assert.AreEqual("T1Y 7C7", response.AdminContact.Address[3]); Assert.AreEqual("Canada", response.AdminContact.Address[4]); // BillingContact Details Assert.AreEqual("54100C-COOP", response.BillingContact.RegistryId); Assert.AreEqual("Net Admin", response.BillingContact.Name); Assert.AreEqual("Calgary Co operative Association Limited", response.BillingContact.Organization); Assert.AreEqual("+1.4032196025", response.BillingContact.TelephoneNumber); Assert.AreEqual("+1.4032995416", response.BillingContact.FaxNumber); Assert.AreEqual("netadmin@calgarycoop.com", response.BillingContact.Email); // BillingContact Address Assert.AreEqual(5, response.BillingContact.Address.Count); Assert.AreEqual("2735 39 Avenue NE", response.BillingContact.Address[0]); Assert.AreEqual("Calgary", response.BillingContact.Address[1]); Assert.AreEqual("AB", response.BillingContact.Address[2]); Assert.AreEqual("T1Y 7C7", response.BillingContact.Address[3]); Assert.AreEqual("Canada", response.BillingContact.Address[4]); // TechnicalContact Details Assert.AreEqual("54100C-COOP", response.TechnicalContact.RegistryId); Assert.AreEqual("Net Admin", response.TechnicalContact.Name); Assert.AreEqual("Calgary Co operative Association Limited", response.TechnicalContact.Organization); Assert.AreEqual("+1.4032196025", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("+1.4032995416", response.TechnicalContact.FaxNumber); Assert.AreEqual("netadmin@calgarycoop.com", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(5, response.TechnicalContact.Address.Count); Assert.AreEqual("2735 39 Avenue NE", response.TechnicalContact.Address[0]); Assert.AreEqual("Calgary", response.TechnicalContact.Address[1]); Assert.AreEqual("AB", response.TechnicalContact.Address[2]); Assert.AreEqual("T1Y 7C7", response.TechnicalContact.Address[3]); Assert.AreEqual("Canada", response.TechnicalContact.Address[4]); // Nameservers Assert.AreEqual(2, response.NameServers.Count); Assert.AreEqual("ns1.calgarycoop.net", response.NameServers[0]); Assert.AreEqual("ns2.calgarycoop.net", response.NameServers[1]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("ok", response.DomainStatus[0]); Assert.AreEqual(58, response.FieldsParsed); } [Test] public void Test_not_found() { var sample = SampleReader.Read("whois.nic.coop", "coop", "not_found.txt"); var response = parser.Parse("whois.nic.coop", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.NotFound, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.coop/coop/NotFound", response.TemplateName); Assert.AreEqual("u34jedzcq.coop", response.DomainName.ToString()); Assert.AreEqual(2, response.FieldsParsed); } [Test] public void Test_found_status_registered() { var sample = SampleReader.Read("whois.nic.coop", "coop", "found_status_registered.txt"); var response = parser.Parse("whois.nic.coop", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); AssertWriter.Write(response); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.coop/coop/Found", response.TemplateName); Assert.AreEqual("calgary.coop", response.DomainName.ToString()); Assert.AreEqual("7441D-COOP", response.RegistryDomainId); // Registrar Details Assert.AreEqual("domains.coop", response.Registrar.Name); Assert.AreEqual("465", response.Registrar.IanaId); Assert.AreEqual(new DateTime(2002, 01, 31, 22, 12, 44, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2017, 01, 31, 22, 12, 44, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("54100C-COOP", response.Registrant.RegistryId); Assert.AreEqual("Net Admin", response.Registrant.Name); Assert.AreEqual("Calgary Co operative Association Limited", response.Registrant.Organization); Assert.AreEqual("+1.4032196025", response.Registrant.TelephoneNumber); Assert.AreEqual("+1.4032995416", response.Registrant.FaxNumber); Assert.AreEqual("netadmin@calgarycoop.com", response.Registrant.Email); // Registrant Address Assert.AreEqual(5, response.Registrant.Address.Count); Assert.AreEqual("2735 39 Avenue NE", response.Registrant.Address[0]); Assert.AreEqual("Calgary", response.Registrant.Address[1]); Assert.AreEqual("AB", response.Registrant.Address[2]); Assert.AreEqual("T1Y 7C7", response.Registrant.Address[3]); Assert.AreEqual("Canada", response.Registrant.Address[4]); // AdminContact Details Assert.AreEqual("54100C-COOP", response.AdminContact.RegistryId); Assert.AreEqual("Net Admin", response.AdminContact.Name); Assert.AreEqual("Calgary Co operative Association Limited", response.AdminContact.Organization); Assert.AreEqual("+1.4032196025", response.AdminContact.TelephoneNumber); Assert.AreEqual("+1.4032995416", response.AdminContact.FaxNumber); Assert.AreEqual("netadmin@calgarycoop.com", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(5, response.AdminContact.Address.Count); Assert.AreEqual("2735 39 Avenue NE", response.AdminContact.Address[0]); Assert.AreEqual("Calgary", response.AdminContact.Address[1]); Assert.AreEqual("AB", response.AdminContact.Address[2]); Assert.AreEqual("T1Y 7C7", response.AdminContact.Address[3]); Assert.AreEqual("Canada", response.AdminContact.Address[4]); // BillingContact Details Assert.AreEqual("54100C-COOP", response.BillingContact.RegistryId); Assert.AreEqual("Net Admin", response.BillingContact.Name); Assert.AreEqual("Calgary Co operative Association Limited", response.BillingContact.Organization); Assert.AreEqual("+1.4032196025", response.BillingContact.TelephoneNumber); Assert.AreEqual("+1.4032995416", response.BillingContact.FaxNumber); Assert.AreEqual("netadmin@calgarycoop.com", response.BillingContact.Email); // BillingContact Address Assert.AreEqual(5, response.BillingContact.Address.Count); Assert.AreEqual("2735 39 Avenue NE", response.BillingContact.Address[0]); Assert.AreEqual("Calgary", response.BillingContact.Address[1]); Assert.AreEqual("AB", response.BillingContact.Address[2]); Assert.AreEqual("T1Y 7C7", response.BillingContact.Address[3]); Assert.AreEqual("Canada", response.BillingContact.Address[4]); // TechnicalContact Details Assert.AreEqual("54100C-COOP", response.TechnicalContact.RegistryId); Assert.AreEqual("Net Admin", response.TechnicalContact.Name); Assert.AreEqual("Calgary Co operative Association Limited", response.TechnicalContact.Organization); Assert.AreEqual("+1.4032196025", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("+1.4032995416", response.TechnicalContact.FaxNumber); Assert.AreEqual("netadmin@calgarycoop.com", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(5, response.TechnicalContact.Address.Count); Assert.AreEqual("2735 39 Avenue NE", response.TechnicalContact.Address[0]); Assert.AreEqual("Calgary", response.TechnicalContact.Address[1]); Assert.AreEqual("AB", response.TechnicalContact.Address[2]); Assert.AreEqual("T1Y 7C7", response.TechnicalContact.Address[3]); Assert.AreEqual("Canada", response.TechnicalContact.Address[4]); // Nameservers Assert.AreEqual(2, response.NameServers.Count); Assert.AreEqual("ns1.calgarycoop.net", response.NameServers[0]); Assert.AreEqual("ns2.calgarycoop.net", response.NameServers[1]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("ok", response.DomainStatus[0]); Assert.AreEqual(58, response.FieldsParsed); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using Microsoft.Research.CodeAnalysis; using Microsoft.Research.DataStructures; namespace Microsoft.Research.Slicing { using Dest = Int32; using Source = Int32; [ContractVerification(false)] public abstract class Chain<M, F, T> : IChain<M, F, T> { public virtual ChainTag Tag { get { throw new InvalidOperationException(); } } public virtual F Field { get { throw new InvalidOperationException(); } } public virtual M Method { get { throw new InvalidOperationException(); } } public virtual T Type { get { throw new InvalidOperationException(); } } public virtual MethodHashAttribute MethodHashAttribute { get { throw new InvalidOperationException(); } internal set { throw new InvalidOperationException(); } } public virtual IEnumerable<IChain<M, F, T>> Children { get { throw new InvalidOperationException(); } } public abstract class MemberBindingChain<Member> : Chain<M, F, T> { protected readonly Member member; protected MemberBindingChain(Member member) { this.member = member; } public override int GetHashCode() { return this.member.GetHashCode(); } public override string ToString() { return String.Format("{0}:{1}", this.Tag, this.member); } } private class FieldChain : MemberBindingChain<F> { public FieldChain(F f) : base(f) { } public override ChainTag Tag { get { return ChainTag.Field; } } public override F Field { get { return this.member; } } } internal class MethodChain : MemberBindingChain<M> { public MethodChain(M m) : base(m) { } public override ChainTag Tag { get { return ChainTag.Method; } } public override M Method { get { return this.member; } } public override MethodHashAttribute MethodHashAttribute { get; internal set; } // cannot do only override get; } public class TypeRootChain : MemberBindingChain<T> { public TypeRootChain(T t) : base(t) { } public override ChainTag Tag { get { return ChainTag.Type; } } public override T Type { get { return this.member; } } private readonly Dictionary<T, Chain<M, F, T>> childrenT = new Dictionary<T, Chain<M, F, T>>(); internal void Add(T t, Chain<M, F, T> chain) { Contract.Assume(!this.childrenT.ContainsKey(t)); this.childrenT.Add(t, chain); } public override IEnumerable<IChain<M, F, T>> Children { get { return this.childrenT.Values; } } } internal class TypeChain : TypeRootChain { public TypeChain(T t) : base(t) { } // We use three different dictionaries because equality is lost if a M, a F, or a T is boxed into an Object private readonly Dictionary<M, MethodChain> childrenM = new Dictionary<M, MethodChain>(); private readonly Dictionary<F, FieldChain> childrenF = new Dictionary<F, FieldChain>(); internal TypeChain ContractClass { get; set; } internal void Add(F f) { if (!this.childrenF.ContainsKey(f)) this.childrenF.Add(f, new FieldChain(f)); } internal MethodChain Add(M m) { Contract.Assume(!this.childrenM.ContainsKey(m)); var chain = new MethodChain(m); this.childrenM.Add(m, chain); return chain; } public override IEnumerable<IChain<M, F, T>> Children { get { return base.Children.Concat(this.childrenM.Values).Concat(this.childrenF.Values); } } } public class RootChain : TypeRootChain { public RootChain() : base(default(T)) { } public override int GetHashCode() { return 0; } public override string ToString() { return "RootChain"; } } } public class Slice<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> : Chain<Method, Field, Type>.RootChain, ISlice<Method, Field, Type, Assembly> where Type : IEquatable<Type> { #region Object invariants [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(this.containingAssembly != null); Contract.Invariant(this.containingAssemblyName != null); Contract.Invariant(this.mdDecoder != null); Contract.Invariant(this.methods != null); Contract.Invariant(this.dependencies != null); Contract.Invariant(this.contractDecoder != null); } #endregion // the state should not contain method-specific objects private readonly string name; private readonly Assembly containingAssembly; private readonly string containingAssemblyName; protected readonly IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder; protected readonly IDecodeContracts<Local, Parameter, Method, Field, Type> contractDecoder; protected readonly HashSet<Method> methods = new HashSet<Method>(); protected readonly HashSet<Method> dependencies = new HashSet<Method>(); public string Name { get { return this.name; } } public Assembly ContainingAssembly { get { return this.containingAssembly; } } public IEnumerable<Method> Methods { get { return this.methods; } } public IEnumerable<IChain<Method, Field, Type>> Chains { get { return this.Children; } } public IEnumerable<Method> Dependencies { get { return this.dependencies; } } private IEnumerable<Method> cachedMethodsInTheSameType = null; public IEnumerable<Method> OtherMethodsInTheSameType { get { if (this.cachedMethodsInTheSameType == null) { var tmp = new Set<Method>(); foreach (var method in this.methods) { foreach (var m in this.mdDecoder.Methods(this.mdDecoder.DeclaringType(method))) { if (!method.Equals(m)) { tmp.Add(m); } } } this.cachedMethodsInTheSameType = tmp; } Contract.Assert(this.cachedMethodsInTheSameType != null); return this.cachedMethodsInTheSameType; } } protected Slice( string name, Assembly containingAssembly, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder, IDecodeContracts<Local, Parameter, Method, Field, Type> contractDecoder) { Contract.Requires(containingAssembly != null); Contract.Requires(contractDecoder != null); Contract.Requires(mdDecoder != null); this.name = name; this.containingAssembly = containingAssembly; this.containingAssemblyName = mdDecoder.Name(containingAssembly); this.mdDecoder = mdDecoder; this.contractDecoder = contractDecoder; } protected bool IsAssemblySelected(string moduleName) { return moduleName == this.containingAssemblyName; } } public class SliceBuilder<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Context, Expression, SymbolicValue> : Slice<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> where Type : IEquatable<Type> where Method : IEquatable<Method> { #region Object invariants [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(this.cachedTouchedTypes != null); Contract.Invariant(this.cachedTouchedMethods != null); Contract.Invariant(this.cachedTouchedFields != null); Contract.Invariant(this.methodsToTouchLater != null); Contract.Invariant(this.typesToTouchLater != null); Contract.Invariant(this.getMethodDriver != null); } #endregion private readonly Dictionary<Type, TypeChain> cachedTouchedTypes = new Dictionary<Type, TypeChain>(); private readonly Dictionary<Method, MethodChain> cachedTouchedMethods = new Dictionary<Method, MethodChain>(); private readonly Set<Field> cachedTouchedFields = new Set<Field>(); private readonly Set<Type> typesToTouchLater = new Set<Type>(); private readonly Set<Method> methodsToTouchLater = new Set<Method>(); private readonly Func<Method, IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, ILogOptions>> getMethodDriver; public SliceBuilder( string name, IEnumerable<Method> methods, Assembly containingAssembly, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder, IDecodeContracts<Local, Parameter, Method, Field, Type> contractDecoder, Func<Method, IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, ILogOptions>> getMethodDriver, bool includeOtherMethodsInTheType) : base(name, containingAssembly, mdDecoder, contractDecoder) { Contract.Requires(methods != null); Contract.Requires(containingAssembly != null); Contract.Requires(contractDecoder != null); Contract.Requires(mdDecoder != null); Contract.Requires(getMethodDriver != null); this.getMethodDriver = getMethodDriver; foreach (var m in methods) { this.AddMethod(m); } if (includeOtherMethodsInTheType) { foreach (var m in this.OtherMethodsInTheSameType) { Touch(m); } } } [ContractVerification(false)] private void Touch(Type type) { // lazyly touch types to avoid cyclic recursivity if (!this.cachedTouchedTypes.ContainsKey(type)) this.typesToTouchLater.Add(type); } [ContractVerification(false)] private void Touch(Method method) { if (!this.cachedTouchedMethods.ContainsKey(method)) this.methodsToTouchLater.Add(method); } [ContractVerification(false)] private TypeChain GetTypeChain(Type type) { TypeChain chain; if (this.cachedTouchedTypes.TryGetValue(type, out chain)) return chain; if (this.mdDecoder.IsVoid(type) || this.mdDecoder.IsPrimitive(type) || this.mdDecoder.Equal(type, this.mdDecoder.System_Object) // primitive types || this.mdDecoder.IsFormalTypeParameter(type) || this.mdDecoder.IsMethodFormalTypeParameter(type)) // abstract types { this.cachedTouchedTypes.Add(type, null); return null; } Type modified; IIndexable<Pair<bool, Type>> modifiers; if (this.mdDecoder.IsModified(type, out modified, out modifiers)) // modified types { foreach (var p in modifiers.Enumerate()) this.Touch(p.Two); chain = this.GetTypeChain(modified); this.cachedTouchedTypes.Add(type, chain); } else if (this.mdDecoder.IsArray(type) || this.mdDecoder.IsManagedPointer(type) || this.mdDecoder.IsUnmanagedPointer(type)) // boxing types { chain = this.GetTypeChain(this.mdDecoder.ElementType(type)); this.cachedTouchedTypes.Add(type, chain); } else { IIndexable<Type> typeArguments; if (this.mdDecoder.NormalizedIsSpecialized(type, out typeArguments)) // specialized types { foreach (var t in typeArguments.Enumerate()) this.Touch(t); chain = this.GetTypeChain(this.mdDecoder.Unspecialized(type)); this.cachedTouchedTypes.Add(type, chain); } else if (this.mdDecoder.Namespace(type) == null && this.mdDecoder.Name(type) == this.mdDecoder.FullName(type)) // weird types like function pointers (TODO) { this.cachedTouchedTypes.Add(type, null); return null; } else // named types { // here type should be a INamedTypeDefinition if (!this.IsAssemblySelected(this.mdDecoder.DeclaringModuleName(type))) { // do not keep types from other assemblies this.cachedTouchedTypes.Add(type, null); return null; } chain = new TypeChain(type); this.cachedTouchedTypes.Add(type, chain); // put this here because of cyclic dependences Type parentType; if (this.mdDecoder.IsNested(type, out parentType)) // nested types { var parentChain = this.GetTypeChain(parentType); if (parentChain == null) { this.cachedTouchedTypes[type] = null; return null; } parentChain.Add(type, chain); } else this.Add(type, chain); } } // No need to keep dependences of types that we won't keep anyway if (chain == null) return null; // Put this here to avoid infinite recursion if (this.mdDecoder.HasBaseClass(type)) // add the base class this.Touch(this.mdDecoder.BaseClass(type)); foreach (var t in this.mdDecoder.Interfaces(type)) // add the implemented interfaces this.Touch(t); this.Touch(this.mdDecoder.GetAttributes(type), chain); foreach (var f in this.mdDecoder.Fields(type)) this.Touch(f); foreach (var p in this.mdDecoder.Properties(type)) { Method getter; if (this.mdDecoder.HasGetter(p, out getter)) this.Touch(getter); } foreach (var m in this.mdDecoder.Methods(type)) { if (this.contractDecoder.IsPure(m)) this.Touch(m); } return chain; } private void Touch(IEnumerable<Attribute> attrs, TypeChain typeChain = null) { Contract.Requires(attrs != null); foreach (var attr in attrs) this.Touch(attr, typeChain); } private void Touch(Attribute attr, TypeChain typeChain = null) { var type = this.mdDecoder.AttributeType(attr); this.Touch(type); this.Touch(this.mdDecoder.AttributeConstructor(attr)); foreach (var arg in this.mdDecoder.PositionalArguments(attr).Enumerate()) { if (arg == null || arg is string || arg.GetType().IsPrimitive) continue; if (arg is Type) this.Touch((Type)arg); else throw new NotImplementedException("Attribute argument of type " + arg.GetType().Name); } if (typeChain != null && this.mdDecoder.FullName(type) == NameFor.ContractClassAttribute) { var arg = this.mdDecoder.PositionalArguments(attr)[0]; if (arg is Type) typeChain.ContractClass = this.GetTypeChain((Type)arg); } } private void Touch(Parameter param) { this.Touch(this.mdDecoder.ParameterType(param)); this.Touch(this.mdDecoder.GetAttributes(param)); } private void Touch(Local local) { this.Touch(this.mdDecoder.LocalType(local)); } private void TouchAutoProperty(Property property) { this.Touch(this.mdDecoder.DeclaringType(property)); this.Touch(this.mdDecoder.PropertyType(property)); Method getter, setter; if (this.mdDecoder.HasGetter(property, out getter)) this.Touch(getter); // the contract decoder assumes an auto property has a non-null getter if (this.mdDecoder.HasSetter(property, out setter)) { this.AddMethod(setter); // we will need it to retrieve the backing field again Field backingField; if (this.mdDecoder.IsAutoPropertySetter(setter, out backingField)) this.Touch(backingField); } } private void Touch(Field field) { if (this.cachedTouchedFields.Add(field)) { if (this.mdDecoder.IsSpecialized(field)) this.Touch(this.mdDecoder.Unspecialized(field)); else { var parentChain = this.GetTypeChain(this.mdDecoder.DeclaringType(field)); if (parentChain == null) return; parentChain.Add(field); this.Touch(this.mdDecoder.FieldType(field)); this.Touch(this.mdDecoder.GetAttributes(field)); } } } [ContractVerification(false)] private MethodChain GetMethodChain(Method method) { MethodChain chain; if (this.cachedTouchedMethods.TryGetValue(method, out chain)) return chain; IIndexable<Type> methodTypeArguments; Method genericMethod; if (this.mdDecoder.IsSpecialized(method, out genericMethod, out methodTypeArguments)) { foreach (var t in methodTypeArguments.Enumerate()) this.Touch(t); var unspecialized = genericMethod; if (!unspecialized.Equals(method)) // avoids infinite recursion for anonymous delegates { chain = this.GetMethodChain(unspecialized); this.cachedTouchedMethods.Add(method, chain); return chain; } } var declaringType = this.mdDecoder.DeclaringType(method); var declaringTypeChain = this.GetTypeChain(declaringType); if (declaringTypeChain == null || this.mdDecoder.IsDelegate(declaringType)) chain = null; else chain = declaringTypeChain.Add(method); this.cachedTouchedMethods.Add(method, chain); if (chain == null) return null; this.dependencies.Add(method); if (declaringTypeChain.ContractClass != null) { Method implementingMethod; if (this.mdDecoder.TryGetImplementingMethod(declaringTypeChain.ContractClass.Type, method, out implementingMethod)) this.Touch(implementingMethod); } if (this.mdDecoder.IsObjectInvariantMethod(method)) this.AddMethod(method); this.Touch(this.mdDecoder.ReturnType(method)); if (!this.mdDecoder.IsStatic(method)) this.Touch(this.mdDecoder.This(method)); foreach (var arg in this.mdDecoder.Parameters(method).Enumerate()) this.Touch(arg); foreach (var local in this.mdDecoder.Locals(method).Enumerate()) this.Touch(local); foreach (var m in this.mdDecoder.OverriddenAndImplementedMethods(method)) this.Touch(m); this.Touch(this.mdDecoder.GetAttributes(method)); if (this.mdDecoder.IsAutoPropertyMember(method)) { var property = this.mdDecoder.GetPropertyFromAccessor(method); if (property != null) this.TouchAutoProperty(property); } return chain; } private void TouchMethodBody(Method method) { var mDriver = this.getMethodDriver(method); if (mDriver != null) new SlicerMethodVisitor(this, mDriver).TouchMe(); } // Entry method // Add the method and its body public void AddMethod(Method method) { this.Touch(method); if (!this.methods.Add(method)) return; this.TouchMethodBody(method); } [ContractVerification(false)] public Slice<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> ComputeSlice(Func<Method, ByteArray> getMethodHash) { Contract.Requires(getMethodHash != null); // We were lazy, now it's time to work while (this.typesToTouchLater.Any() || this.methodsToTouchLater.Any()) { while (this.typesToTouchLater.Any()) { var t = this.typesToTouchLater.First(); this.GetTypeChain(t); this.typesToTouchLater.Remove(t); } while (this.methodsToTouchLater.Any()) { var m = this.methodsToTouchLater.First(); this.GetMethodChain(m); this.methodsToTouchLater.Remove(m); } } this.dependencies.ExceptWith(this.methods); foreach (var m in this.dependencies) { if (m == null) continue; Contract.Assume(this.cachedTouchedMethods[m] != null); this.cachedTouchedMethods[m].MethodHashAttribute = new MethodHashAttribute(getMethodHash(m), MethodHashAttributeFlags.ForDependenceMethod); } foreach (var m in this.methods) { var methodChain = this.cachedTouchedMethods[m]; if (methodChain != null) // this should not happen, but it currently happens because of lambda/anonymous delegates methodChain.MethodHashAttribute = new MethodHashAttribute(getMethodHash(m), MethodHashAttributeFlags.Default); } return this; } #region IL Visitor private class SlicerMethodVisitor : IVisitMSIL<APC, Local, Parameter, Method, Field, Type, Source, Dest, Unit, Unit> { #region Object Invariant [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(this.visitedSubroutines != null); Contract.Invariant(this.mDriver != null); Contract.Invariant(this.parent != null); Contract.Invariant(this.mdDecoder != null); } #endregion private readonly SliceBuilder<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Context, Expression, SymbolicValue> parent; private readonly IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, ILogOptions> mDriver; private readonly Set<Subroutine> visitedSubroutines = new Set<Subroutine>(); private IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder { get { return this.parent.mdDecoder; } } private ICodeLayer<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Source, Dest, IStackContext<Field, Method>, Unit> codeLayer { get { return this.mDriver.StackLayer; } } public SlicerMethodVisitor( SliceBuilder<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Context, Expression, SymbolicValue> parent, IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, ILogOptions> mDriver) { Contract.Requires(parent != null); Contract.Requires(mDriver != null); this.parent = parent; this.mDriver = mDriver; } #region Slicing members public void TouchMe() { //this.Touch(mDriver.CFG.Subroutine); this.Touch(this.mDriver.StackLayer.Decoder.Context.MethodContext.CFG.Subroutine); } private void Touch(Subroutine subroutine) { Contract.Requires(subroutine != null); if (!this.visitedSubroutines.Add(subroutine)) return; var usedSubroutines = new Set<Subroutine>(subroutine.UsedSubroutines()); var stackCFG = this.mDriver.StackLayer.Decoder.Context.MethodContext.CFG; foreach (var block in subroutine.Blocks) { Contract.Assume(block != null); foreach (var apc in block.APCs()) { mDriver.StackLayer.Decoder.ForwardDecode<Unit, Unit, SlicerMethodVisitor>(apc, this, Unit.Value); } foreach (var taggedSucc in subroutine.SuccessorEdgesFor(block)) { foreach (var edgeSub in stackCFG.GetOrdinaryEdgeSubroutines(block, taggedSucc.Two, null).GetEnumerable()) { var sub = edgeSub.Two; usedSubroutines.Add(sub); var methodInfo = sub as IMethodInfo<Method>; if (methodInfo != null && !this.mDriver.CurrentMethod.Equals(methodInfo.Method)) { this.parent.Touch(methodInfo.Method); } } } } foreach (var usedSubroutine in usedSubroutines) { this.Touch(usedSubroutine); } } #endregion private void InlineMethod(Method method) { method = this.mdDecoder.Unspecialized(method); if (this.mdDecoder.HasBody(method)) this.Touch(this.mDriver.AnalysisDriver.MethodCache.GetCFG(method).Subroutine); } #region IVisitMSIL<Label,Local,Parameter,Method,Field,Type,Source,Dest,Unit,Unit> Members #region Should not be used in the stack based CFG -> NotImplementedException public Unit BranchCond(APC pc, APC target, BranchOperator bop, Source value1, Source value2, Unit data) { throw new NotImplementedException(); } public Unit BranchTrue(APC pc, APC target, Source cond, Unit data) { throw new NotImplementedException(); } public Unit BranchFalse(APC pc, APC target, Source cond, Unit data) { throw new NotImplementedException(); } public Unit Branch(APC pc, APC target, bool leave, Unit data) { throw new NotImplementedException(); } public Unit Switch(APC pc, Type type, IEnumerable<Pair<object, APC>> cases, Source value, Unit data) { throw new NotImplementedException(); } #endregion #region No interesting argument -> do nothing public Unit Break(APC pc, Unit data) { return Unit.Value; } public Unit Arglist(APC pc, Dest dest, Unit data) { return Unit.Value; } public Unit Ckfinite(APC pc, Dest dest, Source source, Unit data) { return Unit.Value; } public Unit Cpblk(APC pc, bool @volatile, Source destaddr, Source srcaddr, Source len, Unit data) { return Unit.Value; } public Unit Endfilter(APC pc, Source decision, Unit data) { return Unit.Value; } public Unit Endfinally(APC pc, Unit data) { return Unit.Value; } public Unit Initblk(APC pc, bool @volatile, Source destaddr, Source value, Source len, Unit data) { return Unit.Value; } public Unit Localloc(APC pc, Dest dest, Source size, Unit data) { return Unit.Value; } public Unit Nop(APC pc, Unit data) { return Unit.Value; } public Unit Pop(APC pc, Source source, Unit data) { return Unit.Value; } public Unit Return(APC pc, Source source, Unit data) { return Unit.Value; } public Unit Ldlen(APC pc, Dest dest, Source array, Unit data) { return Unit.Value; } public Unit Rethrow(APC pc, Unit data) { return Unit.Value; } public Unit Refanytype(APC pc, Dest dest, Source source, Unit data) { return Unit.Value; } public Unit Throw(APC pc, Source exn, Unit data) { return Unit.Value; } #endregion #region Calls public Unit Call<TypeList, ArgList>(APC pc, Method method, bool tail, bool virt, TypeList extraVarargs, Dest dest, ArgList args, Unit data) where TypeList : IIndexable<Type> where ArgList : IIndexable<Source> { this.parent.Touch(method); if (args != null && args.Count > 0 && this.codeLayer.ContractDecoder.IsPure(method)) { // if we call Contract.{ForAll, Exists} with a delegate that we decompile, we need to hash the delegate's il too var mName = this.mdDecoder.Name(method); if ((mName == "ForAll") || (mName == "Exists")) { // last argument is closure Method quantifierClosure; if (this.codeLayer.Decoder.Context.StackContext.TryGetCallArgumentDelegateTarget(pc, args[args.Count - 1], out quantifierClosure)) this.InlineMethod(quantifierClosure); } } if (extraVarargs != null) foreach (var argType in extraVarargs.Enumerate()) this.parent.Touch(argType); return Unit.Value; } public Unit ConstrainedCallvirt<TypeList, ArgList>(APC pc, Method method, bool tail, Type constraint, TypeList extraVarargs, Dest dest, ArgList args, Unit data) where TypeList : IIndexable<Type> where ArgList : IIndexable<Source> { if (extraVarargs != null) foreach (var argType in extraVarargs.Enumerate()) this.parent.Touch(argType); return Unit.Value; } public Unit Calli<TypeList, ArgList>(APC pc, Type returnType, TypeList argTypes, bool tail, bool isInstance, Dest dest, Source fp, ArgList args, Unit data) where TypeList : IIndexable<Type> where ArgList : IIndexable<Source> { this.parent.Touch(returnType); if (argTypes != null) foreach (var argType in argTypes.Enumerate()) this.parent.Touch(argType); return Unit.Value; } #endregion #region Method -> Visit(method) public Unit Jmp(APC pc, Method method, Unit data) { this.parent.Touch(method); return Unit.Value; } public Unit Ldftn(APC pc, Method method, Dest dest, Unit data) { this.parent.Touch(method); return Unit.Value; } public Unit Ldmethodtoken(APC pc, Method method, Dest dest, Unit data) { this.parent.Touch(method); return Unit.Value; } public Unit Ldvirtftn(APC pc, Method method, Dest dest, Source obj, Unit data) { this.parent.Touch(method); return Unit.Value; } public Unit Newobj<ArgList>(APC pc, Method ctor, Dest dest, ArgList args, Unit data) where ArgList : IIndexable<Source> { this.parent.Touch(ctor); return Unit.Value; } #endregion #region Parameter -> Visit(argument) public Unit Ldarg(APC pc, Parameter argument, bool isOld, Dest dest, Unit data) { this.parent.Touch(argument); return Unit.Value; } public Unit Ldarga(APC pc, Parameter argument, bool isOld, Dest dest, Unit data) { this.parent.Touch(argument); return Unit.Value; } public Unit Starg(APC pc, Parameter argument, Source source, Unit data) { this.parent.Touch(argument); return Unit.Value; } #endregion #region Type -> Visit(type) public Unit Castclass(APC pc, Type type, Dest dest, Source obj, Unit data) { this.parent.Touch(type); return Unit.Value; } public Unit Cpobj(APC pc, Type type, Source destptr, Source srcptr, Unit data) { this.parent.Touch(type); return Unit.Value; } public Unit Initobj(APC pc, Type type, Source ptr, Unit data) { this.parent.Touch(type); return Unit.Value; } public Unit Ldelem(APC pc, Type type, Dest dest, Source array, Source index, Unit data) { this.parent.Touch(type); return Unit.Value; } public Unit Ldelema(APC pc, Type type, bool @readonly, Dest dest, Source array, Source index, Unit data) { this.parent.Touch(type); return Unit.Value; } public Unit Ldind(APC pc, Type type, bool @volatile, Dest dest, Source ptr, Unit data) { this.parent.Touch(type); return Unit.Value; } public Unit Stind(APC pc, Type type, bool @volatile, Source ptr, Source value, Unit data) { this.parent.Touch(type); return Unit.Value; } public Unit Box(APC pc, Type type, Dest dest, Source source, Unit data) { this.parent.Touch(type); return Unit.Value; } public Unit Ldtypetoken(APC pc, Type type, Dest dest, Unit data) { this.parent.Touch(type); return Unit.Value; } public Unit Mkrefany(APC pc, Type type, Dest dest, Source obj, Unit data) { this.parent.Touch(type); return Unit.Value; } public Unit Newarray<ArgList>(APC pc, Type type, Dest dest, ArgList len, Unit data) where ArgList : IIndexable<Source> { this.parent.Touch(type); return Unit.Value; } public Unit Refanyval(APC pc, Type type, Dest dest, Source source, Unit data) { this.parent.Touch(type); return Unit.Value; } public Unit Stelem(APC pc, Type type, Source array, Source index, Source value, Unit data) { this.parent.Touch(type); return Unit.Value; } public Unit Unbox(APC pc, Type type, Dest dest, Source obj, Unit data) { this.parent.Touch(type); return Unit.Value; } public Unit Unboxany(APC pc, Type type, Dest dest, Source obj, Unit data) { this.parent.Touch(type); return Unit.Value; } #endregion #region Local -> Visit(local) public Unit Ldloc(APC pc, Local local, Dest dest, Unit data) { this.parent.Touch(local); return Unit.Value; } public Unit Ldloca(APC pc, Local local, Dest dest, Unit data) { this.parent.Touch(local); return Unit.Value; } public Unit Stloc(APC pc, Local local, Source source, Unit data) { this.parent.Touch(local); return Unit.Value; } #endregion #region Field -> Visit(field) public Unit Ldfld(APC pc, Field field, bool @volatile, Dest dest, Source obj, Unit data) { this.parent.Touch(field); return Unit.Value; } public Unit Ldflda(APC pc, Field field, Dest dest, Source obj, Unit data) { this.parent.Touch(field); return Unit.Value; } public Unit Ldsfld(APC pc, Field field, bool @volatile, Dest dest, Unit data) { this.parent.Touch(field); return Unit.Value; } public Unit Ldfieldtoken(APC pc, Field field, Dest dest, Unit data) { this.parent.Touch(field); return Unit.Value; } public Unit Ldsflda(APC pc, Field field, Dest dest, Unit data) { this.parent.Touch(field); return Unit.Value; } public Unit Stfld(APC pc, Field field, bool @volatile, Source obj, Source value, Unit data) { this.parent.Touch(field); return Unit.Value; } public Unit Stsfld(APC pc, Field field, bool @volatile, Source value, Unit data) { this.parent.Touch(field); return Unit.Value; } #endregion #endregion #region IVisitSynthIL<Label,Method,Type,Source,Dest,Unit,Unit> Members #region no nothing public Unit Ldstack(APC pc, int offset, Dest dest, Source source, bool isOld, Unit data) { return Unit.Value; } public Unit BeginOld(APC pc, APC matchingEnd, Unit data) { return Unit.Value; } #endregion #region assume, assert -> do nothing public Unit Assume(APC pc, string tag, Source condition, object provenance, Unit data) { // TODO: do we need to visit the provenance ? return Unit.Value; } public Unit Assert(APC pc, string tag, Source condition, object provenance, Unit data) { // TODO: do we need to visit the provenance ? return Unit.Value; } #endregion #region Type public Unit Ldstacka(APC pc, int offset, Dest dest, Source source, Type origParamType, bool isOld, Unit data) { this.parent.Touch(origParamType); return Unit.Value; } public Unit Ldresult(APC pc, Type type, Dest dest, Source source, Unit data) { this.parent.Touch(type); return Unit.Value; } public Unit EndOld(APC pc, APC matchingBegin, Type type, Dest dest, Source source, Unit data) { this.parent.Touch(type); return Unit.Value; } #endregion #region Method public Unit Entry(APC pc, Method method, Unit data) { this.parent.Touch(method); return Unit.Value; } #endregion #endregion #region IVisitExprIL<Label,Type,Source,Dest,Unit,Unit> Members #region operators, null -> do nothing public Unit Binary(APC pc, BinaryOperator op, Dest dest, Source s1, Source s2, Unit data) { return Unit.Value; } public Unit Unary(APC pc, UnaryOperator op, bool overflow, bool unsigned, Dest dest, Source source, Unit data) { return Unit.Value; } public Unit Ldnull(APC pc, Dest dest, Unit data) { return Unit.Value; } #endregion #region Type public Unit Isinst(APC pc, Type type, Dest dest, Source obj, Unit data) { this.parent.Touch(type); return Unit.Value; } public Unit Ldconst(APC pc, object constant, Type type, Dest dest, Unit data) { this.parent.Touch(type); return Unit.Value; } public Unit Sizeof(APC pc, Type type, Dest dest, Unit data) { this.parent.Touch(type); return Unit.Value; } #endregion #endregion } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; namespace LibGit2Sharp.Core { internal class HistoryRewriter { private readonly IRepository repo; private readonly HashSet<Commit> targetedCommits; private readonly Dictionary<GitObject, GitObject> objectMap = new Dictionary<GitObject, GitObject>(); private readonly Dictionary<Reference, Reference> refMap = new Dictionary<Reference, Reference>(); private readonly Queue<Action> rollbackActions = new Queue<Action>(); private readonly string backupRefsNamespace; private readonly RewriteHistoryOptions options; public HistoryRewriter( IRepository repo, IEnumerable<Commit> commitsToRewrite, RewriteHistoryOptions options) { this.repo = repo; this.options = options; targetedCommits = new HashSet<Commit>(commitsToRewrite); backupRefsNamespace = this.options.BackupRefsNamespace; if (!backupRefsNamespace.EndsWith("/", StringComparison.Ordinal)) { backupRefsNamespace += "/"; } } public void Execute() { var success = false; try { // Find out which refs lead to at least one the commits var refsToRewrite = repo.Refs.ReachableFrom(targetedCommits).ToList(); var filter = new CommitFilter { IncludeReachableFrom = refsToRewrite, SortBy = CommitSortStrategies.Reverse | CommitSortStrategies.Topological }; var commits = repo.Commits.QueryBy(filter); foreach (var commit in commits) { RewriteCommit(commit, options); } // Ordering matters. In the case of `A -> B -> commit`, we need to make sure B is rewritten // before A. foreach (var reference in refsToRewrite.OrderBy(ReferenceDepth)) { // TODO: Rewrite refs/notes/* properly if (reference.CanonicalName.StartsWith("refs/notes/")) { continue; } RewriteReference(reference); } success = true; if (options.OnSucceeding != null) { options.OnSucceeding(); } } catch (Exception ex) { try { if (!success && options.OnError != null) { options.OnError(ex); } } finally { foreach (var action in rollbackActions) { action(); } } throw; } finally { rollbackActions.Clear(); } } private Reference RewriteReference(Reference reference) { // Has this target already been rewritten? if (refMap.ContainsKey(reference)) { return refMap[reference]; } var sref = reference as SymbolicReference; if (sref != null) { return RewriteReference(sref, old => old.Target, RewriteReference, (refs, old, target, logMessage) => refs.UpdateTarget(old, target, logMessage)); } var dref = reference as DirectReference; if (dref != null) { return RewriteReference(dref, old => old.Target, RewriteTarget, (refs, old, target, logMessage) => refs.UpdateTarget(old, target.Id, logMessage)); } return reference; } private delegate Reference ReferenceUpdater<in TRef, in TTarget>( ReferenceCollection refs, TRef origRef, TTarget origTarget, string logMessage) where TRef : Reference where TTarget : class; private Reference RewriteReference<TRef, TTarget>( TRef oldRef, Func<TRef, TTarget> selectTarget, Func<TTarget, TTarget> rewriteTarget, ReferenceUpdater<TRef, TTarget> updateTarget) where TRef : Reference where TTarget : class { var oldRefTarget = selectTarget(oldRef); string newRefName = oldRef.CanonicalName; if (oldRef.IsTag && options.TagNameRewriter != null) { newRefName = Reference.TagPrefix + options.TagNameRewriter(oldRef.CanonicalName.Substring(Reference.TagPrefix.Length), false, oldRef.TargetIdentifier); } var newTarget = rewriteTarget(oldRefTarget); if (oldRefTarget.Equals(newTarget) && oldRef.CanonicalName == newRefName) { // The reference isn't rewritten return oldRef; } string backupName = backupRefsNamespace + oldRef.CanonicalName.Substring("refs/".Length); if (repo.Refs.Resolve<Reference>(backupName) != null) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Can't back up reference '{0}' - '{1}' already exists", oldRef.CanonicalName, backupName)); } repo.Refs.Add(backupName, oldRef.TargetIdentifier, "filter-branch: backup"); rollbackActions.Enqueue(() => repo.Refs.Remove(backupName)); if (newTarget == null) { repo.Refs.Remove(oldRef); rollbackActions.Enqueue(() => repo.Refs.Add(oldRef.CanonicalName, oldRef, "filter-branch: abort", true)); return refMap[oldRef] = null; } Reference newRef = updateTarget(repo.Refs, oldRef, newTarget, "filter-branch: rewrite"); rollbackActions.Enqueue(() => updateTarget(repo.Refs, oldRef, oldRefTarget, "filter-branch: abort")); if (newRef.CanonicalName == newRefName) { return refMap[oldRef] = newRef; } var movedRef = repo.Refs.Rename(newRef, newRefName, false); rollbackActions.Enqueue(() => repo.Refs.Rename(newRef, oldRef.CanonicalName, false)); return refMap[oldRef] = movedRef; } private void RewriteCommit(Commit commit, RewriteHistoryOptions options) { var newHeader = CommitRewriteInfo.From(commit); var newTree = commit.Tree; // Find the new parents var newParents = commit.Parents; if (targetedCommits.Contains(commit)) { // Get the new commit header if (options.CommitHeaderRewriter != null) { newHeader = options.CommitHeaderRewriter(commit) ?? newHeader; } if (options.CommitTreeRewriter != null) { // Get the new commit tree var newTreeDefinition = options.CommitTreeRewriter(commit); newTree = repo.ObjectDatabase.CreateTree(newTreeDefinition); } // Retrieve new parents if (options.CommitParentsRewriter != null) { newParents = options.CommitParentsRewriter(commit); } } // Create the new commit var mappedNewParents = newParents .Select(oldParent => objectMap.ContainsKey(oldParent) ? objectMap[oldParent] as Commit : oldParent) .Where(newParent => newParent != null) .ToList(); if (options.PruneEmptyCommits && TryPruneEmptyCommit(commit, mappedNewParents, newTree)) { return; } var newCommit = repo.ObjectDatabase.CreateCommit(newHeader.Author, newHeader.Committer, newHeader.Message, newTree, mappedNewParents, options.PrettifyMessages); // Record the rewrite objectMap[commit] = newCommit; } private bool TryPruneEmptyCommit(Commit commit, IList<Commit> mappedNewParents, Tree newTree) { var parent = mappedNewParents.Count > 0 ? mappedNewParents[0] : null; if (parent == null) { if (newTree.Count == 0) { objectMap[commit] = null; return true; } } else if (parent.Tree == newTree) { objectMap[commit] = parent; return true; } return false; } private GitObject RewriteTarget(GitObject oldTarget) { // Has this target already been rewritten? if (objectMap.ContainsKey(oldTarget)) { return objectMap[oldTarget]; } Debug.Assert((oldTarget as Commit) == null); var annotation = oldTarget as TagAnnotation; if (annotation == null) { //TODO: Probably a Tree or a Blob. This is not covered by any test return oldTarget; } // Recursively rewrite annotations if necessary var newTarget = RewriteTarget(annotation.Target); string newName = annotation.Name; if (options.TagNameRewriter != null) { newName = options.TagNameRewriter(annotation.Name, true, annotation.Target.Sha); } var newAnnotation = repo.ObjectDatabase.CreateTagAnnotation(newName, newTarget, annotation.Tagger, annotation.Message); objectMap[annotation] = newAnnotation; return newAnnotation; } private int ReferenceDepth(Reference reference) { var dref = reference as DirectReference; return dref == null ? 1 + ReferenceDepth(((SymbolicReference)reference).Target) : 1; } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Reflection; using System.Text; using OpenMetaverse; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes.Serialization; namespace OpenSim.Region.Framework.Scenes { public class SceneObjectPartInventory : IEntityInventory { private string m_inventoryFileName = String.Empty; private byte[] m_fileData = new byte[0]; private uint m_inventoryFileNameSerial = 0; /// <value> /// The part to which the inventory belongs. /// </value> private readonly SceneObjectPart m_part; /// <summary> /// Serial count for inventory file , used to tell if inventory has changed /// no need for this to be part of Database backup /// </summary> protected uint m_inventorySerial = 0; /// <summary> /// Holds in memory prim inventory /// </summary> protected TaskInventoryDictionary m_items = new TaskInventoryDictionary(); protected object m_itemsLock = new object(); /// <summary> /// Tracks whether inventory has changed since the last persistent backup /// </summary> internal bool m_HasInventoryChanged; public bool HasInventoryChanged { get { return m_HasInventoryChanged; } set { //Set the parent as well so that backup will occur if (value && m_part.ParentGroup != null) m_part.ParentGroup.HasGroupChanged = true; m_HasInventoryChanged = value; } } /// <value> /// Inventory serial number /// </value> protected internal uint Serial { get { return m_inventorySerial; } set { m_inventorySerial = value; } } /// <value> /// Raw inventory data /// </value> protected internal TaskInventoryDictionary Items { get { return m_items; } set { m_items = value; m_inventorySerial++; } } /// <summary> /// Constructor /// </summary> /// <param name="part"> /// A <see cref="SceneObjectPart"/> /// </param> public SceneObjectPartInventory(SceneObjectPart part) { m_part = part; } /// <summary> /// Force the task inventory of this prim to persist at the next update sweep /// </summary> public void ForceInventoryPersistence() { HasInventoryChanged = true; } /// <summary> /// Reset UUIDs for all the items in the prim's inventory. This involves either generating /// new ones or setting existing UUIDs to the correct parent UUIDs. /// /// If this method is called and there are inventory items, then we regard the inventory as having changed. /// </summary> ///<param name="ChangeScripts"></param> public void ResetInventoryIDs (bool ChangeScripts) { if (null == m_part || null == m_part.ParentGroup) return; if (0 == m_items.Count) return; IList<TaskInventoryItem> items = GetInventoryItems (); lock (m_itemsLock) { m_items.Clear (); foreach (TaskInventoryItem item in items) { //UUID oldItemID = item.ItemID; item.ResetIDs (m_part.UUID); m_items.Add (item.ItemID, item); //LEAVE THIS COMMENTED!!! // When an object is duplicated, this will be called and it will destroy the original prims scripts!! // This needs to be moved to a place that is safer later // This was *originally* intended to be used on scripts that were crossing region borders /*if (m_part.ParentGroup != null) { lock (m_part.ParentGroup) { if (m_part.ParentGroup.Scene != null) { foreach (IScriptModule engine in m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>()) { engine.UpdateScriptToNewObject(oldItemID, item, m_part); } } } }*/ } HasInventoryChanged = true; } } public void ResetObjectID () { if (Items.Count == 0) { return; } lock (m_itemsLock) { HasInventoryChanged = true; if (m_part.ParentGroup != null) { m_part.ParentGroup.HasGroupChanged = true; } IList<TaskInventoryItem> items = Items.Values.ToList(); Items.Clear (); foreach (TaskInventoryItem item in items) { //UUID oldItemID = item.ItemID; item.ResetIDs (m_part.UUID); //LEAVE THIS COMMENTED!!! // When an object is duplicated, this will be called and it will destroy the original prims scripts!! // This needs to be moved to a place that is safer later // This was *originally* intended to be used on scripts that were crossing region borders /*if (m_part.ParentGroup != null) { lock (m_part.ParentGroup) { if (m_part.ParentGroup.Scene != null) { foreach (IScriptModule engine in m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>()) { engine.UpdateScriptToNewObject(oldItemID, item, m_part); } } } }*/ item.ResetIDs (m_part.UUID); Items.Add (item.ItemID, item); } } } /// <summary> /// Change every item in this inventory to a new owner. /// </summary> /// <param name="ownerId"></param> public void ChangeInventoryOwner(UUID ownerId) { lock (Items) { if (0 == Items.Count) { return; } } HasInventoryChanged = true; List<TaskInventoryItem> items = GetInventoryItems(); foreach (TaskInventoryItem item in items) { if (ownerId != item.OwnerID) { item.LastOwnerID = item.OwnerID; item.OwnerChanged = true; item.OwnerID = ownerId; item.PermsMask = 0; item.PermsGranter = UUID.Zero; } } } /// <summary> /// Change every item in this inventory to a new group. /// </summary> /// <param name="groupID"></param> public void ChangeInventoryGroup(UUID groupID) { lock (Items) { if (0 == Items.Count) { return; } } HasInventoryChanged = true; List<TaskInventoryItem> items = GetInventoryItems(); foreach (TaskInventoryItem item in items) { if (groupID != item.GroupID) item.GroupID = groupID; } } /// <summary> /// Start all the scripts contained in this prim's inventory /// </summary> public void CreateScriptInstances (int startParam, bool postOnRez, StateSource stateSource, UUID RezzedFrom, bool clearStateSaves) { List<TaskInventoryItem> LSLItems = GetInventoryScripts(); if (LSLItems.Count == 0) return; bool SendUpdate = m_part.AddFlag(PrimFlags.Scripted); m_part.ParentGroup.Scene.EventManager.TriggerRezScripts( m_part, LSLItems.ToArray(), startParam, postOnRez, stateSource, RezzedFrom, clearStateSaves); if(SendUpdate) m_part.ScheduleUpdate(PrimUpdateFlags.PrimFlags); //We only need to send a compressed ResumeScripts(); } public List<TaskInventoryItem> GetInventoryScripts() { List<TaskInventoryItem> ret = new List<TaskInventoryItem>(); lock (m_items) { #if (!ISWIN) foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType == (int)InventoryType.LSL) { if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID)) continue; ret.Add(item); } } #else ret.AddRange(m_items.Values.Where(item => item.InvType == (int)InventoryType.LSL).Where(item => m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID))); #endif } return ret; } public ArrayList GetScriptErrors(UUID itemID) { IScriptModule engine = m_part.ParentGroup.Scene.RequestModuleInterface<IScriptModule>(); if (engine == null) // No engine at all { ArrayList ret = new ArrayList {"No Script Engines available at this time."}; return ret; } return engine.GetScriptErrors(itemID); } /// <summary> /// Stop all the scripts in this prim. /// </summary> /// <param name="sceneObjectBeingDeleted"> /// Should be true if these scripts are being removed because the scene /// object is being deleted. This will prevent spurious updates to the client. /// </param> public void RemoveScriptInstances(bool sceneObjectBeingDeleted) { List<TaskInventoryItem> scripts = GetInventoryScripts(); foreach (TaskInventoryItem item in scripts) RemoveScriptInstance(item.ItemID, sceneObjectBeingDeleted); HasInventoryChanged = true; } /// <summary> /// Start a script which is in this prim's inventory. /// </summary> /// <param name="item"></param> /// <param name="startParam"></param> /// <param name="postOnRez"></param> /// <param name="stateSource"></param> /// <returns></returns> public void CreateScriptInstance (TaskInventoryItem item, int startParam, bool postOnRez, StateSource stateSource) { // MainConsole.Instance.InfoFormat( // "[PRIM INVENTORY]: " + // "Starting script {0}, {1} in prim {2}, {3}", // item.Name, item.ItemID, Name, UUID); if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID)) return; if (!m_part.ParentGroup.Scene.RegionInfo.RegionSettings.DisableScripts) { lock (m_itemsLock) { m_items[item.ItemID].PermsMask = 0; m_items[item.ItemID].PermsGranter = UUID.Zero; } bool SendUpdate = m_part.AddFlag (PrimFlags.Scripted); m_part.ParentGroup.Scene.EventManager.TriggerRezScripts ( m_part, new[] { item }, startParam, postOnRez, stateSource, UUID.Zero, false); if (SendUpdate) m_part.ScheduleUpdate (PrimUpdateFlags.PrimFlags); //We only need to send a compressed } HasInventoryChanged = true; ResumeScript(item); } /// <summary> /// Updates a script which is in this prim's inventory. /// </summary> /// <param name="item"></param> /// <returns></returns> public void UpdateScriptInstance (UUID itemID, byte[] assetData, int startParam, bool postOnRez, StateSource stateSource) { TaskInventoryItem item = m_items[itemID]; if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID)) return; m_part.AddFlag(PrimFlags.Scripted); if (!m_part.ParentGroup.Scene.RegionInfo.RegionSettings.DisableScripts) { lock (m_itemsLock) { m_items[item.ItemID].PermsMask = 0; m_items[item.ItemID].PermsGranter = UUID.Zero; } string script = Utils.BytesToString(assetData); IScriptModule[] modules = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); foreach (IScriptModule module in modules) { module.UpdateScript(m_part.UUID, item.ItemID, script, startParam, postOnRez, stateSource); } ResumeScript(item); } HasInventoryChanged = true; } /// <summary> /// Start a script which is in this prim's inventory. /// </summary> /// <param name="itemId"> /// A <see cref="UUID"/> /// </param> /// <param name="startParam"></param> /// <param name="postOnRez"></param> /// <param name="stateSource"></param> public void CreateScriptInstance (UUID itemId, int startParam, bool postOnRez, StateSource stateSource) { TaskInventoryItem item = GetInventoryItem(itemId); if (item != null) CreateScriptInstance(item, startParam, postOnRez, stateSource); else MainConsole.Instance.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't start script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}", itemId, m_part.Name, m_part.UUID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); } /// <summary> /// Stop a script which is in this prim's inventory. /// </summary> /// <param name="itemId"></param> /// <param name="sceneObjectBeingDeleted"> /// Should be true if this script is being removed because the scene /// object is being deleted. This will prevent spurious updates to the client. /// </param> public void RemoveScriptInstance(UUID itemId, bool sceneObjectBeingDeleted) { bool scriptPresent = false; lock (m_itemsLock) { if (m_items.ContainsKey (itemId)) scriptPresent = true; } if (scriptPresent) { if (!sceneObjectBeingDeleted) m_part.RemoveScriptEvents(itemId); m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemId); } else { MainConsole.Instance.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't stop script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}", itemId, m_part.Name, m_part.UUID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); } } /// <summary> /// Check if the inventory holds an item with a given name. /// </summary> /// <param name="name"></param> /// <returns></returns> private bool InventoryContainsName (string name) { lock (m_itemsLock) { #if (!ISWIN) foreach (TaskInventoryItem item in m_items.Values) { if (item.Name == name) { return true; } } #else if (m_items.Values.Any(item => item.Name == name)) { return true; } #endif } return false; } /// <summary> /// For a given item name, return that name if it is available. Otherwise, return the next available /// similar name (which is currently the original name with the next available numeric suffix). /// </summary> /// <param name="name"></param> /// <returns></returns> private string FindAvailableInventoryName(string name) { if (!InventoryContainsName(name)) return name; int suffix=1; while (suffix < 256) { string tryName=String.Format("{0} {1}", name, suffix); if (!InventoryContainsName(tryName)) return tryName; suffix++; } return String.Empty; } /// <summary> /// Add an item to this prim's inventory. If an item with the same name already exists, then an alternative /// name is chosen. /// </summary> /// <param name="item"></param> /// <param name="allowedDrop"></param> public void AddInventoryItem(TaskInventoryItem item, bool allowedDrop) { AddInventoryItem(item.Name, item, allowedDrop); } /// <summary> /// Add an item to this prim's inventory. If an item with the same name already exists, it is replaced. /// </summary> /// <param name="item"></param> /// <param name="allowedDrop"></param> public void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop) { List<TaskInventoryItem> il = GetInventoryItems(); foreach (TaskInventoryItem i in il) { if (i.Name == item.Name) { if (i.InvType == (int)InventoryType.LSL) RemoveScriptInstance(i.ItemID, false); RemoveInventoryItem(i.ItemID); break; } } AddInventoryItem(item.Name, item, allowedDrop); } /// <summary> /// Add an item to this prim's inventory. /// </summary> /// <param name="name">The name that the new item should have.</param> /// <param name="item"> /// The item itself. The name within this structure is ignored in favour of the name /// given in this method's arguments /// </param> /// <param name="allowedDrop"> /// Item was only added to inventory because AllowedDrop is set /// </param> protected void AddInventoryItem(string name, TaskInventoryItem item, bool allowedDrop) { name = FindAvailableInventoryName(name); if (name == String.Empty) return; item.ParentID = m_part.UUID; item.ParentPartID = m_part.UUID; item.Name = name; item.GroupID = m_part.GroupID; lock (m_itemsLock) { m_items.Add (item.ItemID, item); } m_part.TriggerScriptChangedEvent(allowedDrop ? Changed.ALLOWED_DROP : Changed.INVENTORY); m_inventorySerial++; //m_inventorySerial += 2; HasInventoryChanged = true; } /// <summary> /// Restore a whole collection of items to the prim's inventory at once. /// We assume that the items already have all their fields correctly filled out. /// The items are not flagged for persistence to the database, since they are being restored /// from persistence rather than being newly added. /// </summary> /// <param name="items"></param> public void RestoreInventoryItems (ICollection<TaskInventoryItem> items) { lock (m_itemsLock) { foreach (TaskInventoryItem item in items) { m_items.Add (item.ItemID, item); // m_part.TriggerScriptChangedEvent(Changed.INVENTORY); } m_inventorySerial++; } } /// <summary> /// Returns an existing inventory item. Returns the original, so any changes will be live. /// </summary> /// <param name="itemId"></param> /// <returns>null if the item does not exist</returns> public TaskInventoryItem GetInventoryItem(UUID itemId) { TaskInventoryItem item; lock (m_itemsLock) { m_items.TryGetValue (itemId, out item); } return item; } /// <summary> /// Get inventory items by name. /// </summary> /// <param name="name"></param> /// <returns> /// A list of inventory items with that name. /// If no inventory item has that name then an empty list is returned. /// </returns> public IList<TaskInventoryItem> GetInventoryItems (string name) { IList<TaskInventoryItem> items = new List<TaskInventoryItem> (); lock (m_itemsLock) { foreach (TaskInventoryItem item in m_items.Values) { if (item.Name == name) items.Add (item); } } return items; } public ISceneEntity GetRezReadySceneObject (TaskInventoryItem item) { AssetBase rezAsset = m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString()); if (null == rezAsset) { MainConsole.Instance.WarnFormat( "[PRIM INVENTORY]: Could not find asset {0} for inventory item {1} in {2}", item.AssetID, item.Name, m_part.Name); return null; } string xmlData = Utils.BytesToString(rezAsset.Data); SceneObjectGroup group = SceneObjectSerializer.FromOriginalXmlFormat(xmlData, m_part.ParentGroup.Scene); if (group == null) return null; group.IsDeleted = false; group.m_isLoaded = true; foreach (SceneObjectPart part in group.ChildrenList) { part.IsLoading = false; } //Reset IDs, etc m_part.ParentGroup.Scene.SceneGraph.PrepPrimForAdditionToScene(group); SceneObjectPart rootPart = (SceneObjectPart)group.GetChildPart(group.UUID); // Since renaming the item in the inventory does not affect the name stored // in the serialization, transfer the correct name from the inventory to the // object itself before we rez. rootPart.Name = item.Name; rootPart.Description = item.Description; SceneObjectPart[] partList = group.Parts; group.SetGroup(m_part.GroupID, group.OwnerID, false); if ((rootPart.OwnerID != item.OwnerID) || (item.CurrentPermissions & 16) != 0) { if (m_part.ParentGroup.Scene.Permissions.PropagatePermissions()) { foreach (SceneObjectPart part in partList) { part.EveryoneMask = item.EveryonePermissions; part.NextOwnerMask = item.NextPermissions; } group.ApplyNextOwnerPermissions(); } } foreach (SceneObjectPart part in partList) { if ((part.OwnerID != item.OwnerID) || (item.CurrentPermissions & 16) != 0) { part.LastOwnerID = part.OwnerID; part.OwnerID = item.OwnerID; part.Inventory.ChangeInventoryOwner(item.OwnerID); } part.EveryoneMask = item.EveryonePermissions; part.NextOwnerMask = item.NextPermissions; } rootPart.TrimPermissions(); return group; } /// <summary> /// Update an existing inventory item. /// </summary> /// <param name="item">The updated item. An item with the same id must already exist /// in this prim's inventory.</param> /// <returns>false if the item did not exist, true if the update occurred successfully</returns> public bool UpdateInventoryItem(TaskInventoryItem item) { return UpdateInventoryItem(item, true); } public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents) { TaskInventoryItem it = GetInventoryItem(item.ItemID); if (it != null) { item.ParentID = m_part.UUID; item.ParentPartID = m_part.UUID; item.Flags = m_items[item.ItemID].Flags; // If group permissions have been set on, check that the groupID is up to date in case it has // changed since permissions were last set. if (item.GroupPermissions != (uint)PermissionMask.None) item.GroupID = m_part.GroupID; if (item.AssetID == UUID.Zero) item.AssetID = it.AssetID; lock (m_itemsLock) { m_items[item.ItemID] = item; m_inventorySerial++; } if (fireScriptEvents) m_part.TriggerScriptChangedEvent(Changed.INVENTORY); HasInventoryChanged = true; return true; } MainConsole.Instance.ErrorFormat( "[PRIM INVENTORY]: " + "Tried to retrieve item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory", item.ItemID, m_part.Name, m_part.UUID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); return false; } /// <summary> /// Remove an item from this prim's inventory /// </summary> /// <param name="itemID"></param> /// <returns>Numeric asset type of the item removed. Returns -1 if the item did not exist /// in this prim's inventory.</returns> public int RemoveInventoryItem(UUID itemID) { TaskInventoryItem item = GetInventoryItem(itemID); if (item != null) { int type = m_items[itemID].InvType; if (type == 10) // Script { m_part.RemoveScriptEvents(itemID); m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemID); } m_items.Remove(itemID); m_inventorySerial++; m_part.TriggerScriptChangedEvent(Changed.INVENTORY); HasInventoryChanged = true; if (!ContainsScripts()) { if (m_part.RemFlag(PrimFlags.Scripted)) m_part.ScheduleUpdate(PrimUpdateFlags.PrimFlags); } return type; } return -1; } /// <summary> /// Returns true if the file needs to be rebuild, false if it does not /// </summary> /// <returns></returns> public bool GetInventoryFileName() { if (m_inventoryFileName == String.Empty || m_inventoryFileNameSerial < m_inventorySerial) { m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp"; m_inventoryFileNameSerial = m_inventorySerial; return true; //We had to change the filename, need to rebuild the file } return false; } /// <summary> /// Serialize all the metadata for the items in this prim's inventory ready for sending to the client /// </summary> /// <param name="client"></param> public void RequestInventoryFile(IClientAPI client) { IXfer xferManager = client.Scene.RequestModuleInterface<IXfer> (); if (m_inventorySerial == 0) { //No inventory, no sending client.SendTaskInventory(m_part.UUID, 0, new byte[0]); return; } //If update == true, we need to recreate the file for the client bool Update = GetInventoryFileName(); if (!Update) { //We don't need to update the fileData, so just send the cached info and exit out of this method if (m_fileData.Length > 2) { client.SendTaskInventory (m_part.UUID, (short)m_inventorySerial, Utils.StringToBytes (m_inventoryFileName)); xferManager.AddNewFile(m_inventoryFileName, m_fileData); } else client.SendTaskInventory (m_part.UUID, 0, new byte[0]); return; } // Confusingly, the folder item has to be the object id, while the 'parent id' has to be zero. This matches // what appears to happen in the Second Life protocol. If this isn't the case. then various functionality // isn't available (such as drag from prim inventory to agent inventory) InventoryStringBuilder invString = new InventoryStringBuilder(m_part.UUID, UUID.Zero); bool includeAssets = false; if (m_part.ParentGroup.Scene.Permissions.CanEditObjectInventory(m_part.UUID, client.AgentId)) includeAssets = true; List<TaskInventoryItem> items = m_items.Clone2List(); foreach (TaskInventoryItem item in items) { UUID ownerID = item.OwnerID; const uint everyoneMask = 0; uint baseMask = item.BasePermissions; uint ownerMask = item.CurrentPermissions; uint groupMask = item.GroupPermissions; invString.AddItemStart (); invString.AddNameValueLine ("item_id", item.ItemID.ToString ()); invString.AddNameValueLine ("parent_id", m_part.UUID.ToString ()); invString.AddPermissionsStart (); invString.AddNameValueLine ("base_mask", Utils.UIntToHexString (baseMask)); invString.AddNameValueLine ("owner_mask", Utils.UIntToHexString (ownerMask)); invString.AddNameValueLine ("group_mask", Utils.UIntToHexString (groupMask)); invString.AddNameValueLine ("everyone_mask", Utils.UIntToHexString (everyoneMask)); invString.AddNameValueLine ("next_owner_mask", Utils.UIntToHexString (item.NextPermissions)); invString.AddNameValueLine ("creator_id", item.CreatorID.ToString ()); invString.AddNameValueLine ("owner_id", ownerID.ToString ()); invString.AddNameValueLine ("last_owner_id", item.LastOwnerID.ToString ()); invString.AddNameValueLine ("group_id", item.GroupID.ToString ()); invString.AddSectionEnd (); invString.AddNameValueLine("asset_id", includeAssets ? item.AssetID.ToString() : UUID.Zero.ToString()); invString.AddNameValueLine ("type", TaskInventoryItemHelpers.Types[item.Type]); invString.AddNameValueLine ("inv_type", TaskInventoryItemHelpers.InvTypes[item.InvType]); invString.AddNameValueLine ("flags", Utils.UIntToHexString (item.Flags)); invString.AddSaleStart (); invString.AddNameValueLine ("sale_type", TaskInventoryItemHelpers.SaleTypes[item.SaleType]); invString.AddNameValueLine ("sale_price", item.SalePrice.ToString ()); invString.AddSectionEnd (); invString.AddNameValueLine ("name", item.Name + "|"); invString.AddNameValueLine ("desc", item.Description + "|"); invString.AddNameValueLine ("creation_date", item.CreationDate.ToString ()); invString.AddSectionEnd (); } string str = invString.GetString(); if(str.Length > 0) str = str.Substring(0, str.Length - 1); m_fileData = Utils.StringToBytes(str); //MainConsole.Instance.Debug(Utils.BytesToString(fileData)); //MainConsole.Instance.Debug("[PRIM INVENTORY]: RequestInventoryFile fileData: " + Utils.BytesToString(fileData)); if (m_fileData.Length > 2) { client.SendTaskInventory (m_part.UUID, (short)m_inventorySerial, Utils.StringToBytes (m_inventoryFileName)); xferManager.AddNewFile(m_inventoryFileName, m_fileData); } else client.SendTaskInventory (m_part.UUID, 0, new byte[0]); } public void SaveScriptStateSaves() { IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); if (engines != null) { List<TaskInventoryItem> items = GetInventoryItems(); foreach (TaskInventoryItem item in items) { if (item.Type == (int)InventoryType.LSL) { foreach (IScriptModule engine in engines) { if (engine != null) { //NOTE: We will need to save the prim if we do this engine.SaveStateSave(item.ItemID, m_part.UUID); } } } } } } public class InventoryStringBuilder { private StringBuilder BuildString = new StringBuilder(); private bool _hasAddeditems = false; public string GetString() { if (_hasAddeditems) return BuildString.ToString(); return ""; } public InventoryStringBuilder(UUID folderID, UUID parentID) { BuildString.Append("\tinv_object\t0\n\t{\n"); AddNameValueLine("obj_id", folderID.ToString()); AddNameValueLine("parent_id", parentID.ToString()); AddNameValueLine("type", "category"); AddNameValueLine("name", "Contents|"); AddSectionEnd(); } public void AddItemStart() { _hasAddeditems = true; BuildString.Append("\tinv_item\t0\n"); AddSectionStart(); } public void AddPermissionsStart() { BuildString.Append("\tpermissions 0\n"); AddSectionStart(); } public void AddSaleStart() { BuildString.Append("\tsale_info\t0\n"); AddSectionStart(); } protected void AddSectionStart() { BuildString.Append("\t{\n"); } public void AddSectionEnd() { BuildString.Append("\t}\n"); } public void AddLine(string addLine) { BuildString.Append(addLine); } public void AddNameValueLine(string name, string value) { BuildString.Append("\t\t"); BuildString.Append( name + "\t"); BuildString.Append(value + "\n"); } public void Close() { } } public uint MaskEffectivePermissions () { uint mask = 0x7fffffff; lock (m_itemsLock) { foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType != (int)InventoryType.Object) { if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0) mask &= ~((uint)PermissionMask.Copy >> 13); if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0) mask &= ~((uint)PermissionMask.Transfer >> 13); if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0) mask &= ~((uint)PermissionMask.Modify >> 13); } else { if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0) mask &= ~((uint)PermissionMask.Copy >> 13); if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0) mask &= ~((uint)PermissionMask.Transfer >> 13); if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0) mask &= ~((uint)PermissionMask.Modify >> 13); } if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) mask &= ~(uint)PermissionMask.Copy; if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0) mask &= ~(uint)PermissionMask.Transfer; if ((item.CurrentPermissions & (uint)PermissionMask.Modify) == 0) mask &= ~(uint)PermissionMask.Modify; } } return mask; } public void ApplyNextOwnerPermissions () { lock (m_itemsLock) { foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0) { if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0) item.CurrentPermissions &= ~(uint)PermissionMask.Copy; if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0) item.CurrentPermissions &= ~(uint)PermissionMask.Transfer; if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0) item.CurrentPermissions &= ~(uint)PermissionMask.Modify; } item.CurrentPermissions &= item.NextPermissions; item.BasePermissions &= item.NextPermissions; item.EveryonePermissions &= item.NextPermissions; item.OwnerChanged = true; item.PermsMask = 0; item.PermsGranter = UUID.Zero; } } } public void ApplyGodPermissions (uint perms) { lock (m_itemsLock) { foreach (TaskInventoryItem item in m_items.Values) { item.CurrentPermissions = perms; item.BasePermissions = perms; } } } public bool ContainsScripts () { lock (m_itemsLock) { #if (!ISWIN) foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType == (int) InventoryType.LSL) { return true; } } #else if (m_items.Values.Any(item => item.InvType == (int)InventoryType.LSL)) { return true; } #endif } return false; } public List<UUID> GetInventoryList() { List<UUID> ret = new List<UUID>(); lock (m_itemsLock) { #if (!ISWIN) foreach (TaskInventoryItem item in m_items.Values) ret.Add(item.ItemID); #else ret.AddRange(m_items.Values.Select(item => item.ItemID)); #endif } return ret; } public List<TaskInventoryItem> GetInventoryItems() { List<TaskInventoryItem> ret = new List<TaskInventoryItem>(); lock (m_itemsLock) { ret.AddRange(m_items.Values); } return ret; } public void ResumeScripts() { List<TaskInventoryItem> scripts = GetInventoryScripts(); foreach (TaskInventoryItem item in scripts) { ResumeScript(item); } } private void ResumeScript(TaskInventoryItem item) { IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); if (engines == null) return; foreach (IScriptModule engine in engines) { if (engine != null) { engine.ResumeScript(item.ItemID); if (item.OwnerChanged) engine.PostScriptEvent(item.ItemID, m_part.UUID, "changed", new Object[] { (int)Changed.OWNER }); item.OwnerChanged = false; } } } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using NUnit.TestUtilities; using System; using System.IO; namespace NUnit.Framework.Assertions { [TestFixture] public class AssertEqualsTests { [Test] public void Equals() { string nunitString = "Hello NUnit"; string expected = nunitString; string actual = nunitString; Assert.IsTrue(expected == actual); Assert.AreEqual(expected, actual); } [Test] public void EqualsNull() { Assert.AreEqual(null, null); } [Test] public void Bug575936Int32Int64Comparison() { long l64 = 0; int i32 = 0; Assert.AreEqual(i32, l64); } [Test] public void Bug524CharIntComparison() { char c = '\u0000'; Assert.AreEqual(0, c); } [Test] public void Bug524CharIntWithoutOverload() { char c = '\u0000'; Assert.That(c, Is.EqualTo(0)); } [Test] public void CharCharComparison() { char c = 'a'; Assert.That(c, Is.EqualTo('a')); } [Test] public void IntegerLongComparison() { Assert.AreEqual(1, 1L); Assert.AreEqual(1L, 1); } [Test] public void IntegerEquals() { int val = 42; Assert.AreEqual(val, 42); } [Test] public void EqualsFail() { string junitString = "Goodbye JUnit"; string expected = "Hello NUnit"; var expectedMessage = " Expected string length 11 but was 13. Strings differ at index 0." + Environment.NewLine + " Expected: \"Hello NUnit\"" + Environment.NewLine + " But was: \"Goodbye JUnit\"" + Environment.NewLine + " -----------^" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(expected, junitString)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void EqualsNaNFails() { var expectedMessage = " Expected: 1.234d +/- 0.0d" + Environment.NewLine + " But was: " + Double.NaN + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(1.234, Double.NaN, 0.0)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void NanEqualsFails() { var expectedMessage = " Expected: " + Double.NaN + Environment.NewLine + " But was: 1.234d" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(Double.NaN, 1.234, 0.0)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void NanEqualsNaNSucceeds() { Assert.AreEqual(Double.NaN, Double.NaN, 0.0); } [Test] public void NegInfinityEqualsInfinity() { Assert.AreEqual(Double.NegativeInfinity, Double.NegativeInfinity, 0.0); } [Test] public void PosInfinityEqualsInfinity() { Assert.AreEqual(Double.PositiveInfinity, Double.PositiveInfinity, 0.0); } [Test] public void PosInfinityNotEquals() { var expectedMessage = " Expected: " + Double.PositiveInfinity + Environment.NewLine + " But was: 1.23d" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(Double.PositiveInfinity, 1.23, 0.0)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void PosInfinityNotEqualsNegInfinity() { var expectedMessage = " Expected: " + Double.PositiveInfinity + Environment.NewLine + " But was: " + Double.NegativeInfinity + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(Double.PositiveInfinity, Double.NegativeInfinity, 0.0)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void SinglePosInfinityNotEqualsNegInfinity() { var expectedMessage = " Expected: " + Double.PositiveInfinity + Environment.NewLine + " But was: " + Double.NegativeInfinity + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(float.PositiveInfinity, float.NegativeInfinity, (float)0.0)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void EqualsThrowsException() { object o = new object(); Assert.Throws<InvalidOperationException>(() => Assert.Equals(o, o)); } [Test] public void ReferenceEqualsThrowsException() { object o = new object(); Assert.Throws<InvalidOperationException>(() => Assert.ReferenceEquals(o, o)); } [Test] public void Float() { float val = (float)1.0; float expected = val; float actual = val; Assert.IsTrue(expected == actual); Assert.AreEqual(expected, actual, (float)0.0); } [Test] public void Byte() { byte val = 1; byte expected = val; byte actual = val; Assert.IsTrue(expected == actual); Assert.AreEqual(expected, actual); } [Test] public void String() { string s1 = "test"; string s2 = new System.Text.StringBuilder(s1).ToString(); Assert.IsTrue(s1.Equals(s2)); Assert.AreEqual(s1,s2); } [Test] public void Short() { short val = 1; short expected = val; short actual = val; Assert.IsTrue(expected == actual); Assert.AreEqual(expected, actual); } [Test] public void Int() { int val = 1; int expected = val; int actual = val; Assert.IsTrue(expected == actual); Assert.AreEqual(expected, actual); } [Test] public void UInt() { uint val = 1; uint expected = val; uint actual = val; Assert.IsTrue(expected == actual); Assert.AreEqual(expected, actual); } [Test] public void Decimal() { decimal expected = 100m; decimal actual = 100.0m; int integer = 100; Assert.IsTrue( expected == actual ); Assert.AreEqual(expected, actual); Assert.IsTrue(expected == integer); Assert.AreEqual(expected, integer); Assert.IsTrue(actual == integer); Assert.AreEqual(actual, integer); } /// <summary> /// Checks to see that a value comparison works with all types. /// Current version has problems when value is the same but the /// types are different...C# is not like Java, and doesn't automatically /// perform value type conversion to simplify this type of comparison. /// /// Related to Bug575936Int32Int64Comparison, but covers all numeric /// types. /// </summary> [Test] public void EqualsSameTypes() { byte b1 = 35; sbyte sb2 = 35; decimal d4 = 35; double d5 = 35; float f6 = 35; int i7 = 35; uint u8 = 35; long l9 = 35; short s10 = 35; ushort us11 = 35; char c1 = '3'; char c2 = 'a'; System.Byte b12 = 35; System.SByte sb13 = 35; System.Decimal d14 = 35; System.Double d15 = 35; System.Single s16 = 35; System.Int32 i17 = 35; System.UInt32 ui18 = 35; System.Int64 i19 = 35; System.UInt64 ui20 = 35; System.Int16 i21 = 35; System.UInt16 i22 = 35; System.Char c12 = '3'; System.Char c22 = 'a'; Assert.AreEqual(35, b1); Assert.AreEqual(35, sb2); Assert.AreEqual(35, d4); Assert.AreEqual(35, d5); Assert.AreEqual(35, f6); Assert.AreEqual(35, i7); Assert.AreEqual(35, u8); Assert.AreEqual(35, l9); Assert.AreEqual(35, s10); Assert.AreEqual(35, us11); Assert.AreEqual('3', c1); Assert.AreEqual('a', c2); Assert.AreEqual( 35, b12 ); Assert.AreEqual( 35, sb13 ); Assert.AreEqual( 35, d14 ); Assert.AreEqual( 35, d15 ); Assert.AreEqual( 35, s16 ); Assert.AreEqual( 35, i17 ); Assert.AreEqual( 35, ui18 ); Assert.AreEqual( 35, i19 ); Assert.AreEqual( 35, ui20 ); Assert.AreEqual( 35, i21 ); Assert.AreEqual( 35, i22 ); Assert.AreEqual('3', c12); Assert.AreEqual('a', c22); byte? b23 = 35; sbyte? sb24 = 35; decimal? d25 = 35; double? d26 = 35; float? f27 = 35; int? i28 = 35; uint? u29 = 35; long? l30 = 35; short? s31 = 35; ushort? us32 = 35; char? c3 = '3'; char? c4 = 'a'; Assert.AreEqual(35, b23); Assert.AreEqual(35, sb24); Assert.AreEqual(35, d25); Assert.AreEqual(35, d26); Assert.AreEqual(35, f27); Assert.AreEqual(35, i28); Assert.AreEqual(35, u29); Assert.AreEqual(35, l30); Assert.AreEqual(35, s31); Assert.AreEqual(35, us32); Assert.AreEqual('3', c3); Assert.AreEqual('a', c4); } [Test] public void EnumsEqual() { MyEnum actual = MyEnum.A; Assert.AreEqual(MyEnum.A, actual); } [Test] public void EnumsNotEqual() { MyEnum actual = MyEnum.A; var expectedMessage = " Expected: " + nameof(MyEnum.C) + Environment.NewLine + " But was: " + nameof(MyEnum.A) + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(MyEnum.C, actual)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void DateTimeEqual() { DateTime dt1 = new DateTime( 2005, 6, 1, 7, 0, 0 ); DateTime dt2 = new DateTime( 2005, 6, 1, 0, 0, 0 ) + TimeSpan.FromHours( 7.0 ); Assert.AreEqual( dt1, dt2 ); } [Test] public void DateTimeNotEqual_DifferenceInHours() { DateTime dt1 = new DateTime( 2005, 6, 1, 7, 0, 0 ); DateTime dt2 = new DateTime( 2005, 6, 1, 0, 0, 0 ); var expectedMessage = " Expected: 2005-06-01 07:00:00" + Environment.NewLine + " But was: 2005-06-01 00:00:00" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(dt1, dt2)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void DateTimeNotEqual_DifferenceInTicks() { DateTime dt1 = new DateTime(1914, 06, 28, 12, 00, 00); DateTime dt2 = dt1.AddTicks(666); var expectedMessage = " Expected: 1914-06-28 12:00:00" + Environment.NewLine + " But was: 1914-06-28 12:00:00.0000666" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(dt1, dt2)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void DirectoryInfoEqual() { using (var testDir = new TestDirectory()) { var one = new DirectoryInfo(testDir.Directory.FullName); var two = new DirectoryInfo(testDir.Directory.FullName); Assert.AreEqual(one, two); } } [Test] public void DirectoryInfoNotEqual() { using (var one = new TestDirectory()) using (var two = new TestDirectory()) { Assert.Throws<AssertionException>(() => Assert.AreEqual(one.Directory, two.Directory)); } } private enum MyEnum { A, B, C } [Test] public void DoubleNotEqualMessageDisplaysAllDigits() { double d1 = 36.1; double d2 = 36.099999999999994; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(d1, d2) ); var message = ex.Message; int i = message.IndexOf('3'); int j = message.IndexOf( 'd', i ); string expected = message.Substring( i, j - i + 1 ); i = message.IndexOf( '3', j ); j = message.IndexOf( 'd', i ); string actual = message.Substring( i , j - i + 1 ); Assert.AreNotEqual( expected, actual ); } [Test] public void FloatNotEqualMessageDisplaysAllDigits() { float f1 = 36.125F; float f2 = 36.125004F; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(f1, f2)); var message = ex.Message; int i = message.IndexOf( '3' ); int j = message.IndexOf( 'f', i ); string expected = message.Substring( i, j - i + 1 ); i = message.IndexOf( '3', j ); j = message.IndexOf( 'f', i ); string actual = message.Substring( i, j - i + 1 ); Assert.AreNotEqual( expected, actual ); } [Test] public void DoubleNotEqualMessageDisplaysTolerance() { double d1 = 0.15; double d2 = 0.12; double tol = 0.005; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(d1, d2, tol)); Assert.That(ex.Message, Does.Contain("+/- 0.005")); } [Test] public void FloatNotEqualMessageDisplaysTolerance() { float f1 = 0.15F; float f2 = 0.12F; float tol = 0.001F; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual( f1, f2, tol )); Assert.That(ex.Message, Does.Contain( "+/- 0.001")); } [Test, DefaultFloatingPointTolerance(0.005)] public void DoubleNotEqualMessageDisplaysDefaultTolerance() { double d1 = 0.15; double d2 = 0.12; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(d1, d2)); Assert.That(ex.Message, Does.Contain("+/- 0.005")); } [Test, DefaultFloatingPointTolerance(0.005)] public void DoubleNotEqualWithNanDoesNotDisplayDefaultTolerance() { double d1 = double.NaN; double d2 = 0.12; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(d1, d2)); Assert.That(ex.Message.IndexOf("+/-") == -1); } [Test] public void IEquatableSuccess_OldSyntax() { IntEquatable a = new IntEquatable(1); Assert.AreEqual(1, a); Assert.AreEqual(a, 1); } [Test] public void IEquatableSuccess_ConstraintSyntax() { IntEquatable a = new IntEquatable(1); Assert.That(a, Is.EqualTo(1)); Assert.That(1, Is.EqualTo(a)); } [Test] public void EqualsFailsWhenUsed() { var ex = Assert.Throws<InvalidOperationException>(() => Assert.Equals(string.Empty, string.Empty)); Assert.That(ex.Message, Does.StartWith("Assert.Equals should not be used.")); } [Test] public void ReferenceEqualsFailsWhenUsed() { var ex = Assert.Throws<InvalidOperationException>(() => Assert.ReferenceEquals(string.Empty, string.Empty)); Assert.That(ex.Message, Does.StartWith("Assert.ReferenceEquals should not be used.")); } [Test] public void ShouldNotCallToStringOnClassForPassingTests() { var actual = new ThrowsIfToStringIsCalled(1); var expected = new ThrowsIfToStringIsCalled(1); Assert.AreEqual(expected, actual); } class IntEquatable : IEquatable<int> { readonly int i; public IntEquatable(int i) { this.i = i; } public bool Equals(int other) { return i.Equals(other); } } } /// <summary> /// This class is for testing issue #1301 where ToString() is called on /// a class to create the description of the constraint even where that /// description is not used because the test passes. /// </summary> internal class ThrowsIfToStringIsCalled { readonly int _x; public ThrowsIfToStringIsCalled(int x) { _x = x; } public override bool Equals(object obj) { if (obj == null) return false; var other = obj as ThrowsIfToStringIsCalled; if (other == null) return false; return _x == other._x; } public override int GetHashCode() { return _x; } public override string ToString() { Assert.Fail("Should not call ToString() if Assert does not fail"); return base.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. namespace System.Xml.Xsl.XsltOld { using System.Diagnostics; using System.IO; using System.Globalization; using System.Collections; using System.Xml.XPath; using System.Xml.Xsl.Runtime; using MS.Internal.Xml.XPath; using System.Reflection; using System.Security; using System.Runtime.Versioning; internal class XsltCompileContext : XsltContext { private InputScopeManager _manager; private Processor _processor; // storage for the functions private static Hashtable s_FunctionTable = CreateFunctionTable(); private static IXsltContextFunction s_FuncNodeSet = new FuncNodeSet(); private const string f_NodeSet = "node-set"; internal XsltCompileContext(InputScopeManager manager, Processor processor) : base(/*dummy*/false) { _manager = manager; _processor = processor; } internal XsltCompileContext() : base(/*dummy*/ false) { } internal void Recycle() { _manager = null; _processor = null; } internal void Reinitialize(InputScopeManager manager, Processor processor) { _manager = manager; _processor = processor; } public override int CompareDocument(string baseUri, string nextbaseUri) { return String.Compare(baseUri, nextbaseUri, StringComparison.Ordinal); } // Namespace support public override string DefaultNamespace { get { return string.Empty; } } public override string LookupNamespace(string prefix) { return _manager.ResolveXPathNamespace(prefix); } // --------------------------- XsltContext ------------------- // Resolving variables and functions public override IXsltContextVariable ResolveVariable(string prefix, string name) { string namespaceURI = this.LookupNamespace(prefix); XmlQualifiedName qname = new XmlQualifiedName(name, namespaceURI); IXsltContextVariable variable = _manager.VariableScope.ResolveVariable(qname); if (variable == null) { throw XsltException.Create(SR.Xslt_InvalidVariable, qname.ToString()); } return variable; } internal object EvaluateVariable(VariableAction variable) { Object result = _processor.GetVariableValue(variable); if (result == null && !variable.IsGlobal) { // This was uninitialized local variable. May be we have sutable global var too? VariableAction global = _manager.VariableScope.ResolveGlobalVariable(variable.Name); if (global != null) { result = _processor.GetVariableValue(global); } } if (result == null) { throw XsltException.Create(SR.Xslt_InvalidVariable, variable.Name.ToString()); } return result; } // Whitespace stripping support public override bool Whitespace { get { return _processor.Stylesheet.Whitespace; } } public override bool PreserveWhitespace(XPathNavigator node) { node = node.Clone(); node.MoveToParent(); return _processor.Stylesheet.PreserveWhiteSpace(_processor, node); } private MethodInfo FindBestMethod(MethodInfo[] methods, bool ignoreCase, bool publicOnly, string name, XPathResultType[] argTypes) { int length = methods.Length; int free = 0; // restrict search to methods with the same name and requiested protection attribute for (int i = 0; i < length; i++) { if (string.Compare(name, methods[i].Name, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0) { if (!publicOnly || methods[i].GetBaseDefinition().IsPublic) { methods[free++] = methods[i]; } } } length = free; if (length == 0) { // this is the only place we returning null in this function return null; } if (argTypes == null) { // without arg types we can't do more detailed search return methods[0]; } // restrict search by number of parameters free = 0; for (int i = 0; i < length; i++) { if (methods[i].GetParameters().Length == argTypes.Length) { methods[free++] = methods[i]; } } length = free; if (length <= 1) { // 0 -- not method found. We have to return non-null and let it fail with correct exception on call. // 1 -- no reason to continue search anyway. return methods[0]; } // restrict search by parameters type free = 0; for (int i = 0; i < length; i++) { bool match = true; ParameterInfo[] parameters = methods[i].GetParameters(); for (int par = 0; par < parameters.Length; par++) { XPathResultType required = argTypes[par]; if (required == XPathResultType.Any) { continue; // Any means we don't know type and can't discriminate by it } XPathResultType actual = GetXPathType(parameters[par].ParameterType); if ( actual != required && actual != XPathResultType.Any // actual arg is object and we can pass everithing here. ) { match = false; break; } } if (match) { methods[free++] = methods[i]; } } length = free; return methods[0]; } private const BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; private IXsltContextFunction GetExtentionMethod(string ns, string name, XPathResultType[] argTypes, out object extension) { FuncExtension result = null; extension = _processor.GetScriptObject(ns); if (extension != null) { MethodInfo method = FindBestMethod(extension.GetType().GetMethods(bindingFlags), /*ignoreCase:*/true, /*publicOnly:*/false, name, argTypes); if (method != null) { result = new FuncExtension(extension, method); } return result; } extension = _processor.GetExtensionObject(ns); if (extension != null) { MethodInfo method = FindBestMethod(extension.GetType().GetMethods(bindingFlags), /*ignoreCase:*/false, /*publicOnly:*/true, name, argTypes); if (method != null) { result = new FuncExtension(extension, method); } return result; } return null; } public override IXsltContextFunction ResolveFunction(string prefix, string name, XPathResultType[] argTypes) { IXsltContextFunction func = null; if (prefix.Length == 0) { func = s_FunctionTable[name] as IXsltContextFunction; } else { string ns = this.LookupNamespace(prefix); if (ns == XmlReservedNs.NsMsxsl && name == f_NodeSet) { func = s_FuncNodeSet; } else { object extension; func = GetExtentionMethod(ns, name, argTypes, out extension); if (extension == null) { throw XsltException.Create(SR.Xslt_ScriptInvalidPrefix, prefix); // BugBug: It's better to say that method 'name' not found } } } if (func == null) { throw XsltException.Create(SR.Xslt_UnknownXsltFunction, name); } if (argTypes.Length < func.Minargs || func.Maxargs < argTypes.Length) { throw XsltException.Create(SR.Xslt_WrongNumberArgs, name, argTypes.Length.ToString(CultureInfo.InvariantCulture)); } return func; } // // Xslt Function Extensions to XPath // private Uri ComposeUri(string thisUri, string baseUri) { Debug.Assert(thisUri != null && baseUri != null); XmlResolver resolver = _processor.Resolver; Uri uriBase = null; if (baseUri.Length != 0) { uriBase = resolver.ResolveUri(null, baseUri); } return resolver.ResolveUri(uriBase, thisUri); } private XPathNodeIterator Document(object arg0, string baseUri) { XPathNodeIterator it = arg0 as XPathNodeIterator; if (it != null) { ArrayList list = new ArrayList(); Hashtable documents = new Hashtable(); while (it.MoveNext()) { Uri uri = ComposeUri(it.Current.Value, baseUri ?? it.Current.BaseURI); if (!documents.ContainsKey(uri)) { documents.Add(uri, null); list.Add(_processor.GetNavigator(uri)); } } return new XPathArrayIterator(list); } else { return new XPathSingletonIterator( _processor.GetNavigator( ComposeUri(XmlConvert.ToXPathString(arg0), baseUri ?? _manager.Navigator.BaseURI) ) ); } } private Hashtable BuildKeyTable(Key key, XPathNavigator root) { Hashtable keyTable = new Hashtable(); string matchStr = _processor.GetQueryExpression(key.MatchKey); Query matchExpr = _processor.GetCompiledQuery(key.MatchKey); Query useExpr = _processor.GetCompiledQuery(key.UseKey); XPathNodeIterator sel = root.SelectDescendants(XPathNodeType.All, /*matchSelf:*/ false); while (sel.MoveNext()) { XPathNavigator node = sel.Current; EvaluateKey(node, matchExpr, matchStr, useExpr, keyTable); if (node.MoveToFirstAttribute()) { do { EvaluateKey(node, matchExpr, matchStr, useExpr, keyTable); } while (node.MoveToNextAttribute()); node.MoveToParent(); } } return keyTable; } private static void AddKeyValue(Hashtable keyTable, String key, XPathNavigator value, bool checkDuplicates) { ArrayList list = (ArrayList)keyTable[key]; if (list == null) { list = new ArrayList(); keyTable.Add(key, list); } else { Debug.Assert( value.ComparePosition((XPathNavigator)list[list.Count - 1]) != XmlNodeOrder.Before, "The way we traversing nodes should garantees node-order" ); if (checkDuplicates) { // it's posible that this value already was assosiated with current node // but if this happened the node is last in the list of values. if (value.ComparePosition((XPathNavigator)list[list.Count - 1]) == XmlNodeOrder.Same) { return; } } else { Debug.Assert( value.ComparePosition((XPathNavigator)list[list.Count - 1]) != XmlNodeOrder.Same, "checkDuplicates == false : We can't have duplicates" ); } } list.Add(value.Clone()); } private static void EvaluateKey(XPathNavigator node, Query matchExpr, string matchStr, Query useExpr, Hashtable keyTable) { try { if (matchExpr.MatchNode(node) == null) { return; } } catch (XPathException) { throw XsltException.Create(SR.Xslt_InvalidPattern, matchStr); } object result = useExpr.Evaluate(new XPathSingletonIterator(node, /*moved:*/true)); XPathNodeIterator it = result as XPathNodeIterator; if (it != null) { bool checkDuplicates = false; while (it.MoveNext()) { AddKeyValue(keyTable, /*key:*/it.Current.Value, /*value:*/node, checkDuplicates); checkDuplicates = true; } } else { String key = XmlConvert.ToXPathString(result); AddKeyValue(keyTable, key, /*value:*/node, /*checkDuplicates:*/ false); } } private DecimalFormat ResolveFormatName(string formatName) { string ns = string.Empty, local = string.Empty; if (formatName != null) { string prefix; PrefixQName.ParseQualifiedName(formatName, out prefix, out local); ns = LookupNamespace(prefix); } DecimalFormat formatInfo = _processor.RootAction.GetDecimalFormat(new XmlQualifiedName(local, ns)); if (formatInfo == null) { if (formatName != null) { throw XsltException.Create(SR.Xslt_NoDecimalFormat, formatName); } formatInfo = new DecimalFormat(new NumberFormatInfo(), '#', '0', ';'); } return formatInfo; } // see http://www.w3.org/TR/xslt#function-element-available private bool ElementAvailable(string qname) { string name, prefix; PrefixQName.ParseQualifiedName(qname, out prefix, out name); string ns = _manager.ResolveXmlNamespace(prefix); // msxsl:script - is not an "instruction" so we return false for it. if (ns == XmlReservedNs.NsXslt) { return ( name == "apply-imports" || name == "apply-templates" || name == "attribute" || name == "call-template" || name == "choose" || name == "comment" || name == "copy" || name == "copy-of" || name == "element" || name == "fallback" || name == "for-each" || name == "if" || name == "message" || name == "number" || name == "processing-instruction" || name == "text" || name == "value-of" || name == "variable" ); } return false; } // see: http://www.w3.org/TR/xslt#function-function-available private bool FunctionAvailable(string qname) { string name, prefix; PrefixQName.ParseQualifiedName(qname, out prefix, out name); string ns = LookupNamespace(prefix); if (ns == XmlReservedNs.NsMsxsl) { return name == f_NodeSet; } else if (ns.Length == 0) { return ( // It'll be better to get this information from XPath name == "last" || name == "position" || name == "name" || name == "namespace-uri" || name == "local-name" || name == "count" || name == "id" || name == "string" || name == "concat" || name == "starts-with" || name == "contains" || name == "substring-before" || name == "substring-after" || name == "substring" || name == "string-length" || name == "normalize-space" || name == "translate" || name == "boolean" || name == "not" || name == "true" || name == "false" || name == "lang" || name == "number" || name == "sum" || name == "floor" || name == "ceiling" || name == "round" || // XSLT functions: (s_FunctionTable[name] != null && name != "unparsed-entity-uri") ); } else { // Is this script or extention function? object extension; return GetExtentionMethod(ns, name, /*argTypes*/null, out extension) != null; } } private XPathNodeIterator Current() { XPathNavigator nav = _processor.Current; if (nav != null) { return new XPathSingletonIterator(nav.Clone()); } return XPathEmptyIterator.Instance; } private String SystemProperty(string qname) { String result = string.Empty; string prefix; string local; PrefixQName.ParseQualifiedName(qname, out prefix, out local); // verify the prefix corresponds to the Xslt namespace string urn = LookupNamespace(prefix); if (urn == XmlReservedNs.NsXslt) { if (local == "version") { result = "1"; } else if (local == "vendor") { result = "Microsoft"; } else if (local == "vendor-url") { result = "http://www.microsoft.com"; } } else { if (urn == null && prefix != null) { // if prefix exist it has to be mapped to namespace. // Can it be "" here ? throw XsltException.Create(SR.Xslt_InvalidPrefix, prefix); } return string.Empty; } return result; } public static XPathResultType GetXPathType(Type type) { switch (Type.GetTypeCode(type)) { case TypeCode.String: return XPathResultType.String; case TypeCode.Boolean: return XPathResultType.Boolean; case TypeCode.Object: if (typeof(XPathNavigator).IsAssignableFrom(type) || typeof(IXPathNavigable).IsAssignableFrom(type)) { return XPathResultType.Navigator; } if (typeof(XPathNodeIterator).IsAssignableFrom(type)) { return XPathResultType.NodeSet; } // sdub: It be better to check that type is realy object and otherwise return XPathResultType.Error return XPathResultType.Any; case TypeCode.DateTime: return XPathResultType.Error; default: /* all numeric types */ return XPathResultType.Number; } } // ---------------- Xslt Function Implementations ------------------- // private static Hashtable CreateFunctionTable() { Hashtable ft = new Hashtable(10); { ft["current"] = new FuncCurrent(); ft["unparsed-entity-uri"] = new FuncUnEntityUri(); ft["generate-id"] = new FuncGenerateId(); ft["system-property"] = new FuncSystemProp(); ft["element-available"] = new FuncElementAvailable(); ft["function-available"] = new FuncFunctionAvailable(); ft["document"] = new FuncDocument(); ft["key"] = new FuncKey(); ft["format-number"] = new FuncFormatNumber(); } return ft; } // + IXsltContextFunction // + XsltFunctionImpl func. name, min/max args, return type args types // FuncCurrent "current" 0 0 XPathResultType.NodeSet { } // FuncUnEntityUri "unparsed-entity-uri" 1 1 XPathResultType.String { XPathResultType.String } // FuncGenerateId "generate-id" 0 1 XPathResultType.String { XPathResultType.NodeSet } // FuncSystemProp "system-property" 1 1 XPathResultType.String { XPathResultType.String } // FuncElementAvailable "element-available" 1 1 XPathResultType.Boolean { XPathResultType.String } // FuncFunctionAvailable "function-available" 1 1 XPathResultType.Boolean { XPathResultType.String } // FuncDocument "document" 1 2 XPathResultType.NodeSet { XPathResultType.Any , XPathResultType.NodeSet } // FuncKey "key" 2 2 XPathResultType.NodeSet { XPathResultType.String , XPathResultType.Any } // FuncFormatNumber "format-number" 2 3 XPathResultType.String { XPathResultType.Number , XPathResultType.String, XPathResultType.String } // FuncNodeSet "msxsl:node-set" 1 1 XPathResultType.NodeSet { XPathResultType.Navigator } // FuncExtension // private abstract class XsltFunctionImpl : IXsltContextFunction { private int _minargs; private int _maxargs; private XPathResultType _returnType; private XPathResultType[] _argTypes; public XsltFunctionImpl() { } public XsltFunctionImpl(int minArgs, int maxArgs, XPathResultType returnType, XPathResultType[] argTypes) { this.Init(minArgs, maxArgs, returnType, argTypes); } protected void Init(int minArgs, int maxArgs, XPathResultType returnType, XPathResultType[] argTypes) { _minargs = minArgs; _maxargs = maxArgs; _returnType = returnType; _argTypes = argTypes; } public int Minargs { get { return _minargs; } } public int Maxargs { get { return _maxargs; } } public XPathResultType ReturnType { get { return _returnType; } } public XPathResultType[] ArgTypes { get { return _argTypes; } } public abstract object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext); // static helper methods: public static XPathNodeIterator ToIterator(object argument) { XPathNodeIterator it = argument as XPathNodeIterator; if (it == null) { throw XsltException.Create(SR.Xslt_NoNodeSetConversion); } return it; } public static XPathNavigator ToNavigator(object argument) { XPathNavigator nav = argument as XPathNavigator; if (nav == null) { throw XsltException.Create(SR.Xslt_NoNavigatorConversion); } return nav; } private static string IteratorToString(XPathNodeIterator it) { Debug.Assert(it != null); if (it.MoveNext()) { return it.Current.Value; } return string.Empty; } public static string ToString(object argument) { XPathNodeIterator it = argument as XPathNodeIterator; if (it != null) { return IteratorToString(it); } else { return XmlConvert.ToXPathString(argument); } } public static bool ToBoolean(object argument) { XPathNodeIterator it = argument as XPathNodeIterator; if (it != null) { return Convert.ToBoolean(IteratorToString(it), CultureInfo.InvariantCulture); } XPathNavigator nav = argument as XPathNavigator; if (nav != null) { return Convert.ToBoolean(nav.ToString(), CultureInfo.InvariantCulture); } return Convert.ToBoolean(argument, CultureInfo.InvariantCulture); } public static double ToNumber(object argument) { XPathNodeIterator it = argument as XPathNodeIterator; if (it != null) { return XmlConvert.ToXPathDouble(IteratorToString(it)); } XPathNavigator nav = argument as XPathNavigator; if (nav != null) { return XmlConvert.ToXPathDouble(nav.ToString()); } return XmlConvert.ToXPathDouble(argument); } private static object ToNumeric(object argument, Type type) { return Convert.ChangeType(ToNumber(argument), type, CultureInfo.InvariantCulture); } public static object ConvertToXPathType(object val, XPathResultType xt, Type type) { switch (xt) { case XPathResultType.String: // Unfortunetely XPathResultType.String == XPathResultType.Navigator (This is wrong but cant be changed in Everett) // Fortunetely we have typeCode hare so let's discriminate by typeCode if (type == typeof(String)) { return ToString(val); } else { return ToNavigator(val); } case XPathResultType.Number: return ToNumeric(val, type); case XPathResultType.Boolean: return ToBoolean(val); case XPathResultType.NodeSet: return ToIterator(val); // case XPathResultType.Navigator : return ToNavigator(val); case XPathResultType.Any: case XPathResultType.Error: return val; default: Debug.Assert(false, "unexpected XPath type"); return val; } } } private class FuncCurrent : XsltFunctionImpl { public FuncCurrent() : base(0, 0, XPathResultType.NodeSet, new XPathResultType[] { }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { return ((XsltCompileContext)xsltContext).Current(); } } private class FuncUnEntityUri : XsltFunctionImpl { public FuncUnEntityUri() : base(1, 1, XPathResultType.String, new XPathResultType[] { XPathResultType.String }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { throw XsltException.Create(SR.Xslt_UnsuppFunction, "unparsed-entity-uri"); } } private class FuncGenerateId : XsltFunctionImpl { public FuncGenerateId() : base(0, 1, XPathResultType.String, new XPathResultType[] { XPathResultType.NodeSet }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { if (args.Length > 0) { XPathNodeIterator it = ToIterator(args[0]); if (it.MoveNext()) { return it.Current.UniqueId; } else { // if empty nodeset, return empty string, otherwise return generated id return string.Empty; } } else { return docContext.UniqueId; } } } private class FuncSystemProp : XsltFunctionImpl { public FuncSystemProp() : base(1, 1, XPathResultType.String, new XPathResultType[] { XPathResultType.String }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { return ((XsltCompileContext)xsltContext).SystemProperty(ToString(args[0])); } } // see http://www.w3.org/TR/xslt#function-element-available private class FuncElementAvailable : XsltFunctionImpl { public FuncElementAvailable() : base(1, 1, XPathResultType.Boolean, new XPathResultType[] { XPathResultType.String }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { return ((XsltCompileContext)xsltContext).ElementAvailable(ToString(args[0])); } } // see: http://www.w3.org/TR/xslt#function-function-available private class FuncFunctionAvailable : XsltFunctionImpl { public FuncFunctionAvailable() : base(1, 1, XPathResultType.Boolean, new XPathResultType[] { XPathResultType.String }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { return ((XsltCompileContext)xsltContext).FunctionAvailable(ToString(args[0])); } } private class FuncDocument : XsltFunctionImpl { public FuncDocument() : base(1, 2, XPathResultType.NodeSet, new XPathResultType[] { XPathResultType.Any, XPathResultType.NodeSet }) { } // SxS: This method uses resource names read from source document and does not expose any resources to the caller. // It's OK to suppress the SxS warning. public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { string baseUri = null; if (args.Length == 2) { XPathNodeIterator it = ToIterator(args[1]); if (it.MoveNext()) { baseUri = it.Current.BaseURI; } else { // http://www.w3.org/1999/11/REC-xslt-19991116-errata (E14): // It is an error if the second argument node-set is empty and the URI reference is relative; the XSLT processor may signal the error; // if it does not signal an error, it must recover by returning an empty node-set. baseUri = string.Empty; // call to Document will fail if args[0] is reletive. } } try { return ((XsltCompileContext)xsltContext).Document(args[0], baseUri); } catch (Exception e) { if (!XmlException.IsCatchableException(e)) { throw; } return XPathEmptyIterator.Instance; } } } private class FuncKey : XsltFunctionImpl { public FuncKey() : base(2, 2, XPathResultType.NodeSet, new XPathResultType[] { XPathResultType.String, XPathResultType.Any }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { XsltCompileContext xsltCompileContext = (XsltCompileContext)xsltContext; string local, prefix; PrefixQName.ParseQualifiedName(ToString(args[0]), out prefix, out local); string ns = xsltContext.LookupNamespace(prefix); XmlQualifiedName keyName = new XmlQualifiedName(local, ns); XPathNavigator root = docContext.Clone(); root.MoveToRoot(); ArrayList resultCollection = null; foreach (Key key in xsltCompileContext._processor.KeyList) { if (key.Name == keyName) { Hashtable keyTable = key.GetKeys(root); if (keyTable == null) { keyTable = xsltCompileContext.BuildKeyTable(key, root); key.AddKey(root, keyTable); } XPathNodeIterator it = args[1] as XPathNodeIterator; if (it != null) { it = it.Clone(); while (it.MoveNext()) { resultCollection = AddToList(resultCollection, (ArrayList)keyTable[it.Current.Value]); } } else { resultCollection = AddToList(resultCollection, (ArrayList)keyTable[ToString(args[1])]); } } } if (resultCollection == null) { return XPathEmptyIterator.Instance; } else if (resultCollection[0] is XPathNavigator) { return new XPathArrayIterator(resultCollection); } else { return new XPathMultyIterator(resultCollection); } } private static ArrayList AddToList(ArrayList resultCollection, ArrayList newList) { if (newList == null) { return resultCollection; } if (resultCollection == null) { return newList; } Debug.Assert(resultCollection.Count != 0); Debug.Assert(newList.Count != 0); if (!(resultCollection[0] is ArrayList)) { // Transform resultCollection from ArrayList(XPathNavigator) to ArrayList(ArrayList(XPathNavigator)) Debug.Assert(resultCollection[0] is XPathNavigator); ArrayList firstList = resultCollection; resultCollection = new ArrayList(); resultCollection.Add(firstList); } resultCollection.Add(newList); return resultCollection; } } private class FuncFormatNumber : XsltFunctionImpl { public FuncFormatNumber() : base(2, 3, XPathResultType.String, new XPathResultType[] { XPathResultType.Number, XPathResultType.String, XPathResultType.String }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { DecimalFormat formatInfo = ((XsltCompileContext)xsltContext).ResolveFormatName(args.Length == 3 ? ToString(args[2]) : null); return DecimalFormatter.Format(ToNumber(args[0]), ToString(args[1]), formatInfo); } } private class FuncNodeSet : XsltFunctionImpl { public FuncNodeSet() : base(1, 1, XPathResultType.NodeSet, new XPathResultType[] { XPathResultType.Navigator }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { return new XPathSingletonIterator(ToNavigator(args[0])); } } private class FuncExtension : XsltFunctionImpl { private object _extension; private MethodInfo _method; private Type[] _types; public FuncExtension(object extension, MethodInfo method) { Debug.Assert(extension != null); Debug.Assert(method != null); _extension = extension; _method = method; XPathResultType returnType = GetXPathType(method.ReturnType); ParameterInfo[] parameters = method.GetParameters(); int minArgs = parameters.Length; int maxArgs = parameters.Length; _types = new Type[parameters.Length]; XPathResultType[] argTypes = new XPathResultType[parameters.Length]; bool optionalParams = true; // we allow only last params be optional. Set false on the first non optional. for (int i = parameters.Length - 1; 0 <= i; i--) { // Revers order is essential: counting optional parameters _types[i] = parameters[i].ParameterType; argTypes[i] = GetXPathType(parameters[i].ParameterType); if (optionalParams) { if (parameters[i].IsOptional) { minArgs--; } else { optionalParams = false; } } } base.Init(minArgs, maxArgs, returnType, argTypes); } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { Debug.Assert(args.Length <= this.Minargs, "We cheking this on resolve time"); for (int i = args.Length - 1; 0 <= i; i--) { args[i] = ConvertToXPathType(args[i], this.ArgTypes[i], _types[i]); } return _method.Invoke(_extension, args); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithElementUInt167() { var test = new VectorGetAndWithElement__GetAndWithElementUInt167(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); // Validates that invalid indices throws ArgumentOutOfRangeException test.RunArgumentOutOfRangeScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithElement__GetAndWithElementUInt167 { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 7, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); UInt16[] values = new UInt16[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt16(); } Vector256<UInt16> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15]); bool succeeded = !expectedOutOfRangeException; try { UInt16 result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; UInt16 insertedValue = TestLibrary.Generator.GetUInt16(); try { Vector256<UInt16> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 7, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); UInt16[] values = new UInt16[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt16(); } Vector256<UInt16> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector256) .GetMethod(nameof(Vector256.GetElement)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((UInt16)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; UInt16 insertedValue = TestLibrary.Generator.GetUInt16(); try { object result2 = typeof(Vector256) .GetMethod(nameof(Vector256.WithElement)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector256<UInt16>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(7 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(7 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(7 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(7 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(UInt16 result, UInt16[] values, [CallerMemberName] string method = "") { if (result != values[7]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.GetElement(7): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector256<UInt16> result, UInt16[] values, UInt16 insertedValue, [CallerMemberName] string method = "") { UInt16[] resultElements = new UInt16[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(UInt16[] result, UInt16[] values, UInt16 insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 7) && (result[i] != values[i])) { succeeded = false; break; } } if (result[7] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.WithElement(7): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" insert: insertedValue"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Specialized; using System.Net; using System.Web; using Skybrud.Social.Http; using Skybrud.Social.Instagram.Endpoints.Raw; using Skybrud.Social.Instagram.Responses; using Skybrud.Social.Interfaces; using Skybrud.Social.Json; namespace Skybrud.Social.Instagram.OAuth { /// <summary> /// Class for handling the raw communication with the Instagram API as well /// as any OAuth 2.0 communication/authentication. /// </summary> public class InstagramOAuthClient { #region Private fields private InstagramLocationsRawEndpoint _locations; private InstagramMediaRawEndpoint _media; private InstagramRelationshipsRawEndpoint _relationships; private InstagramTagsRawEndpoint _tags; private InstagramUsersRawEndpoint _users; #endregion #region Properties /// <summary> /// The ID of the app/client. /// </summary> public string ClientId { get; set; } /// <summary> /// The secret of the app/client. /// </summary> public string ClientSecret { get; set; } /// <summary> /// The redirect URI of your application. /// </summary> [Obsolete("Use \"RedirectUri\" instead to follow Instagram lingo.")] public string ReturnUri { get { return RedirectUri; } set { RedirectUri = value; } } /// <summary> /// The redirect URI of your application. /// </summary> public string RedirectUri { get; set; } /// <summary> /// The access token. /// </summary> public string AccessToken { get; set; } /// <summary> /// Gets a reference to the locations endpoint. /// </summary> public InstagramLocationsRawEndpoint Locations { get { return _locations ?? (_locations = new InstagramLocationsRawEndpoint(this)); } } /// <summary> /// Gets a reference to the media endpoint. /// </summary> public InstagramMediaRawEndpoint Media { get { return _media ?? (_media = new InstagramMediaRawEndpoint(this)); } } /// <summary> /// Gets a reference to the relationships endpoint. /// </summary> public InstagramRelationshipsRawEndpoint Relationships { get { return _relationships ?? (_relationships = new InstagramRelationshipsRawEndpoint(this)); } } /// <summary> /// Gets a reference to the tags endpoint. /// </summary> public InstagramTagsRawEndpoint Tags { get { return _tags ?? (_tags = new InstagramTagsRawEndpoint(this)); } } /// <summary> /// Gets a reference to the users endpoint. /// </summary> public InstagramUsersRawEndpoint Users { get { return _users ?? (_users = new InstagramUsersRawEndpoint(this)); } } #endregion #region Constructors /// <summary> /// Initializes an OAuth client with empty information. /// </summary> public InstagramOAuthClient() { // default constructor } /// <summary> /// Initializes an OAuth client with the specified access token. Using this initializer, /// the client will have no information about your app. /// </summary> /// <param name="accessToken">A valid access token.</param> public InstagramOAuthClient(string accessToken) { AccessToken = accessToken; } /// <summary> /// Initializes an OAuth client with the specified app ID and app secret. /// </summary> /// <param name="appId">The ID of the app.</param> /// <param name="appSecret">The secret of the app.</param> public InstagramOAuthClient(long appId, string appSecret) { ClientId = appId + ""; ClientSecret = appSecret; } /// <summary> /// Initializes an OAuth client with the specified app ID, app secret and return URI. /// </summary> /// <param name="appId">The ID of the app.</param> /// <param name="appSecret">The secret of the app.</param> /// <param name="redirectUri">The return URI of the app.</param> public InstagramOAuthClient(long appId, string appSecret, string redirectUri) { ClientId = appId + ""; ClientSecret = appSecret; RedirectUri = redirectUri; } /// <summary> /// Initializes an OAuth client with the specified app ID and app secret. /// </summary> /// <param name="appId">The ID of the app.</param> /// <param name="appSecret">The secret of the app.</param> public InstagramOAuthClient(string appId, string appSecret) { ClientId = appId; ClientSecret = appSecret; } /// <summary> /// Initializes an OAuth client with the specified app ID, app secret and return URI. /// </summary> /// <param name="appId">The ID of the app.</param> /// <param name="appSecret">The secret of the app.</param> /// <param name="redirectUri">The return URI of the app.</param> public InstagramOAuthClient(string appId, string appSecret, string redirectUri) { ClientId = appId; ClientSecret = appSecret; RedirectUri = redirectUri; } #endregion #region Methods /// <summary> /// Gets an authorization URL using the specified <var>state</var>. /// This URL will only make your application request a basic scope. /// </summary> /// <param name="state">A unique state for the request.</param> public string GetAuthorizationUrl(string state) { return GetAuthorizationUrl(state, InstagramScope.Basic); } /// <summary> /// Gets an authorization URL using the specified <var>state</var> and /// request the specified <var>scope</var>. /// </summary> /// <param name="state">A unique state for the request.</param> /// <param name="scope">The scope of your application.</param> public string GetAuthorizationUrl(string state, InstagramScope scope) { return String.Format( "https://api.instagram.com/oauth/authorize/?client_id={0}&redirect_uri={1}&response_type=code&state={2}&scope={3}", HttpUtility.UrlEncode(ClientId), HttpUtility.UrlEncode(RedirectUri), HttpUtility.UrlEncode(state), HttpUtility.UrlEncode(scope.ToString().Replace(", ", "+").ToLower()) ); } public InstagramAccessTokenResponse GetAccessTokenFromAuthCode(string authCode) { // Initialize collection with POST data NameValueCollection parameters = new NameValueCollection { {"client_id", ClientId}, {"client_secret", ClientSecret}, {"grant_type", "authorization_code"}, {"redirect_uri", RedirectUri}, {"code", authCode } }; // Make the call to the API string contents = SocialUtils.DoHttpPostRequestAndGetBodyAsString("https://api.instagram.com/oauth/access_token", null, parameters); // Parse the response return InstagramAccessTokenResponse.ParseJson(contents); } /// <summary> /// Makes an authenticated GET request to the specified URL. If an access token has been /// specified for this client, that access token will be added to the query string. /// Similar if a client ID has been specified instead of an access token, that client ID /// will be added to the query string. However some endpoint methods may require an access /// token, and a client ID will therefore not be sufficient for such methods. /// </summary> /// <param name="url">The URL to call.</param> public SocialHttpResponse DoAuthenticatedGetRequest(string url) { return DoAuthenticatedGetRequest(url, new NameValueCollection()); } /// <summary> /// Makes an authenticated GET request to the specified URL. If an access token has been /// specified for this client, that access token will be added to the query string. /// Similar if a client ID has been specified instead of an access token, that client ID /// will be added to the query string. However some endpoint methods may require an access /// token, and a client ID will therefore not be sufficient for such methods. /// </summary> /// <param name="url">The URL to call.</param> /// <param name="query">The query string for the call.</param> public SocialHttpResponse DoAuthenticatedGetRequest(string url, NameValueCollection query) { return DoAuthenticatedGetRequest(url, new SocialQueryString(query)); } /// <summary> /// Makes an authenticated GET request to the specified URL. If an access token has been /// specified for this client, that access token will be added to the query string. /// Similar if a client ID has been specified instead of an access token, that client ID /// will be added to the query string. However some endpoint methods may require an access /// token, and a client ID will therefore not be sufficient for such methods. /// </summary> /// <param name="url">The URL to call.</param> /// <param name="query">The query string for the call.</param> public SocialHttpResponse DoAuthenticatedGetRequest(string url, IGetOptions query) { return DoAuthenticatedGetRequest(url, query == null ? null : query.GetQueryString()); } /// <summary> /// Makes an authenticated GET request to the specified URL. If an access token has been /// specified for this client, that access token will be added to the query string. /// Similar if a client ID has been specified instead of an access token, that client ID /// will be added to the query string. However some endpoint methods may require an access /// token, and a client ID will therefore not be sufficient for such methods. /// </summary> /// <param name="url">The URL to call.</param> /// <param name="query">The query string for the call.</param> public SocialHttpResponse DoAuthenticatedGetRequest(string url, SocialQueryString query) { // Throw an exception if the URL is empty if (String.IsNullOrWhiteSpace(url)) throw new ArgumentNullException("url"); // Initialize a new instance of SocialQueryString if the one specified is NULL if (query == null) query = new SocialQueryString(); // Append either the access token or the client ID to the query string if (!String.IsNullOrWhiteSpace(AccessToken)) { query.Add("access_token", AccessToken); } else if (!String.IsNullOrWhiteSpace(ClientId)) { query.Add("client_id", ClientId); } // Append the query string to the URL if (!query.IsEmpty) url += (url.Contains("?") ? "&" : "?") + query; // Initialize a new HTTP request HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url); // Get the HTTP response try { return SocialHttpResponse.GetFromWebResponse(request.GetResponse() as HttpWebResponse); } catch (WebException ex) { if (ex.Status != WebExceptionStatus.ProtocolError) throw; return SocialHttpResponse.GetFromWebResponse(ex.Response as HttpWebResponse); } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; namespace Orleans.Runtime.ConsistentRing { /// <summary> /// We use the 'backward/clockwise' definition to assign responsibilities on the ring. /// E.g. in a ring of nodes {5, 10, 15} the responsible for key 7 is 10 (the node is responsible for its predecessing range). /// The backwards/clockwise approach is consistent with many overlays, e.g., Chord, Cassandra, etc. /// Note: MembershipOracle uses 'forward/counter-clockwise' definition to assign responsibilities. /// E.g. in a ring of nodes {5, 10, 15}, the responsible of key 7 is node 5 (the node is responsible for its sucessing range).. /// </summary> internal class ConsistentRingProvider : MarshalByRefObject, IConsistentRingProvider, ISiloStatusListener // make the ring shutdown-able? { // internal, so that unit tests can access them internal SiloAddress MyAddress { get; private set; } internal IRingRange MyRange { get; private set; } /// list of silo members sorted by the hash value of their address private readonly List<SiloAddress> membershipRingList; private readonly ILogger log; private bool isRunning; private readonly int myKey; private readonly List<IRingRangeListener> statusListeners; public ConsistentRingProvider(SiloAddress siloAddr, ILoggerFactory loggerFactory) { log = loggerFactory.CreateLogger<ConsistentRingProvider>(); membershipRingList = new List<SiloAddress>(); MyAddress = siloAddr; myKey = MyAddress.GetConsistentHashCode(); // add myself to the list of members AddServer(MyAddress); MyRange = RangeFactory.CreateFullRange(); // i am responsible for the whole range statusListeners = new List<IRingRangeListener>(); Start(); } /// <summary> /// Returns the silo that this silo thinks is the primary owner of the key /// </summary> /// <param name="key"></param> /// <returns></returns> public SiloAddress GetPrimaryTargetSilo(uint key) { return CalculateTargetSilo(key); } public IRingRange GetMyRange() { return MyRange; // its immutable, so no need to clone } /// <summary> /// Returns null if silo is not in the list of members /// </summary> public List<SiloAddress> GetMySucessors(int n = 1) { return FindSuccessors(MyAddress, n); } /// <summary> /// Returns null if silo is not in the list of members /// </summary> public List<SiloAddress> GetMyPredecessors(int n = 1) { return FindPredecessors(MyAddress, n); } private void Start() { isRunning = true; } private void Stop() { isRunning = false; } internal void AddServer(SiloAddress silo) { lock (membershipRingList) { if (membershipRingList.Contains(silo)) return; // we already have this silo int myOldIndex = membershipRingList.FindIndex(elem => elem.Equals(MyAddress)); if (!(membershipRingList.Count == 0 || myOldIndex != -1)) throw new OrleansException(string.Format("{0}: Couldn't find my position in the ring {1}.", MyAddress, Utils.EnumerableToString(membershipRingList))); // insert new silo in the sorted order int hash = silo.GetConsistentHashCode(); // Find the last silo with hash smaller than the new silo, and insert the latter after (this is why we have +1 here) the former. // Notice that FindLastIndex might return -1 if this should be the first silo in the list, but then // 'index' will get 0, as needed. int index = membershipRingList.FindLastIndex(siloAddr => siloAddr.GetConsistentHashCode() < hash) + 1; membershipRingList.Insert(index, silo); // relating to triggering handler ... new node took over some of my responsibility if (index == myOldIndex || // new node was inserted in my place (myOldIndex == 0 && index == membershipRingList.Count - 1)) // I am the first node, and the new server is the last node { IRingRange oldRange = MyRange; try { MyRange = RangeFactory.CreateRange(unchecked((uint)hash), unchecked((uint)myKey)); } catch (OverflowException exc) { log.Error(ErrorCode.ConsistentRingProviderBase + 5, String.Format("OverflowException: hash as int= x{0, 8:X8}, hash as uint= x{1, 8:X8}, myKey as int x{2, 8:X8}, myKey as uint x{3, 8:X8}.", hash, (uint)hash, myKey, (uint)myKey), exc); } NotifyLocalRangeSubscribers(oldRange, MyRange, false); } log.Info("Added Server {0}. Current view: {1}", silo.ToStringWithHashCode(), this.ToString()); } } public override string ToString() { lock (membershipRingList) { if (membershipRingList.Count == 1) return Utils.EnumerableToString(membershipRingList, silo => String.Format("{0} -> {1}", silo.ToStringWithHashCode(), RangeFactory.CreateFullRange())); var sb = new StringBuilder("["); for (int i=0; i < membershipRingList.Count; i++) { SiloAddress curr = membershipRingList[ i ]; SiloAddress next = membershipRingList[ (i +1) % membershipRingList.Count]; IRingRange range = RangeFactory.CreateRange(unchecked((uint)curr.GetConsistentHashCode()), unchecked((uint)next.GetConsistentHashCode())); sb.Append(String.Format("{0} -> {1}, ", curr.ToStringWithHashCode(), range)); } sb.Append("]"); return sb.ToString(); } } internal void RemoveServer(SiloAddress silo) { lock (membershipRingList) { int indexOfFailedSilo = membershipRingList.FindIndex(elem => elem.Equals(silo)); if (indexOfFailedSilo < 0) return; // we have already removed this silo membershipRingList.Remove(silo); // related to triggering handler int myNewIndex = membershipRingList.FindIndex(elem => elem.Equals(MyAddress)); if (myNewIndex == -1) throw new OrleansException(string.Format("{0}: Couldn't find my position in the ring {1}.", MyAddress, this.ToString())); bool wasMyPred = ((myNewIndex == indexOfFailedSilo) || (myNewIndex == 0 && indexOfFailedSilo == membershipRingList.Count)); // no need for '- 1' if (wasMyPred) // failed node was our predecessor { if (log.IsEnabled(LogLevel.Debug)) log.Debug("Failed server was my pred? {0}, updated view {1}", wasMyPred, this.ToString()); IRingRange oldRange = MyRange; if (membershipRingList.Count == 1) // i'm the only one left { MyRange = RangeFactory.CreateFullRange(); NotifyLocalRangeSubscribers(oldRange, MyRange, true); } else { int myNewPredIndex = myNewIndex == 0 ? membershipRingList.Count - 1 : myNewIndex - 1; int myPredecessorsHash = membershipRingList[myNewPredIndex].GetConsistentHashCode(); MyRange = RangeFactory.CreateRange(unchecked((uint)myPredecessorsHash), unchecked((uint)myKey)); NotifyLocalRangeSubscribers(oldRange, MyRange, true); } } log.Info("Removed Server {0} hash {1}. Current view {2}", silo, silo.GetConsistentHashCode(), this.ToString()); } } /// <summary> /// Returns null if silo is not in the list of members /// </summary> internal List<SiloAddress> FindPredecessors(SiloAddress silo, int count) { lock (membershipRingList) { int index = membershipRingList.FindIndex(elem => elem.Equals(silo)); if (index == -1) { log.Warn(ErrorCode.Runtime_Error_100201, "Got request to find predecessors of silo " + silo + ", which is not in the list of members."); return null; } var result = new List<SiloAddress>(); int numMembers = membershipRingList.Count; for (int i = index - 1; ((i + numMembers) % numMembers) != index && result.Count < count; i--) { result.Add(membershipRingList[(i + numMembers) % numMembers]); } return result; } } /// <summary> /// Returns null if silo is not in the list of members /// </summary> internal List<SiloAddress> FindSuccessors(SiloAddress silo, int count) { lock (membershipRingList) { int index = membershipRingList.FindIndex(elem => elem.Equals(silo)); if (index == -1) { log.Warn(ErrorCode.Runtime_Error_100203, "Got request to find successors of silo " + silo + ", which is not in the list of members."); return null; } var result = new List<SiloAddress>(); int numMembers = membershipRingList.Count; for (int i = index + 1; i % numMembers != index && result.Count < count; i++) { result.Add(membershipRingList[i % numMembers]); } return result; } } public bool SubscribeToRangeChangeEvents(IRingRangeListener observer) { lock (statusListeners) { if (statusListeners.Contains(observer)) return false; statusListeners.Add(observer); return true; } } public bool UnSubscribeFromRangeChangeEvents(IRingRangeListener observer) { lock (statusListeners) { return statusListeners.Contains(observer) && statusListeners.Remove(observer); } } private void NotifyLocalRangeSubscribers(IRingRange old, IRingRange now, bool increased) { log.Info("-NotifyLocalRangeSubscribers about old {0} new {1} increased? {2}", old, now, increased); List<IRingRangeListener> copy; lock (statusListeners) { copy = statusListeners.ToList(); } foreach (IRingRangeListener listener in copy) { try { listener.RangeChangeNotification(old, now, increased); } catch (Exception exc) { log.Error(ErrorCode.CRP_Local_Subscriber_Exception, String.Format("Local IRangeChangeListener {0} has thrown an exception when was notified about RangeChangeNotification about old {1} new {2} increased? {3}", listener.GetType().FullName, old, now, increased), exc); } } } public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status) { // This silo's status has changed if (updatedSilo.Equals(MyAddress)) { if (status.IsTerminating()) { Stop(); } } else // Status change for some other silo { if (status.IsTerminating()) { RemoveServer(updatedSilo); } else if (status == SiloStatus.Active) // do not do anything with SiloStatus.Created or SiloStatus.Joining -- wait until it actually becomes active { AddServer(updatedSilo); } } } /// <summary> /// Finds the silo that owns the given hash value. /// This routine will always return a non-null silo address unless the excludeThisSiloIfStopping parameter is true, /// this is the only silo known, and this silo is stopping. /// </summary> /// <param name="hash"></param> /// <param name="excludeThisSiloIfStopping"></param> /// <returns></returns> public SiloAddress CalculateTargetSilo(uint hash, bool excludeThisSiloIfStopping = true) { SiloAddress siloAddress = null; lock (membershipRingList) { // excludeMySelf from being a TargetSilo if we're not running and the excludeThisSIloIfStopping flag is true. see the comment in the Stop method. bool excludeMySelf = excludeThisSiloIfStopping && !isRunning; if (membershipRingList.Count == 0) { // If the membership ring is empty, then we're the owner by default unless we're stopping. return excludeMySelf ? null : MyAddress; } // use clockwise ... current code in membershipOracle.CalculateTargetSilo() does counter-clockwise ... // if you want to stick to counter-clockwise, change the responsibility definition in 'In()' method & responsibility defs in OrleansReminderMemory // need to implement a binary search, but for now simply traverse the list of silos sorted by their hashes for (int index = 0; index < membershipRingList.Count; ++index) { var siloAddr = membershipRingList[index]; if (IsSiloNextInTheRing(siloAddr, hash, excludeMySelf)) { siloAddress = siloAddr; break; } } if (siloAddress == null) { // if not found in traversal, then first silo should be returned (we are on a ring) // if you go back to their counter-clockwise policy, then change the 'In()' method in OrleansReminderMemory siloAddress = membershipRingList[0]; // vs [membershipRingList.Count - 1]; for counter-clockwise policy // Make sure it's not us... if (siloAddress.Equals(MyAddress) && excludeMySelf) { // vs [membershipRingList.Count - 2]; for counter-clockwise policy siloAddress = membershipRingList.Count > 1 ? membershipRingList[1] : null; } } } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Silo {0} calculated ring partition owner silo {1} for key {2}: {3} --> {4}", MyAddress, siloAddress, hash, hash, siloAddress.GetConsistentHashCode()); return siloAddress; } private bool IsSiloNextInTheRing(SiloAddress siloAddr, uint hash, bool excludeMySelf) { return siloAddr.GetConsistentHashCode() >= hash && (!siloAddr.Equals(MyAddress) || !excludeMySelf); } } }
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 GarageKept.WebConsole.Server.Areas.HelpPage.ModelDescriptions; using GarageKept.WebConsole.Server.Areas.HelpPage.Models; namespace GarageKept.WebConsole.Server.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using GraphQL.Types; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Newtonsoft.Json.Linq; using OrchardCore.Apis.GraphQL; using OrchardCore.Apis.GraphQL.Queries; using OrchardCore.Apis.GraphQL.Resolvers; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.GraphQL.Options; using OrchardCore.ContentManagement.GraphQL.Queries; using OrchardCore.ContentManagement.Records; using OrchardCore.Environment.Shell; using Xunit; using YesSql; using YesSql.Indexes; using YesSql.Provider.Sqlite; using YesSql.Sql; namespace OrchardCore.Tests.Apis.GraphQL { public class ContentItemsFieldTypeTests : IDisposable { protected IStore _store; protected IStore _prefixedStore; protected string _prefix; protected string _tempFilename; private Task _initializeTask; public ContentItemsFieldTypeTests() { _initializeTask = InitializeAsync(); } private async Task InitializeAsync() { var connectionStringTemplate = @"Data Source={0};Cache=Shared"; _tempFilename = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); _store = await StoreFactory.CreateAsync(new Configuration().UseSqLite(String.Format(connectionStringTemplate, _tempFilename))); _prefix = "tp"; _prefixedStore = await StoreFactory.CreateAsync(new Configuration().UseSqLite(String.Format(connectionStringTemplate, _tempFilename + _prefix)).SetTablePrefix(_prefix + "_")); await CreateTablesAsync(_store); await CreateTablesAsync(_prefixedStore); } public void Dispose() { _store.Dispose(); _store = null; _prefixedStore.Dispose(); _prefixedStore = null; if (File.Exists(_tempFilename)) { File.Delete(_tempFilename); } var prefixFilename = _tempFilename + _prefix; if (File.Exists(prefixFilename)) { File.Delete(prefixFilename); } } private async Task CreateTablesAsync(IStore store) { using (var session = store.CreateSession()) { var builder = new SchemaBuilder(store.Configuration, await session.DemandAsync()); builder.CreateMapIndexTable<ContentItemIndex>(table => table .Column<string>("ContentItemId", c => c.WithLength(26)) .Column<string>("ContentItemVersionId", c => c.WithLength(26)) .Column<bool>("Latest") .Column<bool>("Published") .Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) .Column<DateTime>("ModifiedUtc", column => column.Nullable()) .Column<DateTime>("PublishedUtc", column => column.Nullable()) .Column<DateTime>("CreatedUtc", column => column.Nullable()) .Column<string>("Owner", column => column.Nullable().WithLength(ContentItemIndex.MaxOwnerSize)) .Column<string>("Author", column => column.Nullable().WithLength(ContentItemIndex.MaxAuthorSize)) .Column<string>("DisplayText", column => column.Nullable().WithLength(ContentItemIndex.MaxDisplayTextSize)) ); builder.CreateMapIndexTable<AnimalIndex>(table => table .Column<string>(nameof(AnimalIndex.Name)) ); builder.CreateMapIndexTable<AnimalTraitsIndex>(table => table .Column<bool>(nameof(AnimalTraitsIndex.IsHappy)) .Column<bool>(nameof(AnimalTraitsIndex.IsScary)) ); } store.RegisterIndexes<ContentItemIndexProvider>(); } [Fact] public async Task ShouldFilterByContentItemIndex() { await _initializeTask; _store.RegisterIndexes<AnimalIndexProvider>(); using (var services = new FakeServiceCollection()) { services.Populate(new ServiceCollection()); services.Services.AddScoped(x => _store.CreateSession()); services.Services.AddScoped(x => new ShellSettings()); services.Services.AddSingleton<IIndexPropertyProvider, IndexPropertyProvider<ContentItemIndex>>(); services.Services.AddSingleton<IIndexPropertyProvider, IndexPropertyProvider<AnimalIndex>>(); services.Build(); var returnType = new ListGraphType<StringGraphType>(); returnType.ResolvedType = new StringGraphType() { Name = "Animal" }; var animalWhereInput = new AnimalPartWhereInput(); var inputs = new FieldType { Name = "Inputs", Arguments = new QueryArguments { new QueryArgument<WhereInputObjectGraphType> { Name = "where", Description = "filters the animals", ResolvedType = animalWhereInput } } }; var context = new ResolveFieldContext { Arguments = new Dictionary<string, object>(), UserContext = new GraphQLContext { ServiceProvider = services }, ReturnType = returnType, FieldDefinition = inputs }; var ci = new ContentItem { ContentType = "Animal", Published = true, ContentItemId = "1", ContentItemVersionId = "1" }; ci.Weld(new AnimalPart { Name = "doug" }); var session = ((GraphQLContext)context.UserContext).ServiceProvider.GetService<ISession>(); session.Save(ci); await session.CommitAsync(); var type = new ContentItemsFieldType("Animal", new Schema(), Options.Create(new GraphQLContentOptions()), Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 })); context.Arguments["where"] = JObject.Parse("{ contentItemId: \"1\" }"); var dogs = await ((LockedAsyncFieldResolver<IEnumerable<ContentItem>>)type.Resolver).Resolve(context); Assert.Single(dogs); Assert.Equal("doug", dogs.First().As<AnimalPart>().Name); } } [Fact] public async Task ShouldFilterByContentItemIndexWhenSqlTablePrefixIsUsed() { await _initializeTask; _prefixedStore.RegisterIndexes<AnimalIndexProvider>(); using (var services = new FakeServiceCollection()) { services.Populate(new ServiceCollection()); services.Services.AddScoped(x => _prefixedStore.CreateSession()); services.Services.AddSingleton<IIndexPropertyProvider, IndexPropertyProvider<ContentItemIndex>>(); services.Services.AddSingleton<IIndexPropertyProvider, IndexPropertyProvider<AnimalIndex>>(); services.Services.AddSingleton<IIndexPropertyProvider, IndexPropertyProvider<AnimalTraitsIndex>>(); var shellSettings = new ShellSettings(); shellSettings["TablePrefix"] = _prefix; services.Services.AddScoped(x => shellSettings); services.Build(); var returnType = new ListGraphType<StringGraphType>(); returnType.ResolvedType = new StringGraphType() { Name = "Animal" }; var animalWhereInput = new AnimalPartWhereInput(); var inputs = new FieldType { Name = "Inputs", Arguments = new QueryArguments { new QueryArgument<WhereInputObjectGraphType> { Name = "where", Description = "filters the animals", ResolvedType = animalWhereInput } } }; var context = new ResolveFieldContext { Arguments = new Dictionary<string, object>(), UserContext = new GraphQLContext { ServiceProvider = services }, ReturnType = returnType, FieldDefinition = inputs }; var ci = new ContentItem { ContentType = "Animal", Published = true, ContentItemId = "1", ContentItemVersionId = "1" }; ci.Weld(new AnimalPart { Name = "doug" }); var session = ((GraphQLContext)context.UserContext).ServiceProvider.GetService<ISession>(); session.Save(ci); await session.CommitAsync(); var type = new ContentItemsFieldType("Animal", new Schema(), Options.Create(new GraphQLContentOptions()), Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 })); context.Arguments["where"] = JObject.Parse("{ contentItemId: \"1\" }"); var dogs = await ((LockedAsyncFieldResolver<IEnumerable<ContentItem>>)type.Resolver).Resolve(context); Assert.Single(dogs); Assert.Equal("doug", dogs.First().As<AnimalPart>().Name); } } [Theory] [InlineData("animal")] [InlineData("ANIMAL")] [InlineData("Animal")] public async Task ShouldFilterByAliasIndexRegardlessOfInputFieldCase(string fieldName) { await _initializeTask; _store.RegisterIndexes<AnimalIndexProvider>(); using (var services = new FakeServiceCollection()) { services.Populate(new ServiceCollection()); services.Services.AddScoped(x => _store.CreateSession()); services.Services.AddScoped(x => new ShellSettings()); services.Services.AddScoped<IIndexProvider, AnimalIndexProvider>(); services.Services.AddScoped<IIndexAliasProvider, MultipleAliasIndexProvider>(); services.Services.AddSingleton<IIndexPropertyProvider, IndexPropertyProvider<AnimalIndex>>(); services.Build(); var returnType = new ListGraphType<StringGraphType> { ResolvedType = new StringGraphType() { Name = "Animal" } }; // setup the whereinput fieldname with the test data var animalWhereInput = new AnimalPartWhereInput(fieldName); var inputs = new FieldType { Name = "Inputs", Arguments = new QueryArguments { new QueryArgument<WhereInputObjectGraphType> { Name = "where", Description = "filters the animals", ResolvedType = animalWhereInput } } }; var context = new ResolveFieldContext { Arguments = new Dictionary<string, object>(), UserContext = new GraphQLContext { ServiceProvider = services }, ReturnType = returnType, FieldDefinition = inputs }; var ci = new ContentItem { ContentType = "Animal", Published = true, ContentItemId = "1", ContentItemVersionId = "1" }; ci.Weld(new AnimalPart { Name = "doug" }); var session = ((GraphQLContext)context.UserContext).ServiceProvider.GetService<ISession>(); session.Save(ci); await session.CommitAsync(); var type = new ContentItemsFieldType("Animal", new Schema(), Options.Create(new GraphQLContentOptions()), Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 })); context.Arguments["where"] = JObject.Parse(string.Concat("{ ", fieldName, ": { name: \"doug\" } }")); var dogs = await ((LockedAsyncFieldResolver<IEnumerable<ContentItem>>)type.Resolver).Resolve(context); Assert.Single(dogs); Assert.Equal("doug", dogs.First().As<AnimalPart>().Name); } } [Fact] public async Task ShouldBeAbleToUseTheSameIndexForMultipleAliases() { await _initializeTask; _store.RegisterIndexes<AnimalIndexProvider>(); using (var services = new FakeServiceCollection()) { services.Populate(new ServiceCollection()); services.Services.AddScoped(x => new ShellSettings()); services.Services.AddScoped(x => _store.CreateSession()); services.Services.AddScoped<IIndexProvider, ContentItemIndexProvider>(); services.Services.AddScoped<IIndexProvider, AnimalIndexProvider>(); services.Services.AddScoped<IIndexAliasProvider, MultipleAliasIndexProvider>(); services.Services.AddSingleton<IIndexPropertyProvider, IndexPropertyProvider<AnimalIndex>>(); services.Build(); var retrunType = new ListGraphType<StringGraphType>(); retrunType.ResolvedType = new StringGraphType() { Name = "Animal" }; var context = new ResolveFieldContext { Arguments = new Dictionary<string, object>(), UserContext = new GraphQLContext { ServiceProvider = services }, ReturnType = retrunType }; var ci = new ContentItem { ContentType = "Animal", Published = true, ContentItemId = "1", ContentItemVersionId = "1" }; ci.Weld(new Animal { Name = "doug" }); var session = ((GraphQLContext)context.UserContext).ServiceProvider.GetService<ISession>(); session.Save(ci); await session.CommitAsync(); var type = new ContentItemsFieldType("Animal", new Schema(), Options.Create(new GraphQLContentOptions()), Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 })); context.Arguments["where"] = JObject.Parse("{ cats: { name: \"doug\" } }"); var cats = await ((LockedAsyncFieldResolver<IEnumerable<ContentItem>>)type.Resolver).Resolve(context); Assert.Single(cats); Assert.Equal("doug", cats.First().As<Animal>().Name); context.Arguments["where"] = JObject.Parse("{ dogs: { name: \"doug\" } }"); var dogs = await ((LockedAsyncFieldResolver<IEnumerable<ContentItem>>)type.Resolver).Resolve(context); Assert.Single(dogs); Assert.Equal("doug", dogs.First().As<Animal>().Name); } } [Fact] public async Task ShouldFilterOnMultipleIndexesOnSameAlias() { await _initializeTask; _store.RegisterIndexes<AnimalIndexProvider>(); _store.RegisterIndexes<AnimalTraitsIndexProvider>(); using (var services = new FakeServiceCollection()) { services.Populate(new ServiceCollection()); services.Services.AddScoped(x => new ShellSettings()); services.Services.AddScoped(x => _store.CreateSession()); services.Services.AddScoped<IIndexProvider, ContentItemIndexProvider>(); services.Services.AddScoped<IIndexProvider, AnimalIndexProvider>(); services.Services.AddScoped<IIndexProvider, AnimalTraitsIndexProvider>(); services.Services.AddScoped<IIndexAliasProvider, MultipleIndexesIndexProvider>(); services.Services.AddSingleton<IIndexPropertyProvider, IndexPropertyProvider<AnimalIndex>>(); services.Services.AddSingleton<IIndexPropertyProvider, IndexPropertyProvider<AnimalTraitsIndex>>(); services.Build(); var retrunType = new ListGraphType<StringGraphType>(); retrunType.ResolvedType = new StringGraphType() { Name = "Animal" }; var context = new ResolveFieldContext { Arguments = new Dictionary<string, object>(), UserContext = new GraphQLContext { ServiceProvider = services }, ReturnType = retrunType }; var ci = new ContentItem { ContentType = "Animal", Published = true, ContentItemId = "1", ContentItemVersionId = "1" }; ci.Weld(new Animal { Name = "doug", IsHappy = true, IsScary = false }); var ci1 = new ContentItem { ContentType = "Animal", Published = true, ContentItemId = "2", ContentItemVersionId = "2" }; ci1.Weld(new Animal { Name = "doug", IsHappy = false, IsScary = true }); var ci2 = new ContentItem { ContentType = "Animal", Published = true, ContentItemId = "3", ContentItemVersionId = "3" }; ci2.Weld(new Animal { Name = "tommy", IsHappy = false, IsScary = true }); var session = ((GraphQLContext)context.UserContext).ServiceProvider.GetService<ISession>(); session.Save(ci); session.Save(ci1); session.Save(ci2); await session.CommitAsync(); var type = new ContentItemsFieldType("Animal", new Schema(), Options.Create(new GraphQLContentOptions()), Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 })); context.Arguments["where"] = JObject.Parse("{ animals: { name: \"doug\", isScary: true } }"); var animals = await ((LockedAsyncFieldResolver<IEnumerable<ContentItem>>)type.Resolver).Resolve(context); Assert.Single(animals); Assert.Equal("doug", animals.First().As<Animal>().Name); Assert.True(animals.First().As<Animal>().IsScary); Assert.False(animals.First().As<Animal>().IsHappy); } } [Fact] public async Task ShouldFilterPartsWithoutAPrefixWhenThePartHasNoPrefix() { await _initializeTask; _store.RegisterIndexes<AnimalIndexProvider>(); using (var services = new FakeServiceCollection()) { services.Populate(new ServiceCollection()); services.Services.AddScoped(x => _store.CreateSession()); services.Services.AddScoped(x => new ShellSettings()); services.Services.AddScoped<IIndexProvider, ContentItemIndexProvider>(); services.Services.AddScoped<IIndexProvider, AnimalIndexProvider>(); services.Services.AddScoped<IIndexAliasProvider, MultipleAliasIndexProvider>(); services.Services.AddSingleton<IIndexPropertyProvider, IndexPropertyProvider<AnimalIndex>>(); services.Build(); var returnType = new ListGraphType<StringGraphType>(); returnType.ResolvedType = new StringGraphType() { Name = "Animal" }; var animalWhereInput = new AnimalPartWhereInput(); var inputs = new FieldType { Name = "Inputs", Arguments = new QueryArguments { new QueryArgument<WhereInputObjectGraphType> { Name = "where", Description = "filters the animals", ResolvedType = animalWhereInput } } }; var context = new ResolveFieldContext { Arguments = new Dictionary<string, object>(), UserContext = new GraphQLContext { ServiceProvider = services }, ReturnType = returnType, FieldDefinition = inputs }; var ci = new ContentItem { ContentType = "Animal", Published = true, ContentItemId = "1", ContentItemVersionId = "1" }; ci.Weld(new AnimalPart { Name = "doug" }); var session = ((GraphQLContext)context.UserContext).ServiceProvider.GetService<ISession>(); session.Save(ci); await session.CommitAsync(); var type = new ContentItemsFieldType("Animal", new Schema(), Options.Create(new GraphQLContentOptions()), Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 })); context.Arguments["where"] = JObject.Parse("{ animal: { name: \"doug\" } }"); var dogs = await ((LockedAsyncFieldResolver<IEnumerable<ContentItem>>)type.Resolver).Resolve(context); Assert.Single(dogs); Assert.Equal("doug", dogs.First().As<AnimalPart>().Name); } } [Fact] public async Task ShouldFilterByCollapsedWhereInputForCollapsedParts() { await _initializeTask; _store.RegisterIndexes<AnimalIndexProvider>(); using (var services = new FakeServiceCollection()) { services.Populate(new ServiceCollection()); services.Services.AddScoped(x => new ShellSettings()); services.Services.AddScoped(x => _store.CreateSession()); services.Services.AddScoped<IIndexProvider, ContentItemIndexProvider>(); services.Services.AddScoped<IIndexProvider, AnimalIndexProvider>(); services.Services.AddScoped<IIndexAliasProvider, MultipleAliasIndexProvider>(); services.Services.AddSingleton<IIndexPropertyProvider, IndexPropertyProvider<AnimalIndex>>(); services.Build(); var returnType = new ListGraphType<StringGraphType>(); returnType.ResolvedType = new StringGraphType() { Name = "Animal" }; var animalWhereInput = new AnimalPartCollapsedWhereInput(); var context = new ResolveFieldContext { Arguments = new Dictionary<string, object>(), UserContext = new GraphQLContext { ServiceProvider = services }, ReturnType = returnType, FieldDefinition = new FieldType { Name = "Inputs", Arguments = new QueryArguments { new QueryArgument<WhereInputObjectGraphType> { Name = "where", Description = "filters the animals", ResolvedType = animalWhereInput } } } }; var ci = new ContentItem { ContentType = "Animal", Published = true, ContentItemId = "1", ContentItemVersionId = "1" }; ci.Weld(new AnimalPart { Name = "doug" }); var session = ((GraphQLContext)context.UserContext).ServiceProvider.GetService<ISession>(); session.Save(ci); await session.CommitAsync(); var type = new ContentItemsFieldType("Animal", new Schema(), Options.Create(new GraphQLContentOptions()), Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 })); context.Arguments["where"] = JObject.Parse("{ name: \"doug\" }"); var dogs = await ((LockedAsyncFieldResolver<IEnumerable<ContentItem>>)type.Resolver).Resolve(context); Assert.Single(dogs); Assert.Equal("doug", dogs.First().As<AnimalPart>().Name); } } } public class AnimalPartWhereInput : WhereInputObjectGraphType { public AnimalPartWhereInput() { Name = "Test"; Description = "Foo"; AddField(new FieldType { Name = "Animal", Type = typeof(StringGraphType), Metadata = new Dictionary<string, object> { { "PartName", "AnimalPart" } } }); } public AnimalPartWhereInput(string fieldName) { Name = "Test"; Description = "Foo"; AddField(new FieldType { Name = fieldName, Type = typeof(StringGraphType), Metadata = new Dictionary<string, object> { { "PartName", "AnimalPart" } } }); } } public class AnimalPartCollapsedWhereInput : WhereInputObjectGraphType { public AnimalPartCollapsedWhereInput() { Name = "Test"; Description = "Foo"; AddField(new FieldType { Name = "Name", Type = typeof(StringGraphType), Metadata = new Dictionary<string, object> { { "PartName", "AnimalPart" }, { "PartCollapsed", true } } }); } } public class Animal : ContentPart { public string Name { get; set; } public bool IsHappy { get; set; } public bool IsScary { get; set; } } public class AnimalPart : Animal { }; public class AnimalIndex : MapIndex { public string Name { get; set; } } public class AnimalIndexProvider : IndexProvider<ContentItem> { public override void Describe(DescribeContext<ContentItem> context) { context.For<AnimalIndex>() .Map(contentItem => { return new AnimalIndex { Name = contentItem.As<Animal>() != null ? contentItem.As<Animal>().Name : contentItem.As<AnimalPart>().Name }; }); } } public class AnimalTraitsIndex : MapIndex { public bool IsHappy { get; set; } public bool IsScary { get; set; } } public class AnimalTraitsIndexProvider : IndexProvider<ContentItem> { public override void Describe(DescribeContext<ContentItem> context) { context.For<AnimalTraitsIndex>() .Map(contentItem => { var animal = contentItem.As<Animal>(); if (animal != null) { return new AnimalTraitsIndex { IsHappy = contentItem.As<Animal>().IsHappy, IsScary = contentItem.As<Animal>().IsScary }; } var animalPartSuffix = contentItem.As<AnimalPart>(); return new AnimalTraitsIndex { IsHappy = animalPartSuffix.IsHappy, IsScary = animalPartSuffix.IsScary }; }); } } public class MultipleAliasIndexProvider : IIndexAliasProvider { private static readonly IndexAlias[] _aliases = new[] { new IndexAlias { Alias = "cats", Index = nameof(AnimalIndex), With = q => q.With<AnimalIndex>() }, new IndexAlias { Alias = "dogs", Index = nameof(AnimalIndex), With = q => q.With<AnimalIndex>() }, new IndexAlias { Alias = nameof(AnimalPart), Index = nameof(AnimalIndex), With = q => q.With<AnimalIndex>() } }; public IEnumerable<IndexAlias> GetAliases() { return _aliases; } } public class MultipleIndexesIndexProvider : IIndexAliasProvider { private static readonly IndexAlias[] _aliases = new[] { new IndexAlias { Alias = "animals.name", Index = $"Name", With = q => q.With<AnimalIndex>() }, new IndexAlias { Alias = "animals.isHappy", Index = $"IsHappy", With = q => q.With<AnimalTraitsIndex>() }, new IndexAlias { Alias = "animals.isScary", Index = $"IsScary", With = q => q.With<AnimalTraitsIndex>() } }; public IEnumerable<IndexAlias> GetAliases() { return _aliases; } } public class FakeServiceCollection : IServiceProvider, IDisposable { private IServiceProvider _inner; private IServiceCollection _services; public IServiceCollection Services => _services; public string State { get; set; } public object GetService(Type serviceType) { return _inner.GetService(serviceType); } public void Populate(IServiceCollection services) { _services = services; _services.AddSingleton<FakeServiceCollection>(this); } public void Build() { _inner = _services.BuildServiceProvider(); } public void Dispose() { (_inner as IDisposable)?.Dispose(); } } }
#region Copyright & License // // Copyright 2006 The Apache Software Foundation // // 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.Text; using System.Xml; using System.Text.RegularExpressions; namespace log4net.Util { /// <summary> /// Utility class that represents a format string. /// </summary> /// <remarks> /// <para> /// Utility class that represents a format string. /// </para> /// </remarks> /// <author>Nicko Cadell</author> public sealed class SystemStringFormat { private readonly IFormatProvider m_provider; private readonly string m_format; private readonly object[] m_args; #region Constructor /// <summary> /// Initialise the <see cref="SystemStringFormat"/> /// </summary> /// <param name="provider">An <see cref="System.IFormatProvider"/> that supplies culture-specific formatting information.</param> /// <param name="format">A <see cref="System.String"/> containing zero or more format items.</param> /// <param name="args">An <see cref="System.Object"/> array containing zero or more objects to format.</param> public SystemStringFormat(IFormatProvider provider, string format, params object[] args) { m_provider = provider; m_format = format; m_args = args; } #endregion Constructor /// <summary> /// Format the string and arguments /// </summary> /// <returns>the formatted string</returns> public override string ToString() { return StringFormat(m_provider, m_format, m_args); } #region StringFormat /// <summary> /// Replaces the format item in a specified <see cref="System.String"/> with the text equivalent /// of the value of a corresponding <see cref="System.Object"/> instance in a specified array. /// A specified parameter supplies culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="System.IFormatProvider"/> that supplies culture-specific formatting information.</param> /// <param name="format">A <see cref="System.String"/> containing zero or more format items.</param> /// <param name="args">An <see cref="System.Object"/> array containing zero or more objects to format.</param> /// <returns> /// A copy of format in which the format items have been replaced by the <see cref="System.String"/> /// equivalent of the corresponding instances of <see cref="System.Object"/> in args. /// </returns> /// <remarks> /// <para> /// This method does not throw exceptions. If an exception thrown while formatting the result the /// exception and arguments are returned in the result string. /// </para> /// </remarks> private static string StringFormat(IFormatProvider provider, string format, params object[] args) { try { // The format is missing, log null value if (format == null) { return null; } // The args are missing - should not happen unless we are called explicitly with a null array if (args == null) { return format; } // Try to format the string return String.Format(provider, format, args); } catch(Exception ex) { log4net.Util.LogLog.Warn("StringFormat: Exception while rendering format ["+format+"]", ex); return StringFormatError(ex, format, args); } catch { log4net.Util.LogLog.Warn("StringFormat: Exception while rendering format ["+format+"]"); return StringFormatError(null, format, args); } } /// <summary> /// Process an error during StringFormat /// </summary> private static string StringFormatError(Exception formatException, string format, object[] args) { try { StringBuilder buf = new StringBuilder("<log4net.Error>"); if (formatException != null) { buf.Append("Exception during StringFormat: ").Append(formatException.Message); } else { buf.Append("Exception during StringFormat"); } buf.Append(" <format>").Append(format).Append("</format>"); buf.Append("<args>"); RenderArray(args, buf); buf.Append("</args>"); buf.Append("</log4net.Error>"); return buf.ToString(); } catch(Exception ex) { log4net.Util.LogLog.Error("StringFormat: INTERNAL ERROR during StringFormat error handling", ex); return "<log4net.Error>Exception during StringFormat. See Internal Log.</log4net.Error>"; } catch { log4net.Util.LogLog.Error("StringFormat: INTERNAL ERROR during StringFormat error handling"); return "<log4net.Error>Exception during StringFormat. See Internal Log.</log4net.Error>"; } } /// <summary> /// Dump the contents of an array into a string builder /// </summary> private static void RenderArray(Array array, StringBuilder buffer) { if (array == null) { buffer.Append(SystemInfo.NullText); } else { if (array.Rank != 1) { buffer.Append(array.ToString()); } else { buffer.Append("{"); int len = array.Length; if (len > 0) { RenderObject(array.GetValue(0), buffer); for (int i = 1; i < len; i++) { buffer.Append(", "); RenderObject(array.GetValue(i), buffer); } } buffer.Append("}"); } } } /// <summary> /// Dump an object to a string /// </summary> private static void RenderObject(Object obj, StringBuilder buffer) { if (obj == null) { buffer.Append(SystemInfo.NullText); } else { try { buffer.Append(obj); } catch(Exception ex) { buffer.Append("<Exception: ").Append(ex.Message).Append(">"); } catch { buffer.Append("<Exception>"); } } } #endregion StringFormat } }
/************************************************************************************ Filename : OVRDevice.cs Content : Interface for the Oculus Rift Device Created : February 14, 2013 Authors : Peter Giokaris Copyright : Copyright 2014 Oculus VR, Inc. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.1 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ using UnityEngine; using System; using System.Collections.Generic; using System.Runtime.InteropServices; //------------------------------------------------------------------------------------- // ***** OVRDevice // /// <summary> /// OVRDevice is the main interface to the Oculus Rift hardware. It includes wrapper functions /// for all exported C++ functions, as well as helper functions that use the stored Oculus /// variables to help set up camera behavior. /// /// This component is added to the OVRCameraController prefab. It can be part of any /// game object that one sees fit to place it. However, it should only be declared once, /// since there are public members that allow for tweaking certain Rift values in the /// Unity inspector. /// /// </summary> public class OVRDevice : MonoBehaviour { // Imported functions from // OVRPlugin.dll (PC) // OVRPlugin.bundle (OSX) // OVRPlugin.so (Linux, Android) // MessageList [StructLayout(LayoutKind.Sequential)] public struct MessageList { public byte isHMDSensorAttached; public byte isHMDAttached; public byte isLatencyTesterAttached; public MessageList(byte HMDSensor, byte HMD, byte LatencyTester) { isHMDSensorAttached = HMDSensor; isHMDAttached = HMD; isLatencyTesterAttached = LatencyTester; } } public const string strOvrLib = "OculusPlugin"; [DllImport (strOvrLib)] private static extern bool OVR_Initialize(); [DllImport (strOvrLib)] private static extern bool OVR_Update(ref MessageList messageList); [DllImport (strOvrLib)] private static extern bool OVR_Destroy(); // SENSOR FUNCTIONS [DllImport (strOvrLib)] private static extern bool OVR_IsSensorPresent(); [DllImport (strOvrLib)] private static extern bool OVR_UseSensorPrediction(bool predictionOn); [DllImport (strOvrLib)] private static extern bool OVR_GetSensorPredictionTime(ref float predictionTime); [DllImport (strOvrLib)] private static extern bool OVR_SetSensorPredictionTime(float predictionTime); [DllImport (strOvrLib)] private static extern bool OVR_ResetSensorOrientation(); [DllImport (strOvrLib)] private static extern bool OVR_GetAcceleration(ref float x, ref float y, ref float z); [DllImport (strOvrLib)] private static extern bool OVR_GetAngularVelocity(ref float x, ref float y, ref float z); [DllImport (strOvrLib)] private static extern bool OVR_GetMagnetometer(ref float x, ref float y, ref float z); // CAMERA VISION FUNCTIONS [DllImport (strOvrLib)] private static extern bool OVR_IsCameraPresent(); [DllImport (strOvrLib)] private static extern bool OVR_IsCameraTracking(); [DllImport (strOvrLib)] private static extern void OVR_ResetCameraOffset(); [DllImport (strOvrLib)] private static extern void OVR_SetHeadModel(float x, float y, float z); [DllImport (strOvrLib)] private static extern bool OVR_GetCameraPositionOrientation(ref float px, ref float py, ref float pz, ref float ox, ref float oy, ref float oz, ref float ow); [DllImport (strOvrLib)] private static extern void OVR_SetVisionEnabled(bool on); // HMD FUNCTIONS [DllImport (strOvrLib)] private static extern bool OVR_IsHMDPresent(); [DllImport (strOvrLib)] private static extern void OVR_SetLowPersistenceMode(bool on); [DllImport (strOvrLib)] private static extern bool OVR_GetPlayerEyeHeight(ref float eyeHeight); [DllImport (strOvrLib)] private static extern bool OVR_GetInterpupillaryDistance(ref float interpupillaryDistance); // LATENCY TEST FUNCTIONS [DllImport (strOvrLib)] private static extern void OVR_ProcessLatencyInputs(); [DllImport (strOvrLib)] private static extern bool OVR_DisplayLatencyScreenColor(ref byte r, ref byte g, ref byte b); [DllImport (strOvrLib)] private static extern System.IntPtr OVR_GetLatencyResultsString(); // MAGNETOMETER YAW-DRIFT CORRECTION FUNCTIONS [DllImport (strOvrLib)] private static extern bool OVR_IsMagCalibrated(); [DllImport (strOvrLib)] private static extern bool OVR_EnableMagYawCorrection(bool enable); [DllImport (strOvrLib)] private static extern bool OVR_IsYawCorrectionEnabled(); // PUBLIC public float PredictionTime = 0.03f; // 30 ms public bool ResetTrackerOnLoad = true; // if off, tracker will not reset when new scene // is loaded // STATIC private static MessageList MsgList = new MessageList(0, 0, 0); private static bool OVRInit = false; // * * * * * * * * * * * * * /// <summary> /// Awake this instance. /// </summary> void Awake () { // Init OVRInit = OVR_Initialize(); if(OVRInit == false) return; // Set initial prediction time SetPredictionTime(PredictionTime); } /// <summary> /// Start this instance. /// (Note: make sure to always have a Start function for classes that have /// editors attached to them) /// </summary> void Start() { } /// <summary> /// We can detect if our devices have been plugged or unplugged, as well as /// run things that need to be updated in our game thread /// </summary> void Update() { MessageList oldMsgList = MsgList; OVR_Update(ref MsgList); // HMD SENSOR if((MsgList.isHMDSensorAttached != 0) && (oldMsgList.isHMDSensorAttached == 0)) { OVRMessenger.Broadcast<OVRMainMenu.Device, bool>("Sensor_Attached", OVRMainMenu.Device.HMDSensor, true); //Debug.Log("HMD SENSOR ATTACHED"); } else if((MsgList.isHMDSensorAttached == 0) && (oldMsgList.isHMDSensorAttached != 0)) { OVRMessenger.Broadcast<OVRMainMenu.Device, bool>("Sensor_Attached", OVRMainMenu.Device.HMDSensor, false); //Debug.Log("HMD SENSOR DETACHED"); } // HMD if((MsgList.isHMDAttached != 0) && (oldMsgList.isHMDAttached == 0)) { OVRMessenger.Broadcast<OVRMainMenu.Device, bool>("Sensor_Attached", OVRMainMenu.Device.HMD, true); //Debug.Log("HMD ATTACHED"); } else if((MsgList.isHMDAttached == 0) && (oldMsgList.isHMDAttached != 0)) { OVRMessenger.Broadcast<OVRMainMenu.Device, bool>("Sensor_Attached", OVRMainMenu.Device.HMD, false); //Debug.Log("HMD DETACHED"); } // LATENCY TESTER if((MsgList.isLatencyTesterAttached != 0) && (oldMsgList.isLatencyTesterAttached == 0)) { OVRMessenger.Broadcast<OVRMainMenu.Device, bool>("Sensor_Attached", OVRMainMenu.Device.LatencyTester, true); //Debug.Log("LATENCY TESTER ATTACHED"); } else if((MsgList.isLatencyTesterAttached == 0) && (oldMsgList.isLatencyTesterAttached != 0)) { OVRMessenger.Broadcast<OVRMainMenu.Device, bool>("Sensor_Attached", OVRMainMenu.Device.LatencyTester, false); //Debug.Log("LATENCY TESTER DETACHED"); } // Update prediction if being changed from outside PredictionTime = GetPredictionTime(); } /// <summary> /// Raises the destroy event. /// </summary> void OnDestroy() { // We may want to turn this off so that values are maintained between level / scene loads if(ResetTrackerOnLoad == true) { OVR_Destroy(); OVRInit = false; } } // * * * * * * * * * * * * // PUBLIC FUNCTIONS // * * * * * * * * * * * * /// <summary> /// Inited - Check to see if system has been initialized /// </summary> /// <returns><c>true</c> if is initialized; otherwise, <c>false</c>.</returns> public static bool IsInitialized() { return OVRInit; } /// <summary> /// Determines if is HMD present. /// </summary> /// <returns><c>true</c> if is HMD present; otherwise, <c>false</c>.</returns> public static bool IsHMDPresent() { return OVR_IsHMDPresent(); } /// <summary> /// Determines if is sensor present. /// </summary> /// <returns><c>true</c> if is sensor present; otherwise, <c>false</c>.</returns> public static bool IsSensorPresent() { return OVR_IsSensorPresent(); } /// <summary> /// Resets the orientation. /// </summary> /// <returns><c>true</c>, if orientation was reset, <c>false</c> otherwise.</returns> public static bool ResetOrientation() { return OVR_ResetSensorOrientation(); } // Latest absolute sensor readings (note: in right-hand co-ordinates) /// <summary> /// Gets the acceleration. /// </summary> /// <returns><c>true</c>, if acceleration was gotten, <c>false</c> otherwise.</returns> /// <param name="x">The x coordinate.</param> /// <param name="y">The y coordinate.</param> /// <param name="z">The z coordinate.</param> public static bool GetAcceleration(ref float x, ref float y, ref float z) { return OVR_GetAcceleration(ref x, ref y, ref z); } /// <summary> /// Gets the angular velocity. /// </summary> /// <returns><c>true</c>, if angular velocity was gotten, <c>false</c> otherwise.</returns> /// <param name="x">The x coordinate.</param> /// <param name="y">The y coordinate.</param> /// <param name="z">The z coordinate.</param> public static bool GetAngularVelocity(ref float x, ref float y, ref float z) { return OVR_GetAngularVelocity(ref x, ref y, ref z); } /// <summary> /// Gets the magnetometer. /// </summary> /// <returns><c>true</c>, if magnetometer was gotten, <c>false</c> otherwise.</returns> /// <param name="x">The x coordinate.</param> /// <param name="y">The y coordinate.</param> /// <param name="z">The z coordinate.</param> public static bool GetMagnetometer(ref float x, ref float y, ref float z) { return OVR_GetMagnetometer(ref x, ref y, ref z); } /// <summary> /// Uses the prediction. /// </summary> /// <param name="on">If set to <c>true</c> on.</param> public static void UsePrediction(bool on) { OVR_UseSensorPrediction(on); } /// <summary> /// Gets the prediction time. /// </summary> /// <returns>The prediction time.</returns> public static float GetPredictionTime() { float pt = 0.0f; OVR_GetSensorPredictionTime(ref pt); return pt; } /// <summary> /// Sets the prediction time. /// </summary> /// <returns><c>true</c>, if prediction time was set, <c>false</c> otherwise.</returns> /// <param name="predictionTime">Prediction time.</param> public static bool SetPredictionTime(float predictionTime) { return OVR_SetSensorPredictionTime(predictionTime); } /// <summary> /// Gets the IPD. /// </summary> /// <returns><c>true</c>, if IP was gotten, <c>false</c> otherwise.</returns> /// <param name="IPD">IP.</param> public static bool GetIPD(ref float IPD) { if(!OVRInit) return false; OVR_GetInterpupillaryDistance(ref IPD); return true; } /// <summary> /// Processes the latency inputs. /// </summary> public static void ProcessLatencyInputs() { OVR_ProcessLatencyInputs(); } /// <summary> /// Displays the color of the latency screen. /// </summary> /// <returns><c>true</c>, if latency screen color was displayed, <c>false</c> otherwise.</returns> /// <param name="r">The red component.</param> /// <param name="g">The green component.</param> /// <param name="b">The blue component.</param> public static bool DisplayLatencyScreenColor(ref byte r, ref byte g, ref byte b) { return OVR_DisplayLatencyScreenColor(ref r, ref g, ref b); } /// <summary> /// Gets the latency results string. /// </summary> /// <returns>The latency results string.</returns> public static System.IntPtr GetLatencyResultsString() { return OVR_GetLatencyResultsString(); } // MAG YAW-DRIFT CORRECTION FUNCTIONS /// <summary> /// Determines if is mag calibrated. /// </summary> /// <returns><c>true</c> if is mag calibrated; otherwise, <c>false</c>.</returns> public static bool IsMagCalibrated() { return OVR_IsMagCalibrated(); } /// <summary> /// Enables the mag yaw correction. /// </summary> /// <returns><c>true</c>, if mag yaw correction was enabled, <c>false</c> otherwise.</returns> /// <param name="enable">If set to <c>true</c> enable.</param> public static bool EnableMagYawCorrection(bool enable) { return OVR_EnableMagYawCorrection(enable); } /// <summary> /// Determines if is yaw correction enabled. /// </summary> /// <returns><c>true</c> if is yaw correction enabled; otherwise, <c>false</c>.</returns> public static bool IsYawCorrectionEnabled() { return OVR_IsYawCorrectionEnabled(); } /// <summary> /// Orients the sensor. /// </summary> /// <param name="q">Q.</param> public static void OrientSensor(ref Quaternion q) { // Change the co-ordinate system from right-handed to Unity left-handed /* q.x = x; q.y = y; q.z = -z; q = Quaternion.Inverse(q); */ // The following does the exact same conversion as above q.x = -q.x; q.y = -q.y; } /// <summary> /// Gets the height of the player eye. /// </summary> /// <returns><c>true</c>, if player eye height was gotten, <c>false</c> otherwise.</returns> /// <param name="eyeHeight">Eye height.</param> public static bool GetPlayerEyeHeight(ref float eyeHeight) { return OVR_GetPlayerEyeHeight(ref eyeHeight); } // CAMERA VISION FUNCTIONS /// <summary> /// Determines if is camera present. /// </summary> /// <returns><c>true</c> if is camera present; otherwise, <c>false</c>.</returns> public static bool IsCameraPresent() { return OVR_IsCameraPresent(); } /// <summary> /// Determines if is camera tracking. /// </summary> /// <returns><c>true</c> if is camera tracking; otherwise, <c>false</c>.</returns> public static bool IsCameraTracking() { return OVR_IsCameraTracking (); } /// <summary> /// Resets the camera offsdet. /// </summary> public static void ResetCameraOffsdet() { OVR_ResetCameraOffset(); } /// <summary> /// Sets the head model. /// </summary> /// <param name="x">The x coordinate.</param> /// <param name="y">The y coordinate.</param> /// <param name="z">The z coordinate.</param> public static void SetHeadModel(float x, float y, float z) { // make sure to negate z, so that the position is right-handed CS OVR_SetHeadModel(x,y,-z); } /// <summary> /// Gets the camera position orientation. /// </summary> /// <returns><c>true</c>, if camera position orientation was gotten, <c>false</c> otherwise.</returns> /// <param name="p">P.</param> /// <param name="o">O.</param> public static bool GetCameraPositionOrientation(ref Vector3 p, ref Quaternion o) { float px = 0, py = 0, pz = 0, ow = 0, ox = 0, oy = 0, oz = 0; bool result = OVR_GetCameraPositionOrientation(ref px, ref py, ref pz, ref ox, ref oy, ref oz, ref ow); p.x = px; p.y = py; p.z = -pz; o.w = ow; o.x = ox; o.y = oy; o.z = oz; // Convert to Left hand CS OrientSensor(ref o); return result; } /// <summary> /// Sets the vision enabled. /// </summary> /// <param name="on">If set to <c>true</c> on.</param> public static void SetVisionEnabled(bool on) { OVR_SetVisionEnabled (on); } /// <summary> /// Sets the low Persistence mode. /// </summary> /// <param name="on">If set to <c>true</c> on.</param> public static void SetLowPersistenceMode(bool on) { OVR_SetLowPersistenceMode(on); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Reactive.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using NUnit.Framework; using Refit; // InterfaceStubGenerator looks for this namespace Refit.Tests { public class RootObject { public string _id { get; set; } public string _rev { get; set; } public string name { get; set; } } [Headers("User-Agent: Refit Integration Tests")] public interface INpmJs { [Get("/congruence")] Task<RootObject> GetCongruence(); } public interface IRequestBin { [Post("/1h3a5jm1")] Task Post(); } public interface INoRefitHereBuddy { Task Post(); } public interface IAmHalfRefit { [Post("/anything")] Task Post(); Task Get(); } public interface IHttpBinApi<TResponse, in TParam, in THeader> where TResponse : class where THeader : struct { [Get("")] Task<TResponse> Get(TParam param, [Header("X-Refit")] THeader header); } public interface IBrokenWebApi { [Post("/what-spec")] Task<bool> PostAValue([Body] string derp); } public interface IHttpContentApi { [Post("/blah")] Task<HttpContent> PostFileUpload([Body] HttpContent content); } public class HttpBinGet { public Dictionary<string, string> Args { get; set; } public Dictionary<string, string> Headers { get; set; } public string Origin { get; set; } public string Url { get; set; } } [TestFixture] public class RestServiceIntegrationTests { [Test] public async Task HitTheGitHubUserApi() { var fixture = RestService.For<IGitHubApi>("https://api.github.com"); JsonConvert.DefaultSettings = () => new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() }; var result = await fixture.GetUser("octocat"); Assert.AreEqual("octocat", result.Login); Assert.IsFalse(String.IsNullOrEmpty(result.AvatarUrl)); } [Test] public async Task HitWithCamelCaseParameter() { var fixture = RestService.For<IGitHubApi>("https://api.github.com"); JsonConvert.DefaultSettings = () => new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() }; var result = await fixture.GetUserCamelCase("octocat"); Assert.AreEqual("octocat", result.Login); Assert.IsFalse(String.IsNullOrEmpty(result.AvatarUrl)); } [Test] public async Task HitTheGitHubOrgMembersApi() { var fixture = RestService.For<IGitHubApi>("https://api.github.com"); JsonConvert.DefaultSettings = () => new JsonSerializerSettings { ContractResolver = new SnakeCasePropertyNamesContractResolver() }; var result = await fixture.GetOrgMembers("github"); Assert.IsTrue(result.Count > 0); Assert.IsTrue(result.Any(member => member.Type == "User")); } [Test] public async Task HitTheGitHubUserSearchApi() { var fixture = RestService.For<IGitHubApi>("https://api.github.com"); JsonConvert.DefaultSettings = () => new JsonSerializerSettings { ContractResolver = new SnakeCasePropertyNamesContractResolver() }; var result = await fixture.FindUsers("tom repos:>42 followers:>1000"); Assert.IsTrue(result.TotalCount > 0); Assert.IsTrue(result.Items.Any(member => member.Type == "User")); } [Test] public async Task HitTheGitHubUserApiAsObservable() { var fixture = RestService.For<IGitHubApi>("https://api.github.com"); JsonConvert.DefaultSettings = () => new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() }; var result = await fixture.GetUserObservable("octocat") .Timeout(TimeSpan.FromSeconds(10)); Assert.AreEqual("octocat", result.Login); Assert.IsFalse(String.IsNullOrEmpty(result.AvatarUrl)); } [Test] public async Task HitTheGitHubUserApiAsObservableAndSubscribeAfterTheFact() { var fixture = RestService.For<IGitHubApi>("https://api.github.com"); JsonConvert.DefaultSettings = () => new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() }; var obs = fixture.GetUserObservable("octocat") .Timeout(TimeSpan.FromSeconds(10)); // NB: We're gonna await twice, so that the 2nd await is definitely // after the result has completed. await obs; var result2 = await obs; Assert.AreEqual("octocat", result2.Login); Assert.IsFalse(String.IsNullOrEmpty(result2.AvatarUrl)); } [Test] public async Task HitTheGitHubUserApiWithSettingsObj() { JsonConvert.DefaultSettings = () => new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var fixture = RestService.For<IGitHubApi>( "https://api.github.com", new RefitSettings{ JsonSerializerSettings = new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() } }); var result = await fixture.GetUser("octocat"); Assert.AreEqual("octocat", result.Login); Assert.IsFalse(String.IsNullOrEmpty(result.AvatarUrl)); } [Test] public async Task HitWithCamelCaseParameterWithSettingsObj() { JsonConvert.DefaultSettings = () => new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var fixture = RestService.For<IGitHubApi>( "https://api.github.com", new RefitSettings { JsonSerializerSettings = new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() } }); var result = await fixture.GetUserCamelCase("octocat"); Assert.AreEqual("octocat", result.Login); Assert.IsFalse(String.IsNullOrEmpty(result.AvatarUrl)); } [Test] public async Task HitTheGitHubOrgMembersApiWithSettingsObj() { JsonConvert.DefaultSettings = () => new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var fixture = RestService.For<IGitHubApi>( "https://api.github.com", new RefitSettings { JsonSerializerSettings = new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() } }); var result = await fixture.GetOrgMembers("github"); Assert.IsTrue(result.Count > 0); Assert.IsTrue(result.Any(member => member.Type == "User")); } [Test] public async Task HitTheGitHubUserSearchApiWithSettingsObj() { JsonConvert.DefaultSettings = () => new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var fixture = RestService.For<IGitHubApi>( "https://api.github.com", new RefitSettings { JsonSerializerSettings = new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() } }); var result = await fixture.FindUsers("tom repos:>42 followers:>1000"); Assert.IsTrue(result.TotalCount > 0); Assert.IsTrue(result.Items.Any(member => member.Type == "User")); } [Test] public async Task HitTheGitHubUserApiAsObservableWithSettingsObj() { JsonConvert.DefaultSettings = () => new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var fixture = RestService.For<IGitHubApi>( "https://api.github.com", new RefitSettings { JsonSerializerSettings = new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() } }); var result = await fixture.GetUserObservable("octocat") .Timeout(TimeSpan.FromSeconds(10)); Assert.AreEqual("octocat", result.Login); Assert.IsFalse(String.IsNullOrEmpty(result.AvatarUrl)); } [Test] public async Task HitTheGitHubUserApiAsObservableAndSubscribeAfterTheFactWithSettingsObj() { JsonConvert.DefaultSettings = () => new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var fixture = RestService.For<IGitHubApi>( "https://api.github.com", new RefitSettings { JsonSerializerSettings = new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() } }); var obs = fixture.GetUserObservable("octocat") .Timeout(TimeSpan.FromSeconds(10)); // NB: We're gonna await twice, so that the 2nd await is definitely // after the result has completed. await obs; var result2 = await obs; Assert.AreEqual("octocat", result2.Login); Assert.IsFalse(String.IsNullOrEmpty(result2.AvatarUrl)); } [Test] public async Task TwoSubscriptionsResultInTwoRequests() { var input = new TestHttpMessageHandler(); // we need to use a factory here to ensure each request gets its own httpcontent instance input.ContentFactory = () => new StringContent("test"); var client = new HttpClient(input) { BaseAddress = new Uri("http://foo") }; var fixture = RestService.For<IGitHubApi>(client); Assert.AreEqual(0, input.MessagesSent); var obs = fixture.GetIndexObservable() .Timeout(TimeSpan.FromSeconds(10)); var result1 = await obs; Assert.AreEqual(1, input.MessagesSent); var result2 = await obs; Assert.AreEqual(2, input.MessagesSent); // NB: TestHttpMessageHandler returns what we tell it to ('test' by default) Assert.IsTrue(result1.Contains("test")); Assert.IsTrue(result2.Contains("test")); } [Test] public async Task ShouldRetHttpResponseMessage() { var fixture = RestService.For<IGitHubApi>("https://api.github.com"); var result = await fixture.GetIndex(); Assert.IsNotNull(result); Assert.IsTrue(result.IsSuccessStatusCode); } [Test] public async Task HitTheNpmJs() { var fixture = RestService.For<INpmJs>("https://registry.npmjs.org"); var result = await fixture.GetCongruence(); Assert.AreEqual("congruence", result._id); } [Test] public async Task PostToRequestBin() { var fixture = RestService.For<IRequestBin>("http://httpbin.org/"); try { await fixture.Post(); } catch (ApiException ex) { // we should be good but maybe a 404 occurred } } [Test] public async Task CanGetDataOutOfErrorResponses() { var fixture = RestService.For<IGitHubApi>("https://api.github.com"); try { await fixture.NothingToSeeHere(); Assert.Fail(); } catch (ApiException exception) { Assert.AreEqual(HttpStatusCode.NotFound, exception.StatusCode); var content = exception.GetContentAs<Dictionary<string, string>>(); Assert.AreEqual("Not Found", content["message"]); Assert.IsNotNull(content["documentation_url"]); } } [Test] public void NonRefitInterfacesThrowMeaningfulExceptions() { try { RestService.For<INoRefitHereBuddy>("http://example.com"); } catch (InvalidOperationException exception) { StringAssert.StartsWith("INoRefitHereBuddy", exception.Message); } } [Test] public async Task NonRefitMethodsThrowMeaningfulExceptions() { try { var fixture = RestService.For<IAmHalfRefit>("http://example.com"); await fixture.Get(); } catch (NotImplementedException exception) { StringAssert.Contains("no Refit HTTP method attribute", exception.Message); } } [Test] public async Task GenericsWork() { var fixture = RestService.For<IHttpBinApi<HttpBinGet, string, int>>("http://httpbin.org/get"); var result = await fixture.Get("foo", 99); Assert.AreEqual("http://httpbin.org/get?param=foo", result.Url); Assert.AreEqual("foo", result.Args["param"]); Assert.AreEqual("99", result.Headers["X-Refit"]); } [Test] public async Task ValueTypesArentValidButTheyWorkAnyway() { var handler = new TestHttpMessageHandler("true"); var fixture = RestService.For<IBrokenWebApi>(new HttpClient(handler) { BaseAddress = new Uri("http://nowhere.com") }); var result = await fixture.PostAValue("Does this work?"); Assert.AreEqual(true, result); } } }
using System; using System.ComponentModel.DataAnnotations; using System.Diagnostics; using System.Net; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; #if !SILVERLIGHT using System.Web; #endif #if SERVERFX namespace OpenRiaServices.DomainServices.Hosting.Test #else namespace OpenRiaServices.DomainServices.Client.Test #endif { public delegate void GenericDelegate(); [DebuggerStepThrough] [System.Security.SecuritySafeCritical] // Because our assembly is [APTCA] and we are used from partial trust tests public static class ExceptionHelper { private static TException ExpectExceptionHelper<TException>(GenericDelegate del) where TException : Exception { return ExpectExceptionHelper<TException>(del, false); } private static TException ExpectExceptionHelper<TException>(GenericDelegate del, bool allowDerivedExceptions) where TException : Exception { try { del(); Assert.Fail("Expected exception of type " + typeof(TException) + "."); throw new Exception("can't happen"); } catch (TException e) { if (!allowDerivedExceptions) { Assert.AreEqual(typeof(TException), e.GetType()); } return e; } catch (TargetInvocationException e) { TException te = e.InnerException as TException; if (te == null) { // Rethrow if it's not the right type throw; } if (!allowDerivedExceptions) { Assert.AreEqual(typeof(TException), te.GetType()); } return te; } // HACK: (ron) Starting with VS 2008 SP1, I found the "catch (TException)" is not always catching the expected type // when running under the VS debugger. Added what looks like redundant code below, since that's the catch block // that's actually receiving the TException thrown. catch (Exception ex) { TException te = ex as TException; if (te != null) { if (!allowDerivedExceptions) { Assert.AreEqual(typeof(TException), ex.GetType()); } } else { Type tExpected = typeof(TException); Type tActual = ex.GetType(); Assert.Fail("Expected " + tExpected.Name + " but caught " + tActual.Name); } return te; } } public static TException ExpectException<TException>(GenericDelegate del) where TException : Exception { return ExpectException<TException>(del, false); } public static TException ExpectException<TException>(GenericDelegate del, bool allowDerivedExceptions) where TException : Exception { if (typeof(ArgumentNullException).IsAssignableFrom(typeof(TException))) { throw new InvalidOperationException( "ExpectException<TException>() cannot be used with exceptions of type 'ArgumentNullException'. " + "Use ExpectArgumentNullException() instead."); } else if (typeof(ArgumentException).IsAssignableFrom(typeof(TException))) { throw new InvalidOperationException( "ExpectException<TException>() cannot be used with exceptions of type 'ArgumentException'. " + "Use ExpectArgumentException() instead."); } return ExpectExceptionHelper<TException>(del, allowDerivedExceptions); } public static TException ExpectException<TException>(GenericDelegate del, string exceptionMessage) where TException : Exception { TException e = ExpectException<TException>(del); // Only check exception message on English build and OS, since some exception messages come from the OS // and will be in the native language. if (UnitTestHelper.EnglishBuildAndOS) { Assert.AreEqual(exceptionMessage, e.Message, "Incorrect exception message."); } return e; } public static ArgumentException ExpectArgumentException(GenericDelegate del, string exceptionMessage) { ArgumentException e = ExpectExceptionHelper<ArgumentException>(del); // Only check exception message on English build and OS, since some exception messages come from the OS // and will be in the native language. if (UnitTestHelper.EnglishBuildAndOS) { Assert.AreEqual(exceptionMessage, e.Message, "Incorrect exception message."); } return e; } public static ArgumentException ExpectArgumentException(GenericDelegate del, string exceptionMessage, string paramName) { ArgumentException e = ExpectExceptionHelper<ArgumentException>(del); var expectedException = new ArgumentException(exceptionMessage, paramName); Assert.AreEqual(expectedException.Message, e.Message); return e; } public static ArgumentNullException ExpectArgumentNullExceptionStandard(GenericDelegate del, string paramName) { ArgumentNullException e = ExpectExceptionHelper<ArgumentNullException>(del); var expectedException = new ArgumentNullException(paramName); Assert.AreEqual(expectedException.Message, e.Message); #if !SILVERLIGHT Assert.AreEqual(paramName, e.ParamName, "Incorrect exception parameter name."); #endif return e; } public static ArgumentNullException ExpectArgumentNullException(GenericDelegate del, string paramName) { return ExpectArgumentNullExceptionStandard(del, paramName); } public static ArgumentNullException ExpectArgumentNullException(GenericDelegate del, string exceptionMessage, string paramName) { ArgumentNullException e = ExpectExceptionHelper<ArgumentNullException>(del); var expectedException = new ArgumentNullException(paramName, exceptionMessage); Assert.AreEqual(expectedException.Message, e.Message); return e; } public static ArgumentOutOfRangeException ExpectArgumentOutOfRangeException(GenericDelegate del, string paramName, string exceptionMessage) { ArgumentOutOfRangeException e = ExpectExceptionHelper<ArgumentOutOfRangeException>(del); #if !SILVERLIGHT Assert.AreEqual(paramName, e.ParamName, "Incorrect exception parameter name."); #endif // Only check exception message on English build and OS, since some exception messages come from the OS // and will be in the native language. if (exceptionMessage != null && UnitTestHelper.EnglishBuildAndOS) { Assert.AreEqual(exceptionMessage, e.Message, "Incorrect exception message."); } return e; } public static InvalidOperationException ExpectInvalidOperationException(GenericDelegate del, string message) { InvalidOperationException e = ExpectExceptionHelper<InvalidOperationException>(del); Assert.AreEqual(message, e.Message); return e; } public static ValidationException ExpectValidationException(GenericDelegate del, string message, Type validationAttributeType, object value) { ValidationException e = ExpectExceptionHelper<ValidationException>(del); Assert.AreEqual(message, e.Message); Assert.AreEqual(value, e.Value); Assert.IsNotNull(e.ValidationAttribute); Assert.AreEqual(validationAttributeType, e.ValidationAttribute.GetType()); return e; } #if !SILVERLIGHT public static HttpException ExpectHttpException(GenericDelegate del, string message, int errorCode) { HttpException e = ExpectExceptionHelper<HttpException>(del); Assert.AreEqual(message, e.Message); Assert.AreEqual(errorCode, e.GetHttpCode()); return e; } #endif public static WebException ExpectWebException(GenericDelegate del, string message, int errorCode) { WebException e = ExpectExceptionHelper<WebException>(del); Assert.AreEqual(message, e.Message); HttpWebResponse response = e.Response as HttpWebResponse; Assert.AreEqual(errorCode, response.StatusCode); return e; } public static WebException ExpectWebException(GenericDelegate del, string message, WebExceptionStatus webExceptionStatus) { WebException e = ExpectExceptionHelper<WebException>(del); #if !SILVERLIGHT // Message is set to "" in Silverlight in some cases Assert.AreEqual(message, e.Message); #endif Assert.AreEqual(webExceptionStatus, e.Status); return e; } } }
/* * Copyright (2011) Intel Corporation and Sandia Corporation. Under the * terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the * U.S. Government retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * -- Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * -- Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * -- Neither the name of the Intel Corporation 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 INTEL OR ITS * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using WaterWars.Views.Interactions; using WaterWars.Views.Widgets.Behaviours; namespace WaterWars.Views.Widgets { /// <summary> /// A hud or in-world OpenSim button /// </summary> public class OsButton { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public static string OK_OPTION = "OK"; public static string CANCEL_OPTION = "Cancel"; public static string[] OK_CANCEL_OPTIONS = new string[] { OK_OPTION, CANCEL_OPTION }; public static string BUY_OPTION = "Buy"; public static string UPGRADE_OPTION = "Upgrade"; public static string SELL_OPTION = "Sell"; public static string[] BUY_UPGRADE_SELL_OPTIONS = new string[] { BUY_OPTION, UPGRADE_OPTION, SELL_OPTION }; public static string[] BUY_SELL_OPTIONS = new string[] { BUY_OPTION, SELL_OPTION }; public static string[] BUY_OPTIONS = new string[] { BUY_OPTION }; public static readonly UUID DUMMY_SCRIPT_UUID = UUID.Parse("00000000-0000-0000-0000-000000000001"); /// <value> /// Fired if the button receives chat, as happens if it's receiving information from a dialog box /// </value> public event OnChatDelegate OnChat; public delegate void OnChatDelegate(OSChatMessage chat); /// <value> /// Fired if the button is clicked /// </value> public event OnClickDelegate OnClick; public delegate void OnClickDelegate( Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs); /// <value> /// These handle the interaction between a particular player and this button /// </value> protected Dictionary<UUID, AbstractInteraction> m_interactions = new Dictionary<UUID, AbstractInteraction>(); public SceneObjectPart Part { get { return m_part; } } protected SceneObjectPart m_part; public IDialogModule DialogModule { get { return m_dialogModule; } } protected IDialogModule m_dialogModule; protected Scene m_scene; protected EventManager m_eventManager; public int Channel { get; private set; } public IDisplayBehaviour DisplayBehaviour { get; set; } public ILabelBehaviour LabelBehaviour { get { return m_labelBehaviour; } set { m_labelBehaviour = value; m_labelBehaviour.Button = this; m_labelBehaviour.UpdateAppearance(); } } protected ILabelBehaviour m_labelBehaviour; /// <value> /// The set of prim local ids for which we will need to process events. /// </value> protected HashSet<uint> m_localIds = new HashSet<uint>(); public OsButton(SceneObjectPart part, IDisplayBehaviour displayBehaviour) : this(part, displayBehaviour, new FixedLabelBehaviour()) {} public OsButton(SceneObjectPart part, IDisplayBehaviour displayBehaviour, ILabelBehaviour labelBehaviour) { m_part = part; m_scene = m_part.ParentGroup.Scene; ResetButtonPrims(); m_eventManager = m_scene.EventManager; m_dialogModule = m_scene.RequestModuleInterface<IDialogModule>(); DisplayBehaviour = displayBehaviour; displayBehaviour.Button = this; DisplayBehaviour.UpdateAppearance(); LabelBehaviour = labelBehaviour; } public OsButton(SceneObjectPart part, int channel, IDisplayBehaviour displayBehaviour) : this(part, displayBehaviour) { Channel = channel; } public OsButton(SceneObjectPart part, int channel, IDisplayBehaviour displayBehaviour, ILabelBehaviour labelBehaviour) : this(part, displayBehaviour, labelBehaviour) { Channel = channel; } /// <value> /// Enable or disable button /// </value> public virtual bool Enabled { get { return m_enabled; } set { if (value == m_enabled) return; m_enabled = value; Update(); } } protected bool m_enabled; /// <summary> /// Reset the prims the constitue this button. /// </summary> /// <remarks> /// This must be called if the object changes in the virtual environment. /// </remarks> /// <param name="part"></param> public void ResetButtonPrims(SceneObjectPart part) { m_part = part; ResetButtonPrims(); Update(); } /// <summary> /// Reset the prims that constitute this button /// </summary> /// <remarks> /// This must be called if the object is morphed in the virtual environment. /// </remarks> public void ResetButtonPrims() { m_localIds.Clear(); if (m_part.IsRoot) m_part.ParentGroup.ForEachPart(delegate(SceneObjectPart sop) { m_localIds.Add(sop.LocalId); }); else m_localIds.Add(m_part.LocalId); } protected void OnOsChat(object sender, OSChatMessage chat) { if (OnChat != null) { foreach (OnChatDelegate d in OnChat.GetInvocationList()) { try { d(chat); } catch (Exception e) { m_log.ErrorFormat( "[WATER WARS]: Delegate for OnOsChat failed - continuing. {0}{1}", e.Message, e.StackTrace); } } } } protected void OnOsTouch( uint localID, uint originalID, Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) { if (!m_localIds.Contains(originalID)) return; lock (m_interactions) { if (m_interactions.ContainsKey(remoteClient.AgentId)) { m_interactions[remoteClient.AgentId].Close(); m_interactions.Remove(remoteClient.AgentId); } AbstractInteraction interaction = CreateInteraction(remoteClient); // Not all clickable buttons implement interactions // FIXME: May change this at some stage for simplicity. if (interaction != null) m_interactions.Add(remoteClient.AgentId, interaction); } if (OnClick != null) { foreach (OnClickDelegate d in OnClick.GetInvocationList()) { try { d(offsetPos, remoteClient, surfaceArgs); } catch (Exception e) { m_log.ErrorFormat( "[WATER WARS]: Delegate for OnOsTouch failed - continuing. {0}{1}", e.Message, e.StackTrace); } } } // m_log.InfoFormat( // "[OS WIDGETS]: Fired OnTouch() with localID {0}, originalID {1} (part has localID {2}, Text {3})", // localID, originalID, m_part.LocalId, DisplayBehaviour.Text.Replace("\n", @"\n")); } public virtual void Close() { DisableEvents(); } protected void DisableEvents() { m_part.SetScriptEvents(DUMMY_SCRIPT_UUID, (int)scriptEvents.None); m_eventManager.OnObjectGrab -= OnOsTouch; m_eventManager.OnChatFromClient -= OnOsChat; } protected void EnableEvents() { m_part.SetScriptEvents(DUMMY_SCRIPT_UUID, (int)scriptEvents.touch); m_eventManager.OnObjectGrab += OnOsTouch; m_eventManager.OnChatFromClient += OnOsChat; } /// <summary> /// Update this button to match the current event listening and display requirements. /// </summary> /// <remarks> /// This is called when some button state is changed or if the underlying virtual environment object changes /// and needs to be resynchronized. /// </remarks> protected void Update() { if (m_enabled) { EnableEvents(); } else { DisableEvents(); } DisplayBehaviour.UpdateAppearance(); LabelBehaviour.UpdateAppearance(); } /// <summary> /// Override this if your button is involved in any dialog interactions. /// </summary> /// <param name="CreateInteraction"></param> protected virtual AbstractInteraction CreateInteraction(IClientAPI remoteClient) { return null; } /// <summary> /// Change the texture colour of the entire button. /// </summary> /// /// It is left to the caller to initiate an update of the part. /// /// <param name="newColor"></param> public void ChangeTextureColor(Color4 newColor) { Part.ParentGroup.ForEachPart( delegate(SceneObjectPart part) { Primitive.TextureEntry textures = part.Shape.Textures; if (textures.DefaultTexture != null) textures.DefaultTexture.RGBA = newColor; if (textures.FaceTextures != null) { foreach (Primitive.TextureEntryFace texture in textures.FaceTextures) { if (texture != null) texture.RGBA = newColor; } } // Tediously we have to do this to re-serialize the data into the underlying byte[] which is // actually used. part.Shape.Textures = textures; }); } /// <summary> /// Send an alert to everybody in the region /// </summary> /// <param name="text"></param> public void SendAlert(string text) { DialogModule.SendGeneralAlert(text); } /// <summary> /// Send an alert to a particular user /// </summary> /// <param name="userId"></param> /// <param name="text"></param> public void SendAlert(UUID userId, string text) { DialogModule.SendAlertToUser(userId, text); } /// <summary> /// Send an alert to a particular user /// </summary> /// <param name="userId"></param> /// <param name="textFormat"></param> /// <param name="textParams"></param> public void SendAlert(UUID userId, string textFormat, params object[] textParams) { DialogModule.SendAlertToUser(userId, string.Format(textFormat, textParams)); } /// <summary> /// Send a dialog to the user /// </summary> /// <param name="userId"></param> /// <param name="text"></param> /// <param name="options"></param> public void SendDialog(UUID userId, string text, string[] options) { DialogModule.SendDialogToUser( userId, Part.Name, Part.UUID, Part.OwnerID, text, new UUID("00000000-0000-2222-3333-100000001000"), Channel, options); } } }
#region License /* * WebSocketBehavior.cs * * The MIT License * * Copyright (c) 2012-2016 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion using System; using System.Collections.Specialized; using System.IO; using WebSocketSharp.Net; using WebSocketSharp.Net.WebSockets; namespace WebSocketSharp.Server { /// <summary> /// Exposes a set of methods and properties used to define the behavior of /// a WebSocket service provided by the <see cref="WebSocketServer"/> or /// <see cref="HttpServer"/>. /// </summary> /// <remarks> /// This class is an abstract class. /// </remarks> public abstract class WebSocketBehavior : IWebSocketSession { #region Private Fields private WebSocketContext _context; private Func<CookieCollection, CookieCollection, bool> _cookiesValidator; private bool _emitOnPing; private string _id; private bool _ignoreExtensions; private Func<string, bool> _originValidator; private string _protocol; private WebSocketSessionManager _sessions; private DateTime _startTime; private WebSocket _websocket; #endregion #region Protected Constructors /// <summary> /// Initializes a new instance of the <see cref="WebSocketBehavior"/> class. /// </summary> protected WebSocketBehavior () { _startTime = DateTime.MaxValue; } #endregion #region Protected Properties /// <summary> /// Gets the HTTP headers included in a WebSocket handshake request. /// </summary> /// <value> /// <para> /// A <see cref="NameValueCollection"/> that contains the headers. /// </para> /// <para> /// <see langword="null"/> if the session has not started yet. /// </para> /// </value> protected NameValueCollection Headers { get { return _context != null ? _context.Headers : null; } } /// <summary> /// Gets the logging function. /// </summary> /// <value> /// <para> /// A <see cref="Logger"/> that provides the logging function. /// </para> /// <para> /// <see langword="null"/> if the session has not started yet. /// </para> /// </value> [Obsolete ("This property will be removed.")] protected Logger Log { get { return _websocket != null ? _websocket.Log : null; } } /// <summary> /// Gets the query string included in a WebSocket handshake request. /// </summary> /// <value> /// <para> /// A <see cref="NameValueCollection"/> that contains the query /// parameters. /// </para> /// <para> /// An empty collection if not included. /// </para> /// <para> /// <see langword="null"/> if the session has not started yet. /// </para> /// </value> protected NameValueCollection QueryString { get { return _context != null ? _context.QueryString : null; } } /// <summary> /// Gets the management function for the sessions in the service. /// </summary> /// <value> /// <para> /// A <see cref="WebSocketSessionManager"/> that manages the sessions in /// the service. /// </para> /// <para> /// <see langword="null"/> if the session has not started yet. /// </para> /// </value> protected WebSocketSessionManager Sessions { get { return _sessions; } } #endregion #region Public Properties /// <summary> /// Gets the current state of the WebSocket connection for a session. /// </summary> /// <value> /// <para> /// One of the <see cref="WebSocketState"/> enum values. /// </para> /// <para> /// It indicates the current state of the connection. /// </para> /// <para> /// <see cref="WebSocketState.Connecting"/> if the session has not /// started yet. /// </para> /// </value> public WebSocketState ConnectionState { get { return _websocket != null ? _websocket.ReadyState : WebSocketState.Connecting; } } /// <summary> /// Gets the information in a WebSocket handshake request to the service. /// </summary> /// <value> /// <para> /// A <see cref="WebSocketContext"/> instance that provides the access to /// the information in the handshake request. /// </para> /// <para> /// <see langword="null"/> if the session has not started yet. /// </para> /// </value> public WebSocketContext Context { get { return _context; } } /// <summary> /// Gets or sets the delegate used to validate the HTTP cookies included in /// a WebSocket handshake request to the service. /// </summary> /// <value> /// <para> /// A <c>Func&lt;CookieCollection, CookieCollection, bool&gt;</c> delegate /// or <see langword="null"/> if not needed. /// </para> /// <para> /// The delegate invokes the method called when the WebSocket instance /// for a session validates the handshake request. /// </para> /// <para> /// 1st <see cref="CookieCollection"/> parameter passed to the method /// contains the cookies to validate if present. /// </para> /// <para> /// 2nd <see cref="CookieCollection"/> parameter passed to the method /// receives the cookies to send to the client. /// </para> /// <para> /// The method must return <c>true</c> if the cookies are valid. /// </para> /// <para> /// The default value is <see langword="null"/>. /// </para> /// </value> public Func<CookieCollection, CookieCollection, bool> CookiesValidator { get { return _cookiesValidator; } set { _cookiesValidator = value; } } /// <summary> /// Gets or sets a value indicating whether the WebSocket instance for /// a session emits the message event when receives a ping. /// </summary> /// <value> /// <para> /// <c>true</c> if the WebSocket instance emits the message event /// when receives a ping; otherwise, <c>false</c>. /// </para> /// <para> /// The default value is <c>false</c>. /// </para> /// </value> public bool EmitOnPing { get { return _websocket != null ? _websocket.EmitOnPing : _emitOnPing; } set { if (_websocket != null) { _websocket.EmitOnPing = value; return; } _emitOnPing = value; } } /// <summary> /// Gets the unique ID of a session. /// </summary> /// <value> /// <para> /// A <see cref="string"/> that represents the unique ID of the session. /// </para> /// <para> /// <see langword="null"/> if the session has not started yet. /// </para> /// </value> public string ID { get { return _id; } } /// <summary> /// Gets or sets a value indicating whether the service ignores /// the Sec-WebSocket-Extensions header included in a WebSocket /// handshake request. /// </summary> /// <value> /// <para> /// <c>true</c> if the service ignores the extensions requested /// from a client; otherwise, <c>false</c>. /// </para> /// <para> /// The default value is <c>false</c>. /// </para> /// </value> public bool IgnoreExtensions { get { return _ignoreExtensions; } set { _ignoreExtensions = value; } } /// <summary> /// Gets or sets the delegate used to validate the Origin header included in /// a WebSocket handshake request to the service. /// </summary> /// <value> /// <para> /// A <c>Func&lt;string, bool&gt;</c> delegate or <see langword="null"/> /// if not needed. /// </para> /// <para> /// The delegate invokes the method called when the WebSocket instance /// for a session validates the handshake request. /// </para> /// <para> /// The <see cref="string"/> parameter passed to the method is the value /// of the Origin header or <see langword="null"/> if the header is not /// present. /// </para> /// <para> /// The method must return <c>true</c> if the header value is valid. /// </para> /// <para> /// The default value is <see langword="null"/>. /// </para> /// </value> public Func<string, bool> OriginValidator { get { return _originValidator; } set { _originValidator = value; } } /// <summary> /// Gets or sets the name of the WebSocket subprotocol for the service. /// </summary> /// <value> /// <para> /// A <see cref="string"/> that represents the name of the subprotocol. /// </para> /// <para> /// The value specified for a set must be a token defined in /// <see href="http://tools.ietf.org/html/rfc2616#section-2.2"> /// RFC 2616</see>. /// </para> /// <para> /// The default value is an empty string. /// </para> /// </value> /// <exception cref="InvalidOperationException"> /// The set operation is not available if the session has already started. /// </exception> /// <exception cref="ArgumentException"> /// The value specified for a set operation is not a token. /// </exception> public string Protocol { get { return _websocket != null ? _websocket.Protocol : (_protocol ?? String.Empty); } set { if (ConnectionState != WebSocketState.Connecting) { var msg = "The session has already started."; throw new InvalidOperationException (msg); } if (value == null || value.Length == 0) { _protocol = null; return; } if (!value.IsToken ()) throw new ArgumentException ("Not a token.", "value"); _protocol = value; } } /// <summary> /// Gets the time that a session has started. /// </summary> /// <value> /// <para> /// A <see cref="DateTime"/> that represents the time that the session /// has started. /// </para> /// <para> /// <see cref="DateTime.MaxValue"/> if the session has not started yet. /// </para> /// </value> public DateTime StartTime { get { return _startTime; } } /// <summary> /// Gets the compression-method of the <see cref="WebSocket"/> used in a session. /// </summary> /// <value> /// One of the <see cref="CompressionMethod"/> enum values, indicates the compression of /// the <see cref="WebSocket"/>. /// </value> public CompressionMethod Compression { get { return _websocket.Compression; } } #endregion #region Private Methods private string checkHandshakeRequest (WebSocketContext context) { if (_originValidator != null) { if (!_originValidator (context.Origin)) return "It includes no Origin header or an invalid one."; } if (_cookiesValidator != null) { var req = context.CookieCollection; var res = context.WebSocket.CookieCollection; if (!_cookiesValidator (req, res)) return "It includes no cookie or an invalid one."; } return null; } private void onClose (object sender, CloseEventArgs e) { if (_id == null) return; _sessions.Remove (_id); OnClose (e); } private void onError (object sender, ErrorEventArgs e) { OnError (e); } private void onMessage (object sender, MessageEventArgs e) { OnMessage (e); } private void onOpen (object sender, EventArgs e) { _id = _sessions.Add (this); if (_id == null) { _websocket.Close (CloseStatusCode.Away); return; } _startTime = DateTime.Now; OnOpen (); OnOpen (_websocket); } #endregion #region Internal Methods internal void Start (WebSocketContext context, WebSocketSessionManager sessions) { if (_websocket != null) { _websocket.Log.Error ("A session instance cannot be reused."); context.WebSocket.Close (HttpStatusCode.ServiceUnavailable); return; } _context = context; _sessions = sessions; _websocket = context.WebSocket; _websocket.CustomHandshakeRequestChecker = checkHandshakeRequest; _websocket.EmitOnPing = _emitOnPing; _websocket.IgnoreExtensions = _ignoreExtensions; _websocket.Protocol = _protocol; var waitTime = sessions.WaitTime; if (waitTime != _websocket.WaitTime) _websocket.WaitTime = waitTime; _websocket.OnOpen += onOpen; _websocket.OnMessage += onMessage; _websocket.OnError += onError; _websocket.OnClose += onClose; _websocket.InternalAccept (); } #endregion #region Protected Methods /// <summary> /// Closes the WebSocket connection for a session. /// </summary> /// <remarks> /// This method does nothing if the current state of the connection is /// Closing or Closed. /// </remarks> /// <exception cref="InvalidOperationException"> /// The session has not started yet. /// </exception> protected void Close () { if (_websocket == null) { var msg = "The session has not started yet."; throw new InvalidOperationException (msg); } _websocket.Close (); } /// <summary> /// Closes the WebSocket connection for a session with the specified /// code and reason. /// </summary> /// <remarks> /// This method does nothing if the current state of the connection is /// Closing or Closed. /// </remarks> /// <param name="code"> /// <para> /// A <see cref="ushort"/> that represents the status code indicating /// the reason for the close. /// </para> /// <para> /// The status codes are defined in /// <see href="http://tools.ietf.org/html/rfc6455#section-7.4"> /// Section 7.4</see> of RFC 6455. /// </para> /// </param> /// <param name="reason"> /// <para> /// A <see cref="string"/> that represents the reason for the close. /// </para> /// <para> /// The size must be 123 bytes or less in UTF-8. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The session has not started yet. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <para> /// <paramref name="code"/> is less than 1000 or greater than 4999. /// </para> /// <para> /// -or- /// </para> /// <para> /// The size of <paramref name="reason"/> is greater than 123 bytes. /// </para> /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="code"/> is 1010 (mandatory extension). /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="code"/> is 1005 (no status) and there is reason. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="reason"/> could not be UTF-8-encoded. /// </para> /// </exception> protected void Close (ushort code, string reason) { if (_websocket == null) { var msg = "The session has not started yet."; throw new InvalidOperationException (msg); } _websocket.Close (code, reason); } /// <summary> /// Closes the WebSocket connection for a session with the specified /// code and reason. /// </summary> /// <remarks> /// This method does nothing if the current state of the connection is /// Closing or Closed. /// </remarks> /// <param name="code"> /// <para> /// One of the <see cref="CloseStatusCode"/> enum values. /// </para> /// <para> /// It represents the status code indicating the reason for the close. /// </para> /// </param> /// <param name="reason"> /// <para> /// A <see cref="string"/> that represents the reason for the close. /// </para> /// <para> /// The size must be 123 bytes or less in UTF-8. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The session has not started yet. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The size of <paramref name="reason"/> is greater than 123 bytes. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="code"/> is /// <see cref="CloseStatusCode.MandatoryExtension"/>. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="code"/> is /// <see cref="CloseStatusCode.NoStatus"/> and there is reason. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="reason"/> could not be UTF-8-encoded. /// </para> /// </exception> protected void Close (CloseStatusCode code, string reason) { if (_websocket == null) { var msg = "The session has not started yet."; throw new InvalidOperationException (msg); } _websocket.Close (code, reason); } /// <summary> /// Closes the WebSocket connection for a session asynchronously. /// </summary> /// <remarks> /// <para> /// This method does not wait for the close to be complete. /// </para> /// <para> /// This method does nothing if the current state of the connection is /// Closing or Closed. /// </para> /// </remarks> /// <exception cref="InvalidOperationException"> /// The session has not started yet. /// </exception> protected void CloseAsync () { if (_websocket == null) { var msg = "The session has not started yet."; throw new InvalidOperationException (msg); } _websocket.CloseAsync (); } /// <summary> /// Closes the WebSocket connection for a session asynchronously with /// the specified code and reason. /// </summary> /// <remarks> /// <para> /// This method does not wait for the close to be complete. /// </para> /// <para> /// This method does nothing if the current state of the connection is /// Closing or Closed. /// </para> /// </remarks> /// <param name="code"> /// <para> /// A <see cref="ushort"/> that represents the status code indicating /// the reason for the close. /// </para> /// <para> /// The status codes are defined in /// <see href="http://tools.ietf.org/html/rfc6455#section-7.4"> /// Section 7.4</see> of RFC 6455. /// </para> /// </param> /// <param name="reason"> /// <para> /// A <see cref="string"/> that represents the reason for the close. /// </para> /// <para> /// The size must be 123 bytes or less in UTF-8. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The session has not started yet. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <para> /// <paramref name="code"/> is less than 1000 or greater than 4999. /// </para> /// <para> /// -or- /// </para> /// <para> /// The size of <paramref name="reason"/> is greater than 123 bytes. /// </para> /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="code"/> is 1010 (mandatory extension). /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="code"/> is 1005 (no status) and there is reason. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="reason"/> could not be UTF-8-encoded. /// </para> /// </exception> protected void CloseAsync (ushort code, string reason) { if (_websocket == null) { var msg = "The session has not started yet."; throw new InvalidOperationException (msg); } _websocket.CloseAsync (code, reason); } /// <summary> /// Closes the WebSocket connection for a session asynchronously with /// the specified code and reason. /// </summary> /// <remarks> /// <para> /// This method does not wait for the close to be complete. /// </para> /// <para> /// This method does nothing if the current state of the connection is /// Closing or Closed. /// </para> /// </remarks> /// <param name="code"> /// <para> /// One of the <see cref="CloseStatusCode"/> enum values. /// </para> /// <para> /// It represents the status code indicating the reason for the close. /// </para> /// </param> /// <param name="reason"> /// <para> /// A <see cref="string"/> that represents the reason for the close. /// </para> /// <para> /// The size must be 123 bytes or less in UTF-8. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The session has not started yet. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="code"/> is /// <see cref="CloseStatusCode.MandatoryExtension"/>. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="code"/> is /// <see cref="CloseStatusCode.NoStatus"/> and there is reason. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="reason"/> could not be UTF-8-encoded. /// </para> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The size of <paramref name="reason"/> is greater than 123 bytes. /// </exception> protected void CloseAsync (CloseStatusCode code, string reason) { if (_websocket == null) { var msg = "The session has not started yet."; throw new InvalidOperationException (msg); } _websocket.CloseAsync (code, reason); } /// <summary> /// Calls the <see cref="OnError"/> method with the specified message. /// </summary> /// <param name="message"> /// A <see cref="string"/> that represents the error message. /// </param> /// <param name="exception"> /// An <see cref="Exception"/> instance that represents the cause of /// the error if present. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="message"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="message"/> is an empty string. /// </exception> [Obsolete ("This method will be removed.")] protected void Error (string message, Exception exception) { if (message == null) throw new ArgumentNullException ("message"); if (message.Length == 0) throw new ArgumentException ("An empty string.", "message"); OnError (new ErrorEventArgs (message, exception)); } /// <summary> /// Called when the WebSocket connection for a session has been closed. /// </summary> /// <param name="e"> /// A <see cref="CloseEventArgs"/> that represents the event data passed /// from a <see cref="WebSocket.OnClose"/> event. /// </param> protected virtual void OnClose (CloseEventArgs e) { } /// <summary> /// Called when the WebSocket instance for a session gets an error. /// </summary> /// <param name="e"> /// A <see cref="ErrorEventArgs"/> that represents the event data passed /// from a <see cref="WebSocket.OnError"/> event. /// </param> protected virtual void OnError (ErrorEventArgs e) { } /// <summary> /// Called when the WebSocket instance for a session receives a message. /// </summary> /// <param name="e"> /// A <see cref="MessageEventArgs"/> that represents the event data passed /// from a <see cref="WebSocket.OnMessage"/> event. /// </param> protected virtual void OnMessage (MessageEventArgs e) { } /// <summary> /// Called when the WebSocket connection for a session has been established. /// </summary> protected virtual void OnOpen () { } /// <summary> /// Called when the WebSocket connection for a session has been established. /// </summary> protected virtual void OnOpen(WebSocket webSocket) { } /// <summary> /// Sends the specified data to a client using the WebSocket connection. /// </summary> /// <param name="data"> /// An array of <see cref="byte"/> that represents the binary data to send. /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the connection is not Open. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="data"/> is <see langword="null"/>. /// </exception> protected void Send (byte[] data) { if (_websocket == null) { var msg = "The current state of the connection is not Open."; throw new InvalidOperationException (msg); } _websocket.Send (data); } /// <summary> /// Sends binary <paramref name="data"/> with Opcode.Text to the client on a session. /// </summary> /// <remarks> /// This method is available after the WebSocket connection has been established. /// </remarks> /// <param name="data"> /// An array of <see cref="byte"/> that represents the binary data to send. /// </param> protected void SendByteArrayAsText(byte[] data) { if (_websocket != null) _websocket.SendByteArrayAsText (data); } /// <summary> /// Sends the specified file to a client using the WebSocket connection. /// </summary> /// <param name="fileInfo"> /// <para> /// A <see cref="FileInfo"/> that specifies the file to send. /// </para> /// <para> /// The file is sent as the binary data. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the connection is not Open. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="fileInfo"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// The file does not exist. /// </para> /// <para> /// -or- /// </para> /// <para> /// The file could not be opened. /// </para> /// </exception> protected void Send (FileInfo fileInfo) { if (_websocket == null) { var msg = "The current state of the connection is not Open."; throw new InvalidOperationException (msg); } _websocket.Send (fileInfo); } /// <summary> /// Sends the specified data to a client using the WebSocket connection. /// </summary> /// <param name="data"> /// A <see cref="string"/> that represents the text data to send. /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the connection is not Open. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="data"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="data"/> could not be UTF-8-encoded. /// </exception> protected void Send (string data) { if (_websocket == null) { var msg = "The current state of the connection is not Open."; throw new InvalidOperationException (msg); } _websocket.Send (data); } /// <summary> /// Sends the data from the specified stream to a client using /// the WebSocket connection. /// </summary> /// <param name="stream"> /// <para> /// A <see cref="Stream"/> instance from which to read the data to send. /// </para> /// <para> /// The data is sent as the binary data. /// </para> /// </param> /// <param name="length"> /// An <see cref="int"/> that specifies the number of bytes to send. /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the connection is not Open. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="stream"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="stream"/> cannot be read. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="length"/> is less than 1. /// </para> /// <para> /// -or- /// </para> /// <para> /// No data could be read from <paramref name="stream"/>. /// </para> /// </exception> protected void Send (Stream stream, int length) { if (_websocket == null) { var msg = "The current state of the connection is not Open."; throw new InvalidOperationException (msg); } _websocket.Send (stream, length); } /// <summary> /// Sends the specified data to a client asynchronously using /// the WebSocket connection. /// </summary> /// <remarks> /// This method does not wait for the send to be complete. /// </remarks> /// <param name="data"> /// An array of <see cref="byte"/> that represents the binary data to send. /// </param> /// <param name="completed"> /// <para> /// An <c>Action&lt;bool&gt;</c> delegate or <see langword="null"/> /// if not needed. /// </para> /// <para> /// The delegate invokes the method called when the send is complete. /// </para> /// <para> /// <c>true</c> is passed to the method if the send has done with /// no error; otherwise, <c>false</c>. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the connection is not Open. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="data"/> is <see langword="null"/>. /// </exception> protected void SendAsync (byte[] data, Action<bool> completed) { if (_websocket == null) { var msg = "The current state of the connection is not Open."; throw new InvalidOperationException (msg); } _websocket.SendAsync (data, completed); } /// <summary> /// Sends the specified file to a client asynchronously using /// the WebSocket connection. /// </summary> /// <remarks> /// This method does not wait for the send to be complete. /// </remarks> /// <param name="fileInfo"> /// <para> /// A <see cref="FileInfo"/> that specifies the file to send. /// </para> /// <para> /// The file is sent as the binary data. /// </para> /// </param> /// <param name="completed"> /// <para> /// An <c>Action&lt;bool&gt;</c> delegate or <see langword="null"/> /// if not needed. /// </para> /// <para> /// The delegate invokes the method called when the send is complete. /// </para> /// <para> /// <c>true</c> is passed to the method if the send has done with /// no error; otherwise, <c>false</c>. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the connection is not Open. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="fileInfo"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// The file does not exist. /// </para> /// <para> /// -or- /// </para> /// <para> /// The file could not be opened. /// </para> /// </exception> protected void SendAsync (FileInfo fileInfo, Action<bool> completed) { if (_websocket == null) { var msg = "The current state of the connection is not Open."; throw new InvalidOperationException (msg); } _websocket.SendAsync (fileInfo, completed); } /// <summary> /// Sends the specified data to a client asynchronously using /// the WebSocket connection. /// </summary> /// <remarks> /// This method does not wait for the send to be complete. /// </remarks> /// <param name="data"> /// A <see cref="string"/> that represents the text data to send. /// </param> /// <param name="completed"> /// <para> /// An <c>Action&lt;bool&gt;</c> delegate or <see langword="null"/> /// if not needed. /// </para> /// <para> /// The delegate invokes the method called when the send is complete. /// </para> /// <para> /// <c>true</c> is passed to the method if the send has done with /// no error; otherwise, <c>false</c>. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the connection is not Open. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="data"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="data"/> could not be UTF-8-encoded. /// </exception> protected void SendAsync (string data, Action<bool> completed) { if (_websocket == null) { var msg = "The current state of the connection is not Open."; throw new InvalidOperationException (msg); } _websocket.SendAsync (data, completed); } /// <summary> /// Sends the data from the specified stream to a client asynchronously /// using the WebSocket connection. /// </summary> /// <remarks> /// This method does not wait for the send to be complete. /// </remarks> /// <param name="stream"> /// <para> /// A <see cref="Stream"/> instance from which to read the data to send. /// </para> /// <para> /// The data is sent as the binary data. /// </para> /// </param> /// <param name="length"> /// An <see cref="int"/> that specifies the number of bytes to send. /// </param> /// <param name="completed"> /// <para> /// An <c>Action&lt;bool&gt;</c> delegate or <see langword="null"/> /// if not needed. /// </para> /// <para> /// The delegate invokes the method called when the send is complete. /// </para> /// <para> /// <c>true</c> is passed to the method if the send has done with /// no error; otherwise, <c>false</c>. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the connection is not Open. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="stream"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="stream"/> cannot be read. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="length"/> is less than 1. /// </para> /// <para> /// -or- /// </para> /// <para> /// No data could be read from <paramref name="stream"/>. /// </para> /// </exception> protected void SendAsync (Stream stream, int length, Action<bool> completed) { if (_websocket == null) { var msg = "The current state of the connection is not Open."; throw new InvalidOperationException (msg); } _websocket.SendAsync (stream, length, completed); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.Contracts; namespace System.Globalization { // // This class implements the Julian calendar. In 48 B.C. Julius Caesar ordered a calendar reform, and this calendar // is called Julian calendar. It consisted of a solar year of twelve months and of 365 days with an extra day // every fourth year. //* //* Calendar support range: //* Calendar Minimum Maximum //* ========== ========== ========== //* Gregorian 0001/01/01 9999/12/31 //* Julia 0001/01/03 9999/10/19 [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class JulianCalendar : Calendar { public static readonly int JulianEra = 1; private const int DatePartYear = 0; private const int DatePartDayOfYear = 1; private const int DatePartMonth = 2; private const int DatePartDay = 3; // Number of days in a non-leap year private const int JulianDaysPerYear = 365; // Number of days in 4 years private const int JulianDaysPer4Years = JulianDaysPerYear * 4 + 1; private static readonly int[] s_daysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; private static readonly int[] s_daysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; // Gregorian Calendar 9999/12/31 = Julian Calendar 9999/10/19 // keep it as variable field for serialization compat. internal int MaxYear = 9999; [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } [System.Runtime.InteropServices.ComVisible(false)] public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } public JulianCalendar() { // There is no system setting of TwoDigitYear max, so set the value here. twoDigitYearMax = 2029; } internal override CalendarId ID { get { return CalendarId.JULIAN; } } internal static void CheckEraRange(int era) { if (era != CurrentEra && era != JulianEra) { throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue); } } internal void CheckYearEraRange(int year, int era) { CheckEraRange(era); if (year <= 0 || year > MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } } internal static void CheckMonthRange(int month) { if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException("month", SR.ArgumentOutOfRange_Month); } } /*===================================CheckDayRange============================ **Action: Check for if the day value is valid. **Returns: **Arguments: **Exceptions: **Notes: ** Before calling this method, call CheckYearEraRange()/CheckMonthRange() to make ** sure year/month values are correct. ============================================================================*/ internal static void CheckDayRange(int year, int month, int day) { if (year == 1 && month == 1) { // The mimimum supported Julia date is Julian 0001/01/03. if (day < 3) { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } } bool isLeapYear = (year % 4) == 0; int[] days = isLeapYear ? s_daysToMonth366 : s_daysToMonth365; int monthDays = days[month] - days[month - 1]; if (day < 1 || day > monthDays) { throw new ArgumentOutOfRangeException( "day", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, monthDays)); } } // Returns a given date part of this DateTime. This method is used // to compute the year, day-of-year, month, or day part. internal static int GetDatePart(long ticks, int part) { // Gregorian 1/1/0001 is Julian 1/3/0001. Remember DateTime(0) is refered to Gregorian 1/1/0001. // The following line convert Gregorian ticks to Julian ticks. long julianTicks = ticks + TicksPerDay * 2; // n = number of days since 1/1/0001 int n = (int)(julianTicks / TicksPerDay); // y4 = number of whole 4-year periods within 100-year period int y4 = n / JulianDaysPer4Years; // n = day number within 4-year period n -= y4 * JulianDaysPer4Years; // y1 = number of whole years within 4-year period int y1 = n / JulianDaysPerYear; // Last year has an extra day, so decrement result if 4 if (y1 == 4) y1 = 3; // If year was requested, compute and return it if (part == DatePartYear) { return (y4 * 4 + y1 + 1); } // n = day number within year n -= y1 * JulianDaysPerYear; // If day-of-year was requested, return it if (part == DatePartDayOfYear) { return (n + 1); } // Leap year calculation looks different from IsLeapYear since y1, y4, // and y100 are relative to year 1, not year 0 bool leapYear = (y1 == 3); int[] days = leapYear ? s_daysToMonth366 : s_daysToMonth365; // All months have less than 32 days, so n >> 5 is a good conservative // estimate for the month int m = n >> 5 + 1; // m = 1-based month number while (n >= days[m]) m++; // If month was requested, return it if (part == DatePartMonth) return (m); // Return 1-based day-of-month return (n - days[m - 1] + 1); } // Returns the tick count corresponding to the given year, month, and day. internal static long DateToTicks(int year, int month, int day) { int[] days = (year % 4 == 0) ? s_daysToMonth366 : s_daysToMonth365; int y = year - 1; int n = y * 365 + y / 4 + days[month - 1] + day - 1; // Gregorian 1/1/0001 is Julian 1/3/0001. n * TicksPerDay is the ticks in JulianCalendar. // Therefore, we subtract two days in the following to convert the ticks in JulianCalendar // to ticks in Gregorian calendar. return ((n - 2) * TicksPerDay); } public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( "months", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, -120000, 120000)); } Contract.EndContractBlock(); int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? s_daysToMonth366 : s_daysToMonth365; int days = (daysArray[m] - daysArray[m - 1]); if (d > days) { d = days; } long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay; Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } public override DateTime AddYears(DateTime time, int years) { return (AddMonths(time, years * 12)); } public override int GetDayOfMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartDay)); } public override DayOfWeek GetDayOfWeek(DateTime time) { return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7)); } public override int GetDayOfYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartDayOfYear)); } public override int GetDaysInMonth(int year, int month, int era) { CheckYearEraRange(year, era); CheckMonthRange(month); int[] days = (year % 4 == 0) ? s_daysToMonth366 : s_daysToMonth365; return (days[month] - days[month - 1]); } public override int GetDaysInYear(int year, int era) { // Year/Era range is done in IsLeapYear(). return (IsLeapYear(year, era) ? 366 : 365); } public override int GetEra(DateTime time) { return (JulianEra); } public override int GetMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartMonth)); } public override int[] Eras { get { return (new int[] { JulianEra }); } } public override int GetMonthsInYear(int year, int era) { CheckYearEraRange(year, era); return (12); } public override int GetYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartYear)); } public override bool IsLeapDay(int year, int month, int day, int era) { CheckMonthRange(month); // Year/Era range check is done in IsLeapYear(). if (IsLeapYear(year, era)) { CheckDayRange(year, month, day); return (month == 2 && day == 29); } CheckDayRange(year, month, day); return (false); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // [System.Runtime.InteropServices.ComVisible(false)] public override int GetLeapMonth(int year, int era) { CheckYearEraRange(year, era); return (0); } public override bool IsLeapMonth(int year, int month, int era) { CheckYearEraRange(year, era); CheckMonthRange(month); return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public override bool IsLeapYear(int year, int era) { CheckYearEraRange(year, era); return (year % 4 == 0); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { CheckYearEraRange(year, era); CheckMonthRange(month); CheckDayRange(year, month, day); if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( "millisecond", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)); } if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60) { return new DateTime(DateToTicks(year, month, day) + (new TimeSpan(0, hour, minute, second, millisecond)).Ticks); } else { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond); } } public override int TwoDigitYearMax { get { return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, MaxYear)); } twoDigitYearMax = value; } } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.EndContractBlock(); if (year > MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, MaxYear)); } return (base.ToFourDigitYear(year)); } } }
using System; using System.Collections.Generic; using System.Drawing; namespace AlgorithmSandbox.Teapot { public static class Triangle { /// <summary> /// c is to the left of the line determined by a and b /// </summary> public static bool IsLeft(this PointF c, PointF a, PointF b) { return (c.Y - a.Y) * (b.X - a.X) - (c.X - a.X) * (b.Y - a.Y) > 0; } /// <summary> /// Area of triangle is below treshold (probably not the best way to determine if a triangle is small) /// </summary> public static bool IsSmall(this PointF[] triangle) { return triangle.Area() < 300.0; } /// <summary> /// /\ /// / \ /// ---- /// </summary> public static bool IsAcuteUp(this PointF[] triangle) { return HasHorizontalLeg(triangle) && (triangle[0].Y <= triangle[1].Y) && (triangle[1].X < triangle[0].X) && (triangle[0].X < triangle[2].X); } /// <summary> /// ----- /// \ / /// \ / /// </summary> public static bool IsAcuteDown(this PointF[] triangle) { return HasHorizontalLeg(triangle) && triangle[2].Y >= triangle[0].Y && triangle[0].X < triangle[2].X && triangle[2].X < triangle[1].X; } public static bool IsRight(this PointF[] triangle) { return HasHorizontalLeg(triangle) && (Math.Abs(triangle[0].X - triangle[1].X) < Double.Epsilon || Math.Abs(triangle[0].X - triangle[2].X) < Double.Epsilon || Math.Abs(triangle[1].X - triangle[2].X) < Double.Epsilon); } public static bool IsBottomRight(this PointF[] triangle) { return triangle.IsRight() && Math.Abs(triangle[0].X - triangle[2].X) < Double.Epsilon && triangle[0].Y < triangle[2].Y && Math.Abs(triangle[1].Y - triangle[2].Y) < Double.Epsilon && triangle[1].X < triangle[2].X; } public static bool IsTopRight(this PointF[] triangle) { return triangle.IsRight() && Math.Abs(triangle[0].Y - triangle[1].Y) < Double.Epsilon && triangle[0].X < triangle[1].X && Math.Abs(triangle[1].X - triangle[2].X) < Double.Epsilon && triangle[1].Y < triangle[2].Y; } public static bool IsBottomLeft(this PointF[] triangle) { return triangle.IsRight() && Math.Abs(triangle[0].X - triangle[1].X) < Double.Epsilon && triangle[0].Y < triangle[1].Y && Math.Abs(triangle[1].Y - triangle[2].Y) < Double.Epsilon && triangle[1].X < triangle[2].X; } public static bool IsTopLeft(this PointF[] triangle) { return triangle.IsRight() && Math.Abs(triangle[0].Y - triangle[1].Y) < Double.Epsilon && triangle[0].X < triangle[1].X && Math.Abs(triangle[0].X - triangle[2].X) < Double.Epsilon && triangle[0].Y < triangle[2].Y; } public static bool IsObtuseUpLeft(this PointF[] triangle) { return HasHorizontalLeg(triangle) && triangle[0].Y < triangle[1].Y && triangle[0].X < triangle[1].X; } /// <summary> /// /| /// / / /// / | /// / / /// --- /// </summary> public static bool IsObtuseUpRight(this PointF[] triangle) { return HasHorizontalLeg(triangle) && triangle[0].Y < triangle[1].Y && triangle[0].X > triangle[2].X; } public static bool IsObtuseDownLeft(this PointF[] triangle) { return HasHorizontalLeg(triangle) && triangle[2].Y > triangle[0].Y && triangle[2].X < triangle[0].X; } public static bool IsObtuseDownRight(this PointF[] triangle) { return HasHorizontalLeg(triangle) && triangle[2].Y > triangle[0].Y && triangle[2].X > triangle[1].X; } public static bool IsTiltedRight(this PointF[] triangle) { return !HasHorizontalLeg(triangle) && !triangle[1].IsLeft(triangle[0], triangle[2]); } /// <summary> /// /| /// / | /// \ | /// \| /// </summary> public static bool IsTiltedLeft(this PointF[] triangle) { return !HasHorizontalLeg(triangle) && triangle[1].IsLeft(triangle[0], triangle[2]); } public static bool HasHorizontalLeg(this PointF[] triangle) { return Math.Abs(triangle[0].Y - triangle[1].Y) < Double.Epsilon || Math.Abs(triangle[1].Y - triangle[2].Y) < Double.Epsilon; } public static float Area(this PointF[] triangle) { return Math.Abs((triangle[0].X * (triangle[1].Y - triangle[2].Y) + triangle[1].X * (triangle[2].Y - triangle[0].Y) + triangle[2].X * (triangle[0].Y - triangle[1].Y)) / 2); } public static IEnumerable<PointF[]> SplitV2(this PointF[] triangle) { if (triangle.IsRight()) yield return triangle; if (triangle.IsSmall()) yield break; if (IsAcuteUp(triangle)) { var p = new PointF(triangle[0].X, triangle[1].Y); foreach (var t in new[] { triangle[0], triangle[1], p }.SplitV2()) yield return t; foreach (var t in new[] { triangle[0], p, triangle[2] }.SplitV2()) yield return t; yield break; } if (IsAcuteDown(triangle)) { var p = new PointF(triangle[2].X, triangle[0].Y); foreach (var t in new[] { triangle[0], p, triangle[2] }.SplitV2()) yield return t; foreach (var t in new[] { p, triangle[1], triangle[2] }.SplitV2()) yield return t; yield break; } if (IsObtuseUpLeft(triangle)) { var A = triangle[2].Y - triangle[0].Y; var B = triangle[2].X - triangle[1].X; var C = triangle[2].X - triangle[0].X; var D = A * (B / C); var p = new PointF(triangle[1].X, triangle[1].Y - D); foreach (var t in new[] { triangle[0], p, triangle[1] }.SplitV2()) yield return t; foreach (var t in new[] { p, triangle[1], triangle[2] }.SplitV2()) yield return t; yield break; } if (IsObtuseUpRight(triangle)) { var A = triangle[1].Y - triangle[0].Y; var B = triangle[0].X - triangle[2].X; var C = triangle[0].X - triangle[1].X; var D = A * (B / C); var p = new PointF(triangle[2].X, triangle[0].Y + D); foreach (var t in new[] { triangle[0], p, triangle[2] }.SplitV2()) yield return t; foreach (var t in new[] { p, triangle[1], triangle[2] }.SplitV2()) yield return t; yield break; } if (IsObtuseDownLeft(triangle)) { var A = triangle[2].Y - triangle[0].Y; var B = triangle[1].X - triangle[0].X; var C = triangle[1].X - triangle[2].X; var D = A * (B / C); var p = new PointF(triangle[0].X, triangle[0].Y + D); foreach (var t in new[] { triangle[0], triangle[1], p }.SplitV2()) yield return t; foreach (var t in new[] { triangle[0], p, triangle[2] }.SplitV2()) yield return t; yield break; } if (IsObtuseDownRight(triangle)) { var A = triangle[2].Y - triangle[1].Y; var B = triangle[1].X - triangle[0].X; var C = triangle[2].X - triangle[0].X; var D = A * (B / C); var p = new PointF(triangle[1].X, triangle[1].Y + D); foreach (var t in new[] { triangle[0], triangle[1], p }.SplitV2()) yield return t; foreach (var t in new[] { triangle[1], p, triangle[2] }.SplitV2()) yield return t; yield break; } if (IsTiltedRight(triangle)) { var A = triangle[0].X - triangle[2].X; var B = triangle[2].Y - triangle[1].Y; var C = triangle[2].Y - triangle[0].Y; var D = A * (B / C); var p = new PointF(triangle[2].X + D, triangle[1].Y); foreach (var t in new[] { triangle[0], p, triangle[1] }.SplitV2()) yield return t; foreach (var t in new[] { p, triangle[1], triangle[2] }.SplitV2()) yield return t; yield break; } if (IsTiltedLeft(triangle)) { var A = triangle[0].X - triangle[2].X; var B = triangle[1].Y - triangle[0].Y; var C = triangle[2].Y - triangle[0].Y; var D = A * (B / C); var p = new PointF(triangle[0].X - D, triangle[1].Y); foreach (var t in new[] { triangle[0], triangle[1], p }.SplitV2()) yield return t; foreach (var t in new[] { triangle[1], p, triangle[2] }.SplitV2()) yield return t; yield break; } yield break; } /// <summary> /// Split once. /// </summary> public static IEnumerable<PointF[]> Split(this PointF[] triangle) { if (IsRight(triangle)) { yield break; } if (IsAcuteUp(triangle)) { var p = new PointF(triangle[0].X, triangle[1].Y); yield return new[] { triangle[0], triangle[1], p }; yield return new[] { triangle[0], p, triangle[2] }; yield break; } if (IsAcuteDown(triangle)) { var p = new PointF(triangle[2].X, triangle[0].Y); yield return new[] { triangle[0], p, triangle[2] }; yield return new[] { p, triangle[1], triangle[2] }; yield break; } if (IsObtuseUpLeft(triangle)) { var A = triangle[2].Y - triangle[0].Y; var B = triangle[2].X - triangle[1].X; var C = triangle[2].X - triangle[0].X; var D = A * (B / C); var p = new PointF(triangle[1].X, triangle[1].Y - D); yield return new[] { triangle[0], p, triangle[1] }; yield return new[] { p, triangle[1], triangle[2] }; yield break; } if (IsObtuseUpRight(triangle)) { var A = triangle[1].Y - triangle[0].Y; var B = triangle[0].X - triangle[2].X; var C = triangle[0].X - triangle[1].X; var D = A * (B / C); var p = new PointF(triangle[2].X, triangle[0].Y + D); yield return new[] { triangle[0], p, triangle[2] }; yield return new[] { p, triangle[1], triangle[2] }; yield break; } if (IsObtuseDownLeft(triangle)) { var A = triangle[2].Y - triangle[0].Y; var B = triangle[1].X - triangle[0].X; var C = triangle[1].X - triangle[2].X; var D = A * (B / C); var p = new PointF(triangle[0].X, triangle[0].Y + D); yield return new[] { triangle[0], triangle[1], p }; yield return new[] { triangle[0], p, triangle[2] }; yield break; } if (IsObtuseDownRight(triangle)) { var A = triangle[2].Y - triangle[1].Y; var B = triangle[1].X - triangle[0].X; var C = triangle[2].X - triangle[0].X; var D = A * (B / C); var p = new PointF(triangle[1].X, triangle[1].Y + D); yield return new[] { triangle[0], triangle[1], p }; yield return new[] { triangle[1], p, triangle[2] }; yield break; } if (IsTiltedRight(triangle)) { var A = triangle[0].X - triangle[2].X; var B = triangle[2].Y - triangle[1].Y; var C = triangle[2].Y - triangle[0].Y; var D = A * (B / C); var p = new PointF(triangle[2].X + D, triangle[1].Y); yield return new[] { triangle[0], p, triangle[1] }; yield return new[] { p, triangle[1], triangle[2] }; yield break; } if (IsTiltedLeft(triangle)) { var A = triangle[0].X - triangle[2].X; var B = triangle[1].Y - triangle[0].Y; var C = triangle[2].Y - triangle[0].Y; var D = A * (B / C); var p = new PointF(triangle[0].X - D, triangle[1].Y); yield return new[] { triangle[0], triangle[1], p }; yield return new[] { triangle[1], p, triangle[2] }; yield break; } yield break; //throw new Exception("Should never happen!"); } static Random randonGen = new Random(); public static Color RandomColor() { return Color.FromArgb(randonGen.Next(256), randonGen.Next(256), randonGen.Next(256)); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; namespace CSemVer { public sealed partial class CSVersion { [StructLayout( LayoutKind.Explicit )] struct SOrderedVersion { [FieldOffset( 0 )] public long Number; [FieldOffset( 6 )] public UInt16 Major; [FieldOffset( 4 )] public UInt16 Minor; [FieldOffset( 2 )] public UInt16 Build; [FieldOffset( 0 )] public UInt16 Revision; } readonly SOrderedVersion _orderedVersion; /// <summary> /// The maximum number of major versions. /// </summary> public const int MaxMajor = 99999; /// <summary> /// The maximum number of minor versions for a major one. /// </summary> public const int MaxMinor = 49999; /// <summary> /// The maximum number of patches for a minor one. /// </summary> public const int MaxPatch = 9999; /// <summary> /// The maximum number of prereleases is also the index of the "rc" entry in <see cref="StandardPrereleaseNames"/>. /// </summary> public const int MaxPreReleaseNameIdx = 7; /// <summary> /// The maximum number of prereleases. /// </summary> public const int MaxPreReleaseNumber = 99; /// <summary> /// The maximum number of fixes to a pre-release. /// </summary> public const int MaxPreReleasePatch = 99; const long MaxOrderedVersion = (MaxMajor + 1L) * (MaxMinor + 1L) * (MaxPatch + 1L) * (1L + (MaxPreReleaseNameIdx + 1L) * (MaxPreReleaseNumber + 1L) * (MaxPreReleasePatch + 1L)); static readonly string[] _standardNames = new[] { "alpha", "beta", "delta", "epsilon", "gamma", "kappa", "prerelease", "rc" }; static readonly string[] _standardNamesI = new[] { "a", "b", "d", "e", "g", "k", "p", "r" }; const long MulNum = MaxPreReleasePatch + 1; const long MulName = MulNum * (MaxPreReleaseNumber + 1); const long MulPatch = MulName * (MaxPreReleaseNameIdx + 1) + 1; const long MulMinor = MulPatch * (MaxPatch + 1); const long MulMajor = MulMinor * (MaxMinor + 1); const long DivPatch = MulPatch + 1; const long DivMinor = DivPatch * (MaxPatch); const long DivMajor = DivMinor * (MaxMinor + 1); /// <summary> /// Gets the standard <see cref="PrereleaseName"/>. /// </summary> public static IReadOnlyList<string> StandardPrereleaseNames => _standardNames; /// <summary> /// Gets the short form <see cref="PrereleaseName"/> (the initials). /// </summary> public static IReadOnlyList<string> StandardPreReleaseNamesShort => _standardNamesI; /// <summary> /// Gets the very first possible version (0.0.0-alpha). /// </summary> public static readonly CSVersion VeryFirstVersion = new CSVersion( 0, 0, 0, String.Empty, 0, 0, 0, 1 ); /// <summary> /// Gets the very first possible release versions (0.0.0, 0.1.0 or 1.0.0 or any prereleases of them). /// </summary> public static readonly IReadOnlyList<CSVersion> FirstPossibleVersions = BuildFirstPossibleVersions(); /// <summary> /// Gets the very last possible version. /// </summary> public static readonly CSVersion VeryLastVersion = new CSVersion( MaxMajor, MaxMinor, MaxPatch, String.Empty, -1, 0, 0, MaxOrderedVersion ); static IReadOnlyList<CSVersion> BuildFirstPossibleVersions() { var versions = new CSVersion[3 * 9]; long v = 1L; int i = 0; while( i < 3 * 9 ) { versions[i++] = Create( v ); if( (i % 18) == 0 ) v += MulMajor - MulMinor - MulPatch + 1; else if( (i % 9) == 0 ) v += MulMinor - MulPatch + 1; else v += MulName; } return versions; } /// <summary> /// Creates a new version from an ordered version that must be between 0 (invalid version) and <see cref="VeryLastVersion"/>.<see cref="OrderedVersion"/>. /// </summary> /// <param name="v">The ordered version.</param> /// <returns>The version.</returns> public static CSVersion Create( long v ) { if( v < 0 || v > MaxOrderedVersion ) throw new ArgumentException( "Must be between 0 and VeryLastVersion.OrderedVersion." ); if( v == 0 ) return new CSVersion( "Invalid CSVersion.", null ); long dV = v; int prNameIdx = -1; int prNumber = 0; int prPatch = 0; long preReleasePart = dV % MulPatch; if( preReleasePart != 0 ) { preReleasePart = preReleasePart - 1L; prNameIdx = (int)(preReleasePart / MulName); preReleasePart -= (long)prNameIdx * MulName; prNumber = (int)(preReleasePart / MulNum); preReleasePart -= (long)prNumber * MulNum; prPatch = (int)preReleasePart; } else { dV -= MulPatch; prNameIdx = -1; } int major = (int)(dV / MulMajor); dV -= major * MulMajor; int minor = (int)(dV / MulMinor); dV -= minor * MulMinor; int patch = (int)(dV / MulPatch); return new CSVersion( major, minor, patch, String.Empty, prNameIdx, prNumber, prPatch, v ); } static long ComputeOrderedVersion( int major, int minor, int patch, int preReleaseNameIdx = -1, int preReleaseNumber = 0, int preReleaseFix = 0 ) { long v = MulMajor * major; v += MulMinor * minor; v += MulPatch * (patch + 1); if( preReleaseNameIdx >= 0 ) { v -= MulPatch - 1; v += MulName * preReleaseNameIdx; v += MulNum * preReleaseNumber; v += preReleaseFix; } Debug.Assert( Create( v )._orderedVersion.Number == v ); Debug.Assert( preReleaseNameIdx >= 0 == ((v % MulPatch) != 0) ); Debug.Assert( major == (int)((preReleaseNameIdx >= 0 ? v : v - MulPatch) / MulMajor) ); Debug.Assert( minor == (int)(((preReleaseNameIdx >= 0 ? v : v - MulPatch) / MulMinor) - major * (MaxMinor + 1L)) ); Debug.Assert( patch == (int)(((preReleaseNameIdx >= 0 ? v : v - MulPatch) / MulPatch) - (major * (MaxMinor + 1L) + minor) * (MaxPatch + 1L)) ); Debug.Assert( preReleaseNameIdx == (preReleaseNameIdx >= 0 ? (int)(((v - 1L) % MulPatch) / MulName) : -1) ); Debug.Assert( preReleaseNumber == (preReleaseNameIdx >= 0 ? (int)(((v - 1L) % MulPatch) / MulNum - preReleaseNameIdx * MulNum) : 0) ); Debug.Assert( preReleaseFix == (preReleaseNameIdx >= 0 ? (int)(((v - 1L) % MulPatch) % MulNum) : 0) ); return v; } /// <summary> /// Gets the ordered version number. /// </summary> public long OrderedVersion => _orderedVersion.Number; /// <summary> /// Gets the Major (first, most significant) part of the <see cref="OrderedVersion"/>: between 0 and 32767. /// </summary> public int OrderedVersionMajor => _orderedVersion.Major; /// <summary> /// Gets the Minor (second) part of the <see cref="OrderedVersion"/>: between 0 and 65535. /// </summary> public int OrderedVersionMinor => _orderedVersion.Minor; /// <summary> /// Gets the Build (third) part of the <see cref="OrderedVersion"/>: between 0 and 65535. /// </summary> public int OrderedVersionBuild => _orderedVersion.Build; /// <summary> /// Gets the Revision (last, less significant) part of the <see cref="OrderedVersion"/>: between 0 and 65535. /// </summary> public int OrderedVersionRevision => _orderedVersion.Revision; /// <summary> /// Versions are equal if their <see cref="OrderedVersion"/> are equals. /// No other members are used for equality and comparison. /// </summary> /// <param name="other">Other version.</param> /// <returns>True if they have the same OrderedVersion.</returns> public bool Equals( CSVersion other ) { if( other == null ) return false; return _orderedVersion.Number == other._orderedVersion.Number; } /// <summary> /// Relies only on <see cref="OrderedVersion"/>. /// </summary> /// <param name="other">Other release tag (can be null).</param> /// <returns>A signed number indicating the relative values of this instance and <paramref name="other"/>.</returns> public int CompareTo( CSVersion other ) { if( other == null ) return 1; return _orderedVersion.Number.CompareTo( other._orderedVersion.Number ); } /// <summary> /// Implements == operator. /// </summary> /// <param name="x">First version.</param> /// <param name="y">Second version.</param> /// <returns>True if they are equal.</returns> static public bool operator ==( CSVersion x, CSVersion y ) { if( ReferenceEquals( x, y ) ) return true; if( !ReferenceEquals( x, null ) && !ReferenceEquals( y, null ) ) { return x._orderedVersion.Number == y._orderedVersion.Number; } return false; } /// <summary> /// Implements &gt; operator. /// </summary> /// <param name="x">First version.</param> /// <param name="y">Second version.</param> /// <returns>True if x is greater than y.</returns> static public bool operator >( CSVersion x, CSVersion y ) { if( ReferenceEquals( x, y ) ) return false; if( !ReferenceEquals( x, null ) ) { if( ReferenceEquals( y, null ) ) return true; return x._orderedVersion.Number > y._orderedVersion.Number; } return false; } /// <summary> /// Implements &gt;= operator. /// </summary> /// <param name="x">First version.</param> /// <param name="y">Second version.</param> /// <returns>True if x is greater than or equal to y.</returns> static public bool operator >=( CSVersion x, CSVersion y ) { if( ReferenceEquals( x, y ) ) return true; if( !ReferenceEquals( x, null ) ) { if( ReferenceEquals( y, null ) ) return true; return x._orderedVersion.Number >= y._orderedVersion.Number; } return false; } /// <summary> /// Implements != operator. /// </summary> /// <param name="x">First version.</param> /// <param name="y">Second version.</param> /// <returns>True if they are not equal.</returns> static public bool operator !=( CSVersion x, CSVersion y ) => !(x == y); /// <summary> /// Implements &lt;= operator. /// </summary> /// <param name="x">First version.</param> /// <param name="y">Second version.</param> /// <returns>True if x is lower than or equal to y.</returns> static public bool operator <=( CSVersion x, CSVersion y ) => !(x > y); /// <summary> /// Implements &lt; operator. /// </summary> /// <param name="x">First version.</param> /// <param name="y">Second version.</param> /// <returns>True if x is lower than y.</returns> static public bool operator <( CSVersion x, CSVersion y ) => !(x >= y); /// <summary> /// Version are equal it their <see cref="OrderedVersion"/> are equals. /// No other members are used for equality and comparison. /// </summary> /// <param name="obj">Other release version.</param> /// <returns>True if obj is a version that has the same OrderedVersion as this.</returns> public override bool Equals( object obj ) => Equals( obj as CSVersion ); /// <summary> /// Versions are equal it their <see cref="OrderedVersion"/> are equals. /// No other members are used for equality and comparison. /// </summary> /// <returns>True if they have the same OrderedVersion.</returns> public override int GetHashCode() => _orderedVersion.Number.GetHashCode(); } }
using System; using System.IO; using IdSharp.Common.Utils; namespace IdSharp.AudioInfo { /// <summary> /// Shorten /// </summary> public class Shorten : IAudioFile { static Shorten() { uint val = 0; masktab[0] = val; for (int i = 1; i < MASKTABSIZE; i++) { val <<= 1; val |= 1; masktab[i] = val; } } private const int MASKTABSIZE = 33; private const int BUFSIZE = 32768; private const int DEFAULT_BLOCK_SIZE = 256; private const int CHANSIZE = 0; private const int LPCQUANT = 5; private const int VERBATIM_CKSIZE_SIZE = 5; // a var_put code size private const int BITSHIFTSIZE = 2; private const int ULONGSIZE = 2; private const int NSKIPSIZE = 1; private const int XBYTESIZE = 7; private const int MAX_VERSION = 7; private const int MAX_SUPPORTED_VERSION = 3; private const int ENERGYSIZE = 3; private const int LPCQSIZE = 2; private const int TYPESIZE = 4; private const int FNSIZE = 2; private const int FN_DIFF0 = 0; private const int FN_DIFF1 = 1; private const int FN_DIFF2 = 2; private const int FN_DIFF3 = 3; private const int FN_QUIT = 4; private const int FN_BLOCKSIZE = 5; private const int FN_BITSHIFT = 6; private const int FN_QLPC = 7; private const int FN_ZERO = 8; private const int FN_VERBATIM = 9; private const int VERBATIM_BYTE_SIZE = 8; // code size 8 on single bytes means no compression at all private const double M_LN2 = 0.69314718055994530942; private static readonly byte[] MAGIC = new byte[] { (byte)'a', (byte)'j', (byte)'k', (byte)'g', 0x00 }; private static readonly uint[] masktab = new uint[MASKTABSIZE]; private readonly int _frequency = 44100; // TODO: Hard-coded private readonly decimal _totalSeconds; private readonly decimal _bitrate; private readonly int _channels = 2; // TODO: Hard-coded private readonly int _samples; private readonly byte[] getbuf; private int nbyteget; private uint gbuffer; private int nbitget; private int getbufOffset; private int version; /// <summary> /// Initializes a new instance of the <see cref="Shorten"/> class. /// </summary> /// <param name="path">The path of the file.</param> public Shorten(string path) { getbuf = new byte[BUFSIZE]; nbyteget = 0; gbuffer = 0; nbitget = 0; using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { _samples = getSamples(fs); _totalSeconds = (decimal)_samples / _frequency; _bitrate = fs.Length / _totalSeconds / 125.0m; } } private uint UINT_GET(int nbit, Stream file) { if (version == 0) return (uint)uvar_get(nbit, file); else return ulong_get(file); } private uint ulong_get(Stream stream) { int nbit = uvar_get(ULONGSIZE, stream); return (uint)uvar_get(nbit, stream); } private uint word_get(Stream stream) { if (nbyteget < 4) { int bytes = stream.Read(getbuf, 0, BUFSIZE); getbufOffset = 0; nbyteget += bytes; if (nbyteget < 4) { unchecked { return (uint)(-1); } } } uint buffer = (((uint)getbuf[getbufOffset]) << 24) | (((uint)getbuf[getbufOffset + 1]) << 16) | (((uint)getbuf[getbufOffset + 2]) << 8) | (getbuf[getbufOffset + 3]); getbufOffset += 4; nbyteget -= 4; return (buffer); } private int uvar_get(int nbin, Stream stream) { int result; if (nbitget == 0) { gbuffer = word_get(stream); nbitget = 32; } for (result = 0; (gbuffer & (1L << --nbitget)) == 0; result++) { if (nbitget == 0) { gbuffer = word_get(stream); nbitget = 32; } } while (nbin != 0) { if (nbitget >= nbin) { result = (int)((uint)(result << nbin) | ((gbuffer >> (nbitget - nbin)) & masktab[nbin])); nbitget -= nbin; nbin = 0; } else { result = (int)((uint)(result << nbitget) | (gbuffer & masktab[nbitget])); gbuffer = word_get(stream); nbin -= nbitget; nbitget = 32; } } return (result); } private int var_get(int nbin, Stream stream) { uint uvar = (uint)uvar_get(nbin + 1, stream); if ((uvar & 1) == 1) return ((int)~(uvar >> 1)); else return ((int)(uvar >> 1)); } private int getSamples(Stream stream) { int SampleNumber = 0; int i; int nscan = 0; version = MAX_VERSION + 1; while (version > MAX_VERSION) { int myByte = stream.Read1(); if (MAGIC[nscan] != '\0' && myByte == MAGIC[nscan]) { nscan++; } else if (MAGIC[nscan] == '\0' && myByte <= MAX_VERSION) { version = myByte; } else { if (myByte == MAGIC[0]) { nscan = 1; } else { nscan = 0; } version = MAX_VERSION + 1; } } // check version number if (version > MAX_SUPPORTED_VERSION) return 0; UINT_GET(TYPESIZE, stream); int blocksize; int nchan = (int)UINT_GET(CHANSIZE, stream); if (version > 0) { blocksize = (int)UINT_GET((int)(Math.Log(DEFAULT_BLOCK_SIZE) / M_LN2), stream); UINT_GET(LPCQSIZE, stream); UINT_GET(0, stream); int nskip = (int)UINT_GET(NSKIPSIZE, stream); for (i = 0; i < nskip; i++) { uvar_get(XBYTESIZE, stream); } } else { blocksize = DEFAULT_BLOCK_SIZE; } // get commands from file and execute them int chan = 0; int cmd = uvar_get(FNSIZE, stream); while (cmd != FN_QUIT) { switch (cmd) { case FN_ZERO: case FN_DIFF0: case FN_DIFF1: case FN_DIFF2: case FN_DIFF3: case FN_QLPC: int resn = 0; if (cmd != FN_ZERO) { resn = uvar_get(ENERGYSIZE, stream); // this is a hack as version 0 differed in definition of var_get if (version == 0) resn--; } switch (cmd) { case FN_ZERO: break; case FN_DIFF0: case FN_DIFF1: case FN_DIFF2: case FN_DIFF3: for (i = 0; i < blocksize; i++) { int nbin = resn + 1; if (nbitget == 0) { if (nbyteget < 4) { int bytes = stream.Read(getbuf, 0, BUFSIZE); getbufOffset = 0; nbyteget += bytes; } gbuffer = (((uint)getbuf[getbufOffset]) << 24) | (((uint)getbuf[getbufOffset + 1]) << 16) | (((uint)getbuf[getbufOffset + 2]) << 8) | (getbuf[getbufOffset + 3]); getbufOffset += 4; nbyteget -= 4; nbitget = 32; } while ((gbuffer & (1L << --nbitget)) == 0) { if (nbitget == 0) { if (nbyteget < 4) { int bytes = stream.Read(getbuf, 0, BUFSIZE); getbufOffset = 0; nbyteget += bytes; } gbuffer = (((uint)getbuf[getbufOffset]) << 24) | (((uint)getbuf[getbufOffset + 1]) << 16) | (((uint)getbuf[getbufOffset + 2]) << 8) | (getbuf[getbufOffset + 3]); getbufOffset += 4; nbyteget -= 4; nbitget = 32; } } while (nbin != 0) { if (nbitget >= nbin) { nbitget -= nbin; nbin = 0; } else { if (nbyteget < 4) { int bytes = stream.Read(getbuf, 0, BUFSIZE); getbufOffset = 0; nbyteget += bytes; } gbuffer = (((uint)getbuf[getbufOffset]) << 24) | (((uint)getbuf[getbufOffset + 1]) << 16) | (((uint)getbuf[getbufOffset + 2]) << 8) | (getbuf[getbufOffset + 3]); getbufOffset += 4; nbyteget -= 4; nbin -= nbitget; nbitget = 32; } } } break; case FN_QLPC: int nlpc = uvar_get(LPCQSIZE, stream); for (i = 0; i < nlpc; i++) var_get(LPCQUANT, stream); break; } if (chan == nchan - 1) { SampleNumber += blocksize; } chan = (chan + 1) % nchan; break; case FN_BLOCKSIZE: blocksize = (int)UINT_GET((int)(Math.Log(blocksize) / M_LN2), stream); break; case FN_BITSHIFT: uvar_get(BITSHIFTSIZE, stream); break; case FN_VERBATIM: int cklen = uvar_get(VERBATIM_CKSIZE_SIZE, stream); while (cklen-- != 0) { uvar_get(VERBATIM_BYTE_SIZE, stream); } break; default: return 0; } cmd = uvar_get(FNSIZE, stream); } return SampleNumber; } /// <summary> /// Gets the frequency. /// </summary> /// <value>The frequency.</value> public int Frequency { get { return _frequency; } } /// <summary> /// Gets the sample count. /// </summary> /// <value>The sample count.</value> public int Samples { get { return _samples; } } /// <summary> /// Gets the total seconds. /// </summary> /// <value>The total seconds.</value> public decimal TotalSeconds { get { return _totalSeconds; } } /// <summary> /// Gets the bitrate. /// </summary> /// <value>The bitrate.</value> public decimal Bitrate { get { return _bitrate; } } /// <summary> /// Gets the number of channels. /// </summary> /// <value>The number of channels.</value> public int Channels { get { return _channels; } } /// <summary> /// Gets the type of the audio file. /// </summary> /// <value>The type of the audio file.</value> public AudioFileType FileType { get { return AudioFileType.Shorten; } } } }
using Epi.Fields; namespace Epi.Collections { /// <summary> /// Named Object Field Collection Master class /// </summary> public class FieldCollectionMaster : NamedObjectCollection<Field> { #region Private Class Members private NamedObjectCollection<TextField> textFields = null; private NamedObjectCollection<MirrorField> mirrorFields = null; private NamedObjectCollection<IInputField> inputFields = null; private NamedObjectCollection<IDataField> dataFields = null; private NamedObjectCollection<IDataField> tableColumnFields = null; private NamedObjectCollection<RelatedViewField> relatedFields = null; private NamedObjectCollection<GridField> gridFields = null; #endregion Private Class Members #region Constructors /// <summary> /// Default constructor /// </summary> public FieldCollectionMaster() { textFields = new NamedObjectCollection<TextField>(); mirrorFields = new NamedObjectCollection<MirrorField>(); inputFields = new NamedObjectCollection<IInputField>(); dataFields = new NamedObjectCollection<IDataField>(); tableColumnFields = new NamedObjectCollection<IDataField>(); relatedFields = new NamedObjectCollection<RelatedViewField>(); gridFields = new NamedObjectCollection<GridField>(); } #endregion Constructors #region Public Properties /// <summary> /// Returns the Unique Key Field. /// </summary> public UniqueKeyField UniqueKeyField { get { return this[ColumnNames.UNIQUE_KEY] as UniqueKeyField; } } /// <summary> /// Returns the Unique Identifier Field. /// </summary> public UniqueIdentifierField UniqueIdentifierField { get { return this[ColumnNames.UNIQUE_IDENTIFIER] as UniqueIdentifierField; } } /// <summary> /// Returns the Record Status Field. /// </summary> public RecStatusField RecStatusField { get { return this[ColumnNames.REC_STATUS] as RecStatusField; } } /// <summary> /// Returns the Foreign Key Field. /// </summary> public ForeignKeyField ForeignKeyField { get { return this[ColumnNames.FOREIGN_KEY] as ForeignKeyField; } } public bool ForeignKeyFieldExists { get { return this.Contains(ColumnNames.FOREIGN_KEY); } } /// <summary> /// Returns the Foreign Key Field. /// </summary> public GlobalRecordIdField GlobalRecordIdField { get { return this[ColumnNames.GLOBAL_RECORD_ID] as GlobalRecordIdField; } } /// <summary> /// Returns the named collection of Text Fields. /// </summary> public NamedObjectCollection<TextField> TextFields { get { return this.textFields; } } /// <summary> /// Returns the named collection of Mirror Fields. /// </summary> public NamedObjectCollection<MirrorField> MirrorFields { get { return this.mirrorFields; } } /// <summary> /// Returns the named collection of IInput Fields. /// </summary> public NamedObjectCollection<IInputField> InputFields { get { return this.inputFields; } } /// <summary> /// Returns the named collection of IDataFields. /// </summary> public NamedObjectCollection<IDataField> DataFields { get { return dataFields; } } /// <summary> /// Returns the named collection of Table column data fields. /// </summary> public NamedObjectCollection<IDataField> TableColumnFields { get { return this.tableColumnFields; } } /// <summary> /// Returns the named collection of Related View Fields /// </summary> public NamedObjectCollection<RelatedViewField> RelatedFields { get { return this.relatedFields; } } /// <summary> /// Returns the named collection of Grid Fields /// </summary> public NamedObjectCollection<GridField> GridFields { get { return this.gridFields; } } #endregion Public Properties #region Public Methods /// <summary> /// Add a new field collection master. /// </summary> /// <param name="field">Field object to add.</param> public override void Add(Field field) { base.Add(field); if (field is TextField) { textFields.Add(field as TextField); } if (field is MirrorField) { mirrorFields.Add(field as MirrorField); } if (field is RelatedViewField) { relatedFields.Add(field as RelatedViewField); } if (field is IDataField) { dataFields.Add(field as IDataField); // Only IDataFields make it into table columns with the exception of MirrorFields if (!(field is MirrorField)) { tableColumnFields.Add(field as IDataField); } } if (field is IInputField) { inputFields.Add(field as IInputField); } if (field is GridField) { gridFields.Add(field as GridField); } } /// <summary> /// Deletes a field from the master field collection. /// </summary> /// <param name="field">Field object to delete.</param> /// <returns></returns> public override bool Remove(Field field) { bool result = base.Remove(field); if (field is TextField) { textFields.Remove(field.Name); } if (field is MirrorField) { mirrorFields.Remove(field.Name); } if (field is RelatedViewField) { relatedFields.Add(field as RelatedViewField); } if (field is IDataField) { dataFields.Remove(field.Name); // Only IDataFields make it into table columns with the exception of MirrorFields if (!(field is MirrorField)) { tableColumnFields.Remove(field.Name); } } if (field is IInputField) { inputFields.Remove(field.Name); } if (field is GridField) { gridFields.Remove(field as GridField); } return result; } /// <summary> /// Dispose of the field collections. /// </summary> public override void Dispose() { if (this.dataFields != null) { dataFields.Dispose(); dataFields = null; } if (this.inputFields != null) { inputFields.Dispose(); inputFields = null; } if (this.mirrorFields != null) { mirrorFields.Dispose(); mirrorFields = null; } if (this.tableColumnFields != null) { tableColumnFields.Dispose(); tableColumnFields = null; } if (this.textFields != null) { textFields.Dispose(); textFields = null; } if (this.relatedFields != null) { relatedFields.Dispose(); relatedFields = null; } if (this.gridFields != null) { gridFields.Dispose(); gridFields = null; } base.Dispose(); } #endregion Public Methods } }
// 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.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 CompareEqualScalarSingle() { var test = new SimpleBinaryOpTest__CompareEqualScalarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.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 (Sse.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 (Sse.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 works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareEqualScalarSingle { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Single); private const int Op2ElementCount = VectorSize / sizeof(Single); private const int RetElementCount = VectorSize / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable; static SimpleBinaryOpTest__CompareEqualScalarSingle() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__CompareEqualScalarSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], VectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse.CompareEqualScalar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse.CompareEqualScalar( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse.CompareEqualScalar( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse).GetMethod(nameof(Sse.CompareEqualScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse).GetMethod(nameof(Sse.CompareEqualScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse).GetMethod(nameof(Sse.CompareEqualScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse.CompareEqualScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.CompareEqualScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareEqualScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareEqualScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareEqualScalarSingle(); var result = Sse.CompareEqualScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse.CompareEqualScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(result[0]) != ((left[0] == right[0]) ? -1 : 0)) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.CompareEqualScalar)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// 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.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 DivideDouble() { var test = new SimpleBinaryOpTest__DivideDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // 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(); // 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(); // 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 works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__DivideDouble { private const int VectorSize = 32; private const int ElementCount = VectorSize / sizeof(Double); private static Double[] _data1 = new Double[ElementCount]; private static Double[] _data2 = new Double[ElementCount]; private static Vector256<Double> _clsVar1; private static Vector256<Double> _clsVar2; private Vector256<Double> _fld1; private Vector256<Double> _fld2; private SimpleBinaryOpTest__DataTable<Double> _dataTable; static SimpleBinaryOpTest__DivideDouble() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__DivideDouble() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Double>(_data1, _data2, new Double[ElementCount], VectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.Divide( Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx.Divide( Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx.Divide( Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx).GetMethod(nameof(Avx.Divide), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx).GetMethod(nameof(Avx.Divide), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx).GetMethod(nameof(Avx.Divide), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx.Divide( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr); var result = Avx.Divide(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.Divide(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.Divide(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__DivideDouble(); var result = Avx.Divide(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx.Divide(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Double> left, Vector256<Double> right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[ElementCount]; Double[] inArray2 = new Double[ElementCount]; Double[] outArray = new Double[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[ElementCount]; Double[] inArray2 = new Double[ElementCount]; Double[] outArray = new Double[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { if (BitConverter.DoubleToInt64Bits(left[0] / right[0]) != BitConverter.DoubleToInt64Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if (BitConverter.DoubleToInt64Bits(left[i] / right[i]) != BitConverter.DoubleToInt64Bits(result[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.Divide)}<Double>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using AutoMapper; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Common.Authentication; using Microsoft.Azure.Common.Authentication.Models; using Microsoft.WindowsAzure.Commands.Common; using Microsoft.WindowsAzure.Commands.ServiceManagement.Model; using Microsoft.WindowsAzure.Commands.Utilities.Properties; using Microsoft.WindowsAzure.Management; using Microsoft.WindowsAzure.Management.Compute; using Microsoft.WindowsAzure.Management.Network; using Microsoft.WindowsAzure.Management.Storage; using System; using System.Collections.Generic; using System.Globalization; using System.Management.Automation.Runspaces; using System.ServiceModel; using System.ServiceModel.Dispatcher; namespace Microsoft.WindowsAzure.Commands.Utilities.Common { public abstract class ServiceManagementBaseCmdlet : CloudBaseCmdlet<IServiceManagement> { private Lazy<Runspace> runspace; protected ServiceManagementBaseCmdlet() { IClientProvider clientProvider = new ClientProvider(this); SetupClients(clientProvider); } private void SetupClients(IClientProvider clientProvider) { runspace = new Lazy<Runspace>(() => { var localRunspace = RunspaceFactory.CreateRunspace(this.Host); localRunspace.Open(); return localRunspace; }); client = new Lazy<ManagementClient>(clientProvider.CreateClient); computeClient = new Lazy<ComputeManagementClient>(clientProvider.CreateComputeClient); storageClient = new Lazy<StorageManagementClient>(clientProvider.CreateStorageClient); networkClient = new Lazy<NetworkManagementClient>(clientProvider.CreateNetworkClient); } protected ServiceManagementBaseCmdlet(IClientProvider clientProvider) { SetupClients(clientProvider); } private Lazy<ManagementClient> client; public ManagementClient ManagementClient { get { return client.Value; } } private Lazy<ComputeManagementClient> computeClient; public ComputeManagementClient ComputeClient { get { return computeClient.Value; } } private Lazy<StorageManagementClient> storageClient; public StorageManagementClient StorageClient { get { return storageClient.Value; } } private Lazy<NetworkManagementClient> networkClient; public NetworkManagementClient NetworkClient { get { return networkClient.Value; } } protected override void InitChannelCurrentSubscription(bool force) { // Do nothing for service management based cmdlets } protected OperationStatusResponse GetOperation(string operationId) { OperationStatusResponse operation = null; try { operation = this.ManagementClient.GetOperationStatus(operationId); if (operation.Status == OperationStatus.Failed) { var errorMessage = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", operation.Status, operation.Error.Message); throw new Exception(errorMessage); } } catch (AggregateException ex) { if (ex.InnerException is CloudException) { WriteExceptionError(ex.InnerException); } else { WriteExceptionError(ex); } } catch (Exception ex) { WriteExceptionError(ex); } return operation; } protected OperationStatusResponse GetOperation(AzureOperationResponse result) { OperationStatusResponse operation; if (result is OperationStatusResponse) { operation = result as OperationStatusResponse; } else { operation = result == null ? null : GetOperation(result.RequestId); } return operation; } //TODO: Input argument is not used and should probably be removed. protected void ExecuteClientActionNewSM<TResult>(object input, string operationDescription, Func<TResult> action, Func<OperationStatusResponse, TResult, object> contextFactory) where TResult : AzureOperationResponse { WriteVerboseWithTimestamp(Resources.ServiceManagementExecuteClientActionInOCSBeginOperation, operationDescription); try { try { TResult result = action(); OperationStatusResponse operation = GetOperation(result); var context = contextFactory(operation, result); if (context != null) { WriteObject(context, true); } } catch (CloudException ce) { throw new ComputeCloudException(ce); } } catch (Exception ex) { WriteExceptionError(ex); } WriteVerboseWithTimestamp(Resources.ServiceManagementExecuteClientActionInOCSCompletedOperation, operationDescription); } protected void ExecuteClientActionNewSM<TResult>(object input, string operationDescription, Func<TResult> action) where TResult : AzureOperationResponse { this.ExecuteClientActionNewSM(input, operationDescription, action, (s, response) => this.ContextFactory<AzureOperationResponse, ManagementOperationContext>(response, s)); } protected TDestination ContextFactory<TSource, TDestination>(TSource s1, OperationStatusResponse s2) where TDestination : ManagementOperationContext { TDestination result = Mapper.Map<TSource, TDestination>(s1); result = Mapper.Map(s2, result); result.OperationDescription = CommandRuntime.ToString(); return result; } protected void ExecuteClientAction(Action action) { try { try { action(); } catch (CloudException ex) { throw new ComputeCloudException(ex); } } catch (Exception ex) { WriteExceptionError(ex); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using Autofac; using NUnit.Framework; using Orchard.Caching; using Orchard.Environment.Extensions; using Orchard.Environment.Extensions.Folders; using Orchard.Environment.Extensions.Loaders; using Orchard.Environment.Extensions.Models; using Orchard.FileSystems.Dependencies; using Orchard.Tests.Extensions.ExtensionTypes; using Orchard.Tests.Stubs; namespace Orchard.Tests.Environment.Extensions { [TestFixture] public class ExtensionManagerTests { private IContainer _container; private IExtensionManager _manager; private StubFolders _folders; [SetUp] public void Init() { var builder = new ContainerBuilder(); _folders = new StubFolders(); builder.RegisterInstance(_folders).As<IExtensionFolders>(); builder.RegisterType<ExtensionManager>().As<IExtensionManager>(); builder.RegisterType<StubCacheManager>().As<ICacheManager>(); builder.RegisterType<StubParallelCacheContext>().As<IParallelCacheContext>(); builder.RegisterType<StubAsyncTokenProvider>().As<IAsyncTokenProvider>(); _container = builder.Build(); _manager = _container.Resolve<IExtensionManager>(); } public class StubFolders : IExtensionFolders { private readonly string _extensionType; public StubFolders(string extensionType) { Manifests = new Dictionary<string, string>(); _extensionType = extensionType; } public StubFolders() : this(DefaultExtensionTypes.Module) { } public IDictionary<string, string> Manifests { get; set; } public IEnumerable<ExtensionDescriptor> AvailableExtensions() { foreach (var e in Manifests) { string name = e.Key; yield return ExtensionHarvester.GetDescriptorForExtension("~/", name, _extensionType, Manifests[name]); } } } public class StubLoaders : IExtensionLoader { #region Implementation of IExtensionLoader public int Order { get { return 1; } } public string Name { get { throw new NotImplementedException(); } } public Assembly LoadReference(DependencyReferenceDescriptor reference) { throw new NotImplementedException(); } public void ReferenceActivated(ExtensionLoadingContext context, ExtensionReferenceProbeEntry referenceEntry) { throw new NotImplementedException(); } public void ReferenceDeactivated(ExtensionLoadingContext context, ExtensionReferenceProbeEntry referenceEntry) { throw new NotImplementedException(); } public bool IsCompatibleWithModuleReferences(ExtensionDescriptor extension, IEnumerable<ExtensionProbeEntry> references) { throw new NotImplementedException(); } public ExtensionProbeEntry Probe(ExtensionDescriptor descriptor) { return new ExtensionProbeEntry { Descriptor = descriptor, Loader = this }; } public IEnumerable<ExtensionReferenceProbeEntry> ProbeReferences(ExtensionDescriptor extensionDescriptor) { throw new NotImplementedException(); } public ExtensionEntry Load(ExtensionDescriptor descriptor) { return new ExtensionEntry { Descriptor = descriptor, ExportedTypes = new[] { typeof(Alpha), typeof(Beta), typeof(Phi) } }; } public void ExtensionActivated(ExtensionLoadingContext ctx, ExtensionDescriptor extension) { throw new NotImplementedException(); } public void ExtensionDeactivated(ExtensionLoadingContext ctx, ExtensionDescriptor extension) { throw new NotImplementedException(); } public void ExtensionRemoved(ExtensionLoadingContext ctx, DependencyDescriptor dependency) { throw new NotImplementedException(); } public void Monitor(ExtensionDescriptor extension, Action<IVolatileToken> monitor) { } public IEnumerable<ExtensionCompilationReference> GetCompilationReferences(DependencyDescriptor dependency) { throw new NotImplementedException(); } public IEnumerable<string> GetVirtualPathDependencies(DependencyDescriptor dependency) { throw new NotImplementedException(); } #endregion } [Test] public void AvailableExtensionsShouldFollowCatalogLocations() { _folders.Manifests.Add("foo", "Name: Foo"); _folders.Manifests.Add("bar", "Name: Bar"); _folders.Manifests.Add("frap", "Name: Frap"); _folders.Manifests.Add("quad", "Name: Quad"); var available = _manager.AvailableExtensions(); Assert.That(available.Count(), Is.EqualTo(4)); Assert.That(available, Has.Some.Property("Id").EqualTo("foo")); } [Test] public void ExtensionDescriptorKeywordsAreCaseInsensitive() { _folders.Manifests.Add("Sample", @" NaMe: Sample Extension SESSIONSTATE: disabled version: 2.x DESCRIPTION: HELLO "); var descriptor = _manager.AvailableExtensions().Single(); Assert.That(descriptor.Id, Is.EqualTo("Sample")); Assert.That(descriptor.Name, Is.EqualTo("Sample Extension")); Assert.That(descriptor.Version, Is.EqualTo("2.x")); Assert.That(descriptor.Description, Is.EqualTo("HELLO")); Assert.That(descriptor.SessionState, Is.EqualTo("disabled")); } [Test] public void ExtensionDescriptorsShouldHaveNameAndVersion() { _folders.Manifests.Add("Sample", @" Name: Sample Extension Version: 2.x "); var descriptor = _manager.AvailableExtensions().Single(); Assert.That(descriptor.Id, Is.EqualTo("Sample")); Assert.That(descriptor.Name, Is.EqualTo("Sample Extension")); Assert.That(descriptor.Version, Is.EqualTo("2.x")); } [Test] public void ExtensionDescriptorsShouldBeParsedForMinimalModuleTxt() { _folders.Manifests.Add("SuperWiki", @" Name: SuperWiki Version: 1.0.3 OrchardVersion: 1 Features: SuperWiki: Description: My super wiki module for Orchard. "); var descriptor = _manager.AvailableExtensions().Single(); Assert.That(descriptor.Id, Is.EqualTo("SuperWiki")); Assert.That(descriptor.Version, Is.EqualTo("1.0.3")); Assert.That(descriptor.OrchardVersion, Is.EqualTo("1")); Assert.That(descriptor.Features.Count(), Is.EqualTo(1)); Assert.That(descriptor.Features.First().Id, Is.EqualTo("SuperWiki")); Assert.That(descriptor.Features.First().Extension.Id, Is.EqualTo("SuperWiki")); Assert.That(descriptor.Features.First().Description, Is.EqualTo("My super wiki module for Orchard.")); } [Test] public void ExtensionDescriptorsShouldBeParsedForCompleteModuleTxt() { _folders.Manifests.Add("MyCompany.AnotherWiki", @" Name: AnotherWiki SessionState: required Author: Coder Notaprogrammer Website: http://anotherwiki.codeplex.com Version: 1.2.3 OrchardVersion: 1 Features: AnotherWiki: Description: My super wiki module for Orchard. Dependencies: Versioning, Search Category: Content types AnotherWiki Editor: Description: A rich editor for wiki contents. Dependencies: TinyMce, AnotherWiki Category: Input methods AnotherWiki DistributionList: Description: Sends e-mail alerts when wiki contents gets published. Dependencies: AnotherWiki, Email Subscriptions Category: Email AnotherWiki Captcha: Description: Kills spam. Or makes it zombie-like. Dependencies: AnotherWiki, reCaptcha Category: Spam "); var descriptor = _manager.AvailableExtensions().Single(); Assert.That(descriptor.Id, Is.EqualTo("MyCompany.AnotherWiki")); Assert.That(descriptor.Name, Is.EqualTo("AnotherWiki")); Assert.That(descriptor.Author, Is.EqualTo("Coder Notaprogrammer")); Assert.That(descriptor.WebSite, Is.EqualTo("http://anotherwiki.codeplex.com")); Assert.That(descriptor.Version, Is.EqualTo("1.2.3")); Assert.That(descriptor.OrchardVersion, Is.EqualTo("1")); Assert.That(descriptor.Features.Count(), Is.EqualTo(5)); Assert.That(descriptor.SessionState, Is.EqualTo("required")); foreach (var featureDescriptor in descriptor.Features) { switch (featureDescriptor.Id) { case "AnotherWiki": Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor)); Assert.That(featureDescriptor.Description, Is.EqualTo("My super wiki module for Orchard.")); Assert.That(featureDescriptor.Category, Is.EqualTo("Content types")); Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2)); Assert.That(featureDescriptor.Dependencies.Contains("Versioning")); Assert.That(featureDescriptor.Dependencies.Contains("Search")); break; case "AnotherWiki Editor": Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor)); Assert.That(featureDescriptor.Description, Is.EqualTo("A rich editor for wiki contents.")); Assert.That(featureDescriptor.Category, Is.EqualTo("Input methods")); Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2)); Assert.That(featureDescriptor.Dependencies.Contains("TinyMce")); Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki")); break; case "AnotherWiki DistributionList": Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor)); Assert.That(featureDescriptor.Description, Is.EqualTo("Sends e-mail alerts when wiki contents gets published.")); Assert.That(featureDescriptor.Category, Is.EqualTo("Email")); Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2)); Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki")); Assert.That(featureDescriptor.Dependencies.Contains("Email Subscriptions")); break; case "AnotherWiki Captcha": Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor)); Assert.That(featureDescriptor.Description, Is.EqualTo("Kills spam. Or makes it zombie-like.")); Assert.That(featureDescriptor.Category, Is.EqualTo("Spam")); Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2)); Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki")); Assert.That(featureDescriptor.Dependencies.Contains("reCaptcha")); break; // default feature. case "MyCompany.AnotherWiki": Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor)); break; default: Assert.Fail("Features not parsed correctly"); break; } } } [Test] public void ExtensionManagerShouldLoadFeatures() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); extensionFolder.Manifests.Add("TestModule", @" Name: TestModule Version: 1.0.3 OrchardVersion: 1 Features: TestModule: Description: My test module for Orchard. TestFeature: Description: Contains the Phi type. "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var testFeature = extensionManager.AvailableExtensions() .SelectMany(x => x.Features); var features = extensionManager.LoadFeatures(testFeature); var types = features.SelectMany(x => x.ExportedTypes); Assert.That(types.Count(), Is.Not.EqualTo(0)); } [Test] public void ExtensionManagerFeaturesContainNonAbstractClasses() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); extensionFolder.Manifests.Add("TestModule", @" Name: TestModule Version: 1.0.3 OrchardVersion: 1 Features: TestModule: Description: My test module for Orchard. TestFeature: Description: Contains the Phi type. "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var testFeature = extensionManager.AvailableExtensions() .SelectMany(x => x.Features); var features = extensionManager.LoadFeatures(testFeature); var types = features.SelectMany(x => x.ExportedTypes); foreach (var type in types) { Assert.That(type.IsClass); Assert.That(!type.IsAbstract); } } private static ExtensionManager CreateExtensionManager(StubFolders extensionFolder, StubLoaders extensionLoader) { return CreateExtensionManager(new[] { extensionFolder }, new[] { extensionLoader }); } private static ExtensionManager CreateExtensionManager(IEnumerable<StubFolders> extensionFolder, IEnumerable<StubLoaders> extensionLoader) { return new ExtensionManager(extensionFolder, extensionLoader, new StubCacheManager(), new StubParallelCacheContext(), new StubAsyncTokenProvider()); } [Test] public void ExtensionManagerShouldReturnEmptyFeatureIfFeatureDoesNotExist() { var featureDescriptor = new FeatureDescriptor { Id = "NoSuchFeature", Extension = new ExtensionDescriptor { Id = "NoSuchFeature" } }; Feature feature = _manager.LoadFeatures(new[] { featureDescriptor }).First(); Assert.AreEqual(featureDescriptor, feature.Descriptor); Assert.AreEqual(0, feature.ExportedTypes.Count()); } [Test] public void ExtensionManagerTestFeatureAttribute() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); extensionFolder.Manifests.Add("TestModule", @" Name: TestModule Version: 1.0.3 OrchardVersion: 1 Features: TestModule: Description: My test module for Orchard. TestFeature: Description: Contains the Phi type. "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var testFeature = extensionManager.AvailableExtensions() .SelectMany(x => x.Features) .Single(x => x.Id == "TestFeature"); foreach (var feature in extensionManager.LoadFeatures(new[] { testFeature })) { foreach (var type in feature.ExportedTypes) { foreach (OrchardFeatureAttribute featureAttribute in type.GetCustomAttributes(typeof(OrchardFeatureAttribute), false)) { Assert.That(featureAttribute.FeatureName, Is.EqualTo("TestFeature")); } } } } [Test] public void ExtensionManagerLoadFeatureReturnsTypesFromSpecificFeaturesWithFeatureAttribute() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); extensionFolder.Manifests.Add("TestModule", @" Name: TestModule Version: 1.0.3 OrchardVersion: 1 Features: TestModule: Description: My test module for Orchard. TestFeature: Description: Contains the Phi type. "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var testFeature = extensionManager.AvailableExtensions() .SelectMany(x => x.Features) .Single(x => x.Id == "TestFeature"); foreach (var feature in extensionManager.LoadFeatures(new[] { testFeature })) { foreach (var type in feature.ExportedTypes) { Assert.That(type == typeof(Phi)); } } } [Test] public void ExtensionManagerLoadFeatureDoesNotReturnTypesFromNonMatchingFeatures() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); extensionFolder.Manifests.Add("TestModule", @" Name: TestModule Version: 1.0.3 OrchardVersion: 1 Features: TestModule: Description: My test module for Orchard. TestFeature: Description: Contains the Phi type. "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var testModule = extensionManager.AvailableExtensions() .SelectMany(x => x.Features) .Single(x => x.Id == "TestModule"); foreach (var feature in extensionManager.LoadFeatures(new[] { testModule })) { foreach (var type in feature.ExportedTypes) { Assert.That(type != typeof(Phi)); Assert.That((type == typeof(Alpha) || (type == typeof(Beta)))); } } } [Test] public void ModuleNameIsIntroducedAsFeatureImplicitly() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); extensionFolder.Manifests.Add("Minimalistic", @" Name: Minimalistic Version: 1.0.3 OrchardVersion: 1 "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var minimalisticModule = extensionManager.AvailableExtensions().Single(x => x.Id == "Minimalistic"); Assert.That(minimalisticModule.Features.Count(), Is.EqualTo(1)); Assert.That(minimalisticModule.Features.Single().Id, Is.EqualTo("Minimalistic")); } [Test] public void FeatureDescriptorsAreInDependencyOrder() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); extensionFolder.Manifests.Add("Alpha", @" Name: Alpha Version: 1.0.3 OrchardVersion: 1 Features: Alpha: Dependencies: Gamma "); extensionFolder.Manifests.Add("Beta", @" Name: Beta Version: 1.0.3 OrchardVersion: 1 "); extensionFolder.Manifests.Add("Gamma", @" Name: Gamma Version: 1.0.3 OrchardVersion: 1 Features: Gamma: Dependencies: Beta "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var features = extensionManager.AvailableFeatures(); Assert.That(features.Aggregate("<", (a, b) => a + b.Id + "<"), Is.EqualTo("<Beta<Gamma<Alpha<")); } [Test] public void FeatureDescriptorsShouldBeLoadedInThemes() { var extensionLoader = new StubLoaders(); var moduleExtensionFolder = new StubFolders(); var themeExtensionFolder = new StubFolders(DefaultExtensionTypes.Theme); moduleExtensionFolder.Manifests.Add("Alpha", @" Name: Alpha Version: 1.0.3 OrchardVersion: 1 Features: Alpha: Dependencies: Gamma "); moduleExtensionFolder.Manifests.Add("Beta", @" Name: Beta Version: 1.0.3 OrchardVersion: 1 "); moduleExtensionFolder.Manifests.Add("Gamma", @" Name: Gamma Version: 1.0.3 OrchardVersion: 1 Features: Gamma: Dependencies: Beta "); moduleExtensionFolder.Manifests.Add("Classic", @" Name: Classic Version: 1.0.3 OrchardVersion: 1 "); IExtensionManager extensionManager = CreateExtensionManager(new[] { moduleExtensionFolder, themeExtensionFolder }, new[] { extensionLoader }); var features = extensionManager.AvailableFeatures(); Assert.That(features.Count(), Is.EqualTo(4)); } [Test] public void ThemeFeatureDescriptorsShouldBeAbleToDependOnModules() { var extensionLoader = new StubLoaders(); var moduleExtensionFolder = new StubFolders(); var themeExtensionFolder = new StubFolders(DefaultExtensionTypes.Theme); moduleExtensionFolder.Manifests.Add("Alpha", CreateManifest("Alpha", null, "Gamma")); moduleExtensionFolder.Manifests.Add("Beta", CreateManifest("Beta")); moduleExtensionFolder.Manifests.Add("Gamma", CreateManifest("Gamma", null, "Beta")); moduleExtensionFolder.Manifests.Add("Classic", CreateManifest("Classic", null, "Alpha")); AssertFeaturesAreInOrder(new[] { moduleExtensionFolder, themeExtensionFolder }, extensionLoader, "<Beta<Gamma<Alpha<Classic<"); } private static string CreateManifest(string name, string priority = null, string dependencies = null) { return string.Format(CultureInfo.InvariantCulture, @" Name: {0} Version: 1.0.3 OrchardVersion: 1{1}{2}", name, (dependencies == null ? null : "\nDependencies: " + dependencies), (priority == null ? null : "\nPriority:" + priority)); } private static void AssertFeaturesAreInOrder(StubFolders folder, StubLoaders loader, string expectedOrder) { AssertFeaturesAreInOrder(new StubFolders[] { folder }, loader, expectedOrder); } private static void AssertFeaturesAreInOrder(IEnumerable<StubFolders> folders, StubLoaders loader, string expectedOrder) { var extensionManager = CreateExtensionManager(folders, new[] { loader }); var features = extensionManager.AvailableFeatures(); Assert.That(features.Aggregate("<", (a, b) => a + b.Id + "<"), Is.EqualTo(expectedOrder)); } [Test] public void FeatureDescriptorsAreInDependencyAndPriorityOrder() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); // Check that priorities apply correctly on items on the same level of dependencies and are overwritten by dependencies extensionFolder.Manifests.Add("Alpha", CreateManifest("Alpha", "2", "Gamma")); // More important than Gamma but will get overwritten by the dependency extensionFolder.Manifests.Add("Beta", CreateManifest("Beta", "2")); extensionFolder.Manifests.Add("Foo", CreateManifest("Foo", "1")); extensionFolder.Manifests.Add("Gamma", CreateManifest("Gamma", "3", "Beta, Foo")); AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Foo<Beta<Gamma<Alpha<"); // Change priorities and see that it reflects properly // Gamma comes after Foo (same priority) because their order in the Manifests is preserved extensionFolder.Manifests["Foo"] = CreateManifest("Foo", "3"); AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Beta<Foo<Gamma<Alpha<"); // Remove dependency on Foo and see that it moves down the list since no one depends on it anymore extensionFolder.Manifests["Gamma"] = CreateManifest("Gamma", "3", "Beta"); AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Beta<Gamma<Alpha<Foo<"); // Change Foo to depend on Gamma and see that it says in its position (same dependencies as alpha but lower priority) extensionFolder.Manifests["Foo"] = CreateManifest("Foo", "3", "Gamma"); AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Beta<Gamma<Alpha<Foo<"); // Update Foo to a higher priority than alpha and see that it moves before alpha extensionFolder.Manifests["Foo"] = CreateManifest("Foo", "1", "Gamma"); AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Beta<Gamma<Foo<Alpha<"); } [Test] public void FeatureDescriptorsAreInPriorityOrder() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); // Check that priorities apply correctly on items on the same level of dependencies and are overwritten by dependencies extensionFolder.Manifests.Add("Alpha", CreateManifest("Alpha", "4")); // More important than Gamma but will get overwritten by the dependency extensionFolder.Manifests.Add("Beta", CreateManifest("Beta", "3")); extensionFolder.Manifests.Add("Foo", CreateManifest("Foo", "1")); extensionFolder.Manifests.Add("Gamma", CreateManifest("Gamma", "2")); AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Foo<Gamma<Beta<Alpha<"); } [Test] public void FeatureDescriptorsAreInManifestOrderWhenTheyHaveEqualPriority() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(); extensionFolder.Manifests.Add("Alpha", CreateManifest("Alpha", "4")); extensionFolder.Manifests.Add("Beta", CreateManifest("Beta", "4")); extensionFolder.Manifests.Add("Gamma", CreateManifest("Gamma", "4")); extensionFolder.Manifests.Add("Foo", CreateManifest("Foo", "3")); extensionFolder.Manifests.Add("Bar", CreateManifest("Bar", "3")); extensionFolder.Manifests.Add("Baz", CreateManifest("Baz", "3")); AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Foo<Bar<Baz<Alpha<Beta<Gamma<"); } } }
using System; using System.Windows.Input; using Avalonia.Input; using Avalonia.Media.Imaging; using Avalonia.Metadata; using Avalonia.Utilities; namespace Avalonia.Controls { public class NativeMenuItem : NativeMenuItemBase, INativeMenuItemExporterEventsImplBridge { private string _header; private KeyGesture _gesture; private bool _isEnabled = true; private ICommand _command; private bool _isChecked = false; private NativeMenuItemToggleType _toggleType; private IBitmap _icon; private NativeMenu _menu; static NativeMenuItem() { MenuProperty.Changed.Subscribe(args => { var item = (NativeMenuItem)args.Sender; var value = args.NewValue.GetValueOrDefault(); if (value.Parent != null && value.Parent != item) throw new InvalidOperationException("NativeMenu already has a parent"); value.Parent = item; }); } class CanExecuteChangedSubscriber : IWeakSubscriber<EventArgs> { private readonly NativeMenuItem _parent; public CanExecuteChangedSubscriber(NativeMenuItem parent) { _parent = parent; } public void OnEvent(object sender, EventArgs e) { _parent.CanExecuteChanged(); } } private readonly CanExecuteChangedSubscriber _canExecuteChangedSubscriber; public NativeMenuItem() { _canExecuteChangedSubscriber = new CanExecuteChangedSubscriber(this); } public NativeMenuItem(string header) : this() { Header = header; } public static readonly DirectProperty<NativeMenuItem, NativeMenu> MenuProperty = AvaloniaProperty.RegisterDirect<NativeMenuItem, NativeMenu>(nameof(Menu), o => o.Menu, (o, v) => o.Menu = v); [Content] public NativeMenu Menu { get => _menu; set { if (value.Parent != null && value.Parent != this) throw new InvalidOperationException("NativeMenu already has a parent"); SetAndRaise(MenuProperty, ref _menu, value); } } public static readonly DirectProperty<NativeMenuItem, IBitmap> IconProperty = AvaloniaProperty.RegisterDirect<NativeMenuItem, IBitmap>(nameof(Icon), o => o.Icon, (o, v) => o.Icon = v); public IBitmap Icon { get => _icon; set => SetAndRaise(IconProperty, ref _icon, value); } public static readonly DirectProperty<NativeMenuItem, string> HeaderProperty = AvaloniaProperty.RegisterDirect<NativeMenuItem, string>(nameof(Header), o => o.Header, (o, v) => o.Header = v); public string Header { get => _header; set => SetAndRaise(HeaderProperty, ref _header, value); } public static readonly DirectProperty<NativeMenuItem, KeyGesture> GestureProperty = AvaloniaProperty.RegisterDirect<NativeMenuItem, KeyGesture>(nameof(Gesture), o => o.Gesture, (o, v) => o.Gesture = v); public KeyGesture Gesture { get => _gesture; set => SetAndRaise(GestureProperty, ref _gesture, value); } public static readonly DirectProperty<NativeMenuItem, bool> IsCheckedProperty = AvaloniaProperty.RegisterDirect<NativeMenuItem, bool>( nameof(IsChecked), o => o.IsChecked, (o, v) => o.IsChecked = v); public bool IsChecked { get => _isChecked; set => SetAndRaise(IsCheckedProperty, ref _isChecked, value); } public static readonly DirectProperty<NativeMenuItem, NativeMenuItemToggleType> ToggleTypeProperty = AvaloniaProperty.RegisterDirect<NativeMenuItem, NativeMenuItemToggleType>( nameof(ToggleType), o => o.ToggleType, (o, v) => o.ToggleType = v); public NativeMenuItemToggleType ToggleType { get => _toggleType; set => SetAndRaise(ToggleTypeProperty, ref _toggleType, value); } public static readonly DirectProperty<NativeMenuItem, ICommand> CommandProperty = Button.CommandProperty.AddOwner<NativeMenuItem>( menuItem => menuItem.Command, (menuItem, command) => menuItem.Command = command, enableDataValidation: true); /// <summary> /// Defines the <see cref="CommandParameter"/> property. /// </summary> public static readonly StyledProperty<object> CommandParameterProperty = Button.CommandParameterProperty.AddOwner<MenuItem>(); public static readonly DirectProperty<NativeMenuItem, bool> IsEnabledProperty = AvaloniaProperty.RegisterDirect<NativeMenuItem, bool>(nameof(IsEnabled), o => o.IsEnabled, (o, v) => o.IsEnabled = v, true); public bool IsEnabled { get => _isEnabled; set => SetAndRaise(IsEnabledProperty, ref _isEnabled, value); } void CanExecuteChanged() { IsEnabled = _command?.CanExecute(CommandParameter) ?? true; } public bool HasClickHandlers => Click != null; public ICommand Command { get => _command; set { if (_command != null) WeakSubscriptionManager.Unsubscribe(_command, nameof(ICommand.CanExecuteChanged), _canExecuteChangedSubscriber); SetAndRaise(CommandProperty, ref _command, value); if (_command != null) WeakSubscriptionManager.Subscribe(_command, nameof(ICommand.CanExecuteChanged), _canExecuteChangedSubscriber); CanExecuteChanged(); } } /// <summary> /// Gets or sets the parameter to pass to the <see cref="Command"/> property of a /// <see cref="NativeMenuItem"/>. /// </summary> public object CommandParameter { get { return GetValue(CommandParameterProperty); } set { SetValue(CommandParameterProperty, value); } } /// <summary> /// Occurs when a <see cref="NativeMenuItem"/> is clicked. /// </summary> public event EventHandler Click; [Obsolete("Use Click event.")] public event EventHandler Clicked { add => Click += value; remove => Click -= value; } void INativeMenuItemExporterEventsImplBridge.RaiseClicked() { Click?.Invoke(this, new EventArgs()); if (Command?.CanExecute(CommandParameter) == true) { Command.Execute(CommandParameter); } } } public enum NativeMenuItemToggleType { None, CheckBox, Radio } }
// // Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s). // All rights reserved. // using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using System.Timers; using OpenADK.Library; using OpenADK.Library.us.Common; using OpenADK.Library.us.Student; using Timer = System.Timers.Timer; namespace Library.Examples.SimpleProvider { internal class StudentPersonalProvider : IPublisher { public StudentPersonalProvider() { try { InitializeDB(); } catch (AdkSchemaException adkse) { Console.WriteLine(adkse); } } /** * The amount of time to wait in between sending change events */ private int EVENT_INTERVAL = 30000; /** * The data provided by this simple provider class */ private List<StudentPersonal> fData; /** * The zone to send SIF events to */ private IZone fZone; public void OnRequest(IDataObjectOutputStream outStream, Query query, IZone zone, IMessageInfo info) { // To be a successful publisher of data using the ADK, follow these steps // 1) Examine the query conditions. If they are too complex for your agent, // throw the appropriate SIFException // This example agent uses the autoFilter() capability of DataObjectOutputStream. Using // this capability, any object can be written to the output stream and the stream will // filter out any objects that don't meet the conditions of the Query. However, a more // robust agent with large amounts of data would want to pre-filter the data when it does its // initial database query. outStream.Filter = query; Console.WriteLine("Responding to SIF_Request for StudentPersonal"); // 2) Write any data to the output stream foreach (StudentPersonal sp in fData) { outStream.Write(sp); } } /** * @param zone * @throws ADKException */ public void Provision(IZone zone) { zone.SetPublisher(this, StudentDTD.STUDENTPERSONAL, null); } /** * This class periodically publishes change events to the zone. This * method starts up the thread that publishes the change events. * * A normal SIF Agent would, instead look for changes in the application's database * and publish those as changes. */ public void StartEventProcessing(IZone zone) { if (fZone != null) { throw new AdkException("Event Processing thread is already running", zone); } fZone = zone; Timer timer = new Timer(); timer.Elapsed += delegate { SendEvent(); }; timer.Interval = 5000; timer.Start(); } public void SendEvent() { /** * This class periodically publishes change events to the zone. This * method starts up the thread that publishes the change events. * * A normal SIF Agent would, instead look for changes in the application's database * and publish those as changes. */ Console.WriteLine ("Event publishing enabled with an interval of " + EVENT_INTERVAL / 1000 + " seconds."); Random random = new Random(); bool isProcessing = true; // Go into a loop and send events while (isProcessing) { try { Thread.Sleep(EVENT_INTERVAL); StudentPersonal changedObject = fData[random.Next(fData.Count)]; StudentPersonal eventObject = new StudentPersonal(); eventObject.RefId = changedObject.RefId; // Create a change event with a random Student ID; String newNum = "A" + random.Next(999999).ToString(); eventObject.LocalId = newNum; fZone.ReportEvent(eventObject, EventAction.Change); } catch (Exception ex) { Console.WriteLine("Error during event processing: " + ex); isProcessing = false; } } } protected void InitializeDB() { fData = new List<StudentPersonal>(); Random rand = new Random(); fData.Add (CreateStudent ("C831540004395", "Ackerman", "Brian", "133 Devon Drive", "Birmingham", StatePrCode.AL, CountryCode.US, "35203", "0121 4541000", Gender.MALE, GradeLevelCode.C07, RaceType.WHITE, "19910102")); fData.Add (CreateStudent ("M830540004340", "Acosta", "Stacey", "17 Wellesley Park", "Birmingham", StatePrCode.AL, CountryCode.US, "35203", "0121 4541001", Gender.FEMALE, GradeLevelCode.C08, RaceType.AFRICAN_AMERICAN, "19871012")); fData.Add (CreateStudent ("X831540004405", "Addicks", "Amber", "162 Crossfield Road", "Birmingham", StatePrCode.AL, CountryCode.US, "35203", "0121 4541002", Gender.FEMALE, GradeLevelCode.C07, RaceType.WHITE, "19920402")); fData.Add (CreateStudent ("Birmingham", "Aguilar", "Mike", "189 Writtle Mews", "Edgebaston", StatePrCode.AL, CountryCode.US, "35203", "0121 4541003", Gender.MALE, GradeLevelCode.C07, RaceType.WHITE, "19910102")); fData.Add (CreateStudent ("A831540004820", "Alaev", "Dianna", "737 Writtle Mews", "Birmingham", StatePrCode.AL, CountryCode.US, "35203", "0121 4541004", Gender.FEMALE, GradeLevelCode.C07, RaceType.PACISLANDER, "19980704")); fData.Add (CreateStudent ("G831540004469", "Balboa", "Amy", "87 Almond Avenue", "Birmingham", StatePrCode.AL, CountryCode.US, "35203", "0121 4545000", Gender.FEMALE, GradeLevelCode.C01, RaceType.WHITE, "19901205")); fData.Add (CreateStudent ("H831540004078", "Baldwin", "Joshua", "142 Clarendon Avenue", "Edgebaston", StatePrCode.AL, CountryCode.US, "35203", "0121 4545001", Gender.MALE, GradeLevelCode.C02, RaceType.WHITE, "19960105")); fData.Add (CreateStudent ("J830540004064", "Ballard", "Aimee", "134 Dixon Close", "Birmingham", StatePrCode.AL, CountryCode.US, "35203", "0121 4545002", Gender.FEMALE, GradeLevelCode.C03, RaceType.WHITE, "19940506")); fData.Add (CreateStudent ("V831540004012", "Banas", "Ryan", "26 Mountview Drive", "Birmingham", StatePrCode.AL, CountryCode.US, "35203", "0121 4545003", Gender.MALE, GradeLevelCode.C04, RaceType.WHITE, "19930808")); fData.Add (CreateStudent ("B830540004119", "Barba", "Ashley", "958 Manchester Road", "Birmingham", StatePrCode.AL, CountryCode.US, "35203", "0121 4545004", Gender.FEMALE, GradeLevelCode.C05, RaceType.ASIAN, "19890102")); } private static StudentPersonal CreateStudent( String id, String lastName, String firstName, String street, String city, StatePrCode state, CountryCode country, String post, String phone, Gender gender, GradeLevelCode grade, RaceType race, String birthDateyyyyMMdd) { StudentPersonal student = new StudentPersonal(); ; student.RefId = Adk.MakeGuid(); student.LocalId = id; // Set the Name Name name = new Name(NameType.LEGAL, firstName, lastName); student.Name = name; Address addr = new Address(); addr.SetType(AddressType.C0369_PERMANENT); addr.SetStreet(street); addr.City = city; addr.SetStateProvince(state); addr.PostalCode = post; addr.SetCountry(country); student.AddressList = new StudentAddressList(PickupOrDropoff.NA, "NA", addr); student.PhoneNumberList = new PhoneNumberList(new PhoneNumber(PhoneNumberType.PRIMARY, phone)); Demographics dem = new Demographics(); dem.RaceList = new RaceList(new Race("", race)); dem.SetGender(gender); dem.BirthDate = DateTime.ParseExact (birthDateyyyyMMdd, "yyyyMMdd", CultureInfo.InvariantCulture.DateTimeFormat); student.Demographics = dem; return student; } } }
// 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.Reflection; using System.Runtime.CompilerServices; using Encoding = System.Text.Encoding; #if ES_BUILD_STANDALONE using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment; namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// TraceLogging: Constants and utility functions. /// </summary> internal static class Statics { #region Constants public const byte DefaultLevel = 5; public const byte TraceLoggingChannel = 0xb; public const byte InTypeMask = 31; public const byte InTypeFixedCountFlag = 32; public const byte InTypeVariableCountFlag = 64; public const byte InTypeCustomCountFlag = 96; public const byte InTypeCountMask = 96; public const byte InTypeChainFlag = 128; public const byte OutTypeMask = 127; public const byte OutTypeChainFlag = 128; public const EventTags EventTagsMask = (EventTags)0xfffffff; public static readonly TraceLoggingDataType IntPtrType = IntPtr.Size == 8 ? TraceLoggingDataType.Int64 : TraceLoggingDataType.Int32; public static readonly TraceLoggingDataType UIntPtrType = IntPtr.Size == 8 ? TraceLoggingDataType.UInt64 : TraceLoggingDataType.UInt32; public static readonly TraceLoggingDataType HexIntPtrType = IntPtr.Size == 8 ? TraceLoggingDataType.HexInt64 : TraceLoggingDataType.HexInt32; #endregion #region Metadata helpers /// <summary> /// A complete metadata chunk can be expressed as: /// length16 + prefix + null-terminated-utf8-name + suffix + additionalData. /// We assume that excludedData will be provided by some other means, /// but that its size is known. This function returns a blob containing /// length16 + prefix + name + suffix, with prefix and suffix initialized /// to 0's. The length16 value is initialized to the length of the returned /// blob plus additionalSize, so that the concatenation of the returned blob /// plus a blob of size additionalSize constitutes a valid metadata blob. /// </summary> /// <param name="name"> /// The name to include in the blob. /// </param> /// <param name="prefixSize"> /// Amount of space to reserve before name. For provider or field blobs, this /// should be 0. For event blobs, this is used for the tags field and will vary /// from 1 to 4, depending on how large the tags field needs to be. /// </param> /// <param name="suffixSize"> /// Amount of space to reserve after name. For example, a provider blob with no /// traits would reserve 0 extra bytes, but a provider blob with a single GroupId /// field would reserve 19 extra bytes. /// </param> /// <param name="additionalSize"> /// Amount of additional data in another blob. This value will be counted in the /// blob's length field, but will not be included in the returned byte[] object. /// The complete blob would then be the concatenation of the returned byte[] object /// with another byte[] object of length additionalSize. /// </param> /// <returns> /// A byte[] object with the length and name fields set, with room reserved for /// prefix and suffix. If additionalSize was 0, the byte[] object is a complete /// blob. Otherwise, another byte[] of size additionalSize must be concatenated /// with this one to form a complete blob. /// </returns> public static byte[] MetadataForString( string name, int prefixSize, int suffixSize, int additionalSize) { Statics.CheckName(name); int metadataSize = Encoding.UTF8.GetByteCount(name) + 3 + prefixSize + suffixSize; var metadata = new byte[metadataSize]; ushort totalSize = checked((ushort)(metadataSize + additionalSize)); metadata[0] = unchecked((byte)totalSize); metadata[1] = unchecked((byte)(totalSize >> 8)); Encoding.UTF8.GetBytes(name, 0, name.Length, metadata, 2 + prefixSize); return metadata; } /// <summary> /// Serialize the low 28 bits of the tags value into the metadata stream, /// starting at the index given by pos. Updates pos. Writes 1 to 4 bytes, /// depending on the value of the tags variable. Usable for event tags and /// field tags. /// /// Note that 'metadata' can be null, in which case it only updates 'pos'. /// This is useful for a two pass approach where you figure out how big to /// make the array, and then you fill it in. /// </summary> public static void EncodeTags(int tags, ref int pos, byte[] metadata) { // We transmit the low 28 bits of tags, high bits first, 7 bits at a time. var tagsLeft = tags & 0xfffffff; bool more; do { byte current = (byte)((tagsLeft >> 21) & 0x7f); more = (tagsLeft & 0x1fffff) != 0; current |= (byte)(more ? 0x80 : 0x00); tagsLeft = tagsLeft << 7; if (metadata != null) { metadata[pos] = current; } pos += 1; } while (more); } public static byte Combine( int settingValue, byte defaultValue) { unchecked { return (byte)settingValue == settingValue ? (byte)settingValue : defaultValue; } } public static byte Combine( int settingValue1, int settingValue2, byte defaultValue) { unchecked { return (byte)settingValue1 == settingValue1 ? (byte)settingValue1 : (byte)settingValue2 == settingValue2 ? (byte)settingValue2 : defaultValue; } } public static int Combine( int settingValue1, int settingValue2) { unchecked { return (byte)settingValue1 == settingValue1 ? settingValue1 : settingValue2; } } public static void CheckName(string name) { if (name != null && 0 <= name.IndexOf('\0')) { throw new ArgumentOutOfRangeException("name"); } } public static bool ShouldOverrideFieldName(string fieldName) { return (fieldName.Length <= 2 && fieldName[0] == '_'); } public static TraceLoggingDataType MakeDataType( TraceLoggingDataType baseType, EventFieldFormat format) { return (TraceLoggingDataType)(((int)baseType & 0x1f) | ((int)format << 8)); } /// <summary> /// Adjusts the native type based on format. /// - If format is default, return native. /// - If format is recognized, return the canonical type for that format. /// - Otherwise remove existing format from native and apply the requested format. /// </summary> public static TraceLoggingDataType Format8( EventFieldFormat format, TraceLoggingDataType native) { switch (format) { case EventFieldFormat.Default: return native; case EventFieldFormat.String: return TraceLoggingDataType.Char8; case EventFieldFormat.Boolean: return TraceLoggingDataType.Boolean8; case EventFieldFormat.Hexadecimal: return TraceLoggingDataType.HexInt8; #if false case EventSourceFieldFormat.Signed: return TraceLoggingDataType.Int8; case EventSourceFieldFormat.Unsigned: return TraceLoggingDataType.UInt8; #endif default: return MakeDataType(native, format); } } /// <summary> /// Adjusts the native type based on format. /// - If format is default, return native. /// - If format is recognized, return the canonical type for that format. /// - Otherwise remove existing format from native and apply the requested format. /// </summary> public static TraceLoggingDataType Format16( EventFieldFormat format, TraceLoggingDataType native) { switch (format) { case EventFieldFormat.Default: return native; case EventFieldFormat.String: return TraceLoggingDataType.Char16; case EventFieldFormat.Hexadecimal: return TraceLoggingDataType.HexInt16; #if false case EventSourceFieldFormat.Port: return TraceLoggingDataType.Port; case EventSourceFieldFormat.Signed: return TraceLoggingDataType.Int16; case EventSourceFieldFormat.Unsigned: return TraceLoggingDataType.UInt16; #endif default: return MakeDataType(native, format); } } /// <summary> /// Adjusts the native type based on format. /// - If format is default, return native. /// - If format is recognized, return the canonical type for that format. /// - Otherwise remove existing format from native and apply the requested format. /// </summary> public static TraceLoggingDataType Format32( EventFieldFormat format, TraceLoggingDataType native) { switch (format) { case EventFieldFormat.Default: return native; case EventFieldFormat.Boolean: return TraceLoggingDataType.Boolean32; case EventFieldFormat.Hexadecimal: return TraceLoggingDataType.HexInt32; #if false case EventSourceFieldFormat.Ipv4Address: return TraceLoggingDataType.Ipv4Address; case EventSourceFieldFormat.ProcessId: return TraceLoggingDataType.ProcessId; case EventSourceFieldFormat.ThreadId: return TraceLoggingDataType.ThreadId; case EventSourceFieldFormat.Win32Error: return TraceLoggingDataType.Win32Error; case EventSourceFieldFormat.NTStatus: return TraceLoggingDataType.NTStatus; #endif case EventFieldFormat.HResult: return TraceLoggingDataType.HResult; #if false case EventSourceFieldFormat.Signed: return TraceLoggingDataType.Int32; case EventSourceFieldFormat.Unsigned: return TraceLoggingDataType.UInt32; #endif default: return MakeDataType(native, format); } } /// <summary> /// Adjusts the native type based on format. /// - If format is default, return native. /// - If format is recognized, return the canonical type for that format. /// - Otherwise remove existing format from native and apply the requested format. /// </summary> public static TraceLoggingDataType Format64( EventFieldFormat format, TraceLoggingDataType native) { switch (format) { case EventFieldFormat.Default: return native; case EventFieldFormat.Hexadecimal: return TraceLoggingDataType.HexInt64; #if false case EventSourceFieldFormat.FileTime: return TraceLoggingDataType.FileTime; case EventSourceFieldFormat.Signed: return TraceLoggingDataType.Int64; case EventSourceFieldFormat.Unsigned: return TraceLoggingDataType.UInt64; #endif default: return MakeDataType(native, format); } } /// <summary> /// Adjusts the native type based on format. /// - If format is default, return native. /// - If format is recognized, return the canonical type for that format. /// - Otherwise remove existing format from native and apply the requested format. /// </summary> public static TraceLoggingDataType FormatPtr( EventFieldFormat format, TraceLoggingDataType native) { switch (format) { case EventFieldFormat.Default: return native; case EventFieldFormat.Hexadecimal: return HexIntPtrType; #if false case EventSourceFieldFormat.Signed: return IntPtrType; case EventSourceFieldFormat.Unsigned: return UIntPtrType; #endif default: return MakeDataType(native, format); } } #endregion #region Reflection helpers /* All TraceLogging use of reflection APIs should go through wrappers here. This helps with portability, and it also makes it easier to audit what kinds of reflection operations are being done. */ public static object CreateInstance(Type type, params object[] parameters) { return Activator.CreateInstance(type, parameters); } public static bool IsValueType(Type type) { bool result; #if ES_BUILD_PCL result = type.GetTypeInfo().IsValueType; #else result = type.IsValueType; #endif return result; } public static bool IsEnum(Type type) { bool result; #if ES_BUILD_PCL result = type.GetTypeInfo().IsEnum; #else result = type.IsEnum; #endif return result; } public static IEnumerable<PropertyInfo> GetProperties(Type type) { IEnumerable<PropertyInfo> result; #if ES_BUILD_PCL result = type.GetRuntimeProperties(); #else result = type.GetProperties(); #endif return result; } public static MethodInfo GetGetMethod(PropertyInfo propInfo) { MethodInfo result; #if ES_BUILD_PCL result = propInfo.GetMethod; #else result = propInfo.GetGetMethod(); #endif return result; } public static MethodInfo GetDeclaredStaticMethod(Type declaringType, string name) { MethodInfo result; #if ES_BUILD_PCL result = declaringType.GetTypeInfo().GetDeclaredMethod(name); #else result = declaringType.GetMethod( name, BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.NonPublic); #endif return result; } public static bool HasCustomAttribute( PropertyInfo propInfo, Type attributeType) { bool result; #if ES_BUILD_PCL result = propInfo.IsDefined(attributeType); #else var attributes = propInfo.GetCustomAttributes( attributeType, false); result = attributes.Length != 0; #endif return result; } public static AttributeType GetCustomAttribute<AttributeType>(PropertyInfo propInfo) where AttributeType : Attribute { AttributeType result = null; #if ES_BUILD_PCL foreach (var attrib in propInfo.GetCustomAttributes<AttributeType>(false)) { result = attrib; break; } #else var attributes = propInfo.GetCustomAttributes(typeof(AttributeType), false); if (attributes.Length != 0) { result = (AttributeType)attributes[0]; } #endif return result; } public static AttributeType GetCustomAttribute<AttributeType>(Type type) where AttributeType : Attribute { AttributeType result = null; #if ES_BUILD_PCL foreach (var attrib in type.GetTypeInfo().GetCustomAttributes<AttributeType>(false)) { result = attrib; break; } #else var attributes = type.GetCustomAttributes(typeof(AttributeType), false); if (attributes.Length != 0) { result = (AttributeType)attributes[0]; } #endif return result; } public static Type[] GetGenericArguments(Type type) { #if ES_BUILD_PCL return type.GenericTypeArguments; #else return type.GetGenericArguments(); #endif } public static Type FindEnumerableElementType(Type type) { Type elementType = null; if (IsGenericMatch(type, typeof(IEnumerable<>))) { elementType = GetGenericArguments(type)[0]; } else { #if ES_BUILD_PCL var ifaceTypes = type.GetTypeInfo().ImplementedInterfaces; #else var ifaceTypes = type.FindInterfaces(IsGenericMatch, typeof(IEnumerable<>)); #endif foreach (var ifaceType in ifaceTypes) { #if ES_BUILD_PCL if (!IsGenericMatch(ifaceType, typeof(IEnumerable<>))) { continue; } #endif if (elementType != null) { // ambiguous match. report no match at all. elementType = null; break; } elementType = GetGenericArguments(ifaceType)[0]; } } return elementType; } public static bool IsGenericMatch(Type type, object openType) { bool isGeneric; #if ES_BUILD_PCL isGeneric = type.IsConstructedGenericType; #else isGeneric = type.IsGenericType; #endif return isGeneric && type.GetGenericTypeDefinition() == (Type)openType; } public static Delegate CreateDelegate(Type delegateType, MethodInfo methodInfo) { Delegate result; #if ES_BUILD_PCL result = methodInfo.CreateDelegate( delegateType); #else result = Delegate.CreateDelegate( delegateType, methodInfo); #endif return result; } public static TraceLoggingTypeInfo GetTypeInfoInstance(Type dataType, List<Type> recursionCheck) { TraceLoggingTypeInfo result; if (dataType == typeof(Int32)) { result = TraceLoggingTypeInfo<Int32>.Instance; } else if (dataType == typeof(Int64)) { result = TraceLoggingTypeInfo<Int64>.Instance; } else if (dataType == typeof(String)) { result = TraceLoggingTypeInfo<String>.Instance; } else { var getInstanceInfo = Statics.GetDeclaredStaticMethod( typeof(TraceLoggingTypeInfo<>).MakeGenericType(dataType), "GetInstance"); var typeInfoObj = getInstanceInfo.Invoke(null, new object[] { recursionCheck }); result = (TraceLoggingTypeInfo)typeInfoObj; } return result; } public static TraceLoggingTypeInfo<DataType> CreateDefaultTypeInfo<DataType>( List<Type> recursionCheck) { TraceLoggingTypeInfo result; var dataType = typeof(DataType); if (recursionCheck.Contains(dataType)) { throw new NotSupportedException(Environment.GetResourceString("EventSource_RecursiveTypeDefinition")); } recursionCheck.Add(dataType); var eventAttrib = Statics.GetCustomAttribute<EventDataAttribute>(dataType); if (eventAttrib != null || Statics.GetCustomAttribute<CompilerGeneratedAttribute>(dataType) != null) { var analysis = new TypeAnalysis(dataType, eventAttrib, recursionCheck); result = new InvokeTypeInfo<DataType>(analysis); } else if (dataType.IsArray) { var elementType = dataType.GetElementType(); if (elementType == typeof(Boolean)) { result = new BooleanArrayTypeInfo(); } else if (elementType == typeof(Byte)) { result = new ByteArrayTypeInfo(); } else if (elementType == typeof(SByte)) { result = new SByteArrayTypeInfo(); } else if (elementType == typeof(Int16)) { result = new Int16ArrayTypeInfo(); } else if (elementType == typeof(UInt16)) { result = new UInt16ArrayTypeInfo(); } else if (elementType == typeof(Int32)) { result = new Int32ArrayTypeInfo(); } else if (elementType == typeof(UInt32)) { result = new UInt32ArrayTypeInfo(); } else if (elementType == typeof(Int64)) { result = new Int64ArrayTypeInfo(); } else if (elementType == typeof(UInt64)) { result = new UInt64ArrayTypeInfo(); } else if (elementType == typeof(Char)) { result = new CharArrayTypeInfo(); } else if (elementType == typeof(Double)) { result = new DoubleArrayTypeInfo(); } else if (elementType == typeof(Single)) { result = new SingleArrayTypeInfo(); } else if (elementType == typeof(IntPtr)) { result = new IntPtrArrayTypeInfo(); } else if (elementType == typeof(UIntPtr)) { result = new UIntPtrArrayTypeInfo(); } else if (elementType == typeof(Guid)) { result = new GuidArrayTypeInfo(); } else { result = (TraceLoggingTypeInfo<DataType>)CreateInstance( typeof(ArrayTypeInfo<>).MakeGenericType(elementType), GetTypeInfoInstance(elementType, recursionCheck)); } } else if (Statics.IsEnum(dataType)) { var underlyingType = Enum.GetUnderlyingType(dataType); if (underlyingType == typeof(Int32)) { result = new EnumInt32TypeInfo<DataType>(); } else if (underlyingType == typeof(UInt32)) { result = new EnumUInt32TypeInfo<DataType>(); } else if (underlyingType == typeof(Byte)) { result = new EnumByteTypeInfo<DataType>(); } else if (underlyingType == typeof(SByte)) { result = new EnumSByteTypeInfo<DataType>(); } else if (underlyingType == typeof(Int16)) { result = new EnumInt16TypeInfo<DataType>(); } else if (underlyingType == typeof(UInt16)) { result = new EnumUInt16TypeInfo<DataType>(); } else if (underlyingType == typeof(Int64)) { result = new EnumInt64TypeInfo<DataType>(); } else if (underlyingType == typeof(UInt64)) { result = new EnumUInt64TypeInfo<DataType>(); } else { // Unexpected throw new NotSupportedException(Environment.GetResourceString("EventSource_NotSupportedEnumType", dataType.Name, underlyingType.Name)); } } else if (dataType == typeof(String)) { result = new StringTypeInfo(); } else if (dataType == typeof(Boolean)) { result = new BooleanTypeInfo(); } else if (dataType == typeof(Byte)) { result = new ByteTypeInfo(); } else if (dataType == typeof(SByte)) { result = new SByteTypeInfo(); } else if (dataType == typeof(Int16)) { result = new Int16TypeInfo(); } else if (dataType == typeof(UInt16)) { result = new UInt16TypeInfo(); } else if (dataType == typeof(Int32)) { result = new Int32TypeInfo(); } else if (dataType == typeof(UInt32)) { result = new UInt32TypeInfo(); } else if (dataType == typeof(Int64)) { result = new Int64TypeInfo(); } else if (dataType == typeof(UInt64)) { result = new UInt64TypeInfo(); } else if (dataType == typeof(Char)) { result = new CharTypeInfo(); } else if (dataType == typeof(Double)) { result = new DoubleTypeInfo(); } else if (dataType == typeof(Single)) { result = new SingleTypeInfo(); } else if (dataType == typeof(DateTime)) { result = new DateTimeTypeInfo(); } else if (dataType == typeof(Decimal)) { result = new DecimalTypeInfo(); } else if (dataType == typeof(IntPtr)) { result = new IntPtrTypeInfo(); } else if (dataType == typeof(UIntPtr)) { result = new UIntPtrTypeInfo(); } else if (dataType == typeof(Guid)) { result = new GuidTypeInfo(); } else if (dataType == typeof(TimeSpan)) { result = new TimeSpanTypeInfo(); } else if (dataType == typeof(DateTimeOffset)) { result = new DateTimeOffsetTypeInfo(); } else if (dataType == typeof(EmptyStruct)) { result = new NullTypeInfo<EmptyStruct>(); } else if (IsGenericMatch(dataType, typeof(KeyValuePair<,>))) { var args = GetGenericArguments(dataType); result = (TraceLoggingTypeInfo<DataType>)CreateInstance( typeof(KeyValuePairTypeInfo<,>).MakeGenericType(args[0], args[1]), recursionCheck); } else if (IsGenericMatch(dataType, typeof(Nullable<>))) { var args = GetGenericArguments(dataType); result = (TraceLoggingTypeInfo<DataType>)CreateInstance( typeof(NullableTypeInfo<>).MakeGenericType(args[0]), recursionCheck); } else { var elementType = FindEnumerableElementType(dataType); if (elementType != null) { result = (TraceLoggingTypeInfo<DataType>)CreateInstance( typeof(EnumerableTypeInfo<,>).MakeGenericType(dataType, elementType), GetTypeInfoInstance(elementType, recursionCheck)); } else { throw new ArgumentException(Environment.GetResourceString("EventSource_NonCompliantTypeError", dataType.Name)); } } return (TraceLoggingTypeInfo<DataType>)result; } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace ExpenseRegister.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.Diagnostics; using System.IO.PortsTests; using System.Text; using System.Threading; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class Write_char_int_int : PortsTest { //The string size used for large char array testing private const int LARGE_BUFFER_SIZE = 2048; //When we test Write and do not care about actually writing anything we must still //create an cahr array to pass into the method the following is the size of the //char array used in this situation private const int DEFAULT_BUFFER_SIZE = 1; private const int DEFAULT_CHAR_OFFSET = 0; private const int DEFAULT_CHAR_COUNT = 1; //The maximum buffer size when a exception occurs private const int MAX_BUFFER_SIZE_FOR_EXCEPTION = 255; //The maximum buffer size when a exception is not expected private const int MAX_BUFFER_SIZE = 8; //The default number of times the write method is called when verifying write private const int DEFAULT_NUM_WRITES = 3; #region Test Cases [ConditionalFact(nameof(HasOneSerialPort))] public void Buffer_Null() { VerifyWriteException(null, 0, 1, typeof(ArgumentNullException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_NEG1() { VerifyWriteException(new char[DEFAULT_BUFFER_SIZE], -1, DEFAULT_CHAR_COUNT, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_NEGRND() { Random rndGen = new Random(-55); VerifyWriteException(new char[DEFAULT_BUFFER_SIZE], rndGen.Next(int.MinValue, 0), DEFAULT_CHAR_COUNT, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_MinInt() { VerifyWriteException(new char[DEFAULT_BUFFER_SIZE], int.MinValue, DEFAULT_CHAR_COUNT, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_NEG1() { VerifyWriteException(new char[DEFAULT_BUFFER_SIZE], DEFAULT_CHAR_OFFSET, -1, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_NEGRND() { Random rndGen = new Random(-55); VerifyWriteException(new char[DEFAULT_BUFFER_SIZE], DEFAULT_CHAR_OFFSET, rndGen.Next(int.MinValue, 0), typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_MinInt() { VerifyWriteException(new char[DEFAULT_BUFFER_SIZE], DEFAULT_CHAR_OFFSET, int.MinValue, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void OffsetCount_EQ_Length_Plus_1() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); int offset = rndGen.Next(0, bufferLength); int count = bufferLength + 1 - offset; Type expectedException = typeof(ArgumentException); VerifyWriteException(new char[bufferLength], offset, count, expectedException); } [ConditionalFact(nameof(HasOneSerialPort))] public void OffsetCount_GT_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); int offset = rndGen.Next(0, bufferLength); int count = rndGen.Next(bufferLength + 1 - offset, int.MaxValue); Type expectedException = typeof(ArgumentException); VerifyWriteException(new char[bufferLength], offset, count, expectedException); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_GT_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); int offset = rndGen.Next(bufferLength, int.MaxValue); int count = DEFAULT_CHAR_COUNT; Type expectedException = typeof(ArgumentException); VerifyWriteException(new char[bufferLength], offset, count, expectedException); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_GT_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); int offset = DEFAULT_CHAR_OFFSET; int count = rndGen.Next(bufferLength + 1, int.MaxValue); Type expectedException = typeof(ArgumentException); VerifyWriteException(new char[bufferLength], offset, count, expectedException); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void OffsetCount_EQ_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = bufferLength - offset; VerifyWrite(new char[bufferLength], offset, count); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void Offset_EQ_Length_Minus_1() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = bufferLength - 1; int count = 1; VerifyWrite(new char[bufferLength], offset, count); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void Count_EQ_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = 0; int count = bufferLength; VerifyWrite(new char[bufferLength], offset, count); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void Count_EQ_Zero() { int bufferLength = 0; int offset = 0; int count = bufferLength; VerifyWrite(new char[bufferLength], offset, count); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void ASCIIEncoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); VerifyWrite(new char[bufferLength], offset, count, new ASCIIEncoding()); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void UTF8Encoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); VerifyWrite(new char[bufferLength], offset, count, new UTF8Encoding()); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void UTF32Encoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); VerifyWrite(new char[bufferLength], offset, count, new UTF32Encoding()); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void UnicodeEncoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); VerifyWrite(new char[bufferLength], offset, count, new UnicodeEncoding()); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void LargeBuffer() { int bufferLength = LARGE_BUFFER_SIZE; int offset = 0; int count = bufferLength; VerifyWrite(new char[bufferLength], offset, count, 1); } #endregion #region Verification for Test Cases private void VerifyWriteException(char[] buffer, int offset, int count, Type expectedException) { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { int bufferLength = null == buffer ? 0 : buffer.Length; Debug.WriteLine("Verifying write method throws {0} buffer.Lenght={1}, offset={2}, count={3}", expectedException, bufferLength, offset, count); com.Open(); try { com.Write(buffer, offset, count); Fail("ERROR!!!: No Excpetion was thrown"); } catch (Exception e) { if (e.GetType() != expectedException) { Fail("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); } } if (com.IsOpen) com.Close(); } } private void VerifyWrite(char[] buffer, int offset, int count) { VerifyWrite(buffer, offset, count, new ASCIIEncoding()); } private void VerifyWrite(char[] buffer, int offset, int count, int numWrites) { VerifyWrite(buffer, offset, count, new ASCIIEncoding(), numWrites); } private void VerifyWrite(char[] buffer, int offset, int count, Encoding encoding) { VerifyWrite(buffer, offset, count, encoding, DEFAULT_NUM_WRITES); } private void VerifyWrite(char[] buffer, int offset, int count, Encoding encoding, int numWrites) { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { Debug.WriteLine("Verifying write method buffer.Lenght={0}, offset={1}, count={2}, endocing={3}", buffer.Length, offset, count, encoding.EncodingName); com1.Encoding = encoding; com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); TCSupport.GetRandomChars(buffer, 0, buffer.Length, TCSupport.CharacterOptions.Surrogates); VerifyWriteCharArray(buffer, offset, count, com1, com2, numWrites); } } private void VerifyWriteCharArray(char[] buffer, int offset, int count, SerialPort com1, SerialPort com2) { VerifyWriteCharArray(buffer, offset, count, com1, com2, DEFAULT_NUM_WRITES); } private void VerifyWriteCharArray(char[] buffer, int offset, int count, SerialPort com1, SerialPort com2, int numWrites) { char[] oldBuffer, expectedChars, actualChars; byte[] expectedBytes, actualBytes; int byteRead; int index = 0; oldBuffer = (char[])buffer.Clone(); expectedBytes = com1.Encoding.GetBytes(buffer, offset, count); expectedChars = com1.Encoding.GetChars(expectedBytes); actualBytes = new byte[expectedBytes.Length * numWrites]; for (int i = 0; i < numWrites; i++) { com1.Write(buffer, offset, count); } com2.ReadTimeout = 500; Thread.Sleep((int)(((expectedBytes.Length * numWrites * 10.0) / com1.BaudRate) * 1000) + 250); Assert.Equal(oldBuffer, buffer); while (true) { try { byteRead = com2.ReadByte(); } catch (TimeoutException) { break; } if (actualBytes.Length <= index) { //If we have read in more bytes then we expect Fail("ERROR!!!: We have received more bytes then were sent"); } actualBytes[index] = (byte)byteRead; index++; if (actualBytes.Length - index != com2.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", actualBytes.Length - index, com2.BytesToRead); } } actualChars = com1.Encoding.GetChars(actualBytes); if (actualChars.Length != expectedChars.Length * numWrites) { Fail("ERROR!!!: Expected to read {0} chars actually read {1}", expectedChars.Length * numWrites, actualChars.Length); } else { //Compare the chars that were read with the ones we expected to read for (int j = 0; j < numWrites; j++) { for (int i = 0; i < expectedChars.Length; i++) { if (expectedChars[i] != actualChars[i + expectedChars.Length * j]) { Fail("ERROR!!!: Expected to read {0} actual read {1} at {2}", (int)expectedChars[i], (int)actualChars[i + expectedChars.Length * j], i); } } } } //Compare the bytes that were read with the ones we expected to read for (int j = 0; j < numWrites; j++) { for (int i = 0; i < expectedBytes.Length; i++) { if (expectedBytes[i] != actualBytes[i + expectedBytes.Length * j]) { Fail("ERROR!!!: Expected to read byte {0} actual read {1} at {2}", (int)expectedBytes[i], (int)actualBytes[i + expectedBytes.Length * j], i); } } } } #endregion } }
/* VRPhysicsConstraintUJoint * MiddleVR * (c) MiddleVR */ using UnityEngine; using System; using System.Collections; using MiddleVR_Unity3D; [AddComponentMenu("MiddleVR/Physics/Constraints/Universal-Joint")] [RequireComponent(typeof(VRPhysicsBody))] public class VRPhysicsConstraintUJoint : MonoBehaviour { #region Member Variables [SerializeField] private GameObject m_ConnectedBody = null; [SerializeField] private Vector3 m_Anchor = new Vector3(0.0f, 0.0f, 0.0f); [SerializeField] private Vector3 m_Axis0 = new Vector3(1.0f, 0.0f, 0.0f); [SerializeField] private Vector3 m_Axis1 = new Vector3(0.0f, 1.0f, 0.0f); [SerializeField] private float m_GizmoSphereRadius = 0.1f; [SerializeField] private float m_GizmoLineLength = 1.0f; private vrPhysicsConstraintUJoint m_PhysicsConstraint = null; private string m_PhysicsConstraintName = ""; private vrEventListener m_MVREventListener = null; #endregion #region Member Properties public vrPhysicsConstraintUJoint PhysicsConstraint { get { return m_PhysicsConstraint; } } public string PhysicsConstraintName { get { return m_PhysicsConstraintName; } } public GameObject ConnectedBody { get { return m_ConnectedBody; } set { m_ConnectedBody = value; } } public Vector3 Anchor { get { return m_Anchor; } set { m_Anchor = value; } } public Vector3 Axis0 { get { return m_Axis0; } set { m_Axis0 = value; } } public Vector3 Axis1 { get { return m_Axis1; } set { m_Axis1 = value; } } #endregion #region MonoBehaviour Member Functions protected void Start() { if (MiddleVR.VRClusterMgr.IsCluster() && !MiddleVR.VRClusterMgr.IsServer()) { enabled = false; return; } if (MiddleVR.VRPhysicsMgr == null) { MiddleVRTools.Log(0, "No PhysicsManager found when creating a U-joint constraint."); return; } vrPhysicsEngine physicsEngine = MiddleVR.VRPhysicsMgr.GetPhysicsEngine(); if (physicsEngine == null) { return; } if (m_PhysicsConstraint == null) { m_PhysicsConstraint = physicsEngine.CreateConstraintUJointWithUniqueName(name); if (m_PhysicsConstraint == null) { MiddleVRTools.Log(0, "[X] Could not create a U-joint physics constraint for '" + name + "'."); } else { GC.SuppressFinalize(m_PhysicsConstraint); m_MVREventListener = new vrEventListener(OnMVRNodeDestroy); m_PhysicsConstraint.AddEventListener(m_MVREventListener); m_PhysicsConstraintName = m_PhysicsConstraint.GetName(); AddConstraint(); } } } protected void OnDrawGizmosSelected() { if (enabled) { Gizmos.color = Color.green; Vector3 origin = transform.TransformPoint(m_Anchor); Gizmos.DrawSphere(origin, m_GizmoSphereRadius); Gizmos.color = Color.yellow; Vector3 axis0Dir = transform.TransformDirection(m_Axis0); axis0Dir.Normalize(); Gizmos.DrawLine(origin, origin + m_GizmoLineLength * axis0Dir); Gizmos.color = Color.gray; Vector3 axis1Dir = transform.TransformDirection(m_Axis1); axis1Dir.Normalize(); Gizmos.DrawLine(origin, origin + m_GizmoLineLength * axis1Dir); } } protected void OnDestroy() { if (m_PhysicsConstraint == null) { return; } if (MiddleVR.VRPhysicsMgr == null) { return; } vrPhysicsEngine physicsEngine = MiddleVR.VRPhysicsMgr.GetPhysicsEngine(); if (physicsEngine == null) { return; } physicsEngine.DestroyConstraint(m_PhysicsConstraintName); m_PhysicsConstraint = null; m_PhysicsConstraintName = ""; } #endregion #region VRPhysicsConstraintUJoint Functions protected bool AddConstraint() { vrPhysicsEngine physicsEngine = MiddleVR.VRPhysicsMgr.GetPhysicsEngine(); if (physicsEngine == null) { return false; } if (m_PhysicsConstraint == null) { return false; } bool addedToSimulation = false; // Cannot fail since we require this component. VRPhysicsBody body0 = GetComponent<VRPhysicsBody>(); VRPhysicsBody body1 = null; if (m_ConnectedBody != null) { body1 = m_ConnectedBody.GetComponent<VRPhysicsBody>(); } if (body0.PhysicsBody != null) { m_PhysicsConstraint.SetPosition(MiddleVRTools.FromUnity(Anchor)); m_PhysicsConstraint.SetAxis0(MiddleVRTools.FromUnity(Axis0)); m_PhysicsConstraint.SetAxis1(MiddleVRTools.FromUnity(Axis1)); m_PhysicsConstraint.SetBody(0, body0.PhysicsBody); m_PhysicsConstraint.SetBody(1, body1 != null ? body1.PhysicsBody : null); addedToSimulation = physicsEngine.AddConstraint(m_PhysicsConstraint); if (addedToSimulation) { MiddleVRTools.Log(3, "[ ] The constraint '" + m_PhysicsConstraintName + "' was added to the physics simulation."); } else { MiddleVRTools.Log(3, "[X] Failed to add the constraint '" + m_PhysicsConstraintName + "' to the physics simulation."); } } else { MiddleVRTools.Log(0, "[X] The PhysicsBody of '" + name + "' for the U-joint physics constraint '" + m_PhysicsConstraintName + "' is null."); } return addedToSimulation; } private bool OnMVRNodeDestroy(vrEvent iBaseEvt) { vrObjectEvent e = vrObjectEvent.Cast(iBaseEvt); if (e != null) { if (e.ComesFrom(m_PhysicsConstraint)) { if (e.eventType == (int)VRObjectEventEnum.VRObjectEvent_Destroy) { // Killed in MiddleVR so delete it in C#. m_PhysicsConstraint.Dispose(); } } } return true; } #endregion }
using System; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Collections.Generic; using System.ComponentModel; using System.Text; using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Shared; using System.Xml; using System.IO; using DSL.POS.Facade; using DSL.POS.DTO.DTO; using DSL.POS.BusinessLogicLayer.Interface; using DSL.POS.Common.Utility; using DSL.POS.Report; public partial class SalesReturn : System.Web.UI.Page { protected DataTable myDt; Guid guidSalesMain_Pk_Code; ClsErrorHandle cls = new ClsErrorHandle(); private ReportDocument oReportDocument = new ReportDocument(); protected void Page_Load(object sender, EventArgs e) { if (!Roles.IsUserInRole(ConfigurationManager.AppSettings["salesuserrolename"])) { Response.Redirect("~/CustomErrorPages/NotAuthorized.aspx"); } if (!IsPostBack) { //this.txtDate.Text = DateTime.Now.Day.ToString(); txtInvoiceNo.Attributes.Add("onkeypress", "clickbtn('" + btnInvoice.ClientID + "')"); ddlProductName.Attributes.Add("onkeypress", "clickbtn('" + btnClickProduct_ddl.ClientID + "')"); txtProduct.Attributes.Add("onkeypress", "clickbtn('" + btnClickProductCode.ClientID + "')"); txtQuantity.Attributes.Add("onkeypress", "clickbtn('" + btnAdd.ClientID + "')"); txtCustomerId.Attributes.Add("onkeypress", "clickbtn('" + btnClickMemberID.ClientID + "')"); //txtProduct.Attributes.Add("onkeypress", "clickbtn('" + btnClickProductCode.ClientID + "')"); //txtQuantity.Attributes.Add("onkeypress", "FocusControl_byEnter()"); ddlReturnMode.Attributes.Add("onkeypress", "FocusControl_byEnter()"); txtReturnAmount.Attributes.Add("onkeypress", "FocusControl_byEnter()"); // fill drop down list Facade facade = Facade.GetInstance(); DropDownListProduct(facade); // Create Temporary Table in Session for Store Product Information CreateTableInSession(); this.txtInvoiceNo.Focus(); //this.txtDate.Text = DateTime.Now.ToString(); this.ddlReturnMode.Items.Add("Credit"); this.ddlReturnMode.Items.Add("Cash"); this.ddlReturnMode.Items.Add("Cheque"); } } private void DropDownListProduct(Facade facade) { IProductInfoBL oIProductInfoBL = facade.GetProductInfoInstance(); List<ProductInfoDTO> oCategoryList = oIProductInfoBL.GetProductInfo(); int i = 0; ddlProductName.Items.Clear(); ddlProductName.Items.Add("(Select any category)"); this.ddlProductName.Items[i].Value = ""; foreach (ProductInfoDTO newDto in oCategoryList) { i++; this.ddlProductName.Items.Add(newDto.P_Name); this.ddlProductName.Items[i].Value = newDto.PrimaryKey.ToString(); } } /// All Method is available under the block #region All_Method /// <summary> /// Create A New Table And keep in Session /// </summary> protected void CreateTableInSession() { //Initialize data table myDt = new DataTable(); //create data table: column, data type, name myDt = CreateDataTable(); //Keep data table in session Session["myDatatable"] = myDt; //Convert data table from session, put data source for grid view this.GridView1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView; //Bind grid this.GridView1.DataBind(); } /// <summary> /// Create data table /// </summary> /// <returns>Data table</returns> private DataTable CreateDataTable() { DataTable myDataTable = new DataTable("SalesSub"); DataColumn myDataColumn; myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "Product Code"; myDataTable.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "Product Name"; myDataTable.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "Quantity"; myDataTable.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "Rate"; myDataTable.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "VAT"; myDataTable.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "TAX"; myDataTable.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "Discount"; myDataTable.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "Total Amount"; myDataTable.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.Guid"); myDataColumn.ColumnName = "PK"; myDataTable.Columns.Add(myDataColumn); return myDataTable; } /// <summary> /// Create data table for Invoice /// </summary> /// <returns>Data table</returns> private DataTable CreateDataTableInvoice() { DataTable myDataTableInvoice = new DataTable("SalesMain"); DataColumn myDataColumn; myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.Guid"); myDataColumn.ColumnName = "PK"; myDataTableInvoice.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "InvoiceNo"; myDataTableInvoice.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "InvoiceDate"; myDataTableInvoice.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "MemberID"; myDataColumn.AllowDBNull=true; myDataTableInvoice.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "MemberName"; myDataColumn.AllowDBNull = true; myDataTableInvoice.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "MemberAddress"; myDataColumn.AllowDBNull = true; myDataTableInvoice.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "DipositBalance"; myDataColumn.AllowDBNull = true; myDataTableInvoice.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "Discount"; myDataTableInvoice.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "ReturnMode"; myDataTableInvoice.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "ReturnAmount"; myDataTableInvoice.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "TotalAmount"; myDataTableInvoice.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "Remarks"; myDataTableInvoice.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "SSProductCode"; myDataTableInvoice.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "SSProductName"; myDataTableInvoice.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "SSQuantity"; myDataTableInvoice.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "SSRate"; myDataTableInvoice.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "SSVAT"; myDataTableInvoice.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "SSTAX"; myDataTableInvoice.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "SSDiscount"; myDataTableInvoice.Columns.Add(myDataColumn); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.Guid"); myDataColumn.ColumnName = "SSPK"; myDataTableInvoice.Columns.Add(myDataColumn); return myDataTableInvoice; } /// <summary> /// Add in Table Sales Main & Sub Information /// </summary> /// <param name="myTable">DataTable Main</param> /// <param name="subTable">DataTable Sub</param> /// <param name="strInvoiceNo">Invoice No</param> private void AddRowInTableSalesMain(ref DataTable myTable,DataTable subTable,string strInvoiceNo) { try { int rowNo = 0; int totalRows = 0; // total datatable's rows keep in local variable totalRows = subTable.Rows.Count; for (rowNo = 0; rowNo < totalRows; rowNo++) { DataRow row; row = myTable.NewRow(); row["PK"] = this.hfMemberPK.Value; row["InvoiceNo"] = strInvoiceNo; row["InvoiceDate"] = this.txtInvoiceDate.Text; row["MemberID"] = this.txtCustomerId.Text; row["MemberName"] = this.txtCustomerName.Text; row["MemberAddress"] = this.txtAddress.Text; row["DipositBalance"] = (this.txtDepositBalance.Text == string.Empty ? "0" : this.txtDepositBalance.Text); row["TotalAmount"] = this.txtTotalAmount.Text; row["ReturnMode"] = this.ddlReturnMode.Text; row["ReturnAmount"] = (this.txtReturnAmount.Text == string.Empty ? "0" : this.txtReturnAmount.Text); row["Remarks"] = (this.txtRemarks.Text == string.Empty ? "" : this.txtRemarks.Text); row["TotalAmount"] = this.txtTotalAmount.Text; row["SSProductCode"] = subTable.Rows[rowNo][0]; row["SSProductName"] = subTable.Rows[rowNo][1]; row["SSQuantity"] = subTable.Rows[rowNo][2]; row["SSRate"] = subTable.Rows[rowNo][3]; row["SSVAT"] = subTable.Rows[rowNo][4]; row["SSTAX"] = subTable.Rows[rowNo][5]; row["SSDiscount"] = subTable.Rows[rowNo][6]; row["SSPK"] = subTable.Rows[rowNo][8]; myTable.Rows.Add(row); } } catch (Exception Exp) { lblErrorMessage.Text = cls.ErrorString(Exp); } } /// <summary> /// Get Total Amount all Entry product amount /// </summary> /// <returns>decimal</returns> private decimal GetTotalAmount() { decimal totalAmount = 0; int rowNo = 0; int totalRows = 0; DataTable myDataTable = new DataTable(); myDataTable = ((DataTable)Session["myDatatable"]); totalRows = myDataTable.Rows.Count; for (rowNo = 0; rowNo < totalRows; rowNo++) { totalAmount = totalAmount + Convert.ToDecimal(myDataTable.Rows[rowNo][7]); } return totalAmount; } /// <summary> /// Add New Raw In table /// </summary> /// <param name="ProductCode"></param> /// <param name="strProductName"></param> /// <param name="quantity"></param> /// <param name="rate"></param> /// <param name="vat"></param> /// <param name="tax"></param> /// <param name="discount"></param> /// <param name="myTable"></param> private void AddDataToTable(string ProductCode, string strProductName, string quantity, string rate, string vat, string tax, string discount, string P_PK, DataTable myTable) { try { DataRow row; row = myTable.NewRow(); row["Product Code"] = ProductCode; row["Product Name"] = strProductName; row["Quantity"] = quantity; row["Rate"] = rate; row["VAT"] = vat; row["TAX"] = tax; row["Discount"] = discount; row["Total Amount"] = ((Convert.ToDecimal(rate) + Convert.ToDecimal(tax) + Convert.ToDecimal(vat)) * Convert.ToDecimal(quantity)) - (Convert.ToDecimal(discount) * Convert.ToDecimal(quantity)); //row["PK"]=Guid Guid p_pk = new Guid(P_PK); row["PK"] = p_pk; myTable.Rows.Add(row); } catch (Exception Exp) { lblErrorMessage.Text = cls.ErrorString(Exp); } } /// <summary> /// set up data in Grid View /// </summary> protected void Get_Data_InTable() { try { int count = 0; int rowNo = 0; int totalRows = 0; if (txtProduct.Text.Trim() == "") { this.lblErrorMessage.Text = "You must fill a Product Code."; return; } else if (txtQuantity.Text.Trim() == "") { this.lblErrorMessage.Text = "You must fill a Quantity."; return; } else if (txtRate.Text.Trim() == "") { this.lblErrorMessage.Text = "You must fill a Rate."; return; } else { this.lblErrorMessage.Text = ""; // create data table DataTable myDataTable = new DataTable(); myDataTable = ((DataTable)Session["myDatatable"]); // total datatable's rows keep in local variable totalRows = myDataTable.Rows.Count; for (rowNo = 0; rowNo < totalRows; rowNo++) { //we get the Hidden Fields value if user try to insert same product // or update inserted product if (this.HiddenField1.Value != "") { // under declear condition will execute when user want to update // Existing product information if (Convert.ToString(this.HiddenField1.Value) == (string)myDataTable.Rows[rowNo][0]) { myDataTable.Rows[rowNo][0] = this.txtProduct.Text; myDataTable.Rows[rowNo][1] = this.txtProductName.Text; myDataTable.Rows[rowNo][2] = this.txtQuantity.Text; myDataTable.Rows[rowNo][3] = this.txtRate.Text; myDataTable.Rows[rowNo][4] = this.hfVat.Value; myDataTable.Rows[rowNo][5] = this.hfTax.Value; myDataTable.Rows[rowNo][6] = this.txtDiscount.Text; myDataTable.Rows[rowNo][7] = (((this.txtRate.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtRate.Text)) + (this.hfVat.Value == string.Empty ? 0 : Convert.ToDecimal(this.hfVat.Value)) + (this.hfTax.Value == string.Empty ? 0 : Convert.ToDecimal(this.hfTax.Value))) * (this.txtQuantity.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtQuantity.Text))) - ((this.txtDiscount.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtDiscount.Text)) * (this.txtQuantity.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtQuantity.Text))); myDataTable.Rows[rowNo][8] = this.hfP_PK.Value.ToString(); count = 1; this.HiddenField1.Value = ""; this.btnAdd.Text = "Add"; this.hfP_PK.Value = ""; break; } else count = 0; } // under declear condition will execute when user want to insert // same product information else if (this.txtProduct.Text.Trim() == myDataTable.Rows[rowNo][0].ToString()) { string addQuantity; decimal totalQuantity = 0; addQuantity = myDataTable.Rows[rowNo][2].ToString(); totalQuantity = (this.txtQuantity.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtQuantity.Text)) + Convert.ToDecimal(addQuantity); myDataTable.Rows[rowNo][2] = totalQuantity.ToString(); myDataTable.Rows[rowNo][7] = (((this.txtRate.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtRate.Text)) + (this.hfVat.Value == string.Empty ? 0 : Convert.ToDecimal(this.hfVat.Value)) + (this.hfTax.Value == string.Empty ? 0 : Convert.ToDecimal(this.hfTax.Value))) * (totalQuantity)) - ((this.txtDiscount.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtDiscount.Text)) * (totalQuantity)); myDataTable.Rows[rowNo][8] = this.hfP_PK.Value.ToString(); this.btnAdd.Text = "Add"; count = 1; this.HiddenField1.Value = ""; break; } else count = 0; } if (count == 0) { // under declare the statement will execute when user try to insert in new product information. AddDataToTable(this.txtProduct.Text.Trim(), this.txtProductName.Text.Trim(), this.txtQuantity.Text.Trim(), this.txtRate.Text.Trim(), this.hfVat.Value.Trim(), this.hfTax.Value.Trim(), this.txtDiscount.Text.Trim(), this.hfP_PK.Value.ToString(), (DataTable)Session["myDatatable"]); } // Bind Table With Session this.GridView1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView; this.GridView1.DataBind(); //clear input texts this.txtProduct.Text = ""; this.txtQuantity.Text = ""; this.txtRate.Text = ""; this.hfVat.Value = ""; this.hfTax.Value = ""; this.txtQuantity.Text = ""; this.txtProductName.Text = ""; this.txtDiscount.Text = ""; this.hfP_PK.Value = ""; } } catch (Exception Exp) { lblErrorMessage.Text = cls.ErrorString(Exp); } finally { // update Total Amount, Dur Amount , Paid Amount // when user insert new or update Product information. this.txtTotalAmount.Text = GetTotalAmount().ToString("#####.#0"); this.txtReturnAmount.Text = GetTotalAmount().ToString("#####.#0"); //this.txtDue.Text = GetTotalAmount().ToString("#####.#0"); } } # endregion /// <summary> /// Save the Information in Grid View /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnAdd_Click(object sender, EventArgs e) { try { this.Get_Data_InTable(); } catch (Exception Exp) { lblErrorMessage.Text = cls.ErrorString(Exp); } finally { ScriptManager1.SetFocus(txtProduct); } } /// <summary> /// Entey Product update or delete /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowEdting(object sender, GridViewCommandEventArgs e) { //=========================================================== // under the variable used for Data delele DataTable myDataTable = new DataTable(); int rowNo = 0; int totalRows = 0; //============================================================ try { if (e.CommandName == "Edit") { int index = Convert.ToInt32(e.CommandArgument); GridViewRow row = GridView1.Rows[index]; DataKey xx = this.GridView1.DataKeys[index]; this.hfP_PK.Value= xx.Value.ToString(); this.txtProduct.Text = Server.HtmlDecode(row.Cells[2].Text); this.txtProductName.Text = Server.HtmlDecode(row.Cells[3].Text); this.txtQuantity.Text = Server.HtmlDecode(row.Cells[4].Text); this.txtRate.Text = Server.HtmlDecode(row.Cells[5].Text); this.hfTax.Value = Server.HtmlDecode(row.Cells[6].Text); this.txtDiscount.Text = Server.HtmlDecode(row.Cells[7].Text); this.btnAdd.Text = "Update"; this.HiddenField1.Value = row.Cells[2].Text; } if (e.CommandName == "Delete") { int index = Convert.ToInt32(e.CommandArgument); GridViewRow row = GridView1.Rows[index]; this.HiddenField1.Value = row.Cells[2].Text; myDataTable = ((DataTable)Session["myDatatable"]); totalRows = myDataTable.Rows.Count; for (rowNo = 0; rowNo < totalRows; rowNo++) { if (Convert.ToString(HiddenField1.Value) == (string)myDataTable.Rows[rowNo][0]) { myDataTable.Rows.RemoveAt(rowNo); break; } } this.GridView1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView; this.GridView1.DataBind(); // for get update Total, Due , Paid Amount after delete any Product inserted formation this.txtTotalAmount.Text = GetTotalAmount().ToString("#####.#0"); this.txtReturnAmount.Text = GetTotalAmount().ToString("#####.#0"); //this.txtDue.Text = GetTotalAmount().ToString("#####.#0"); } } catch (Exception Exp) { lblErrorMessage.Text = cls.ErrorString(Exp); } } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { } protected void btnSave_Click(object sender, EventArgs e) { try { string strInvoiceNo = null; // DataSet ds = new DataSet(); // create Data Table object for sales sub DataTable myDataTable = new DataTable(); // create Data Table object for sales Main DataTable myDataTableSalesMain = new DataTable(); // //create data table: column, data type, name myDataTableSalesMain=CreateDataTableInvoice(); myDataTable = ((DataTable)Session["myDatatable"]); SalesReturnMainDTO dto = populate(); if (dto.SalesReturnSubDTO.Count == 0) { this.lblErrorMessage.Text = "Have to insert at least one product."; return; } Facade facade = Facade.GetInstance(); ISalesReturnInfoBL oISalesReturnInfoBL = facade.createSalesReturnBL(); oISalesReturnInfoBL.addNewSalesReturnInfo(dto); this.AddRowInTableSalesMain(ref myDataTableSalesMain,myDataTable, strInvoiceNo); ds.Tables.Add(myDataTableSalesMain); //string crPath = "CrysSalesInvoice.rpt"; //string reportPath = Server.MapPath(crPath); //oReportDocument.Load(reportPath); //oReportDocument.SetDataSource(ds.Tables[0]); //CommonViewer.CRReportDefinition = oReportDocument; //Response.Redirect("~/Client/Sales/ReportViewer.aspx"); this.lblErrorMessage.Text = "Data Save Successfully."; //===========Clear Text Box and GridView5======================== this.hfMemberPK.Value = ""; this.hfP_PK.Value = ""; this.HiddenField1.Value = ""; this.txtCustomerId.Text = ""; this.txtCustomerName.Text = ""; this.txtAddress.Text = ""; this.txtDepositBalance.Text = ""; this.txtDiscount.Text = ""; this.txtInvoiceNo.Text = ""; this.txtProduct.Text = ""; this.txtQuantity.Text = ""; this.txtRate.Text = ""; this.txtReturnAmount.Text = ""; this.hfTax.Value = ""; this.hfVat.Value = ""; this.txtTotalAmount.Text = ""; this.txtDepositBalance.Text = ""; this.pnlMember.Visible = false; this.pnlInvoiceDate.Visible = false; myDataTable.Clear(); myDataTable.Reset(); myDataTableSalesMain.Clear(); myDataTableSalesMain.Reset(); this.GridView1.DataSource = myDataTable.DefaultView; this.GridView1.DataBind(); // Create a New Session and Table CreateTableInSession(); //============================================================== } catch (Exception Exp) { lblErrorMessage.Text = cls.ErrorString(Exp); } } private Guid Get_Booth_PK() { Guid BoothID = Guid.NewGuid(); if (Request.Cookies["DPOS"] != null) { string strBoothID = ""; if (Request.Cookies["DPOS"]["BoothNo"] != null) { strBoothID = Request.Cookies["DPOS"]["BoothNo"]; BoothInfoDTO dto = new BoothInfoDTO(); // populate dto //Facade facade = Facade.GetInstance(); // PK keep in local variable BoothID= (Guid)TypeDescriptor.GetConverter(BoothID).ConvertFromString(strBoothID); } } return BoothID; } /// <summary> /// set up Sales Main And Sub DTO /// </summary> /// <returns></returns> public SalesReturnMainDTO populate() { SalesReturnMainDTO oSalesReturnMainDTO = new SalesReturnMainDTO(); List<SalesReturnSubDTO> lSalesReturnSubDTO = new List<SalesReturnSubDTO>(); try { int rowNo = 0; int totalRows = 0; DataTable myDataTable = new DataTable(); guidSalesMain_Pk_Code = Guid.NewGuid(); oSalesReturnMainDTO.PrimaryKey = guidSalesMain_Pk_Code; if ((this.hfMemberPK.Value.ToString()) == "") { oSalesReturnMainDTO.Cust_PK =new Guid("00000000-0000-0000-0000-000000000000") ; } else oSalesReturnMainDTO.Cust_PK = new Guid(this.hfMemberPK.Value.ToString());; // for update Sales Main Primary Key in Data Table // for using relation in Sales Main & Sub Table. this.hfMemberPK.Value = guidSalesMain_Pk_Code.ToString(); oSalesReturnMainDTO.InvoiceDate = this.txtInvoiceDate.Text == string.Empty ? "" : Convert.ToString(this.txtInvoiceDate.Text); oSalesReturnMainDTO.InvoiceNo = this.txtInvoiceNo.Text == string.Empty ? "" : Convert.ToString(this.txtInvoiceNo.Text); if (this.txtReturnAmount.Text.Length != 0) oSalesReturnMainDTO.ReturnAmount = (Decimal)TypeDescriptor.GetConverter(oSalesReturnMainDTO.ReturnAmount).ConvertFromString(this.txtReturnAmount.Text); else oSalesReturnMainDTO.ReturnAmount = 0; oSalesReturnMainDTO.ReturnMode = this.ddlReturnMode.Text; oSalesReturnMainDTO.Remarks = this.txtRemarks.Text; oSalesReturnMainDTO.Bo_PK = Get_Booth_PK(); oSalesReturnMainDTO.TotalReturnAmount = (Decimal)TypeDescriptor.GetConverter(oSalesReturnMainDTO.TotalReturnAmount).ConvertFromString(this.txtTotalAmount.Text); //================================Get Data From Table/GridView for SalesSub===================== myDataTable = ((DataTable)Session["myDatatable"]); totalRows = myDataTable.Rows.Count; for (rowNo = 0; rowNo < totalRows; rowNo++) { // call SetSalesSubInfoDTO method for // set up in Sales Sub Domin all information from Data Table SalesReturnSubDTO oSalesReturnSubDTO = SetSalesReturnSubDTO(rowNo, guidSalesMain_Pk_Code, myDataTable); // Add one by one Sales Sub Information in List lSalesReturnSubDTO.Add(oSalesReturnSubDTO); } // oSalesReturnMainDTO.SalesReturnSubDTO = lSalesReturnSubDTO; oSalesReturnMainDTO.EntryBy = User.Identity.Name; //==================================================================================== } catch (Exception Exp) { lblErrorMessage.Text = cls.ErrorString(Exp); } return oSalesReturnMainDTO; } /// <summary> /// set up sales sub information from the date table /// </summary> /// <param name="rowNo"></param> /// <param name="guidSM"></param> /// <param name="myDataTable"></param> /// <returns>SalesSubInfoDTO</returns> protected SalesReturnSubDTO SetSalesReturnSubDTO(int rowNo, Guid guidSM, DataTable myDataTable) { //dto.Sal_Pk = guidSalesMain_Pk_Code; SalesReturnSubDTO dto = new SalesReturnSubDTO(); dto.SALRM_PK = guidSM; dto.P_PK = (Guid)myDataTable.Rows[rowNo][8]; dto.SalesQuantity = Decimal.Parse(myDataTable.Rows[rowNo][2].ToString()); dto.SalesRate = Decimal.Parse(myDataTable.Rows[rowNo][3].ToString()); dto.VatAmount = Decimal.Parse(myDataTable.Rows[rowNo][4].ToString()); dto.TaxAmount = Decimal.Parse(myDataTable.Rows[rowNo][5].ToString()); dto.Discount = Decimal.Parse(myDataTable.Rows[rowNo][6].ToString()); dto.TotalAmount = Decimal.Parse(myDataTable.Rows[rowNo][7].ToString()); dto.EntryBy = User.Identity.Name; dto.EntryDate = DateTime.Now.Date; return dto; } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { } /// <summary> /// Fill Text Box Corresponding the Customer Code. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnClickMemberID_Click(object sender, EventArgs e) { try { long lCustID = 0; string strCustID = ""; MemberInfoDTO dto = new MemberInfoDTO(); Facade facade = Facade.GetInstance(); // member id keep in local variable for cust format lCustID = long.Parse(this.txtCustomerId.Text); // format in member ID strCustID = lCustID.ToString("000000"); // Get the Member Information Corresponding member code and keep Member Info Domain Object dto = facade.getMemberInfo(facade.getMemberPKInfoByCode(strCustID)); // set up the member primary code in local declared Hidden field this.hfMemberPK.Value = dto.PrimaryKey.ToString(); if (this.hfMemberPK.Value != "00000000-0000-0000-0000-000000000000") { this.lblErrorMessage.Text = ""; pnlMember.Visible = true; } else { pnlMember.Visible = false; this.txtCustomerId.Text = ""; this.lblErrorMessage.Text = "Member Not Available. Please Insert Correct Member ID."; return; } this.txtCustomerId.Text = dto.CustId; this.txtCustomerName.Text = dto.CustName; this.txtAddress.Text = dto.CustAddr; this.txtDepositBalance.Text = dto.CreditLimit.ToString(); this.txtProduct.Focus(); } catch (Exception Exp) { lblErrorMessage.Text = cls.ErrorString(Exp); } finally { ScriptManager1.SetFocus(txtProduct); } } protected void btnClickProduct_ddl_Click(object sender, EventArgs e) { this.ProductCode_click(); this.ddlProductName.SelectedValue = ""; } protected void ProductCode_click() { try { if ((this.lblErrorMessage.Text.Length != 0) || (this.lblSuccessMessage.Text.Length != 0)) { this.lblSuccessMessage.Text = ""; this.lblErrorMessage.Text = ""; } // Create the Product Info Domain Instance ProductInfoDTO dto = new ProductInfoDTO(); // Create the facade Instance Facade facade = Facade.GetInstance(); // Get the Product Info Corresponding Primary key or Product Code and keep those information if (this.txtProduct.Text.Length != 0) { dto = facade.GetProductInfoDTO((Guid)(facade.getProductPKInfoByCode((string)(this.txtProduct.Text)))); } else { dto = facade.GetProductInfoDTO((Guid)TypeDescriptor.GetConverter(dto.PrimaryKey).ConvertFromString(this.ddlProductName.SelectedValue)); } // keep the product Product primary key(GUID) in Local Hidden Field //for use insert in temporary table this.hfP_PK.Value = dto.PrimaryKey.ToString(); //set up product information in domain properties if (this.hfP_PK.Value != "00000000-0000-0000-0000-000000000000") { this.txtProduct.Text = dto.P_Code; this.txtProductName.Text = dto.P_Name; this.txtRate.Text = dto.P_SalesPrice.ToString(); this.hfVat.Value = dto.P_VAT.ToString(); this.hfTax.Value = dto.P_Tax.ToString(); this.txtDiscount.Text = dto.P_Discount.ToString(); // default Quantity has 1 this.txtQuantity.Text = "1"; this.txtQuantity.Focus(); // set focus in Quantity Text Field ScriptManager1.SetFocus(txtQuantity); } else { this.lblErrorMessage.Text = "Product Not Available. Please Insert Correct Product ID."; this.txtProduct.Text = ""; this.txtProductName.Text = ""; this.txtRate.Text = ""; this.hfVat.Value = ""; this.hfTax.Value = ""; this.hfVat.Value = ""; this.hfTax.Value = ""; this.txtDiscount.Text = ""; this.txtQuantity.Text = "0"; this.txtProduct.Focus(); ScriptManager1.SetFocus(txtProduct); return; } } catch (Exception Exp) { lblErrorMessage.Text = cls.ErrorString(Exp); } finally { } } protected void Invoice_Click() { try { string lInvoiceNo = this.txtInvoiceNo.Text; //string strCustID = ""; SalesMainInfoDTO dto = new SalesMainInfoDTO(); SalesReturnMainDTO reDto = new SalesReturnMainDTO(); Facade facade = Facade.GetInstance(); reDto = facade.GetSalesReturnInfoDTO(lInvoiceNo); // set up the InvoiceNo primary code in local declared Hidden field this.hfInvoiceNo.Value = reDto.SalesMainInfoDTO.PrimaryKey.ToString(); if (this.hfInvoiceNo.Value != "00000000-0000-0000-0000-000000000000") { this.lblErrorMessage.Text = ""; pnlMember.Visible = true; pnlInvoiceDate.Visible = true; } else { pnlMember.Visible = false; this.txtInvoiceNo.Text = ""; this.lblErrorMessage.Text = "Sales Not Available. Please Insert Correct Invoice No."; return; } this.hfMemberPK.Value = reDto.MemberInfoDTO.PrimaryKey.ToString(); this.txtInvoiceDate.Text = Convert.ToString(reDto.SalesMainInfoDTO.DeliveryDate); this.txtCustomerId.Text = reDto.MemberInfoDTO.CustId; this.txtCustomerName.Text = reDto.MemberInfoDTO.CustName; this.txtAddress.Text = reDto.MemberInfoDTO.CustAddr; this.txtDepositBalance.Text = reDto.MemberInfoDTO.CreditLimit.ToString(); //this.GridView1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView; //this.GridView1.DataBind(); this.txtInvoiceNo.Focus(); } catch (Exception Exp) { lblErrorMessage.Text = cls.ErrorString(Exp); } finally { ScriptManager1.SetFocus(txtProduct); } } protected void btnInvoice_Click(object sender, EventArgs e) { this.Invoice_Click(); } protected void btnClickProductCode_Click(object sender, EventArgs e) { if (this.txtInvoiceNo.Text.Length != 13) { this.Invoice_Click(); } else { this.ProductCode_click(); } } }
#nullable enable using System.Collections.Generic; using System.IO; using System.Linq; using Content.Client.UserInterface.Stylesheets; using Newtonsoft.Json; using Robust.Client.Credits; using Robust.Client.Interfaces.ResourceManagement; using Robust.Client.UserInterface; using Robust.Client.UserInterface.Controls; using Robust.Client.UserInterface.CustomControls; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Maths; using Robust.Shared.Utility; namespace Content.Client.UserInterface { public sealed class CreditsWindow : SS14Window { [Dependency] private readonly IResourceCache _resourceManager = default!; private static readonly Dictionary<string, int> PatronTierPriority = new Dictionary<string, int> { ["Nuclear Operative"] = 1, ["Syndicate Agent"] = 2, ["Revolutionary"] = 3 }; public CreditsWindow() { IoCManager.InjectDependencies(this); Title = Loc.GetString("Credits"); var rootContainer = new TabContainer(); var patronsList = new ScrollContainer(); var ss14ContributorsList = new ScrollContainer(); var licensesList = new ScrollContainer(); rootContainer.AddChild(ss14ContributorsList); rootContainer.AddChild(patronsList); rootContainer.AddChild(licensesList); TabContainer.SetTabTitle(patronsList, Loc.GetString("Patrons")); TabContainer.SetTabTitle(ss14ContributorsList, Loc.GetString("Credits")); TabContainer.SetTabTitle(licensesList, Loc.GetString("Open Source Licenses")); PopulatePatronsList(patronsList); PopulateCredits(ss14ContributorsList); PopulateLicenses(licensesList); Contents.AddChild(rootContainer); CustomMinimumSize = (650, 450); } private void PopulateLicenses(ScrollContainer licensesList) { var margin = new MarginContainer {MarginLeftOverride = 2, MarginTopOverride = 2}; var vBox = new VBoxContainer(); margin.AddChild(vBox); foreach (var entry in CreditsManager.GetLicenses().OrderBy(p => p.Name)) { vBox.AddChild(new Label {StyleClasses = {StyleBase.StyleClassLabelHeading}, Text = entry.Name}); // We split these line by line because otherwise // the LGPL causes Clyde to go out of bounds in the rendering code. foreach (var line in entry.License.Split("\n")) { vBox.AddChild(new Label {Text = line, FontColorOverride = new Color(200, 200, 200)}); } } licensesList.AddChild(margin); } private void PopulatePatronsList(Control patronsList) { var margin = new MarginContainer {MarginLeftOverride = 2, MarginTopOverride = 2}; var vBox = new VBoxContainer(); margin.AddChild(vBox); var patrons = ReadJson<PatronEntry[]>("/Credits/Patrons.json"); Button patronButton; vBox.AddChild(patronButton = new Button { Text = "Become a Patron", SizeFlagsHorizontal = SizeFlags.ShrinkCenter }); var first = true; foreach (var tier in patrons.GroupBy(p => p.Tier).OrderBy(p => PatronTierPriority[p.Key])) { if (!first) { vBox.AddChild(new Control {CustomMinimumSize = (0, 10)}); } first = false; vBox.AddChild(new Label {StyleClasses = {StyleBase.StyleClassLabelHeading}, Text = $"{tier.Key}"}); var msg = string.Join(", ", tier.OrderBy(p => p.Name).Select(p => p.Name)); var label = new RichTextLabel(); label.SetMessage(msg); vBox.AddChild(label); } patronButton.OnPressed += _ => IoCManager.Resolve<IUriOpener>().OpenUri(UILinks.Patreon); patronsList.AddChild(margin); } private void PopulateCredits(Control contributorsList) { Button contributeButton; var margin = new MarginContainer { MarginLeftOverride = 2, MarginTopOverride = 2 }; var vBox = new VBoxContainer(); margin.AddChild(vBox); vBox.AddChild(new HBoxContainer { SizeFlagsHorizontal = SizeFlags.ShrinkCenter, SeparationOverride = 20, Children = { new Label {Text = "Want to get on this list?"}, (contributeButton = new Button {Text = "Contribute!"}) } }); var first = true; void AddSection(string title, string path, bool markup = false) { if (!first) { vBox.AddChild(new Control {CustomMinimumSize = (0, 10)}); } first = false; vBox.AddChild(new Label {StyleClasses = {StyleBase.StyleClassLabelHeading}, Text = title}); var label = new RichTextLabel(); var text = _resourceManager.ContentFileReadAllText($"/Credits/{path}"); if (markup) { label.SetMessage(FormattedMessage.FromMarkup(text.Trim())); } else { label.SetMessage(text); } vBox.AddChild(label); } AddSection("Space Station 14 Contributors", "GitHub.txt"); AddSection("Space Station 13 Codebases", "SpaceStation13.txt"); AddSection("Original Space Station 13 Remake Team", "OriginalRemake.txt"); AddSection("Special Thanks", "SpecialThanks.txt", true); contributorsList.AddChild(margin); contributeButton.OnPressed += _ => IoCManager.Resolve<IUriOpener>().OpenUri(UILinks.GitHub); } private static IEnumerable<string> Lines(TextReader reader) { while (true) { var line = reader.ReadLine(); if (line == null) { yield break; } yield return line; } } private T ReadJson<T>(string path) { var serializer = new JsonSerializer(); using var stream = _resourceManager.ContentFileRead(path); using var streamReader = new StreamReader(stream); using var jsonTextReader = new JsonTextReader(streamReader); return serializer.Deserialize<T>(jsonTextReader)!; } [JsonObject(ItemRequired = Required.Always)] private sealed class PatronEntry { public string Name { get; set; } = default!; public string Tier { get; set; } = default!; } [JsonObject(ItemRequired = Required.Always)] private sealed class OpenSourceLicense { public string Name { get; set; } = default!; public string License { get; set; } = default!; } } }
// <copyright file="StudentCode.cs" company="Pioneers in Engineering"> // Licensed to Pioneers in Engineering under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Pioneers in Engineering 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. // </copyright> namespace StudentPiER { using System; using PiE.HAL.GHIElectronics.NETMF.FEZ; using PiE.HAL.GHIElectronics.NETMF.Hardware; using PiE.HAL.Microsoft.SPOT; using PiE.HAL.Microsoft.SPOT.Hardware; using PiEAPI; /// <summary> /// Student Code template /// </summary> public class StudentCode : RobotCode { /// <summary> /// This is your robot /// </summary> private Robot robot; /// <summary> /// This stopwatch measures time, in seconds /// </summary> private Stopwatch stopwatch; /// <summary> /// The right drive motor, on connector M0 /// </summary> private GrizzlyBear rightMotor; /// <summary> /// The left drive motor, on connector M1 /// </summary> private GrizzlyBear leftMotor; /// <summary> /// The sonar sensor on connector A5 /// </summary> private AnalogSonarDistanceSensor sonar; /// <summary> /// The motor controlling the position of the hopper, on connector M2 /// </summary> private GrizzlyBear hopperMotor; /// <summary> /// The motor controlling the converyor belt for the pick-up mechanism, on connector M3 /// </summary> private GrizzlyBear conveyorBeltMotor; /// <summary> /// A flag to toggle RFID usage in the code /// </summary> private bool useRfid; /// <summary> /// The rfid sensor /// </summary> private Rfid rfid; /// <summary> /// This is your I2CEncoder /// </summary> private GrizzlyEncoder leftEncoder; private GrizzlyEncoder rightEncoder; /// <summary> /// Step to use with the ^^ encoder /// </summary> private float Step = 0.0125f; /// <summary> /// The limit switch for testing if the hopper is open, on connector D1 /// </summary> private DigitalLimitSwitch servoSwitch; /// <summary> /// The limit switch for testing if the hopper is closed, on connector D2 /// </summary> private DigitalLimitSwitch autonomousSwitch; /// <summary> /// Create a new MicroMaestro and servos /// </summary> private MicroMaestro mm; private ServoMotor servo0; //For autonomous private Boolean StartTime; //for hopper delay //private Boolean dump; //private Boolean notDump; //For stage 3 autonomous //private int n; /// <summary> /// Initializes a new instance of the /// <see cref="StudentPiER.StudentCode"/> class. /// </summary> /// <param name='robot'> /// The Robot to associate with this StudentCode /// </param> public StudentCode(Robot robot) { this.robot = robot; this.stopwatch = new Stopwatch(); this.stopwatch.Start(); this.useRfid = false; /*if (this.useRfid) { this.rfid = new Rfid(robot); }*/ this.leftMotor = new GrizzlyBear(robot, Watson.Motor.M0); this.rightMotor = new GrizzlyBear(robot, Watson.Motor.M1); this.conveyorBeltMotor = new GrizzlyBear(robot, Watson.Motor.M3); this.hopperMotor = new GrizzlyBear(robot, Watson.Motor.M2); this.sonar = new AnalogSonarDistanceSensor(robot, Watson.Analog.A5); this.leftEncoder = new GrizzlyEncoder(Step, this.leftMotor, this.robot); this.rightEncoder = new GrizzlyEncoder(Step, this.rightMotor, this.robot); this.servoSwitch = new DigitalLimitSwitch(robot, Watson.Digital.D1); this.autonomousSwitch = new DigitalLimitSwitch(robot, Watson.Digital.D3); this.StartTime = true; this.mm = new MicroMaestro(robot, 12); this.servo0 = new ServoMotor(robot, mm, 0, 500, 2000); //this.dump = true; //this.notDump = false; //this.n = 0; } /// <summary> /// Main method which initializes the robot, and starts /// it running. Do not modify. /// </summary> public static void Main() { // Initialize robot Robot robot = new Robot("1", "COM4"); Debug.Print("Code loaded successfully!"); Supervisor supervisor = new Supervisor(new StudentCode(robot)); supervisor.RunCode(); } /// <summary> /// The Robot to use. /// </summary> /// <returns> /// Robot associated with this StudentCode. /// </returns> public Robot GetRobot() { return this.robot; } /// <summary> /// The robot will call this method every time it needs to run the /// user-controlled student code /// The StudentCode should basically treat this as a chance to read all the /// new PiEMOS analog/digital values and then use them to update the /// actuator states /// </summary> public void SpeedAdjust() { double timeStart = this.stopwatch.ElapsedTime; float startRightDisplacement = this.rightEncoder.Displacement; float startLeftDisplacement = this.leftEncoder.Displacement; double time = stopwatch.ElapsedTime; float leftWheelSpeed = this.leftEncoder.Displacement / (float)stopwatch.ElapsedTime; float rightWheelSpeed = this.rightEncoder.Displacement / (float)stopwatch.ElapsedTime; float SpeedRatio = leftWheelSpeed / rightWheelSpeed; } /// <summary> /// Determines throttle value based on the activation of precision mode /// </summary> /// <param name="baseThrottle">The input value from the controller. The analog value of the left and right sticks.</param> /// <param name="slow">Whether slow mode is initiated or not</param> /// <param name="deadpan">The margin for error in the released throttle</param> /// <returns>The adjusted throttle value</returns> /// Not being used public int GetTrueThrottle(int baseThrottle, Boolean slow, int deadpan) { if (slow) { return baseThrottle; } if (baseThrottle > deadpan) { return ((int)(baseThrottle * 0.4) + 40); } if (baseThrottle < -1 * deadpan) { return ((int)(baseThrottle * 0.4) - 40); } else { return 0; } } /// <summary> /// Uses the position of the hopper to determine the speed at which the motor should rotate when the driver elects to move the door /// </summary> /// <returns>A value of throttle for the hopper motor</returns> public int getTrueHopperThrottle() { //Open hopper - Press once to open RightThumbB, press again to close if (this.robot.PiEMOSDigitalVals[7] == true) { //this.dump = this.notDump; return -20; } else { //this.notDump = this.dump; return 60; } } public void TeleoperatedCode() { //Turn on/off slow mode - Press Left Stick this.rightMotor.Throttle = GetTrueThrottle(this.robot.PiEMOSAnalogVals[1], this.robot.PiEMOSDigitalVals[6], 5); this.leftMotor.Throttle = -1 * GetTrueThrottle(this.robot.PiEMOSAnalogVals[3], this.robot.PiEMOSDigitalVals[6], 5); //key bindings for wheel throttle //RightMotor - Right Stick y-axis //LeftMotor - Right Stick x-axis this.robot.FeedbackAnalogVals[0] = this.rightMotor.Throttle; this.robot.FeedbackAnalogVals[1] = this.leftMotor.Throttle; //Turn on conveyor belt - Press and Hold Left Trigger this.conveyorBeltMotor.Throttle = this.robot.PiEMOSAnalogVals[5] + -1 * this.robot.PiEMOSAnalogVals[4]; //Open hopper - Press once to open RightThumbB, press again to close this.hopperMotor.Throttle = getTrueHopperThrottle(); //Start Flashing Dispensor and compare release code - Press and Hold RB /*if (this.robot.PiEMOSDigitalVals[5] == true) { this.useRfid = true; if (this.useRfid && (this.rfid.LastItemScanned != null)) { FieldItem last = this.rfid.LastItemScanned; int groupTypeLast = last.GroupType; this.robot.SendConsoleMessage("Scanned"); if (groupTypeLast == 3 || groupTypeLast == 4) { this.robot.StartFlashingDispenser(last); this.robot.SendConsoleMessage("Flashing"); if (this.robot.PiEMOSDigitalVals[4] == true) { this.robot.SendReleaseCode(last); this.robot.SendConsoleMessage("Releasing"); } } else { } } } else { this.useRfid = false; }*/ /*this.useRfid = true; this.robot.SendConsoleMessage("Test"); this.robot.SendConsoleMessage("Last item scanned type: " + this.rfid.LastItemScanned.GroupType.ToString()); //Check if lastItemScanned was a false release code int groupType = this.rfid.LastItemScanned.GroupType; //Make sure that releasing the code will not disable robot if (this.rfid.LastItemScanned.GroupType != PiEAPI.FieldItem.FalseReleaseCode && this.rfid.LastItemScanned != null) { this.robot.SendConsoleMessage("Test 2"); //Find which dispenser this release code corresponds to this.robot.StartFlashingDispenser(this.rfid.LastItemScanned); //this.robot.SendConsoleMessage(this.rfid.LastItemScanned.ToString()); //Release code - Press and Hold Left Bumper while holding RB if (this.robot.FeedbackDigitalVals[4] == true) { this.robot.SendConsoleMessage("test 3"); this.robot.SendReleaseCode(this.rfid.LastItemScanned); this.robot.SendConsoleMessage("Code releasing"); this.robot.StopFlashingDispenser(this.rfid.LastItemScanned); } } }*/ //Turn on servo - Press and Hold Right Bumper /*this.servo0.TargetRotation = this.robot.FeedbackAnalogVals[4]; if (this.robot.PiEMOSDigitalVals[1] == true && this.servo0.TargetRotation == 0) { this.servo0.TargetRotation = 50; //this.servo0.AngularSpeed = 0; //this.robot.SendConsoleMessage(this.servo0.TargetRotation.ToString()); this.servo0.Write(); } else if (this.robot.PiEMOSDigitalVals[1] == false && this.servo0.TargetRotation == 50) { this.servo0.TargetRotation = 0; //this.servo0.AngularSpeed = 0; //this.robot.SendConsoleMessage(this.servo0.TargetRotation.ToString()); this.servo0.Write(); } else if (this.robot.PiEMOSDigitalVals[1] == true && (this.servo0.TargetRotation != 0 && this.servo0.TargetRotation != 90)) { this.servo0.TargetRotation = 0; //this.servo0.AngularSpeed = 0; this.robot.SendConsoleMessage(this.servo0.TargetRotation.ToString()); //this.servo0.Write(); }*/ /*//Tank Mode - Press Right Stick if (this.robot.PiEMOSDigitalVals[7] == false) { this.rightMotor.Throttle = this.robot.PiEMOSAnalogVals[1]; this.leftMotor.Throttle = this.robot.PiEMOSAnalogVals[3]; this.robot.FeedbackAnalogVals[0] = this.rightMotor.Throttle; this.robot.FeedbackAnalogVals[1] = this.leftMotor.Throttle; } //Arcade Mode - Press Right Stick if (this.robot.PiEMOSDigitalVals[7] == true) { this.rightMotor.Throttle = (this.robot.PiEMOSAnalogVals[3] - this.robot.PiEMOSAnalogVals[0]); this.leftMotor.Throttle = (this.robot.PiEMOSAnalogVals[3] + this.robot.PiEMOSAnalogVals[0]); } if (this.robot.PiEMOSDigitalVals[7] == true) { this.rightMotor.Throttle = (this.robot.PiEMOSAnalogVals[3] - this.robot.PiEMOSAnalogVals[0]); this.leftMotor.Throttle = (this.robot.PiEMOSAnalogVals[3] + this.robot.PiEMOSAnalogVals[0]); }*/ } /// <summary> /// The robot will call this method every time it needs to run the /// autonomous student code /// The StudentCode should basically treat this as a chance to change motorsw /// and servos based on non user-controlled input like sensors. But you /// don't need sensors, as this example demonstrates. /// </summary> public void AutonomousCode() { Debug.Print("Autonomous"); //this.robot.SendConsoleMessage(n.ToString());// float leftDisplacement = this.leftEncoder.Displacement; float rightDisplacement = this.rightEncoder.Displacement; float TotalDisplacement = Math.Abs((int)this.leftEncoder.Displacement) + Math.Abs((int)this.rightEncoder.Displacement); this.rightMotor.Throttle = GetTrueThrottle(this.robot.PiEMOSAnalogVals[1], this.robot.PiEMOSDigitalVals[6], 5); this.leftMotor.Throttle = -1 * GetTrueThrottle(this.robot.PiEMOSAnalogVals[3], this.robot.PiEMOSDigitalVals[6], 5); this.robot.SendConsoleMessage("TotalDisplacement = " + (Math.Abs((int)this.leftEncoder.Displacement) + Math.Abs((int)this.rightEncoder.Displacement))); //this.hopperMotor.Throttle = 60; //stage 3 autonomous - getting ball into goal /*switch (n) { case 0: this.robot.SendConsoleMessage("reached 0"); if (TotalDisplacement < 600.0) { this.robot.SendConsoleMessage("Forward"); this.rightMotor.Throttle = -100; this.leftMotor.Throttle = 100; } else { n = 1; } break; case 1: this.robot.SendConsoleMessage("reached 1"); if (TotalDisplacement < 1400.0) { this.robot.SendConsoleMessage("veer Left"); this.rightMotor.Throttle = 100; this.leftMotor.Throttle = 95; } else { n = 2; } break; case 2: this.robot.SendConsoleMessage("reached 2"); if (TotalDisplacement < 2000.0) { this.robot.SendConsoleMessage("Turn"); this.rightMotor.Throttle = 100; this.leftMotor.Throttle = 0; } break; case 3: this.robot.SendConsoleMessage("reached 2"); if (TotalDisplacement < 1600.0) { this.robot.SendConsoleMessage("Staigheten"); this.rightMotor.Throttle = 100; this.leftMotor.Throttle = -100; } else { n = 3; } break; case 4: this.robot.SendConsoleMessage("reached 3"); if (TotalDisplacement < 2300.0) { this.robot.SendConsoleMessage("Forward"); this.rightMotor.Throttle = -100; this.leftMotor.Throttle = 100; } else { n = 4; } break; default: this.robot.SendConsoleMessage("reached default"); this.rightMotor.Throttle = 0; this.leftMotor.Throttle = 0; break; }*/ //move forward initially /*if (TotalDisplacement < 20.0) { this.hopperMotor.Throttle = -20; this.robot.SendConsoleMessage("Forward"); this.rightMotor.Throttle = -100; this.leftMotor.Throttle = 100; } //turn left (to face the goal) else if (TotalDisplacement < 25.0) { this.robot.SendConsoleMessage("Turn Left"); this.rightMotor.Throttle = 100; this.leftMotor.Throttle = 95; } //straighten against wall else if (TotalDisplacement < 29.3) { this.robot.SendConsoleMessage("Backwards"); this.rightMotor.Throttle = 100; this.leftMotor.Throttle = -100; } //move forward (get to goal else if (TotalDisplacement < 60.0) { this.robot.SendConsoleMessage("Forward 2"); this.rightMotor.Throttle = -100; this.leftMotor.Throttle = 100; } //stop when reached location else { this.conveyorBeltMotor.Throttle = 100; this.rightMotor.Throttle = 0; this.leftMotor.Throttle = 0; }*/ //Stage 2 autonomous - getting ball over wall if (this.autonomousSwitch.IsPressed == true) { //veers to right if (StartTime) { this.stopwatch.Start(); StartTime = false; } this.robot.SendConsoleMessage(this.stopwatch.ElapsedTime.ToString()); this.rightMotor.Throttle = -100; this.leftMotor.Throttle = 85; this.hopperMotor.Throttle = -20; if (this.stopwatch.ElapsedTime >= 5.0) { this.conveyorBeltMotor.Throttle = 100; } } if (this.autonomousSwitch.IsPressed == false) { //veers to left if (StartTime) { this.stopwatch.Start(); StartTime = false; } this.robot.SendConsoleMessage(this.stopwatch.ElapsedTime.ToString()); this.rightMotor.Throttle = -78; this.leftMotor.Throttle = 100; this.hopperMotor.Throttle = -20; if (this.stopwatch.ElapsedTime >= 5.0) { this.conveyorBeltMotor.Throttle = 100; } } } /// <summary> /// The robot will call this method periodically while it is disabled /// during the autonomous period. Actuators will not be updated during /// this time. /// </summary> public void DisabledAutonomousCode() { this.stopwatch.Reset(); // Restart stopwatch before start of autonomous //reset encoder displacement values this.leftEncoder.Displacement = 0; this.rightEncoder.Displacement = 0; this.rightMotor.Throttle = GetTrueThrottle(this.robot.PiEMOSAnalogVals[1], this.robot.PiEMOSDigitalVals[6], 5); this.leftMotor.Throttle = -1 * GetTrueThrottle(this.robot.PiEMOSAnalogVals[3], this.robot.PiEMOSDigitalVals[6], 5); this.stopwatch.Reset(); this.StartTime = true; } /// <summary> /// The robot will call this method periodically while it is disabled /// during the user controlled period. Actuators will not be updated /// during this time. /// </summary> public void DisabledTeleoperatedCode() { this.stopwatch.Reset(); } /// <summary> /// This is called whenever the supervisor disables studentcode. /// </summary> public void WatchdogReset() { } /// <summary> /// Send the GroupType of a FieldItem object to PiEMOS. /// Populates two indices of FeedbackDigitalVals. /// </summary> /// <param name="item">the FieldItem to send infotmaion about</param> /// <param name="index1">first index to use</param> /// <param name="index2">second index to use</param> private void ReportFieldItemType(FieldItem item, int index1 = 6, int index2 = 7) { bool feedback1; bool feedback2; if (item == null) { feedback1 = false; feedback2 = false; } else if (item.GroupType == FieldItem.PlusOneBox) { feedback1 = true; feedback2 = false; } else if (item.GroupType == FieldItem.TimesTwoBox) { feedback1 = true; feedback2 = true; } else { feedback1 = false; feedback2 = true; } this.robot.FeedbackDigitalVals[index1] = feedback1; this.robot.FeedbackDigitalVals[index2] = feedback2; } } }
using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using System.Web.Routing; using Orchard.Forms.Services; using Orchard.Rules.Models; using Orchard.Rules.Services; using Orchard.Rules.ViewModels; using Orchard.ContentManagement; using Orchard.Core.Contents.Controllers; using Orchard.Data; using Orchard.DisplayManagement; using Orchard.Localization; using Orchard.Security; using Orchard.UI.Notify; using System; using Orchard.Settings; using Orchard.UI.Navigation; namespace Orchard.Rules.Controllers { [ValidateInput(false)] public class AdminController : Controller, IUpdateModel { private readonly ISiteService _siteService; private readonly IRulesManager _rulesManager; private readonly IRulesServices _rulesServices; public AdminController( IOrchardServices services, IShapeFactory shapeFactory, ISiteService siteService, IRulesManager rulesManager, IRulesServices rulesServices, IRepository<RuleRecord> repository) { _siteService = siteService; _rulesManager = rulesManager; _rulesServices = rulesServices; Services = services; T = NullLocalizer.Instance; Shape = shapeFactory; } dynamic Shape { get; set; } public IOrchardServices Services { get; set; } public Localizer T { get; set; } public ActionResult Index(RulesIndexOptions options, PagerParameters pagerParameters) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to list rules"))) return new HttpUnauthorizedResult(); var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters); // default options if (options == null) options = new RulesIndexOptions(); var rules = _rulesServices.GetRules(); switch (options.Filter) { case RulesFilter.Disabled: rules = rules.Where(r => r.Enabled == false); break; case RulesFilter.Enabled: rules = rules.Where(u => u.Enabled); break; } if (!String.IsNullOrWhiteSpace(options.Search)) { rules = rules.Where(r => r.Name.Contains(options.Search)); } var pagerShape = Shape.Pager(pager).TotalItemCount(rules.Count()); switch (options.Order) { case RulesOrder.Name: rules = rules.OrderBy(u => u.Name); break; } var results = rules .Skip(pager.GetStartIndex()) .Take(pager.PageSize) .ToList(); var model = new RulesIndexViewModel { Rules = results.Select(x => new RulesEntry { Rule = x, IsChecked = false, RuleId = x.Id }).ToList(), Options = options, Pager = pagerShape }; // maintain previous route data when generating page links var routeData = new RouteData(); routeData.Values.Add("Options.Filter", options.Filter); routeData.Values.Add("Options.Search", options.Search); routeData.Values.Add("Options.Order", options.Order); pagerShape.RouteData(routeData); return View(model); } [HttpPost] [FormValueRequired("submit.BulkEdit")] public ActionResult Index(FormCollection input) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage rules"))) return new HttpUnauthorizedResult(); var viewModel = new RulesIndexViewModel { Rules = new List<RulesEntry>(), Options = new RulesIndexOptions() }; UpdateModel(viewModel); var checkedEntries = viewModel.Rules.Where(c => c.IsChecked); switch (viewModel.Options.BulkAction) { case RulesBulkAction.None: break; case RulesBulkAction.Enable: foreach (var entry in checkedEntries) { _rulesServices.GetRule(entry.RuleId).Enabled = true; } break; case RulesBulkAction.Disable: foreach (var entry in checkedEntries) { _rulesServices.GetRule(entry.RuleId).Enabled = false; } break; case RulesBulkAction.Delete: foreach (var entry in checkedEntries) { _rulesServices.DeleteRule(entry.RuleId); } break; } return RedirectToAction("Index"); } public ActionResult Move(string direction, int id, int actionId) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage rules"))) return new HttpUnauthorizedResult(); switch(direction) { case "up" : _rulesServices.MoveUp(actionId); break; case "down": _rulesServices.MoveDown(actionId); break; default: throw new ArgumentException("direction"); } return RedirectToAction("Edit", new { id }); } public ActionResult Create() { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage rules"))) return new HttpUnauthorizedResult(); return View(new CreateRuleViewModel()); } [HttpPost, ActionName("Create")] public ActionResult CreatePost(CreateRuleViewModel viewModel) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage rules"))) return new HttpUnauthorizedResult(); if (!ModelState.IsValid) { Services.TransactionManager.Cancel(); } else { var rule = _rulesServices.CreateRule(viewModel.Name); return RedirectToAction("Edit", new { id = rule.Id }); } return View(viewModel); } public ActionResult Edit(int id) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit rules"))) return new HttpUnauthorizedResult(); var rule = _rulesServices.GetRule(id); var viewModel = new EditRuleViewModel { Id = rule.Id, Enabled = rule.Enabled, Name = rule.Name }; #region Load events var eventEntries = new List<EventEntry>(); var allEvents = _rulesManager.DescribeEvents().SelectMany(x => x.Descriptors); foreach (var eventRecord in rule.Events) { var category = eventRecord.Category; var type = eventRecord.Type; var ev = allEvents.Where(x => category == x.Category && type == x.Type).FirstOrDefault(); if (ev != null) { var eventParameters = FormParametersHelper.FromString(eventRecord.Parameters); eventEntries.Add( new EventEntry { Category = ev.Category, Type = ev.Type, EventRecordId = eventRecord.Id, DisplayText = ev.Display(new EventContext { Properties = eventParameters }) }); } } viewModel.Events = eventEntries; #endregion #region Load actions var actionEntries = new List<ActionEntry>(); var allActions = _rulesManager.DescribeActions().SelectMany(x => x.Descriptors); foreach (var actionRecord in rule.Actions.OrderBy(x => x.Position)) { var category = actionRecord.Category; var type = actionRecord.Type; var action = allActions.Where(x => category == x.Category && type == x.Type).FirstOrDefault(); if (action != null) { var actionParameters = FormParametersHelper.FromString(actionRecord.Parameters); actionEntries.Add( new ActionEntry { Category = action.Category, Type = action.Type, ActionRecordId = actionRecord.Id, DisplayText = action.Display(new ActionContext { Properties = actionParameters }) }); } } viewModel.Actions = actionEntries; #endregion return View(viewModel); } [HttpPost, ActionName("Edit")] [FormValueRequired("submit.Save")] public ActionResult EditPost(EditRuleViewModel viewModel) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage rules"))) return new HttpUnauthorizedResult(); if (!ModelState.IsValid) { Services.TransactionManager.Cancel(); } else { var rule = _rulesServices.GetRule(viewModel.Id); rule.Name = viewModel.Name; rule.Enabled = viewModel.Enabled; Services.Notifier.Information(T("Rule Saved")); return RedirectToAction("Edit", new { id = rule.Id }); } return View(viewModel); } [HttpPost, ActionName("Edit")] [FormValueRequired("submit.SaveAndEnable")] public ActionResult EditAndEnablePost(EditRuleViewModel viewModel) { viewModel.Enabled = true; return EditPost(viewModel); } [HttpPost] public ActionResult Delete(int id) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage rules"))) return new HttpUnauthorizedResult(); var rule = _rulesServices.GetRule(id); if (rule != null) { _rulesServices.DeleteRule(id); Services.Notifier.Information(T("Rule {0} deleted", rule.Name)); } return RedirectToAction("Index"); } public ActionResult Enable(int id) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage rules"))) return new HttpUnauthorizedResult(); var rule = _rulesServices.GetRule(id); if (rule != null) { rule.Enabled = true; Services.Notifier.Information(T("Rule enabled")); } return RedirectToAction("Index"); } public ActionResult Disable(int id) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage rules"))) return new HttpUnauthorizedResult(); var rule = _rulesServices.GetRule(id); if (rule != null) { rule.Enabled = false; Services.Notifier.Information(T("Rule disabled")); } return RedirectToAction("Index"); } bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) { return TryUpdateModel(model, prefix, includeProperties, excludeProperties); } public void AddModelError(string key, LocalizedString errorMessage) { ModelState.AddModelError(key, errorMessage.ToString()); } } }
// 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.IO; using System.Xml; using System.Xml.Linq; using Microsoft.Test.ModuleCore; namespace CoreXml.Test.XLinq { public partial class FunctionalTests : TestModule { public partial class SDMSamplesTests : XLinqTestCase { public partial class SDM_Node : XLinqTestCase { /// <summary> /// Tests the Parent property on Node. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "NodeParent")] public void NodeParent() { // Only elements are returned as parents from the Parent property. // Documents are not returned. XDocument document = new XDocument(); XNode[] nodes = new XNode[] { new XComment("comment"), new XElement("element"), new XProcessingInstruction("target", "data"), new XDocumentType("name", "publicid", "systemid", "internalsubset") }; foreach (XNode node in nodes) { Validate.IsNull(node.Parent); document.Add(node); Validate.IsReferenceEqual(document, node.Document); // Parent element is null. Validate.IsNull(node.Parent); document.RemoveNodes(); } // Now test the cases where an element is the parent. nodes = new XNode[] { new XComment("abcd"), new XElement("nested"), new XProcessingInstruction("target2", "data2"), new XText("text") }; XElement root = new XElement("root"); document.ReplaceNodes(root); foreach (XNode node in nodes) { Validate.IsNull(node.Parent); root.AddFirst(node); Validate.IsReferenceEqual(node.Parent, root); root.RemoveNodes(); Validate.IsNull(node.Parent); } } /// <summary> /// Tests the ReadFrom static method on Node. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "NodeReadFrom")] public void NodeReadFrom() { // Null reader not allowed. try { XNode.ReadFrom(null); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } // Valid cases: cdata, comment, element string[] rawXml = new string[] { "text", "<![CDATA[abcd]]>", "<!-- comment -->", "<y>y</y>" }; Type[] types = new Type[] { typeof(XText), typeof(XCData), typeof(XComment), typeof(XElement) }; int count = rawXml.Length; for (int i = 0; i < count; i++) { using (StringReader stringReader = new StringReader("<x>" + rawXml[i] + "</x>")) { using (XmlReader reader = XmlReader.Create(stringReader)) { reader.Read(); // skip to <x> reader.Read(); // skip over <x> to the meat XNode node = XNode.ReadFrom(reader); // Ensure that the right kind of node got created. Validate.Type(node, types[i]); // Ensure that the value is right. Validate.IsEqual(rawXml[i], node.ToString(SaveOptions.DisableFormatting)); } } } // Also test a case that is not allowed. using (StringReader stringReader = new StringReader("<x y='abcd'/>")) { using (XmlReader reader = XmlReader.Create(stringReader)) { reader.Read(); reader.MoveToFirstAttribute(); try { XNode node = XNode.ReadFrom(reader); Validate.ExpectedThrow(typeof(InvalidOperationException)); } catch (Exception ex) { Validate.Catch(ex, typeof(InvalidOperationException)); } } } } /// <summary> /// Tests the AddAfterSelf/AddBeforeSelf/Remove method on Node, /// when there's no parent. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "NodeNoParentAddRemove")] public void NodeNoParentAddRemove() { // Not allowed if parent is null. int i = 0; while (true) { XNode node = null; switch (i++) { case 0: node = new XElement("x"); break; case 1: node = new XComment("c"); break; case 2: node = new XText("abc"); break; case 3: node = new XProcessingInstruction("target", "data"); break; default: i = -1; break; } if (i < 0) { break; } try { node.AddBeforeSelf("foo"); Validate.ExpectedThrow(typeof(InvalidOperationException)); } catch (Exception ex) { Validate.Catch(ex, typeof(InvalidOperationException)); } try { node.AddAfterSelf("foo"); Validate.ExpectedThrow(typeof(InvalidOperationException)); } catch (Exception ex) { Validate.Catch(ex, typeof(InvalidOperationException)); } try { node.Remove(); Validate.ExpectedThrow(typeof(InvalidOperationException)); } catch (Exception ex) { Validate.Catch(ex, typeof(InvalidOperationException)); } } } /// <summary> /// Tests AddAfterSelf on Node. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "NodeAddAfterSelf")] public void NodeAddAfterSelf() { XElement parent = new XElement("parent"); XElement child = new XElement("child"); parent.Add(child); XText sibling1 = new XText("sibling1"); XElement sibling2 = new XElement("sibling2"); XComment sibling3 = new XComment("sibling3"); child.AddAfterSelf(sibling1); Validate.EnumeratorDeepEquals(parent.Nodes(), new XNode[] { child, sibling1 }); child.AddAfterSelf(sibling2, sibling3); Validate.EnumeratorDeepEquals( parent.Nodes(), new XNode[] { child, sibling2, sibling3, sibling1 }); } /// <summary> /// Tests AddBeforeSelf on Node. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "NodeAddBeforeSelf")] public void NodeAddBeforeSelf() { XElement parent = new XElement("parent"); XElement child = new XElement("child"); parent.Add(child); XElement sibling1 = new XElement("sibling1"); XComment sibling2 = new XComment("sibling2"); XText sibling3 = new XText("sibling3"); child.AddBeforeSelf(sibling1); Validate.EnumeratorDeepEquals(parent.Nodes(), new XNode[] { sibling1, child }); child.AddBeforeSelf(sibling2, sibling3); Validate.EnumeratorDeepEquals( parent.Nodes(), new XNode[] { sibling1, sibling2, sibling3, child }); } /// <summary> /// Tests Remove on Node. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "NodeRemove")] public void NodeRemove() { XElement parent = new XElement("parent"); XComment child1 = new XComment("child1"); XText child2 = new XText("child2"); XElement child3 = new XElement("child3"); parent.Add(child1, child2, child3); // Sanity check Validate.EnumeratorDeepEquals(parent.Nodes(), new XNode[] { child1, child2, child3 }); // Remove the text. child1.NextNode.Remove(); Validate.EnumeratorDeepEquals(parent.Nodes(), new XNode[] { child1, child3 }); // Remove the XComment. child1.Remove(); Validate.EnumeratorDeepEquals(parent.Nodes(), new XNode[] { child3 }); // Remove the XElement. child3.Remove(); Validate.EnumeratorDeepEquals(parent.Nodes(), new XNode[] { }); } /// <summary> /// Tests the AllContentBeforeSelf method on Node. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "NodeAllContentBeforeSelf")] public void NodeAllContentBeforeSelf() { XElement parent = new XElement("parent"); XComment child = new XComment("Self is a comment"); XComment comment1 = new XComment("Another comment"); XComment comment2 = new XComment("Yet another comment"); XElement element1 = new XElement("childelement", new XElement("nested"), new XAttribute("foo", "bar")); XElement element2 = new XElement("childelement2", new XElement("nested"), new XAttribute("foo", "bar")); XAttribute attribute = new XAttribute("attribute", "value"); // If no parent, should not be any content before it. Validate.Enumerator<XNode>(child.NodesBeforeSelf(), new XNode[0]); // Add child to parent. Should still be no content before it. // Attributes are not content. parent.Add(attribute); parent.Add(child); Validate.Enumerator<XNode>(child.NodesBeforeSelf(), new XNode[0]); // Add more children and validate. parent.Add(comment1); parent.Add(element1); Validate.Enumerator<XNode>(child.NodesBeforeSelf(), new XNode[0]); parent.AddFirst(element2); parent.AddFirst(comment2); Validate.Enumerator<XNode>(child.NodesBeforeSelf(), new XNode[] { comment2, element2 }); } /// <summary> /// Tests the AllContentAfterSelf method on Node. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "NodeAllContentAfterSelf")] public void NodeAllContentAfterSelf() { XElement parent = new XElement("parent"); XComment child = new XComment("Self is a comment"); XComment comment1 = new XComment("Another comment"); XComment comment2 = new XComment("Yet another comment"); XElement element1 = new XElement("childelement", new XElement("nested"), new XAttribute("foo", "bar")); XElement element2 = new XElement("childelement2", new XElement("nested"), new XAttribute("foo", "bar")); XAttribute attribute = new XAttribute("attribute", "value"); // If no parent, should not be any content after it. Validate.Enumerator<XNode>(child.NodesAfterSelf(), new XNode[0]); // Add child to parent. Should still be no content after it. // Attributes are not content. parent.Add(child); parent.Add(attribute); Validate.Enumerator<XNode>(child.NodesAfterSelf(), new XNode[0]); // Add more children and validate. parent.AddFirst(comment1); parent.AddFirst(element1); Validate.Enumerator<XNode>(child.NodesAfterSelf(), new XNode[0]); parent.Add(element2); parent.Add(comment2); Validate.Enumerator<XNode>(child.NodesAfterSelf(), new XNode[] { element2, comment2 }); } /// <summary> /// Tests the ContentBeforeSelf method on Node. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "NodeContentBeforeSelf")] public void NodeContentBeforeSelf() { XElement parent = new XElement("parent"); XComment child = new XComment("Self is a comment"); XComment comment1 = new XComment("Another comment"); XComment comment2 = new XComment("Yet another comment"); XElement element1 = new XElement("childelement", new XElement("nested"), new XAttribute("foo", "bar")); XElement element2 = new XElement("childelement2", new XElement("nested"), new XAttribute("foo", "bar")); XAttribute attribute = new XAttribute("attribute", "value"); // If no parent, should not be any content before it. Validate.Enumerator(child.NodesBeforeSelf(), new XNode[0]); // Add some content, including the child, and validate. parent.Add(attribute); parent.Add(comment1); parent.Add(element1); parent.Add(child); parent.Add(comment2); parent.Add(element2); Validate.Enumerator( child.NodesBeforeSelf(), new XNode[] { comment1, element1 }); } /// <summary> /// Tests the ContentAfterSelf method on Node. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "NodeContentAfterSelf")] public void NodeContentAfterSelf() { XElement parent = new XElement("parent"); XComment child = new XComment("Self is a comment"); XComment comment1 = new XComment("Another comment"); XComment comment2 = new XComment("Yet another comment"); XElement element1 = new XElement("childelement", new XElement("nested"), new XAttribute("foo", "bar")); XElement element2 = new XElement("childelement2", new XElement("nested"), new XAttribute("foo", "bar")); XAttribute attribute = new XAttribute("attribute", "value"); // If no parent, should not be any content after it. Validate.Enumerator(child.NodesAfterSelf(), new XNode[0]); // Add some content, including the child, and validate. parent.Add(attribute); parent.Add(comment1); parent.Add(element1); parent.Add(child); parent.Add(comment2); parent.Add(element2); Validate.Enumerator(child.NodesAfterSelf(), new XNode[] { comment2, element2 }); } /// <summary> /// Tests the ElementsBeforeSelf methods on Node. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "NodeElementsBeforeSelf")] public void NodeElementsBeforeSelf() { XElement parent = new XElement("parent"); XElement child1a = new XElement("child1", new XElement("nested")); XElement child1b = new XElement("child1", new XElement("nested")); XElement child2a = new XElement("child2", new XElement("nested")); XElement child2b = new XElement("child2", new XElement("nested")); XComment comment = new XComment("this is a comment"); // If no parent, should not be any elements before it. Validate.Enumerator(comment.ElementsBeforeSelf(), new XElement[0]); parent.Add(child1a); parent.Add(child1b); parent.Add(child2a); parent.Add(comment); parent.Add(child2b); Validate.Enumerator( comment.ElementsBeforeSelf(), new XElement[] { child1a, child1b, child2a }); Validate.Enumerator( comment.ElementsBeforeSelf("child1"), new XElement[] { child1a, child1b }); Validate.Enumerator( child2b.ElementsBeforeSelf(), new XElement[] { child1a, child1b, child2a }); Validate.Enumerator( child2b.ElementsBeforeSelf("child2"), new XElement[] { child2a }); } /// <summary> /// Tests the ElementsAfterSelf methods on Node. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "NodeElementsAfterSelf")] public void NodeElementsAfterSelf() { XElement parent = new XElement("parent"); XElement child1a = new XElement("child1", new XElement("nested")); XElement child1b = new XElement("child1", new XElement("nested")); XElement child2a = new XElement("child2", new XElement("nested")); XElement child2b = new XElement("child2", new XElement("nested")); XComment comment = new XComment("this is a comment"); // If no parent, should not be any elements before it. Validate.Enumerator(comment.ElementsAfterSelf(), new XElement[0]); parent.Add(child1a); parent.Add(comment); parent.Add(child1b); parent.Add(child2a); parent.Add(child2b); Validate.Enumerator( comment.ElementsAfterSelf(), new XElement[] { child1b, child2a, child2b }); Validate.Enumerator( comment.ElementsAfterSelf("child1"), new XElement[] { child1b }); Validate.Enumerator( child1a.ElementsAfterSelf("child1"), new XElement[] { child1b }); Validate.Enumerator(child2b.ElementsAfterSelf(), new XElement[0]); } /// <summary> /// Tests the Document property on Node. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "NodeDocument")] public void NodeDocument() { XDocument document = new XDocument(); XNode[] topLevelNodes = new XNode[] { new XComment("comment"), new XElement("element"), new XProcessingInstruction("target", "data"), }; XNode[] nestedNodes = new XNode[] { new XText("abcd"), new XElement("nested"), new XProcessingInstruction("target2", "data2") }; // Test top-level cases. foreach (XNode node in topLevelNodes) { Validate.IsNull(node.Document); document.Add(node); Validate.IsReferenceEqual(document, node.Document); document.RemoveNodes(); } // Test nested cases. XElement root = new XElement("root"); document.Add(root); foreach (XNode node in nestedNodes) { Validate.IsNull(node.Document); root.Add(node); Validate.IsReferenceEqual(document, root.Document); root.RemoveNodes(); } } /// <summary> /// Gets the full path of the RuntimeTestXml directory, allowing for the /// possibility of being run from the VS build (bin\debug, etc). /// </summary> /// <returns></returns> internal string GetTestXmlDirectory() { const string TestXmlDirectoryName = "RuntimeTestXml"; string baseDir = Path.Combine(XLinqTestCase.RootPath, @"TestData\XLinq\"); string dir = Path.Combine(baseDir, TestXmlDirectoryName); return Path.Combine(baseDir, "..\\..\\" + TestXmlDirectoryName); } /// <summary> /// Gets the filenames of all files in the RuntimeTestXml directory. /// We use all files we find in a directory with a known name and location. /// </summary> /// <returns></returns> internal string[] GetTestXmlFilenames() { string[] filenames = new string[] { }; return filenames; } /// <summary> /// Gets the filenames of all files in the RuntimeTestXml directory. /// We use all files we find in a directory with a known name and location. /// </summary> /// <returns></returns> internal string GetTestXmlFilename(string filename) { string directory = GetTestXmlDirectory(); string fullName = Path.Combine(directory, filename); return fullName; } } } } }
//--------------------------------------------------------------------- // File: XmlValidationStep.cs // // Summary: // //--------------------------------------------------------------------- // Copyright (c) 2004-2015, Kevin B. Smith. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR // PURPOSE. //--------------------------------------------------------------------- using System; using System.IO; using System.Xml; using System.Xml.Schema; using System.Xml.XPath; using System.Collections.ObjectModel; using BizUnit.Common; using BizUnit.TestSteps.Common; using BizUnit.Xaml; namespace BizUnit.TestSteps.ValidationSteps.Xml { /// <summary> /// The XmlValidationStep validates an Xml document, it may validate against a given schema, and also evaluate XPath queries. /// The Xpath query is extended from XmlValidationStep to allow Xpath functions to be used which may not return a node set. /// </summary> /// /// <remarks> /// The following shows an example of the Xml representation of this test step. /// /// <code escaped="true"> /// <SubSteps assemblyPath="" typeName="BizUnit.XmlValidationStep"> /// <XmlSchemaPath>.\TestData\PurchaseOrder.xsd</XmlSchemaPath> /// <XmlSchemaNameSpace>urn:bookstore-schema</XmlSchemaNameSpace> /// <XPathList> /// <XPathValidation query="/*[local-name()='PurchaseOrder' and namespace-uri()='http://SendMail.PurchaseOrder']/*[local-name()='PONumber' and namespace-uri()='']">PONumber_0</XPathValidation> /// </XPathList> /// </SubSteps> /// </code> /// /// <list type="table"> /// <listheader> /// <term>Tag</term> /// <description>Description</description> /// </listheader> /// <item> /// <term>XmlSchemaPath</term> /// <description>The XSD schema to use to validate the XML data (optional)</description> /// </item> /// <item> /// <term>XmlSchemaNameSpace</term> /// <description>The XSD schema namespace to validate the XML data against (optional)</description> /// </item> /// <item> /// <term>XPathList/XPathValidation</term> /// <description>XPath expression to evaluate against the XML document (optional)(repeating).</description> /// </item> /// </list> /// </remarks> public class XmlValidationStep : SubStepBase { private Collection<XPathDefinition> _xPathValidations = new Collection<XPathDefinition>(); private Collection<SchemaDefinition> _xmlSchemas = new Collection<SchemaDefinition>(); private Exception _validationException; private Context _context; public Collection<SchemaDefinition> XmlSchemas { set { _xmlSchemas = value; } get { return _xmlSchemas; } } public Collection<XPathDefinition> XPathValidations { get { return _xPathValidations; } set { _xPathValidations = value; } } /// <summary> /// ITestStep.Execute() implementation /// </summary> /// <param name='data'>The stream cintaining the data to be validated.</param> /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param> public override Stream Execute(Stream data, Context context) { _context = context; var document = ValidateXmlInstance(data, context); ValidateXPathExpressions(document, context); data.Seek(0, SeekOrigin.Begin); return data; } public override void Validate(Context context) { foreach(var schema in XmlSchemas) { ArgumentValidation.CheckForNullReference(schema.XmlSchemaPath, "schema.XmlSchemaPath"); ArgumentValidation.CheckForNullReference(schema.XmlSchemaNameSpace, "schema.XmlSchemaNameSpace"); } foreach(var xpath in XPathValidations) { ArgumentValidation.CheckForNullReference(xpath.XPath, "xpath.XPath"); ArgumentValidation.CheckForNullReference(xpath.Value, "xpath.Value"); } } private XmlDocument ValidateXmlInstance(Stream data, Context context) { try { var settings = new XmlReaderSettings(); foreach (var xmlSchema in _xmlSchemas) { settings.Schemas.Add(xmlSchema.XmlSchemaNameSpace, xmlSchema.XmlSchemaPath); } settings.ValidationType = ValidationType.Schema; XmlReader reader = XmlReader.Create(data, settings); var document = new XmlDocument(); document.Load(reader); var eventHandler = new ValidationEventHandler(ValidationEventHandler); document.Validate(eventHandler); return document; } catch (Exception ex) { context.LogException(ex); throw new ValidationStepExecutionException("Failed to validate document instance", ex, context.TestName); } } private void ValidateXPathExpressions(XmlDocument doc, Context context) { foreach (XPathDefinition validation in _xPathValidations) { var xpathExp = validation.XPath; var expectedValue = validation.Value; if (null != validation.Description) { context.LogInfo("XPath: {0}", validation.Description); } context.LogInfo("Evaluting XPath {0} equals \"{1}\"", xpathExp, expectedValue); XPathNavigator xpn = doc.CreateNavigator(); object result = xpn.Evaluate(xpathExp); string actualValue = null; if (result.GetType().Name == "XPathSelectionIterator") { var xpi = result as XPathNodeIterator; xpi.MoveNext(); // BUGBUG! actualValue = xpi.Current.ToString(); } else { actualValue = result.ToString(); } if (!string.IsNullOrEmpty(validation.ContextKey)) { context.Add(validation.ContextKey, actualValue); } if (!string.IsNullOrEmpty(expectedValue)) { if (0 != expectedValue.CompareTo(actualValue)) { context.LogError("XPath evaluation failed. Expected:<{0}>. Actual:<{1}>.", expectedValue, actualValue); throw new ApplicationException( string.Format("XmlValidationStep failed, compare {0} != {1}, xpath query used: {2}", expectedValue, actualValue, xpathExp)); } context.LogInfo("XPath evaluation succeeded. Expected:<{0}>. Actual:<{1}>.", expectedValue, actualValue); } } } void ValidationEventHandler(object sender, ValidationEventArgs e) { switch (e.Severity) { case XmlSeverityType.Error: _context.LogError(e.Message); _validationException = e.Exception; break; case XmlSeverityType.Warning: _context.LogWarning(e.Message); _validationException = e.Exception; break; } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text.RegularExpressions; using System.Xml.Linq; using System.Xml.XPath; using Highlight.Extensions; using Highlight.Patterns; using SixLabors.Fonts; namespace Highlight.Configuration { public class XmlConfiguration : IConfiguration { private IDictionary<string, Definition> definitions; public IDictionary<string, Definition> Definitions { get { return GetDefinitions(); } } public XDocument XmlDocument { get; protected set; } public XmlConfiguration(XDocument xmlDocument) { if (xmlDocument == null) { throw new ArgumentNullException("xmlDocument"); } XmlDocument = xmlDocument; } protected XmlConfiguration() { } private IDictionary<string, Definition> GetDefinitions() { if (definitions == null) { definitions = XmlDocument .Descendants("definition") .Select(GetDefinition) .ToDictionary(x => x.Name); } return definitions; } private Definition GetDefinition(XElement definitionElement) { var name = definitionElement.GetAttributeValue("name"); var patterns = GetPatterns(definitionElement); var caseSensitive = Boolean.Parse(definitionElement.GetAttributeValue("caseSensitive")); var style = GetDefinitionStyle(definitionElement); return new Definition(name, caseSensitive, style, patterns); } private IDictionary<string, Pattern> GetPatterns(XContainer definitionElement) { var patterns = definitionElement .Descendants("pattern") .Select(GetPattern) .ToDictionary(x => x.Name); return patterns; } private Pattern GetPattern(XElement patternElement) { const StringComparison stringComparison = StringComparison.OrdinalIgnoreCase; var patternType = patternElement.GetAttributeValue("type"); if (patternType.Equals("block", stringComparison)) { return GetBlockPattern(patternElement); } if (patternType.Equals("markup", stringComparison)) { return GetMarkupPattern(patternElement); } if (patternType.Equals("word", stringComparison)) { return GetWordPattern(patternElement); } throw new InvalidOperationException(String.Format("Unknown pattern type: {0}", patternType)); } private BlockPattern GetBlockPattern(XElement patternElement) { var name = patternElement.GetAttributeValue("name"); var style = GetPatternStyle(patternElement); var beginsWith = patternElement.GetAttributeValue("beginsWith"); var endsWith = patternElement.GetAttributeValue("endsWith"); var escapesWith = patternElement.GetAttributeValue("escapesWith"); return new BlockPattern(name, style, beginsWith, endsWith, escapesWith); } private MarkupPattern GetMarkupPattern(XElement patternElement) { var name = patternElement.GetAttributeValue("name"); var style = GetPatternStyle(patternElement); var highlightAttributes = Boolean.Parse(patternElement.GetAttributeValue("highlightAttributes")); var bracketColors = GetMarkupPatternBracketColors(patternElement); var attributeNameColors = GetMarkupPatternAttributeNameColors(patternElement); var attributeValueColors = GetMarkupPatternAttributeValueColors(patternElement); return new MarkupPattern(name, style, highlightAttributes, bracketColors, attributeNameColors, attributeValueColors); } private WordPattern GetWordPattern(XElement patternElement) { var name = patternElement.GetAttributeValue("name"); var style = GetPatternStyle(patternElement); var words = GetPatternWords(patternElement); return new WordPattern(name, style, words); } private IEnumerable<string> GetPatternWords(XContainer patternElement) { var words = new List<string>(); var wordElements = patternElement.Descendants("word"); if (wordElements != null) { words.AddRange(from wordElement in wordElements select Regex.Escape(wordElement.Value)); } return words; } private Style GetPatternStyle(XContainer patternElement) { var fontElement = patternElement.Descendants("font").Single(); var colors = GetPatternColors(fontElement); var font = GetPatternFont(fontElement); return new Style(colors, font); } private ColorPair GetPatternColors(XElement fontElement) { var foreColor = Color.FromName(fontElement.GetAttributeValue("foreColor")); var backColor = Color.FromName(fontElement.GetAttributeValue("backColor")); return new ColorPair(foreColor, backColor); } private Font GetPatternFont(XElement fontElement, Font defaultFont = null) { var fontFamily = fontElement.GetAttributeValue("name"); if (fontFamily != null) { var emSize = fontElement.GetAttributeValue("size").ToSingle(11f); var style = Enum<FontStyle>.Parse(fontElement.GetAttributeValue("style"), FontStyle.Regular, true); return SystemFonts.CreateFont(fontFamily, emSize, style); } return defaultFont; } private ColorPair GetMarkupPatternBracketColors(XContainer patternElement) { const string descendantName = "bracketStyle"; return GetMarkupPatternColors(patternElement, descendantName); } private ColorPair GetMarkupPatternAttributeNameColors(XContainer patternElement) { const string descendantName = "attributeNameStyle"; return GetMarkupPatternColors(patternElement, descendantName); } private ColorPair GetMarkupPatternAttributeValueColors(XContainer patternElement) { const string descendantName = "attributeValueStyle"; return GetMarkupPatternColors(patternElement, descendantName); } private ColorPair GetMarkupPatternColors(XContainer patternElement, XName descendantName) { var fontElement = patternElement.Descendants("font").Single(); var element = fontElement.Descendants(descendantName).SingleOrDefault(); if (element != null) { var colors = GetPatternColors(element); return colors; } return null; } private Style GetDefinitionStyle(XNode definitionElement) { const string xpath = "default/font"; var fontElement = definitionElement.XPathSelectElement(xpath); var colors = GetDefinitionColors(fontElement); var font = GetDefinitionFont(fontElement); return new Style(colors, font); } private ColorPair GetDefinitionColors(XElement fontElement) { var foreColor = Color.FromName(fontElement.GetAttributeValue("foreColor")); var backColor = Color.FromName(fontElement.GetAttributeValue("backColor")); return new ColorPair(foreColor, backColor); } private Font GetDefinitionFont(XElement fontElement) { var fontName = fontElement.GetAttributeValue("name"); var fontSize = Convert.ToSingle(fontElement.GetAttributeValue("size")); var fontStyle = (FontStyle) Enum.Parse(typeof(FontStyle), fontElement.GetAttributeValue("style"), true); return SystemFonts.CreateFont(fontName, fontSize, fontStyle); } } }
/* * 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 Lucene.Net.Index; using IndexReader = Lucene.Net.Index.IndexReader; namespace Lucene.Net.Search { /// <summary> A query that wraps a filter and simply returns a constant score equal to the /// query boost for every document in the filter. /// </summary> [Serializable] public class ConstantScoreQuery:Query { protected internal Filter internalFilter; public ConstantScoreQuery(Filter filter) { this.internalFilter = filter; } /// <summary>Returns the encapsulated filter </summary> public virtual Filter Filter { get { return internalFilter; } } public override Query Rewrite(IndexReader reader) { return this; } public override void ExtractTerms(System.Collections.Generic.ISet<Term> terms) { // OK to not add any terms when used for MultiSearcher, // but may not be OK for highlighting } [Serializable] protected internal class ConstantWeight:Weight { private void InitBlock(ConstantScoreQuery enclosingInstance) { this.enclosingInstance = enclosingInstance; } private ConstantScoreQuery enclosingInstance; public ConstantScoreQuery Enclosing_Instance { get { return enclosingInstance; } } private readonly Similarity similarity; private float queryNorm; private float queryWeight; public ConstantWeight(ConstantScoreQuery enclosingInstance, Searcher searcher) { InitBlock(enclosingInstance); this.similarity = Enclosing_Instance.GetSimilarity(searcher); } public override Query Query { get { return Enclosing_Instance; } } public override float Value { get { return queryWeight; } } public override float GetSumOfSquaredWeights() { queryWeight = Enclosing_Instance.Boost; return queryWeight*queryWeight; } public override void Normalize(float norm) { this.queryNorm = norm; queryWeight *= this.queryNorm; } public override Scorer Scorer(IndexReader reader, bool scoreDocsInOrder, bool topScorer) { return new ConstantScorer(enclosingInstance, similarity, reader, this); } public override Explanation Explain(IndexReader reader, int doc) { var cs = new ConstantScorer(enclosingInstance, similarity, reader, this); bool exists = cs.docIdSetIterator.Advance(doc) == doc; var result = new ComplexExplanation(); if (exists) { result.Description = "ConstantScoreQuery(" + Enclosing_Instance.internalFilter + "), product of:"; result.Value = queryWeight; System.Boolean tempAux = true; result.Match = tempAux; result.AddDetail(new Explanation(Enclosing_Instance.Boost, "boost")); result.AddDetail(new Explanation(queryNorm, "queryNorm")); } else { result.Description = "ConstantScoreQuery(" + Enclosing_Instance.internalFilter + ") doesn't match id " + doc; result.Value = 0; System.Boolean tempAux2 = false; result.Match = tempAux2; } return result; } } protected internal class ConstantScorer : Scorer { private void InitBlock(ConstantScoreQuery enclosingInstance) { this.enclosingInstance = enclosingInstance; } private ConstantScoreQuery enclosingInstance; public ConstantScoreQuery Enclosing_Instance { get { return enclosingInstance; } } internal DocIdSetIterator docIdSetIterator; internal float theScore; internal int doc = - 1; public ConstantScorer(ConstantScoreQuery enclosingInstance, Similarity similarity, IndexReader reader, Weight w):base(similarity) { InitBlock(enclosingInstance); theScore = w.Value; DocIdSet docIdSet = Enclosing_Instance.internalFilter.GetDocIdSet(reader); if (docIdSet == null) { docIdSetIterator = DocIdSet.EMPTY_DOCIDSET.Iterator(); } else { DocIdSetIterator iter = docIdSet.Iterator(); if (iter == null) { docIdSetIterator = DocIdSet.EMPTY_DOCIDSET.Iterator(); } else { docIdSetIterator = iter; } } } public override int NextDoc() { return docIdSetIterator.NextDoc(); } public override int DocID() { return docIdSetIterator.DocID(); } public override float Score() { return theScore; } public override int Advance(int target) { return docIdSetIterator.Advance(target); } } public override Weight CreateWeight(Searcher searcher) { return new ConstantScoreQuery.ConstantWeight(this, searcher); } /// <summary>Prints a user-readable version of this query. </summary> public override System.String ToString(string field) { return "ConstantScore(" + internalFilter + (Boost == 1.0?")":"^" + Boost); } /// <summary>Returns true if <c>o</c> is equal to this. </summary> public override bool Equals(System.Object o) { if (this == o) return true; if (!(o is ConstantScoreQuery)) return false; ConstantScoreQuery other = (ConstantScoreQuery) o; return this.Boost == other.Boost && internalFilter.Equals(other.internalFilter); } /// <summary>Returns a hash code value for this object. </summary> public override int GetHashCode() { // Simple add is OK since no existing filter hashcode has a float component. return internalFilter.GetHashCode() + BitConverter.ToInt32(BitConverter.GetBytes(Boost), 0); } override public System.Object Clone() { // {{Aroush-1.9}} is this all that we need to clone?! ConstantScoreQuery clone = (ConstantScoreQuery)base.Clone(); clone.internalFilter = (Filter)this.internalFilter; return clone; } } }
// 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.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Diagnostics.Tests { using Configuration = System.Net.Test.Common.Configuration; public class HttpHandlerDiagnosticListenerTests : RemoteExecutorTestBase { /// <summary> /// A simple test to make sure the Http Diagnostic Source is added into the list of DiagnosticListeners. /// </summary> [Fact] public void TestHttpDiagnosticListenerIsRegistered() { bool listenerFound = false; using (DiagnosticListener.AllListeners.Subscribe(new CallbackObserver<DiagnosticListener>(diagnosticListener => { if (diagnosticListener.Name == "System.Net.Http.Desktop") { listenerFound = true; } }))) { Assert.True(listenerFound, "The Http Diagnostic Listener didn't get added to the AllListeners list."); } } /// <summary> /// A simple test to make sure the Http Diagnostic Source is initialized properly after we subscribed to it, using /// the subscribe overload with just the observer argument. /// </summary> [OuterLoop] [Fact] public void TestReflectInitializationViaSubscription1() { using (var eventRecords = new EventObserverAndRecorder()) { // Send a random Http request to generate some events using (var client = new HttpClient()) { client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose(); } // Just make sure some events are written, to confirm we successfully subscribed to it. // We should have exactly one Start and one Stop event Assert.Equal(2, eventRecords.Records.Count); } } /// <summary> /// A simple test to make sure the Http Diagnostic Source is initialized properly after we subscribed to it, using /// the subscribe overload with just the observer argument and the more complicating enable filter function. /// </summary> [OuterLoop] [Fact] public void TestReflectInitializationViaSubscription2() { using (var eventRecords = new EventObserverAndRecorder(eventName => true)) { // Send a random Http request to generate some events using (var client = new HttpClient()) { client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose(); } // Just make sure some events are written, to confirm we successfully subscribed to it. // We should have exactly one Start and one Stop event Assert.Equal(2, eventRecords.Records.Count); } } /// <summary> /// A simple test to make sure the Http Diagnostic Source is initialized properly after we subscribed to it, using /// the subscribe overload with the observer argument and the simple predicate argument. /// </summary> [OuterLoop] [Fact] public void TestReflectInitializationViaSubscription3() { using (var eventRecords = new EventObserverAndRecorder((eventName, arg1, arg2) => true)) { // Send a random Http request to generate some events using (var client = new HttpClient()) { client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose(); } // Just make sure some events are written, to confirm we successfully subscribed to it. // We should have exactly one Start and one Stop event Assert.Equal(2, eventRecords.Records.Count); } } /// <summary> /// Test to make sure we get both request and response events. /// </summary> [OuterLoop] [Fact] public async Task TestBasicReceiveAndResponseEvents() { using (var eventRecords = new EventObserverAndRecorder()) { // Send a random Http request to generate some events using (var client = new HttpClient()) { (await client.GetAsync(Configuration.Http.RemoteEchoServer)).Dispose(); } // We should have exactly one Start and one Stop event Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Start"))); Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Stop"))); Assert.Equal(2, eventRecords.Records.Count); // Check to make sure: The first record must be a request, the next record must be a response. KeyValuePair<string, object> startEvent; Assert.True(eventRecords.Records.TryDequeue(out startEvent)); Assert.Equal("System.Net.Http.Desktop.HttpRequestOut.Start", startEvent.Key); HttpWebRequest startRequest = ReadPublicProperty<HttpWebRequest>(startEvent.Value, "Request"); Assert.NotNull(startRequest); Assert.NotNull(startRequest.Headers["Request-Id"]); Assert.Null(startRequest.Headers["traceparent"]); Assert.Null(startRequest.Headers["tracestate"]); KeyValuePair<string, object> stopEvent; Assert.True(eventRecords.Records.TryDequeue(out stopEvent)); Assert.Equal("System.Net.Http.Desktop.HttpRequestOut.Stop", stopEvent.Key); HttpWebRequest stopRequest = ReadPublicProperty<HttpWebRequest>(stopEvent.Value, "Request"); Assert.Equal(startRequest, stopRequest); HttpWebResponse response = ReadPublicProperty<HttpWebResponse>(stopEvent.Value, "Response"); Assert.NotNull(response); } } [OuterLoop] [Fact] public async Task TestW3CHeaders() { try { using (var eventRecords = new EventObserverAndRecorder()) { Activity.DefaultIdFormat = ActivityIdFormat.W3C; Activity.ForceDefaultIdFormat = true; // Send a random Http request to generate some events using (var client = new HttpClient()) { (await client.GetAsync(Configuration.Http.RemoteEchoServer)).Dispose(); } // Check to make sure: The first record must be a request, the next record must be a response. KeyValuePair<string, object> startEvent; Assert.True(eventRecords.Records.TryDequeue(out startEvent)); Assert.Equal("System.Net.Http.Desktop.HttpRequestOut.Start", startEvent.Key); HttpWebRequest startRequest = ReadPublicProperty<HttpWebRequest>(startEvent.Value, "Request"); Assert.NotNull(startRequest); var traceparent = startRequest.Headers["traceparent"]; Assert.NotNull(traceparent); Assert.True(Regex.IsMatch(traceparent, "^[0-9a-f][0-9a-f]-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f][0-9a-f]$")); Assert.Null(startRequest.Headers["tracestate"]); Assert.Null(startRequest.Headers["Request-Id"]); } } finally { CleanUp(); } } [OuterLoop] [Fact] public async Task TestW3CHeadersTraceStateAndCorrelationContext() { try { using (var eventRecords = new EventObserverAndRecorder()) { var parent = new Activity("w3c activity"); parent.SetParentId(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom()); parent.TraceStateString = "some=state"; parent.AddBaggage("k", "v"); parent.Start(); // Send a random Http request to generate some events using (var client = new HttpClient()) { (await client.GetAsync(Configuration.Http.RemoteEchoServer)).Dispose(); } parent.Stop(); // Check to make sure: The first record must be a request, the next record must be a response. Assert.True(eventRecords.Records.TryDequeue(out var evnt)); Assert.Equal("System.Net.Http.Desktop.HttpRequestOut.Start", evnt.Key); HttpWebRequest startRequest = ReadPublicProperty<HttpWebRequest>(evnt.Value, "Request"); Assert.NotNull(startRequest); var traceparent = startRequest.Headers["traceparent"]; var tracestate = startRequest.Headers["tracestate"]; var correlationContext = startRequest.Headers["Correlation-Context"]; Assert.NotNull(traceparent); Assert.Equal("some=state", tracestate); Assert.Equal("k=v", correlationContext); Assert.True(traceparent.StartsWith($"00-{parent.TraceId.ToHexString()}-")); Assert.True(Regex.IsMatch(traceparent, "^[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$")); Assert.Null(startRequest.Headers["Request-Id"]); } } finally { CleanUp(); } } [OuterLoop] [Fact] public async Task DoNotInjectRequestIdWhenPresent() { using (var eventRecords = new EventObserverAndRecorder()) { // Send a random Http request to generate some events using (var client = new HttpClient()) using (var request = new HttpRequestMessage(HttpMethod.Get, Configuration.Http.RemoteEchoServer)) { request.Headers.Add("Request-Id", "|rootId.1."); (await client.SendAsync(request)).Dispose(); } // Check to make sure: The first record must be a request, the next record must be a response. Assert.True(eventRecords.Records.TryDequeue(out var evnt)); HttpWebRequest startRequest = ReadPublicProperty<HttpWebRequest>(evnt.Value, "Request"); Assert.NotNull(startRequest); Assert.Equal("|rootId.1.", startRequest.Headers["Request-Id"]); } } [OuterLoop] [Fact] public async Task DoNotInjectTraceParentWhenPresent() { try { using (var eventRecords = new EventObserverAndRecorder()) { Activity.DefaultIdFormat = ActivityIdFormat.W3C; Activity.ForceDefaultIdFormat = true; // Send a random Http request to generate some events using (var client = new HttpClient()) using (var request = new HttpRequestMessage(HttpMethod.Get, Configuration.Http.RemoteEchoServer)) { request.Headers.Add("traceparent", "00-abcdef0123456789abcdef0123456789-abcdef0123456789-01"); (await client.SendAsync(request)).Dispose(); } // Check to make sure: The first record must be a request, the next record must be a response. Assert.True(eventRecords.Records.TryDequeue(out var evnt)); HttpWebRequest startRequest = ReadPublicProperty<HttpWebRequest>(evnt.Value, "Request"); Assert.NotNull(startRequest); Assert.Equal("00-abcdef0123456789abcdef0123456789-abcdef0123456789-01", startRequest.Headers["traceparent"]); } } finally { CleanUp(); } } /// <summary> /// Test to make sure we get both request and response events. /// </summary> [OuterLoop] [Fact] public async Task TestResponseWithoutContentEvents() { using (var eventRecords = new EventObserverAndRecorder()) { // Send a random Http request to generate some events using (var client = new HttpClient()) { (await client.GetAsync(Configuration.Http.RemoteEmptyContentServer)).Dispose(); } // We should have exactly one Start and one Stop event Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Start"))); Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Stop"))); Assert.Equal(2, eventRecords.Records.Count); // Check to make sure: The first record must be a request, the next record must be a response. KeyValuePair<string, object> startEvent; Assert.True(eventRecords.Records.TryDequeue(out startEvent)); Assert.Equal("System.Net.Http.Desktop.HttpRequestOut.Start", startEvent.Key); HttpWebRequest startRequest = ReadPublicProperty<HttpWebRequest>(startEvent.Value, "Request"); Assert.NotNull(startRequest); Assert.NotNull(startRequest.Headers["Request-Id"]); KeyValuePair<string, object> stopEvent; Assert.True(eventRecords.Records.TryDequeue(out stopEvent)); Assert.Equal("System.Net.Http.Desktop.HttpRequestOut.Ex.Stop", stopEvent.Key); HttpWebRequest stopRequest = ReadPublicProperty<HttpWebRequest>(stopEvent.Value, "Request"); Assert.Equal(startRequest, stopRequest); HttpStatusCode status = ReadPublicProperty<HttpStatusCode>(stopEvent.Value, "StatusCode"); Assert.NotNull(status); WebHeaderCollection headers = ReadPublicProperty<WebHeaderCollection>(stopEvent.Value, "Headers"); Assert.NotNull(headers); } } /// <summary> /// Test that if request is redirected, it gets only one Start and one Stop event /// </summary> [OuterLoop] [Fact] public async Task TestRedirectedRequest() { using (var eventRecords = new EventObserverAndRecorder()) { using (var client = new HttpClient()) { Uri uriWithRedirect = Configuration.Http.RedirectUriForDestinationUri(true, 302, Configuration.Http.RemoteEchoServer, 10); (await client.GetAsync(uriWithRedirect)).Dispose(); } // We should have exactly one Start and one Stop event Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Start"))); Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Stop"))); } } /// <summary> /// Test exception in request processing: exception should have expected type/status and now be swallowed by reflection hook /// </summary> [OuterLoop] [Fact] public async Task TestRequestWithException() { using (var eventRecords = new EventObserverAndRecorder()) { var ex = await Assert.ThrowsAsync<HttpRequestException>( () => new HttpClient().GetAsync($"http://{Guid.NewGuid()}.com")); // check that request failed because of the wrong domain name and not because of reflection var webException = (WebException)ex.InnerException; Assert.NotNull(webException); Assert.True(webException.Status == WebExceptionStatus.NameResolutionFailure); // We should have one Start event and no stop event Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Start"))); Assert.Equal(0, eventRecords.Records.Count(rec => rec.Key.EndsWith("Stop"))); } } /// <summary> /// Test request cancellation: reflection hook does not throw /// </summary> [OuterLoop] [Fact] public async Task TestCanceledRequest() { CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); using (var eventRecords = new EventObserverAndRecorder(_ => { cts.Cancel(); })) { using (var client = new HttpClient()) { var ex = await Assert.ThrowsAnyAsync<Exception>(() => client.GetAsync(Configuration.Http.RemoteEchoServer, cts.Token)); Assert.True(ex is TaskCanceledException || ex is WebException); } // We should have one Start event and no stop event Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Start"))); Assert.Equal(0, eventRecords.Records.Count(rec => rec.Key.EndsWith("Stop"))); } } /// <summary> /// Test Request-Id and Correlation-Context headers injection /// </summary> [OuterLoop] [Fact] public async Task TestActivityIsCreated() { var parentActivity = new Activity("parent").AddBaggage("k1", "v1").AddBaggage("k2", "v2").Start(); using (var eventRecords = new EventObserverAndRecorder()) { using (var client = new HttpClient()) { (await client.GetAsync(Configuration.Http.RemoteEchoServer)).Dispose(); } Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Start"))); Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key.EndsWith("Stop"))); WebRequest thisRequest = ReadPublicProperty<WebRequest>(eventRecords.Records.First().Value, "Request"); var requestId = thisRequest.Headers["Request-Id"]; var correlationContext = thisRequest.Headers["Correlation-Context"]; Assert.NotNull(requestId); Assert.True(requestId.StartsWith(parentActivity.Id)); Assert.NotNull(correlationContext); Assert.True(correlationContext == "k1=v1,k2=v2" || correlationContext == "k2=v2,k1=v1"); } parentActivity.Stop(); } /// <summary> /// Tests IsEnabled order and parameters /// </summary> [OuterLoop] [Fact] public async Task TestIsEnabled() { int eventNumber = 0; bool IsEnabled(string evnt, object arg1, object arg2) { if (eventNumber == 0) { Assert.True(evnt == "System.Net.Http.Desktop.HttpRequestOut"); Assert.True(arg1 is WebRequest); } else if (eventNumber == 1) { Assert.True(evnt == "System.Net.Http.Desktop.HttpRequestOut.Start"); } eventNumber++; return true; } using (new EventObserverAndRecorder(IsEnabled)) { using (var client = new HttpClient()) { (await client.GetAsync(Configuration.Http.RemoteEchoServer)).Dispose(); } Assert.Equal(2, eventNumber); } } /// <summary> /// Tests that nothing happens if IsEnabled returns false /// </summary> [OuterLoop] [Fact] public async Task TestIsEnabledAllOff() { using (var eventRecords = new EventObserverAndRecorder((evnt, arg1, arg2) => false)) { using (var client = new HttpClient()) { (await client.GetAsync(Configuration.Http.RemoteEchoServer)).Dispose(); } Assert.Equal(0, eventRecords.Records.Count); } } /// <summary> /// Tests that if IsEnabled for request is false, request is not instrumented /// </summary> [OuterLoop] [Fact] public async Task TestIsEnabledRequestOff() { bool IsEnabled(string evnt, object arg1, object arg2) { if (evnt == "System.Net.Http.Desktop.HttpRequestOut") { return (arg1 as WebRequest).RequestUri.Scheme == "https"; } return true; } using (var eventRecords = new EventObserverAndRecorder(IsEnabled)) { using (var client = new HttpClient()) { (await client.GetAsync(Configuration.Http.RemoteEchoServer)).Dispose(); Assert.Equal(0, eventRecords.Records.Count); (await client.GetAsync(Configuration.Http.SecureRemoteEchoServer)).Dispose(); Assert.Equal(2, eventRecords.Records.Count); } } } /// <summary> /// Test to make sure every event record has the right dynamic properties. /// </summary> [OuterLoop] [Fact] public void TestMultipleConcurrentRequests() { ServicePointManager.DefaultConnectionLimit = int.MaxValue; var parentActivity = new Activity("parent").Start(); using (var eventRecords = new EventObserverAndRecorder()) { Dictionary<Uri, Tuple<WebRequest, WebResponse>> requestData = new Dictionary<Uri, Tuple<WebRequest, WebResponse>>(); for (int i = 0; i < 10; i++) { Uri uriWithRedirect = Configuration.Http.RedirectUriForDestinationUri(true, 302, new Uri($"{Configuration.Http.RemoteEchoServer}?q={i}"), 3); requestData[uriWithRedirect] = null; } // Issue all requests simultaneously HttpClient httpClient = new HttpClient(); Dictionary<Uri, Task<HttpResponseMessage>> tasks = new Dictionary<Uri, Task<HttpResponseMessage>>(); CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); foreach (var url in requestData.Keys) { tasks.Add(url, httpClient.GetAsync(url, cts.Token)); } // wait up to 10 sec for all requests and suppress exceptions Task.WhenAll(tasks.Select(t => t.Value).ToArray()).ContinueWith(tt => { foreach (var task in tasks) { task.Value.Result?.Dispose(); } }).Wait(); // Examine the result. Make sure we got all successful requests. // Just make sure some events are written, to confirm we successfully subscribed to it. We should have // exactly 1 Start event per request and exaclty 1 Stop event per response (if request succeeded) var successfulTasks = tasks.Where(t => t.Value.Status == TaskStatus.RanToCompletion); Assert.Equal(tasks.Count, eventRecords.Records.Count(rec => rec.Key.EndsWith("Start"))); Assert.Equal(successfulTasks.Count(), eventRecords.Records.Count(rec => rec.Key.EndsWith("Stop"))); // Check to make sure: We have a WebRequest and a WebResponse for each successful request foreach (var pair in eventRecords.Records) { object eventFields = pair.Value; Assert.True( pair.Key == "System.Net.Http.Desktop.HttpRequestOut.Start" || pair.Key == "System.Net.Http.Desktop.HttpRequestOut.Stop", "An unexpected event of name " + pair.Key + "was received"); WebRequest request = ReadPublicProperty<WebRequest>(eventFields, "Request"); Assert.Equal(request.GetType().Name, "HttpWebRequest"); if (pair.Key == "System.Net.Http.Desktop.HttpRequestOut.Start") { // Make sure this is an URL that we recognize. If not, just skip Tuple<WebRequest, WebResponse> tuple = null; if (!requestData.TryGetValue(request.RequestUri, out tuple)) { continue; } // all requests have Request-Id with proper parent Id var requestId = request.Headers["Request-Id"]; Assert.True(requestId.StartsWith(parentActivity.Id)); // all request activities are siblings: var childSuffix = requestId.Substring(0, parentActivity.Id.Length); Assert.True(childSuffix.IndexOf('.') == childSuffix.Length - 1); Assert.Null(requestData[request.RequestUri]); requestData[request.RequestUri] = new Tuple<WebRequest, WebResponse>(request, null); } else { // This must be the response. WebResponse response = ReadPublicProperty<WebResponse>(eventFields, "Response"); Assert.Equal(response.GetType().Name, "HttpWebResponse"); // By the time we see the response, the request object may already have been redirected with a different // url. Hence, it's not reliable to just look up requestData by the URL/hostname. Instead, we have to look // through each one and match by object reference on the request object. Tuple<WebRequest, WebResponse> tuple = null; foreach (Tuple<WebRequest, WebResponse> currentTuple in requestData.Values) { if (currentTuple != null && currentTuple.Item1 == request) { // Found it! tuple = currentTuple; break; } } // Update the tuple with the response object Assert.NotNull(tuple); requestData[request.RequestUri] = new Tuple<WebRequest, WebResponse>(request, response); } } // Finally, make sure we have request and response objects for every successful request foreach (KeyValuePair<Uri, Tuple<WebRequest, WebResponse>> pair in requestData) { if (successfulTasks.Any(t => t.Key == pair.Key)) { Assert.NotNull(pair.Value); Assert.NotNull(pair.Value.Item1); Assert.NotNull(pair.Value.Item2); } } } } public void CleanUp() { Activity.DefaultIdFormat = ActivityIdFormat.Hierarchical; Activity.ForceDefaultIdFormat = false; while (Activity.Current != null) { Activity.Current.Stop(); } } private static T ReadPublicProperty<T>(object obj, string propertyName) { Type type = obj.GetType(); PropertyInfo property = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public); return (T)property.GetValue(obj); } /// <summary> /// CallbackObserver is an adapter class that creates an observer (which you can pass /// to IObservable.Subscribe), and calls the given callback every time the 'next' /// operation on the IObserver happens. /// </summary> /// <typeparam name="T"></typeparam> private class CallbackObserver<T> : IObserver<T> { public CallbackObserver(Action<T> callback) { _callback = callback; } public void OnCompleted() { } public void OnError(Exception error) { } public void OnNext(T value) { _callback(value); } private Action<T> _callback; } /// <summary> /// EventObserverAndRecorder is an observer that watches all Http diagnostic listener events flowing /// through, and record all of them /// </summary> private class EventObserverAndRecorder : IObserver<KeyValuePair<string, object>>, IDisposable { private readonly Action<KeyValuePair<string, object>> onEvent; public EventObserverAndRecorder(Action<KeyValuePair<string, object>> onEvent = null) { listSubscription = DiagnosticListener.AllListeners.Subscribe(new CallbackObserver<DiagnosticListener>(diagnosticListener => { if (diagnosticListener.Name == "System.Net.Http.Desktop") { httpSubscription = diagnosticListener.Subscribe(this); } })); this.onEvent = onEvent; } public EventObserverAndRecorder(Predicate<string> isEnabled) { listSubscription = DiagnosticListener.AllListeners.Subscribe(new CallbackObserver<DiagnosticListener>(diagnosticListener => { if (diagnosticListener.Name == "System.Net.Http.Desktop") { httpSubscription = diagnosticListener.Subscribe(this, isEnabled); } })); } public EventObserverAndRecorder(Func<string, object, object, bool> isEnabled) { listSubscription = DiagnosticListener.AllListeners.Subscribe(new CallbackObserver<DiagnosticListener>(diagnosticListener => { if (diagnosticListener.Name == "System.Net.Http.Desktop") { httpSubscription = diagnosticListener.Subscribe(this, isEnabled); } })); } public void Dispose() { listSubscription.Dispose(); httpSubscription.Dispose(); } public ConcurrentQueue<KeyValuePair<string, object>> Records { get; } = new ConcurrentQueue<KeyValuePair<string, object>>(); public void OnCompleted() { } public void OnError(Exception error) { } public void OnNext(KeyValuePair<string, object> record) { Records.Enqueue(record); onEvent?.Invoke(record); } private readonly IDisposable listSubscription; private IDisposable httpSubscription; } } }
// 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. #if WINDOWS using Microsoft.Diagnostics.Tracing.Parsers.Clr; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace GCPerfTestFramework.Metrics.Builders { internal class GCEvent { #region Public Fields // Time it takes to do the suspension. Before 4.0 we didn't have a SuspendEnd event so we calculate it by just // substracting GC duration from pause duration. For concurrent GC this would be inaccurate so we just return 0. public double _SuspendDurationMSec; public double[] AllocedSinceLastGCBasedOnAllocTickMB = { 0.0, 0.0 }; public long duplicatedPinningReports; public double DurationSinceLastRestartMSec; // The amount of CPU time this GC consumed. public float GCCpuMSec; public float[] GCCpuServerGCThreads = null; public double GCDurationMSec; public int GCGeneration; // Primary fields (set in the callbacks) public int GCNumber; public double GCStartRelativeMSec; public GCGlobalHeapHistoryTraceData GlobalHeapHistory; public bool HasAllocTickEvents = false; public GCHeapStatsTraceData HeapStats; public int Index; // In 2.0 we didn't have all the events. I try to keep the code not version specific and this is really // for debugging/verification purpose. public bool is20Event; // Did we get the complete event sequence for this GC? // For BGC this is the HeapStats event; for other GCs this means you have both the HeapStats and RestartEEEnd event. public bool isComplete; // Set in Start, does not include suspension. // Set in Stop This is JUST the GC time (not including suspension) That is Stop-Start. // This only applies to 2.0. I could just set the type to Background GC but I'd rather not disturb // the code that handles background GC. public bool isConcurrentGC; public GCProcess Parent; //process that did that GC public double PauseDurationMSec; public double PauseStartRelativeMSec; public List<GCPerHeapHistoryTraceData> PerHeapHistories; // The dictionary of heap number and info on time it takes to mark various roots. public Dictionary<int, MarkInfo> PerHeapMarkTimes; public Dictionary<ulong, long> PinnedObjects = new Dictionary<ulong, long>(); public List<PinnedPlug> PinnedPlugs = new List<PinnedPlug>(); // For background GC we need to remember when the GC before it ended because // when we get the GCStop event some foreground GCs may have happened. public float ProcessCpuAtLastGC; // Total time EE is suspended (can be less than GC time for background) // The amount of CPU time the process consumed since the last GC. public float ProcessCpuMSec; public GCReason Reason; public long totalPinnedPlugSize; public long totalUserPinnedPlugSize; // Set in GCStop(Generation 0, 1 or 2) public GCType Type; private GCCondemnedReasons[] _PerHeapCondemnedReasons; private GCPerHeapHistoryGenData[][] _PerHeapGenData; #endregion #region Private Fields // Set in GCStart private double _TotalGCTimeMSec = -1; // Set in GCStart // When we are using Server GC we store the CPU spent on each thread // so we can see if there's an imbalance. We concurrently don't do this // for server background GC as the imbalance there is much less important. int heapCount = -1; private long pinnedObjectSizes; // Set in GCStart // Set in GCStart //list of workload histories per server GC heap private List<ServerGcHistory> ServerGcHeapHistories = new List<ServerGcHistory>(); private PerHeapEventVersion Version = PerHeapEventVersion.V0; #endregion #region Constructors public GCEvent(GCProcess owningProcess) { Parent = owningProcess; heapCount = owningProcess.heapCount; if (heapCount > 1) { GCCpuServerGCThreads = new float[heapCount]; } pinnedObjectSizes = -1; totalPinnedPlugSize = -1; totalUserPinnedPlugSize = -1; duplicatedPinningReports = 0; } #endregion #region Private Enums private enum InducedType { Blocking = 1, NotForced = 2, } // TODO: get rid of the remaining version checking here - convert the leftover checks with using the Has* methods // to determine whether that particular data is available. private enum PerHeapEventVersion { V0, // Not set V4_0, V4_5, V4_6, } #endregion #region Public Properties public double AllocedSinceLastGCMB { get { return GetUserAllocated(Gens.Gen0) + GetUserAllocated(Gens.GenLargeObj); } } public double AllocRateMBSec { get { return AllocedSinceLastGCMB * 1000.0 / DurationSinceLastRestartMSec; } } public double CondemnedMB { get { double ret = GenSizeBeforeMB(0); if (1 <= GCGeneration) ret += GenSizeBeforeMB(Gens.Gen1); if (2 <= GCGeneration) ret += GenSizeBeforeMB(Gens.Gen2) + GenSizeBeforeMB(Gens.GenLargeObj); return ret; } } // Index into the list of GC events // The list that contains this event private List<GCEvent> Events { get { return Parent.Events.OfType<GCEvent>().ToList(); } } public double FragmentationMB { get { double ret = 0; for (Gens gen = Gens.Gen0; gen <= Gens.GenLargeObj; gen++) ret += GenFragmentationMB(gen); return ret; } } public int Generation => GCNumber; public bool HasServerGcThreadingInfo { get { foreach (var heap in ServerGcHeapHistories) { if (heap.SampleSpans.Count > 0 || heap.SwitchSpans.Count > 0) return true; } return false; } } /// <summary> /// This include fragmentation /// </summary> public double HeapSizeAfterMB { get { if (null != HeapStats) { return (HeapStats.GenerationSize0 + HeapStats.GenerationSize1 + HeapStats.GenerationSize2 + HeapStats.GenerationSize3) / 1000000.0; } else { return -1.0; } } } public double HeapSizeBeforeMB { get { double ret = 0; for (Gens gen = Gens.Gen0; gen <= Gens.GenLargeObj; gen++) ret += GenSizeBeforeMB(gen); return ret; } } public double HeapSizePeakMB { get { var ret = HeapSizeBeforeMB; if (Type == GCType.BackgroundGC) { var BgGcEndedRelativeMSec = PauseStartRelativeMSec + GCDurationMSec; for (int i = Index + 1; i < Events.Count; i++) { var _event = Events[i]; if (BgGcEndedRelativeMSec < _event.PauseStartRelativeMSec) break; ret = Math.Max(ret, _event.HeapSizeBeforeMB); } } return ret; } } // Set in GCStart (starts at 1, unique for process) // Of all the CPU, how much as a percentage is spent in the GC since end of last GC. public double PercentTimeInGC { get { return (GetTotalGCTime() * 100 / ProcessCpuMSec); } } public double PromotedMB { get { return (HeapStats.TotalPromotedSize0 + HeapStats.TotalPromotedSize1 + HeapStats.TotalPromotedSize2 + HeapStats.TotalPromotedSize3) / 1000000.0; } } public double RatioPeakAfter { get { if (HeapSizeAfterMB == 0) return 0; return HeapSizePeakMB / HeapSizeAfterMB; } } private GCCondemnedReasons[] PerHeapCondemnedReasons { get { if ((PerHeapHistories != null) && (_PerHeapCondemnedReasons == null)) { GetVersion(); int NumHeaps = PerHeapHistories.Count; _PerHeapCondemnedReasons = new GCCondemnedReasons[NumHeaps]; for (int HeapIndex = 0; HeapIndex < NumHeaps; HeapIndex++) { _PerHeapCondemnedReasons[HeapIndex] = new GCCondemnedReasons(); _PerHeapCondemnedReasons[HeapIndex].EncodedReasons.Reasons = PerHeapHistories[HeapIndex].CondemnReasons0; if (Version != PerHeapEventVersion.V4_0) { _PerHeapCondemnedReasons[HeapIndex].EncodedReasons.ReasonsEx = PerHeapHistories[HeapIndex].CondemnReasons1; } _PerHeapCondemnedReasons[HeapIndex].CondemnedReasonGroups = new byte[(int)CondemnedReasonGroup.CRG_Max]; _PerHeapCondemnedReasons[HeapIndex].Decode(Version); } } return _PerHeapCondemnedReasons; } } // There's a list of things we need to get from the events we collected. // To increase the efficiency so we don't need to go back to TraceEvent // too often we construct the generation data all at once here. private GCPerHeapHistoryGenData[][] PerHeapGenData { get { if ((PerHeapHistories != null) && (_PerHeapGenData == null)) { GetVersion(); int NumHeaps = PerHeapHistories.Count; _PerHeapGenData = new GCPerHeapHistoryGenData[NumHeaps][]; for (int HeapIndex = 0; HeapIndex < NumHeaps; HeapIndex++) { _PerHeapGenData[HeapIndex] = new GCPerHeapHistoryGenData[(int)Gens.GenLargeObj + 1]; for (Gens GenIndex = Gens.Gen0; GenIndex <= Gens.GenLargeObj; GenIndex++) { _PerHeapGenData[HeapIndex][(int)GenIndex] = PerHeapHistories[HeapIndex].GenData(GenIndex); } } } return _PerHeapGenData; } } #endregion #region Public Methods public void AddLOHWaitThreadInfo(int TID, double time, int reason, bool IsStart) { #if HAS_PRIVATE_GC_EVENTS BGCAllocWaitReason ReasonLOHAlloc = (BGCAllocWaitReason)reason; if ((ReasonLOHAlloc == BGCAllocWaitReason.GetLOHSeg) || (ReasonLOHAlloc == BGCAllocWaitReason.AllocDuringSweep)) { if (LOHWaitThreads == null) { LOHWaitThreads = new Dictionary<int, BGCAllocWaitInfo>(); } BGCAllocWaitInfo info; if (LOHWaitThreads.TryGetValue(TID, out info)) { if (IsStart) { // If we are finding the value it means we are hitting the small // window where BGC sweep finished and BGC itself finished, discard // this. } else { Debug.Assert(info.Reason == ReasonLOHAlloc); info.WaitStopRelativeMSec = time; } } else { info = new BGCAllocWaitInfo(); if (IsStart) { info.Reason = ReasonLOHAlloc; info.WaitStartRelativeMSec = time; } else { // We are currently not displaying this because it's incomplete but I am still adding // it so we could display if we want to. info.WaitStopRelativeMSec = time; } LOHWaitThreads.Add(TID, info); } } #endif } public void AddServerGcSample(ThreadWorkSpan sample) { if (sample.ProcessorNumber >= 0 && sample.ProcessorNumber < ServerGcHeapHistories.Count) ServerGcHeapHistories[sample.ProcessorNumber].AddSampleEvent(sample); } public void AddServerGcThreadSwitch(ThreadWorkSpan cswitch) { if (cswitch.ProcessorNumber >= 0 && cswitch.ProcessorNumber < ServerGcHeapHistories.Count) ServerGcHeapHistories[cswitch.ProcessorNumber].AddSwitchEvent(cswitch); } public void AddServerGCThreadTime(int heapIndex, float cpuMSec) { if (GCCpuServerGCThreads != null) GCCpuServerGCThreads[heapIndex] += cpuMSec; } // Unfortunately sometimes we just don't get mark events from all heaps, even for GCs that we have seen GCStart for. // So accommodating this scenario. public bool AllHeapsSeenMark() { if (PerHeapMarkTimes != null) return (heapCount == PerHeapMarkTimes.Count); else return false; } public bool DetailedGenDataAvailable() { return (PerHeapHistories != null); } public void GCEnd() { ConvertMarkTimes(); if (ServerGcHeapHistories != null) { foreach (var serverHeap in ServerGcHeapHistories) { serverHeap.GCEnd(); } } } public double GenBudgetMB(Gens gen) { if (PerHeapHistories == null) return double.NaN; double budget = 0.0; for (int HeapIndex = 0; HeapIndex < PerHeapHistories.Count; HeapIndex++) budget += PerHeapGenData[HeapIndex][(int)gen].Budget / 1000000.0; return budget; } public double GenFragmentationMB(Gens gen) { if (PerHeapHistories == null) return double.NaN; double ret = 0.0; for (int HeapIndex = 0; HeapIndex < PerHeapHistories.Count; HeapIndex++) ret += PerHeapGenData[HeapIndex][(int)gen].Fragmentation / 1000000.0; return ret; } public double GenFragmentationPercent(Gens gen) { return (GenFragmentationMB(gen) * 100.0 / GenSizeAfterMB(gen)); } public double GenFreeListAfter(Gens gen) { if (PerHeapHistories == null) return double.NaN; double ret = 0.0; for (int HeapIndex = 0; HeapIndex < PerHeapHistories.Count; HeapIndex++) ret += PerHeapGenData[HeapIndex][(int)gen].FreeListSpaceAfter; return ret; } public double GenFreeListBefore(Gens gen) { if (PerHeapHistories == null) return double.NaN; double ret = 0.0; for (int HeapIndex = 0; HeapIndex < PerHeapHistories.Count; HeapIndex++) ret += PerHeapGenData[HeapIndex][(int)gen].FreeListSpaceBefore; return ret; } public double GenInMB(Gens gen) { if (PerHeapHistories == null) return double.NaN; double ret = 0.0; for (int HeapIndex = 0; HeapIndex < PerHeapHistories.Count; HeapIndex++) ret += PerHeapGenData[HeapIndex][(int)gen].In / 1000000.0; return ret; } public double GenNonePinnedSurv(Gens gen) { if ((PerHeapHistories == null) || !(PerHeapGenData[0][0].HasNonePinnedSurv())) return double.NaN; double ret = 0.0; for (int HeapIndex = 0; HeapIndex < PerHeapHistories.Count; HeapIndex++) ret += PerHeapGenData[HeapIndex][(int)gen].NonePinnedSurv; return ret; } public double GenOut(Gens gen) { if (PerHeapHistories == null) return double.NaN; double ret = 0.0; for (int HeapIndex = 0; HeapIndex < PerHeapHistories.Count; HeapIndex++) ret += PerHeapGenData[HeapIndex][(int)gen].Out; return ret; } public double GenOutMB(Gens gen) { if (PerHeapHistories == null) return double.NaN; double ret = 0.0; for (int HeapIndex = 0; HeapIndex < PerHeapHistories.Count; HeapIndex++) ret += PerHeapGenData[HeapIndex][(int)gen].Out / 1000000.0; return ret; } public double GenPinnedSurv(Gens gen) { if ((PerHeapHistories == null) || !(PerHeapGenData[0][0].HasPinnedSurv())) return double.NaN; double ret = 0.0; for (int HeapIndex = 0; HeapIndex < PerHeapHistories.Count; HeapIndex++) ret += PerHeapGenData[HeapIndex][(int)gen].PinnedSurv; return ret; } // Note that in 4.0 TotalPromotedSize is not entirely accurate (since it doesn't // count the pins that got demoted. We could consider using the PerHeap event data // to compute the accurate promoted size. // In 4.5 this is accurate. public double GenPromotedMB(Gens gen) { if (gen == Gens.GenLargeObj) return HeapStats.TotalPromotedSize3 / 1000000.0; if (gen == Gens.Gen2) return HeapStats.TotalPromotedSize2 / 1000000.0; if (gen == Gens.Gen1) return HeapStats.TotalPromotedSize1 / 1000000.0; if (gen == Gens.Gen0) return HeapStats.TotalPromotedSize0 / 1000000.0; Debug.Assert(false); return double.NaN; } public double GenSizeAfterMB(Gens gen) { if (gen == Gens.GenLargeObj) return HeapStats.GenerationSize3 / 1000000.0; if (gen == Gens.Gen2) return HeapStats.GenerationSize2 / 1000000.0; if (gen == Gens.Gen1) return HeapStats.GenerationSize1 / 1000000.0; if (gen == Gens.Gen0) return HeapStats.GenerationSize0 / 1000000.0; Debug.Assert(false); return double.NaN; } // Per generation stats. public double GenSizeBeforeMB(Gens gen) { if (PerHeapHistories != null) { double ret = 0.0; for (int HeapIndex = 0; HeapIndex < PerHeapHistories.Count; HeapIndex++) ret += PerHeapGenData[HeapIndex][(int)gen].SizeBefore / 1000000.0; return ret; } // When we don't have perheap history we can only estimate for gen0 and gen3. double Gen0SizeBeforeMB = 0; if (gen == Gens.Gen0) Gen0SizeBeforeMB = AllocedSinceLastGCBasedOnAllocTickMB[0]; if (Index == 0) { return ((gen == Gens.Gen0) ? Gen0SizeBeforeMB : 0); } // Find a previous HeapStats. GCHeapStatsTraceData heapStats = null; for (int j = Index - 1; ; --j) { if (j == 0) return 0; heapStats = Events[j].HeapStats; if (heapStats != null) break; } if (gen == Gens.Gen0) return Math.Max((heapStats.GenerationSize0 / 1000000.0), Gen0SizeBeforeMB); if (gen == Gens.Gen1) return heapStats.GenerationSize1 / 1000000.0; if (gen == Gens.Gen2) return heapStats.GenerationSize2 / 1000000.0; Debug.Assert(gen == Gens.GenLargeObj); if (HeapStats != null) return Math.Max(heapStats.GenerationSize3, HeapStats.GenerationSize3) / 1000000.0; else return heapStats.GenerationSize3 / 1000000.0; } public void GetCondemnedReasons(Dictionary<CondemnedReasonGroup, int> ReasonsInfo) { // Older versions of the runtime does not have this event. So even for a complete GC, we may not have this // info. if (PerHeapCondemnedReasons == null) return; int HeapIndexHighestGen = 0; if (PerHeapCondemnedReasons.Length != 1) { HeapIndexHighestGen = FindFirstHighestCondemnedHeap(); } byte[] ReasonGroups = PerHeapCondemnedReasons[HeapIndexHighestGen].CondemnedReasonGroups; // These 2 reasons indicate a gen number. If the number is the same as the condemned gen, we // include this reason. for (int i = (int)CondemnedReasonGroup.CRG_Alloc_Exceeded; i <= (int)CondemnedReasonGroup.CRG_Time_Tuning; i++) { if (ReasonGroups[i] == GCGeneration) AddCondemnedReason(ReasonsInfo, (CondemnedReasonGroup)i); } if (ReasonGroups[(int)CondemnedReasonGroup.CRG_Induced] != 0) { if (ReasonGroups[(int)CondemnedReasonGroup.CRG_Initial_Generation] == GCGeneration) { AddCondemnedReason(ReasonsInfo, CondemnedReasonGroup.CRG_Induced); } } // The rest of the reasons are conditions so include the ones that are set. for (int i = (int)CondemnedReasonGroup.CRG_Low_Ephemeral; i < (int)CondemnedReasonGroup.CRG_Max; i++) { if (ReasonGroups[i] != 0) AddCondemnedReason(ReasonsInfo, (CondemnedReasonGroup)i); } } // // Approximations we do in this function for V4_5 and prior: // On 4.0 we didn't seperate free list from free obj, so we just use fragmentation (which is the sum) // as an approximation. This makes the efficiency value a bit larger than it actually is. // We don't actually update in for the older gen - this means we only know the out for the younger // gen which isn't necessarily all allocated into the older gen. So we could see cases where the // out is > 0, yet the older gen's free list doesn't change. Using the younger gen's out as an // approximation makes the efficiency value larger than it actually is. // // For V4_6 this requires no approximation. // public bool GetFreeListEfficiency(Gens gen, ref double Allocated, ref double FreeListConsumed) { // I am not worried about gen0 or LOH's free list efficiency right now - it's // calculated differently. if ((PerHeapHistories == null) || (gen == Gens.Gen0) || (gen == Gens.GenLargeObj) || (Index <= 0) || !(PerHeapHistories[0].VersionRecognized)) { return false; } int YoungerGen = (int)gen - 1; if (GCGeneration != YoungerGen) return false; if (PerHeapHistories[0].V4_6) { Allocated = 0; FreeListConsumed = 0; for (int HeapIndex = 0; HeapIndex < PerHeapHistories.Count; HeapIndex++) { GCPerHeapHistoryTraceData3 hist = (GCPerHeapHistoryTraceData3)PerHeapHistories[HeapIndex]; Allocated += hist.FreeListAllocated; FreeListConsumed += hist.FreeListAllocated + hist.FreeListRejected; } return true; } // I am not using MB here because what's promoted from gen1 can easily be less than a MB. double YoungerGenOut = 0; double FreeListBefore = 0; double FreeListAfter = 0; // Includes fragmentation. This lets us know if we had to expand the size. double GenSizeBefore = 0; double GenSizeAfter = 0; for (int HeapIndex = 0; HeapIndex < PerHeapHistories.Count; HeapIndex++) { YoungerGenOut += PerHeapGenData[HeapIndex][YoungerGen].Out; GenSizeBefore += PerHeapGenData[HeapIndex][(int)gen].SizeBefore; GenSizeAfter += PerHeapGenData[HeapIndex][(int)gen].SizeAfter; if (Version == PerHeapEventVersion.V4_0) { // Occasionally I've seen a GC in the middle that simply missed some events, // some of which are PerHeap hist events so we don't have data. if (Events[Index - 1].PerHeapGenData == null) return false; FreeListBefore += Events[Index - 1].PerHeapGenData[HeapIndex][(int)gen].Fragmentation; FreeListAfter += PerHeapGenData[HeapIndex][(int)gen].Fragmentation; } else { FreeListBefore += PerHeapGenData[HeapIndex][(int)gen].FreeListSpaceBefore; FreeListAfter += PerHeapGenData[HeapIndex][(int)gen].FreeListSpaceAfter; } } double GenSizeGrown = GenSizeAfter - GenSizeBefore; // This is the most accurate situation we can calculuate (if it's not accurate it means // we are over estimating which is ok. if ((GenSizeGrown == 0) && ((FreeListBefore > 0) && (FreeListAfter >= 0))) { Allocated = YoungerGenOut; FreeListConsumed = FreeListBefore - FreeListAfter; // We don't know how much of the survived is pinned so we are overestimating here. if (Allocated < FreeListConsumed) return true; } return false; } public void GetGenDataObjSizeAfterMB(ref double[] GenData) { for (int HeapIndex = 0; HeapIndex < PerHeapHistories.Count; HeapIndex++) { for (int GenIndex = 0; GenIndex <= (int)Gens.GenLargeObj; GenIndex++) GenData[GenIndex] += PerHeapGenData[HeapIndex][GenIndex].ObjSizeAfter / 1000000.0; } } public void GetGenDataSizeAfterMB(ref double[] GenData) { for (int GenIndex = 0; GenIndex <= (int)Gens.GenLargeObj; GenIndex++) GenData[GenIndex] = GenSizeAfterMB((Gens)GenIndex); } public double GetMaxGen0ObjSizeMB() { double MaxGen0ObjSize = 0; for (int HeapIndex = 0; HeapIndex < PerHeapHistories.Count; HeapIndex++) { MaxGen0ObjSize = Math.Max(MaxGen0ObjSize, PerHeapGenData[HeapIndex][(int)Gens.Gen0].ObjSizeAfter / 1000000.0); } return MaxGen0ObjSize; } // This represents the percentage time spent paused for this GC since the last GC completed. public double GetPauseTimePercentageSinceLastGC() { double pauseTimePercentage; if (Type == GCType.BackgroundGC) { // Find all GCs that occurred during the current background GC. double startTimeRelativeMSec = this.GCStartRelativeMSec; double endTimeRelativeMSec = this.GCStartRelativeMSec + this.GCDurationMSec; // Calculate the pause time for this BGC. // Pause time is defined as pause time for the BGC + pause time for all FGCs that ran during the BGC. double totalPauseTime = this.PauseDurationMSec; if (Index + 1 < Events.Count) { GCEvent gcEvent; for (int i = Index + 1; i < Events.Count; ++i) { gcEvent = Events[i]; if ((gcEvent.GCStartRelativeMSec >= startTimeRelativeMSec) && (gcEvent.GCStartRelativeMSec < endTimeRelativeMSec)) { totalPauseTime += gcEvent.PauseDurationMSec; } else { // We've finished processing all FGCs that occurred during this BGC. break; } } } // Get the elapsed time since the previous GC finished. int previousGCIndex = Index - 1; double previousGCStopTimeRelativeMSec; if (previousGCIndex >= 0) { GCEvent previousGCEvent = Events[previousGCIndex]; previousGCStopTimeRelativeMSec = previousGCEvent.GCStartRelativeMSec + previousGCEvent.GCDurationMSec; } else { // Backstop in case this is the first GC. previousGCStopTimeRelativeMSec = Events[0].GCStartRelativeMSec; } double totalTime = (GCStartRelativeMSec + GCDurationMSec) - previousGCStopTimeRelativeMSec; pauseTimePercentage = (totalPauseTime * 100) / (totalTime); } else { double totalTime = PauseDurationMSec + DurationSinceLastRestartMSec; pauseTimePercentage = (PauseDurationMSec * 100) / (totalTime); } Debug.Assert(pauseTimePercentage <= 100); return pauseTimePercentage; } public int GetPinnedObjectPercentage() { if (totalPinnedPlugSize == -1) { totalPinnedPlugSize = 0; totalUserPinnedPlugSize = 0; foreach (KeyValuePair<ulong, long> item in PinnedObjects) { ulong Address = item.Key; for (int i = 0; i < PinnedPlugs.Count; i++) { if ((Address >= PinnedPlugs[i].Start) && (Address < PinnedPlugs[i].End)) { PinnedPlugs[i].PinnedByUser = true; break; } } } for (int i = 0; i < PinnedPlugs.Count; i++) { long Size = (long)(PinnedPlugs[i].End - PinnedPlugs[i].Start); totalPinnedPlugSize += Size; if (PinnedPlugs[i].PinnedByUser) { totalUserPinnedPlugSize += Size; } } } return ((totalPinnedPlugSize == 0) ? -1 : (int)((double)pinnedObjectSizes * 100 / (double)totalPinnedPlugSize)); } public long GetPinnedObjectSizes() { if (pinnedObjectSizes == -1) { pinnedObjectSizes = 0; foreach (KeyValuePair<ulong, long> item in PinnedObjects) { pinnedObjectSizes += item.Value; } } return pinnedObjectSizes; } public double GetTotalGCTime() { if (_TotalGCTimeMSec < 0) { _TotalGCTimeMSec = 0; if (GCCpuServerGCThreads != null) { for (int i = 0; i < GCCpuServerGCThreads.Length; i++) { _TotalGCTimeMSec += GCCpuServerGCThreads[i]; } } _TotalGCTimeMSec += GCCpuMSec; } Debug.Assert(_TotalGCTimeMSec >= 0); return _TotalGCTimeMSec; } /// <summary> /// Get what's allocated into gen0 or gen3. For server GC this gets the total for /// all heaps. /// </summary> public double GetUserAllocated(Gens gen) { Debug.Assert((gen == Gens.Gen0) || (gen == Gens.GenLargeObj)); if ((Type == GCType.BackgroundGC) && (gen == Gens.Gen0)) { return AllocedSinceLastGCBasedOnAllocTickMB[(int)gen]; } if (PerHeapHistories != null && Index > 0 && Events[Index - 1].PerHeapHistories != null) { double TotalAllocated = 0; if (Index > 0) { for (int i = 0; i < PerHeapHistories.Count; i++) { double Allocated = GetUserAllocatedPerHeap(i, gen); TotalAllocated += Allocated / 1000000.0; } return TotalAllocated; } else { return GenSizeBeforeMB(gen); } } return AllocedSinceLastGCBasedOnAllocTickMB[(gen == Gens.Gen0) ? 0 : 1]; } public bool IsLowEphemeral() { return CondemnedReasonGroupSet(CondemnedReasonGroup.CRG_Low_Ephemeral); } public bool IsNotCompacting() { return ((GlobalHeapHistory.GlobalMechanisms & (GCGlobalMechanisms.Compaction)) != 0); } public double ObjSizeAfter(Gens gen) { double TotalObjSizeAfter = 0; if (PerHeapHistories != null) { for (int i = 0; i < PerHeapHistories.Count; i++) { TotalObjSizeAfter += PerHeapGenData[i][(int)gen].ObjSizeAfter; } } return TotalObjSizeAfter; } // Set in HeapStats public void SetHeapCount(int count) { if (heapCount == -1) { heapCount = count; } } public void SetUpServerGcHistory() { for (int i = 0; i < heapCount; i++) { int gcThreadId = 0; int gcThreadPriority = 0; Parent.ServerGcHeap2ThreadId.TryGetValue(i, out gcThreadId); Parent.ThreadId2Priority.TryGetValue(gcThreadId, out gcThreadPriority); ServerGcHeapHistories.Add(new ServerGcHistory { Parent = this, ProcessId = Parent.ProcessID, HeapId = i, GcWorkingThreadId = gcThreadId, GcWorkingThreadPriority = gcThreadPriority }); } } public double SurvivalPercent(Gens gen) { double retSurvRate = double.NaN; long SurvRate = 0; if (gen == Gens.GenLargeObj) { if (GCGeneration < 2) { return retSurvRate; } } else if ((int)gen > GCGeneration) { return retSurvRate; } if (PerHeapHistories != null) { for (int i = 0; i < PerHeapHistories.Count; i++) { SurvRate += PerHeapGenData[i][(int)gen].SurvRate; } SurvRate /= PerHeapHistories.Count; } retSurvRate = SurvRate; return retSurvRate; } #endregion #region Internal Methods internal void AddGcJoin(GCJoinTraceData data) { if (data.Heap >= 0 && data.Heap < ServerGcHeapHistories.Count) ServerGcHeapHistories[data.Heap].AddJoin(data); else { foreach (var heap in ServerGcHeapHistories) heap.AddJoin(data); } } #endregion #region Private Methods private void AddCondemnedReason(Dictionary<CondemnedReasonGroup, int> ReasonsInfo, CondemnedReasonGroup Reason) { if (!ReasonsInfo.ContainsKey(Reason)) ReasonsInfo.Add(Reason, 1); else (ReasonsInfo[Reason])++; } // For true/false groups, return whether that group is set. private bool CondemnedReasonGroupSet(CondemnedReasonGroup Group) { if (PerHeapCondemnedReasons == null) { return false; } int HeapIndexHighestGen = 0; if (PerHeapCondemnedReasons.Length != 1) { HeapIndexHighestGen = FindFirstHighestCondemnedHeap(); } return (PerHeapCondemnedReasons[HeapIndexHighestGen].CondemnedReasonGroups[(int)Group] != 0); } // We recorded these as the timestamps when we saw the mark events, now convert them // to the actual time that it took for each mark. private void ConvertMarkTimes() { if (PerHeapMarkTimes != null) { foreach (KeyValuePair<int, MarkInfo> item in PerHeapMarkTimes) { if (item.Value.MarkTimes[(int)MarkRootType.MarkSizedRef] == 0.0) item.Value.MarkTimes[(int)MarkRootType.MarkSizedRef] = GCStartRelativeMSec; if (GCGeneration == 2) item.Value.MarkTimes[(int)MarkRootType.MarkOlder] = 0; else item.Value.MarkTimes[(int)MarkRootType.MarkOlder] -= item.Value.MarkTimes[(int)MarkRootType.MarkHandles]; item.Value.MarkTimes[(int)MarkRootType.MarkHandles] -= item.Value.MarkTimes[(int)MarkRootType.MarkFQ]; item.Value.MarkTimes[(int)MarkRootType.MarkFQ] -= item.Value.MarkTimes[(int)MarkRootType.MarkStack]; item.Value.MarkTimes[(int)MarkRootType.MarkStack] -= item.Value.MarkTimes[(int)MarkRootType.MarkSizedRef]; item.Value.MarkTimes[(int)MarkRootType.MarkSizedRef] -= GCStartRelativeMSec; } } } // When survival rate is 0, for certain releases (see comments for GetUserAllocatedPerHeap) // we need to estimate. private double EstimateAllocSurv0(int HeapIndex, Gens gen) { if (HasAllocTickEvents) { return AllocedSinceLastGCBasedOnAllocTickMB[(gen == Gens.Gen0) ? 0 : 1]; } else { if (Index > 0) { // If the prevous GC has that heap get its size. var perHeapGenData = Events[Index - 1].PerHeapGenData; if (HeapIndex < perHeapGenData.Length) return perHeapGenData[HeapIndex][(int)gen].Budget; } return 0; } } private int FindFirstHighestCondemnedHeap() { int GenNumberHighest = (int)GCGeneration; for (int HeapIndex = 0; HeapIndex < PerHeapCondemnedReasons.Length; HeapIndex++) { int gen = PerHeapCondemnedReasons[HeapIndex].CondemnedReasonGroups[(int)CondemnedReasonGroup.CRG_Final_Generation]; if (gen == GenNumberHighest) { return HeapIndex; } } return 0; } /// <summary> /// For a given heap, get what's allocated into gen0 or gen3. /// We calculate this differently on 4.0, 4.5 Beta and 4.5 RC+. /// The caveat with 4.0 and 4.5 Beta is that when survival rate is 0, /// We don't know how to calculate the allocated - so we just use the /// last GC's budget (We should indicate this in the tool) /// </summary> private double GetUserAllocatedPerHeap(int HeapIndex, Gens gen) { long prevObjSize = 0; if (Index > 0) { // If the prevous GC has that heap get its size. var perHeapGenData = Events[Index - 1].PerHeapGenData; if (HeapIndex < perHeapGenData.Length) prevObjSize = perHeapGenData[HeapIndex][(int)gen].ObjSizeAfter; } GCPerHeapHistoryGenData currentGenData = PerHeapGenData[HeapIndex][(int)gen]; long survRate = currentGenData.SurvRate; long currentObjSize = currentGenData.ObjSizeAfter; double Allocated; if (Version == PerHeapEventVersion.V4_0) { if (survRate == 0) Allocated = EstimateAllocSurv0(HeapIndex, gen); else Allocated = (currentGenData.Out + currentObjSize) * 100 / survRate - prevObjSize; } else { Allocated = currentGenData.ObjSpaceBefore - prevObjSize; } return Allocated; } private void GetVersion() { if (Version == PerHeapEventVersion.V0) { if (PerHeapHistories[0].V4_0) Version = PerHeapEventVersion.V4_0; else if (PerHeapHistories[0].V4_5) { Version = PerHeapEventVersion.V4_5; Debug.Assert(PerHeapHistories[0].Version == 2); } else { Version = PerHeapEventVersion.V4_6; Debug.Assert(PerHeapHistories[0].Version == 3); } } } #endregion #region Inner Private Structs private struct EncodedCondemnedReasons { public int Reasons; public int ReasonsEx; } #endregion #region Inner Public Classes public class MarkInfo { public long[] MarkPromoted; // Note that in 4.5 and prior (ie, from GCMark events, not GCMarkWithType), the first stage of the time // includes scanning sizedref handles(which can be very significant). We could distinguish that by interpreting // the Join events which I haven't done yet. public double[] MarkTimes; public MarkInfo(bool initPromoted = true) { MarkTimes = new double[(int)MarkRootType.MarkMax]; if (initPromoted) MarkPromoted = new long[(int)MarkRootType.MarkMax]; } }; public class PinnedPlug { public ulong End; public bool PinnedByUser; public ulong Start; public PinnedPlug(ulong s, ulong e) { Start = s; End = e; PinnedByUser = false; } }; public class ServerGcHistory { public int GcWorkingThreadId; public int GcWorkingThreadPriority; public int HeapId; public GCEvent Parent; public int ProcessId; public List<GcWorkSpan> SampleSpans = new List<GcWorkSpan>(); public List<GcWorkSpan> SwitchSpans = new List<GcWorkSpan>(); //list of times in msc starting from GC start when GCJoin events were fired for this heap private List<GcJoin> GcJoins = new List<GcJoin>(); public enum WorkSpanType { GcThread, RivalThread, LowPriThread, Idle } public double TimeBaseMsc { get { return Parent.PauseStartRelativeMSec; } } public void AddSampleEvent(ThreadWorkSpan sample) { GcWorkSpan lastSpan = SampleSpans.Count > 0 ? SampleSpans[SampleSpans.Count - 1] : null; if (lastSpan != null && lastSpan.ThreadId == sample.ThreadId && lastSpan.ProcessId == sample.ProcessId) { lastSpan.DurationMsc++; } else { SampleSpans.Add(new GcWorkSpan(sample) { Type = GetSpanType(sample), RelativeTimestampMsc = sample.AbsoluteTimestampMsc - TimeBaseMsc, DurationMsc = 1 }); } } public void AddSwitchEvent(ThreadWorkSpan switchData) { GcWorkSpan lastSpan = SwitchSpans.Count > 0 ? SwitchSpans[SwitchSpans.Count - 1] : null; if (switchData.ThreadId == GcWorkingThreadId && switchData.ProcessId == ProcessId) { //update gc thread priority since we have new data GcWorkingThreadPriority = switchData.Priority; } if (lastSpan != null) { //updating duration of the last one, based on a timestamp from the new one lastSpan.DurationMsc = switchData.AbsoluteTimestampMsc - lastSpan.AbsoluteTimestampMsc; //updating wait readon of the last one lastSpan.WaitReason = switchData.WaitReason; } SwitchSpans.Add(new GcWorkSpan(switchData) { Type = GetSpanType(switchData), RelativeTimestampMsc = switchData.AbsoluteTimestampMsc - TimeBaseMsc, Priority = switchData.Priority }); } internal void AddJoin(GCJoinTraceData data) { GcJoins.Add(new GcJoin { Heap = data.ProcessorNumber, //data.Heap is not reliable for reset events, so we use ProcessorNumber AbsoluteTimestampMsc = data.TimeStampRelativeMSec, RelativeTimestampMsc = data.TimeStampRelativeMSec - Parent.PauseStartRelativeMSec, Type = data.JoinType, Time = data.JoinTime, }); } internal void GCEnd() { GcWorkSpan lastSpan = SwitchSpans.Count > 0 ? SwitchSpans[SwitchSpans.Count - 1] : null; if (lastSpan != null) { lastSpan.DurationMsc = Parent.PauseDurationMSec - lastSpan.RelativeTimestampMsc; } } private WorkSpanType GetSpanType(ThreadWorkSpan span) { if (span.ThreadId == GcWorkingThreadId && span.ProcessId == ProcessId) return WorkSpanType.GcThread; if (span.ProcessId == 0) return WorkSpanType.Idle; if (span.Priority >= GcWorkingThreadPriority || span.Priority == -1) return WorkSpanType.RivalThread; else return WorkSpanType.LowPriThread; } public class GcJoin { public double AbsoluteTimestampMsc; public int Heap; public double RelativeTimestampMsc; public GcJoinTime Time; public GcJoinType Type; } public class GcWorkSpan : ThreadWorkSpan { public double RelativeTimestampMsc; public WorkSpanType Type; public GcWorkSpan(ThreadWorkSpan span) : base(span) { } } } #endregion #region Inner Private Classes private class GCCondemnedReasons { /// <summary> /// This records which reasons are used and the value. Since the biggest value /// we need to record is the generation number a byte is sufficient. /// </summary> public byte[] CondemnedReasonGroups; public EncodedCondemnedReasons EncodedReasons; #if HAS_PRIVATE_GC_EVENTS public Dictionary<int, BGCAllocWaitInfo> LOHWaitThreads; #endif enum Condemned_Reason_Condition { CRC_induced_fullgc_p = 0, CRC_expand_fullgc_p = 1, CRC_high_mem_p = 2, CRC_very_high_mem_p = 3, CRC_low_ephemeral_p = 4, CRC_low_card_p = 5, CRC_eph_high_frag_p = 6, CRC_max_high_frag_p = 7, CRC_max_high_frag_e_p = 8, CRC_max_high_frag_m_p = 9, CRC_max_high_frag_vm_p = 10, CRC_max_gen1 = 11, CRC_before_oom = 12, CRC_gen2_too_small = 13, CRC_induced_noforce_p = 14, CRC_before_bgc = 15, CRC_max = 16, }; // These values right now are the same as the first 4 in CondemnedReasonGroup. enum Condemned_Reason_Generation { CRG_initial = 0, CRG_final_per_heap = 1, CRG_alloc_budget = 2, CRG_time_tuning = 3, CRG_max = 4, }; public void Decode(PerHeapEventVersion Version) { // First decode the reasons that return us a generation number. // It's the same in 4.0 and 4.5. for (Condemned_Reason_Generation i = 0; i < Condemned_Reason_Generation.CRG_max; i++) { CondemnedReasonGroups[(int)i] = (byte)GetReasonWithGenNumber(i); } // Then decode the reasons that just indicate true or false. for (Condemned_Reason_Condition i = 0; i < Condemned_Reason_Condition.CRC_max; i++) { if (GetReasonWithCondition(i, Version)) { switch (i) { case Condemned_Reason_Condition.CRC_induced_fullgc_p: CondemnedReasonGroups[(int)CondemnedReasonGroup.CRG_Induced] = (byte)InducedType.Blocking; break; case Condemned_Reason_Condition.CRC_induced_noforce_p: CondemnedReasonGroups[(int)CondemnedReasonGroup.CRG_Induced] = (byte)InducedType.NotForced; break; case Condemned_Reason_Condition.CRC_low_ephemeral_p: CondemnedReasonGroups[(int)CondemnedReasonGroup.CRG_Low_Ephemeral] = 1; break; case Condemned_Reason_Condition.CRC_low_card_p: CondemnedReasonGroups[(int)CondemnedReasonGroup.CRG_Internal_Tuning] = 1; break; case Condemned_Reason_Condition.CRC_eph_high_frag_p: CondemnedReasonGroups[(int)CondemnedReasonGroup.CRG_Fragmented_Ephemeral] = 1; break; case Condemned_Reason_Condition.CRC_max_high_frag_p: CondemnedReasonGroups[(int)CondemnedReasonGroup.CRG_Fragmented_Gen2] = 1; break; case Condemned_Reason_Condition.CRC_max_high_frag_e_p: CondemnedReasonGroups[(int)CondemnedReasonGroup.CRG_Fragmented_Gen1_To_Gen2] = 1; break; case Condemned_Reason_Condition.CRC_max_high_frag_m_p: case Condemned_Reason_Condition.CRC_max_high_frag_vm_p: CondemnedReasonGroups[(int)CondemnedReasonGroup.CRG_Fragmented_Gen2_High_Mem] = 1; break; case Condemned_Reason_Condition.CRC_max_gen1: CondemnedReasonGroups[(int)CondemnedReasonGroup.CRG_Alloc_Exceeded] = 2; break; case Condemned_Reason_Condition.CRC_expand_fullgc_p: CondemnedReasonGroups[(int)CondemnedReasonGroup.CRG_Expand_Heap] = 1; break; case Condemned_Reason_Condition.CRC_before_oom: CondemnedReasonGroups[(int)CondemnedReasonGroup.CRG_GC_Before_OOM] = 1; break; case Condemned_Reason_Condition.CRC_gen2_too_small: CondemnedReasonGroups[(int)CondemnedReasonGroup.CRG_Too_Small_For_BGC] = 1; break; case Condemned_Reason_Condition.CRC_before_bgc: CondemnedReasonGroups[(int)CondemnedReasonGroup.CRG_Ephemeral_Before_BGC] = 1; break; default: Debug.Assert(false, "Unexpected reason"); break; } } } } private bool GetReasonWithCondition(Condemned_Reason_Condition Reason_Condition, PerHeapEventVersion Version) { bool ConditionIsSet = false; if (Version == PerHeapEventVersion.V4_0) { Debug.Assert((int)Reason_Condition < 16); ConditionIsSet = ((EncodedReasons.Reasons & (1 << (int)(Reason_Condition + 16))) != 0); } else { ConditionIsSet = ((EncodedReasons.ReasonsEx & (1 << (int)Reason_Condition)) != 0); } return ConditionIsSet; } private int GetReasonWithGenNumber(Condemned_Reason_Generation Reason_GenNumber) { int GenNumber = ((EncodedReasons.Reasons >> ((int)Reason_GenNumber * 2)) & 0x3); return GenNumber; } } #endregion } } #endif
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Windows.Forms; using bv.common; using bv.common.Core; using bv.common.Enums; using bv.common.Objects; using bv.common.win; using eidss.model.Enums; namespace EIDSS { public class FreezerTree : BaseDetailForm { private TreeView treeFreezer; private IContainer components = null; private ImageList SelectImageList; private bool isClickable = false; //public string selected = ""; // private bool expandflag = false; public FreezerTree() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); base.DbService = new FreezerTree_DB(); AuditObject = new AuditObject((long) EIDSSAuditObject.daoRepositoryScheme, (long) AuditTable.tlbFreezer); PermissionObject = EIDSSPermissionObject.RepositoryScheme; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } public override object GetKey(string aTableName = null, string aKeyFieldName = null) { var ret = base.GetKey(aTableName, aKeyFieldName); TreeNode treeNode = treeFreezer.SelectedNode; if (treeNode != null) { var row = (treeNode.Tag as DataRow); if (row != null) { return row["ID"]; } } return ret; } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FreezerTree)); this.treeFreezer = new System.Windows.Forms.TreeView(); this.SelectImageList = new System.Windows.Forms.ImageList(); this.SuspendLayout(); bv.common.Resources.BvResourceManagerChanger.GetResourceManager(typeof(FreezerTree), out resources); // Form Is Localizable: True // // treeFreezer // resources.ApplyResources(this.treeFreezer, "treeFreezer"); this.treeFreezer.ItemHeight = 16; this.treeFreezer.Name = "treeFreezer"; this.treeFreezer.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeFreezer_AfterSelect); this.treeFreezer.DoubleClick += new System.EventHandler(this.treeFreezer_DoubleClick); // // SelectImageList // this.SelectImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("SelectImageList.ImageStream"))); this.SelectImageList.TransparentColor = System.Drawing.Color.Transparent; this.SelectImageList.Images.SetKeyName(0, ""); this.SelectImageList.Images.SetKeyName(1, ""); this.SelectImageList.Images.SetKeyName(2, ""); // // FreezerTree // resources.ApplyResources(this, "$this"); this.Controls.Add(this.treeFreezer); this.DefaultFormState = System.Windows.Forms.FormWindowState.Normal; this.FormID = "L28"; this.HelpTopicID = "lab_l02"; this.LeftIcon = ((System.Drawing.Image)(resources.GetObject("$this.LeftIcon"))); this.Name = "FreezerTree"; this.ShowDeleteButton = false; this.ShowSaveButton = false; this.Status = bv.common.win.FormStatus.Draft; this.Controls.SetChildIndex(this.treeFreezer, 0); this.ResumeLayout(false); } #endregion protected override void RefreshLayout() { DataTable treeTable; // DataView dataView; // DataView view; // DataRow row; // string filter; base.RefreshLayout(); treeTable = baseDataSet.Tables["ContainerTree"]; if (treeTable == null) { throw new ApplicationException("Invalid dataset."); } var view = new DataView(treeTable); FillNode(view, null); //this.FillTree(view, false, this.selected); } private string NodeText(string nodeName, string nodeBarcode, object used, object total) { string ret = nodeName; if (nodeBarcode.Length > 0) { ret += " - " + nodeBarcode; } if (!Utils.IsEmpty(total)) { ret += " " + used + "/" + total; } return ret; } private void FillNode(DataView view, TreeNode parent) { string filter; if (parent == null) { filter = "idfParentSubdivision is null"; } else { filter = "idfParentSubdivision=" + ((DataRow) (parent.Tag))["ID"]; } view.RowFilter = filter; var list = new List<TreeNode>(); foreach (DataRowView row in view) { var current = new TreeNode(NodeText(row["Path"].ToString(), row["SubdivisionBarcode"].ToString(), row["intUsed"], row["intCapacity"])); current.SelectedImageIndex = current.ImageIndex = (parent == null ? 0 : 1); current.Tag = row.Row; if (parent == null) { treeFreezer.Nodes.Add(current); } else { parent.Nodes.Add(current); } if (row["ID"].ToString() == Utils.Str(DbService.ID)) { treeFreezer.SelectedNode = current; } list.Add(current); } foreach (TreeNode node in list) { FillNode(view, node); } if (parent != null) { parent.Expand(); } } // copy-pasted from VialTransferDetail // /* private void FillTree(DataView treeTable, bool withContainers, string selectedID) { TreeNode treeNode = null; TreeNode parentNode = null; TreeNode focusNode = null; DataRow row = null; this.treeFreezer.Nodes.Clear(); if(treeTable == null) { throw new ApplicationException("Invalid dataset"); } // this.expandflag = true; foreach (DataRowView rowView in treeTable) { parentNode = null; row = rowView.Row; // freezer parentNode = this.FindNode(this.treeFreezer.Nodes, "idfFreezer", row["idfFreezer"].ToString()); if (parentNode == null){ treeNode = new TreeNode(NodeText(row["strFreezerName"].ToString(), row["FreezerBarcode"].ToString(), row["intUsed"], row["intCapacity"])); treeNode.ImageIndex = 0; treeNode.SelectedImageIndex = 0; treeNode.Tag = row; this.treeFreezer.Nodes.Add(treeNode); parentNode = treeNode; } // ParentSubdivision if (row.IsNull("idfParentsubDivision") == false) { treeNode = this.FindNode(parentNode.Nodes, "idfSubdivision", row["idfParentsubDivision"].ToString()); if (treeNode == null) { treeNode = new TreeNode(NodeText(row["Subdivision_Name"].ToString(), row["Subdivision_Barcode"].ToString(),row["intUsed"],row["intCapacity"])); treeNode.ImageIndex = 1; treeNode.SelectedImageIndex = 1; treeNode.Tag = row; parentNode.Nodes.Add(treeNode); } parentNode = treeNode; } // Subdivision if (row.IsNull("idfSubdivision") == false) { treeNode = this.FindNode(parentNode.Nodes, "idfSubdivision", row["idfSubdivision"].ToString()); if (treeNode == null) { treeNode = new TreeNode(NodeText(row["SubdivisionName"].ToString(), row["SubdivisionBarcode"].ToString(), row["intUsed"], row["intCapacity"])); treeNode.ImageIndex = 1; treeNode.SelectedImageIndex = 1; treeNode.Tag = row; parentNode.Nodes.Add(treeNode); if ((selectedID.Length > 0) && (selectedID.ToLower(System.Globalization.CultureInfo.InvariantCulture).CompareTo(row["idfSubdivision"].ToString().ToLower()) == 0)) { focusNode = treeNode; } } parentNode = treeNode; } // Container } if ((focusNode == null) && (this.treeFreezer.Nodes.Count > 0)) { focusNode = this.treeFreezer.Nodes[0]; foreach (TreeNode trNode in this.treeFreezer.Nodes) { trNode.Expand(); } } if (focusNode != null) { focusNode.EnsureVisible(); this.treeFreezer.SelectedNode = focusNode; } // Switch off expand control // this.expandflag = false; } // copy-pasted from VialTransferDetail // private TreeNode FindNode(TreeNodeCollection nodes, string field, string Id) { DataRow row = null; TreeNode returnNode = null; foreach(TreeNode node in nodes) { row = node.Tag as DataRow; if (row != null) { if (row[field].ToString().ToLower(System.Globalization.CultureInfo.InvariantCulture).CompareTo(Id.ToLower(System.Globalization.CultureInfo.InvariantCulture)) == 0) { returnNode = node; break; } if (node.Nodes.Count > 0) { returnNode = this.FindNode(node.Nodes, field, Id); if (returnNode != null) { break; } } } } return returnNode; } */ public new DataRow GetCurrentRow(string aTableName) { TreeNode treeNode = treeFreezer.SelectedNode; if (treeNode == null) { return null; } return treeNode.Tag as DataRow; } public override DataRow[] GetSelectedRows() { TreeNode treeNode; DataRow dataRow; treeNode = treeFreezer.SelectedNode; if ((treeNode == null) && (treeNode.Tag as DataRow == null)) { throw new ApplicationException("Ivalid item selected"); } dataRow = treeNode.Tag as DataRow; return (new DataRow[] {dataRow}); } private void treeFreezer_DoubleClick(object sender, EventArgs e) { if (isClickable) { if (BusinessObjectState.SelectObject > 0) { if (Post()) { DoOk(); } } } } public override bool Post(PostType postType = PostType.FinalPosting) { base.Post(postType); m_PromptResult = DialogResult.Yes; return true; } private void treeFreezer_AfterSelect(object sender, TreeViewEventArgs e) { SetIsClickable((DataRow) e.Node.Tag); OkButton.Enabled = isClickable; } private void SetIsClickable(DataRow e) { DataRow row = e; object u = row["intUsed"]; object t = row["intCapacity"]; int used = Utils.IsEmpty(u) ? 0 : (int) u; int total = Utils.IsEmpty(t) ? 0 : (int) t; isClickable = //row["ID"].ToString()==Utils.Str(this.DbService.ID) || (Utils.IsEmpty(row["idfSubdivision"]) == false && used < total); } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. using System.IO; using System.Text; using System.Globalization; using Xunit; using System.Collections; using System.Collections.Generic; namespace System.Json.Tests { public class JsonValueTests { [Fact] public void JsonValue_Load_LoadWithTrailingCommaInDictionary() { Parse("{ \"a\": \"b\",}", value => { Assert.Equal(1, value.Count); Assert.Equal(JsonType.String, value["a"].JsonType); Assert.Equal("b", value["a"]); JsonValue.Parse("[{ \"a\": \"b\",}]"); }); } [Theory] [InlineData("[]")] [InlineData(" \t \r \n [ \t \r \n ] \t \r \n ")] public void Parse_EmptyArray(string jsonString) { Parse(jsonString, value => { Assert.Equal(0, value.Count); Assert.Equal(JsonType.Array, value.JsonType); }); } [Theory] [InlineData("{}")] [InlineData(" \t \r \n { \t \r \n } \t \r \n ")] public void Parse_EmptyDictionary(string jsonString) { Parse(jsonString, value => { Assert.Equal(0, value.Count); Assert.Equal(JsonType.Object, value.JsonType); }); } public static IEnumerable<object[]> ParseIntegralBoundaries_TestData() { yield return new object[] { "2147483649", "2147483649" }; yield return new object[] { "4294967297", "4294967297" }; yield return new object[] { "9223372036854775807", "9223372036854775807" }; yield return new object[] { "18446744073709551615", "18446744073709551615" }; yield return new object[] { "79228162514264337593543950336", "7.9228162514264338E+28" }; } [Theory] [MemberData(nameof(ParseIntegralBoundaries_TestData))] public void Parse_IntegralBoundaries_LessThanMaxDouble_Works(string jsonString, string expectedToString) { Parse(jsonString, value => { Assert.Equal(JsonType.Number, value.JsonType); Assert.Equal(expectedToString, value.ToString()); }); } [Fact] public void Parse_TrueFalse() { Parse("[true, false]", value => { Assert.Equal(2, value.Count); Assert.Equal("true", value[0].ToString()); Assert.Equal("false", value[1].ToString()); }); } [Fact] public void JsonValue_Load_ToString_JsonArrayWithNulls() { Parse("[1,2,3,null]", value => { Assert.Equal(4, value.Count); Assert.Equal(JsonType.Array, value.JsonType); Assert.Equal("[1, 2, 3, null]", value.ToString()); ((JsonArray) value).Add(null); Assert.Equal("[1, 2, 3, null, null]", value.ToString()); }); } [Fact] public void JsonValue_ToString_JsonObjectWithNulls() { Parse("{\"a\":null,\"b\":2}", value => { Assert.Equal(2, value.Count); Assert.Equal(JsonType.Object, value.JsonType); Assert.Equal("{\"a\": null, \"b\": 2}", value.ToString()); }); } [Fact] public void JsonObject_ToString_OrderingMaintained() { var obj = new JsonObject(); obj["a"] = 1; obj["c"] = 3; obj["b"] = 2; Assert.Equal("{\"a\": 1, \"b\": 2, \"c\": 3}", obj.ToString()); } [Fact] public void JsonPrimitive_QuoteEscape() { Assert.Equal((new JsonPrimitive("\"\"")).ToString(), "\"\\\"\\\"\""); } [Fact] public void Load_NullStream_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("stream", () => JsonValue.Load((Stream)null)); } [Fact] public void Load_NullTextReader_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("textReader", () => JsonValue.Load((TextReader)null)); } [Fact] public void Parse_NullJsonString_ThrowArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("jsonString", () => JsonValue.Parse(null)); } [Theory] [InlineData("")] [InlineData("-")] [InlineData("- ")] [InlineData("1.")] [InlineData("1. ")] [InlineData("1e+")] [InlineData("1 2")] [InlineData("077")] [InlineData("[1,]")] [InlineData("NaN")] [InlineData("Infinity")] [InlineData("-Infinity")] [InlineData("[")] [InlineData("[1")] [InlineData("{")] [InlineData("{ ")] [InlineData("{1")] [InlineData("{\"")] [InlineData("{\"u")] [InlineData("{\"\\")] [InlineData("{\"\\u")] [InlineData("{\"\\uABC")] [InlineData("{\"\\/")] [InlineData("{\"\\\\")] [InlineData("{\"\\\"")] [InlineData("{\"\\!")] [InlineData("[tru]")] [InlineData("[fals]")] [InlineData("{\"name\"}")] [InlineData("{\"name\":}")] [InlineData("{\"name\":1")] [InlineData("1e")] [InlineData("1e-")] [InlineData("\0")] [InlineData("\u000B1")] [InlineData("\u000C1")] [InlineData("{\"\\a\"}")] [InlineData("{\"\\z\"}")] public void Parse_InvalidInput_ThrowsArgumentException(string value) { AssertExtensions.Throws<ArgumentException>(null, () => JsonValue.Parse(value)); using (StringReader textReader = new StringReader(value)) { AssertExtensions.Throws<ArgumentException>(null, () => JsonValue.Load(textReader)); } using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(value))) { AssertExtensions.Throws<ArgumentException>(null, () => JsonValue.Load(stream)); } } [Fact] public void Parse_DoubleTooLarge_ThrowsOverflowException() { Assert.Throws<OverflowException>(() => JsonValue.Parse("1.7976931348623157E+309")); } [Fact] public void Parse_InvalidNumericString_ThrowsFormatException() { Assert.Throws<FormatException>(() => JsonValue.Parse("1E!")); } [Theory] [InlineData("0", 0)] [InlineData("-0", 0)] [InlineData("0.00", 0)] [InlineData("-0.00", 0)] [InlineData("1", 1)] [InlineData("1.1", 1.1)] [InlineData("-1", -1)] [InlineData("-1.1", -1.1)] [InlineData("1e-10", 1e-10)] [InlineData("1e+10", 1e+10)] [InlineData("1e-30", 1e-30)] [InlineData("1e+30", 1e+30)] [InlineData("\"1\"", 1)] [InlineData("\"1.1\"", 1.1)] [InlineData("\"-1\"", -1)] [InlineData("\"-1.1\"", -1.1)] [InlineData("\"NaN\"", double.NaN)] [InlineData("\"Infinity\"", double.PositiveInfinity)] [InlineData("\"-Infinity\"", double.NegativeInfinity)] [InlineData("0.000000000000000000000000000011", 1.1E-29)] public void JsonValue_Parse_Double(string json, double expected) { foreach (string culture in new[] { "en", "fr", "de" }) { CultureInfo old = CultureInfo.CurrentCulture; try { CultureInfo.CurrentCulture = new CultureInfo(culture); Assert.Equal(expected, (double)JsonValue.Parse(json)); } finally { CultureInfo.CurrentCulture = old; } } } // Convert a number to json and parse the string, then compare the result to the original value [Theory] [InlineData(1)] [InlineData(1.1)] [InlineData(1.25)] [InlineData(-1)] [InlineData(-1.1)] [InlineData(-1.25)] [InlineData(1e-20)] [InlineData(1e+20)] [InlineData(1e-30)] [InlineData(1e+30)] [InlineData(3.1415926535897932384626433)] [InlineData(3.1415926535897932384626433e-20)] [InlineData(3.1415926535897932384626433e+20)] [InlineData(double.NaN)] [InlineData(double.PositiveInfinity)] [InlineData(double.NegativeInfinity)] [InlineData(double.MinValue)] [InlineData(double.MaxValue)] [InlineData(18014398509481982.0)] // A number which needs 17 digits (see http://stackoverflow.com/questions/6118231/why-do-i-need-17-significant-digits-and-not-16-to-represent-a-double) [InlineData(1.123456789e-29)] [InlineData(1.123456789e-28)] // Values around the smallest positive decimal value public void JsonValue_Parse_Double_ViaJsonPrimitive(double number) { foreach (string culture in new[] { "en", "fr", "de" }) { CultureInfo old = CultureInfo.CurrentCulture; try { CultureInfo.CurrentCulture = new CultureInfo(culture); Assert.Equal(number, (double)JsonValue.Parse(new JsonPrimitive(number).ToString())); } finally { CultureInfo.CurrentCulture = old; } } } [Fact] public void JsonValue_Parse_MinMax_Integers_ViaJsonPrimitive() { Assert.Equal(sbyte.MinValue, (sbyte)JsonValue.Parse(new JsonPrimitive(sbyte.MinValue).ToString())); Assert.Equal(sbyte.MaxValue, (sbyte)JsonValue.Parse(new JsonPrimitive(sbyte.MaxValue).ToString())); Assert.Equal(byte.MinValue, (byte)JsonValue.Parse(new JsonPrimitive(byte.MinValue).ToString())); Assert.Equal(byte.MaxValue, (byte)JsonValue.Parse(new JsonPrimitive(byte.MaxValue).ToString())); Assert.Equal(short.MinValue, (short)JsonValue.Parse(new JsonPrimitive(short.MinValue).ToString())); Assert.Equal(short.MaxValue, (short)JsonValue.Parse(new JsonPrimitive(short.MaxValue).ToString())); Assert.Equal(ushort.MinValue, (ushort)JsonValue.Parse(new JsonPrimitive(ushort.MinValue).ToString())); Assert.Equal(ushort.MaxValue, (ushort)JsonValue.Parse(new JsonPrimitive(ushort.MaxValue).ToString())); Assert.Equal(int.MinValue, (int)JsonValue.Parse(new JsonPrimitive(int.MinValue).ToString())); Assert.Equal(int.MaxValue, (int)JsonValue.Parse(new JsonPrimitive(int.MaxValue).ToString())); Assert.Equal(uint.MinValue, (uint)JsonValue.Parse(new JsonPrimitive(uint.MinValue).ToString())); Assert.Equal(uint.MaxValue, (uint)JsonValue.Parse(new JsonPrimitive(uint.MaxValue).ToString())); Assert.Equal(long.MinValue, (long)JsonValue.Parse(new JsonPrimitive(long.MinValue).ToString())); Assert.Equal(long.MaxValue, (long)JsonValue.Parse(new JsonPrimitive(long.MaxValue).ToString())); Assert.Equal(ulong.MinValue, (ulong)JsonValue.Parse(new JsonPrimitive(ulong.MinValue).ToString())); Assert.Equal(ulong.MaxValue, (ulong)JsonValue.Parse(new JsonPrimitive(ulong.MaxValue).ToString())); Assert.Equal("1E-30", JsonValue.Parse("1e-30").ToString()); Assert.Equal("1E+30", JsonValue.Parse("1e+30").ToString()); } [Theory] [InlineData("Fact\b\f\n\r\t\"\\/</\0x")] [InlineData("\ud800")] [InlineData("x\ud800")] [InlineData("\udfff\ud800")] [InlineData("\ude03\ud912")] [InlineData("\uc000\ubfff")] [InlineData("\udfffx")] public void JsonPrimitive_Roundtrip_ValidUnicode(string str) { string json = new JsonPrimitive(str).ToString(); new UTF8Encoding(false, true).GetBytes(json); Assert.Equal(str, JsonValue.Parse(json)); } [Fact] public void JsonPrimitive_Roundtrip_ValidUnicode_AllChars() { for (int i = 0; i <= char.MaxValue; i++) { JsonPrimitive_Roundtrip_ValidUnicode("x" + (char)i); } } // String handling: http://tools.ietf.org/html/rfc7159#section-7 [Fact] public void JsonPrimitive_StringHandling() { Assert.Equal("\"Fact\"", new JsonPrimitive("Fact").ToString()); // Handling of characters Assert.Equal("\"f\"", new JsonPrimitive('f').ToString()); Assert.Equal('f', (char)JsonValue.Parse("\"f\"")); // Control characters with special escape sequence Assert.Equal("\"\\b\\f\\n\\r\\t\"", new JsonPrimitive("\b\f\n\r\t").ToString()); // Other characters which must be escaped Assert.Equal(@"""\""\\""", new JsonPrimitive("\"\\").ToString()); // Control characters without special escape sequence for (int i = 0; i < 32; i++) { if (i != '\b' && i != '\f' && i != '\n' && i != '\r' && i != '\t') { Assert.Equal("\"\\u" + i.ToString("x04") + "\"", new JsonPrimitive("" + (char)i).ToString()); } } // JSON does not require U+2028 and U+2029 to be escaped, but // JavaScript does require this: // http://stackoverflow.com/questions/2965293/javascript-parse-error-on-u2028-unicode-character/9168133#9168133 Assert.Equal("\"\\u2028\\u2029\"", new JsonPrimitive("\u2028\u2029").ToString()); // '/' also does not have to be escaped, but escaping it when // preceeded by a '<' avoids problems with JSON in HTML <script> tags Assert.Equal("\"<\\/\"", new JsonPrimitive("</").ToString()); // Don't escape '/' in other cases as this makes the JSON hard to read Assert.Equal("\"/bar\"", new JsonPrimitive("/bar").ToString()); Assert.Equal("\"foo/bar\"", new JsonPrimitive("foo/bar").ToString()); // Valid strings should not be escaped: Assert.Equal("\"\ud7ff\"", new JsonPrimitive("\ud7ff").ToString()); Assert.Equal("\"\ue000\"", new JsonPrimitive("\ue000").ToString()); Assert.Equal("\"\ud800\udc00\"", new JsonPrimitive("\ud800\udc00").ToString()); Assert.Equal("\"\ud912\ude03\"", new JsonPrimitive("\ud912\ude03").ToString()); Assert.Equal("\"\udbff\udfff\"", new JsonPrimitive("\udbff\udfff").ToString()); Assert.Equal("\"{\\\"\\\\uD800\\\\uDC00\\\": 1}\"", new JsonPrimitive("{\"\\uD800\\uDC00\": 1}").ToString()); } [Fact] public void GetEnumerator_ThrowsInvalidOperationException() { JsonValue value = JsonValue.Parse("1"); Assert.Throws<InvalidOperationException>(() => ((IEnumerable)value).GetEnumerator()); } [Fact] public void Count_ThrowsInvalidOperationException() { JsonValue value = JsonValue.Parse("1"); Assert.Throws<InvalidOperationException>(() => value.Count); } [Fact] public void Item_Int_ThrowsInvalidOperationException() { JsonValue value = JsonValue.Parse("1"); Assert.Throws<InvalidOperationException>(() => value[0]); Assert.Throws<InvalidOperationException>(() => value[0] = 0); } [Fact] public void Item_String_ThrowsInvalidOperationException() { JsonValue value = JsonValue.Parse("1"); Assert.Throws<InvalidOperationException>(() => value["abc"]); Assert.Throws<InvalidOperationException>(() => value["abc"] = 0); } [Fact] public void ContainsKey_ThrowsInvalidOperationException() { JsonValue value = JsonValue.Parse("1"); Assert.Throws<InvalidOperationException>(() => value.ContainsKey("key")); } [Fact] public void Save_Stream() { JsonSubValue value = new JsonSubValue(); using (MemoryStream stream = new MemoryStream()) { value.Save(stream); string json = Encoding.UTF8.GetString(stream.ToArray()); Assert.True(stream.CanWrite); Assert.Equal("Hello", json); } } [Fact] public void Save_TextWriter() { JsonSubValue value = new JsonSubValue(); using (StringWriter writer = new StringWriter()) { value.Save(writer); string json = writer.ToString(); Assert.Equal("Hello", json); } } [Fact] public void Save_Null_ThrowsArgumentNullException() { JsonValue value = new JsonSubValue(); AssertExtensions.Throws<ArgumentNullException>("stream", () => value.Save((Stream)null)); } [Fact] public void ImplicitConversion_NullJsonValue_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("value", () => { bool i = (JsonValue)null; }); AssertExtensions.Throws<ArgumentNullException>("value", () => { byte i = (JsonValue)null; }); AssertExtensions.Throws<ArgumentNullException>("value", () => { char i = (JsonValue)null; }); AssertExtensions.Throws<ArgumentNullException>("value", () => { decimal i = (JsonValue)null; }); AssertExtensions.Throws<ArgumentNullException>("value", () => { double i = (JsonValue)null; }); AssertExtensions.Throws<ArgumentNullException>("value", () => { float i = (JsonValue)null; }); AssertExtensions.Throws<ArgumentNullException>("value", () => { int i = (JsonValue)null; }); AssertExtensions.Throws<ArgumentNullException>("value", () => { long i = (JsonValue)null; }); AssertExtensions.Throws<ArgumentNullException>("value", () => { sbyte i = (JsonValue)null; }); AssertExtensions.Throws<ArgumentNullException>("value", () => { short i = (JsonValue)null; }); AssertExtensions.Throws<ArgumentNullException>("value", () => { uint i = (JsonValue)null; }); AssertExtensions.Throws<ArgumentNullException>("value", () => { ulong i = (JsonValue)null; }); AssertExtensions.Throws<ArgumentNullException>("value", () => { ushort i = (JsonValue)null; }); AssertExtensions.Throws<ArgumentNullException>("value", () => { DateTime i = (JsonValue)null; }); AssertExtensions.Throws<ArgumentNullException>("value", () => { DateTimeOffset i = (JsonValue)null; }); AssertExtensions.Throws<ArgumentNullException>("value", () => { TimeSpan i = (JsonValue)null; }); AssertExtensions.Throws<ArgumentNullException>("value", () => { Guid i = (JsonValue)null; }); AssertExtensions.Throws<ArgumentNullException>("value", () => { Uri i = (JsonValue)null; }); } [Fact] public void ImplicitConversion_NotJsonPrimitive_ThrowsInvalidCastException() { Assert.Throws<InvalidCastException>(() => { bool i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { byte i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { char i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { decimal i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { double i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { float i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { int i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { long i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { sbyte i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { short i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { string i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { uint i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { ulong i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { ushort i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { DateTime i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { DateTimeOffset i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { TimeSpan i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { Guid i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { Uri i = new JsonArray(); }); } [Fact] public void ImplicitCast_Bool() { JsonPrimitive primitive = new JsonPrimitive(true); bool toPrimitive = primitive; Assert.True(toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Byte() { JsonPrimitive primitive = new JsonPrimitive(1); byte toPrimitive = primitive; Assert.Equal(1, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Char() { JsonPrimitive primitive = new JsonPrimitive(1); char toPrimitive = primitive; Assert.Equal(1, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Decimal() { JsonPrimitive primitive = new JsonPrimitive(1m); decimal toPrimitive = primitive; Assert.Equal(1m, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Double() { JsonPrimitive primitive = new JsonPrimitive(1); double toPrimitive = primitive; Assert.Equal(1.0, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Float() { JsonPrimitive primitive = new JsonPrimitive(1); float toPrimitive = primitive; Assert.Equal(1.0f, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Int() { JsonPrimitive primitive = new JsonPrimitive(1); int toPrimitive = primitive; Assert.Equal(1, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Long() { JsonPrimitive primitive = new JsonPrimitive(1); long toPrimitive = primitive; Assert.Equal(1, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_SByte() { JsonPrimitive primitive = new JsonPrimitive(1); sbyte toPrimitive = primitive; Assert.Equal(1, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Short() { JsonPrimitive primitive = new JsonPrimitive(1); short toPrimitive = primitive; Assert.Equal(1, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Theory] [InlineData("abc")] [InlineData(null)] public void ImplicitCast_String(string value) { JsonPrimitive primitive = new JsonPrimitive(value); string toPrimitive = primitive; Assert.Equal(value, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_String_NullString() { string toPrimitive = (JsonPrimitive)null; Assert.Equal(null, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(new JsonPrimitive((string)null), toPrimitive); } [Fact] public void ImplicitCast_UInt() { JsonPrimitive primitive = new JsonPrimitive(1); uint toPrimitive = primitive; Assert.Equal((uint)1, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_ULong() { JsonPrimitive primitive = new JsonPrimitive(1); ulong toPrimitive = primitive; Assert.Equal((ulong)1, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_UShort() { JsonPrimitive primitive = new JsonPrimitive(1); ushort toPrimitive = primitive; Assert.Equal((ushort)1, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_DateTime() { JsonPrimitive primitive = new JsonPrimitive(DateTime.MinValue); DateTime toPrimitive = primitive; Assert.Equal(DateTime.MinValue, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_DateTimeOffset() { JsonPrimitive primitive = new JsonPrimitive(DateTimeOffset.MinValue); DateTimeOffset toPrimitive = primitive; Assert.Equal(DateTimeOffset.MinValue, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_TimeSpan() { JsonPrimitive primitive = new JsonPrimitive(TimeSpan.Zero); TimeSpan toPrimitive = primitive; Assert.Equal(TimeSpan.Zero, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Guid() { JsonPrimitive primitive = new JsonPrimitive(new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)); Guid toPrimitive = primitive; Assert.Equal(new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Uri() { JsonPrimitive primitive = new JsonPrimitive(new Uri("scheme://host/")); Uri toPrimitive = primitive; Assert.Equal(new Uri("scheme://host/"), toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ToString_InvalidJsonType_ThrowsInvalidCastException() { InvalidJsonValue value = new InvalidJsonValue(); Assert.Throws<InvalidCastException>(() => value.ToString()); } private static void Parse(string jsonString, Action<JsonValue> action) { action(JsonValue.Parse(jsonString)); using (StringReader textReader = new StringReader(jsonString)) { action(JsonValue.Load(textReader)); } using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString))) { action(JsonValue.Load(stream)); } } public class JsonSubValue : JsonValue { public override JsonType JsonType => JsonType.String; public override void Save(TextWriter textWriter) => textWriter.Write("Hello"); } public class InvalidJsonValue : JsonValue { public override JsonType JsonType => (JsonType)(-1); } } }
using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.CompilerServices; using BudgetAnalyser.Engine.BankAccount; using BudgetAnalyser.Engine.Budget; namespace BudgetAnalyser.Engine.Statement { /// <summary> /// A bank statement transaction. /// </summary> /// <seealso cref="System.ComponentModel.INotifyPropertyChanged" /> /// <seealso cref="System.IComparable" /> /// <seealso cref="BudgetAnalyser.Engine.ICloneable{Transaction}" /> [SuppressMessage("Microsoft.Design", "CA1036:OverrideMethodsOnComparableTypes", Justification = "IComparable is implemented for sorting only. One transactions is not considered < or > than another. Also Equals is not overiden." )] public class Transaction : INotifyPropertyChanged, IComparable, ICloneable<Transaction> { private BudgetBucket budgetBucket; private Account doNotUseAccount; private decimal doNotUseAmount; private DateTime doNotUseDate; private string doNotUseDescription; private string doNotUseReference1; private string doNotUseReference2; private string doNotUseReference3; private TransactionType doNotUseTransactionType; /// <summary> /// Initializes a new instance of the <see cref="Transaction" /> class. /// </summary> public Transaction() { Id = Guid.NewGuid(); } /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets or sets the bank account that this transaction belongs in. /// </summary> public Account Account { get { return this.doNotUseAccount; } set { this.doNotUseAccount = value; OnPropertyChanged(); } } /// <summary> /// Gets or sets the transaction amount. /// </summary> public decimal Amount { get { return this.doNotUseAmount; } set { this.doNotUseAmount = value; OnPropertyChanged(); } } /// <summary> /// Gets or sets the budget bucket classification for this transaction. /// </summary> /// <exception cref="System.ArgumentNullException"> /// Setting a budget bucket to null when it already has a non-null value is /// not allowed. /// </exception> public BudgetBucket BudgetBucket { get { return this.budgetBucket; } set { if (value == null && this.budgetBucket != null) { throw new ArgumentNullException(nameof(value), "Setting a budget bucket to null when it already has a non-null value is not allowed."); } this.budgetBucket = value; OnPropertyChanged(); } } /// <summary> /// Gets or sets the transaction date. /// </summary> public DateTime Date { get { return this.doNotUseDate; } set { this.doNotUseDate = value; OnPropertyChanged(); } } /// <summary> /// Gets or sets the transaction description. /// </summary> public string Description { get { return this.doNotUseDescription; } set { this.doNotUseDescription = value; OnPropertyChanged(); } } /// <summary> /// The unique identifier for the transaction. Ideally this should not be public settable, but this is used during /// serialisation. /// </summary> public Guid Id { get; internal set; } /// <summary> /// Gets a value indicating whether this transaction is a suspected duplicate. /// </summary> /// <value> /// <c>true</c> if this transaction is suspected duplicate; otherwise, <c>false</c>. /// </value> public bool IsSuspectedDuplicate { get; internal set; } /// <summary> /// Gets or sets the transaction reference1. /// </summary> public string Reference1 { get { return this.doNotUseReference1; } set { this.doNotUseReference1 = value; OnPropertyChanged(); } } /// <summary> /// Gets or sets the transaction reference2. /// </summary> public string Reference2 { get { return this.doNotUseReference2; } set { this.doNotUseReference2 = value; OnPropertyChanged(); } } /// <summary> /// Gets or sets the transaction reference3. /// </summary> public string Reference3 { get { return this.doNotUseReference3; } set { this.doNotUseReference3 = value; OnPropertyChanged(); } } /// <summary> /// Gets or sets the type of the transaction. This is a type classification provided by the bank. /// </summary> public TransactionType TransactionType { get { return this.doNotUseTransactionType; } set { this.doNotUseTransactionType = value; OnPropertyChanged(); } } /// <summary> /// Clones this transaction into a new instance. /// </summary> public Transaction Clone() { return new Transaction { Account = Account, Amount = Amount, BudgetBucket = BudgetBucket, Date = Date, Description = Description, Reference1 = Reference1, Reference2 = Reference2, Reference3 = Reference3, TransactionType = TransactionType }; } /// <summary> /// Compare the transaction to the one provided. /// </summary> public int CompareTo(object obj) { var otherTransaction = obj as Transaction; if (otherTransaction == null) { return 1; } return Date.CompareTo(otherTransaction.Date); } /// <summary> /// Get a hash code that will indicate value based equivalence with another instance of <see cref="Transaction" />. /// <see cref="Object.GetHashCode" /> cannot be used because it is intended to show instance reference equivalence. It /// will give a different value (and it should) for every instance. If overriden changing hashcodes will cause problems /// with /// UI controls such as ListBox. /// </summary> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Following GetHashCode")] public int GetEqualityHashCode() { // WARNING: Do not add Bucket to this change detection. It will interfer with finding transactions and duplicate detection. unchecked { var result = 37; // prime result += Account.GetType().GetHashCode(); result *= 397; // also prime result += Amount.GetHashCode(); result *= 397; result += Date.GetHashCode(); result *= 397; if (!string.IsNullOrWhiteSpace(Description)) { result += Description.GetHashCode(); } result *= 397; if (!string.IsNullOrWhiteSpace(Reference1)) { result += Reference1.GetHashCode(); } result *= 397; if (!string.IsNullOrWhiteSpace(Reference2)) { result += Reference2.GetHashCode(); } result *= 397; if (!string.IsNullOrWhiteSpace(Reference3)) { result += Reference3.GetHashCode(); } result *= 397; result += TransactionType.GetHashCode(); result *= 397; return result; } } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns> /// A string that represents the current object. /// </returns> public override string ToString() { return string.Format(CultureInfo.CurrentUICulture, "Transaction: ({0} {1:N} {2} {3} {4} {5})", Date, Amount, Description, BudgetBucket?.Code, Reference1, Id); } private void OnPropertyChanged([CallerMemberName] string propertyName = null) { var handler = PropertyChanged; handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
#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 #region Imports using System.Globalization; using NUnit.Framework; using Rhino.Mocks; #endregion namespace Spring.Context.Support { [TestFixture] public sealed class AbstractMessageSourceTests : AbstractMessageSource { private MockRepository mocks; [SetUp] public void Init() { mocks = new MockRepository(); resetMe(); } [Test] [ExpectedException(typeof (NoSuchMessageException))] public void GetResolvableNullCodes() { IMessageSourceResolvable res = (IMessageSourceResolvable) mocks.CreateMock(typeof (IMessageSourceResolvable)); Expect.Call(res.GetCodes()).Return(null); Expect.Call(res.DefaultMessage).Return(null); mocks.ReplayAll(); GetMessage(res, CultureInfo.CurrentCulture); mocks.VerifyAll(); } [Test] public void GetResolvableDefaultsToParentMessageSource() { string MSGCODE = "nullCode"; object[] MSGARGS = new object[] { "arg1", "arg2" }; IMessageSourceResolvable res = (IMessageSourceResolvable)mocks.CreateMock(typeof(IMessageSourceResolvable)); Expect.Call(res.GetArguments()).Return(MSGARGS); Expect.Call(res.GetCodes()).Return(new string[] {MSGCODE}).Repeat.Once(); IMessageSource parentSource = (IMessageSource)mocks.CreateMock(typeof(IMessageSource)); Expect.Call(parentSource.GetMessage(MSGCODE, null, CultureInfo.CurrentCulture, MSGARGS)).Return( "MockMessageSource"); ParentMessageSource = parentSource; mocks.ReplayAll(); Assert.AreEqual("MockMessageSource", GetMessage(res, CultureInfo.CurrentCulture), "My Message"); mocks.VerifyAll(); } [Test] public void GetMessageParentMessageSource() { object[] args = new object[] {"arguments"}; IMessageSource parentSource = (IMessageSource)mocks.CreateMock(typeof(IMessageSource)); Expect.Call(parentSource.GetMessage("null", null, CultureInfo.CurrentCulture, args)).Return( "my parent message"); ParentMessageSource = parentSource; mocks.ReplayAll(); Assert.AreEqual("my parent message", GetMessage("null", "message", CultureInfo.CurrentCulture, args[0])); mocks.VerifyAll(); } [Test] public void GetMessageResolvableDefaultMessage() { IMessageSourceResolvable res = (IMessageSourceResolvable) mocks.CreateMock(typeof (IMessageSourceResolvable)); Expect.Call(res.DefaultMessage).Return("MyDefaultMessage").Repeat.AtLeastOnce(); Expect.Call(res.GetCodes()).Return(null); Expect.Call(res.GetArguments()).Return(null); mocks.ReplayAll(); Assert.AreEqual("MyDefaultMessage", GetMessage(res, CultureInfo.CurrentCulture), "Default"); mocks.VerifyAll(); } [Test] public void GetMessageResolvableReturnsFirstCode() { IMessageSourceResolvable res = (IMessageSourceResolvable)mocks.CreateMock(typeof(IMessageSourceResolvable)); Expect.Call(res.DefaultMessage).Return(null).Repeat.AtLeastOnce(); Expect.Call(res.GetCodes()).Return(new string[] {"null"}); Expect.Call(res.GetArguments()).Return(null).Repeat.AtLeastOnce(); mocks.ReplayAll(); UseCodeAsDefaultMessage = true; Assert.AreEqual("null", GetMessage(res, CultureInfo.CurrentCulture), "Code"); mocks.VerifyAll(); } [Test] [ExpectedException(typeof (NoSuchMessageException))] public void GetMessageResolvableNoValidMessage() { IMessageSourceResolvable res = (IMessageSourceResolvable)mocks.CreateMock(typeof(IMessageSourceResolvable)); Expect.Call(res.DefaultMessage).Return(null).Repeat.AtLeastOnce(); Expect.Call(res.GetCodes()).Return(null); Expect.Call(res.GetArguments()).Return(null).Repeat.AtLeastOnce(); mocks.ReplayAll(); GetMessage(res, CultureInfo.CurrentCulture); } [Test] public void GetMessageResolvableValidMessageAndCode() { IMessageSourceResolvable res = (IMessageSourceResolvable)mocks.CreateMock(typeof(IMessageSourceResolvable)); Expect.Call(res.GetCodes()).Return(new string[] {"code1"}); Expect.Call(res.GetArguments()).Return(new object[] { "my", "arguments" }).Repeat.AtLeastOnce(); mocks.ReplayAll(); Assert.AreEqual("my arguments", GetMessage(res, CultureInfo.CurrentCulture), "Resolve"); mocks.VerifyAll(); } [Test] public void GetMessageResolvableValidMessageAndCodeNullCulture() { IMessageSourceResolvable res = (IMessageSourceResolvable)mocks.CreateMock(typeof(IMessageSourceResolvable)); Expect.Call(res.GetCodes()).Return(new string[] { "code1" }); Expect.Call(res.GetArguments()).Return(new object[] { "my", "arguments" }).Repeat.AtLeastOnce(); mocks.ReplayAll(); Assert.AreEqual("my arguments", GetMessage(res, null), "Resolve"); mocks.VerifyAll(); } [Test] [ExpectedException(typeof(NoSuchMessageException))] public void GetMessageNullCode() { Assert.IsNull(GetMessage(null)); } [Test] public void GetMessageValidMessageAndCode() { Assert.AreEqual("my arguments", GetMessage("code1", new object[] {"my", "arguments"}), "Resolve"); } [Test] public void GetMessageValidMessageAndCodeNullCulture() { Assert.AreEqual("my arguments", GetMessage("code1", null, new object[] {"my", "arguments"}), "Resolve"); } [Test] public void GetMessageUseDefaultCode() { UseCodeAsDefaultMessage = true; Assert.AreEqual("null", GetMessage("null", new object[] {"arguments"}), "message"); Assert.IsTrue(UseCodeAsDefaultMessage, "default"); } [Test] [ExpectedException(typeof (NoSuchMessageException))] public void GetMessageNoValidMessage() { GetMessage("null", new object[] {"arguments"}); } [Test] public void GetMessageWithResolvableArguments() { IMessageSourceResolvable res = (IMessageSourceResolvable)mocks.CreateMock(typeof(IMessageSourceResolvable)); Expect.Call(res.GetCodes()).Return(new string[] { "code1" }); Expect.Call(res.GetArguments()).Return(new object[] { "my", "resolvable" }).Repeat.AtLeastOnce(); mocks.ReplayAll(); Assert.AreEqual("spring my resolvable", GetMessage("code2", CultureInfo.CurrentCulture, new object[] {"spring", res}), "Resolve"); mocks.VerifyAll(); } [Test] public void GetMessageResolvableValidMessageAndCodNullMessageFormat() { IMessageSourceResolvable res = (IMessageSourceResolvable)mocks.CreateMock(typeof(IMessageSourceResolvable)); Expect.Call(res.DefaultMessage).Return("myDefaultMessage").Repeat.AtLeastOnce(); Expect.Call(res.GetCodes()).Return(new string[] { "nullCode" }); Expect.Call(res.GetArguments()).Return(null).Repeat.AtLeastOnce(); mocks.ReplayAll(); Assert.AreEqual("myDefaultMessage", GetMessage(res, null), "Resolve"); mocks.VerifyAll(); } private void resetMe() { ParentMessageSource = null; UseCodeAsDefaultMessage = false; } protected override string ResolveMessage(string code, CultureInfo cultureInfo) { if (code.Equals("null")) { return null; } else if (code.Equals("nullCode")) { return null; } else { return "{0} {1}"; } } protected override object ResolveObject(string code, CultureInfo cultureInfo) { return null; } protected override void ApplyResourcesToObject(object value, string objectName, CultureInfo cultureInfo) { } } }
/* | Version 10.1.84 | Copyright 2013 Esri | | Licensed under the Apache License, Version 2.0 (the "License"); | you may not use this file except in compliance with the License. | You may obtain a copy of the License at | | http://www.apache.org/licenses/LICENSE-2.0 | | Unless required by applicable law or agreed to in writing, software | distributed under the License is distributed on an "AS IS" BASIS, | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | See the License for the specific language governing permissions and | limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Reflection; using System.Text; using ESRI.ArcLogistics.Data.Validation; using ESRI.ArcLogistics.DomainObjects.Attributes; using ESRI.ArcLogistics.DomainObjects.Validation; using Microsoft.Practices.EnterpriseLibrary.Validation; using Microsoft.Practices.EnterpriseLibrary.Validation.Integration; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace ESRI.ArcLogistics.DomainObjects { /// <summary> /// Break class represents a base abstract class for other breaks. /// </summary> public abstract class Break : INotifyPropertyChanged, ICloneable, IDataErrorInfo { #region Constructors /// <summary> /// Initializes a new instance of the <c>Break</c> class. /// </summary> protected Break() { } #endregion // Constructors #region Public static properties /// <summary> /// Gets name of the Duration property. /// </summary> public static string PropertyNameDuration { get { return PROP_NAME_DURATION; } } #endregion // Public static properties #region Public members /// <summary> /// This property used for backward compatibility with existent /// plugins. Without it plugin will crash the application. /// Property doesn't affect anything. Don't use it in new source code. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Don't use this property.", true)] public TimeWindow TimeWindow { get { return new TimeWindow(); } set { var timeWindow = value; } } /// <summary> /// Break's duration in minutes. /// </summary> [DurationValidator] [DomainProperty("DomainPropertyNameDuration")] [UnitPropertyAttribute(Unit.Minute, Unit.Minute, Unit.Minute)] public double Duration { get { return _duration; } set { if (value == _duration) return; _duration = value; _NotifyPropertyChanged(PROP_NAME_DURATION); } } /// <summary> /// Returns a string representation of the break information. /// </summary> /// <returns>Break's string.</returns> public override string ToString() { return string.Format(Properties.Resources.BreakFormat, _duration); } #endregion #region INotifyPropertyChanged members /// <summary> /// Event which is invoked when any of the object's properties change. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion #region ICloneable interface members /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns></returns> public abstract object Clone(); #endregion // ICloneable interface members #region IDataErrorInfo Members /// <summary> /// Validate Break, returns error string or null. /// </summary> public string Error { get { ValidationResults res = _ValidateObject(); return res.IsValid ? null : FormatErrorString(res); } } /// <summary> /// Validate property. /// </summary> /// <param name="columnName">Name of the property to validate.</param> /// <returns>Error string or null.</returns> public string this[string columnName] { get { _InitValidation(); return _ValidateProperty(columnName); } } #endregion #region Internal Method /// <summary> /// Check that both breaks have same types and same duration. /// </summary> /// <param name="breakObject">Brake to compare with this.</param> /// <returns>'True' if second break isnt null and breaks /// types and durations are the same, 'false' otherwise.</returns> internal virtual bool EqualsByValue(Break breakObject) { // If second break is null - breaks are not equal. if (breakObject == null) return false; // Check type and duration. return this.GetType() == breakObject.GetType() && this.Duration == breakObject.Duration; } #endregion #region Internal abstract methods /// <summary> /// Converts state of this instance to its equivalent string representation. /// </summary> /// <returns>The string representation of the value of this instance.</returns> internal abstract string ConvertToString(); /// <summary> /// Converts the string representation of a break to break internal state equivalent. /// </summary> /// <param name="context">String representation of a break.</param> internal abstract void InitFromString(string context); #endregion // Internal abstract methods #region Internal properties /// <summary> /// Breaks collection with this break. /// </summary> internal Breaks Breaks { set { // Unsubscribe from old collection's collection changed event. if (value == null) _breaks.CollectionChanged -= BreaksCollectionChanged; _breaks = value; // Subscribe to new collection's collection changed event. if (value != null) _breaks.CollectionChanged += new NotifyCollectionChangedEventHandler (BreaksCollectionChanged); _NotifyPropertyChanged("Breaks"); } get { return _breaks; } } internal double DefautDuration { get { return DEFAULT_DURATION; } } #endregion #region Protected methods /// <summary> /// Notifies about change of the specified property. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void _NotifyPropertyChanged(string propertyName) { if (null != PropertyChanged) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } /// <summary> /// Formats error string that will be returned by IDataErrorInfo.Error property. /// </summary> /// <param name="results"><c>ValidationResults</c> object.</param> /// <returns>An error string.</returns> private string FormatErrorString(ValidationResults results) { Debug.Assert(results != null); // Clear result string from identical messages. var uniqueMessages = new List<string>(results.Count); var sb = new StringBuilder(); foreach (ValidationResult res in results) { string message = res.Message; if (!uniqueMessages.Contains(message)) { // show only unique sb.AppendLine(message); uniqueMessages.Add(message); } } return sb.ToString().Trim(); } /// <summary> /// Method occured, when breaks collection changed. Need for validation. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Ignored.</param> protected virtual void BreaksCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { } #endregion #region private methods /// <summary> /// Init validationproxy. /// </summary> private void _InitValidation() { _validationProxy = new PropertyValidationProxy(); _validationProxy.ProvidesCustomValueConversion = false; _validationProxy.SpecificationSource = ValidationSpecificationSource.Attributes; _validationProxy.ValidatedType = GetType(); _validationProxy.Ruleset = ""; } /// <summary> /// Validate property. /// </summary> /// <param name="propName">Property name.</param> /// <returns>Error string or null.</returns> private string _ValidateProperty(string propName) { string error = null; if (_CanValidate(propName)) { _validationProxy.ValidatedPropertyName = propName; ValidationIntegrationHelper hlp = new ValidationIntegrationHelper( _validationProxy); Validator validator = hlp.GetValidator(); ValidationResults res = validator.Validate(this); if (!res.IsValid) error = _FindError(res, propName); } return error; } /// <summary> /// Validate this Break. /// </summary> /// <returns><c>ValidationResults</c></returns> private ValidationResults _ValidateObject() { Validator validator = ValidationFactory.CreateValidator( GetType()); return validator.Validate(this); } /// <summary> /// Checking can validate property or not. /// </summary> /// <param name="propName">Property name.</param> /// <returns><returns> private bool _CanValidate(string propName) { bool canValidate = false; PropertyInfo pi = GetType().GetProperty(propName); if (pi != null) { object[] attrs = pi.GetCustomAttributes(false); if (attrs != null) { foreach (object obj in attrs) { if (obj is BaseValidationAttribute) { canValidate = true; break; } } } } return canValidate; } /// <summary> /// Look for string in validation results. /// </summary> /// <param name="results"><c>ValidationResults</c>.</param> /// <param name="propName">Name of property.</param> /// <returns>Error message or null.</returns> private string _FindError(ValidationResults results, string propName) { string error = null; foreach (ValidationResult res in results) { if (res.Key.Equals(propName)) { error = res.Message; break; } } return error; } #endregion private methods #region Private constants /// <summary> /// Name of the Duration property. /// </summary> private const string PROP_NAME_DURATION = "Duration"; /// <summary> /// Name of the primary validation tag. /// </summary> internal const string PRIMARY_VALIDATOR_TAG = "Primary"; /// <summary> /// Default break's duration. /// </summary> internal const double DEFAULT_DURATION = 30; #endregion // Private constants #region Private members /// <summary> /// Used for validation. /// </summary> private PropertyValidationProxy _validationProxy; /// <summary> /// Duration in minutes. /// </summary> private double _duration { get; set; } /// <summary> /// Breaks collection with this break. /// </summary> private Breaks _breaks; #endregion } }
#region license // Copyright (c) 2003, 2004, 2005 Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Boo.Lang.Compiler.TypeSystem.Core; using Boo.Lang.Compiler.TypeSystem.Internal; using Boo.Lang.Compiler.TypeSystem.Services; using Boo.Lang.Compiler.Util; using Boo.Lang.Environments; namespace Boo.Lang.Compiler.TypeSystem.Generics { /// <summary> /// A type constructed by supplying type parameters to a generic type, involving internal types. /// </summary> /// <remarks> /// Constructed types constructed from an external generic type with external type arguments /// are themselves external, and are represented as ExternalType instances. All other cases /// are represented by this type. /// </remarks> public class GenericConstructedType : IType, IConstructedTypeInfo { protected readonly IType _definition; IType[] _arguments; GenericMapping _genericMapping; bool _fullyConstructed; string _fullName = null; public GenericConstructedType(IType definition, IType[] arguments) { _definition = definition; _arguments = arguments; _genericMapping = new InternalGenericMapping(this, arguments); _fullyConstructed = IsFullyConstructed(); } protected bool IsFullyConstructed() { return GenericsServices.GetTypeGenerity(this) == 0; } protected string BuildFullName() {/* var sb = new StringBuilder(); sb.Append(_definition.FullName); sb.Append("[of "); for (var i = 0; i < _arguments.Length; ++i) { sb.Append(_arguments[i].FullName); if (i < _arguments.Length - 1) sb.Append(", "); } sb.Append("]"); return sb.ToString(); */ return _definition.FullName; } public override bool Equals(object other) { if (other == null) return false; if (other.GetType() != this.GetType()) return false; var otherType = (GenericConstructedType) other; if (otherType._definition != _definition) return false; for (var i = 0; i < _arguments.Length; ++i) { if (!_arguments[i].Equals(otherType._arguments[i])) return false; } return true; } protected internal GenericMapping GenericMapping { get { return _genericMapping; } } public IEntity DeclaringEntity { get { return _definition.DeclaringEntity; } } public bool IsClass { get { return _definition.IsClass; } } public bool IsAbstract { get { return _definition.IsAbstract; } } public bool IsInterface { get { return _definition.IsInterface; } } public bool IsEnum { get { return _definition.IsEnum; } } public bool IsByRef { get { return _definition.IsByRef; } } public bool IsValueType { get { return _definition.IsValueType; } } public bool IsFinal { get { return _definition.IsFinal; } } public bool IsArray { get { return _definition.IsArray; } } public bool IsPointer { get { return _definition.IsPointer; } } public int GetTypeDepth() { return _definition.GetTypeDepth(); } public IType ElementType { get { return GenericMapping.MapType(_definition.ElementType); } } public IType BaseType { get { return GenericMapping.MapType(_definition.BaseType); } } public IEntity GetDefaultMember() { IEntity definitionDefaultMember = _definition.GetDefaultMember(); if (definitionDefaultMember != null) return GenericMapping.Map(definitionDefaultMember); return null; } public IType[] GetInterfaces() { return Array.ConvertAll<IType, IType>( _definition.GetInterfaces(), GenericMapping.MapType); } public bool IsSubclassOf(IType other) { if (null == other) return false; if (BaseType != null && (BaseType == other || BaseType.IsSubclassOf(other))) { return true; } if (other.IsInterface && Array.Exists( GetInterfaces(), i => TypeCompatibilityRules.IsAssignableFrom(other, i))) { return true; } if (null != other.ConstructedInfo && ConstructedInfo.GenericDefinition == other.ConstructedInfo.GenericDefinition) { for (int i = 0; i < ConstructedInfo.GenericArguments.Length; ++i) { if (!ConstructedInfo.GenericArguments[i].IsSubclassOf(other.ConstructedInfo.GenericArguments[i])) return false; } return true; } return false; } public virtual bool IsAssignableFrom(IType other) { if (other == null) return false; if (other == this || other.IsSubclassOf(this) || (other.IsNull() && !IsValueType) || IsGenericAssignableFrom(other)) return true; return false; } public bool IsGenericAssignableFrom(IType other) { var gd = _definition; if (gd != null && gd.IsAssignableFrom(other)) return true; var otherConstruct = other as GenericConstructedType; if (otherConstruct == null || otherConstruct._definition != gd) return false; for (var i = 0; i < _arguments.Length; ++i) { if (!_arguments[i].IsAssignableFrom(otherConstruct._arguments[i])) return false; } return true; } public IGenericTypeInfo GenericInfo { get { return _definition.GenericInfo; } } public IConstructedTypeInfo ConstructedInfo { get { return this; } } public IType Type { get { return this; } } public INamespace ParentNamespace { get { return GenericMapping.Map(_definition.ParentNamespace as IEntity) as INamespace; } } public bool Resolve(ICollection<IEntity> resultingSet, string name, EntityType typesToConsider) { Set<IEntity> definitionMatches = new Set<IEntity>(); if (!_definition.Resolve(definitionMatches, name, typesToConsider)) return false; foreach (IEntity match in definitionMatches) resultingSet.Add(GenericMapping.Map(match)); return true; } public IEnumerable<IEntity> GetMembers() { return _definition.GetMembers().Select<IEntity, IEntity>(GenericMapping.Map); } public string Name { get { return _definition.Name; } } public string FullName { get { return _fullName ?? (_fullName = BuildFullName()); } } public EntityType EntityType { get { return EntityType.Type; } } IType[] IGenericArgumentsProvider.GenericArguments { get { return _arguments; } } IType IConstructedTypeInfo.GenericDefinition { get { return _definition; } } bool IConstructedTypeInfo.FullyConstructed { get { return _fullyConstructed; } } IType IConstructedTypeInfo.Map(IType type) { return GenericMapping.MapType(type); } IMember IConstructedTypeInfo.Map(IMember member) { return (IMember)GenericMapping.Map(member); } IMember IConstructedTypeInfo.UnMap(IMember mapped) { return GenericMapping.UnMap(mapped); } public bool IsDefined(IType attributeType) { return _definition.IsDefined(GenericMapping.MapType(attributeType)); } public override string ToString() { return FullName; } private ArrayTypeCache _arrayTypes; public IArrayType MakeArrayType(int rank) { if (null == _arrayTypes) _arrayTypes = new ArrayTypeCache(this); return _arrayTypes.MakeArrayType(rank); } public IType MakePointerType() { return null; } } public class GenericConstructedCallableType : GenericConstructedType, ICallableType { CallableSignature _signature; public GenericConstructedCallableType(ICallableType definition, IType[] arguments) : base(definition, arguments) { } public CallableSignature GetSignature() { if (_signature == null) { CallableSignature definitionSignature = ((ICallableType)_definition).GetSignature(); IParameter[] parameters = GenericMapping.MapParameters(definitionSignature.Parameters); IType returnType = GenericMapping.MapType(definitionSignature.ReturnType); _signature = new CallableSignature(parameters, returnType); } return _signature; } public bool IsAnonymous { get { return false; } } override public bool IsAssignableFrom(IType other) { return My<TypeSystemServices>.Instance.IsCallableTypeAssignableFrom(this, other); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Reflection; using Mercurial.Attributes; namespace Mercurial { /// <summary> /// This is the base class for option classes for various commands for /// the Mercurial and TortoiseHg client. /// </summary> /// <typeparam name="T"> /// The actual type descending from <see cref="CommandBase{T}"/>, used to generate type-correct /// methods in this base class. /// </typeparam> public class CommandBase<T> : ICommand where T : CommandBase<T> { /// <summary> /// This is the backing field for the <see cref="AdditionalArguments"/> property. /// </summary> private readonly List<string> _AdditionalArguments = new List<string>(); /// <summary> /// This is the backing field for the <see cref="Command"/> property. /// </summary> private readonly string _Command; /// <summary> /// This is the backing field for the <see cref="RawStandardErrorOutput"/> property. /// </summary> private string _RawStandardErrorOutput = string.Empty; /// <summary> /// This is the backing field for the <see cref="RawStandardOutput"/> property. /// </summary> private string _RawStandardOutput = string.Empty; /// <summary> /// This is the backing field for the <see cref="Timeout"/> property. /// </summary> private int _Timeout = 60; /// <summary> /// Initializes a new instance of the <see cref="CommandBase{T}"/> class. /// </summary> /// <param name="command"> /// The name of the command that will be passed to the Mercurial or TortoiseHg command line client. /// </param> /// <exception cref="ArgumentNullException"> /// <para><paramref name="command"/> is <c>null</c> or empty.</para> /// </exception> protected CommandBase(string command) { if (StringEx.IsNullOrWhiteSpace(command)) throw new ArgumentNullException("command"); _Command = command; } /// <summary> /// Gets or sets a value indicating whether to enable debug output on the command. This should only be used by the command code /// itself, never by the user. /// </summary> [BooleanArgument(TrueOption = "--debug")] [DefaultValue(false)] [EditorBrowsable(EditorBrowsableState.Never)] protected bool DebugOutput { get; set; } /// <summary> /// Gets the raw standard output from executing the command line client. /// </summary> public string RawStandardOutput { get { return _RawStandardOutput; } } /// <summary> /// Gets the raw standard error output from executing the command line client. /// </summary> public string RawStandardErrorOutput { get { return _RawStandardErrorOutput; } } /// <summary> /// Gets the raw exit code from executing the command line client. /// </summary> public int RawExitCode { get; private set; } #region ICommand Members /// <summary> /// Gets the collection which additional arguments can be added into. This collection /// is exposed for extensions, so that they have a place to add all their /// extra arguments to the Mercurial command line client. /// </summary> /// <remarks> /// Note that all of these arguments will be appended to the end of the command line, /// after all the normal arguments supported by the command classes. /// </remarks> public Collection<string> AdditionalArguments { get { return new Collection<string>(_AdditionalArguments); } } /// <summary> /// Validates the command configuration. This method should throw the necessary /// exceptions to signal missing or incorrect configuration (like attempting to /// add files to the repository without specifying which files to add.) /// </summary> /// <remarks> /// Note that as long as you descend from <see cref="MercurialCommandBase{T}"/> you're not required to call /// the base method at all. /// </remarks> public virtual void Validate() { // Do nothing by default } /// <summary> /// Gets the command to execute with the Mercurial command line client. /// </summary> /// <remarks> /// Note that this property is required to return a non-null non-empty (including whitespace) string, /// as it will be used to specify which command to execute for the Mercurial command line client. You're /// not required to call the base property though, as long as you descend from <see cref="MercurialCommandBase{T}"/>. /// </remarks> public virtual string Command { get { return _Command; } } /// <summary> /// Gets all the arguments to the <see cref="Command"/>, or an /// empty array if there are none. /// </summary> /// <remarks> /// Note that as long as you descend from <see cref="MercurialCommandBase{T}"/> you're not required to access /// the base property at all, but you are required to return a non-<c>null</c> array reference, /// even for an empty array. /// </remarks> public virtual IEnumerable<string> Arguments { get { var options = new List<string>(); var arguments = new List<string>(); foreach (PropertyInfo prop in GetType().GetProperties()) { if (!prop.IsDefined(typeof(ArgumentAttribute), true)) continue; ArgumentAttribute[] attributes = prop.GetCustomAttributes(typeof(ArgumentAttribute), true).Cast<ArgumentAttribute>().ToArray(); foreach (ArgumentAttribute attribute in attributes) { string[] values = attribute.GetOptions(prop.GetValue(this, null)); if (values == null || values.Length == 0) continue; var argAttr = attribute as NullableArgumentAttribute; if (argAttr != null && StringEx.IsNullOrWhiteSpace(argAttr.NonNullOption) && StringEx.IsNullOrWhiteSpace(argAttr.NullOption)) arguments.AddRange(values); else options.AddRange(values); } } return options.Concat(arguments); } } /// <summary> /// This method is called before the command is executed. You can use this to /// store temporary files (like a commit message or similar) that the /// <see cref="Arguments"/> refer to, before the command is executed. /// </summary> public void Before() { Prepare(); } /// <summary> /// This method is called after the command has been executed. You can use this to /// clean up after the command execution (like removing temporary files), and to /// react to the exit code from the command line client. If the exit code is /// considered a failure, this method should throw the correct exception. /// </summary> /// <param name="exitCode">The exit code from the command line client. Typically 0 means success, but this /// can vary from command to command.</param> /// <param name="standardOutput">The standard output of the execution, or <see cref="string.Empty"/> if there /// was none.</param> /// <param name="standardErrorOutput">The standard error output of the execution, or <see cref="string.Empty"/> if /// there was none.</param> public void After(int exitCode, string standardOutput, string standardErrorOutput) { _RawStandardOutput = standardOutput; _RawStandardErrorOutput = standardErrorOutput; RawExitCode = exitCode; try { ThrowOnUnsuccessfulExecution(exitCode, standardErrorOutput); ParseStandardOutputForResults(exitCode, standardOutput); } finally { Cleanup(); } } /// <summary> /// Gets or sets the timeout to use when executing Mercurial commands, in /// seconds. Default is 60. /// </summary> /// <exception cref="ArgumentOutOfRangeException"> /// <para><see cref="Timeout"/> cannot be less than 0.</para> /// </exception> [DefaultValue(60)] public virtual int Timeout { get { return _Timeout; } set { if (value < 0) throw new ArgumentOutOfRangeException("value", value, "Timeout cannot be lower than 0"); _Timeout = value; } } /// <summary> /// Gets or sets the object that will act as an observer of command execution. /// </summary> [DefaultValue(null)] public IMercurialCommandObserver Observer { get; set; } #endregion /// <summary> /// Adds the value to the <see cref="AdditionalArguments"/> collection property and /// returns this instance. /// </summary> /// <param name="value"> /// The value to add to the <see cref="AdditionalArguments"/> collection property. /// </param> /// <returns> /// This instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> /// <exception cref="ArgumentNullException"> /// <para><paramref name="value"/> is <c>null</c> or empty.</para> /// </exception> public T WithAdditionalArgument(string value) { if (StringEx.IsNullOrWhiteSpace(value)) throw new ArgumentNullException("value"); AdditionalArguments.Add(value); return (T)this; } /// <summary> /// This method should throw the appropriate exception depending on the contents of /// the <paramref name="exitCode"/> and <paramref name="standardErrorOutput"/> /// parameters, or simply return if the execution is considered successful. /// </summary> /// <param name="exitCode"> /// The exit code from executing the command line client. /// </param> /// <param name="standardErrorOutput"> /// The standard error output from executing the command client. /// </param> /// <remarks> /// Note that as long as you descend from <see cref="MercurialCommandBase{T}"/> you're not required to call /// the base method at all. The default behavior is to throw a <see cref="MercurialExecutionException"/> /// if <paramref name="exitCode"/> is not zero. If you require different behavior, don't call the base /// method. /// </remarks> /// <exception cref="MercurialExecutionException"> /// <para><paramref name="exitCode"/> is not <c>0</c>.</para> /// </exception> protected virtual void ThrowOnUnsuccessfulExecution(int exitCode, string standardErrorOutput) { if (exitCode == 0) return; throw new MercurialExecutionException(standardErrorOutput); } /// <summary> /// This method should parse and store the appropriate execution result output /// according to the type of data the command line client would return for /// the command. /// </summary> /// <param name="exitCode"> /// The exit code from executing the command line client. /// </param> /// <param name="standardOutput"> /// The standard output from executing the command line client. /// </param> /// <remarks> /// Note that as long as you descend from <see cref="MercurialCommandBase{T}"/> you're not required to call /// the base method at all. /// </remarks> protected virtual void ParseStandardOutputForResults(int exitCode, string standardOutput) { // Do nothing by default } /// <summary> /// Override this method to implement code that will execute before command /// line execution. /// </summary> /// <remarks> /// Note that as long as you descend from <see cref="MercurialCommandBase{T}"/> you're not required to call /// the base method at all. /// </remarks> protected virtual void Prepare() { // Do nothing by default } /// <summary> /// Override this method to implement code that will execute after command /// line execution. /// </summary> /// <remarks> /// Note that as long as you descend from <see cref="MercurialCommandBase{T}"/> you're not required to call /// the base method at all. /// </remarks> protected virtual void Cleanup() { // Do nothing by default } /// <summary> /// Adds the specified argument to the <see cref="AdditionalArguments"/> collection, /// unless it is already present. /// </summary> /// <param name="argument"> /// The argument to add to <see cref="AdditionalArguments"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <para><paramref name="argument"/> is <c>null</c> or empty.</para> /// </exception> [EditorBrowsable(EditorBrowsableState.Never)] public void AddArgument(string argument) { if (StringEx.IsNullOrWhiteSpace(argument)) throw new ArgumentNullException("argument"); if (!_AdditionalArguments.Contains(argument)) _AdditionalArguments.Add(argument); } /// <summary> /// Sets the <see cref="Timeout"/> property to the specified value and /// returns this instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="Timeout"/> property. /// </param> /// <returns> /// This instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public T WithTimeout(int value) { Timeout = value; return (T)this; } /// <summary> /// Sets the <see cref="Observer"/> property to the specified value and /// returns this instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="Observer"/> property. /// </param> /// <returns> /// This instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public T WithObserver(IMercurialCommandObserver value) { Observer = value; return (T)this; } } }
namespace Microsoft.Protocols.TestSuites.MS_AUTHWS { using System.Xml; using Microsoft.Protocols.TestSuites.Common; /// <summary> /// Adapter requirements capture code for MS_AUTHWSAdapter. /// </summary> public partial class MS_AUTHWSAdapter { /// <summary> /// This method is used to verify the requirements about the transport. /// </summary> private void CaptureTransportRelatedRequirements() { TransportProtocol transport = Common.GetConfigurationPropertyValue<TransportProtocol>("TransportType", this.Site); switch (transport) { case TransportProtocol.HTTP: // As response successfully returned, the transport related requirements can be directly captured. Site.CaptureRequirement( 1, @"[In Transport] Protocol servers MUST support SOAP over HTTP."); break; case TransportProtocol.HTTPS: if (Common.IsRequirementEnabled(121, this.Site)) { // Having received the response successfully have proved the HTTPS // transport is supported. If the HTTPS transport is not supported, the // response can't be received successfully. Site.CaptureRequirement( 121, @"[In Appendix B: Product Behavior] Implementation does additionally support SOAP over HTTPS to help secure communication with protocol clients.(The Windows SharePoint Services 3.0 and above products follow this behavior.)"); } break; default: Site.Debug.Fail("Unknown transport type " + transport); break; } SoapVersion soapVersion = Common.GetConfigurationPropertyValue<SoapVersion>("SoapVersion", this.Site); switch (soapVersion) { case SoapVersion.SOAP11: // As response successfully returned, the SOAP1.1 related requirements can be directly captured. Site.CaptureRequirement( 122, @"[In Transport] Protocol messages MUST be formatted as specified in [SOAP1.1] section 4 [or [SOAP1.2/1] section 5]."); break; case SoapVersion.SOAP12: // As response successfully returned, the SOAP1.2 related requirements can be directly captured. Site.CaptureRequirement( 123, @"[In Transport] Protocol messages MUST be formatted as specified in [SOAP1.2/1] section 5."); break; default: Site.Debug.Fail("Unknown soap version" + soapVersion); break; } } /// <summary> /// Validate common message syntax to schema and capture related requirements. /// </summary> private void ValidateAndCaptureCommonMessageSyntax() { bool isResponseValid = SchemaValidation.ValidationResult == ValidationResult.Success; // If the server response is validated successfully, we can make sure that the server responds with an correct message syntax, MS-AUTHWS_R7, MS-AUTHWS_R8 and MS-AUTHWS_R9 can be verified. Site.CaptureRequirementIfIsTrue( isResponseValid, 7, @"[In Common Message Syntax] The syntax of the definitions uses the XML Schema, as specified in [XMLSCHEMA1] and [XMLSCHEMA2]."); Site.CaptureRequirementIfIsTrue( isResponseValid, 8, @"[In Common Message Syntax] The syntax of the definitions uses Web Services Description Language, as specified in [WSDL]."); Site.CaptureRequirementIfIsTrue( isResponseValid, 9, @"[In Namespaces] This specification[MS-AUTHWS] defines and references various XML namespaces using the mechanisms specified in [XMLNS]."); } /// <summary> /// Validate the Login Response. /// </summary> /// <param name="result">The response result of Login.</param> private void ValidateLoginResponse(LoginResult result) { XmlElement xmlResponse = SchemaValidation.LastRawResponseXml; bool isResponseValid = SchemaValidation.ValidationResult == ValidationResult.Success; // If the server response is validated successfully, we can make sure that the server responds with an LoginSoapOut response message, MS-AUTHWS_49, MS-AUTHWS_51, MS-AUTHWS_57 and MS-AUTHWS_40 can be verified. Site.CaptureRequirementIfIsTrue( isResponseValid, 49, @"[In Login] [The Login operation is defined as follow:] <wsdl:operation name=""Login""> <wsdl:input message=""tns:LoginSoapIn"" /> <wsdl:output message=""tns:LoginSoapOut"" /> </wsdl:operation>"); Site.CaptureRequirementIfIsTrue( isResponseValid, 51, @"[In Login] [If the protocol client sends a LoginSoapIn request WSDL message] and the protocol server responds with a LoginSoapOut response WSDL message, as specified in section 3.1.4.1.1.2."); Site.CaptureRequirementIfIsTrue( isResponseValid, 57, @"[In LoginSoapOut] The LoginSoapOut message is the response WSDL message that is used by a protocol server when logging on a user in response to a LoginSoapIn request message."); Site.CaptureRequirementIfIsTrue( isResponseValid, 40, @"[In Message Processing Events and Sequencing Rules] The following table summarizes the list of WSDL operations[Login, Mode] that are defined by this protocol."); // If the server response is validated successfully, and the LoginResponse has returned, MS-AUTHWS_59 can be verified. Site.CaptureRequirementIfIsTrue( this.ResponseExists(xmlResponse, "LoginResponse"), 59, @"[In LoginSoapOut] The SOAP body contains a LoginResponse element, as specified in section 3.1.4.1.2.2."); // If the server response is validated successfully, we can make sure that the server responds with LoginResponse, MS-AUTHWS_66 can be verified. Site.CaptureRequirementIfIsTrue( isResponseValid, 66, @"[In LoginResponse] [The LoginResponse element is defined as follows:] <s:element name=""LoginResponse""> <s:complexType> <s:sequence> <s:element name=""LoginResult"" type=""tns:LoginResult""/> </s:sequence> </s:complexType> </s:element>"); if (result != null) { // If LoginResult element exist, and the server response pass the validation successfully, we can make sure LoginResult is defined according to the schema, MS-AUTHWS_71, MS-AUTHWS_67, MS-AUTHWS_69 can be verified. Site.CaptureRequirementIfIsTrue( isResponseValid, 71, @"[In LoginResult] [The LoginResult complex type is defined as follows:] <s:complexType name=""LoginResult""> <s:sequence> <s:element name=""CookieName"" type=""s:string"" minOccurs=""0""/> <s:element name=""ErrorCode"" type=""tns:LoginErrorCode""/> <s:element name=""TimeoutSeconds"" type=""s:int"" minOccurs=""0"" maxOccurs=""1""/> </s:sequence> </s:complexType>"); Site.CaptureRequirementIfIsTrue( isResponseValid, 67, @"[In LoginResponse] LoginResult: A LoginResult complex type, as specified in section 3.1.4.1.3.1."); Site.CaptureRequirementIfIsTrue( isResponseValid, 69, @"[In LoginResult] The LoginResult complex type contains an error code."); // If LoginResult element exist, and the server response pass the validation successfully, we can make sure LoginErrorCode is defined according to the schema, MS-AUTHWS_79, MS-AUTHWS_75 and MS-AUTHWS_80 can be verified. Site.CaptureRequirementIfIsTrue( isResponseValid, 79, @"[In LoginErrorCode] [The LoginErrorCode simple type is defined as follows:] <s:simpleType name=""LoginErrorCode""> <s:restriction base=""s:string""> <s:enumeration value=""NoError""/> <s:enumeration value=""NotInFormsAuthenticationMode""/> <s:enumeration value=""PasswordNotMatch""/> </s:restriction> </s:simpleType>"); Site.CaptureRequirementIfIsTrue( isResponseValid, 75, @"[In LoginResult] ErrorCode: An error code, as specified in section 3.1.4.1.4.1."); Site.CaptureRequirementIfIsTrue( isResponseValid, 80, @"[In LoginErrorCode] The LoginErrorCode field has three allowable values: [NoError, NotInFormsAuthenticationMode, PasswordNotMatch]."); } this.ValidateAndCaptureCommonMessageSyntax(); } /// <summary> /// Validate the Mode Response. /// </summary> private void ValidateModeResponse() { XmlElement xmlResponse = SchemaValidation.LastRawResponseXml; bool isResponseValid = SchemaValidation.ValidationResult == ValidationResult.Success; // If the server response is validated successfully, we can make sure that the server responds with an ModeSoapOut response message, MS-AUTHWS_87, MS-AUTHWS_89, MS-AUTHWS_95 and MS-AUTHWS_40 can be verified. Site.CaptureRequirementIfIsTrue( isResponseValid, 87, @"[In Mode] [The Mode operation is defined as follows:] <wsdl:operation name=""Mode""> <wsdl:input message=""tns:ModeSoapIn"" /> <wsdl:output message=""tns:ModeSoapOut"" /> </wsdl:operation>"); Site.CaptureRequirementIfIsTrue( isResponseValid, 89, @"[In Mode] [If the protocol client sends a ModeSoapIn request WSDL message] and the protocol server responds with a ModeSoapOut response WSDL message."); Site.CaptureRequirementIfIsTrue( isResponseValid, 95, @"[In ModeSoapOut] The ModeSoapOut message is the response WSDL message that a protocol server sends after retrieving the authentication mode."); Site.CaptureRequirementIfIsTrue( isResponseValid, 40, @"[In Message Processing Events and Sequencing Rules] The following table summarizes the list of WSDL operations[Login, Mode] that are defined by this protocol."); // If the server response is validated successfully, and the ModeResponse has returned, MS-AUTHWS_97 can be verified. Site.CaptureRequirementIfIsTrue( this.ResponseExists(xmlResponse, "ModeResponse"), 97, @"[In ModeSoapOut] The SOAP body contains a ModeResponse element, as specified in section 3.1.4.2.2.2."); // If the server response is validated successfully, we can make sure that the server responds with ModeResponse, MS-AUTHWS_102 can be verified. Site.CaptureRequirementIfIsTrue( isResponseValid, 102, @"[In ModeResponse] [The ModeResponse element is defined as follows:] <s:element name=""ModeResponse""> <s:complexType> <s:sequence> <s:element name=""ModeResult"" type=""tns:AuthenticationMode""/> </s:sequence> </s:complexType> </s:element>"); // If ModeResult element exist, and the server response pass the validation successfully, we can make sure LoginResult is defined according to the schema, MS-AUTHWS_106, MS-AUTHWS_103 and MS-AUTHWS_107 can be verified. Site.CaptureRequirementIfIsTrue( isResponseValid, 106, @"[In AuthenticationMode] [The AuthenticationMode simple type is defined as follows:] <s:simpleType name=""AuthenticationMode""> <s:restriction base=""s:string""> <s:enumeration value=""None""/> <s:enumeration value=""Windows""/> <s:enumeration value=""Passport""/> <s:enumeration value=""Forms""/> </s:restriction> </s:simpleType>"); Site.CaptureRequirementIfIsTrue( isResponseValid, 103, @"[In ModeResponse] ModeResult: An AuthenticationMode simple type, as specified in section 3.1.4.2.4.1."); Site.CaptureRequirementIfIsTrue( isResponseValid, 107, @"[In AuthenticationMode] The AuthenticationMode field has four allowable values: [None, Windows, Passport, Forms]."); this.ValidateAndCaptureCommonMessageSyntax(); } /// <summary> /// This method is used to validate whether there is an element named as responseName in xmlElement. /// </summary> /// <param name="xmlElement">A XmlElement object which is the raw XML response from server.</param> /// <param name="responseName">The name of the response element.</param> /// <returns>A Boolean value indicates whether there is an element named as responseName.</returns> private bool ResponseExists(XmlElement xmlElement, string responseName) { // The first child is the response element. XmlNode firstChildNode = xmlElement.ChildNodes[0].FirstChild; return firstChildNode.Name == responseName; } } }
// 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. #define DEBUG // The behavior of this contract library should be consistent regardless of build type. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Reflection; using DeveloperExperience = Internal.DeveloperExperience.DeveloperExperience; #if FEATURE_RELIABILITY_CONTRACTS using System.Runtime.ConstrainedExecution; #endif #if FEATURE_UNTRUSTED_CALLERS using System.Security; using System.Security.Permissions; #endif namespace System.Diagnostics.Contracts { public static partial class Contract { #region Private Methods [ThreadStatic] private static bool t_assertingMustUseRewriter; /// <summary> /// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly. /// It is NEVER used to indicate failure of actual contracts at runtime. /// </summary> #if FEATURE_UNTRUSTED_CALLERS #endif static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind) { //TODO: Implement CodeContract failure mechanics including enabling CCIRewrite if (t_assertingMustUseRewriter) { System.Diagnostics.Debug.Assert(false, "Asserting that we must use the rewriter went reentrant. Didn't rewrite this System.Private.CoreLib?"); return; } t_assertingMustUseRewriter = true; //// For better diagnostics, report which assembly is at fault. Walk up stack and //// find the first non-mscorlib assembly. //Assembly thisAssembly = typeof(Contract).Assembly; // In case we refactor mscorlib, use Contract class instead of Object. //StackTrace stack = new StackTrace(); //Assembly probablyNotRewritten = null; //for (int i = 0; i < stack.FrameCount; i++) //{ // Assembly caller = stack.GetFrame(i).GetMethod().DeclaringType.Assembly; // if (caller != thisAssembly) // { // probablyNotRewritten = caller; // break; // } //} //if (probablyNotRewritten == null) // probablyNotRewritten = thisAssembly; //String simpleName = probablyNotRewritten.GetName().Name; String simpleName = "System.Private.CoreLib"; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, SR.Format(SR.MustUseCCRewrite, contractKind, simpleName), null, null, null); t_assertingMustUseRewriter = false; } #endregion Private Methods #region Failure Behavior /// <summary> /// Without contract rewriting, failing Assert/Assumes end up calling this method. /// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call /// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by /// System.Runtime.CompilerServices.ContractHelper.TriggerFailure. /// </summary> [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), "failureKind"); Contract.EndContractBlock(); // displayMessage == null means: yes we handled it. Otherwise it is the localized failure message String displayMessage = System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); if (displayMessage == null) return; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(failureKind, displayMessage, userMessage, conditionText, innerException); } #if !FEATURE_CORECLR /// <summary> /// Allows a managed application environment such as an interactive interpreter (IronPython) /// to be notified of contract failures and /// potentially "handle" them, either by throwing a particular exception type, etc. If any of the /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will /// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires /// full trust, because it will inform you of bugs in the appdomain and because the event handler /// could allow you to continue execution. /// </summary> public static event EventHandler<ContractFailedEventArgs> ContractFailed { #if FEATURE_UNTRUSTED_CALLERS #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif add { System.Runtime.CompilerServices.ContractHelper.InternalContractFailed += value; } #if FEATURE_UNTRUSTED_CALLERS #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif remove { System.Runtime.CompilerServices.ContractHelper.InternalContractFailed -= value; } } #endif // !FEATURE_CORECLR #endregion FailureBehavior } #if !FEATURE_CORECLR // Not usable on Silverlight by end users due to security, and full trust users have not yet expressed an interest. public sealed class ContractFailedEventArgs : EventArgs { private ContractFailureKind _failureKind; private String _message; private String _condition; private Exception _originalException; private bool _handled; private bool _unwind; internal Exception thrownDuringHandler; #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public ContractFailedEventArgs(ContractFailureKind failureKind, String message, String condition, Exception originalException) { Contract.Requires(originalException == null || failureKind == ContractFailureKind.PostconditionOnException); _failureKind = failureKind; _message = message; _condition = condition; _originalException = originalException; } public String Message { get { return _message; } } public String Condition { get { return _condition; } } public ContractFailureKind FailureKind { get { return _failureKind; } } public Exception OriginalException { get { return _originalException; } } // Whether the event handler "handles" this contract failure, or to fail via escalation policy. public bool Handled { get { return _handled; } } #if FEATURE_UNTRUSTED_CALLERS #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif public void SetHandled() { _handled = true; } public bool Unwind { get { return _unwind; } } #if FEATURE_UNTRUSTED_CALLERS #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif public void SetUnwind() { _unwind = true; } } #endif // !FEATURE_CORECLR #if FEATURE_SERIALIZATION [Serializable] #else [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors")] #endif [SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic")] internal sealed class ContractException : Exception { private readonly ContractFailureKind _Kind; private readonly string _UserMessage; private readonly string _Condition; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public ContractFailureKind Kind { get { return _Kind; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string Failure { get { return this.Message; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string UserMessage { get { return _UserMessage; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string Condition { get { return _Condition; } } // Called by COM Interop, if we see COR_E_CODECONTRACTFAILED as an HRESULT. private ContractException() { HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED; } public ContractException(ContractFailureKind kind, string failure, string userMessage, string condition, Exception innerException) : base(failure, innerException) { HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED; _Kind = kind; _UserMessage = userMessage; _Condition = condition; } #if FEATURE_SERIALIZATION private ContractException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { _Kind = (ContractFailureKind)info.GetInt32("Kind"); _UserMessage = info.GetString("UserMessage"); _Condition = info.GetString("Condition"); } #endif // FEATURE_SERIALIZATION #if FEATURE_UNTRUSTED_CALLERS && FEATURE_SERIALIZATION #if FEATURE_LINK_DEMAND && FEATURE_SERIALIZATION [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] #endif // FEATURE_LINK_DEMAND #endif // FEATURE_UNTRUSTED_CALLERS #if FEATURE_SERIALIZATION public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); info.AddValue("Kind", _Kind); info.AddValue("UserMessage", _UserMessage); info.AddValue("Condition", _Condition); } #endif } } namespace System.Runtime.CompilerServices { public static partial class ContractHelper { #region Private fields #if !FEATURE_CORECLR private static volatile EventHandler<ContractFailedEventArgs> s_contractFailedEvent; private static readonly Object s_lockObject = new Object(); #endif // !FEATURE_CORECLR internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542); #endregion #if !FEATURE_CORECLR /// <summary> /// Allows a managed application environment such as an interactive interpreter (IronPython) or a /// web browser host (Jolt hosting Silverlight in IE) to be notified of contract failures and /// potentially "handle" them, either by throwing a particular exception type, etc. If any of the /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will /// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires /// full trust. /// </summary> internal static event EventHandler<ContractFailedEventArgs> InternalContractFailed { #if FEATURE_UNTRUSTED_CALLERS #endif add { // Eagerly prepare each event handler _marked with a reliability contract_, to // attempt to reduce out of memory exceptions while reporting contract violations. // This only works if the new handler obeys the constraints placed on // constrained execution regions. Eagerly preparing non-reliable event handlers // would be a perf hit and wouldn't significantly improve reliability. // UE: Please mention reliable event handlers should also be marked with the // PrePrepareMethodAttribute to avoid CER eager preparation work when ngen'ed. //#if !FEATURE_CORECLR // System.Runtime.CompilerServices.RuntimeHelpers.PrepareContractedDelegate(value); //#endif lock (s_lockObject) { s_contractFailedEvent += value; } } #if FEATURE_UNTRUSTED_CALLERS #endif remove { lock (s_lockObject) { s_contractFailedEvent -= value; } } } #endif // !FEATURE_CORECLR /// <summary> /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// This method has 3 functions: /// 1. Call any contract hooks (such as listeners to Contract failed events) /// 2. Determine if the listeneres deem the failure as handled (then resultFailureMessage should be set to null) /// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently. /// </summary> /// <param name="resultFailureMessage">Should really be out (or the return value), but partial methods are not flexible enough. /// On exit: null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message</param> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS #endif static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), "failureKind"); Contract.EndContractBlock(); string returnValue; String displayMessage = "contract failed."; // Incomplete, but in case of OOM during resource lookup... #if !FEATURE_CORECLR ContractFailedEventArgs eventArgs = null; // In case of OOM. #endif // !FEATURE_CORECLR #if FEATURE_RELIABILITY_CONTRACTS System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); #endif try { displayMessage = GetDisplayMessage(failureKind, userMessage, conditionText); #if !FEATURE_CORECLR if (s_contractFailedEvent != null) { eventArgs = new ContractFailedEventArgs(failureKind, displayMessage, conditionText, innerException); foreach (EventHandler<ContractFailedEventArgs> handler in s_contractFailedEvent.GetInvocationList()) { try { handler(null, eventArgs); } catch (Exception e) { eventArgs.thrownDuringHandler = e; eventArgs.SetUnwind(); } } if (eventArgs.Unwind) { //if (Environment.IsCLRHosted) // TriggerCodeContractEscalationPolicy(failureKind, displayMessage, conditionText, innerException); // unwind if (innerException == null) { innerException = eventArgs.thrownDuringHandler; } throw new ContractException(failureKind, displayMessage, userMessage, conditionText, innerException); } } #endif // !FEATURE_CORECLR } finally { #if !FEATURE_CORECLR if (eventArgs != null && eventArgs.Handled) { returnValue = null; // handled } else #endif // !FEATURE_CORECLR { returnValue = displayMessage; } } resultFailureMessage = returnValue; } /// <summary> /// Rewriter calls this method to get the default failure behavior. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "conditionText")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "userMessage")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "innerException")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_UNTRUSTED_CALLERS && !FEATURE_CORECLR #endif static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) { // If we're here, our intent is to pop up a dialog box (if we can). For developers // interacting live with a debugger, this is a good experience. For Silverlight // hosted in Internet Explorer, the assert window is great. If we cannot // pop up a dialog box, throw an exception (consider a library compiled with // "Assert On Failure" but used in a process that can't pop up asserts, like an // NT Service). For the CLR hosted by server apps like SQL or Exchange, we should // trigger escalation policy. //#if !FEATURE_CORECLR // if (Environment.IsCLRHosted) // { // TriggerCodeContractEscalationPolicy(kind, displayMessage, conditionText, innerException); // // Hosts like SQL may choose to abort the thread, so we will not get here in all cases. // // But if the host's chosen action was to throw an exception, we should throw an exception // // here (which is easier to do in managed code with the right parameters). // throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException); // } //#endif // !FEATURE_CORECLR //TODO: Implement CodeContract failure mechanics including enabling CCIRewrite String stackTrace = null; //@todo: Any reasonable way to get a stack trace here? bool userSelectedIgnore = DeveloperExperience.Default.OnContractFailure(stackTrace, kind, displayMessage, userMessage, conditionText, innerException); if (userSelectedIgnore) return; //if (!Environment.UserInteractive) { throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException); //} //// May need to rethink Assert.Fail w/ TaskDialogIndirect as a model. Window title. Main instruction. Content. Expanded info. //// Optional info like string for collapsed text vs. expanded text. //String windowTitle = SR.Format(GetResourceNameForFailure(kind)); //const int numStackFramesToSkip = 2; // To make stack traces easier to read //System.Diagnostics.Debug.Assert(conditionText, displayMessage, windowTitle, COR_E_CODECONTRACTFAILED, StackTrace.TraceFormat.Normal, numStackFramesToSkip); // If we got here, the user selected Ignore. Continue. } private static String GetFailureMessage(ContractFailureKind failureKind, String conditionText) { bool hasConditionText = !String.IsNullOrEmpty(conditionText); switch (failureKind) { case ContractFailureKind.Assert: return hasConditionText ? SR.Format(SR.AssertionFailed_Cnd, conditionText) : SR.AssertionFailed; case ContractFailureKind.Assume: return hasConditionText ? SR.Format(SR.AssumptionFailed_Cnd, conditionText) : SR.AssumptionFailed; case ContractFailureKind.Precondition: return hasConditionText ? SR.Format(SR.PreconditionFailed_Cnd, conditionText) : SR.PreconditionFailed; case ContractFailureKind.Postcondition: return hasConditionText ? SR.Format(SR.PostconditionFailed_Cnd, conditionText) : SR.PostconditionFailed; case ContractFailureKind.Invariant: return hasConditionText ? SR.Format(SR.InvariantFailed_Cnd, conditionText) : SR.InvariantFailed; case ContractFailureKind.PostconditionOnException: return hasConditionText ? SR.Format(SR.PostconditionOnExceptionFailed_Cnd, conditionText) : SR.PostconditionOnExceptionFailed; default: Contract.Assume(false, "Unreachable code"); return SR.AssumptionFailed; } } #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif private static String GetDisplayMessage(ContractFailureKind failureKind, String userMessage, String conditionText) { // Well-formatted English messages will take one of four forms. A sentence ending in // either a period or a colon, the condition string, then the message tacked // on to the end with two spaces in front. // Note that both the conditionText and userMessage may be null. Also, // on Silverlight we may not be able to look up a friendly string for the // error message. Let's leverage Silverlight's default error message there. String failureMessage = GetFailureMessage(failureKind, conditionText); // Now add in the user message, if present. if (!String.IsNullOrEmpty(userMessage)) { return failureMessage + " " + userMessage; } else { return failureMessage; } } //#if !FEATURE_CORECLR // // Will trigger escalation policy, if hosted and the host requested us to do something (such as // // abort the thread or exit the process). Starting in Dev11, for hosted apps the default behavior // // is to throw an exception. // // Implementation notes: // // We implement our default behavior of throwing an exception by simply returning from our native // // method inside the runtime and falling through to throw an exception. // // We must call through this method before calling the method on the Environment class // // because our security team does not yet support SecuritySafeCritical on P/Invoke methods. // // Note this can be called in the context of throwing another exception (EnsuresOnThrow). //#if FEATURE_UNTRUSTED_CALLERS //#endif //#if FEATURE_RELIABILITY_CONTRACTS // [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] //#endif // [DebuggerNonUserCode] // private static void TriggerCodeContractEscalationPolicy(ContractFailureKind failureKind, String message, String conditionText, Exception innerException) // { // String exceptionAsString = null; // if (innerException != null) // exceptionAsString = innerException.ToString(); // Environment.TriggerCodeContractFailure(failureKind, message, conditionText, exceptionAsString); // } //#endif // !FEATURE_CORECLR } } // namespace System.Runtime.CompilerServices
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.NetCore.Analyzers.Runtime.SerializationRulesDiagnosticAnalyzer, Microsoft.NetCore.Analyzers.Runtime.ImplementSerializationConstructorsFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.NetCore.Analyzers.Runtime.SerializationRulesDiagnosticAnalyzer, Microsoft.NetCore.Analyzers.Runtime.ImplementSerializationConstructorsFixer>; namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests { public partial class ImplementSerializationConstructorsTests { [Fact] public async Task CA2229NoConstructor() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.Serialization; [Serializable] public class CA2229NoConstructor : ISerializable { public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } }", GetCA2229CSharpResultAt(5, 30, "CA2229NoConstructor")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Runtime.Serialization <Serializable> Public Class CA2229NoConstructor Implements ISerializable Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext) Implements ISerializable.GetObjectData throw new NotImplementedException() End Sub End Class", GetCA2229BasicResultAt(5, 30, "CA2229NoConstructor")); } [Fact] public async Task CA2229NoConstructorInternal() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.Serialization; [Serializable] internal class CA2229NoConstructorInternal : ISerializable { public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Runtime.Serialization <Serializable> Friend Class CA2229NoConstructorInternal Implements ISerializable Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext) Implements ISerializable.GetObjectData throw new NotImplementedException() End Sub End Class"); } [Fact] public async Task CA2229HasConstructor() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.Serialization; [Serializable] public class CA2229HasConstructor : ISerializable { protected CA2229HasConstructor(SerializationInfo info, StreamingContext context) { } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Runtime.Serialization <Serializable> Public Class CA2229HasConstructor Implements ISerializable Protected Sub New(info As SerializationInfo, context As StreamingContext) End Sub Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext) Implements ISerializable.GetObjectData throw new NotImplementedException() End Sub End Class"); } [Fact] public async Task CA2229HasConstructor1() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.Serialization; [Serializable] public sealed class CA2229HasConstructor1 : ISerializable { private CA2229HasConstructor1(SerializationInfo info, StreamingContext context) { } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Runtime.Serialization <Serializable> Public NotInheritable Class CA2229HasConstructor1 Implements ISerializable Private Sub New(info As SerializationInfo, context As StreamingContext) End Sub Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext) Implements ISerializable.GetObjectData throw new NotImplementedException() End Sub End Class"); } [Fact] public async Task CA2229HasConstructorWrongAccessibility() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.Serialization; [Serializable] public class CA2229HasConstructorWrongAccessibility : ISerializable { public CA2229HasConstructorWrongAccessibility(SerializationInfo info, StreamingContext context) { } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } }", GetCA2229UnsealedCSharpResultAt(7, 28, "CA2229HasConstructorWrongAccessibility")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Runtime.Serialization <Serializable> Public Class CA2229HasConstructorWrongAccessibility Implements ISerializable Public Sub New(info As SerializationInfo, context As StreamingContext) End Sub Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext) Implements ISerializable.GetObjectData throw new NotImplementedException() End Sub End Class", GetCA2229UnsealedBasicResultAt(8, 32, "CA2229HasConstructorWrongAccessibility")); } [Fact] public async Task CA2229HasConstructorWrongAccessibility1() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.Serialization; [Serializable] public class CA2229HasConstructorWrongAccessibility1 : ISerializable { internal CA2229HasConstructorWrongAccessibility1(SerializationInfo info, StreamingContext context) { } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } }", GetCA2229UnsealedCSharpResultAt(7, 30, "CA2229HasConstructorWrongAccessibility1")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Runtime.Serialization <Serializable> Public Class CA2229HasConstructorWrongAccessibility1 Implements ISerializable Friend Sub New(info As SerializationInfo, context As StreamingContext) End Sub Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext) Implements ISerializable.GetObjectData throw new NotImplementedException() End Sub End Class", GetCA2229UnsealedBasicResultAt(8, 32, "CA2229HasConstructorWrongAccessibility1")); } [Fact] public async Task CA2229HasConstructorWrongAccessibility2() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.Serialization; [Serializable] public sealed class CA2229HasConstructorWrongAccessibility2 : ISerializable { protected internal CA2229HasConstructorWrongAccessibility2(SerializationInfo info, StreamingContext context) { } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } }", GetCA2229SealedCSharpResultAt(7, 40, "CA2229HasConstructorWrongAccessibility2")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Runtime.Serialization <Serializable> Public NotInheritable Class CA2229HasConstructorWrongAccessibility2 Implements ISerializable Protected Friend Sub New(info As SerializationInfo, context As StreamingContext) End Sub Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext) Implements ISerializable.GetObjectData throw new NotImplementedException() End Sub End Class", GetCA2229SealedBasicResultAt(8, 42, "CA2229HasConstructorWrongAccessibility2")); } [Fact] public async Task CA2229HasConstructorWrongAccessibility3() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.Serialization; [Serializable] public class CA2229HasConstructorWrongAccessibility3 : ISerializable { protected internal CA2229HasConstructorWrongAccessibility3(SerializationInfo info, StreamingContext context) { } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } }", GetCA2229UnsealedCSharpResultAt(7, 40, "CA2229HasConstructorWrongAccessibility3")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Runtime.Serialization <Serializable> Public Class CA2229HasConstructorWrongAccessibility3 Implements ISerializable Protected Friend Sub New(info As SerializationInfo, context As StreamingContext) End Sub Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext) Implements ISerializable.GetObjectData throw new NotImplementedException() End Sub End Class", GetCA2229UnsealedBasicResultAt(8, 42, "CA2229HasConstructorWrongAccessibility3")); } [Fact] public async Task CA2229HasConstructorWrongOrder() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.Serialization; [Serializable] public class CA2229HasConstructorWrongOrder : ISerializable { protected CA2229HasConstructorWrongOrder(StreamingContext context, SerializationInfo info) { } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } }", GetCA2229CSharpResultAt(5, 30, "CA2229HasConstructorWrongOrder")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Runtime.Serialization <Serializable> Public Class CA2229HasConstructorWrongOrder Implements ISerializable Protected Sub New(context As StreamingContext, info As SerializationInfo) End Sub Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext) Implements ISerializable.GetObjectData throw new NotImplementedException() End Sub End Class", GetCA2229BasicResultAt(5, 30, "CA2229HasConstructorWrongOrder")); } [Fact] public async Task CA2229SerializableProper() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.Serialization; [Serializable] public class CA2229SerializableProper : ISerializable { public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } }", GetCA2229CSharpResultAt(5, 30, "CA2229SerializableProper")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Runtime.Serialization <Serializable> Public Class CA2229SerializableProper Implements ISerializable Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext) Implements ISerializable.GetObjectData throw new NotImplementedException() End Sub End Class", GetCA2229BasicResultAt(5, 30, "CA2229SerializableProper")); } private static DiagnosticResult GetCA2229CSharpResultAt(int line, int column, string objectName) => #pragma warning disable RS0030 // Do not used banned APIs VerifyCS.Diagnostic(SerializationRulesDiagnosticAnalyzer.RuleCA2229Default) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(objectName); private static DiagnosticResult GetCA2229BasicResultAt(int line, int column, string objectName) => #pragma warning disable RS0030 // Do not used banned APIs VerifyVB.Diagnostic(SerializationRulesDiagnosticAnalyzer.RuleCA2229Default) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(objectName); private static DiagnosticResult GetCA2229SealedCSharpResultAt(int line, int column, string objectName) => #pragma warning disable RS0030 // Do not used banned APIs VerifyCS.Diagnostic(SerializationRulesDiagnosticAnalyzer.RuleCA2229Sealed) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(objectName); private static DiagnosticResult GetCA2229SealedBasicResultAt(int line, int column, string objectName) => #pragma warning disable RS0030 // Do not used banned APIs VerifyVB.Diagnostic(SerializationRulesDiagnosticAnalyzer.RuleCA2229Sealed) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(objectName); private static DiagnosticResult GetCA2229UnsealedCSharpResultAt(int line, int column, string objectName) => #pragma warning disable RS0030 // Do not used banned APIs VerifyCS.Diagnostic(SerializationRulesDiagnosticAnalyzer.RuleCA2229Unsealed) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(objectName); private static DiagnosticResult GetCA2229UnsealedBasicResultAt(int line, int column, string objectName) => #pragma warning disable RS0030 // Do not used banned APIs VerifyVB.Diagnostic(SerializationRulesDiagnosticAnalyzer.RuleCA2229Unsealed) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(objectName); } }
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member namespace SqlStreamStore.Imports.Ensure.That { using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using SqlStreamStore.Imports.Ensure.That.Extensions; public static class EnsureCollectionExtensions { [DebuggerStepThrough] public static Param<T> HasItems<T>(this Param<T> param) where T : class, ICollection { if (!Ensure.IsActive) return param; if (param.Value == null || param.Value.Count < 1) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_HasItemsFailed); return param; } [DebuggerStepThrough] public static Param<Collection<T>> HasItems<T>(this Param<Collection<T>> param) { if (!Ensure.IsActive) return param; if (param.Value == null || param.Value.Count < 1) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_HasItemsFailed); return param; } [DebuggerStepThrough] public static Param<ICollection<T>> HasItems<T>(this Param<ICollection<T>> param) { if (!Ensure.IsActive) return param; if (param.Value == null || param.Value.Count < 1) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_HasItemsFailed); return param; } [DebuggerStepThrough] public static Param<T[]> HasItems<T>(this Param<T[]> param) { if (!Ensure.IsActive) return param; if (param.Value == null) throw ExceptionFactory.CreateForParamNullValidation(param, ExceptionMessages.Common_IsNotNull_Failed); if (param.Value.Length < 1) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_HasItemsFailed); return param; } [DebuggerStepThrough] public static Param<List<T>> HasItems<T>(this Param<List<T>> param) { if (!Ensure.IsActive) return param; if (param.Value == null || param.Value.Count < 1) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_HasItemsFailed); return param; } [DebuggerStepThrough] public static Param<IList<T>> HasItems<T>(this Param<IList<T>> param) { if (!Ensure.IsActive) return param; if (param.Value == null || param.Value.Count < 1) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_HasItemsFailed); return param; } [DebuggerStepThrough] public static Param<IDictionary<TKey, TValue>> HasItems<TKey, TValue>(this Param<IDictionary<TKey, TValue>> param) { if (!Ensure.IsActive) return param; if (param.Value == null || param.Value.Count < 1) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_HasItemsFailed); return param; } [DebuggerStepThrough] public static Param<T[]> SizeIs<T>(this Param<T[]> param, int expected) { if (!Ensure.IsActive) return param; if (param.Value.Length != expected) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_SizeIs_Failed.Inject(expected, param.Value.Length)); return param; } [DebuggerStepThrough] public static Param<T[]> SizeIs<T>(this Param<T[]> param, long expected) { if (!Ensure.IsActive) return param; if (param.Value.Length != expected) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_SizeIs_Failed.Inject(expected, param.Value.Length)); return param; } [DebuggerStepThrough] public static Param<T> SizeIs<T>(this Param<T> param, int expected) where T : ICollection { if (!Ensure.IsActive) return param; if (param.Value.Count != expected) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_SizeIs_Failed.Inject(expected, param.Value.Count)); return param; } [DebuggerStepThrough] public static Param<T> SizeIs<T>(this Param<T> param, long expected) where T : ICollection { if (!Ensure.IsActive) return param; if (param.Value.Count != expected) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_SizeIs_Failed.Inject(expected, param.Value.Count)); return param; } [DebuggerStepThrough] public static Param<ICollection<T>> SizeIs<T>(this Param<ICollection<T>> param, int expected) { if (!Ensure.IsActive) return param; if (param.Value.Count != expected) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_SizeIs_Failed.Inject(expected, param.Value.Count)); return param; } [DebuggerStepThrough] public static Param<ICollection<T>> SizeIs<T>(this Param<ICollection<T>> param, long expected) { if (!Ensure.IsActive) return param; if (param.Value.Count != expected) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_SizeIs_Failed.Inject(expected, param.Value.Count)); return param; } [DebuggerStepThrough] public static Param<IList<T>> SizeIs<T>(this Param<IList<T>> param, int expected) { if (!Ensure.IsActive) return param; if (param.Value.Count != expected) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_SizeIs_Failed.Inject(expected, param.Value.Count)); return param; } [DebuggerStepThrough] public static Param<IList<T>> SizeIs<T>(this Param<IList<T>> param, long expected) { if (!Ensure.IsActive) return param; if (param.Value.Count != expected) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_SizeIs_Failed.Inject(expected, param.Value.Count)); return param; } [DebuggerStepThrough] public static Param<IDictionary<TKey, TValue>> SizeIs<TKey, TValue>(this Param<IDictionary<TKey, TValue>> param, int expected) { if (!Ensure.IsActive) return param; if (param.Value.Count != expected) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_SizeIs_Failed.Inject(expected, param.Value.Count)); return param; } [DebuggerStepThrough] public static Param<IDictionary<TKey, TValue>> SizeIs<TKey, TValue>(this Param<IDictionary<TKey, TValue>> param, long expected) { if (!Ensure.IsActive) return param; if (param.Value.Count != expected) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_SizeIs_Failed.Inject(expected, param.Value.Count)); return param; } [DebuggerStepThrough] public static Param<IDictionary<TKey, TValue>> ContainsKey<TKey, TValue>(this Param<IDictionary<TKey, TValue>> param, TKey key) { if (!Ensure.IsActive) return param; if (!param.Value.ContainsKey(key)) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_ContainsKey_Failed.Inject(key)); return param; } [DebuggerStepThrough] public static Param<Dictionary<TKey, TValue>> ContainsKey<TKey, TValue>(this Param<Dictionary<TKey, TValue>> param, TKey key) { if (!Ensure.IsActive) return param; if (!param.Value.ContainsKey(key)) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_ContainsKey_Failed.Inject(key)); return param; } [DebuggerStepThrough] public static Param<IList<T>> Any<T>(this Param<IList<T>> param, Func<T, bool> predicate) { if (!Ensure.IsActive) return param; if (!param.Value.Any(predicate)) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_Any_Failed); return param; } [DebuggerStepThrough] public static Param<List<T>> Any<T>(this Param<List<T>> param, Func<T, bool> predicate) { if (!Ensure.IsActive) return param; if (!param.Value.Any(predicate)) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_Any_Failed); return param; } [DebuggerStepThrough] public static Param<ICollection<T>> Any<T>(this Param<ICollection<T>> param, Func<T, bool> predicate) { if (!Ensure.IsActive) return param; if (!param.Value.Any(predicate)) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_Any_Failed); return param; } [DebuggerStepThrough] public static Param<Collection<T>> Any<T>(this Param<Collection<T>> param, Func<T, bool> predicate) { if (!Ensure.IsActive) return param; if (!param.Value.Any(predicate)) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_Any_Failed); return param; } [DebuggerStepThrough] public static Param<T[]> Any<T>(this Param<T[]> param, Func<T, bool> predicate) { if (!Ensure.IsActive) return param; if (!param.Value.Any(predicate)) throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Collections_Any_Failed); return param; } } }
#define USE_TRACING using System; using Google.GData.Client; using Google.GData.Extensions; namespace Google.GData.Contacts { /// <summary> /// Entry API customization class for defining entries in an Event feed. /// </summary> public class ContactEntry : BaseContactEntry { /// <summary> /// default contact term string for the contact relationship link /// </summary> public static string ContactTerm = "http://schemas.google.com/contact/2008#contact"; /// <summary> /// Category used to label entries that contain contact extension data. /// </summary> public static AtomCategory CONTACT_CATEGORY = new AtomCategory(ContactTerm, new AtomUri(BaseNameTable.gKind)); private ExtensionCollection<CalendarLink> calendars; private ExtensionCollection<EMail> emails; private ExtensionCollection<Event> events; private ExtensionCollection<ExternalId> externalIds; private ExtensionCollection<GroupMembership> groups; private ExtensionCollection<Hobby> hobbies; private ExtensionCollection<IMAddress> ims; private ExtensionCollection<Jot> jots; private ExtensionCollection<Language> languages; private ExtensionCollection<Organization> organizations; private ExtensionCollection<PhoneNumber> phonenumbers; private ExtensionCollection<Relation> relations; private ExtensionCollection<StructuredPostalAddress> structuredAddress; private ExtensionCollection<UserDefinedField> userDefinedFiels; private ExtensionCollection<Website> websites; /// <summary> /// Constructs a new ContactEntry instance with the appropriate category /// to indicate that it is an event. /// </summary> public ContactEntry() { Tracing.TraceMsg("Created Contact Entry"); Categories.Add(CONTACT_CATEGORY); AddExtension(new GroupMembership()); AddExtension(new Where()); ContactsKindExtensions.AddExtension(this); // collections AddExtension(new CalendarLink()); AddExtension(new Event()); AddExtension(new ExternalId()); AddExtension(new Hobby()); AddExtension(new Jot()); AddExtension(new Language()); AddExtension(new Relation()); AddExtension(new UserDefinedField()); AddExtension(new Website()); // singletons AddExtension(new BillingInformation()); AddExtension(new Birthday()); AddExtension(new DirectoryServer()); AddExtension(new Initials()); AddExtension(new MaidenName()); AddExtension(new Mileage()); AddExtension(new Nickname()); AddExtension(new Occupation()); AddExtension(new Priority()); AddExtension(new Sensitivity()); AddExtension(new ShortName()); AddExtension(new Status()); AddExtension(new Subject()); } /// <summary> /// Location associated with the contact /// </summary> /// <returns></returns> public string Location { get { Where w = FindExtension(GDataParserNameTable.XmlWhereElement, BaseNameTable.gNamespace) as Where; return w != null ? w.ValueString : null; } set { Where w = null; if (value != null) { w = new Where(null, null, value); } ReplaceExtension(GDataParserNameTable.XmlWhereElement, BaseNameTable.gNamespace, w); } } /// <summary> /// convenience accessor to find the primary Email /// there is no setter, to change this use the Primary Flag on /// an individual object /// </summary> public EMail PrimaryEmail { get { foreach (EMail e in Emails) { if (e.Primary) { return e; } } return null; } } /// <summary> /// convenience accessor to find the primary Phonenumber /// there is no setter, to change this use the Primary Flag on /// an individual object /// </summary> public PhoneNumber PrimaryPhonenumber { get { foreach (PhoneNumber p in Phonenumbers) { if (p.Primary) { return p; } } return null; } } /// <summary> /// convenience accessor to find the primary PostalAddress /// there is no setter, to change this use the Primary Flag on /// an individual object /// </summary> public StructuredPostalAddress PrimaryPostalAddress { get { foreach (StructuredPostalAddress p in PostalAddresses) { if (p.Primary) { return p; } } return null; } } /// <summary> /// convenience accessor to find the primary IMAddress /// there is no setter, to change this use the Primary Flag on /// an individual object /// </summary> public IMAddress PrimaryIMAddress { get { foreach (IMAddress im in IMs) { if (im.Primary) { return im; } } return null; } } /// <summary> /// returns the groupmembership info on this object /// </summary> /// <returns></returns> public ExtensionCollection<GroupMembership> GroupMembership { get { if (groups == null) { groups = new ExtensionCollection<GroupMembership>(this); } return groups; } } /// <summary> /// getter/setter for the email extension element /// </summary> public ExtensionCollection<EMail> Emails { get { if (emails == null) { emails = new ExtensionCollection<EMail>(this); } return emails; } } /// <summary> /// getter/setter for the IM extension element /// </summary> public ExtensionCollection<IMAddress> IMs { get { if (ims == null) { ims = new ExtensionCollection<IMAddress>(this); } return ims; } } /// <summary> /// returns the phonenumber collection /// </summary> public ExtensionCollection<PhoneNumber> Phonenumbers { get { if (phonenumbers == null) { phonenumbers = new ExtensionCollection<PhoneNumber>(this); } return phonenumbers; } } /// <summary> /// Postal address split into components. It allows to store the address in locale independent format. /// The fields can be interpreted and used to generate formatted, locale dependent address /// </summary> public ExtensionCollection<StructuredPostalAddress> PostalAddresses { get { if (structuredAddress == null) { structuredAddress = new ExtensionCollection<StructuredPostalAddress>(this); } return structuredAddress; } } /// <summary> /// returns the phonenumber collection /// </summary> public ExtensionCollection<Organization> Organizations { get { if (organizations == null) { organizations = new ExtensionCollection<Organization>(this); } return organizations; } } /// <summary> /// getter for the CalendarLink collections /// </summary> public ExtensionCollection<CalendarLink> Calendars { get { if (calendars == null) { calendars = new ExtensionCollection<CalendarLink>(this); } return calendars; } } /// <summary> /// getter for the Events collections /// </summary> public ExtensionCollection<Event> Events { get { if (events == null) { events = new ExtensionCollection<Event>(this); } return events; } } /// <summary> /// getter for the externalids collections /// </summary> public ExtensionCollection<ExternalId> ExternalIds { get { if (externalIds == null) { externalIds = new ExtensionCollection<ExternalId>(this); } return externalIds; } } /// <summary> /// getter for the Hobby collections /// </summary> public ExtensionCollection<Hobby> Hobbies { get { if (hobbies == null) { hobbies = new ExtensionCollection<Hobby>(this); } return hobbies; } } /// <summary> /// getter for the Jot collections /// </summary> public ExtensionCollection<Jot> Jots { get { if (jots == null) { jots = new ExtensionCollection<Jot>(this); } return jots; } } /// <summary> /// getter for the languages collections /// </summary> public ExtensionCollection<Language> Languages { get { if (languages == null) { languages = new ExtensionCollection<Language>(this); } return languages; } } /// <summary> /// getter for the Relation collections /// </summary> public ExtensionCollection<Relation> Relations { get { if (relations == null) { relations = new ExtensionCollection<Relation>(this); } return relations; } } /// <summary> /// getter for the UserDefinedField collections /// </summary> public ExtensionCollection<UserDefinedField> UserDefinedFields { get { if (userDefinedFiels == null) { userDefinedFiels = new ExtensionCollection<UserDefinedField>(this); } return userDefinedFiels; } } /// <summary> /// getter for the website collections /// </summary> public ExtensionCollection<Website> Websites { get { if (websites == null) { websites = new ExtensionCollection<Website>(this); } return websites; } } /// <summary> /// retrieves the Uri of the Photo Link. To set this, you need to create an AtomLink object /// and add/replace it in the atomlinks colleciton. /// </summary> /// <returns></returns> public Uri PhotoUri { get { AtomLink link = Links.FindService(GDataParserNameTable.ServicePhoto, null); return link == null ? null : new Uri(link.HRef.ToString()); } } /// <summary> /// if a photo is present on this contact, it will have an etag associated with it, /// that needs to be used when you want to delete or update that picture. /// </summary> /// <returns>the etag value as a string</returns> public string PhotoEtag { get { AtomLink link = PhotoLink; if (link != null) { foreach (XmlExtension x in link.ExtensionElements) { if (x.XmlNameSpace == GDataParserNameTable.gNamespace && x.XmlName == GDataParserNameTable.XmlEtagAttribute) { return x.Node.Value; } } } return null; } set { AtomLink link = PhotoLink; if (link != null) { foreach (XmlExtension x in link.ExtensionElements) { if (x.XmlNameSpace == GDataParserNameTable.gNamespace && x.XmlName == GDataParserNameTable.XmlEtagAttribute) { x.Node.Value = value; } } } } } private AtomLink PhotoLink { get { AtomLink link = Links.FindService(GDataParserNameTable.ServicePhoto, null); return link; } } /// <summary> /// returns the Name object /// </summary> public Name Name { get { return FindExtension(GDataParserNameTable.NameElement, BaseNameTable.gNamespace) as Name; } set { ReplaceExtension(GDataParserNameTable.NameElement, BaseNameTable.gNamespace, value); } } /// <summary> /// Contact billing information. /// </summary> /// <returns></returns> public string BillingInformation { get { return GetStringValue<BillingInformation>(ContactsNameTable.BillingInformationElement, ContactsNameTable.NSContacts); } set { SetStringValue<BillingInformation>(value, ContactsNameTable.BillingInformationElement, ContactsNameTable.NSContacts); } } /// <summary> /// Contact's birthday. /// </summary> /// <returns></returns> public string Birthday { get { Birthday b = FindExtension(ContactsNameTable.BirthdayElement, ContactsNameTable.NSContacts) as Birthday; if (b != null) { return b.When; } return null; } set { Birthday b = null; if (value != null) { b = new Birthday(value); } ReplaceExtension(ContactsNameTable.BirthdayElement, ContactsNameTable.NSContacts, b); } } /// <summary> /// Directory server associated with the contact. /// </summary> /// <returns></returns> public string DirectoryServer { get { return GetStringValue<DirectoryServer>(ContactsNameTable.DirectoryServerElement, ContactsNameTable.NSContacts); } set { SetStringValue<DirectoryServer>(value, ContactsNameTable.DirectoryServerElement, ContactsNameTable.NSContacts); } } /// <summary> /// Contact's initals /// </summary> /// <returns></returns> public string Initials { get { return GetStringValue<Initials>(ContactsNameTable.InitialsElement, ContactsNameTable.NSContacts); } set { SetStringValue<Initials>(value, ContactsNameTable.InitialsElement, ContactsNameTable.NSContacts); } } /// <summary> /// Maiden name associated with the contact. /// </summary> /// <returns></returns> public string MaidenName { get { return GetStringValue<MaidenName>(ContactsNameTable.MaidenNameElement, ContactsNameTable.NSContacts); } set { SetStringValue<MaidenName>(value, ContactsNameTable.MaidenNameElement, ContactsNameTable.NSContacts); } } /// <summary> /// Mileage associated with the contact. /// </summary> /// <returns></returns> public string Mileage { get { return GetStringValue<Mileage>(ContactsNameTable.MileageElement, ContactsNameTable.NSContacts); } set { SetStringValue<Mileage>(value, ContactsNameTable.MileageElement, ContactsNameTable.NSContacts); } } /// <summary> /// Nickname associated with the contact. /// </summary> /// <returns></returns> public string Nickname { get { return GetStringValue<Nickname>(ContactsNameTable.NicknameElement, ContactsNameTable.NSContacts); } set { SetStringValue<Nickname>(value, ContactsNameTable.NicknameElement, ContactsNameTable.NSContacts); } } /// <summary> /// Occupation associated with the contact. /// </summary> /// <returns></returns> public string Occupation { get { return GetStringValue<Occupation>(ContactsNameTable.OccupationElement, ContactsNameTable.NSContacts); } set { SetStringValue<Occupation>(value, ContactsNameTable.OccupationElement, ContactsNameTable.NSContacts); } } /// <summary> /// Priority associated with the contact. /// </summary> /// <returns></returns> public string Priority { get { Priority b = FindExtension(ContactsNameTable.PriorityElement, ContactsNameTable.NSContacts) as Priority; if (b != null) { return b.Relation; } return null; } set { Priority b = null; if (value != null) { b = new Priority(value); } ReplaceExtension(ContactsNameTable.PriorityElement, ContactsNameTable.NSContacts, b); } } /// <summary> /// Sensitivity associated with the contact. /// </summary> /// <returns></returns> public string Sensitivity { get { Sensitivity b = FindExtension(ContactsNameTable.SensitivityElement, ContactsNameTable.NSContacts) as Sensitivity; if (b != null) { return b.Relation; } return null; } set { Sensitivity b = null; if (value != null) { b = new Sensitivity(value); } ReplaceExtension(ContactsNameTable.SensitivityElement, ContactsNameTable.NSContacts, b); } } /// <summary> /// Contact's short name. /// </summary> /// <returns></returns> public string ShortName { get { return GetStringValue<ShortName>(ContactsNameTable.ShortNameElement, ContactsNameTable.NSContacts); } set { SetStringValue<ShortName>(value, ContactsNameTable.ShortNameElement, ContactsNameTable.NSContacts); } } /// <summary> /// Person's status. /// </summary> /// <returns></returns> public Status Status { get { return FindExtension(ContactsNameTable.StatusElement, ContactsNameTable.NSContacts) as Status; } set { ReplaceExtension(ContactsNameTable.StatusElement, ContactsNameTable.NSContacts, value); } } /// <summary> /// Subject associated with the contact. /// </summary> /// <returns></returns> public string Subject { get { return GetStringValue<Subject>(ContactsNameTable.SubjectElement, ContactsNameTable.NSContacts); } set { SetStringValue<Subject>(value, ContactsNameTable.SubjectElement, ContactsNameTable.NSContacts); } } /// <summary> /// typed override of the Update method /// </summary> /// <returns></returns> public new ContactEntry Update() { return base.Update() as ContactEntry; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Security; using System.Text.RegularExpressions; using System.Threading; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Store; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Transactions; /// <summary> /// Managed environment. Acts as a gateway for native code. /// </summary> internal static class ExceptionUtils { /** NoClassDefFoundError fully-qualified class name which is important during startup phase. */ private const string ClsNoClsDefFoundErr = "java.lang.NoClassDefFoundError"; /** NoSuchMethodError fully-qualified class name which is important during startup phase. */ private const string ClsNoSuchMthdErr = "java.lang.NoSuchMethodError"; /** InteropCachePartialUpdateException. */ private const string ClsCachePartialUpdateErr = "org.apache.ignite.internal.processors.platform.cache.PlatformCachePartialUpdateException"; /** Map with predefined exceptions. */ private static readonly IDictionary<string, ExceptionFactoryDelegate> Exs = new Dictionary<string, ExceptionFactoryDelegate>(); /** Exception factory delegate. */ private delegate Exception ExceptionFactoryDelegate(IIgnite ignite, string msg, Exception innerEx); /** Inner class regex. */ private static readonly Regex InnerClassRegex = new Regex(@"class ([^\s]+): (.*)", RegexOptions.Compiled); /// <summary> /// Static initializer. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Readability")] static ExceptionUtils() { // Common Java exceptions mapped to common .Net exceptions. Exs["java.lang.IllegalArgumentException"] = (i, m, e) => new ArgumentException(m, e); Exs["java.lang.IllegalStateException"] = (i, m, e) => new InvalidOperationException(m, e); Exs["java.lang.UnsupportedOperationException"] = (i, m, e) => new NotImplementedException(m, e); Exs["java.lang.InterruptedException"] = (i, m, e) => new ThreadInterruptedException(m, e); // Generic Ignite exceptions. Exs["org.apache.ignite.IgniteException"] = (i, m, e) => new IgniteException(m, e); Exs["org.apache.ignite.IgniteCheckedException"] = (i, m, e) => new IgniteException(m, e); Exs["org.apache.ignite.IgniteClientDisconnectedException"] = (i, m, e) => new ClientDisconnectedException(m, e, i.GetCluster().ClientReconnectTask); Exs["org.apache.ignite.internal.IgniteClientDisconnectedCheckedException"] = (i, m, e) => new ClientDisconnectedException(m, e, i.GetCluster().ClientReconnectTask); // Cluster exceptions. Exs["org.apache.ignite.cluster.ClusterGroupEmptyException"] = (i, m, e) => new ClusterGroupEmptyException(m, e); Exs["org.apache.ignite.cluster.ClusterTopologyException"] = (i, m, e) => new ClusterTopologyException(m, e); // Compute exceptions. Exs["org.apache.ignite.compute.ComputeExecutionRejectedException"] = (i, m, e) => new ComputeExecutionRejectedException(m, e); Exs["org.apache.ignite.compute.ComputeJobFailoverException"] = (i, m, e) => new ComputeJobFailoverException(m, e); Exs["org.apache.ignite.compute.ComputeTaskCancelledException"] = (i, m, e) => new ComputeTaskCancelledException(m, e); Exs["org.apache.ignite.compute.ComputeTaskTimeoutException"] = (i, m, e) => new ComputeTaskTimeoutException(m, e); Exs["org.apache.ignite.compute.ComputeUserUndeclaredException"] = (i, m, e) => new ComputeUserUndeclaredException(m, e); // Cache exceptions. Exs["javax.cache.CacheException"] = (i, m, e) => new CacheException(m, e); Exs["javax.cache.integration.CacheLoaderException"] = (i, m, e) => new CacheStoreException(m, e); Exs["javax.cache.integration.CacheWriterException"] = (i, m, e) => new CacheStoreException(m, e); Exs["javax.cache.processor.EntryProcessorException"] = (i, m, e) => new CacheEntryProcessorException(m, e); Exs["org.apache.ignite.cache.CacheAtomicUpdateTimeoutException"] = (i, m, e) => new CacheAtomicUpdateTimeoutException(m, e); // Transaction exceptions. Exs["org.apache.ignite.transactions.TransactionOptimisticException"] = (i, m, e) => new TransactionOptimisticException(m, e); Exs["org.apache.ignite.transactions.TransactionTimeoutException"] = (i, m, e) => new TransactionTimeoutException(m, e); Exs["org.apache.ignite.transactions.TransactionRollbackException"] = (i, m, e) => new TransactionRollbackException(m, e); Exs["org.apache.ignite.transactions.TransactionHeuristicException"] = (i, m, e) => new TransactionHeuristicException(m, e); // Security exceptions. Exs["org.apache.ignite.IgniteAuthenticationException"] = (i, m, e) => new SecurityException(m, e); Exs["org.apache.ignite.plugin.security.GridSecurityException"] = (i, m, e) => new SecurityException(m, e); // Future exceptions Exs["org.apache.ignite.lang.IgniteFutureCancelledException"] = (i, m, e) => new IgniteFutureCancelledException(m, e); Exs["org.apache.ignite.internal.IgniteFutureCancelledCheckedException"] = (i, m, e) => new IgniteFutureCancelledException(m, e); } /// <summary> /// Creates exception according to native code class and message. /// </summary> /// <param name="ignite">The ignite.</param> /// <param name="clsName">Exception class name.</param> /// <param name="msg">Exception message.</param> /// <param name="stackTrace">Native stack trace.</param> /// <param name="reader">Error data reader.</param> /// <returns>Exception.</returns> public static Exception GetException(IIgnite ignite, string clsName, string msg, string stackTrace, BinaryReader reader = null) { Exception innerException = string.IsNullOrEmpty(stackTrace) ? null : new JavaException(stackTrace); ExceptionFactoryDelegate ctor; if (Exs.TryGetValue(clsName, out ctor)) { var match = InnerClassRegex.Match(msg ?? string.Empty); ExceptionFactoryDelegate innerCtor; if (match.Success && Exs.TryGetValue(match.Groups[1].Value, out innerCtor)) return ctor(ignite, msg, innerCtor(ignite, match.Groups[2].Value, innerException)); return ctor(ignite, msg, innerException); } if (ClsNoClsDefFoundErr.Equals(clsName, StringComparison.OrdinalIgnoreCase)) return new IgniteException("Java class is not found (did you set IGNITE_HOME environment " + "variable?): " + msg, innerException); if (ClsNoSuchMthdErr.Equals(clsName, StringComparison.OrdinalIgnoreCase)) return new IgniteException("Java class method is not found (did you set IGNITE_HOME environment " + "variable?): " + msg, innerException); if (ClsCachePartialUpdateErr.Equals(clsName, StringComparison.OrdinalIgnoreCase)) return ProcessCachePartialUpdateException(ignite, msg, stackTrace, reader); return new IgniteException(string.Format("Java exception occurred [class={0}, message={1}]", clsName, msg), innerException); } /// <summary> /// Process cache partial update exception. /// </summary> /// <param name="ignite">The ignite.</param> /// <param name="msg">Message.</param> /// <param name="stackTrace">Stack trace.</param> /// <param name="reader">Reader.</param> /// <returns>CachePartialUpdateException.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private static Exception ProcessCachePartialUpdateException(IIgnite ignite, string msg, string stackTrace, BinaryReader reader) { if (reader == null) return new CachePartialUpdateException(msg, new IgniteException("Failed keys are not available.")); bool dataExists = reader.ReadBoolean(); Debug.Assert(dataExists); if (reader.ReadBoolean()) { bool keepBinary = reader.ReadBoolean(); BinaryReader keysReader = reader.Marshaller.StartUnmarshal(reader.Stream, keepBinary); try { return new CachePartialUpdateException(msg, ReadNullableList(keysReader)); } catch (Exception e) { // Failed to deserialize data. return new CachePartialUpdateException(msg, e); } } // Was not able to write keys. string innerErrCls = reader.ReadString(); string innerErrMsg = reader.ReadString(); Exception innerErr = GetException(ignite, innerErrCls, innerErrMsg, stackTrace); return new CachePartialUpdateException(msg, innerErr); } /// <summary> /// Create JVM initialization exception. /// </summary> /// <param name="clsName">Class name.</param> /// <param name="msg">Message.</param> /// <param name="stackTrace">Stack trace.</param> /// <returns>Exception.</returns> public static Exception GetJvmInitializeException(string clsName, string msg, string stackTrace) { if (clsName != null) return new IgniteException("Failed to initialize JVM.", GetException(null, clsName, msg, stackTrace)); if (msg != null) return new IgniteException("Failed to initialize JVM: " + msg + "\n" + stackTrace); return new IgniteException("Failed to initialize JVM."); } /// <summary> /// Reads nullable list. /// </summary> /// <param name="reader">Reader.</param> /// <returns>List.</returns> private static List<object> ReadNullableList(BinaryReader reader) { if (!reader.ReadBoolean()) return null; var size = reader.ReadInt(); var list = new List<object>(size); for (int i = 0; i < size; i++) list.Add(reader.ReadObject<object>()); return list; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using Xunit; namespace System.Linq.Parallel.Tests { public class ParallelEnumerableTests { // // Null query // [Fact] public static void NullQuery() { Assert.Throws<ArgumentNullException>(() => ((IEnumerable<int>)null).AsParallel()); Assert.Throws<ArgumentNullException>(() => ((IEnumerable)null).AsParallel()); Assert.Throws<ArgumentNullException>(() => ((Partitioner<int>)null).AsParallel()); Assert.Throws<ArgumentNullException>(() => ((int[])null).AsParallel()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.AsOrdered((ParallelQuery<int>)null)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.AsOrdered((ParallelQuery)null)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.AsUnordered<int>((ParallelQuery<int>)null)); } // // Range // public static IEnumerable<object[]> RangeData() { int[] datapoints = { 0, 1, 2, 16, }; foreach (int sign in new[] { -1, 1 }) { foreach (int start in datapoints) { foreach (int count in datapoints) { yield return new object[] { start * sign, count }; } } } yield return new object[] { int.MaxValue, 0 }; yield return new object[] { int.MaxValue, 1 }; yield return new object[] { int.MaxValue - 8, 8 + 1 }; yield return new object[] { int.MinValue, 0 }; yield return new object[] { int.MinValue, 1 }; } [Theory] [MemberData(nameof(RangeData))] public static void Range_UndefinedOrder(int start, int count) { ParallelQuery<int> query = ParallelEnumerable.Range(start, count); IntegerRangeSet seen = new IntegerRangeSet(start, count); Assert.All(query, x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData(nameof(RangeData))] public static void Range_AsOrdered(int start, int count) { ParallelQuery<int> query = ParallelEnumerable.Range(start, count).AsOrdered(); int current = start; Assert.All(query, x => Assert.Equal(current++, x)); Assert.Equal(count, current - start); } [Theory] [MemberData(nameof(RangeData))] public static void Range_AsSequential(int start, int count) { IEnumerable<int> query = ParallelEnumerable.Range(start, count).AsSequential(); int current = start; Assert.All(query, x => Assert.Equal(current++, x)); Assert.Equal(count, current - start); } [Theory] [MemberData(nameof(RangeData))] public static void Range_First(int start, int count) { ParallelQuery<int> query = ParallelEnumerable.Range(start, count); if (count == 0) { Assert.Throws<InvalidOperationException>(() => query.First()); } else { Assert.Equal(start, query.First()); } } [Theory] [MemberData(nameof(RangeData))] public static void Range_FirstOrDefault(int start, int count) { ParallelQuery<int> query = ParallelEnumerable.Range(start, count); Assert.Equal(count == 0 ? 0 : start, query.FirstOrDefault()); } [Theory] [MemberData(nameof(RangeData))] public static void Range_Last(int start, int count) { ParallelQuery<int> query = ParallelEnumerable.Range(start, count); if (count == 0) { Assert.Throws<InvalidOperationException>(() => query.Last()); } else { Assert.Equal(start + (count - 1), query.Last()); } } [Theory] [MemberData(nameof(RangeData))] public static void Range_LastOrDefault(int start, int count) { ParallelQuery<int> query = ParallelEnumerable.Range(start, count); Assert.Equal(count == 0 ? 0 : start + (count - 1), query.LastOrDefault()); } [Theory] [MemberData(nameof(RangeData))] public static void Range_Take(int start, int count) { ParallelQuery<int> query = ParallelEnumerable.Range(start, count).Take(count / 2); // Elements are taken from the first half of the list, but order is indeterminate. IntegerRangeSet seen = new IntegerRangeSet(start, count / 2); Assert.All(query, x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData(nameof(RangeData))] public static void Range_Skip(int start, int count) { ParallelQuery<int> query = ParallelEnumerable.Range(start, count).Skip(count / 2); // Skips over the first half of the list, but order is indeterminate. IntegerRangeSet seen = new IntegerRangeSet(start + count / 2, (count + 1) / 2); Assert.All(query, x => seen.Add(x)); seen.AssertComplete(); Assert.Empty(ParallelEnumerable.Range(start, count).Skip(count + 1)); } [Fact] public static void Range_Exception() { Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Range(0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Range(-8, -8)); Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Range(int.MaxValue, 2)); } // // Repeat // public static IEnumerable<object[]> RepeatData() { int[] datapoints = new[] { 0, 1, 2, 16, 128, 1024 }; foreach (int count in datapoints) { foreach (int element in datapoints) { yield return new object[] { element, count }; yield return new object[] { (long)element, count }; yield return new object[] { (double)element, count }; yield return new object[] { (decimal)element, count }; yield return new object[] { "" + element, count }; } yield return new object[] { (object)null, count }; yield return new object[] { (string)null, count }; } } [Theory] [MemberData(nameof(RepeatData))] public static void Repeat<T>(T element, int count) { ParallelQuery<T> query = ParallelEnumerable.Repeat(element, count); int counted = 0; Assert.All(query, e => { counted++; Assert.Equal(element, e); }); Assert.Equal(count, counted); } [Fact] public static void Repeat_Exception() { Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Repeat(1, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Repeat((long)1024, -1024)); Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Repeat(2.0, -2)); Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Repeat((decimal)8, -8)); Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Repeat("fail", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Repeat((string)null, -1)); } // // Empty // public static IEnumerable<object[]> EmptyData() { yield return new object[] { default(int) }; yield return new object[] { default(long) }; yield return new object[] { default(double) }; yield return new object[] { default(decimal) }; yield return new object[] { default(string) }; yield return new object[] { default(object) }; } [Theory] [MemberData(nameof(EmptyData))] public static void Empty<T>(T def) { Assert.Empty(ParallelEnumerable.Empty<T>()); Assert.False(ParallelEnumerable.Empty<T>().Any(x => true)); Assert.False(ParallelEnumerable.Empty<T>().Contains(default(T))); Assert.Equal(0, ParallelEnumerable.Empty<T>().Count()); Assert.Equal(0, ParallelEnumerable.Empty<T>().LongCount()); Assert.Equal(new T[0], ParallelEnumerable.Empty<T>().ToArray()); Assert.Equal(new Dictionary<T, T>(), ParallelEnumerable.Empty<T>().ToDictionary(x => x)); Assert.Equal(new List<T>(), ParallelEnumerable.Empty<T>().ToList()); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<T>().First()); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<T>().Last()); } } }
using Lucene.Net.Support; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Reflection; using System.Runtime.CompilerServices; namespace Lucene.Net.Index { /* * 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 Analyzer = Lucene.Net.Analysis.Analyzer; using BinaryDocValuesUpdate = Lucene.Net.Index.DocValuesUpdate.BinaryDocValuesUpdate; using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using IEvent = Lucene.Net.Index.IndexWriter.IEvent; using FlushedSegment = Lucene.Net.Index.DocumentsWriterPerThread.FlushedSegment; using InfoStream = Lucene.Net.Util.InfoStream; using NumericDocValuesUpdate = Lucene.Net.Index.DocValuesUpdate.NumericDocValuesUpdate; using Query = Lucene.Net.Search.Query; using SegmentFlushTicket = Lucene.Net.Index.DocumentsWriterFlushQueue.SegmentFlushTicket; using ThreadState = Lucene.Net.Index.DocumentsWriterPerThreadPool.ThreadState; /// <summary> /// This class accepts multiple added documents and directly /// writes segment files. /// <para/> /// Each added document is passed to the <see cref="DocConsumer"/>, /// which in turn processes the document and interacts with /// other consumers in the indexing chain. Certain /// consumers, like <see cref="StoredFieldsConsumer"/> and /// <see cref="TermVectorsConsumer"/>, digest a document and /// immediately write bytes to the "doc store" files (ie, /// they do not consume RAM per document, except while they /// are processing the document). /// <para/> /// Other consumers, eg <see cref="FreqProxTermsWriter"/> and /// <see cref="NormsConsumer"/>, buffer bytes in RAM and flush only /// when a new segment is produced. /// <para/> /// Once we have used our allowed RAM buffer, or the number /// of added docs is large enough (in the case we are /// flushing by doc count instead of RAM usage), we create a /// real segment and flush it to the Directory. /// <para/> /// Threads: /// <para/> /// Multiple threads are allowed into AddDocument at once. /// There is an initial synchronized call to <see cref="DocumentsWriterPerThreadPool.GetThreadState(int)"/> /// which allocates a <see cref="ThreadState"/> for this thread. The same /// thread will get the same <see cref="ThreadState"/> over time (thread /// affinity) so that if there are consistent patterns (for /// example each thread is indexing a different content /// source) then we make better use of RAM. Then /// ProcessDocument is called on that <see cref="ThreadState"/> without /// synchronization (most of the "heavy lifting" is in this /// call). Finally the synchronized "finishDocument" is /// called to flush changes to the directory. /// <para/> /// When flush is called by <see cref="IndexWriter"/> we forcefully idle /// all threads and flush only once they are all idle. this /// means you can call flush with a given thread even while /// other threads are actively adding/deleting documents. /// <para/> /// /// Exceptions: /// <para/> /// Because this class directly updates in-memory posting /// lists, and flushes stored fields and term vectors /// directly to files in the directory, there are certain /// limited times when an exception can corrupt this state. /// For example, a disk full while flushing stored fields /// leaves this file in a corrupt state. Or, an OOM /// exception while appending to the in-memory posting lists /// can corrupt that posting list. We call such exceptions /// "aborting exceptions". In these cases we must call /// <see cref="Abort(IndexWriter)"/> to discard all docs added since the last flush. /// <para/> /// All other exceptions ("non-aborting exceptions") can /// still partially update the index structures. These /// updates are consistent, but, they represent only a part /// of the document seen up until the exception was hit. /// When this happens, we immediately mark the document as /// deleted so that the document is always atomically ("all /// or none") added to the index. /// </summary> internal sealed class DocumentsWriter : IDisposable { private readonly Directory directory; private volatile bool closed; private readonly InfoStream infoStream; private readonly LiveIndexWriterConfig config; private readonly AtomicInt32 numDocsInRAM = new AtomicInt32(0); // TODO: cut over to BytesRefHash in BufferedDeletes internal volatile DocumentsWriterDeleteQueue deleteQueue = new DocumentsWriterDeleteQueue(); private readonly DocumentsWriterFlushQueue ticketQueue = new DocumentsWriterFlushQueue(); /// <summary> /// we preserve changes during a full flush since IW might not checkout before /// we release all changes. NRT Readers otherwise suddenly return true from /// IsCurrent() while there are actually changes currently committed. See also /// <see cref="AnyChanges()"/> &amp; <see cref="FlushAllThreads(IndexWriter)"/> /// </summary> private volatile bool pendingChangesInCurrentFullFlush; internal readonly DocumentsWriterPerThreadPool perThreadPool; internal readonly FlushPolicy flushPolicy; internal readonly DocumentsWriterFlushControl flushControl; private readonly IndexWriter writer; private readonly ConcurrentQueue<IEvent> events; internal DocumentsWriter(IndexWriter writer, LiveIndexWriterConfig config, Directory directory) { this.directory = directory; this.config = config; this.infoStream = config.InfoStream; this.perThreadPool = config.IndexerThreadPool; flushPolicy = config.FlushPolicy; this.writer = writer; this.events = new ConcurrentQueue<IEvent>(); flushControl = new DocumentsWriterFlushControl(this, config, writer.bufferedUpdatesStream); } internal bool DeleteQueries(params Query[] queries) { lock (this) { // TODO why is this synchronized? DocumentsWriterDeleteQueue deleteQueue = this.deleteQueue; deleteQueue.AddDelete(queries); flushControl.DoOnDelete(); return ApplyAllDeletes(deleteQueue); } } // TODO: we could check w/ FreqProxTermsWriter: if the // term doesn't exist, don't bother buffering into the // per-DWPT map (but still must go into the global map) internal bool DeleteTerms(params Term[] terms) { lock (this) { // TODO why is this synchronized? DocumentsWriterDeleteQueue deleteQueue = this.deleteQueue; deleteQueue.AddDelete(terms); flushControl.DoOnDelete(); return ApplyAllDeletes(deleteQueue); } } internal bool UpdateNumericDocValue(Term term, string field, long? value) { lock (this) { DocumentsWriterDeleteQueue deleteQueue = this.deleteQueue; deleteQueue.AddNumericUpdate(new NumericDocValuesUpdate(term, field, value)); flushControl.DoOnDelete(); return ApplyAllDeletes(deleteQueue); } } internal bool UpdateBinaryDocValue(Term term, string field, BytesRef value) { lock (this) { DocumentsWriterDeleteQueue deleteQueue = this.deleteQueue; deleteQueue.AddBinaryUpdate(new BinaryDocValuesUpdate(term, field, value)); flushControl.DoOnDelete(); return ApplyAllDeletes(deleteQueue); } } internal DocumentsWriterDeleteQueue CurrentDeleteSession { get { return deleteQueue; } } private bool ApplyAllDeletes(DocumentsWriterDeleteQueue deleteQueue) { if (flushControl.GetAndResetApplyAllDeletes()) { if (deleteQueue != null && !flushControl.IsFullFlush) { ticketQueue.AddDeletes(deleteQueue); } PutEvent(ApplyDeletesEvent.INSTANCE); // apply deletes event forces a purge return true; } return false; } internal int PurgeBuffer(IndexWriter writer, bool forced) { if (forced) { return ticketQueue.ForcePurge(writer); } else { return ticketQueue.TryPurge(writer); } } /// <summary> /// Returns how many docs are currently buffered in RAM. </summary> internal int NumDocs { get { return numDocsInRAM.Get(); } } private void EnsureOpen() { if (closed) { throw new ObjectDisposedException(this.GetType().GetTypeInfo().FullName, "this IndexWriter is closed"); } } /// <summary> /// Called if we hit an exception at a bad time (when /// updating the index files) and must discard all /// currently buffered docs. this resets our state, /// discarding any docs added since last flush. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] internal void Abort(IndexWriter writer) { lock (this) { //Debug.Assert(!Thread.HoldsLock(writer), "IndexWriter lock should never be hold when aborting"); bool success = false; HashSet<string> newFilesSet = new HashSet<string>(); try { deleteQueue.Clear(); if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "abort"); } int limit = perThreadPool.NumThreadStatesActive; for (int i = 0; i < limit; i++) { ThreadState perThread = perThreadPool.GetThreadState(i); perThread.@Lock(); try { AbortThreadState(perThread, newFilesSet); } finally { perThread.Unlock(); } } flushControl.AbortPendingFlushes(newFilesSet); PutEvent(new DeleteNewFilesEvent(newFilesSet)); flushControl.WaitForFlush(); success = true; } finally { if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "done abort; abortedFiles=" + Arrays.ToString(newFilesSet) + " success=" + success); } } } } internal void LockAndAbortAll(IndexWriter indexWriter) { lock (this) { //Debug.Assert(indexWriter.HoldsFullFlushLock()); if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "lockAndAbortAll"); } bool success = false; try { deleteQueue.Clear(); int limit = perThreadPool.MaxThreadStates; HashSet<string> newFilesSet = new HashSet<string>(); for (int i = 0; i < limit; i++) { ThreadState perThread = perThreadPool.GetThreadState(i); perThread.@Lock(); AbortThreadState(perThread, newFilesSet); } deleteQueue.Clear(); flushControl.AbortPendingFlushes(newFilesSet); PutEvent(new DeleteNewFilesEvent(newFilesSet)); flushControl.WaitForFlush(); success = true; } finally { if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "finished lockAndAbortAll success=" + success); } if (!success) { // if something happens here we unlock all states again UnlockAllAfterAbortAll(indexWriter); } } } } private void AbortThreadState(ThreadState perThread, ISet<string> newFiles) { //Debug.Assert(perThread.HeldByCurrentThread); if (perThread.IsActive) // we might be closed { if (perThread.IsInitialized) { try { SubtractFlushedNumDocs(perThread.dwpt.NumDocsInRAM); perThread.dwpt.Abort(newFiles); } finally { perThread.dwpt.CheckAndResetHasAborted(); flushControl.DoOnAbort(perThread); } } else { flushControl.DoOnAbort(perThread); } } else { Debug.Assert(closed); } } internal void UnlockAllAfterAbortAll(IndexWriter indexWriter) { lock (this) { //Debug.Assert(indexWriter.HoldsFullFlushLock()); if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "unlockAll"); } int limit = perThreadPool.MaxThreadStates; for (int i = 0; i < limit; i++) { try { ThreadState perThread = perThreadPool.GetThreadState(i); //if (perThread.HeldByCurrentThread) //{ perThread.Unlock(); //} } catch (Exception e) { if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "unlockAll: could not unlock state: " + i + " msg:" + e.Message); } // ignore & keep on unlocking } } } } internal bool AnyChanges() { if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "anyChanges? numDocsInRam=" + numDocsInRAM.Get() + " deletes=" + AnyDeletions() + " hasTickets:" + ticketQueue.HasTickets + " pendingChangesInFullFlush: " + pendingChangesInCurrentFullFlush); } /* * changes are either in a DWPT or in the deleteQueue. * yet if we currently flush deletes and / or dwpt there * could be a window where all changes are in the ticket queue * before they are published to the IW. ie we need to check if the * ticket queue has any tickets. */ return numDocsInRAM.Get() != 0 || AnyDeletions() || ticketQueue.HasTickets || pendingChangesInCurrentFullFlush; } public int BufferedDeleteTermsSize { get { return deleteQueue.BufferedUpdatesTermsSize; } } //for testing public int NumBufferedDeleteTerms { get { return deleteQueue.NumGlobalTermDeletes; } } public bool AnyDeletions() { return deleteQueue.AnyChanges(); } public void Dispose() { closed = true; flushControl.SetClosed(); } private bool PreUpdate() { EnsureOpen(); bool hasEvents = false; if (flushControl.AnyStalledThreads() || flushControl.NumQueuedFlushes > 0) { // Help out flushing any queued DWPTs so we can un-stall: if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "DocumentsWriter has queued dwpt; will hijack this thread to flush pending segment(s)"); } do { // Try pick up pending threads here if possible DocumentsWriterPerThread flushingDWPT; while ((flushingDWPT = flushControl.NextPendingFlush()) != null) { // Don't push the delete here since the update could fail! hasEvents |= DoFlush(flushingDWPT); } if (infoStream.IsEnabled("DW")) { if (flushControl.AnyStalledThreads()) { infoStream.Message("DW", "WARNING DocumentsWriter has stalled threads; waiting"); } } flushControl.WaitIfStalled(); // block if stalled } while (flushControl.NumQueuedFlushes != 0); // still queued DWPTs try help flushing if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "continue indexing after helping out flushing DocumentsWriter is healthy"); } } return hasEvents; } private bool PostUpdate(DocumentsWriterPerThread flushingDWPT, bool hasEvents) { hasEvents |= ApplyAllDeletes(deleteQueue); if (flushingDWPT != null) { hasEvents |= DoFlush(flushingDWPT); } else { DocumentsWriterPerThread nextPendingFlush = flushControl.NextPendingFlush(); if (nextPendingFlush != null) { hasEvents |= DoFlush(nextPendingFlush); } } return hasEvents; } private void EnsureInitialized(ThreadState state) { if (state.IsActive && state.dwpt == null) { FieldInfos.Builder infos = new FieldInfos.Builder(writer.globalFieldNumberMap); state.dwpt = new DocumentsWriterPerThread(writer.NewSegmentName(), directory, config, infoStream, deleteQueue, infos); } } internal bool UpdateDocuments(IEnumerable<IEnumerable<IIndexableField>> docs, Analyzer analyzer, Term delTerm) { bool hasEvents = PreUpdate(); ThreadState perThread = flushControl.ObtainAndLock(); DocumentsWriterPerThread flushingDWPT; try { if (!perThread.IsActive) { EnsureOpen(); Debug.Assert(false, "perThread is not active but we are still open"); } EnsureInitialized(perThread); Debug.Assert(perThread.IsInitialized); DocumentsWriterPerThread dwpt = perThread.dwpt; int dwptNumDocs = dwpt.NumDocsInRAM; try { int docCount = dwpt.UpdateDocuments(docs, analyzer, delTerm); numDocsInRAM.AddAndGet(docCount); } finally { if (dwpt.CheckAndResetHasAborted()) { if (dwpt.PendingFilesToDelete.Count > 0) { PutEvent(new DeleteNewFilesEvent(dwpt.PendingFilesToDelete)); } SubtractFlushedNumDocs(dwptNumDocs); flushControl.DoOnAbort(perThread); } } bool isUpdate = delTerm != null; flushingDWPT = flushControl.DoAfterDocument(perThread, isUpdate); } finally { perThread.Unlock(); } return PostUpdate(flushingDWPT, hasEvents); } internal bool UpdateDocument(IEnumerable<IIndexableField> doc, Analyzer analyzer, Term delTerm) { bool hasEvents = PreUpdate(); ThreadState perThread = flushControl.ObtainAndLock(); DocumentsWriterPerThread flushingDWPT; try { if (!perThread.IsActive) { EnsureOpen(); Debug.Assert(false, "perThread is not active but we are still open"); } EnsureInitialized(perThread); Debug.Assert(perThread.IsInitialized); DocumentsWriterPerThread dwpt = perThread.dwpt; int dwptNumDocs = dwpt.NumDocsInRAM; try { dwpt.UpdateDocument(doc, analyzer, delTerm); numDocsInRAM.IncrementAndGet(); } finally { if (dwpt.CheckAndResetHasAborted()) { if (dwpt.PendingFilesToDelete.Count > 0) { PutEvent(new DeleteNewFilesEvent(dwpt.PendingFilesToDelete)); } SubtractFlushedNumDocs(dwptNumDocs); flushControl.DoOnAbort(perThread); } } bool isUpdate = delTerm != null; flushingDWPT = flushControl.DoAfterDocument(perThread, isUpdate); } finally { perThread.Unlock(); } return PostUpdate(flushingDWPT, hasEvents); } private bool DoFlush(DocumentsWriterPerThread flushingDWPT) { bool hasEvents = false; while (flushingDWPT != null) { hasEvents = true; bool success = false; SegmentFlushTicket ticket = null; try { Debug.Assert(currentFullFlushDelQueue == null || flushingDWPT.deleteQueue == currentFullFlushDelQueue, "expected: " + currentFullFlushDelQueue + "but was: " + flushingDWPT.deleteQueue + " " + flushControl.IsFullFlush); /* * Since with DWPT the flush process is concurrent and several DWPT * could flush at the same time we must maintain the order of the * flushes before we can apply the flushed segment and the frozen global * deletes it is buffering. The reason for this is that the global * deletes mark a certain point in time where we took a DWPT out of * rotation and freeze the global deletes. * * Example: A flush 'A' starts and freezes the global deletes, then * flush 'B' starts and freezes all deletes occurred since 'A' has * started. if 'B' finishes before 'A' we need to wait until 'A' is done * otherwise the deletes frozen by 'B' are not applied to 'A' and we * might miss to deletes documents in 'A'. */ try { // Each flush is assigned a ticket in the order they acquire the ticketQueue lock ticket = ticketQueue.AddFlushTicket(flushingDWPT); int flushingDocsInRam = flushingDWPT.NumDocsInRAM; bool dwptSuccess = false; try { // flush concurrently without locking FlushedSegment newSegment = flushingDWPT.Flush(); ticketQueue.AddSegment(ticket, newSegment); dwptSuccess = true; } finally { SubtractFlushedNumDocs(flushingDocsInRam); if (flushingDWPT.PendingFilesToDelete.Count > 0) { PutEvent(new DeleteNewFilesEvent(flushingDWPT.PendingFilesToDelete)); hasEvents = true; } if (!dwptSuccess) { PutEvent(new FlushFailedEvent(flushingDWPT.SegmentInfo)); hasEvents = true; } } // flush was successful once we reached this point - new seg. has been assigned to the ticket! success = true; } finally { if (!success && ticket != null) { // In the case of a failure make sure we are making progress and // apply all the deletes since the segment flush failed since the flush // ticket could hold global deletes see FlushTicket#canPublish() ticketQueue.MarkTicketFailed(ticket); } } /* * Now we are done and try to flush the ticket queue if the head of the * queue has already finished the flush. */ if (ticketQueue.TicketCount >= perThreadPool.NumThreadStatesActive) { // this means there is a backlog: the one // thread in innerPurge can't keep up with all // other threads flushing segments. In this case // we forcefully stall the producers. PutEvent(ForcedPurgeEvent.INSTANCE); break; } } finally { flushControl.DoAfterFlush(flushingDWPT); flushingDWPT.CheckAndResetHasAborted(); } flushingDWPT = flushControl.NextPendingFlush(); } if (hasEvents) { PutEvent(MergePendingEvent.INSTANCE); } // If deletes alone are consuming > 1/2 our RAM // buffer, force them all to apply now. this is to // prevent too-frequent flushing of a long tail of // tiny segments: double ramBufferSizeMB = config.RAMBufferSizeMB; if (ramBufferSizeMB != Index.IndexWriterConfig.DISABLE_AUTO_FLUSH && flushControl.DeleteBytesUsed > (1024 * 1024 * ramBufferSizeMB / 2)) { if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "force apply deletes bytesUsed=" + flushControl.DeleteBytesUsed + " vs ramBuffer=" + (1024 * 1024 * ramBufferSizeMB)); } hasEvents = true; if (!this.ApplyAllDeletes(deleteQueue)) { PutEvent(ApplyDeletesEvent.INSTANCE); } } return hasEvents; } internal void SubtractFlushedNumDocs(int numFlushed) { int oldValue = numDocsInRAM.Get(); while (!numDocsInRAM.CompareAndSet(oldValue, oldValue - numFlushed)) { oldValue = numDocsInRAM.Get(); } } // for asserts private volatile DocumentsWriterDeleteQueue currentFullFlushDelQueue = null; // for asserts private bool SetFlushingDeleteQueue(DocumentsWriterDeleteQueue session) { lock (this) { currentFullFlushDelQueue = session; return true; } } /* * FlushAllThreads is synced by IW fullFlushLock. Flushing all threads is a * two stage operation; the caller must ensure (in try/finally) that finishFlush * is called after this method, to release the flush lock in DWFlushControl */ internal bool FlushAllThreads(IndexWriter indexWriter) { DocumentsWriterDeleteQueue flushingDeleteQueue; if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", "startFullFlush"); } lock (this) { pendingChangesInCurrentFullFlush = AnyChanges(); flushingDeleteQueue = deleteQueue; /* Cutover to a new delete queue. this must be synced on the flush control * otherwise a new DWPT could sneak into the loop with an already flushing * delete queue */ flushControl.MarkForFullFlush(); // swaps the delQueue synced on FlushControl Debug.Assert(SetFlushingDeleteQueue(flushingDeleteQueue)); } Debug.Assert(currentFullFlushDelQueue != null); Debug.Assert(currentFullFlushDelQueue != deleteQueue); bool anythingFlushed = false; try { DocumentsWriterPerThread flushingDWPT; // Help out with flushing: while ((flushingDWPT = flushControl.NextPendingFlush()) != null) { anythingFlushed |= DoFlush(flushingDWPT); } // If a concurrent flush is still in flight wait for it flushControl.WaitForFlush(); if (!anythingFlushed && flushingDeleteQueue.AnyChanges()) // apply deletes if we did not flush any document { if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", Thread.CurrentThread.Name + ": flush naked frozen global deletes"); } ticketQueue.AddDeletes(flushingDeleteQueue); } ticketQueue.ForcePurge(indexWriter); Debug.Assert(!flushingDeleteQueue.AnyChanges() && !ticketQueue.HasTickets); } finally { Debug.Assert(flushingDeleteQueue == currentFullFlushDelQueue); } return anythingFlushed; } internal void FinishFullFlush(bool success) { try { if (infoStream.IsEnabled("DW")) { infoStream.Message("DW", Thread.CurrentThread.Name + " finishFullFlush success=" + success); } Debug.Assert(SetFlushingDeleteQueue(null)); if (success) { // Release the flush lock flushControl.FinishFullFlush(); } else { HashSet<string> newFilesSet = new HashSet<string>(); flushControl.AbortFullFlushes(newFilesSet); PutEvent(new DeleteNewFilesEvent(newFilesSet)); } } finally { pendingChangesInCurrentFullFlush = false; } } public LiveIndexWriterConfig IndexWriterConfig { get { return config; } } private void PutEvent(IEvent @event) { events.Enqueue(@event); } internal sealed class ApplyDeletesEvent : IEvent { internal static readonly IEvent INSTANCE = new ApplyDeletesEvent(); private int instCount = 0; // LUCENENET TODO: What is this for? It will always be zero when initialized and 1 after the constructor is called. Should it be static? internal ApplyDeletesEvent() { Debug.Assert(instCount == 0); instCount++; } public void Process(IndexWriter writer, bool triggerMerge, bool forcePurge) { writer.ApplyDeletesAndPurge(true); // we always purge! } } internal sealed class MergePendingEvent : IEvent { internal static readonly IEvent INSTANCE = new MergePendingEvent(); private int instCount = 0; // LUCENENET TODO: What is this for? It will always be zero when initialized and 1 after the constructor is called. Should it be static? internal MergePendingEvent() { Debug.Assert(instCount == 0); instCount++; } public void Process(IndexWriter writer, bool triggerMerge, bool forcePurge) { writer.DoAfterSegmentFlushed(triggerMerge, forcePurge); } } internal sealed class ForcedPurgeEvent : IEvent { internal static readonly IEvent INSTANCE = new ForcedPurgeEvent(); private int instCount = 0; // LUCENENET TODO: What is this for? It will always be zero when initialized and 1 after the constructor is called. Should it be static? internal ForcedPurgeEvent() { Debug.Assert(instCount == 0); instCount++; } public void Process(IndexWriter writer, bool triggerMerge, bool forcePurge) { writer.Purge(true); } } internal class FlushFailedEvent : IEvent { private readonly SegmentInfo info; public FlushFailedEvent(SegmentInfo info) { this.info = info; } public void Process(IndexWriter writer, bool triggerMerge, bool forcePurge) { writer.FlushFailed(info); } } internal class DeleteNewFilesEvent : IEvent { private readonly ICollection<string> files; public DeleteNewFilesEvent(ICollection<string> files) { this.files = files; } public void Process(IndexWriter writer, bool triggerMerge, bool forcePurge) { writer.DeleteNewFiles(files); } } public ConcurrentQueue<IEvent> EventQueue { get { return events; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void LoadVector64_UInt16() { var test = new LoadUnaryOpTest__LoadVector64_UInt16(); if (test.IsSupported) { // Validates basic functionality works test.RunBasicScenario_Load(); // Validates calling via reflection works test.RunReflectionScenario_Load(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class LoadUnaryOpTest__LoadVector64_UInt16 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static UInt16[] _data = new UInt16[Op1ElementCount]; private DataTable _dataTable; public LoadUnaryOpTest__LoadVector64_UInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data, new UInt16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.LoadVector64( (UInt16*)(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LoadVector64), new Type[] { typeof(UInt16*) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(UInt16*)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); Succeeded = false; try { RunBasicScenario_Load(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector64<UInt16> firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (firstOp[0] != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (firstOp[i] != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.LoadVector64)}<UInt16>(Vector64<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; using System.Runtime.InteropServices; using System.Text; using K4os.Compression.LZ4; using SkiaSharp; using ValveResourceFormat.Blocks; using ValveResourceFormat.Blocks.ResourceEditInfoStructs; namespace ValveResourceFormat.ResourceTypes { public class Texture : ResourceData { private const short MipmapLevelToExtract = 0; // for debugging purposes public class SpritesheetData { public class Sequence { public class Frame { public Vector2 StartMins { get; set; } public Vector2 StartMaxs { get; set; } public Vector2 EndMins { get; set; } public Vector2 EndMaxs { get; set; } } public Frame[] Frames { get; set; } public float FramesPerSecond { get; set; } } public Sequence[] Sequences { get; set; } } private BinaryReader Reader; private long DataOffset; private Resource Resource; public ushort Version { get; private set; } public ushort Width { get; private set; } public ushort Height { get; private set; } public ushort Depth { get; private set; } public float[] Reflectivity { get; private set; } public VTexFlags Flags { get; private set; } public VTexFormat Format { get; private set; } public byte NumMipLevels { get; private set; } public uint Picmip0Res { get; private set; } public Dictionary<VTexExtraData, byte[]> ExtraData { get; private set; } public ushort NonPow2Width { get; private set; } public ushort NonPow2Height { get; private set; } private int[] CompressedMips; private bool IsActuallyCompressedMips; private float[] RadianceCoefficients; public ushort ActualWidth => NonPow2Width > 0 ? NonPow2Width : Width; public ushort ActualHeight => NonPow2Height > 0 ? NonPow2Height : Height; public Texture() { ExtraData = new Dictionary<VTexExtraData, byte[]>(); } public override void Read(BinaryReader reader, Resource resource) { Reader = reader; Resource = resource; reader.BaseStream.Position = Offset; Version = reader.ReadUInt16(); if (Version != 1) { throw new InvalidDataException(string.Format("Unknown vtex version. ({0} != expected 1)", Version)); } Flags = (VTexFlags)reader.ReadUInt16(); Reflectivity = new[] { reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), }; Width = reader.ReadUInt16(); Height = reader.ReadUInt16(); Depth = reader.ReadUInt16(); NonPow2Width = 0; NonPow2Height = 0; Format = (VTexFormat)reader.ReadByte(); NumMipLevels = reader.ReadByte(); Picmip0Res = reader.ReadUInt32(); var extraDataOffset = reader.ReadUInt32(); var extraDataCount = reader.ReadUInt32(); if (extraDataCount > 0) { reader.BaseStream.Position += extraDataOffset - 8; // 8 is 2 uint32s we just read for (var i = 0; i < extraDataCount; i++) { var type = (VTexExtraData)reader.ReadUInt32(); var offset = reader.ReadUInt32() - 8; var size = reader.ReadUInt32(); var prevOffset = reader.BaseStream.Position; reader.BaseStream.Position += offset; ExtraData.Add(type, reader.ReadBytes((int)size)); reader.BaseStream.Position -= size; if (type == VTexExtraData.FILL_TO_POWER_OF_TWO) { reader.ReadUInt16(); var nw = reader.ReadUInt16(); var nh = reader.ReadUInt16(); if (nw > 0 && nh > 0 && Width >= nw && Height >= nh) { NonPow2Width = nw; NonPow2Height = nh; } } else if (type == VTexExtraData.COMPRESSED_MIP_SIZE) { var int1 = reader.ReadUInt32(); // 1? var mipsOffset = reader.ReadUInt32(); var mips = reader.ReadUInt32(); if (int1 != 1 && int1 != 0) { throw new InvalidDataException($"int1 got: {int1}"); } IsActuallyCompressedMips = int1 == 1; // TODO: Verify whether this int is the one that actually controls compression CompressedMips = new int[mips]; reader.BaseStream.Position += mipsOffset - 8; for (var mip = 0; mip < mips; mip++) { CompressedMips[mip] = reader.ReadInt32(); } } else if (type == VTexExtraData.CUBEMAP_RADIANCE_SH) { var coeffsOffset = reader.ReadUInt32(); var coeffs = reader.ReadUInt32(); //Spherical Harmonics RadianceCoefficients = new float[coeffs]; reader.BaseStream.Position += coeffsOffset - 8; for (var c = 0; c < coeffs; c++) { RadianceCoefficients[c] = reader.ReadSingle(); } } reader.BaseStream.Position = prevOffset; } } DataOffset = Offset + Size; } public SpritesheetData GetSpriteSheetData() { if (ExtraData.TryGetValue(VTexExtraData.SHEET, out var bytes)) { using var memoryStream = new MemoryStream(bytes); using var reader = new BinaryReader(memoryStream); var version = reader.ReadUInt32(); var numSequences = reader.ReadUInt32(); var sequences = new SpritesheetData.Sequence[numSequences]; for (var i = 0; i < numSequences; i++) { var sequenceNumber = reader.ReadUInt32(); var unknown1 = reader.ReadUInt32(); // 1? var unknown2 = reader.ReadUInt32(); var numFrames = reader.ReadUInt32(); var framesPerSecond = reader.ReadSingle(); // Not too sure about this one var dataOffset = reader.BaseStream.Position + reader.ReadUInt32(); var unknown4 = reader.ReadUInt32(); // 0? var unknown5 = reader.ReadUInt32(); // 0? var endOfHeaderOffset = reader.BaseStream.Position; // Store end of header to return to later // Seek to start of the sequence data reader.BaseStream.Position = dataOffset; var sequenceName = reader.ReadNullTermString(Encoding.UTF8); var frameUnknown = reader.ReadUInt16(); var frames = new SpritesheetData.Sequence.Frame[numFrames]; for (var j = 0; j < numFrames; j++) { var frameUnknown1 = reader.ReadSingle(); var frameUnknown2 = reader.ReadUInt32(); var frameUnknown3 = reader.ReadSingle(); frames[j] = new SpritesheetData.Sequence.Frame(); } for (var j = 0; j < numFrames; j++) { frames[j].StartMins = new Vector2(reader.ReadSingle(), reader.ReadSingle()); frames[j].StartMaxs = new Vector2(reader.ReadSingle(), reader.ReadSingle()); frames[j].EndMins = new Vector2(reader.ReadSingle(), reader.ReadSingle()); frames[j].EndMaxs = new Vector2(reader.ReadSingle(), reader.ReadSingle()); } reader.BaseStream.Position = endOfHeaderOffset; sequences[i] = new SpritesheetData.Sequence { Frames = frames, FramesPerSecond = framesPerSecond, }; } return new SpritesheetData { Sequences = sequences, }; } return null; } public SKBitmap GenerateBitmap() { Reader.BaseStream.Position = DataOffset; var width = ActualWidth >> MipmapLevelToExtract; var height = ActualHeight >> MipmapLevelToExtract; var blockWidth = Width >> MipmapLevelToExtract; var blockHeight = Height >> MipmapLevelToExtract; var skiaBitmap = new SKBitmap(width, height, SKColorType.Bgra8888, SKAlphaType.Unpremul); SkipMipmaps(); switch (Format) { case VTexFormat.DXT1: return TextureDecompressors.UncompressDXT1(skiaBitmap, GetTextureSpan(), blockWidth, blockHeight); case VTexFormat.DXT5: var yCoCg = false; var normalize = false; var invert = false; var hemiOct = false; if (Resource.EditInfo.Structs.ContainsKey(ResourceEditInfo.REDIStruct.SpecialDependencies)) { var specialDeps = (SpecialDependencies)Resource.EditInfo.Structs[ResourceEditInfo.REDIStruct.SpecialDependencies]; yCoCg = specialDeps.List.Any(dependancy => dependancy.CompilerIdentifier == "CompileTexture" && dependancy.String == "Texture Compiler Version Image YCoCg Conversion"); normalize = specialDeps.List.Any(dependancy => dependancy.CompilerIdentifier == "CompileTexture" && dependancy.String == "Texture Compiler Version Image NormalizeNormals"); invert = specialDeps.List.Any(dependancy => dependancy.CompilerIdentifier == "CompileTexture" && dependancy.String == "Texture Compiler Version LegacySource1InvertNormals"); hemiOct = specialDeps.List.Any(dependancy => dependancy.CompilerIdentifier == "CompileTexture" && dependancy.String == "Texture Compiler Version Mip HemiOctAnisoRoughness"); } return TextureDecompressors.UncompressDXT5(skiaBitmap, GetTextureSpan(), blockWidth, blockHeight, yCoCg, normalize, invert, hemiOct); case VTexFormat.I8: return TextureDecompressors.ReadI8(skiaBitmap, GetTextureSpan()); case VTexFormat.RGBA8888: return TextureDecompressors.ReadRGBA8888(skiaBitmap, GetTextureSpan()); case VTexFormat.R16: return TextureDecompressors.ReadR16(GetDecompressedBuffer(), Width, Height); case VTexFormat.RG1616: return TextureDecompressors.ReadRG1616(GetDecompressedBuffer(), Width, Height); case VTexFormat.RGBA16161616: return TextureDecompressors.ReadRGBA16161616(skiaBitmap, GetTextureSpan()); case VTexFormat.R16F: return TextureDecompressors.ReadR16F(GetDecompressedBuffer(), Width, Height); case VTexFormat.RG1616F: return TextureDecompressors.ReadRG1616F(GetDecompressedBuffer(), Width, Height); case VTexFormat.RGBA16161616F: return TextureDecompressors.ReadRGBA16161616F(skiaBitmap, GetTextureSpan()); case VTexFormat.R32F: return TextureDecompressors.ReadR32F(GetDecompressedBuffer(), Width, Height); case VTexFormat.RG3232F: return TextureDecompressors.ReadRG3232F(GetDecompressedBuffer(), Width, Height); case VTexFormat.RGB323232F: return TextureDecompressors.ReadRGB323232F(GetDecompressedBuffer(), Width, Height); case VTexFormat.RGBA32323232F: return TextureDecompressors.ReadRGBA32323232F(GetDecompressedBuffer(), Width, Height); case VTexFormat.BC6H: return BPTC.BPTCDecoders.UncompressBC6H(GetDecompressedBuffer(), Width, Height); case VTexFormat.BC7: bool hemiOctRB = false; invert = false; if (Resource.EditInfo.Structs.ContainsKey(ResourceEditInfo.REDIStruct.SpecialDependencies)) { var specialDeps = (SpecialDependencies)Resource.EditInfo.Structs[ResourceEditInfo.REDIStruct.SpecialDependencies]; hemiOctRB = specialDeps.List.Any(dependancy => dependancy.CompilerIdentifier == "CompileTexture" && dependancy.String == "Texture Compiler Version Mip HemiOctIsoRoughness_RG_B"); invert = specialDeps.List.Any(dependancy => dependancy.CompilerIdentifier == "CompileTexture" && dependancy.String == "Texture Compiler Version LegacySource1InvertNormals"); } return BPTC.BPTCDecoders.UncompressBC7(GetDecompressedBuffer(), Width, Height, hemiOctRB, invert); case VTexFormat.ATI2N: normalize = false; if (Resource.EditInfo.Structs.ContainsKey(ResourceEditInfo.REDIStruct.SpecialDependencies)) { var specialDeps = (SpecialDependencies)Resource.EditInfo.Structs[ResourceEditInfo.REDIStruct.SpecialDependencies]; normalize = specialDeps.List.Any(dependancy => dependancy.CompilerIdentifier == "CompileTexture" && dependancy.String == "Texture Compiler Version Image NormalizeNormals"); } return TextureDecompressors.UncompressATI2N(skiaBitmap, GetTextureSpan(), Width, Height, normalize); case VTexFormat.IA88: return TextureDecompressors.ReadIA88(skiaBitmap, GetTextureSpan()); case VTexFormat.ATI1N: return TextureDecompressors.UncompressATI1N(skiaBitmap, GetTextureSpan(), Width, Height); // TODO: Are we sure DXT5 and RGBA8888 are just raw buffers? case VTexFormat.JPEG_DXT5: case VTexFormat.JPEG_RGBA8888: case VTexFormat.PNG_DXT5: case VTexFormat.PNG_RGBA8888: return ReadBuffer(); case VTexFormat.ETC2: // TODO: Rewrite EtcDecoder to work on skia span directly var etc = new Etc.EtcDecoder(); var data = new byte[skiaBitmap.RowBytes * skiaBitmap.Height]; etc.DecompressETC2(GetDecompressedTextureAtMipLevel(0), width, height, data); var gcHandle = GCHandle.Alloc(data, GCHandleType.Pinned); skiaBitmap.InstallPixels(skiaBitmap.Info, gcHandle.AddrOfPinnedObject(), skiaBitmap.RowBytes, (address, context) => { gcHandle.Free(); }, null); break; case VTexFormat.ETC2_EAC: // TODO: Rewrite EtcDecoder to work on skia span directly var etc2 = new Etc.EtcDecoder(); var data2 = new byte[skiaBitmap.RowBytes * skiaBitmap.Height]; etc2.DecompressETC2A8(GetDecompressedTextureAtMipLevel(0), width, height, data2); var gcHandle2 = GCHandle.Alloc(data2, GCHandleType.Pinned); skiaBitmap.InstallPixels(skiaBitmap.Info, gcHandle2.AddrOfPinnedObject(), skiaBitmap.RowBytes, (address, context) => { gcHandle2.Free(); }, null); break; case VTexFormat.BGRA8888: return TextureDecompressors.ReadBGRA8888(skiaBitmap, GetTextureSpan()); default: throw new NotImplementedException(string.Format("Unhandled image type: {0}", Format)); } return skiaBitmap; } private int CalculateBufferSizeForMipLevel(int mipLevel) { var bytesPerPixel = GetBlockSize(); var width = Width >> mipLevel; var height = Height >> mipLevel; var depth = Depth >> mipLevel; if (depth < 1) { depth = 1; } if (Format == VTexFormat.DXT1 || Format == VTexFormat.DXT5 || Format == VTexFormat.BC6H || Format == VTexFormat.BC7 || Format == VTexFormat.ETC2 || Format == VTexFormat.ETC2_EAC || Format == VTexFormat.ATI1N) { var misalign = width % 4; if (misalign > 0) { width += 4 - misalign; } misalign = height % 4; if (misalign > 0) { height += 4 - misalign; } if (width < 4 && width > 0) { width = 4; } if (height < 4 && height > 0) { height = 4; } if (depth < 4 && depth > 1) { depth = 4; } var numBlocks = (width * height) >> 4; numBlocks *= depth; return numBlocks * bytesPerPixel; } return width * height * depth * bytesPerPixel; } private void SkipMipmaps() { if (NumMipLevels < 2) { return; } for (var j = NumMipLevels - 1; j > MipmapLevelToExtract; j--) { int offset; if (CompressedMips != null) { offset = CompressedMips[j]; } else { offset = CalculateBufferSizeForMipLevel(j) * (Flags.HasFlag(VTexFlags.CUBE_TEXTURE) ? 6 : 1); } Reader.BaseStream.Position += offset; } } private Span<byte> GetTextureSpan(int mipLevel = MipmapLevelToExtract) { var uncompressedSize = CalculateBufferSizeForMipLevel(mipLevel); var output = new Span<byte>(new byte[uncompressedSize]); if (!IsActuallyCompressedMips) { Reader.Read(output); return output; } var compressedSize = CompressedMips[mipLevel]; if (compressedSize >= uncompressedSize) { Reader.Read(output); return output; } var input = Reader.ReadBytes(compressedSize); LZ4Codec.Decode(input, output); return output; } public byte[] GetDecompressedTextureAtMipLevel(int mipLevel) { return GetTextureSpan(mipLevel).ToArray(); } private BinaryReader GetDecompressedBuffer() { if (!IsActuallyCompressedMips) { return Reader; } var outStream = new MemoryStream(GetDecompressedTextureAtMipLevel(MipmapLevelToExtract), false); return new BinaryReader(outStream); // TODO: dispose } private SKBitmap ReadBuffer() { return SKBitmap.Decode(Reader.ReadBytes((int)Reader.BaseStream.Length)); } #pragma warning disable CA1024 // Use properties where appropriate public int GetBlockSize() { return Format switch { VTexFormat.DXT1 => 8, VTexFormat.DXT5 => 16, VTexFormat.RGBA8888 => 4, VTexFormat.R16 => 2, VTexFormat.RG1616 => 4, VTexFormat.RGBA16161616 => 8, VTexFormat.R16F => 2, VTexFormat.RG1616F => 4, VTexFormat.RGBA16161616F => 8, VTexFormat.R32F => 4, VTexFormat.RG3232F => 8, VTexFormat.RGB323232F => 12, VTexFormat.RGBA32323232F => 16, VTexFormat.BC6H => 16, VTexFormat.BC7 => 16, VTexFormat.IA88 => 2, VTexFormat.ETC2 => 8, VTexFormat.ETC2_EAC => 16, VTexFormat.BGRA8888 => 4, VTexFormat.ATI1N => 8, _ => 1, }; } #pragma warning restore CA1024 // Use properties where appropriate public override string ToString() { using var writer = new IndentedTextWriter(); writer.WriteLine("{0,-12} = {1}", "VTEX Version", Version); writer.WriteLine("{0,-12} = {1}", "Width", Width); writer.WriteLine("{0,-12} = {1}", "Height", Height); writer.WriteLine("{0,-12} = {1}", "Depth", Depth); writer.WriteLine("{0,-12} = {1}", "NonPow2W", NonPow2Width); writer.WriteLine("{0,-12} = {1}", "NonPow2H", NonPow2Height); writer.WriteLine("{0,-12} = ( {1:F6}, {2:F6}, {3:F6}, {4:F6} )", "Reflectivity", Reflectivity[0], Reflectivity[1], Reflectivity[2], Reflectivity[3]); writer.WriteLine("{0,-12} = {1}", "NumMipLevels", NumMipLevels); writer.WriteLine("{0,-12} = {1}", "Picmip0Res", Picmip0Res); writer.WriteLine("{0,-12} = {1} (VTEX_FORMAT_{2})", "Format", (int)Format, Format); writer.WriteLine("{0,-12} = 0x{1:X8}", "Flags", (int)Flags); foreach (Enum value in Enum.GetValues(Flags.GetType())) { if (Flags.HasFlag(value)) { writer.WriteLine("{0,-12} | 0x{1:X8} = VTEX_FLAG_{2}", string.Empty, Convert.ToInt32(value), value); } } writer.WriteLine("{0,-12} = {1} entries:", "Extra Data", ExtraData.Count); var entry = 0; foreach (var b in ExtraData) { writer.WriteLine("{0,-12} [ Entry {1}: VTEX_EXTRA_DATA_{2} - {3} bytes ]", string.Empty, entry++, b.Key, b.Value.Length); if (b.Key == VTexExtraData.COMPRESSED_MIP_SIZE) { writer.WriteLine("{0,-16} [ {1} mips, sized: {2} ]", string.Empty, CompressedMips.Length, string.Join(", ", CompressedMips)); } else if (b.Key == VTexExtraData.CUBEMAP_RADIANCE_SH) { writer.WriteLine("{0,-16} [ {1} coefficients: {2} ]", string.Empty, RadianceCoefficients.Length, string.Join(", ", RadianceCoefficients)); } } for (var j = 0; j < NumMipLevels; j++) { writer.WriteLine($"Mip level {j} - buffer size: {CalculateBufferSizeForMipLevel(j)}"); } return writer.ToString(); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace Southwind{ /// <summary> /// Strongly-typed collection for the CustomerAndSuppliersByCity class. /// </summary> [Serializable] public partial class CustomerAndSuppliersByCityCollection : ReadOnlyList<CustomerAndSuppliersByCity, CustomerAndSuppliersByCityCollection> { public CustomerAndSuppliersByCityCollection() {} } /// <summary> /// This is Read-only wrapper class for the customer and suppliers by city view. /// </summary> [Serializable] public partial class CustomerAndSuppliersByCity : ReadOnlyRecord<CustomerAndSuppliersByCity>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor public static TableSchema.Table Schema { get { if (BaseSchema == null) { SetSQLProps(); } return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("customer and suppliers by city", TableType.View, DataService.GetInstance("Southwind")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @""; //columns TableSchema.TableColumn colvarCity = new TableSchema.TableColumn(schema); colvarCity.ColumnName = "City"; colvarCity.DataType = DbType.String; colvarCity.MaxLength = 15; colvarCity.AutoIncrement = false; colvarCity.IsNullable = true; colvarCity.IsPrimaryKey = false; colvarCity.IsForeignKey = false; colvarCity.IsReadOnly = false; schema.Columns.Add(colvarCity); TableSchema.TableColumn colvarCompanyName = new TableSchema.TableColumn(schema); colvarCompanyName.ColumnName = "CompanyName"; colvarCompanyName.DataType = DbType.String; colvarCompanyName.MaxLength = 40; colvarCompanyName.AutoIncrement = false; colvarCompanyName.IsNullable = false; colvarCompanyName.IsPrimaryKey = false; colvarCompanyName.IsForeignKey = false; colvarCompanyName.IsReadOnly = false; schema.Columns.Add(colvarCompanyName); TableSchema.TableColumn colvarContactName = new TableSchema.TableColumn(schema); colvarContactName.ColumnName = "ContactName"; colvarContactName.DataType = DbType.String; colvarContactName.MaxLength = 30; colvarContactName.AutoIncrement = false; colvarContactName.IsNullable = true; colvarContactName.IsPrimaryKey = false; colvarContactName.IsForeignKey = false; colvarContactName.IsReadOnly = false; schema.Columns.Add(colvarContactName); TableSchema.TableColumn colvarRelationship = new TableSchema.TableColumn(schema); colvarRelationship.ColumnName = "Relationship"; colvarRelationship.DataType = DbType.String; colvarRelationship.MaxLength = 9; colvarRelationship.AutoIncrement = false; colvarRelationship.IsNullable = false; colvarRelationship.IsPrimaryKey = false; colvarRelationship.IsForeignKey = false; colvarRelationship.IsReadOnly = false; schema.Columns.Add(colvarRelationship); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["Southwind"].AddSchema("customer and suppliers by city",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public CustomerAndSuppliersByCity() { SetSQLProps(); SetDefaults(); MarkNew(); } public CustomerAndSuppliersByCity(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public CustomerAndSuppliersByCity(object keyID) { SetSQLProps(); LoadByKey(keyID); } public CustomerAndSuppliersByCity(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("City")] [Bindable(true)] public string City { get { return GetColumnValue<string>("City"); } set { SetColumnValue("City", value); } } [XmlAttribute("CompanyName")] [Bindable(true)] public string CompanyName { get { return GetColumnValue<string>("CompanyName"); } set { SetColumnValue("CompanyName", value); } } [XmlAttribute("ContactName")] [Bindable(true)] public string ContactName { get { return GetColumnValue<string>("ContactName"); } set { SetColumnValue("ContactName", value); } } [XmlAttribute("Relationship")] [Bindable(true)] public string Relationship { get { return GetColumnValue<string>("Relationship"); } set { SetColumnValue("Relationship", value); } } #endregion #region Columns Struct public struct Columns { public static string City = @"City"; public static string CompanyName = @"CompanyName"; public static string ContactName = @"ContactName"; public static string Relationship = @"Relationship"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace UserProfile.Manipulation.CSOMWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// 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. #pragma warning disable IDE0066 // switch expression #pragma warning disable IDE0057 // substring using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.ServiceModel; using System.Text; using System.Threading; using System.Threading.Tasks; using Thrift; using Thrift.Collections; using Thrift.Protocol; using Thrift.Transport; using Thrift.Transport.Client; namespace ThriftTest { internal enum ProtocolChoice { Binary, Compact, Json } // it does not make much sense to use buffered when we already use framed internal enum LayeredChoice { None, Buffered, Framed } internal enum TransportChoice { Socket, TlsSocket, Http, NamedPipe } public class TestClient { private class TestParams { public int numIterations = 1; public string host = "localhost"; public int port = 9090; public int numThreads = 1; public string url; public string pipe; public LayeredChoice layered = LayeredChoice.None; public ProtocolChoice protocol = ProtocolChoice.Binary; public TransportChoice transport = TransportChoice.Socket; private readonly TConfiguration Configuration = null; // or new TConfiguration() if needed internal void Parse(List<string> args) { for (var i = 0; i < args.Count; ++i) { if (args[i] == "-u") { url = args[++i]; transport = TransportChoice.Http; } else if (args[i] == "-n") { numIterations = Convert.ToInt32(args[++i]); } else if (args[i].StartsWith("--pipe=")) { pipe = args[i].Substring(args[i].IndexOf("=") + 1); transport = TransportChoice.NamedPipe; } else if (args[i].StartsWith("--host=")) { // check there for ipaddress host = args[i].Substring(args[i].IndexOf("=") + 1); if (transport != TransportChoice.TlsSocket) transport = TransportChoice.Socket; } else if (args[i].StartsWith("--port=")) { port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1)); if (transport != TransportChoice.TlsSocket) transport = TransportChoice.Socket; } else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered") { layered = LayeredChoice.Buffered; } else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed") { layered = LayeredChoice.Framed; } else if (args[i] == "-t") { numThreads = Convert.ToInt32(args[++i]); } else if (args[i] == "--binary" || args[i] == "--protocol=binary") { protocol = ProtocolChoice.Binary; } else if (args[i] == "--compact" || args[i] == "--protocol=compact") { protocol = ProtocolChoice.Compact; } else if (args[i] == "--json" || args[i] == "--protocol=json") { protocol = ProtocolChoice.Json; } else if (args[i] == "--ssl") { transport = TransportChoice.TlsSocket; } else if (args[i] == "--help") { PrintOptionsHelp(); return; } else { Console.WriteLine("Invalid argument: {0}", args[i]); PrintOptionsHelp(); return; } } switch (transport) { case TransportChoice.Socket: Console.WriteLine("Using socket transport"); break; case TransportChoice.TlsSocket: Console.WriteLine("Using encrypted transport"); break; case TransportChoice.Http: Console.WriteLine("Using HTTP transport"); break; case TransportChoice.NamedPipe: Console.WriteLine("Using named pipes transport"); break; default: // unhandled case Debug.Assert(false); break; } switch (layered) { case LayeredChoice.Framed: Console.WriteLine("Using framed transport"); break; case LayeredChoice.Buffered: Console.WriteLine("Using buffered transport"); break; default: // unhandled case? Debug.Assert(layered == LayeredChoice.None); break; } switch (protocol) { case ProtocolChoice.Binary: Console.WriteLine("Using binary protocol"); break; case ProtocolChoice.Compact: Console.WriteLine("Using compact protocol"); break; case ProtocolChoice.Json: Console.WriteLine("Using JSON protocol"); break; default: // unhandled case? Debug.Assert(false); break; } } private static X509Certificate2 GetClientCert() { var clientCertName = "client.p12"; var possiblePaths = new List<string> { "../../../keys/", "../../keys/", "../keys/", "keys/", }; string existingPath = null; foreach (var possiblePath in possiblePaths) { var path = Path.GetFullPath(possiblePath + clientCertName); if (File.Exists(path)) { existingPath = path; break; } } if (string.IsNullOrEmpty(existingPath)) { throw new FileNotFoundException($"Cannot find file: {clientCertName}"); } var cert = new X509Certificate2(existingPath, "thrift"); return cert; } public TTransport CreateTransport() { // endpoint transport TTransport trans = null; switch (transport) { case TransportChoice.Http: Debug.Assert(url != null); trans = new THttpTransport(new Uri(url), Configuration); break; case TransportChoice.NamedPipe: Debug.Assert(pipe != null); trans = new TNamedPipeTransport(pipe,Configuration); break; case TransportChoice.TlsSocket: var cert = GetClientCert(); if (cert == null || !cert.HasPrivateKey) { throw new InvalidOperationException("Certificate doesn't contain private key"); } trans = new TTlsSocketTransport(host, port, Configuration, 0, cert, (sender, certificate, chain, errors) => true, null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12); break; case TransportChoice.Socket: default: trans = new TSocketTransport(host, port, Configuration); break; } // layered transport switch (layered) { case LayeredChoice.Buffered: trans = new TBufferedTransport(trans); break; case LayeredChoice.Framed: trans = new TFramedTransport(trans); break; default: Debug.Assert(layered == LayeredChoice.None); break; } return trans; } public TProtocol CreateProtocol(TTransport transport) { switch (protocol) { case ProtocolChoice.Compact: return new TCompactProtocol(transport); case ProtocolChoice.Json: return new TJsonProtocol(transport); case ProtocolChoice.Binary: default: return new TBinaryProtocol(transport); } } } private const int ErrorBaseTypes = 1; private const int ErrorStructs = 2; private const int ErrorContainers = 4; private const int ErrorExceptions = 8; private const int ErrorUnknown = 64; private class ClientTest { private readonly TTransport transport; private readonly ThriftTest.Client client; private readonly int numIterations; private bool done; public int ReturnCode { get; set; } public ClientTest(TestParams param) { transport = param.CreateTransport(); client = new ThriftTest.Client(param.CreateProtocol(transport)); numIterations = param.numIterations; } public void Execute() { if (done) { Console.WriteLine("Execute called more than once"); throw new InvalidOperationException(); } for (var i = 0; i < numIterations; i++) { try { if (!transport.IsOpen) transport.OpenAsync(MakeTimeoutToken()).GetAwaiter().GetResult(); } catch (TTransportException ex) { Console.WriteLine("*** FAILED ***"); Console.WriteLine("Connect failed: " + ex.Message); ReturnCode |= ErrorUnknown; Console.WriteLine(ex.Message + "\n" + ex.StackTrace); continue; } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); Console.WriteLine("Connect failed: " + ex.Message); ReturnCode |= ErrorUnknown; Console.WriteLine(ex.Message + "\n" + ex.StackTrace); continue; } try { ReturnCode |= ExecuteClientTest(client).GetAwaiter().GetResult(); ; } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); Console.WriteLine(ex.Message + "\n" + ex.StackTrace); ReturnCode |= ErrorUnknown; } } try { transport.Close(); } catch (Exception ex) { Console.WriteLine("Error while closing transport"); Console.WriteLine(ex.Message + "\n" + ex.StackTrace); } done = true; } } internal static void PrintOptionsHelp() { Console.WriteLine("Client options:"); Console.WriteLine(" -u <URL>"); Console.WriteLine(" -t <# of threads to run> default = 1"); Console.WriteLine(" -n <# of iterations> per thread"); Console.WriteLine(" --pipe=<pipe name>"); Console.WriteLine(" --host=<IP address>"); Console.WriteLine(" --port=<port number>"); Console.WriteLine(" --transport=<transport name> one of buffered,framed (defaults to none)"); Console.WriteLine(" --protocol=<protocol name> one of compact,json (defaults to binary)"); Console.WriteLine(" --ssl"); Console.WriteLine(); } public static int Execute(List<string> args) { try { var param = new TestParams(); try { param.Parse(args); } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); Console.WriteLine("Error while parsing arguments"); Console.WriteLine(ex.Message + "\n" + ex.StackTrace); return ErrorUnknown; } var tests = Enumerable.Range(0, param.numThreads).Select(_ => new ClientTest(param)).ToArray(); //issue tests on separate threads simultaneously var threads = tests.Select(test => new Task(test.Execute)).ToArray(); var start = DateTime.Now; foreach (var t in threads) { t.Start(); } Task.WaitAll(threads); Console.WriteLine("Total time: " + (DateTime.Now - start)); Console.WriteLine(); return tests.Select(t => t.ReturnCode).Aggregate((r1, r2) => r1 | r2); } catch (Exception outerEx) { Console.WriteLine("*** FAILED ***"); Console.WriteLine("Unexpected error"); Console.WriteLine(outerEx.Message + "\n" + outerEx.StackTrace); return ErrorUnknown; } } public static string BytesToHex(byte[] data) { return BitConverter.ToString(data).Replace("-", string.Empty); } public enum BinaryTestSize { Empty, // Edge case: the zero-length empty binary Normal, // Fairly small array of usual size (256 bytes) Large, // Large writes/reads may cause range check errors PipeWriteLimit, // Windows Limit: Pipe write operations across a network are limited to 65,535 bytes per write. FifteenMB // that's quite a bit of data }; public static byte[] PrepareTestData(bool randomDist, BinaryTestSize testcase) { int amount; switch (testcase) { case BinaryTestSize.Empty: amount = 0; break; case BinaryTestSize.Normal: amount = 0x100; break; case BinaryTestSize.Large: amount = 0x8000 + 128; break; case BinaryTestSize.PipeWriteLimit: amount = 0xFFFF + 128; break; case BinaryTestSize.FifteenMB: amount = 15 * 1024 * 1024; break; default: throw new ArgumentException("invalid argument",nameof(testcase)); } var retval = new byte[amount]; // linear distribution, unless random is requested if (!randomDist) { for (var i = 0; i < retval.Length; ++i) { retval[i] = (byte)i; } return retval; } // random distribution var rnd = new Random(); for (var i = 1; i < retval.Length; ++i) { retval[i] = (byte)rnd.Next(0x100); } return retval; } private static CancellationToken MakeTimeoutToken(int msec = 5000) { var token = new CancellationTokenSource(msec); return token.Token; } public static async Task<int> ExecuteClientTest(ThriftTest.Client client) { var returnCode = 0; Console.Write("testVoid()"); await client.testVoid(MakeTimeoutToken()); Console.WriteLine(" = void"); Console.Write("testString(\"Test\")"); var s = await client.testString("Test", MakeTimeoutToken()); Console.WriteLine(" = \"" + s + "\""); if ("Test" != s) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testBool(true)"); var t = await client.testBool((bool)true, MakeTimeoutToken()); Console.WriteLine(" = " + t); if (!t) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testBool(false)"); var f = await client.testBool((bool)false, MakeTimeoutToken()); Console.WriteLine(" = " + f); if (f) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testByte(1)"); var i8 = await client.testByte((sbyte)1, MakeTimeoutToken()); Console.WriteLine(" = " + i8); if (1 != i8) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testI32(-1)"); var i32 = await client.testI32(-1, MakeTimeoutToken()); Console.WriteLine(" = " + i32); if (-1 != i32) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testI64(-34359738368)"); var i64 = await client.testI64(-34359738368, MakeTimeoutToken()); Console.WriteLine(" = " + i64); if (-34359738368 != i64) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } // TODO: Validate received message Console.Write("testDouble(5.325098235)"); var dub = await client.testDouble(5.325098235, MakeTimeoutToken()); Console.WriteLine(" = " + dub); if (5.325098235 != dub) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testDouble(-0.000341012439638598279)"); dub = await client.testDouble(-0.000341012439638598279, MakeTimeoutToken()); Console.WriteLine(" = " + dub); if (-0.000341012439638598279 != dub) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } // testBinary() foreach(BinaryTestSize binTestCase in Enum.GetValues(typeof(BinaryTestSize))) { var binOut = PrepareTestData(true, binTestCase); Console.Write("testBinary({0} bytes)", binOut.Length); try { var binIn = await client.testBinary(binOut, MakeTimeoutToken()); Console.WriteLine(" = {0} bytes", binIn.Length); if (binIn.Length != binOut.Length) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } for (var ofs = 0; ofs < Math.Min(binIn.Length, binOut.Length); ++ofs) { if (binIn[ofs] != binOut[ofs]) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } } } catch (Thrift.TApplicationException ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; Console.WriteLine(ex.Message + "\n" + ex.StackTrace); } } // CrazyNesting Console.WriteLine("Test CrazyNesting"); var one = new CrazyNesting(); var two = new CrazyNesting(); one.String_field = "crazy"; two.String_field = "crazy"; one.Binary_field = new byte[] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF }; two.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF }; if (typeof(CrazyNesting).GetMethod("Equals")?.DeclaringType == typeof(CrazyNesting)) { if (!one.Equals(two)) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorContainers; } } // TODO: Validate received message Console.Write("testStruct({\"Zero\", 1, -3, -5})"); var o = new Xtruct { String_thing = "Zero", Byte_thing = (sbyte)1, I32_thing = -3, I64_thing = -5 }; var i = await client.testStruct(o, MakeTimeoutToken()); Console.WriteLine(" = {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}"); // TODO: Validate received message Console.Write("testNest({1, {\"Zero\", 1, -3, -5}, 5})"); var o2 = new Xtruct2 { Byte_thing = (sbyte)1, Struct_thing = o, I32_thing = 5 }; var i2 = await client.testNest(o2, MakeTimeoutToken()); i = i2.Struct_thing; Console.WriteLine(" = {" + i2.Byte_thing + ", {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}, " + i2.I32_thing + "}"); var mapout = new Dictionary<int, int>(); for (var j = 0; j < 5; j++) { mapout[j] = j - 10; } Console.Write("testMap({"); var first = true; foreach (var key in mapout.Keys) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(key + " => " + mapout[key]); } Console.Write("})"); var mapin = await client.testMap(mapout, MakeTimeoutToken()); Console.Write(" = {"); first = true; foreach (var key in mapin.Keys) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(key + " => " + mapin[key]); } Console.WriteLine("}"); // TODO: Validate received message var listout = new List<int>(); for (var j = -2; j < 3; j++) { listout.Add(j); } Console.Write("testList({"); first = true; foreach (var j in listout) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.Write("})"); var listin = await client.testList(listout, MakeTimeoutToken()); Console.Write(" = {"); first = true; foreach (var j in listin) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.WriteLine("}"); //set // TODO: Validate received message var setout = new THashSet<int>(); for (var j = -2; j < 3; j++) { setout.Add(j); } Console.Write("testSet({"); first = true; foreach (int j in setout) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.Write("})"); var setin = await client.testSet(setout, MakeTimeoutToken()); Console.Write(" = {"); first = true; foreach (int j in setin) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.WriteLine("}"); Console.Write("testEnum(ONE)"); var ret = await client.testEnum(Numberz.ONE, MakeTimeoutToken()); Console.WriteLine(" = " + ret); if (Numberz.ONE != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(TWO)"); ret = await client.testEnum(Numberz.TWO, MakeTimeoutToken()); Console.WriteLine(" = " + ret); if (Numberz.TWO != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(THREE)"); ret = await client.testEnum(Numberz.THREE, MakeTimeoutToken()); Console.WriteLine(" = " + ret); if (Numberz.THREE != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(FIVE)"); ret = await client.testEnum(Numberz.FIVE, MakeTimeoutToken()); Console.WriteLine(" = " + ret); if (Numberz.FIVE != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(EIGHT)"); ret = await client.testEnum(Numberz.EIGHT, MakeTimeoutToken()); Console.WriteLine(" = " + ret); if (Numberz.EIGHT != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testTypedef(309858235082523)"); var uid = await client.testTypedef(309858235082523L, MakeTimeoutToken()); Console.WriteLine(" = " + uid); if (309858235082523L != uid) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } // TODO: Validate received message Console.Write("testMapMap(1)"); var mm = await client.testMapMap(1, MakeTimeoutToken()); Console.Write(" = {"); foreach (var key in mm.Keys) { Console.Write(key + " => {"); var m2 = mm[key]; foreach (var k2 in m2.Keys) { Console.Write(k2 + " => " + m2[k2] + ", "); } Console.Write("}, "); } Console.WriteLine("}"); // TODO: Validate received message var insane = new Insanity { UserMap = new Dictionary<Numberz, long> { [Numberz.FIVE] = 5000L } }; var truck = new Xtruct { String_thing = "Truck", Byte_thing = (sbyte)8, I32_thing = 8, I64_thing = 8 }; insane.Xtructs = new List<Xtruct> { truck }; Console.Write("testInsanity()"); var whoa = await client.testInsanity(insane, MakeTimeoutToken()); Console.Write(" = {"); foreach (var key in whoa.Keys) { var val = whoa[key]; Console.Write(key + " => {"); foreach (var k2 in val.Keys) { var v2 = val[k2]; Console.Write(k2 + " => {"); var userMap = v2.UserMap; Console.Write("{"); if (userMap != null) { foreach (var k3 in userMap.Keys) { Console.Write(k3 + " => " + userMap[k3] + ", "); } } else { Console.Write("null"); } Console.Write("}, "); var xtructs = v2.Xtructs; Console.Write("{"); if (xtructs != null) { foreach (var x in xtructs) { Console.Write("{\"" + x.String_thing + "\", " + x.Byte_thing + ", " + x.I32_thing + ", " + x.I32_thing + "}, "); } } else { Console.Write("null"); } Console.Write("}"); Console.Write("}, "); } Console.Write("}, "); } Console.WriteLine("}"); sbyte arg0 = 1; var arg1 = 2; var arg2 = long.MaxValue; var multiDict = new Dictionary<short, string> { [1] = "one" }; var tmpMultiDict = new List<string>(); foreach (var pair in multiDict) tmpMultiDict.Add(pair.Key +" => "+ pair.Value); var arg4 = Numberz.FIVE; long arg5 = 5000000; Console.Write("Test Multi(" + arg0 + "," + arg1 + "," + arg2 + ",{" + string.Join(",", tmpMultiDict) + "}," + arg4 + "," + arg5 + ")"); var multiResponse = await client.testMulti(arg0, arg1, arg2, multiDict, arg4, arg5, MakeTimeoutToken()); Console.Write(" = Xtruct(byte_thing:" + multiResponse.Byte_thing + ",String_thing:" + multiResponse.String_thing + ",i32_thing:" + multiResponse.I32_thing + ",i64_thing:" + multiResponse.I64_thing + ")\n"); try { Console.WriteLine("testException(\"Xception\")"); await client.testException("Xception", MakeTimeoutToken()); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Xception ex) { if (ex.ErrorCode != 1001 || ex.Message != "Xception") { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + "\n" + ex.StackTrace); } try { Console.WriteLine("testException(\"TException\")"); await client.testException("TException", MakeTimeoutToken()); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Thrift.TException) { // OK } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + "\n" + ex.StackTrace); } try { Console.WriteLine("testException(\"ok\")"); await client.testException("ok", MakeTimeoutToken()); // OK } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + "\n" + ex.StackTrace); } try { Console.WriteLine("testMultiException(\"Xception\", ...)"); await client.testMultiException("Xception", "ignore", MakeTimeoutToken()); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Xception ex) { if (ex.ErrorCode != 1001 || ex.Message != "This is an Xception") { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + "\n" + ex.StackTrace); } try { Console.WriteLine("testMultiException(\"Xception2\", ...)"); await client.testMultiException("Xception2", "ignore", MakeTimeoutToken()); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Xception2 ex) { if (ex.ErrorCode != 2002 || ex.Struct_thing.String_thing != "This is an Xception2") { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + "\n" + ex.StackTrace); } try { Console.WriteLine("testMultiException(\"success\", \"OK\")"); if ("OK" != (await client.testMultiException("success", "OK", MakeTimeoutToken())).String_thing) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + "\n" + ex.StackTrace); } Console.WriteLine("Test Oneway(1)"); var sw = new Stopwatch(); sw.Start(); await client.testOneway(1, MakeTimeoutToken()); sw.Stop(); if (sw.ElapsedMilliseconds > 1000) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("Test Calltime()"); var times = 50; sw.Reset(); sw.Start(); var token = MakeTimeoutToken(20000); for (var k = 0; k < times; ++k) await client.testVoid(token); sw.Stop(); Console.WriteLine(" = {0} ms a testVoid() call", sw.ElapsedMilliseconds / times); return returnCode; } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2011 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit wiki.developer.mindtouch.com; * please review the licensing section. * * 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.Diagnostics; using System.Linq; using System.Threading; using log4net; using MindTouch.Dream.Test.Mock; using MindTouch.Tasking; using MindTouch.Xml; namespace MindTouch.Dream.Test { /// <summary> /// Provides a mocking framework for intercepting <see cref="Plug"/> calls. /// </summary> /// <remarks> /// Meant to be used to test services without having to set up dependent remote endpoints the service relies on for proper execution. /// <see cref="MockPlug"/> provides 3 different mechanisms for mocking an endpoint: /// <list type="bullet"> /// <item> /// <see cref="MockPlug"/> endpoints, which can match requests based on content and supply a reply. These endpoints are order independent and /// can be set up to verifiable. /// </item> /// <item> /// <see cref="AutoMockPlug"/> endpoints, which are order dependent and provide an Arrange/Act/Assert workflow for validating calls. /// </item> /// <item> /// <see cref="MockInvokeDelegate"/> endpoints which redirect an intercepted Uri (and child paths) to a delegate to be handled as the /// desired by the delegate implementor. /// </item> /// </list> /// </remarks> public class MockPlug : IMockPlug { //--- Types --- internal interface IMockInvokee { //--- Methods --- void Invoke(Plug plug, string verb, XUri uri, DreamMessage request, Result<DreamMessage> response); //--- Properties --- int EndPointScore { get; } XUri Uri { get; } } internal class MockInvokee : IMockInvokee { //--- Fields --- private readonly XUri _uri; private readonly MockInvokeDelegate _callback; private readonly int _endpointScore; //--- Constructors --- public MockInvokee(XUri uri, MockInvokeDelegate callback, int endpointScore) { _uri = uri; _callback = callback; _endpointScore = endpointScore; } //--- Properties --- public int EndPointScore { get { return _endpointScore; } } public XUri Uri { get { return _uri; } } //--- Methods --- public void Invoke(Plug plug, string verb, XUri uri, DreamMessage request, Result<DreamMessage> response) { _callback(plug, verb, uri, request, response); } } //--- Delegates --- /// <summary> /// Delegate for registering a callback on Uri/Child Uri interception via <see cref="MockPlug.Register(MindTouch.Dream.XUri,MindTouch.Dream.Test.MockPlug.MockInvokeDelegate)"/>. /// </summary> /// <param name="plug">Invoking plug instance.</param> /// <param name="verb">Request verb.</param> /// <param name="uri">Request uri.</param> /// <param name="request">Request message.</param> /// <param name="response">Synchronization handle for response message.</param> public delegate void MockInvokeDelegate(Dream.Plug plug, string verb, XUri uri, DreamMessage request, Result<DreamMessage> response); //--- Class Fields --- private static readonly Dictionary<string, List<MockPlug>> _mocks = new Dictionary<string, List<MockPlug>>(); private static readonly ILog _log = LogUtils.CreateLog(); private static int _setupcounter = 0; //--- Class Properties --- /// <summary> /// The default base Uri that will return a <see cref="DreamMessage.Ok(MindTouch.Xml.XDoc)"/> for any request. Should be used as no-op endpoint. /// </summary> public static readonly XUri DefaultUri = new XUri(MockEndpoint.DEFAULT); //--- Class Methods --- /// <summary> /// Register a callback to intercept any calls to a uri and its child paths. /// </summary> /// <param name="uri">Base Uri to intercept.</param> /// <param name="mock">Interception callback.</param> public static void Register(XUri uri, MockInvokeDelegate mock) { Register(uri, mock, int.MaxValue); } /// <summary> /// Register a callback to intercept any calls to a uri and its child paths. /// </summary> /// <param name="uri">Base Uri to intercept.</param> /// <param name="mock">Interception callback.</param> /// <param name="endpointScore">The score to return to <see cref="IPlugEndpoint.GetScoreWithNormalizedUri"/> for this uri.</param> public static void Register(XUri uri, MockInvokeDelegate mock, int endpointScore) { MockEndpoint.Instance.Register(new MockInvokee(uri, mock, endpointScore)); } /// <summary> /// Create an <see cref="AutoMockPlug"/> instance to intercept calls to a uri and its child paths for for Arrange/Act/Assert style mocking. /// </summary> /// <param name="uri">Base Uri to intercept.</param> /// <returns>A new interceptor instance responsible for the uri.</returns> public static AutoMockPlug Register(XUri uri) { return new AutoMockPlug(uri); } /// <summary> /// Setup a new <see cref="MockPlug"/> interceptor candidate for a uri and its child paths. /// </summary> /// <remarks> /// This mechanism has not been completed and is only a WIP. /// Must further configure ordered <see cref="IMockInvokeExpectationParameter"/> parameters to make validation possible. /// </remarks> /// <param name="baseUri">Base Uri to intercept.</param> /// <returns>A new interceptor instance that may intercept the uri, depending on its additional matching parameters.</returns> public static IMockPlug Setup(string baseUri) { return Setup(new XUri(baseUri)); } /// <summary> /// Setup a new <see cref="MockPlug"/> interceptor candidate for a uri and its child paths. /// </summary> /// <remarks> /// This mechanism has not been completed and is only a WIP. /// Must further configure ordered <see cref="IMockInvokeExpectationParameter"/> parameters to make validation possible. /// </remarks> /// <param name="baseUri">Base Uri to intercept.</param> /// <param name="name">Debug name for setup</param> /// <returns>A new interceptor instance that may intercept the uri, depending on its additional matching parameters.</returns> public static IMockPlug Setup(string baseUri, string name) { return Setup(new XUri(baseUri), name); } /// <summary> /// Setup a new <see cref="MockPlug"/> interceptor candidate for a uri and its child paths. /// </summary> /// <remarks> /// This mechanism has not been completed and is only a WIP. /// Must further configure ordered <see cref="IMockInvokeExpectationParameter"/> parameters to make validation possible. /// </remarks> /// <param name="baseUri">Base Uri to intercept.</param> /// <returns>A new interceptor instance that may intercept the uri, depending on its additional matching parameters.</returns> public static IMockPlug Setup(XUri baseUri) { _setupcounter++; return Setup(baseUri, "Setup#" + _setupcounter, int.MaxValue); } /// <summary> /// Setup a new <see cref="MockPlug"/> interceptor candidate for a uri and its child paths. /// </summary> /// <remarks> /// This mechanism has not been completed and is only a WIP. /// Must further configure ordered <see cref="IMockInvokeExpectationParameter"/> parameters to make validation possible. /// Note: endPointScore is only set on the first set for a specific baseUri. Subsequent values are ignored. /// </remarks> /// <param name="baseUri">Base Uri to intercept.</param> /// <param name="endPointScore">The score to return to <see cref="IPlugEndpoint.GetScoreWithNormalizedUri"/> for this uri.</param> /// <returns>A new interceptor instance that may intercept the uri, depending on its additional matching parameters.</returns> public static IMockPlug Setup(XUri baseUri, int endPointScore) { _setupcounter++; return Setup(baseUri, "Setup#" + _setupcounter, endPointScore); } /// <summary> /// Setup a new <see cref="MockPlug"/> interceptor candidate for a uri and its child paths. /// </summary> /// <remarks> /// This mechanism has not been completed and is only a WIP. /// Must further configure ordered <see cref="IMockInvokeExpectationParameter"/> parameters to make validation possible. /// </remarks> /// <param name="baseUri">Base Uri to intercept.</param> /// <param name="name">Debug name for setup</param> /// <returns>A new interceptor instance that may intercept the uri, depending on its additional matching parameters.</returns> public static IMockPlug Setup(XUri baseUri, string name) { return Setup(baseUri, name, int.MaxValue); } /// <summary> /// Setup a new <see cref="MockPlug"/> interceptor candidate for a uri and its child paths. /// </summary> /// <remarks> /// This mechanism has not been completed and is only a WIP. /// Must further configure ordered <see cref="IMockInvokeExpectationParameter"/> parameters to make validation possible. /// Note: endPointScore is only set on the first set for a specific baseUri. Subsequent values are ignored. /// </remarks> /// <param name="baseUri">Base Uri to intercept.</param> /// <param name="name">Debug name for setup</param> /// <param name="endPointScore">The score to return to <see cref="IPlugEndpoint.GetScoreWithNormalizedUri"/> for this uri.</param> /// <returns>A new interceptor instance that may intercept the uri, depending on its additional matching parameters.</returns> public static IMockPlug Setup(XUri baseUri, string name, int endPointScore) { List<MockPlug> mocks; var key = baseUri.SchemeHostPortPath; lock(_mocks) { if(!_mocks.TryGetValue(key, out mocks)) { mocks = new List<MockPlug>(); MockInvokeDelegate callback = (plug, verb, uri, request, response) => { _log.DebugFormat("checking setups for match on {0}:{1}", verb, uri); MockPlug bestMatch = null; var matchScore = 0; foreach(var match in mocks) { var score = match.GetMatchScore(verb, uri, request); if(score > matchScore) { bestMatch = match; matchScore = score; } } if(bestMatch == null) { _log.Debug("no match"); response.Return(DreamMessage.Ok(new XDoc("empty"))); } else { _log.DebugFormat("[{0}] matched", bestMatch.Name); response.Return(bestMatch.Invoke(verb, uri, request)); } }; MockEndpoint.Instance.Register(new MockInvokee(baseUri, callback, endPointScore)); MockEndpoint.Instance.AllDeregistered += Instance_AllDeregistered; _mocks.Add(key, mocks); } } var mock = new MockPlug(baseUri, name); mocks.Add(mock); return mock; } static void Instance_AllDeregistered(object sender, EventArgs e) { lock(_mocks) { _mocks.Clear(); } } /// <summary> /// Verify all <see cref="MockPlug"/> instances created with <see cref="Setup(MindTouch.Dream.XUri)"/> since the last <see cref="DeregisterAll"/> call. /// </summary> /// <remarks> /// Uses a 10 second timeout. /// </remarks> public static void VerifyAll() { VerifyAll(TimeSpan.FromSeconds(10)); } /// <summary> /// Verify all <see cref="MockPlug"/> instances created with <see cref="Setup(MindTouch.Dream.XUri)"/> since the last <see cref="DeregisterAll"/> call. /// </summary> /// <param name="timeout">Time to wait for all expectations to be met.</param> public static void VerifyAll(TimeSpan timeout) { var verifiable = (from mocks in _mocks.Values from mock in mocks where mock.IsVerifiable select mock); foreach(var mock in verifiable) { var stopwatch = Stopwatch.StartNew(); ((IMockPlug)mock).Verify(timeout); stopwatch.Stop(); timeout = timeout.Subtract(stopwatch.Elapsed); if(timeout.TotalMilliseconds < 0) { timeout = TimeSpan.Zero; } } } /// <summary> /// Deregister all interceptors for a specific base uri /// </summary> /// <remarks> /// This will not deregister an interceptor that was registered specifically for a uri that is a child path of the provided uri. /// </remarks> /// <param name="uri">Base Uri to intercept.</param> public static void Deregister(XUri uri) { MockEndpoint.Instance.Deregister(uri); } /// <summary> /// Deregister all interceptors. /// </summary> public static void DeregisterAll() { MockEndpoint.Instance.DeregisterAll(); _setupcounter = 0; } //--- Fields --- /// <summary> /// Name for the Mock Plug for debug logging purposes. /// </summary> public readonly string Name; private readonly AutoResetEvent _called = new AutoResetEvent(false); private readonly List<Tuplet<string, Predicate<string>>> _queryMatchers = new List<Tuplet<string, Predicate<string>>>(); private readonly List<Tuplet<string, Predicate<string>>> _headerMatchers = new List<Tuplet<string, Predicate<string>>>(); private readonly DreamHeaders _headers = new DreamHeaders(); private readonly DreamHeaders _responseHeaders = new DreamHeaders(); private XUri _uri; private string _verb = "*"; private XDoc _request; private Func<DreamMessage, bool> _requestCallback; private DreamMessage _response; private Func<MockPlugInvocation, DreamMessage> _responseCallback; private int _times; private Times _verifiable; private bool _matchTrailingSlashes; //--- Constructors --- private MockPlug(XUri uri, string name) { _uri = uri; Name = name; } //--- Properties --- /// <summary> /// Used by <see cref="VerifyAll()"/> to determine whether instance should be included in verification. /// </summary> public bool IsVerifiable { get { return _verifiable != null; } } //--- Methods --- private int GetMatchScore(string verb, XUri uri, DreamMessage request) { var score = 0; if(verb.EqualsInvariantIgnoreCase(_verb)) { score = 1; } else if(_verb != "*") { return 0; } var path = _matchTrailingSlashes ? _uri.Path : _uri.WithoutTrailingSlash().Path; var incomingPath = _matchTrailingSlashes ? uri.Path : uri.WithoutTrailingSlash().Path; if(!incomingPath.EqualsInvariantIgnoreCase(path)) { return 0; } score++; if(_uri.Params != null) { foreach(var param in _uri.Params) { var v = uri.GetParam(param.Key); if(v == null || !v.EndsWithInvariantIgnoreCase(param.Value)) { return 0; } score++; } } foreach(var matcher in _queryMatchers) { var v = uri.GetParam(matcher.Item1); if(v == null || !matcher.Item2(v)) { return 0; } score++; } foreach(var matcher in _headerMatchers) { var v = request.Headers[matcher.Item1]; if(string.IsNullOrEmpty(v) || !matcher.Item2(v)) { return 0; } score++; } foreach(var header in _headers) { var v = request.Headers[header.Key]; if(string.IsNullOrEmpty(v) || !v.EqualsInvariant(header.Value)) { return 0; } score++; } if(_requestCallback != null) { if(!_requestCallback(request)) { return 0; } } else if(_request != null && (!request.HasDocument || _request != request.ToDocument())) { return 0; } score++; return score; } private DreamMessage Invoke(string verb, XUri uri, DreamMessage request) { _times++; if(_responseCallback != null) { var response = _responseCallback(new MockPlugInvocation(verb, uri, request, _responseHeaders)); _response = response; } if(_response == null) { _response = DreamMessage.Ok(new XDoc("empty")); } _response.Headers.AddRange(_responseHeaders); _called.Set(); _log.DebugFormat("invoked {0}:{1}", verb, uri); return _response; } #region Implementation of IMockPlug IMockPlug IMockPlug.Verb(string verb) { _verb = verb; return this; } IMockPlug IMockPlug.At(string[] path) { _uri = _uri.At(path); return this; } IMockPlug IMockPlug.With(string key, string value) { _uri = _uri.With(key, value); return this; } IMockPlug IMockPlug.With(string key, Predicate<string> valueCallback) { _queryMatchers.Add(new Tuplet<string, Predicate<string>>(key, valueCallback)); return this; } IMockPlug IMockPlug.WithTrailingSlash() { _uri = _uri.WithTrailingSlash(); _matchTrailingSlashes = true; return this; } IMockPlug IMockPlug.WithoutTrailingSlash() { _uri = _uri.WithoutTrailingSlash(); _matchTrailingSlashes = true; return this; } IMockPlug IMockPlug.WithBody(XDoc request) { _request = request; _requestCallback = null; return this; } IMockPlug IMockPlug.WithMessage(Func<DreamMessage, bool> requestCallback) { _requestCallback = requestCallback; _request = null; return this; } IMockPlug IMockPlug.WithHeader(string key, string value) { _headers[key] = value; return this; } IMockPlug IMockPlug.WithHeader(string key, Predicate<string> valueCallback) { _headerMatchers.Add(new Tuplet<string, Predicate<string>>(key, valueCallback)); return this; } IMockPlug IMockPlug.Returns(DreamMessage response) { _response = response; return this; } IMockPlug IMockPlug.Returns(Func<MockPlugInvocation, DreamMessage> response) { _responseCallback = response; return this; } IMockPlug IMockPlug.Returns(XDoc response) { var status = _response == null ? DreamStatus.Ok : _response.Status; var headers = _response == null ? null : _response.Headers; _response = new DreamMessage(status, headers, response); return this; } IMockPlug IMockPlug.WithResponseHeader(string key, string value) { _responseHeaders[key] = value; return this; } void IMockPlug.Verify() { if(_verifiable == null) { return; } ((IMockPlug)this).Verify(TimeSpan.FromSeconds(5), _verifiable); } void IMockPlug.Verify(Times times) { ((IMockPlug)this).Verify(TimeSpan.FromSeconds(5), times); } IMockPlug IMockPlug.ExpectAtLeastOneCall() { _verifiable = Times.AtLeastOnce(); return this; } IMockPlug IMockPlug.ExpectCalls(Times called) { _verifiable = called; return this; } void IMockPlug.Verify(TimeSpan timeout) { if(_verifiable == null) { return; } ((IMockPlug)this).Verify(timeout, _verifiable); } void IMockPlug.Verify(TimeSpan timeout, Times times) { while(true) { var verified = times.Verify(_times, timeout); if(verified == Times.Result.Ok) { _log.DebugFormat("satisfied {0}", _uri); return; } if(verified == Times.Result.TooMany) { break; } // check if we have any time left to wait if(timeout.TotalMilliseconds < 0) { break; } _log.DebugFormat("waiting on {0}:{1} with {2:0.00}ms left in timeout", _verb, _uri, timeout.TotalMilliseconds); var stopwatch = Stopwatch.StartNew(); if(!_called.WaitOne(timeout)) { break; } timeout = timeout.Subtract(stopwatch.Elapsed); } throw new MockPlugException(string.Format("[{0}] {1}:{2} was called {3} times before timeout.", Name, _verb, _uri, _times)); } #endregion } /// <summary> /// Provides and Arrange/Act/Assert mocking framework for intercepting and handling <see cref="Plug"/> invocations. /// </summary> public class AutoMockPlug : MockPlug.IMockInvokee, IDisposable { //--- Delegates --- /// <summary> /// Delegate for custom expectations. /// </summary> /// <param name="verb">Request verb.</param> /// <param name="uri">Request uri.</param> /// <param name="request">Request message.</param> /// <param name="response">Response message output.</param> /// <param name="failureReason">Output for failure message, should the call not meet expectations.</param> /// <returns><see langword="False"/> if the call did not meet expectations of the callback.</returns> public delegate bool MockAutoInvokeDelegate(string verb, XUri uri, DreamMessage request, out DreamMessage response, out string failureReason); //--- Class Fields --- private static readonly ILog _log = LogUtils.CreateLog(); //--- Fields --- private readonly XUri _baseUri; private readonly ManualResetEvent _resetEvent = new ManualResetEvent(false); private readonly List<AutoMockInvokeExpectation> _expectations = new List<AutoMockInvokeExpectation>(); private readonly List<ExcessInterception> _excess = new List<ExcessInterception>(); private bool _failed = false; private int _current = 0; private int _index = 0; private string _failure; //--- Constructors --- internal AutoMockPlug(XUri baseUri) { _baseUri = baseUri; MockEndpoint.Instance.Register(this); } //--- Properties --- /// <summary> /// Base uri this instance is registered for. /// </summary> public XUri BaseUri { get { return _baseUri; } } /// <summary> /// <see langword="True"/> if after the Act phase has excess requests beyond set up expectations /// </summary> public bool HasInterceptsInExcessOfExpectations { get { return _excess.Count > 0; } } /// <summary> /// Total number of expectations set up. /// </summary> public int TotalExpectationCount { get { return _expectations.Count; } } /// <summary> /// Number of expecattions met. /// </summary> public int MetExpectationCount { get { return _current; } } /// <summary> /// Contains a text message detailing why <see cref="WaitAndVerify"/> failed. /// </summary> public string VerificationFailure { get { return _failure; } } /// <summary> /// Array of excess interceptions caught. /// </summary> public ExcessInterception[] ExcessInterceptions { get { return _excess.ToArray(); } } //--- Methods --- /// <summary> /// Set up an expectation from a chain of parameters. /// </summary> /// <remarks> /// <see cref="IMockInvokeExpectationParameter"/> is meant to be used as a fluent interface to set up parameter qualifications for the expecation. /// </remarks> /// <returns>A new expectation configuration instance.</returns> public IMockInvokeExpectationParameter Expect() { var expectation = new AutoMockInvokeExpectation(_baseUri, _index++); _expectations.Add(expectation); return expectation; } /// <summary> /// Expect a call at the base uri with the given verb, ignoring all other parameters. /// </summary> /// <param name="verb">Http verb to expect.</param> public void Expect(string verb) { Expect().Verb(verb); } /// <summary> /// Expect a call on the given uri with the given verb, ignoring all other parameters. /// </summary> /// <param name="verb">Http verb to expect.</param> /// <param name="uri">Uri to expect (must be a child path of <see cref="BaseUri"/>).</param> public void Expect(string verb, XUri uri) { Expect().Verb(verb).Uri(uri); } /// <summary> /// Expect a call on the given uri with the given verb and document, ignoring all other parameters. /// </summary> /// <param name="verb">Http verb to expect.</param> /// <param name="uri">Uri to expect (must be a child path of <see cref="BaseUri"/>).</param> /// <param name="requestDoc">Expected request document.</param> public void Expect(string verb, XUri uri, XDoc requestDoc) { Expect().Verb(verb).Uri(uri).RequestDocument(requestDoc); } /// <summary> /// Expect a call on the given uri with the given verb and document. /// </summary> /// <param name="verb">Http verb to expect.</param> /// <param name="uri">Uri to expect (must be a child path of <see cref="BaseUri"/>).</param> /// <param name="requestDoc">Expected request document.</param> /// <param name="response">Response message to return.</param> public void Expect(string verb, XUri uri, XDoc requestDoc, DreamMessage response) { Expect().Verb(verb).Uri(uri).RequestDocument(requestDoc).Response(response); } /// <summary> /// Create an expecation delegated to a callback. /// </summary> /// <param name="autoInvokeDelegate">Callback.</param> public void Expect(MockAutoInvokeDelegate autoInvokeDelegate) { AutoMockInvokeExpectation expectation = new AutoMockInvokeExpectation(autoInvokeDelegate); _expectations.Add(expectation); } /// <summary> /// Clear all expectations and status. /// </summary> public void Reset() { lock(this) { _expectations.Clear(); _excess.Clear(); _resetEvent.Reset(); _failed = false; _index = 0; _current = 0; _failure = null; } } /// <summary> /// Block for expectations to be met, a bad expectation to come in or the timeout to expire. /// </summary> /// <param name="timeout">Wait timeout.</param> /// <returns><see langword="True"/> if all expectations were met.</returns> public bool WaitAndVerify(TimeSpan timeout) { var stopwatch = Stopwatch.StartNew(); if(_expectations.Count == 0) { Thread.Sleep((int)timeout.TotalMilliseconds - 200); } else { bool waitResult = _resetEvent.WaitOne(timeout, false); if(!waitResult) { if(_current == 0) { AddFailure("None of the {0} expectations were called", _index); } else { AddFailure("Only {0} out of {1} expectations were called", _current, _index); } } } stopwatch.Stop(); if(string.IsNullOrEmpty(_failure)) { // wait at least 1000 milliseconds, or half as long as things took to executed so far // this should prevent excess expectations on a slow run be missed Thread.Sleep(Math.Max(1000, (int)(stopwatch.ElapsedMilliseconds / 2))); if(HasInterceptsInExcessOfExpectations) { AddFailure("Excess expectations found"); return false; } } if(!string.IsNullOrEmpty(_failure)) { _log.DebugFormat(VerificationFailure); return false; } return true; } /// <summary> /// Deregister this instance from uri interception. /// </summary> public void Dispose() { MockEndpoint.Instance.Deregister(_baseUri); } private void AddFailure(string format, params object[] args) { if(_failure == null) { _failure = string.Format("Expectations were unmet:\r\n"); } _failure += string.Format(format, args) + "\r\n"; } //--- MockPlug.IMockInvokee members --- int MockPlug.IMockInvokee.EndPointScore { get { return int.MaxValue; } } XUri MockPlug.IMockInvokee.Uri { get { return _baseUri; } } void MockPlug.IMockInvokee.Invoke(Plug plug, string verb, XUri uri, DreamMessage request, Result<DreamMessage> response) { lock(this) { if(_failed) { _log.DebugFormat("we've already failed, no point checking more expectations"); response.Return(DreamMessage.InternalError()); return; } _log.DebugFormat("{0}={1}", verb, uri); XDoc requestDoc = request.HasDocument ? request.ToDocument() : null; if(_expectations.Count == _current) { _log.DebugFormat("excess"); ExcessInterception excess = new ExcessInterception(); _excess.Add(excess); ; response.Return(excess.Call(verb, uri, requestDoc)); return; } AutoMockInvokeExpectation expectation = _expectations[_current]; expectation.Call(verb, uri, request); if(!expectation.Verify()) { AddFailure(_expectations[_current].VerificationFailure); _log.DebugFormat("got failure, setting reset event ({0})", _current); _failed = true; _resetEvent.Set(); response.Return(DreamMessage.BadRequest("expectation failure")); return; } _current++; _log.DebugFormat("expected"); if(_expectations.Count == _current) { _log.DebugFormat("setting reset event"); _resetEvent.Set(); } response.Return(expectation.GetResponse()); } } } /// <summary> /// Provides information about an excess request that occured after expecations had already been met. /// </summary> public class ExcessInterception { private string _verb; private XUri _uri; private XDoc _request; /// <summary> /// Request verb. /// </summary> public string Verb { get { return _verb; } } /// <summary> /// Request Uri. /// </summary> public XUri Uri { get { return _uri; } } /// <summary> /// Request document. /// </summary> public XDoc Request { get { return _request; } } internal DreamMessage Call(string verb, XUri uri, XDoc request) { _verb = verb; _uri = uri; _request = request; return DreamMessage.BadRequest("unexpected call"); } } /// <summary> /// Provides a fluent interface for defining parameters of an <see cref="AutoMockPlug"/> expecation. /// </summary> public interface IMockInvokeExpectationParameter { /// <summary> /// Except a given verb. /// </summary> /// <param name="verb">Verb to expect.</param> /// <returns>Same instance of <see cref="IMockInvokeExpectationParameter"/>.</returns> IMockInvokeExpectationParameter Verb(string verb); /// <summary> /// Expect a given uri (must be a child of <see cref="AutoMockPlug.BaseUri"/>. /// </summary> /// <param name="uri"></param> /// <returns>Same instance of <see cref="IMockInvokeExpectationParameter"/>.</returns> IMockInvokeExpectationParameter Uri(XUri uri); /// <summary> /// Modify the expected uri, to expec the call at the given relative path. /// </summary> /// <param name="path">Relative path to add to existing or base uri expectation.</param> /// <returns>Same instance of <see cref="IMockInvokeExpectationParameter"/>.</returns> IMockInvokeExpectationParameter At(string[] path); /// <summary> /// Expect query key/value pair. /// </summary> /// <param name="key">Query key.</param> /// <param name="value">Query value.</param> /// <returns>Same instance of <see cref="IMockInvokeExpectationParameter"/>.</returns> IMockInvokeExpectationParameter With(string key, string value); /// <summary> /// Expect a given request message (mutually exclusive to <see cref="RequestDocument(MindTouch.Xml.XDoc)"/> and <see cref="RequestDocument(System.Func{MindTouch.Xml.XDoc,bool})"/>). /// </summary> /// <param name="request">Expected message.</param> /// <returns>Same instance of <see cref="IMockInvokeExpectationParameter"/>.</returns> IMockInvokeExpectationParameter Request(DreamMessage request); /// <summary> /// Expect a given request document (mutually exclusive to <see cref="Request"/> and <see cref="RequestDocument(System.Func{MindTouch.Xml.XDoc,bool})"/>). /// </summary> /// <param name="request"></param> /// <returns>Same instance of <see cref="IMockInvokeExpectationParameter"/>.</returns> IMockInvokeExpectationParameter RequestDocument(XDoc request); /// <summary> /// Register a callback function to perform custom expectation matching. /// </summary> /// <param name="requestCallback">Callback to determine whether the document matches expecations.</param> /// <returns>Same instance of <see cref="IMockInvokeExpectationParameter"/>.</returns> IMockInvokeExpectationParameter RequestDocument(Func<XDoc, bool> requestCallback); /// <summary> /// Expect the presence of a given header. /// </summary> /// <param name="key">Header key.</param> /// <param name="value">Header value.</param> /// <returns>Same instance of <see cref="IMockInvokeExpectationParameter"/>.</returns> IMockInvokeExpectationParameter RequestHeader(string key, string value); /// <summary> /// Provide a response message on expectation match. /// </summary> /// <param name="response">Response message.</param> /// <returns>Same instance of <see cref="IMockInvokeExpectationParameter"/>.</returns> IMockInvokeExpectationParameter Response(DreamMessage response); /// <summary> /// Provide a response header on expectation match. /// </summary> /// <param name="key">Header key.</param> /// <param name="value">Header value.</param> /// <returns>Same instance of <see cref="IMockInvokeExpectationParameter"/>.</returns> IMockInvokeExpectationParameter ResponseHeader(string key, string value); } internal class AutoMockInvokeExpectation : IMockInvokeExpectationParameter { //--- Static Fields --- private static readonly ILog _log = LogUtils.CreateLog(); //--- Fields --- private readonly AutoMockPlug.MockAutoInvokeDelegate _autoInvokeDelegate; private string _expectedVerb; private XUri _expectedUri; private XDoc _expectedRequestDoc; private Dictionary<string, string> _expectedRequestHeaders = new Dictionary<string, string>(); private readonly XUri _baseUri; private readonly int _index; private DreamMessage _response = DreamMessage.Ok(); private bool _called; private string _failure; private Func<XDoc, bool> _expectedRequestDocCallback; private DreamMessage _expectedRequest; //--- Properties --- public string VerificationFailure { get { return _failure; } } //--- Constructors --- public AutoMockInvokeExpectation(XUri baseUri, int index) { _baseUri = baseUri; _index = index; } public AutoMockInvokeExpectation(AutoMockPlug.MockAutoInvokeDelegate autoInvokeDelegate) { _autoInvokeDelegate = autoInvokeDelegate; } //--- Methods --- public IMockInvokeExpectationParameter Verb(string verb) { _expectedVerb = verb; return this; } public IMockInvokeExpectationParameter Uri(XUri uri) { _expectedUri = uri; return this; } public IMockInvokeExpectationParameter At(string[] path) { if(_expectedUri == null) { _expectedUri = _baseUri; } _expectedUri = _expectedUri.At(path); return this; } public IMockInvokeExpectationParameter With(string key, string value) { if(_expectedUri == null) { _expectedUri = _baseUri; } _expectedUri = _expectedUri.With(key, value); return this; } public IMockInvokeExpectationParameter Request(DreamMessage request) { _expectedRequest = request; foreach(KeyValuePair<string, string> pair in request.Headers) { RequestHeader(pair.Key, pair.Value); } return this; } public IMockInvokeExpectationParameter RequestDocument(XDoc request) { _expectedRequestDoc = request; return this; } public IMockInvokeExpectationParameter RequestDocument(Func<XDoc, bool> requestCallback) { _expectedRequestDocCallback = requestCallback; return this; } public IMockInvokeExpectationParameter RequestHeader(string key, string value) { _expectedRequestHeaders[key] = value; return this; } public IMockInvokeExpectationParameter Response(DreamMessage response) { _response = response; return this; } public IMockInvokeExpectationParameter ResponseHeader(string key, string value) { _response.Headers[key] = value; return this; } public DreamMessage GetResponse() { return _response; } public void Call(string verb, XUri uri, DreamMessage request) { _called = true; if(_autoInvokeDelegate != null) { DreamMessage response; string failure; if(!_autoInvokeDelegate(verb, uri, request, out response, out failure)) { AddFailure(failure); } else { _response = response; } } if(_expectedVerb != null && _expectedVerb != verb) { AddFailure("Expected verb '{0}', got '{1}'", _expectedVerb, verb); } if(_expectedUri != null && _expectedUri != uri) { AddFailure("Uri:\r\nExpected: {0}\r\nGot: {1}", _expectedUri, uri); } if(_expectedRequest != null) { if(request.Status != _expectedRequest.Status) { AddFailure("Status:\r\nExpected: {0}\r\nGot: {1}", _expectedRequest.Status, request.Status); } else if(!request.ContentType.Match(_expectedRequest.ContentType)) { AddFailure("Content type:\r\nExpected: {0}\r\nGot: {1}", _expectedRequest.ContentType, request.ContentType); } else if(!StringUtil.EqualsInvariant(request.ToText(), _expectedRequest.ToText())) { AddFailure("Content:\r\nExpected: {0}\r\nGot: {1}", _expectedRequest.ToText(), request.ToText()); } } else if(_expectedRequestDocCallback == null) { if(!request.HasDocument && _expectedRequestDoc != null) { AddFailure("Expected a document in request, got none"); } else if(request.HasDocument && _expectedRequestDoc != null && _expectedRequestDoc != request.ToDocument()) { AddFailure("Content:\r\nExpected: {0}\r\nGot: {1}", _expectedRequestDoc.ToString(), request.ToText()); } } else { if(!request.HasDocument) { AddFailure("Expected a document in request, got none for callback"); } else if(request.HasDocument && !_expectedRequestDocCallback(request.ToDocument())) { AddFailure("Request document'{0}', failed callback check", request.ToDocument()); } } if(_expectedRequestHeaders.Count > 0) { Dictionary<string, string> headers = new Dictionary<string, string>(); foreach(KeyValuePair<string, string> header in request.Headers) { if(_expectedRequestHeaders.ContainsKey(header.Key) && _expectedRequestHeaders[header.Key] != header.Value) { AddFailure("Expected header '{0}:\r\nExpected: {1}\r\nGot: {2}", header.Key, _expectedRequestHeaders[header.Key], header.Value); } headers[header.Key] = header.Value; } foreach(KeyValuePair<string, string> header in _expectedRequestHeaders) { if(!headers.ContainsKey(header.Key)) { AddFailure("Expected header '{0}', got none", header.Key); } } } } public bool Verify() { if(!_called) { AddFailure("never triggered"); } return _failure == null; } private void AddFailure(string format, params object[] args) { if(_failure == null) { _failure = string.Format("Expectation #{0}: ", _index + 1); } else { _failure += "; "; } string failure = string.Format(format, args); _log.DebugFormat("Expectation failure: {0}", failure); _failure += failure; } } }
using Aspose.Html.Rendering.Image; using System.Threading.Tasks; using System.Diagnostics; using System; using System.IO; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Mime; using System.Web.Http; using System.Linq; using Aspose.HTML.Live.Demos.UI.Models.Common; using Aspose.HTML.Live.Demos.UI.Helpers.Html.Conversion; using Aspose.HTML.Live.Demos.UI.Helpers.Html; namespace Aspose.HTML.Live.Demos.UI.Models { ///<Summary> /// AsposeHtmlConversionController class to convert HTML files to different formats ///</Summary> public class AsposeHtmlConversion : AsposeHTMLBase { private static List<string> imageTypes = new List<string>(){ "jpeg", "jpg", "png", "gif", "bmp", "tif", "tiff" }; private static string[] mergeableTypes = new string[] { "pdf", "xps", "tif", "tiff" }; public AsposeHtmlConversion() : base() { } static AsposeHtmlConversion() { } ///<Summary> /// Convert method - NEW ///</Summary> public Response Convert(InputFiles docs, string sourceFolder, string outputType) { if (docs == null) return BadDocumentResponse; if (docs.Count == 0 || docs.Count > MaximumUploadFiles) return MaximumFileLimitsResponse; Opts.AppName = "ConversionApp"; Opts.MethodName = "Convert"; Opts.OutputType = outputType; //SetupQueryParameters(Opts.OutputType); Opts.ZipFileName = docs.Count == 1 ? Path.GetFileNameWithoutExtension(docs[0].FileName) : "Converted_Documents"; SetDefaultOptions(docs, outputType); Opts.ResultFileName = Opts.ZipFileName; Opts.FolderName = sourceFolder; List<string> FileNames = new List<string>(); foreach (InputFile inputFile in docs) { FileNames.Add(inputFile.LocalFileName); } return Process((inFilePath, outPath, zipOutFolder) => { return ConvertFiles(FileNames.ToArray(), Opts.FolderName, Opts.OutputType); }); } private void SetupQueryParameters(string outputType) { Opts.SetupCustomQueryParameters(Request); string opt = ""; Opts.MergeMultiple = false; if (mergeableTypes.Contains(outputType.ToLower().Replace(".", ""))) { if ((opt = Opts.GetCustomParameter("mergeMultiple")) != null) { bool bMerge; if (bool.TryParse(opt, out bMerge)) Opts.MergeMultiple = bMerge; } } } ///<Summary> /// ConvertHtmlToPdf to convert html file to pdf ///</Summary> public Response ConvertHtmlToPdf(string[] fileNames, string folderName) { return ProcessTask_(fileNames, (inFiles, outPath, zipOutFolder) => { Aspose.Html.Rendering.Pdf.PdfRenderingOptions pdf_options = new Aspose.Html.Rendering.Pdf.PdfRenderingOptions(); if(Opts.HasCustomParameter("ownerPassword") || Opts.HasCustomParameter("userPassword")) { var userPw = Opts.GetCustomParameter("userPassword"); var ownerPw = Opts.GetCustomParameter("ownerPassword"); if (!(string.IsNullOrEmpty(userPw) && string.IsNullOrEmpty(ownerPw))) { pdf_options.Encryption = new Aspose.Html.Rendering.Pdf.Encryption.PdfEncryptionInfo( userPw, ownerPw, (Aspose.Html.Rendering.Pdf.Encryption.PdfPermissions)0xF3C, Aspose.Html.Rendering.Pdf.Encryption.PdfEncryptionAlgorithm.RC4_128 ); } } Dictionary<string, string> customParams = null; if (Opts.HasCustomParameter("mdTheme")) { var csstheme = Opts.GetCustomParameter("mdTheme"); customParams = new Dictionary<string, string> { { "cssTheme", csstheme } }; } SourceFormat srcFormat = ExportHelper.GetSourceFormatByFileName(Opts.FileName); ExportHelper helper = ExportHelper.GetHelper(srcFormat, ExportFormat.PDF, customParams); helper.Export(inFiles, outPath, pdf_options); }); } ///<Summary> /// ConvertHtmlToXps to convert html file to xps ///</Summary> public Response ConvertHtmlToXps(string[] fileNames, string folderName) { return ProcessTask_(fileNames, (inFiles, outPath, zipOutFolder) => { Aspose.Html.Rendering.Xps.XpsRenderingOptions xps_options = new Aspose.Html.Rendering.Xps.XpsRenderingOptions(); if (Opts.HasCustomParameter("pageSize")) { var sz = OptionHelper.getPageSizeByName(Opts.GetCustomParameter("pageSize")); if (sz != null) { xps_options.PageSetup.AnyPage.Size = sz; } } Dictionary<string, string> customParams = null; if (Opts.HasCustomParameter("mdTheme")) { var csstheme = Opts.GetCustomParameter("mdTheme"); customParams = new Dictionary<string, string> { { "cssTheme", csstheme } }; } SourceFormat srcFormat = ExportHelper.GetSourceFormatByFileName(Opts.FileName); ExportHelper helper = ExportHelper.GetHelper(srcFormat, ExportFormat.XPS, customParams); helper.Export(inFiles, outPath, xps_options); }); } ///<Summary> /// ConvertHtmlToMhtml to convert html file to mhtml ///</Summary> public Response ConvertHtmlToMhtml(string[] fileNames, string folderName) { return ProcessTask((inFilePath, outPath, zipOutFolder) => { string fileName = fileNames[0]; Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(fileName); document.Save(outPath, Html.Saving.HTMLSaveFormat.MHTML); }); } ///<Summary> /// ConvertHtmlToMarkdown to convert html file to Markdown ///</Summary> public Response ConvertHtmlToMarkdown(string[] fileNames, string folderName) { return ProcessTask((inFilePath, outPath, zipOutFolder) => { string fileName = fileNames[0]; //string fileName = inFilePath[0]; Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(fileName); document.Save(outPath, Html.Saving.HTMLSaveFormat.Markdown); }); } ///<Summary> /// Convert Markdown to HTML ///</Summary> public Response ConvertMarkdownToHtml(string[] fileNames, string folderName, string outputType) { Opts.OutputType = outputType; Opts.FolderName = folderName; Opts.FileNames = fileNames; return ProcessTask((inFilePath, outPath, zipOutFolder) => { //string fileName = fileNames[0]; string fileName = inFilePath; var document = Aspose.Html.Converters.Converter.ConvertMarkdown(fileName); document.Save(outPath); }); } public Response ConvertMarkdownToHtml_(string[] fileNames, string folderName, string outputType) { Opts.OutputType = outputType; Opts.FolderName = folderName; return ProcessTask_(fileNames, (inFiles, outPath, zipOutFolder) => { string fileName = inFiles[0]; var document = Aspose.Html.Converters.Converter.ConvertMarkdown(fileName); document.Save(outPath); }); } ///<Summary> /// ConvertHtmlToTiff to convert html file to tiff ///</Summary> public Response ConvertHtmlToTiff(string[] fileNames, string folderName) { return ProcessTask_(fileNames, (inFiles, outPath, zipOutFolder) => { ImageRenderingOptions img_options = new ImageRenderingOptions(); img_options.Format = ImageFormat.Tiff; if (Opts.HasCustomParameter("pageSize")) { var sz = OptionHelper.getPageSizeByName(Opts.GetCustomParameter("pageSize")); if (sz != null) { img_options.PageSetup.AnyPage.Size = sz; } } if (Opts.HasCustomParameter("bgColor")) { string bgColor = Opts.GetCustomParameter("bgColor"); if(!string.IsNullOrEmpty(bgColor)) { long argb = long.Parse(bgColor, System.Globalization.NumberStyles.HexNumber); img_options.BackgroundColor = System.Drawing.Color.FromArgb((int)(argb | 0xFF000000)); } } Dictionary<string, string> customParams = null; if (Opts.HasCustomParameter("mdTheme")) { var csstheme = Opts.GetCustomParameter("mdTheme"); customParams = new Dictionary<string, string> { { "cssTheme", csstheme } }; } SourceFormat srcFormat = ExportHelper.GetSourceFormatByFileName(Opts.FileName); ExportHelper helper = ExportHelper.GetHelper(srcFormat, ExportFormat.TIFF, customParams); helper.Export(inFiles, outPath, img_options); }); } ///<Summary> /// ConvertHtmlToImages to convert html file to images ///</Summary> public Response ConvertHtmlToImages(string[] fileNames, string folderName, string outputType) { if (outputType.Equals("bmp") || outputType.Equals("jpg") || outputType.Equals("jpeg") || outputType.Equals("png") || outputType.Equals("gif")) { ImageFormat format = ImageFormat.Bmp; ExportFormat expFormat = ExportFormat.BMP; if (outputType.Equals("jpg") || outputType.Equals("jpeg")) { format = ImageFormat.Jpeg; expFormat = ExportFormat.JPEG; } else if (outputType.Equals("png")) { format = ImageFormat.Png; expFormat = ExportFormat.PNG; } else if (outputType.Equals("gif")) { format = ImageFormat.Gif; expFormat = ExportFormat.GIF; } return ProcessTask_(fileNames, (inFiles, outPath, zipOutFolder) => { ImageRenderingOptions img_options = new ImageRenderingOptions(); img_options.Format = format; if (Opts.HasCustomParameter("pageSize")) { var sz = OptionHelper.getPageSizeByName(Opts.GetCustomParameter("pageSize")); if (sz != null) { img_options.PageSetup.AnyPage.Size = sz; } } if (Opts.HasCustomParameter("bgColor")) { string bgColor = Opts.GetCustomParameter("bgColor"); if (!string.IsNullOrEmpty(bgColor)) { int argb = int.Parse(bgColor, System.Globalization.NumberStyles.HexNumber); img_options.BackgroundColor = System.Drawing.Color.FromArgb(argb); } } Dictionary<string, string> customParams = null; if (Opts.HasCustomParameter("mdTheme")) { var csstheme = Opts.GetCustomParameter("mdTheme"); customParams = new Dictionary<string, string> { { "cssTheme", csstheme } }; } SourceFormat srcFormat = ExportHelper.GetSourceFormatByFileName(Opts.FileName); ExportHelper helper = ExportHelper.GetHelper(srcFormat, expFormat, customParams); helper.Export(inFiles, outPath, img_options); }); } return new Response { FileName = null, Status = "Output type not found", StatusCode = 500 }; } ///<Summary> /// ConvertFile ///</Summary> public Response ConvertFile(string fileName, string folderName, string outputType) { if (System.IO.Path.GetExtension(fileName).ToLower() == ".zip") { ProcessZipArchiveFile(ref fileName, folderName); folderName = Path.GetDirectoryName(fileName); } outputType = outputType.ToLower().Replace(".", "").Replace(" ", ""); var fn = new string[] { fileName }; if (outputType.StartsWith("pdf")) { return ConvertHtmlToPdf(fn, folderName); } else if (outputType.Equals("mhtml")) { return ConvertHtmlToMhtml(fn, folderName); } else if (outputType.Equals("tiff") || outputType.Equals("tif")) { return ConvertHtmlToTiff(fn, folderName); } else if (imageTypes.Contains(outputType)) { return ConvertHtmlToImages(fn, folderName, outputType); } else if (outputType.Equals("md")) { return ConvertHtmlToMarkdown(fn, folderName); } else if (outputType.Equals("xps")) { return ConvertHtmlToXps(fn, folderName); } else if(outputType.Equals("html")) { return ConvertMarkdownToHtml(fn, folderName, "html"); } return new Response { FileName = null, Status = "Output type not found", StatusCode = 500 }; } public Response ConvertFiles(string[] fileNames, string folderName, string outputType) { if (fileNames.Length == 1) return ConvertFile(fileNames[0], folderName, outputType); outputType = outputType.ToLower().Replace(".", "").Replace(" ", ""); if (fileNames.Count(s => ".zip".Equals(Path.GetExtension(s).ToLower())) >= 1) { List<string> fileNames1 = new List<string>(); string unzipFolderName; foreach (var fname in fileNames) { if (Path.GetExtension(fname).ToLower() == ".zip") { var fileName = fname; unzipFolderName = Path.Combine(folderName, $"{fname}__unzip"); ProcessZipArchiveFile(ref fileName, unzipFolderName); fileNames1.Add(fileName); } else fileNames1.Add(fname); } fileNames = fileNames1.ToArray(); } switch (outputType) { case "pdf": return ConvertHtmlToPdf(fileNames, folderName); case "xps": return ConvertHtmlToXps(fileNames, folderName); case "tiff": case "tif": return ConvertHtmlToTiff(fileNames, folderName); case "md": return ConvertHtmlToMarkdown(fileNames, folderName); case "html": return ConvertMarkdownToHtml_(fileNames, folderName, "html"); default: if(imageTypes.Contains(outputType)) { return ConvertHtmlToImages(fileNames, folderName, outputType); } break; } return new Response { FileName = null, Status = "Output type not found", StatusCode = 500 }; } } }
// 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. // // zlib.h -- interface of the 'zlib' general purpose compression library // version 1.2.1, November 17th, 2003 // // Copyright (C) 1995-2003 Jean-loup Gailly and Mark Adler // // 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 System.Diagnostics; namespace System.IO.Compression { internal sealed class InflaterManaged { // const tables used in decoding: // Extra bits for length code 257 - 285. private static readonly byte[] s_extraLengthBits = { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,16,56,62 }; // The base length for length code 257 - 285. // The formula to get the real length for a length code is lengthBase[code - 257] + (value stored in extraBits) private static readonly int[] s_lengthBase = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,3,0,0 }; // The base distance for distance code 0 - 31 // The real distance for a distance code is distanceBasePosition[code] + (value stored in extraBits) private static readonly int[] s_distanceBasePosition = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,32769,49153 }; // code lengths for code length alphabet is stored in following order private static readonly byte[] s_codeOrder = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; private static readonly byte[] s_staticDistanceTreeTable = { 0x00,0x10,0x08,0x18,0x04,0x14,0x0c,0x1c,0x02,0x12,0x0a,0x1a, 0x06,0x16,0x0e,0x1e,0x01,0x11,0x09,0x19,0x05,0x15,0x0d,0x1d, 0x03,0x13,0x0b,0x1b,0x07,0x17,0x0f,0x1f }; private readonly OutputWindow _output; private readonly InputBuffer _input; private HuffmanTree _literalLengthTree; private HuffmanTree _distanceTree; private InflaterState _state; private bool _hasFormatReader; private int _bfinal; private BlockType _blockType; // uncompressed block private readonly byte[] _blockLengthBuffer = new byte[4]; private int _blockLength; // compressed block private int _length; private int _distanceCode; private int _extraBits; private int _loopCounter; private int _literalLengthCodeCount; private int _distanceCodeCount; private int _codeLengthCodeCount; private int _codeArraySize; private int _lengthCode; private readonly byte[] _codeList; // temporary array to store the code length for literal/Length and distance private readonly byte[] _codeLengthTreeCodeLength; private readonly bool _deflate64; private HuffmanTree _codeLengthTree; private IFileFormatReader _formatReader; // class to decode header and footer (e.g. gzip) public InflaterManaged(bool deflate64) { _output = new OutputWindow(); _input = new InputBuffer(); _codeList = new byte[HuffmanTree.MaxLiteralTreeElements + HuffmanTree.MaxDistTreeElements]; _codeLengthTreeCodeLength = new byte[HuffmanTree.NumberOfCodeLengthTreeElements]; _deflate64 = deflate64; Reset(); } internal InflaterManaged(IFileFormatReader reader, bool deflate64) { _output = new OutputWindow(); _input = new InputBuffer(); _codeList = new byte[HuffmanTree.MaxLiteralTreeElements + HuffmanTree.MaxDistTreeElements]; _codeLengthTreeCodeLength = new byte[HuffmanTree.NumberOfCodeLengthTreeElements]; _deflate64 = deflate64; if (reader != null) { _formatReader = reader; _hasFormatReader = true; } Reset(); } public void SetFileFormatReader(IFileFormatReader reader) { _formatReader = reader; _hasFormatReader = true; Reset(); } private void Reset() { _state = _hasFormatReader ? InflaterState.ReadingHeader : // start by reading Header info InflaterState.ReadingBFinal; // start by reading BFinal bit } public void SetInput(byte[] inputBytes, int offset, int length) => _input.SetInput(inputBytes, offset, length); // append the bytes public bool Finished() => _state == InflaterState.Done || _state == InflaterState.VerifyingFooter; public int AvailableOutput => _output.AvailableBytes; public bool NeedsInput() => _input.NeedsInput(); public int Inflate(byte[] bytes, int offset, int length) { // copy bytes from output to outputbytes if we have available bytes // if buffer is not filled up. keep decoding until no input are available // if decodeBlock returns false. Throw an exception. int count = 0; do { int copied = _output.CopyTo(bytes, offset, length); if (copied > 0) { if (_hasFormatReader) { _formatReader.UpdateWithBytesRead(bytes, offset, copied); } offset += copied; count += copied; length -= copied; } if (length == 0) { // filled in the bytes array break; } // Decode will return false when more input is needed } while (!Finished() && Decode()); if (_state == InflaterState.VerifyingFooter) { // finished reading CRC // In this case finished is true and output window has all the data. // But some data in output window might not be copied out. if (_output.AvailableBytes == 0) { _formatReader.Validate(); } } return count; } //Each block of compressed data begins with 3 header bits // containing the following data: // first bit BFINAL // next 2 bits BTYPE // Note that the header bits do not necessarily begin on a byte // boundary, since a block does not necessarily occupy an integral // number of bytes. // BFINAL is set if and only if this is the last block of the data // set. // BTYPE specifies how the data are compressed, as follows: // 00 - no compression // 01 - compressed with fixed Huffman codes // 10 - compressed with dynamic Huffman codes // 11 - reserved (error) // The only difference between the two compressed cases is how the // Huffman codes for the literal/length and distance alphabets are // defined. // // This function returns true for success (end of block or output window is full,) // false if we are short of input // private bool Decode() { bool eob = false; bool result = false; if (Finished()) { return true; } if (_hasFormatReader) { if (_state == InflaterState.ReadingHeader) { if (!_formatReader.ReadHeader(_input)) { return false; } _state = InflaterState.ReadingBFinal; } else if (_state == InflaterState.StartReadingFooter || _state == InflaterState.ReadingFooter) { if (!_formatReader.ReadFooter(_input)) return false; _state = InflaterState.VerifyingFooter; return true; } } if (_state == InflaterState.ReadingBFinal) { // reading bfinal bit // Need 1 bit if (!_input.EnsureBitsAvailable(1)) return false; _bfinal = _input.GetBits(1); _state = InflaterState.ReadingBType; } if (_state == InflaterState.ReadingBType) { // Need 2 bits if (!_input.EnsureBitsAvailable(2)) { _state = InflaterState.ReadingBType; return false; } _blockType = (BlockType)_input.GetBits(2); if (_blockType == BlockType.Dynamic) { _state = InflaterState.ReadingNumLitCodes; } else if (_blockType == BlockType.Static) { _literalLengthTree = HuffmanTree.StaticLiteralLengthTree; _distanceTree = HuffmanTree.StaticDistanceTree; _state = InflaterState.DecodeTop; } else if (_blockType == BlockType.Uncompressed) { _state = InflaterState.UncompressedAligning; } else { throw new InvalidDataException(SR.UnknownBlockType); } } if (_blockType == BlockType.Dynamic) { if (_state < InflaterState.DecodeTop) { // we are reading the header result = DecodeDynamicBlockHeader(); } else { result = DecodeBlock(out eob); // this can returns true when output is full } } else if (_blockType == BlockType.Static) { result = DecodeBlock(out eob); } else if (_blockType == BlockType.Uncompressed) { result = DecodeUncompressedBlock(out eob); } else { throw new InvalidDataException(SR.UnknownBlockType); } // // If we reached the end of the block and the block we were decoding had // bfinal=1 (final block) // if (eob && (_bfinal != 0)) { if (_hasFormatReader) _state = InflaterState.StartReadingFooter; else _state = InflaterState.Done; } return result; } // Format of Non-compressed blocks (BTYPE=00): // // Any bits of input up to the next byte boundary are ignored. // The rest of the block consists of the following information: // // 0 1 2 3 4... // +---+---+---+---+================================+ // | LEN | NLEN |... LEN bytes of literal data...| // +---+---+---+---+================================+ // // LEN is the number of data bytes in the block. NLEN is the // one's complement of LEN. private bool DecodeUncompressedBlock(out bool end_of_block) { end_of_block = false; while (true) { switch (_state) { case InflaterState.UncompressedAligning: // initial state when calling this function // we must skip to a byte boundary _input.SkipToByteBoundary(); _state = InflaterState.UncompressedByte1; goto case InflaterState.UncompressedByte1; case InflaterState.UncompressedByte1: // decoding block length case InflaterState.UncompressedByte2: case InflaterState.UncompressedByte3: case InflaterState.UncompressedByte4: int bits = _input.GetBits(8); if (bits < 0) { return false; } _blockLengthBuffer[_state - InflaterState.UncompressedByte1] = (byte)bits; if (_state == InflaterState.UncompressedByte4) { _blockLength = _blockLengthBuffer[0] + ((int)_blockLengthBuffer[1]) * 256; int blockLengthComplement = _blockLengthBuffer[2] + ((int)_blockLengthBuffer[3]) * 256; // make sure complement matches if ((ushort)_blockLength != (ushort)(~blockLengthComplement)) { throw new InvalidDataException(SR.InvalidBlockLength); } } _state += 1; break; case InflaterState.DecodingUncompressed: // copying block data // Directly copy bytes from input to output. int bytesCopied = _output.CopyFrom(_input, _blockLength); _blockLength -= bytesCopied; if (_blockLength == 0) { // Done with this block, need to re-init bit buffer for next block _state = InflaterState.ReadingBFinal; end_of_block = true; return true; } // We can fail to copy all bytes for two reasons: // Running out of Input // running out of free space in output window if (_output.FreeBytes == 0) { return true; } return false; default: Debug.Fail("check why we are here!"); throw new InvalidDataException(SR.UnknownState); } } } private bool DecodeBlock(out bool end_of_block_code_seen) { end_of_block_code_seen = false; int freeBytes = _output.FreeBytes; // it is a little bit faster than frequently accessing the property while (freeBytes > 258) { // 258 means we can safely do decoding since maximum repeat length is 258 int symbol; switch (_state) { case InflaterState.DecodeTop: // decode an element from the literal tree // TODO: optimize this!!! symbol = _literalLengthTree.GetNextSymbol(_input); if (symbol < 0) { // running out of input return false; } if (symbol < 256) { // literal _output.Write((byte)symbol); --freeBytes; } else if (symbol == 256) { // end of block end_of_block_code_seen = true; // Reset state _state = InflaterState.ReadingBFinal; return true; } else { // length/distance pair symbol -= 257; // length code started at 257 if (symbol < 8) { symbol += 3; // match length = 3,4,5,6,7,8,9,10 _extraBits = 0; } else if (!_deflate64 && symbol == 28) { // extra bits for code 285 is 0 symbol = 258; // code 285 means length 258 _extraBits = 0; } else { if (symbol < 0 || symbol >= s_extraLengthBits.Length) { throw new InvalidDataException(SR.GenericInvalidData); } _extraBits = s_extraLengthBits[symbol]; Debug.Assert(_extraBits != 0, "We handle other cases separately!"); } _length = symbol; goto case InflaterState.HaveInitialLength; } break; case InflaterState.HaveInitialLength: if (_extraBits > 0) { _state = InflaterState.HaveInitialLength; int bits = _input.GetBits(_extraBits); if (bits < 0) { return false; } if (_length < 0 || _length >= s_lengthBase.Length) { throw new InvalidDataException(SR.GenericInvalidData); } _length = s_lengthBase[_length] + bits; } _state = InflaterState.HaveFullLength; goto case InflaterState.HaveFullLength; case InflaterState.HaveFullLength: if (_blockType == BlockType.Dynamic) { _distanceCode = _distanceTree.GetNextSymbol(_input); } else { // get distance code directly for static block _distanceCode = _input.GetBits(5); if (_distanceCode >= 0) { _distanceCode = s_staticDistanceTreeTable[_distanceCode]; } } if (_distanceCode < 0) { // running out input return false; } _state = InflaterState.HaveDistCode; goto case InflaterState.HaveDistCode; case InflaterState.HaveDistCode: // To avoid a table lookup we note that for distanceCode >= 2, // extra_bits = (distanceCode-2) >> 1 int offset; if (_distanceCode > 3) { _extraBits = (_distanceCode - 2) >> 1; int bits = _input.GetBits(_extraBits); if (bits < 0) { return false; } offset = s_distanceBasePosition[_distanceCode] + bits; } else { offset = _distanceCode + 1; } Debug.Assert(freeBytes >= 258, "following operation is not safe!"); _output.WriteLengthDistance(_length, offset); freeBytes -= _length; _state = InflaterState.DecodeTop; break; default: Debug.Fail("check why we are here!"); throw new InvalidDataException(SR.UnknownState); } } return true; } // Format of the dynamic block header: // 5 Bits: HLIT, # of Literal/Length codes - 257 (257 - 286) // 5 Bits: HDIST, # of Distance codes - 1 (1 - 32) // 4 Bits: HCLEN, # of Code Length codes - 4 (4 - 19) // // (HCLEN + 4) x 3 bits: code lengths for the code length // alphabet given just above, in the order: 16, 17, 18, // 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 // // These code lengths are interpreted as 3-bit integers // (0-7); as above, a code length of 0 means the // corresponding symbol (literal/length or distance code // length) is not used. // // HLIT + 257 code lengths for the literal/length alphabet, // encoded using the code length Huffman code // // HDIST + 1 code lengths for the distance alphabet, // encoded using the code length Huffman code // // The code length repeat codes can cross from HLIT + 257 to the // HDIST + 1 code lengths. In other words, all code lengths form // a single sequence of HLIT + HDIST + 258 values. private bool DecodeDynamicBlockHeader() { switch (_state) { case InflaterState.ReadingNumLitCodes: _literalLengthCodeCount = _input.GetBits(5); if (_literalLengthCodeCount < 0) { return false; } _literalLengthCodeCount += 257; _state = InflaterState.ReadingNumDistCodes; goto case InflaterState.ReadingNumDistCodes; case InflaterState.ReadingNumDistCodes: _distanceCodeCount = _input.GetBits(5); if (_distanceCodeCount < 0) { return false; } _distanceCodeCount += 1; _state = InflaterState.ReadingNumCodeLengthCodes; goto case InflaterState.ReadingNumCodeLengthCodes; case InflaterState.ReadingNumCodeLengthCodes: _codeLengthCodeCount = _input.GetBits(4); if (_codeLengthCodeCount < 0) { return false; } _codeLengthCodeCount += 4; _loopCounter = 0; _state = InflaterState.ReadingCodeLengthCodes; goto case InflaterState.ReadingCodeLengthCodes; case InflaterState.ReadingCodeLengthCodes: while (_loopCounter < _codeLengthCodeCount) { int bits = _input.GetBits(3); if (bits < 0) { return false; } _codeLengthTreeCodeLength[s_codeOrder[_loopCounter]] = (byte)bits; ++_loopCounter; } for (int i = _codeLengthCodeCount; i < s_codeOrder.Length; i++) { _codeLengthTreeCodeLength[s_codeOrder[i]] = 0; } // create huffman tree for code length _codeLengthTree = new HuffmanTree(_codeLengthTreeCodeLength); _codeArraySize = _literalLengthCodeCount + _distanceCodeCount; _loopCounter = 0; // reset loop count _state = InflaterState.ReadingTreeCodesBefore; goto case InflaterState.ReadingTreeCodesBefore; case InflaterState.ReadingTreeCodesBefore: case InflaterState.ReadingTreeCodesAfter: while (_loopCounter < _codeArraySize) { if (_state == InflaterState.ReadingTreeCodesBefore) { if ((_lengthCode = _codeLengthTree.GetNextSymbol(_input)) < 0) { return false; } } // The alphabet for code lengths is as follows: // 0 - 15: Represent code lengths of 0 - 15 // 16: Copy the previous code length 3 - 6 times. // The next 2 bits indicate repeat length // (0 = 3, ... , 3 = 6) // Example: Codes 8, 16 (+2 bits 11), // 16 (+2 bits 10) will expand to // 12 code lengths of 8 (1 + 6 + 5) // 17: Repeat a code length of 0 for 3 - 10 times. // (3 bits of length) // 18: Repeat a code length of 0 for 11 - 138 times // (7 bits of length) if (_lengthCode <= 15) { _codeList[_loopCounter++] = (byte)_lengthCode; } else { int repeatCount; if (_lengthCode == 16) { if (!_input.EnsureBitsAvailable(2)) { _state = InflaterState.ReadingTreeCodesAfter; return false; } if (_loopCounter == 0) { // can't have "prev code" on first code throw new InvalidDataException(); } byte previousCode = _codeList[_loopCounter - 1]; repeatCount = _input.GetBits(2) + 3; if (_loopCounter + repeatCount > _codeArraySize) { throw new InvalidDataException(); } for (int j = 0; j < repeatCount; j++) { _codeList[_loopCounter++] = previousCode; } } else if (_lengthCode == 17) { if (!_input.EnsureBitsAvailable(3)) { _state = InflaterState.ReadingTreeCodesAfter; return false; } repeatCount = _input.GetBits(3) + 3; if (_loopCounter + repeatCount > _codeArraySize) { throw new InvalidDataException(); } for (int j = 0; j < repeatCount; j++) { _codeList[_loopCounter++] = 0; } } else { // code == 18 if (!_input.EnsureBitsAvailable(7)) { _state = InflaterState.ReadingTreeCodesAfter; return false; } repeatCount = _input.GetBits(7) + 11; if (_loopCounter + repeatCount > _codeArraySize) { throw new InvalidDataException(); } for (int j = 0; j < repeatCount; j++) { _codeList[_loopCounter++] = 0; } } } _state = InflaterState.ReadingTreeCodesBefore; // we want to read the next code. } break; default: Debug.Fail("check why we are here!"); throw new InvalidDataException(SR.UnknownState); } byte[] literalTreeCodeLength = new byte[HuffmanTree.MaxLiteralTreeElements]; byte[] distanceTreeCodeLength = new byte[HuffmanTree.MaxDistTreeElements]; // Create literal and distance tables Array.Copy(_codeList, 0, literalTreeCodeLength, 0, _literalLengthCodeCount); Array.Copy(_codeList, _literalLengthCodeCount, distanceTreeCodeLength, 0, _distanceCodeCount); // Make sure there is an end-of-block code, otherwise how could we ever end? if (literalTreeCodeLength[HuffmanTree.EndOfBlockCode] == 0) { throw new InvalidDataException(); } _literalLengthTree = new HuffmanTree(literalTreeCodeLength); _distanceTree = new HuffmanTree(distanceTreeCodeLength); _state = InflaterState.DecodeTop; return true; } public void Dispose() { } } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.IO; using Mono.Cecil.Cil; using Mono.Cecil.Metadata; using Mono.Collections.Generic; using RVA = System.UInt32; namespace Mono.Cecil.PE { sealed class ImageReader : BinaryStreamReader { readonly Image image; DataDirectory cli; DataDirectory metadata; uint table_heap_offset; public ImageReader (Disposable<Stream> stream, string file_name) : base (stream.value) { image = new Image (); image.Stream = stream; image.FileName = file_name; } void MoveTo (DataDirectory directory) { BaseStream.Position = image.ResolveVirtualAddress (directory.VirtualAddress); } void ReadImage () { if (BaseStream.Length < 128) throw new BadImageFormatException (); // - DOSHeader // PE 2 // Start 58 // Lfanew 4 // End 64 if (ReadUInt16 () != 0x5a4d) throw new BadImageFormatException (); Advance (58); MoveTo (ReadUInt32 ()); if (ReadUInt32 () != 0x00004550) throw new BadImageFormatException (); // - PEFileHeader // Machine 2 image.Architecture = ReadArchitecture (); // NumberOfSections 2 ushort sections = ReadUInt16 (); // TimeDateStamp 4 image.Timestamp = ReadUInt32 (); // PointerToSymbolTable 4 // NumberOfSymbols 4 // OptionalHeaderSize 2 Advance (10); // Characteristics 2 ushort characteristics = ReadUInt16 (); ushort subsystem, dll_characteristics; ReadOptionalHeaders (out subsystem, out dll_characteristics); ReadSections (sections); ReadCLIHeader (); ReadMetadata (); ReadDebugHeader (); image.Kind = GetModuleKind (characteristics, subsystem); image.Characteristics = (ModuleCharacteristics) dll_characteristics; } TargetArchitecture ReadArchitecture () { return (TargetArchitecture) ReadUInt16 (); } static ModuleKind GetModuleKind (ushort characteristics, ushort subsystem) { if ((characteristics & 0x2000) != 0) // ImageCharacteristics.Dll return ModuleKind.Dll; if (subsystem == 0x2 || subsystem == 0x9) // SubSystem.WindowsGui || SubSystem.WindowsCeGui return ModuleKind.Windows; return ModuleKind.Console; } void ReadOptionalHeaders (out ushort subsystem, out ushort dll_characteristics) { // - PEOptionalHeader // - StandardFieldsHeader // Magic 2 bool pe64 = ReadUInt16 () == 0x20b; // pe32 || pe64 image.LinkerVersion = ReadUInt16 (); // CodeSize 4 // InitializedDataSize 4 // UninitializedDataSize4 // EntryPointRVA 4 // BaseOfCode 4 // BaseOfData 4 || 0 // - NTSpecificFieldsHeader // ImageBase 4 || 8 // SectionAlignment 4 // FileAlignement 4 // OSMajor 2 // OSMinor 2 // UserMajor 2 // UserMinor 2 // SubSysMajor 2 // SubSysMinor 2 Advance(44); image.SubSystemMajor = ReadUInt16 (); image.SubSystemMinor = ReadUInt16 (); // Reserved 4 // ImageSize 4 // HeaderSize 4 // FileChecksum 4 Advance (16); // SubSystem 2 subsystem = ReadUInt16 (); // DLLFlags 2 dll_characteristics = ReadUInt16 (); // StackReserveSize 4 || 8 // StackCommitSize 4 || 8 // HeapReserveSize 4 || 8 // HeapCommitSize 4 || 8 // LoaderFlags 4 // NumberOfDataDir 4 // - DataDirectoriesHeader // ExportTable 8 // ImportTable 8 Advance (pe64 ? 56 : 40); // ResourceTable 8 image.Win32Resources = ReadDataDirectory (); // ExceptionTable 8 // CertificateTable 8 // BaseRelocationTable 8 Advance (24); // Debug 8 image.Debug = ReadDataDirectory (); // Copyright 8 // GlobalPtr 8 // TLSTable 8 // LoadConfigTable 8 // BoundImport 8 // IAT 8 // DelayImportDescriptor8 Advance (56); // CLIHeader 8 cli = ReadDataDirectory (); if (cli.IsZero) throw new BadImageFormatException (); // Reserved 8 Advance (8); } string ReadAlignedString (int length) { int read = 0; var buffer = new char [length]; while (read < length) { var current = ReadByte (); if (current == 0) break; buffer [read++] = (char) current; } Advance (-1 + ((read + 4) & ~3) - read); return new string (buffer, 0, read); } string ReadZeroTerminatedString (int length) { int read = 0; var buffer = new char [length]; var bytes = ReadBytes (length); while (read < length) { var current = bytes [read]; if (current == 0) break; buffer [read++] = (char) current; } return new string (buffer, 0, read); } void ReadSections (ushort count) { var sections = new Section [count]; for (int i = 0; i < count; i++) { var section = new Section (); // Name section.Name = ReadZeroTerminatedString (8); // VirtualSize 4 Advance (4); // VirtualAddress 4 section.VirtualAddress = ReadUInt32 (); // SizeOfRawData 4 section.SizeOfRawData = ReadUInt32 (); // PointerToRawData 4 section.PointerToRawData = ReadUInt32 (); // PointerToRelocations 4 // PointerToLineNumbers 4 // NumberOfRelocations 2 // NumberOfLineNumbers 2 // Characteristics 4 Advance (16); sections [i] = section; } image.Sections = sections; } void ReadCLIHeader () { MoveTo (cli); // - CLIHeader // Cb 4 // MajorRuntimeVersion 2 // MinorRuntimeVersion 2 Advance (8); // Metadata 8 metadata = ReadDataDirectory (); // Flags 4 image.Attributes = (ModuleAttributes) ReadUInt32 (); // EntryPointToken 4 image.EntryPointToken = ReadUInt32 (); // Resources 8 image.Resources = ReadDataDirectory (); // StrongNameSignature 8 image.StrongName = ReadDataDirectory (); // CodeManagerTable 8 // VTableFixups 8 // ExportAddressTableJumps 8 // ManagedNativeHeader 8 } void ReadMetadata () { MoveTo (metadata); if (ReadUInt32 () != 0x424a5342) throw new BadImageFormatException (); // MajorVersion 2 // MinorVersion 2 // Reserved 4 Advance (8); image.RuntimeVersion = ReadZeroTerminatedString (ReadInt32 ()); // Flags 2 Advance (2); var streams = ReadUInt16 (); var section = image.GetSectionAtVirtualAddress (metadata.VirtualAddress); if (section == null) throw new BadImageFormatException (); image.MetadataSection = section; for (int i = 0; i < streams; i++) ReadMetadataStream (section); if (image.PdbHeap != null) ReadPdbHeap (); if (image.TableHeap != null) ReadTableHeap (); } void ReadDebugHeader () { if (image.Debug.IsZero) { image.DebugHeader = new ImageDebugHeader (Empty<ImageDebugHeaderEntry>.Array); return; } MoveTo (image.Debug); var entries = new ImageDebugHeaderEntry [(int) image.Debug.Size / ImageDebugDirectory.Size]; for (int i = 0; i < entries.Length; i++) { var directory = new ImageDebugDirectory { Characteristics = ReadInt32 (), TimeDateStamp = ReadInt32 (), MajorVersion = ReadInt16 (), MinorVersion = ReadInt16 (), Type = (ImageDebugType) ReadInt32 (), SizeOfData = ReadInt32 (), AddressOfRawData = ReadInt32 (), PointerToRawData = ReadInt32 (), }; if (directory.PointerToRawData == 0 || directory.SizeOfData < 0) { entries [i] = new ImageDebugHeaderEntry (directory, Empty<byte>.Array); continue; } var position = Position; try { MoveTo ((uint) directory.PointerToRawData); var data = ReadBytes (directory.SizeOfData); entries [i] = new ImageDebugHeaderEntry (directory, data); } finally { Position = position; } } image.DebugHeader = new ImageDebugHeader (entries); } void ReadMetadataStream (Section section) { // Offset 4 uint offset = metadata.VirtualAddress - section.VirtualAddress + ReadUInt32 (); // relative to the section start // Size 4 uint size = ReadUInt32 (); var data = ReadHeapData (offset, size); var name = ReadAlignedString (16); switch (name) { case "#~": case "#-": image.TableHeap = new TableHeap (data); table_heap_offset = offset; break; case "#Strings": image.StringHeap = new StringHeap (data); break; case "#Blob": image.BlobHeap = new BlobHeap (data); break; case "#GUID": image.GuidHeap = new GuidHeap (data); break; case "#US": image.UserStringHeap = new UserStringHeap (data); break; case "#Pdb": image.PdbHeap = new PdbHeap (data); break; } } byte [] ReadHeapData (uint offset, uint size) { var position = BaseStream.Position; MoveTo (offset + image.MetadataSection.PointerToRawData); var data = ReadBytes ((int) size); BaseStream.Position = position; return data; } void ReadTableHeap () { var heap = image.TableHeap; MoveTo (table_heap_offset + image.MetadataSection.PointerToRawData); // Reserved 4 // MajorVersion 1 // MinorVersion 1 Advance (6); // HeapSizes 1 var sizes = ReadByte (); // Reserved2 1 Advance (1); // Valid 8 heap.Valid = ReadInt64 (); // Sorted 8 heap.Sorted = ReadInt64 (); if (image.PdbHeap != null) { for (int i = 0; i < Mixin.TableCount; i++) { if (!image.PdbHeap.HasTable ((Table) i)) continue; heap.Tables [i].Length = image.PdbHeap.TypeSystemTableRows [i]; } } for (int i = 0; i < Mixin.TableCount; i++) { if (!heap.HasTable ((Table) i)) continue; heap.Tables [i].Length = ReadUInt32 (); } SetIndexSize (image.StringHeap, sizes, 0x1); SetIndexSize (image.GuidHeap, sizes, 0x2); SetIndexSize (image.BlobHeap, sizes, 0x4); ComputeTableInformations (); } static void SetIndexSize (Heap heap, uint sizes, byte flag) { if (heap == null) return; heap.IndexSize = (sizes & flag) > 0 ? 4 : 2; } int GetTableIndexSize (Table table) { return image.GetTableIndexSize (table); } int GetCodedIndexSize (CodedIndex index) { return image.GetCodedIndexSize (index); } void ComputeTableInformations () { uint offset = (uint) BaseStream.Position - table_heap_offset - image.MetadataSection.PointerToRawData; // header int stridx_size = image.StringHeap != null ? image.StringHeap.IndexSize : 2; int guididx_size = image.GuidHeap != null ? image.GuidHeap.IndexSize : 2; int blobidx_size = image.BlobHeap != null ? image.BlobHeap.IndexSize : 2; var heap = image.TableHeap; var tables = heap.Tables; for (int i = 0; i < Mixin.TableCount; i++) { var table = (Table) i; if (!heap.HasTable (table)) continue; int size; switch (table) { case Table.Module: size = 2 // Generation + stridx_size // Name + (guididx_size * 3); // Mvid, EncId, EncBaseId break; case Table.TypeRef: size = GetCodedIndexSize (CodedIndex.ResolutionScope) // ResolutionScope + (stridx_size * 2); // Name, Namespace break; case Table.TypeDef: size = 4 // Flags + (stridx_size * 2) // Name, Namespace + GetCodedIndexSize (CodedIndex.TypeDefOrRef) // BaseType + GetTableIndexSize (Table.Field) // FieldList + GetTableIndexSize (Table.Method); // MethodList break; case Table.FieldPtr: size = GetTableIndexSize (Table.Field); // Field break; case Table.Field: size = 2 // Flags + stridx_size // Name + blobidx_size; // Signature break; case Table.MethodPtr: size = GetTableIndexSize (Table.Method); // Method break; case Table.Method: size = 8 // Rva 4, ImplFlags 2, Flags 2 + stridx_size // Name + blobidx_size // Signature + GetTableIndexSize (Table.Param); // ParamList break; case Table.ParamPtr: size = GetTableIndexSize (Table.Param); // Param break; case Table.Param: size = 4 // Flags 2, Sequence 2 + stridx_size; // Name break; case Table.InterfaceImpl: size = GetTableIndexSize (Table.TypeDef) // Class + GetCodedIndexSize (CodedIndex.TypeDefOrRef); // Interface break; case Table.MemberRef: size = GetCodedIndexSize (CodedIndex.MemberRefParent) // Class + stridx_size // Name + blobidx_size; // Signature break; case Table.Constant: size = 2 // Type + GetCodedIndexSize (CodedIndex.HasConstant) // Parent + blobidx_size; // Value break; case Table.CustomAttribute: size = GetCodedIndexSize (CodedIndex.HasCustomAttribute) // Parent + GetCodedIndexSize (CodedIndex.CustomAttributeType) // Type + blobidx_size; // Value break; case Table.FieldMarshal: size = GetCodedIndexSize (CodedIndex.HasFieldMarshal) // Parent + blobidx_size; // NativeType break; case Table.DeclSecurity: size = 2 // Action + GetCodedIndexSize (CodedIndex.HasDeclSecurity) // Parent + blobidx_size; // PermissionSet break; case Table.ClassLayout: size = 6 // PackingSize 2, ClassSize 4 + GetTableIndexSize (Table.TypeDef); // Parent break; case Table.FieldLayout: size = 4 // Offset + GetTableIndexSize (Table.Field); // Field break; case Table.StandAloneSig: size = blobidx_size; // Signature break; case Table.EventMap: size = GetTableIndexSize (Table.TypeDef) // Parent + GetTableIndexSize (Table.Event); // EventList break; case Table.EventPtr: size = GetTableIndexSize (Table.Event); // Event break; case Table.Event: size = 2 // Flags + stridx_size // Name + GetCodedIndexSize (CodedIndex.TypeDefOrRef); // EventType break; case Table.PropertyMap: size = GetTableIndexSize (Table.TypeDef) // Parent + GetTableIndexSize (Table.Property); // PropertyList break; case Table.PropertyPtr: size = GetTableIndexSize (Table.Property); // Property break; case Table.Property: size = 2 // Flags + stridx_size // Name + blobidx_size; // Type break; case Table.MethodSemantics: size = 2 // Semantics + GetTableIndexSize (Table.Method) // Method + GetCodedIndexSize (CodedIndex.HasSemantics); // Association break; case Table.MethodImpl: size = GetTableIndexSize (Table.TypeDef) // Class + GetCodedIndexSize (CodedIndex.MethodDefOrRef) // MethodBody + GetCodedIndexSize (CodedIndex.MethodDefOrRef); // MethodDeclaration break; case Table.ModuleRef: size = stridx_size; // Name break; case Table.TypeSpec: size = blobidx_size; // Signature break; case Table.ImplMap: size = 2 // MappingFlags + GetCodedIndexSize (CodedIndex.MemberForwarded) // MemberForwarded + stridx_size // ImportName + GetTableIndexSize (Table.ModuleRef); // ImportScope break; case Table.FieldRVA: size = 4 // RVA + GetTableIndexSize (Table.Field); // Field break; case Table.EncLog: size = 8; break; case Table.EncMap: size = 4; break; case Table.Assembly: size = 16 // HashAlgId 4, Version 4 * 2, Flags 4 + blobidx_size // PublicKey + (stridx_size * 2); // Name, Culture break; case Table.AssemblyProcessor: size = 4; // Processor break; case Table.AssemblyOS: size = 12; // Platform 4, Version 2 * 4 break; case Table.AssemblyRef: size = 12 // Version 2 * 4 + Flags 4 + (blobidx_size * 2) // PublicKeyOrToken, HashValue + (stridx_size * 2); // Name, Culture break; case Table.AssemblyRefProcessor: size = 4 // Processor + GetTableIndexSize (Table.AssemblyRef); // AssemblyRef break; case Table.AssemblyRefOS: size = 12 // Platform 4, Version 2 * 4 + GetTableIndexSize (Table.AssemblyRef); // AssemblyRef break; case Table.File: size = 4 // Flags + stridx_size // Name + blobidx_size; // HashValue break; case Table.ExportedType: size = 8 // Flags 4, TypeDefId 4 + (stridx_size * 2) // Name, Namespace + GetCodedIndexSize (CodedIndex.Implementation); // Implementation break; case Table.ManifestResource: size = 8 // Offset, Flags + stridx_size // Name + GetCodedIndexSize (CodedIndex.Implementation); // Implementation break; case Table.NestedClass: size = GetTableIndexSize (Table.TypeDef) // NestedClass + GetTableIndexSize (Table.TypeDef); // EnclosingClass break; case Table.GenericParam: size = 4 // Number, Flags + GetCodedIndexSize (CodedIndex.TypeOrMethodDef) // Owner + stridx_size; // Name break; case Table.MethodSpec: size = GetCodedIndexSize (CodedIndex.MethodDefOrRef) // Method + blobidx_size; // Instantiation break; case Table.GenericParamConstraint: size = GetTableIndexSize (Table.GenericParam) // Owner + GetCodedIndexSize (CodedIndex.TypeDefOrRef); // Constraint break; case Table.Document: size = blobidx_size // Name + guididx_size // HashAlgorithm + blobidx_size // Hash + guididx_size; // Language break; case Table.MethodDebugInformation: size = GetTableIndexSize (Table.Document) // Document + blobidx_size; // SequencePoints break; case Table.LocalScope: size = GetTableIndexSize (Table.Method) // Method + GetTableIndexSize (Table.ImportScope) // ImportScope + GetTableIndexSize (Table.LocalVariable) // VariableList + GetTableIndexSize (Table.LocalConstant) // ConstantList + 4 * 2; // StartOffset, Length break; case Table.LocalVariable: size = 2 // Attributes + 2 // Index + stridx_size; // Name break; case Table.LocalConstant: size = stridx_size // Name + blobidx_size; // Signature break; case Table.ImportScope: size = GetTableIndexSize (Table.ImportScope) // Parent + blobidx_size; break; case Table.StateMachineMethod: size = GetTableIndexSize (Table.Method) // MoveNextMethod + GetTableIndexSize (Table.Method); // KickOffMethod break; case Table.CustomDebugInformation: size = GetCodedIndexSize (CodedIndex.HasCustomDebugInformation) // Parent + guididx_size // Kind + blobidx_size; // Value break; default: throw new NotSupportedException (); } tables [i].RowSize = (uint) size; tables [i].Offset = offset; offset += (uint) size * tables [i].Length; } } void ReadPdbHeap () { var heap = image.PdbHeap; var buffer = new ByteBuffer (heap.data); heap.Id = buffer.ReadBytes (20); heap.EntryPoint = buffer.ReadUInt32 (); heap.TypeSystemTables = buffer.ReadInt64 (); heap.TypeSystemTableRows = new uint [Mixin.TableCount]; for (int i = 0; i < Mixin.TableCount; i++) { var table = (Table) i; if (!heap.HasTable (table)) continue; heap.TypeSystemTableRows [i] = buffer.ReadUInt32 (); } } public static Image ReadImage (Disposable<Stream> stream, string file_name) { try { var reader = new ImageReader (stream, file_name); reader.ReadImage (); return reader.image; } catch (EndOfStreamException e) { throw new BadImageFormatException (stream.value.GetFileName (), e); } } public static Image ReadPortablePdb (Disposable<Stream> stream, string file_name) { try { var reader = new ImageReader (stream, file_name); var length = (uint) stream.value.Length; reader.image.Sections = new[] { new Section { PointerToRawData = 0, SizeOfRawData = length, VirtualAddress = 0, VirtualSize = length, } }; reader.metadata = new DataDirectory (0, length); reader.ReadMetadata (); return reader.image; } catch (EndOfStreamException e) { throw new BadImageFormatException (stream.value.GetFileName (), e); } } } }
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 ComicBookStoreAPI.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 XPT.Games.Generic.Constants; using XPT.Games.Generic.Maps; using XPT.Games.Twinion.Entities; namespace XPT.Games.Twinion.Maps { /// <summary> /// L1: Main Entrance /// </summary> class TwMap00 : TwMap { public override int MapIndex => 0; public override int MapID => 0x0101; protected override int RandomEncounterChance => 0; protected override int RandomEncounterExtraCount => 0; private const int CHORONZAR_KILLED_BIT = 4; protected override void FnEvent01(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "This Gateway leads out of the Dungeon."); ExitDungeon(player, type, doMsgs); } protected override void FnEvent02(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "The door is marked: 'To Gauntlet Gauche.'"); TeleportParty(player, type, doMsgs, 1, 2, 127, Direction.West); } protected override void FnEvent03(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Herein lies Gauntlet Droit."); TeleportParty(player, type, doMsgs, 1, 3, 80, Direction.East); } protected override void FnEvent04(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "To the first level of Her Majesty's proving grounds...The Queen's Aqueduct."); TeleportParty(player, type, doMsgs, 2, 1, 248, Direction.North); } protected override void FnEvent05(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Enter the Kingdom of the Night Elves... "); ShowText(player, type, doMsgs, " ....and beware."); TeleportParty(player, type, doMsgs, 4, 1, 240, Direction.North); } protected override void FnEvent06(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Here you enter the Dralkarians' Lair."); TeleportParty(player, type, doMsgs, 8, 1, 112, Direction.East); } protected override void FnEvent07(TwPlayerServer player, MapEventType type, bool doMsgs) { if ((GetPartyLevel(player, type, doMsgs, 12)) && (GetPartyCount(player, type, doMsgs) == 1)) { if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DEEPPORTALS) == 1) { FindStr(player, type, doMsgs); } else if (UsedItem(player, type, ref doMsgs, QUEENSKEY, QUEENSKEY)) { ShowText(player, type, doMsgs, "As you unlock the door with Her Majesty's key, the lock on the door as well as the key vanish!"); ShowText(player, type, doMsgs, "Now the door will remain unlocked."); SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DEEPPORTALS, 1); RemoveItem(player, type, doMsgs, QUEENSKEY); RemoveItem(player, type, doMsgs, ROPE); FindStr(player, type, doMsgs); } else { ShowText(player, type, doMsgs, "The Queen's key is needed to unlock this door."); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } } else { ShowText(player, type, doMsgs, "Only more experienced heroes may venture beyond this gateway. And even then, you must enter alone!"); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } } private void FindStr(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Find your fate in the portal east of here."); ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.East); } protected override void FnEvent08(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetPartyLevel(player, type, doMsgs, 23)) { if (GetPartyCount(player, type, doMsgs) == 1) { if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DRAKSPORT) == 1 || GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DRAKSPORT) == 2) { NorthStr(player, type, doMsgs); } else if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DRAKSPORT) == 0) && HasItem(player, type, doMsgs, WHOLEMAP)) { ShowText(player, type, doMsgs, "Your map begins to glow with an eerie green light. The light then fades to red followed by blue and finally brilliant yellow."); ShowText(player, type, doMsgs, "The magical light of this most curious map dispels the door's magic!"); ShowText(player, type, doMsgs, "The map, drained of its powers, crumbles into the nothingness from which it came."); SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DRAKSPORT, 1); RemoveItem(player, type, doMsgs, WHOLEMAP); NorthStr(player, type, doMsgs); } else { GenericStr(player, type, doMsgs); } } else { ShowText(player, type, doMsgs, "You must journey northward alone!"); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } } else { GenericStr(player, type, doMsgs); } } private void GenericStr(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Destiny awaits. It will be here for you when you are ready."); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } private void NorthStr(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Northward lies the passage of Fate."); ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); SetWallItem(player, type, doMsgs, DOOR, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } protected override void FnEvent09(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasItem(player, type, doMsgs, JESTERSCAP) && (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.CHOR_NPC_KILLED) & CHORONZAR_KILLED_BIT) == 0) { ShowText(player, type, doMsgs, "A maniacal fiend appears; removes an item you stole from him; and kills you outright."); while (HasItem(player, type, doMsgs, JESTERSCAP)) RemoveItem(player, type, doMsgs, JESTERSCAP); ModifyGold(player, type, doMsgs, - 10000); DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs)); // EXIT_DUNGEON(player, type, doMsgs); } } protected override void FnEvent0A(TwPlayerServer player, MapEventType type, bool doMsgs) { ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); ShowText(player, type, doMsgs, "Welcome, brave Champions. To the west lies Gauntlet Gauche: one of the two maps that interweave a simple quest."); ShowText(player, type, doMsgs, "Eastward lies Gauntlet Droit. There you will find challenges and helpful friends to start you on your way."); ShowText(player, type, doMsgs, "These two maps comprise the Gauntlet... A simple quest that you'd be wise to undertake before all else."); } protected override void FnEvent0B(TwPlayerServer player, MapEventType type, bool doMsgs) { ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); ShowText(player, type, doMsgs, "Northward is the entrance to the Queen's Proving Grounds. You begin there in Her Majesty's Aqueduct."); ShowText(player, type, doMsgs, "That will start your ascent to greater challenges. Fare well wherever you fare."); } protected override void FnEvent0C(TwPlayerServer player, MapEventType type, bool doMsgs) { DisablePartyJoining(player, type, doMsgs); } protected override void FnEvent0D(TwPlayerServer player, MapEventType type, bool doMsgs) { DisableSpells(player, type, doMsgs); if (GetPartyLevel(player, type, doMsgs, 23)) { if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DRAKSPORT) == 1) { ShowPortrait(player, type, doMsgs, QUEENAEOWYN); ShowText(player, type, doMsgs, "The Queen is here:"); ShowText(player, type, doMsgs, "'Loyal Champions! A magnificent achievement!"); ShowText(player, type, doMsgs, "Now, as to the markings here at this secret entrance..."); ShowText(player, type, doMsgs, "This will take you into the lowest depths!"); ShowText(player, type, doMsgs, "Together, we will breach the gates of time and march into a new world of wonders! But only together."); ShowText(player, type, doMsgs, "Each of the vile deities whom the Night Elves worship wears a magical ring. You must get each ring from its owner!"); ShowText(player, type, doMsgs, "Together, the rings are the keys that will allow us to enter the Portal of Time. And then, loyal Champions, I know not where we shall step through into Immortality."); ShowText(player, type, doMsgs, "Go, now! I shall be with thee! I will come to thee when I can. Fare thee well!'"); SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DRAKSPORT, 2); } else if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.FINISHEDGAME) == 0)) { ShowText(player, type, doMsgs, "Let us not dally...northward, onward to destiny."); } } else { ShowText(player, type, doMsgs, "Your experience is not suited for the horrors through here. Seek thee more knowledge then return."); TeleportParty(player, type, doMsgs, 1, 1, 206, Direction.South); } } protected override void FnEvent0E(TwPlayerServer player, MapEventType type, bool doMsgs) { DisableAutomaps(player, type, doMsgs); } protected override void FnEvent0F(TwPlayerServer player, MapEventType type, bool doMsgs) { DisablePartyJoining(player, type, doMsgs); if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DEEPPORTALS) == 0)) { ShowText(player, type, doMsgs, "Only more experienced heroes may venture beyond this gateway. And even then, you must have completed the Queen's proving grounds and acquired Her key!"); TeleportParty(player, type, doMsgs, 1, 1, 200, Direction.East); } } protected override void FnEvent11(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 1, 1, 88, Direction.North); } protected override void FnEvent12(TwPlayerServer player, MapEventType type, bool doMsgs) { if ((GetPartyCount(player, type, doMsgs) == 1) && (GetPartyLevel(player, type, doMsgs, 35))) { if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ENDGAMETELE) == 1) || (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ENDGAMETELE) == 2)) { SetWallItem(player, type, doMsgs, DOOR, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); ShowText(player, type, doMsgs, "A mystic portal appears, granting you an ingress to the chambers of time."); ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } else { ClearWallItem(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } } else { ClearWallItem(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } } protected override void FnEvent13(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetPartyCount(player, type, doMsgs) == 1) { if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ENDGAMETELE) == 1) || (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ENDGAMETELE) == 2)) { ShowText(player, type, doMsgs, "Go from here to the depths of time! Enter into the deepest wells of your destiny! This will take you to the start of Dissemination."); TeleportParty(player, type, doMsgs, 12, 1, 255, Direction.West); } } else { ShowText(player, type, doMsgs, "You must enter alone!"); TeleportParty(player, type, doMsgs, 1, 1, 19, Direction.North); } } protected override void FnEvent14(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetPartyCount(player, type, doMsgs) == 1) { if (IsFlagOn(player, type, doMsgs, FlagTypeDungeon, TwIndexes.TOTHEQUEEN)) { ShowText(player, type, doMsgs, "A portal forms in the wall before you! Iridescent light filters into the room, surrounding you with a vapor of magic."); ShowText(player, type, doMsgs, "THIS portal will take you into the final challenge...your Fate is at hand."); TeleportParty(player, type, doMsgs, 12, 2, 255, Direction.West); } } else { ShowText(player, type, doMsgs, "In time, this ingress shall grant you passage; but only alone and after you've earned the right, may you proceed."); TeleportParty(player, type, doMsgs, 1, 1, 19, Direction.North); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Runtime; using System.Runtime.CompilerServices; using System.ServiceModel.Channels; using System.ServiceModel.Diagnostics; using System.ServiceModel.Dispatcher; using System.Threading; using System.ServiceModel.Diagnostics.Application; using System.Threading.Tasks; namespace System.ServiceModel { public sealed class InstanceContext : CommunicationObject, IExtensibleObject<InstanceContext> { private ConcurrencyInstanceContextFacet _concurrency; private ServiceChannelManager _channels; private ExtensionCollection<InstanceContext> _extensions; private object _serviceInstanceLock = new object(); private SynchronizationContext _synchronizationContext; private object _userObject; private bool _wellKnown; private SynchronizedCollection<IChannel> _wmiChannels; private bool _isUserCreated; public InstanceContext(object implementation) : this(implementation, true) { } internal InstanceContext(object implementation, bool isUserCreated) : this(implementation, true, isUserCreated) { } internal InstanceContext(object implementation, bool wellKnown, bool isUserCreated) { if (implementation != null) { _userObject = implementation; _wellKnown = wellKnown; } _channels = new ServiceChannelManager(this); _isUserCreated = isUserCreated; } internal ConcurrencyInstanceContextFacet Concurrency { get { if (_concurrency == null) { lock (this.ThisLock) { if (_concurrency == null) _concurrency = new ConcurrencyInstanceContextFacet(); } } return _concurrency; } } protected override TimeSpan DefaultCloseTimeout { get { return ServiceDefaults.CloseTimeout; } } protected override TimeSpan DefaultOpenTimeout { get { return ServiceDefaults.OpenTimeout; } } public IExtensionCollection<InstanceContext> Extensions { get { this.ThrowIfClosed(); lock (this.ThisLock) { if (_extensions == null) _extensions = new ExtensionCollection<InstanceContext>(this, this.ThisLock); return _extensions; } } } public ICollection<IChannel> OutgoingChannels { get { this.ThrowIfClosed(); return _channels.OutgoingChannels; } } public SynchronizationContext SynchronizationContext { get { return _synchronizationContext; } set { this.ThrowIfClosedOrOpened(); _synchronizationContext = value; } } new internal object ThisLock { get { return base.ThisLock; } } internal object UserObject { get { return _userObject; } } internal ICollection<IChannel> WmiChannels { get { if (_wmiChannels == null) { lock (this.ThisLock) { if (_wmiChannels == null) { _wmiChannels = new SynchronizedCollection<IChannel>(); } } } return _wmiChannels; } } protected override void OnAbort() { _channels.Abort(); } public object GetServiceInstance(Message message) { throw ExceptionHelper.PlatformNotSupported(); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new CloseAsyncResult(timeout, callback, state, this); } protected override void OnEndClose(IAsyncResult result) { CloseAsyncResult.End(result); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return new CompletedAsyncResult(callback, state); } protected override void OnEndOpen(IAsyncResult result) { CompletedAsyncResult.End(result); } protected override void OnClose(TimeSpan timeout) { _channels.Close(timeout); } protected override void OnOpen(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); } protected override void OnOpened() { base.OnOpened(); } protected override void OnOpening() { base.OnOpening(); } protected internal override Task OnCloseAsync(TimeSpan timeout) { this.OnClose(timeout); return TaskHelpers.CompletedTask(); } protected internal override Task OnOpenAsync(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); return TaskHelpers.CompletedTask(); } internal class CloseAsyncResult : AsyncResult { private InstanceContext _instanceContext; private TimeoutHelper _timeoutHelper; public CloseAsyncResult(TimeSpan timeout, AsyncCallback callback, object state, InstanceContext instanceContext) : base(callback, state) { _timeoutHelper = new TimeoutHelper(timeout); _instanceContext = instanceContext; IAsyncResult result = _instanceContext._channels.BeginClose(_timeoutHelper.RemainingTime(), PrepareAsyncCompletion(new AsyncCompletion(CloseChannelsCallback)), this); if (result.CompletedSynchronously && CloseChannelsCallback(result)) { base.Complete(true); } } public static void End(IAsyncResult result) { AsyncResult.End<CloseAsyncResult>(result); } private bool CloseChannelsCallback(IAsyncResult result) { Fx.Assert(object.ReferenceEquals(this, result.AsyncState), "AsyncState should be this"); _instanceContext._channels.EndClose(result); return true; } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Models; using Newtonsoft.Json.Linq; namespace Microsoft.AzureStack.Management { /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for /// more information) /// </summary> internal partial class ResourceOperations : IServiceOperations<AzureStackClient>, IResourceOperations { /// <summary> /// Initializes a new instance of the ResourceOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ResourceOperations(AzureStackClient client) { this._client = client; } private AzureStackClient _client; /// <summary> /// Gets a reference to the /// Microsoft.AzureStack.Management.AzureStackClient. /// </summary> public AzureStackClient Client { get { return this._client; } } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Your documentation here. /// </param> /// <param name='fqResourceName'> /// Required. Your documentation here. /// </param> /// <param name='action'> /// Required. Your documentation here. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Your documentation here. /// </returns> public async Task<ResourceActionResult> ActionAsync(string resourceGroupName, string resourceProviderNamespace, string fqResourceName, string action, ResourceActionParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (resourceProviderNamespace == null) { throw new ArgumentNullException("resourceProviderNamespace"); } if (fqResourceName == null) { throw new ArgumentNullException("fqResourceName"); } if (action == null) { throw new ArgumentNullException("action"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); tracingParameters.Add("fqResourceName", fqResourceName); tracingParameters.Add("action", action); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "ActionAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(resourceProviderNamespace); url = url + "/"; url = url + Uri.EscapeDataString(fqResourceName); url = url + "/"; url = url + Uri.EscapeDataString(action); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = parameters.ActionParameter; httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ResourceActionResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceActionResult(); result.ActionResult = responseContent; } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Your documentation here. /// </param> /// <param name='fqResourceName'> /// Required. Your documentation here. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Your documentation here. /// </returns> public async Task<ResourceCreateOrUpdateResult> CreateOrUpdateAsync(string resourceGroupName, string resourceProviderNamespace, string fqResourceName, ResourceCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (resourceProviderNamespace == null) { throw new ArgumentNullException("resourceProviderNamespace"); } if (fqResourceName == null) { throw new ArgumentNullException("fqResourceName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Resource == null) { throw new ArgumentNullException("parameters.Resource"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); tracingParameters.Add("fqResourceName", fqResourceName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(resourceProviderNamespace); url = url + "/"; url = url + Uri.EscapeDataString(fqResourceName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject resourceCreateOrUpdateParametersValue = new JObject(); requestDoc = resourceCreateOrUpdateParametersValue; if (parameters.Resource.Properties != null) { resourceCreateOrUpdateParametersValue["properties"] = JObject.Parse(parameters.Resource.Properties); } if (parameters.Resource.Id != null) { resourceCreateOrUpdateParametersValue["id"] = parameters.Resource.Id; } if (parameters.Resource.Name != null) { resourceCreateOrUpdateParametersValue["name"] = parameters.Resource.Name; } if (parameters.Resource.Type != null) { resourceCreateOrUpdateParametersValue["type"] = parameters.Resource.Type; } if (parameters.Resource.Location != null) { resourceCreateOrUpdateParametersValue["location"] = parameters.Resource.Location; } if (parameters.Resource.Tags != null) { JObject tagsDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Resource.Tags) { string tagsKey = pair.Key; string tagsValue = pair.Value; tagsDictionary[tagsKey] = tagsValue; } resourceCreateOrUpdateParametersValue["tags"] = tagsDictionary; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ResourceCreateOrUpdateResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceCreateOrUpdateResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ResourceDefinition resourceInstance = new ResourceDefinition(); result.Resource = resourceInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { string propertiesInstance = propertiesValue.ToString(Newtonsoft.Json.Formatting.Indented); resourceInstance.Properties = propertiesInstance; } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); resourceInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); resourceInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); resourceInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); resourceInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey2 = ((string)property.Name); string tagsValue2 = ((string)property.Value); resourceInstance.Tags.Add(tagsKey2, tagsValue2); } } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Your documentation here. /// </param> /// <param name='fqResourceName'> /// Required. Your documentation here. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string resourceProviderNamespace, string fqResourceName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (resourceProviderNamespace == null) { throw new ArgumentNullException("resourceProviderNamespace"); } if (fqResourceName == null) { throw new ArgumentNullException("fqResourceName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); tracingParameters.Add("fqResourceName", fqResourceName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(resourceProviderNamespace); url = url + "/"; url = url + Uri.EscapeDataString(fqResourceName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Your documentation here. /// </param> /// <param name='fqResourceId'> /// Required. Your documentation here. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Your documentation here. /// </returns> public async Task<ResourceGetResult> GetAsync(string resourceGroupName, string resourceProviderNamespace, string fqResourceId, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (resourceProviderNamespace == null) { throw new ArgumentNullException("resourceProviderNamespace"); } if (fqResourceId == null) { throw new ArgumentNullException("fqResourceId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); tracingParameters.Add("fqResourceId", fqResourceId); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(resourceProviderNamespace); url = url + "/"; url = url + Uri.EscapeDataString(fqResourceId); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ResourceGetResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceGetResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ResourceDefinition resourceInstance = new ResourceDefinition(); result.Resource = resourceInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { string propertiesInstance = propertiesValue.ToString(Newtonsoft.Json.Formatting.Indented); resourceInstance.Properties = propertiesInstance; } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); resourceInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); resourceInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); resourceInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); resourceInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); resourceInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the spend on the resource with the given resource Id. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='resourceId'> /// Required. The resource Id. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The resource spend result /// </returns> public async Task<ResourceGetSpendResult> GetSpendAsync(string resourceId, CancellationToken cancellationToken) { // Validate if (resourceId == null) { throw new ArgumentNullException("resourceId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceId", resourceId); TracingAdapter.Enter(invocationId, this, "GetSpendAsync", tracingParameters); } // Construct URL string url = ""; url = url + Uri.EscapeDataString(resourceId); url = url + "/providers/Microsoft.Commerce/estimateResourceSpend"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=1.0"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ResourceGetSpendResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceGetSpendResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { PriceDefinition spendInstance = new PriceDefinition(); result.Spend = spendInstance; JToken amountValue = responseDoc["amount"]; if (amountValue != null && amountValue.Type != JTokenType.Null) { decimal amountInstance = ((decimal)amountValue); spendInstance.Amount = amountInstance; } JToken currencyCodeValue = responseDoc["currencyCode"]; if (currencyCodeValue != null && currencyCodeValue.Type != JTokenType.Null) { string currencyCodeInstance = ((string)currencyCodeValue); spendInstance.CurrencyCode = currencyCodeInstance; } JToken captionValue = responseDoc["caption"]; if (captionValue != null && captionValue.Type != JTokenType.Null) { string captionInstance = ((string)captionValue); spendInstance.Caption = captionInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Your documentation here. /// </param> /// <param name='fqResourceType'> /// Required. Your documentation here. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Your documentation here. /// </returns> public async Task<ResourceListResult> ListAsync(string resourceGroupName, string resourceProviderNamespace, string fqResourceType, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (resourceProviderNamespace == null) { throw new ArgumentNullException("resourceProviderNamespace"); } if (fqResourceType == null) { throw new ArgumentNullException("fqResourceType"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); tracingParameters.Add("fqResourceType", fqResourceType); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(resourceProviderNamespace); url = url + "/"; url = url + Uri.EscapeDataString(fqResourceType); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ResourceListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ResourceDefinition resourceDefinitionInstance = new ResourceDefinition(); result.Resources.Add(resourceDefinitionInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { string propertiesInstance = propertiesValue.ToString(Newtonsoft.Json.Formatting.Indented); resourceDefinitionInstance.Properties = propertiesInstance; } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); resourceDefinitionInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); resourceDefinitionInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); resourceDefinitionInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); resourceDefinitionInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); resourceDefinitionInstance.Tags.Add(tagsKey, tagsValue); } } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='nextLink'> /// Required. Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Your documentation here. /// </returns> public async Task<ResourceListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + Uri.EscapeDataString(nextLink); url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ResourceListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ResourceDefinition resourceDefinitionInstance = new ResourceDefinition(); result.Resources.Add(resourceDefinitionInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { string propertiesInstance = propertiesValue.ToString(Newtonsoft.Json.Formatting.Indented); resourceDefinitionInstance.Properties = propertiesInstance; } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); resourceDefinitionInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); resourceDefinitionInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); resourceDefinitionInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); resourceDefinitionInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); resourceDefinitionInstance.Tags.Add(tagsKey, tagsValue); } } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='resourceProviderNamespace'> /// Required. Your documentation here. /// </param> /// <param name='fqResourceType'> /// Required. Your documentation here. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Your documentation here. /// </returns> public async Task<ResourceListResult> ListWithoutResourceGroupAsync(string resourceProviderNamespace, string fqResourceType, CancellationToken cancellationToken) { // Validate if (resourceProviderNamespace == null) { throw new ArgumentNullException("resourceProviderNamespace"); } if (fqResourceType == null) { throw new ArgumentNullException("fqResourceType"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); tracingParameters.Add("fqResourceType", fqResourceType); TracingAdapter.Enter(invocationId, this, "ListWithoutResourceGroupAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/"; url = url + Uri.EscapeDataString(resourceProviderNamespace); url = url + "/"; url = url + Uri.EscapeDataString(fqResourceType); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ResourceListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ResourceDefinition resourceDefinitionInstance = new ResourceDefinition(); result.Resources.Add(resourceDefinitionInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { string propertiesInstance = propertiesValue.ToString(Newtonsoft.Json.Formatting.Indented); resourceDefinitionInstance.Properties = propertiesInstance; } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); resourceDefinitionInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); resourceDefinitionInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); resourceDefinitionInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); resourceDefinitionInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); resourceDefinitionInstance.Tags.Add(tagsKey, tagsValue); } } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.Threading; using System.Transactions.Diagnostics; namespace System.Transactions { internal interface IPromotedEnlistment { void EnlistmentDone(); void Prepared(); void ForceRollback(); void ForceRollback(Exception e); void Committed(); void Aborted(); void Aborted(Exception e); void InDoubt(); void InDoubt(Exception e); byte[] GetRecoveryInformation(); InternalEnlistment InternalEnlistment { get; set; } } // // InternalEnlistment by itself can support a Phase0 volatile enlistment. // There are derived classes to support durable, phase1 volatile & PSPE // enlistments. // internal class InternalEnlistment : ISinglePhaseNotificationInternal { // Storage for the state of the enlistment. internal EnlistmentState _twoPhaseState; // Interface implemented by the enlistment owner for notifications protected IEnlistmentNotification _twoPhaseNotifications; // Store a reference to the single phase notification interface in case // the enlisment supports it. protected ISinglePhaseNotification _singlePhaseNotifications; // Reference to the containing transaction. protected InternalTransaction _transaction; // Reference to the lightweight transaction. private Transaction _atomicTransaction; // The EnlistmentTraceIdentifier for this enlistment. private EnlistmentTraceIdentifier _traceIdentifier; // Unique value amongst all enlistments for a given internal transaction. private int _enlistmentId; internal Guid DistributedTxId { get { Guid returnValue = Guid.Empty; if (Transaction != null) { returnValue = Transaction.DistributedTxId; } return returnValue; } } // Parent Enlistment Object private Enlistment _enlistment; private PreparingEnlistment _preparingEnlistment; private SinglePhaseEnlistment _singlePhaseEnlistment; // If this enlistment is promoted store the object it delegates to. private IPromotedEnlistment _promotedEnlistment; // For Recovering Enlistments protected InternalEnlistment(Enlistment enlistment, IEnlistmentNotification twoPhaseNotifications) { Debug.Assert(this is RecoveringInternalEnlistment, "this is RecoveringInternalEnlistment"); _enlistment = enlistment; _twoPhaseNotifications = twoPhaseNotifications; _enlistmentId = 1; _traceIdentifier = EnlistmentTraceIdentifier.Empty; } // For Promotable Enlistments protected InternalEnlistment(Enlistment enlistment, InternalTransaction transaction, Transaction atomicTransaction) { Debug.Assert(this is PromotableInternalEnlistment, "this is PromotableInternalEnlistment"); _enlistment = enlistment; _transaction = transaction; _atomicTransaction = atomicTransaction; _enlistmentId = transaction._enlistmentCount++; _traceIdentifier = EnlistmentTraceIdentifier.Empty; } internal InternalEnlistment( Enlistment enlistment, InternalTransaction transaction, IEnlistmentNotification twoPhaseNotifications, ISinglePhaseNotification singlePhaseNotifications, Transaction atomicTransaction) { _enlistment = enlistment; _transaction = transaction; _twoPhaseNotifications = twoPhaseNotifications; _singlePhaseNotifications = singlePhaseNotifications; _atomicTransaction = atomicTransaction; _enlistmentId = transaction._enlistmentCount++; _traceIdentifier = EnlistmentTraceIdentifier.Empty; } internal InternalEnlistment( Enlistment enlistment, IEnlistmentNotification twoPhaseNotifications, InternalTransaction transaction, Transaction atomicTransaction) { _enlistment = enlistment; _twoPhaseNotifications = twoPhaseNotifications; _transaction = transaction; _atomicTransaction = atomicTransaction; } internal EnlistmentState State { get { return _twoPhaseState; } set { _twoPhaseState = value; } } internal Enlistment Enlistment => _enlistment; internal PreparingEnlistment PreparingEnlistment { get { if (_preparingEnlistment == null) { // If there is a race here one of the objects would simply be garbage collected. _preparingEnlistment = new PreparingEnlistment(this); } return _preparingEnlistment; } } internal SinglePhaseEnlistment SinglePhaseEnlistment { get { if (_singlePhaseEnlistment == null) { // If there is a race here one of the objects would simply be garbage collected. _singlePhaseEnlistment = new SinglePhaseEnlistment(this); } return _singlePhaseEnlistment; } } internal InternalTransaction Transaction => _transaction; internal virtual object SyncRoot { get { Debug.Assert(_transaction != null, "this.transaction != null"); return _transaction; } } internal IEnlistmentNotification EnlistmentNotification => _twoPhaseNotifications; internal ISinglePhaseNotification SinglePhaseNotification => _singlePhaseNotifications; internal virtual IPromotableSinglePhaseNotification PromotableSinglePhaseNotification { get { Debug.Assert(false, "PromotableSinglePhaseNotification called for a non promotable enlistment."); throw new NotImplementedException(); } } internal IPromotedEnlistment PromotedEnlistment { get { return _promotedEnlistment; } set { _promotedEnlistment = value; } } internal EnlistmentTraceIdentifier EnlistmentTraceId { get { if (_traceIdentifier == EnlistmentTraceIdentifier.Empty) { lock (SyncRoot) { if (_traceIdentifier == EnlistmentTraceIdentifier.Empty) { EnlistmentTraceIdentifier temp; if (null != _atomicTransaction) { temp = new EnlistmentTraceIdentifier( Guid.Empty, _atomicTransaction.TransactionTraceId, _enlistmentId); } else { temp = new EnlistmentTraceIdentifier( Guid.Empty, new TransactionTraceIdentifier( InternalTransaction.InstanceIdentifier + Convert.ToString(Interlocked.Increment(ref InternalTransaction._nextHash), CultureInfo.InvariantCulture), 0), _enlistmentId); } Interlocked.MemoryBarrier(); _traceIdentifier = temp; } } } return _traceIdentifier; } } internal virtual void FinishEnlistment() { // Note another enlistment finished. Transaction._phase0Volatiles._preparedVolatileEnlistments++; CheckComplete(); } internal virtual void CheckComplete() { // Make certain we increment the right list. Debug.Assert(Transaction._phase0Volatiles._preparedVolatileEnlistments <= Transaction._phase0Volatiles._volatileEnlistmentCount + Transaction._phase0Volatiles._dependentClones); // Check to see if all of the volatile enlistments are done. if (Transaction._phase0Volatiles._preparedVolatileEnlistments == Transaction._phase0VolatileWaveCount + Transaction._phase0Volatiles._dependentClones) { Transaction.State.Phase0VolatilePrepareDone(Transaction); } } internal virtual Guid ResourceManagerIdentifier { get { Debug.Assert(false, "ResourceManagerIdentifier called for non durable enlistment"); throw new NotImplementedException(); } } void ISinglePhaseNotificationInternal.SinglePhaseCommit(IPromotedEnlistment singlePhaseEnlistment) { bool spcCommitted = false; _promotedEnlistment = singlePhaseEnlistment; try { _singlePhaseNotifications.SinglePhaseCommit(SinglePhaseEnlistment); spcCommitted = true; } finally { if (!spcCommitted) { SinglePhaseEnlistment.InDoubt(); } } } void IEnlistmentNotificationInternal.Prepare( IPromotedEnlistment preparingEnlistment ) { _promotedEnlistment = preparingEnlistment; _twoPhaseNotifications.Prepare(PreparingEnlistment); } void IEnlistmentNotificationInternal.Commit( IPromotedEnlistment enlistment ) { _promotedEnlistment = enlistment; _twoPhaseNotifications.Commit(Enlistment); } void IEnlistmentNotificationInternal.Rollback( IPromotedEnlistment enlistment ) { _promotedEnlistment = enlistment; _twoPhaseNotifications.Rollback(Enlistment); } void IEnlistmentNotificationInternal.InDoubt( IPromotedEnlistment enlistment ) { _promotedEnlistment = enlistment; _twoPhaseNotifications.InDoubt(Enlistment); } } internal class DurableInternalEnlistment : InternalEnlistment { // Resource Manager Identifier for this enlistment if it is durable internal Guid _resourceManagerIdentifier; internal DurableInternalEnlistment( Enlistment enlistment, Guid resourceManagerIdentifier, InternalTransaction transaction, IEnlistmentNotification twoPhaseNotifications, ISinglePhaseNotification singlePhaseNotifications, Transaction atomicTransaction) : base(enlistment, transaction, twoPhaseNotifications, singlePhaseNotifications, atomicTransaction) { _resourceManagerIdentifier = resourceManagerIdentifier; } protected DurableInternalEnlistment(Enlistment enlistment, IEnlistmentNotification twoPhaseNotifications) : base(enlistment, twoPhaseNotifications) { } internal override Guid ResourceManagerIdentifier => _resourceManagerIdentifier; } // // Since RecoveringInternalEnlistment does not have a transaction it must take // a separate object as its sync root. // internal class RecoveringInternalEnlistment : DurableInternalEnlistment { private object _syncRoot; internal RecoveringInternalEnlistment(Enlistment enlistment, IEnlistmentNotification twoPhaseNotifications, object syncRoot) : base(enlistment, twoPhaseNotifications) { _syncRoot = syncRoot; } internal override object SyncRoot => _syncRoot; } internal class PromotableInternalEnlistment : InternalEnlistment { // This class acts as the durable single phase enlistment for a // promotable single phase enlistment. private IPromotableSinglePhaseNotification _promotableNotificationInterface; internal PromotableInternalEnlistment( Enlistment enlistment, InternalTransaction transaction, IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Transaction atomicTransaction) : base(enlistment, transaction, atomicTransaction) { _promotableNotificationInterface = promotableSinglePhaseNotification; } internal override IPromotableSinglePhaseNotification PromotableSinglePhaseNotification => _promotableNotificationInterface; } // This class supports volatile enlistments // internal class Phase1VolatileEnlistment : InternalEnlistment { public Phase1VolatileEnlistment( Enlistment enlistment, InternalTransaction transaction, IEnlistmentNotification twoPhaseNotifications, ISinglePhaseNotification singlePhaseNotifications, Transaction atomicTransaction) : base(enlistment, transaction, twoPhaseNotifications, singlePhaseNotifications, atomicTransaction) { } internal override void FinishEnlistment() { // Note another enlistment finished. _transaction._phase1Volatiles._preparedVolatileEnlistments++; CheckComplete(); } internal override void CheckComplete() { // Make certain we increment the right list. Debug.Assert(_transaction._phase1Volatiles._preparedVolatileEnlistments <= _transaction._phase1Volatiles._volatileEnlistmentCount + _transaction._phase1Volatiles._dependentClones); // Check to see if all of the volatile enlistments are done. if (_transaction._phase1Volatiles._preparedVolatileEnlistments == _transaction._phase1Volatiles._volatileEnlistmentCount + _transaction._phase1Volatiles._dependentClones) { _transaction.State.Phase1VolatilePrepareDone(_transaction); } } } public class Enlistment { // Interface for communicating with the state machine. internal InternalEnlistment _internalEnlistment; internal Enlistment(InternalEnlistment internalEnlistment) { _internalEnlistment = internalEnlistment; } internal Enlistment( Guid resourceManagerIdentifier, InternalTransaction transaction, IEnlistmentNotification twoPhaseNotifications, ISinglePhaseNotification singlePhaseNotifications, Transaction atomicTransaction) { _internalEnlistment = new DurableInternalEnlistment( this, resourceManagerIdentifier, transaction, twoPhaseNotifications, singlePhaseNotifications, atomicTransaction ); } internal Enlistment( InternalTransaction transaction, IEnlistmentNotification twoPhaseNotifications, ISinglePhaseNotification singlePhaseNotifications, Transaction atomicTransaction, EnlistmentOptions enlistmentOptions) { if ((enlistmentOptions & EnlistmentOptions.EnlistDuringPrepareRequired) != 0) { _internalEnlistment = new InternalEnlistment( this, transaction, twoPhaseNotifications, singlePhaseNotifications, atomicTransaction ); } else { _internalEnlistment = new Phase1VolatileEnlistment( this, transaction, twoPhaseNotifications, singlePhaseNotifications, atomicTransaction ); } } // This constructor is for a promotable single phase enlistment. internal Enlistment( InternalTransaction transaction, IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Transaction atomicTransaction) { _internalEnlistment = new PromotableInternalEnlistment( this, transaction, promotableSinglePhaseNotification, atomicTransaction ); } internal Enlistment( IEnlistmentNotification twoPhaseNotifications, InternalTransaction transaction, Transaction atomicTransaction) { _internalEnlistment = new InternalEnlistment( this, twoPhaseNotifications, transaction, atomicTransaction ); } internal Enlistment(IEnlistmentNotification twoPhaseNotifications, object syncRoot) { _internalEnlistment = new RecoveringInternalEnlistment( this, twoPhaseNotifications, syncRoot ); } public void Done() { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceLtm, "Enlistment.Done"); EnlistmentCallbackPositiveTraceRecord.Trace(SR.TraceSourceLtm, _internalEnlistment.EnlistmentTraceId, EnlistmentCallback.Done ); } lock (_internalEnlistment.SyncRoot) { _internalEnlistment.State.EnlistmentDone(_internalEnlistment); } if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceLtm, "Enlistment.Done"); } } internal InternalEnlistment InternalEnlistment => _internalEnlistment; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using Utils; using DevExpress.Utils; using System.Data.SqlClient; namespace KabMan.Client { public partial class NewSwitch : DevExpress.XtraEditors.XtraForm { DatabaseLib data = new DatabaseLib(); private int id; private Home m; Common com; public NewSwitch(Home m, int id) { this.m = m; this.id = id; InitializeComponent(); } private void NewSwitch_Load(object sender, EventArgs e) { Common.FillLookup2(LookUpLocation, "Select * from tblLocation where RecDelete=0", "LocationName", "Id"); Common.FillLookup2(LookUpSan, "Select * from tblSan where RecDelete=0", "San", "Id"); Common.FillLookup2(LookUpSwitchType, "Select * from tblSwitchType where RecDelete=0", "Type", "Id"); Common.FillLookup2(LookUpSwitchModel, "Select * from tblSwitchModel where RecDelete=0", "Name", "Id"); Common.FillLookup2(LookUpBlechType, "select * from tblBlechType where RecDelete=0", "Name", "Id"); } private void LookUpSwitchModel_EditValueChanged(object sender, EventArgs e) { } private void simpleButton1_Click(object sender, EventArgs e) { DataSet ds; DatabaseLib data = new DatabaseLib(); SqlParameter[] prm1 = { data.MakeInParam("@LocationId", LookUpLocation.EditValue), data.MakeInParam("@RoomId", LookUpRoom.EditValue), data.MakeInParam("@SanId", LookUpSan.EditValue), data.MakeInParam("@SwType", LookUpSwitchType.Text), data.MakeInParam("@Name","SW" + LookUpLocation.GetColumnValue("LocationCoord") + LookUpSan.GetColumnValue("Value")) }; data.RunProc(SPROC.SWITCH_CHECK, prm1, out ds); data.Dispose(); if (ds.Tables[0].Rows[0]["retValue"].ToString() == "0") { try { SqlParameter[] prm = { data.MakeInParam("@Id1", id), data.MakeInParam("@LocationId1", LookUpLocation.EditValue), data.MakeInParam("@RoomId1", LookUpRoom.EditValue), data.MakeInParam("@SanId1", LookUpSan.EditValue), data.MakeInParam("@BlechId1", LookUpBlech.EditValue), data.MakeInParam("@TypeId1", LookUpSwitchType.EditValue), data.MakeInParam("@ModelId1", LookUpSwitchModel.EditValue), data.MakeInParam("@VTPortId1", LookUpVTPort.EditValue), data.MakeInParam("@SerialNo1", txtSerialNo.Text), data.MakeInParam("@IpNo1", txtIpNo.Text + "." + txtIPNO2.Text + "." + txtIPNO3.Text + "." + txtIPNO4.Text), data.MakeInParam("@ConnSwitchId1", ConnSwitchId), data.MakeInParam("@LcUrmStartNo", LookUpLcUrmStartNo.EditValue), data.MakeInParam("@CountLcUrm", Convert.ToInt32(txtCountLcUrm.Text)), data.MakeInParam("@LcUrmMeter", Convert.ToInt32(CBoxLcUrmMeter.Text)) }; data.RunProc("sp_insSwitch", prm); data.Dispose(); m.InitTree(); MessageBox.Show("Has been saved succesfully!"); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } Close(); } else { MessageBox.Show("The Switch is in the Database!"); } } int ConnSwitchId = 0; private void LookUpSwitchType_EditValueChanged(object sender, EventArgs e) { if (LookUpLocation.EditValue == null || LookUpRoom.EditValue == null) { MessageBox.Show("Please select Location and Room!"); } else { if (LookUpSwitchType.Text == "Edge") { layoutControlItem5.ContentVisible = true; Common.FillLookup2(LookUpCoreSwitch, "select * from tblSwitch where LocationId=" + LookUpLocation.EditValue + " and RoomId=" + LookUpRoom.EditValue + " and SanId=" + LookUpSan.EditValue + " and TypeId=1 and RecDelete=0", "SwName", "Id"); } } } private void LookUpLocation_EditValueChanged(object sender, EventArgs e) { Common.FillLookup2(LookUpRoom, "Select * from tblRoom where RecDelete=0 and LocationId=" + LookUpLocation.EditValue.ToString(), "RoomName", "Id"); } private void BtnCancel_Click(object sender, EventArgs e) { Close(); } private void LookUpCoreSwitch_EditValueChanged(object sender, EventArgs e) { ConnSwitchId = Convert.ToInt32(LookUpCoreSwitch.EditValue.ToString()); } private void BtnCreateVTPort_Click(object sender, EventArgs e) { if (XtraMessageBox.Show( "Are you sure you want to create New VT Port?", Text, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK) { try { SqlParameter[] prm = { data.MakeInParam("@LocationId", LookUpLocation.EditValue), data.MakeInParam("@RoomId", LookUpRoom.EditValue), data.MakeInParam("@SanId", LookUpSan.EditValue) }; data.RunProc(SPROC.VTPORT_INSERT, prm); data.Dispose(); MessageBox.Show("Has been created VT Port succesfully!"); Common.FillLookup2(LookUpVTPort, "select * from tblVTPort where RecDelete=0 and LocationId=" + LookUpLocation.EditValue + " and RoomId=" + LookUpRoom.EditValue + " and SanId=" + LookUpSan.EditValue, "Name", "Id"); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } private void BtnCreateBlech_Click(object sender, EventArgs e) { if (XtraMessageBox.Show( "Are you sure you want to create New Blech?", Text, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK) { try { SqlParameter[] prm = { data.MakeInParam("@LocationId", LookUpLocation.EditValue), data.MakeInParam("@RoomId", LookUpRoom.EditValue), data.MakeInParam("@SanId", LookUpSan.EditValue), data.MakeInParam("@TypeId", LookUpBlechType.EditValue), data.MakeInParam("@ObjectName", "Switch") }; data.RunProc(SPROC.BLECH_INSERT, prm); data.Dispose(); MessageBox.Show("Has been created Blech succesfully!"); Common.FillLookup2(LookUpBlech, "select * from tblBlech where ObjectId=3 and RecDelete=0 and LocationId=" + LookUpLocation.EditValue + " and RoomId=" + LookUpRoom.EditValue + " and SanId=" + LookUpSan.EditValue + " and TypeId=" + LookUpBlechType.EditValue, "Name", "Id"); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } private void LookUpSan_EditValueChanged(object sender, EventArgs e) { Common.FillLookup2(LookUpVTPort, "select * from tblVTPort where RecDelete=0 and LocationId=" + LookUpLocation.EditValue + " and RoomId=" + LookUpRoom.EditValue + " and SanId=" + LookUpSan.EditValue, "Name", "Id"); } private void LookUpBlechType_EditValueChanged(object sender, EventArgs e) { Common.FillLookup2(LookUpBlech, "select * from tblBlech where ObjectId=3 and RecDelete=0 and LocationId=" + LookUpLocation.EditValue + " and RoomId=" + LookUpRoom.EditValue + " and SanId=" + LookUpSan.EditValue + " and TypeId=" + LookUpBlechType.EditValue, "Name", "Id"); } private void CBoxLcUrmMeter_SelectedIndexChanged(object sender, EventArgs e) { Common.FillLookup2(LookUpLcUrmStartNo, "Select * from tblUrm where RecDelete=0 and Visible=0 and TypeId=1 and Meter=" + Convert.ToInt32(CBoxLcUrmMeter.Text), "No", "Id"); } } }
/* * Magix - A Web Application Framework for Humans * Copyright 2010 - 2014 - thomas@magixilluminate.com * Magix is licensed as MITx11, see enclosed License.txt File for Details. */ using System; using Magix.Core; using System.Globalization; using System.Text.RegularExpressions; namespace Magix.Core { /** * helper for checking statements, such as [if]/[if-else] and [while] */ public static class StatementHelper { /** * checks and expression to see if it evaluates as true */ public static bool CheckExpressions(Node ip, Node dp) { return RecursivelyCheckExpression(ip, ip, dp); } private static bool RecursivelyCheckExpression(Node where, Node ip, Node dp) { string expressionOperator = Expressions.GetExpressionValue<string>(where.Get<string>(), dp, ip, false); object objLhsVal; object objRhsVal; ExtractValues(where, ip, dp, expressionOperator, out objLhsVal, out objRhsVal); bool retVal = RunComparison(expressionOperator, objLhsVal, objRhsVal); if (retVal && where.Contains("and")) { foreach (Node idx in where) { if (idx.Name == "and") { retVal = RecursivelyCheckExpression(idx, ip, dp); if (!retVal) break; } } } if (!retVal && where.Contains("or")) { foreach (Node idx in where) { if (idx.Name == "or") { retVal = RecursivelyCheckExpression(idx, ip, dp); if (retVal) break; } } } return retVal; } private static void ExtractValues( Node where, Node ip, Node dp, string expressionOperator, out object objLhsVal, out object objRhsVal) { string lhsRawValue = where["lhs"].Get<string>(); if (where["lhs"].Count > 0) lhsRawValue = Expressions.FormatString(dp, ip, where["lhs"], lhsRawValue); string rhsRawValue = null; objLhsVal = null; objRhsVal = null; ChangeType(lhsRawValue, out objLhsVal, ip, dp); if (expressionOperator != "exist" && expressionOperator != "not-exist") { if (!where.Contains("rhs")) throw new ArgumentException("missing [rhs] node in expression"); rhsRawValue = where["rhs"].Get<string>(); if (where["rhs"].Count > 0) rhsRawValue = Expressions.FormatString(dp, ip, where["rhs"], rhsRawValue); ChangeType(rhsRawValue, out objRhsVal, ip, dp); } } private static void ChangeType( string stringValue, out object objectValue, Node ip, Node dp) { object objectValueOfExpression = Expressions.GetExpressionValue<object>(stringValue, dp, ip, false); if (!(objectValueOfExpression is string)) { objectValue = objectValueOfExpression; return; } string valueOfExpression = objectValueOfExpression as string; if (valueOfExpression == null) { objectValue = null; return; } // trying to convert the thing to integer int intResult; bool successfulConvertion = int.TryParse(valueOfExpression, out intResult); if (successfulConvertion) { objectValue = intResult; return; } // trying to convert the thing to decimal decimal decimalResult; successfulConvertion = decimal.TryParse( valueOfExpression, NumberStyles.Number, CultureInfo.InvariantCulture, out decimalResult); if (successfulConvertion) { objectValue = decimalResult; return; } // trying to convert the thing to DateTime DateTime dateResult; successfulConvertion = DateTime.TryParseExact( valueOfExpression, "yyyy.MM.dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateResult); if (successfulConvertion) { objectValue = dateResult; return; } // trying to convert the thing to bool bool boolResult; successfulConvertion = bool.TryParse(valueOfExpression, out boolResult); if (successfulConvertion) { objectValue = boolResult; return; } // Couldn't convert the freaking thing to anything ... objectValue = valueOfExpression; } private static bool RunComparison(string expressionOperator, object objLhsVal, object objRhsVal) { bool expressionIsTrue = false; switch (expressionOperator) { case "exist": expressionIsTrue = objLhsVal != null; break; case "not-exist": expressionIsTrue = objLhsVal == null; break; case "equals": expressionIsTrue = CompareValues(objLhsVal, objRhsVal) == 0; break; case "not-equals": expressionIsTrue = CompareValues(objLhsVal, objRhsVal) != 0; break; case "more-than": expressionIsTrue = CompareValues(objLhsVal, objRhsVal) == 1; break; case "less-than": expressionIsTrue = CompareValues(objLhsVal, objRhsVal) == -1; break; case "more-than-equals": expressionIsTrue = CompareValues(objLhsVal, objRhsVal) != -1; break; case "less-than-equals": expressionIsTrue = CompareValues(objLhsVal, objRhsVal) != 1; break; case "regex-match": { if (objLhsVal == null) throw new ArgumentNullException("[lhs]"); string regexExpr = objLhsVal.ToString(); if (objRhsVal == null) expressionIsTrue = false; else { string matchingValue = objRhsVal.ToString(); Regex regex = new Regex(regexExpr, RegexOptions.CultureInvariant); expressionIsTrue = regex.IsMatch(matchingValue); } } break; case "not-regex-match": { if (objLhsVal == null) throw new ArgumentNullException("[lhs]"); string regexExpr = objLhsVal.ToString(); if (objRhsVal == null) expressionIsTrue = true; else { string matchingValue = objRhsVal.ToString(); Regex regex = new Regex(regexExpr, RegexOptions.CultureInvariant); expressionIsTrue = !regex.IsMatch(matchingValue); } } break; default: throw new ArgumentException("tried to pass in a comparison operator which doesn't exist, operator was; " + expressionOperator); } return expressionIsTrue; } private static int CompareValues(object objLhsValue, object objRhsValue) { if (objLhsValue != null && objRhsValue == null) return 1; if (objLhsValue == null && objRhsValue != null) return -1; if (objLhsValue == null && objRhsValue == null) return 0; switch (objLhsValue.GetType().ToString()) { case "System.Int32": if (objRhsValue.GetType() == typeof(int)) return ((int)objLhsValue).CompareTo(objRhsValue); int tmpVal; if (!int.TryParse(objRhsValue.ToString(), out tmpVal)) return (objLhsValue.ToString()).CompareTo(objRhsValue.ToString()); return ((int)objLhsValue).CompareTo(tmpVal); case "System.Decimal": if (objRhsValue.GetType() == typeof(decimal)) return ((decimal)objLhsValue).CompareTo(objRhsValue); decimal tmpVal2; if (!decimal.TryParse(objRhsValue.ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out tmpVal2)) return (objLhsValue.ToString()).CompareTo(objRhsValue.ToString()); return ((decimal)objLhsValue).CompareTo(tmpVal2); case "System.DateTime": if (objRhsValue.GetType() == typeof(DateTime)) return ((DateTime)objLhsValue).CompareTo(objRhsValue); DateTime tmpVal3; if (!DateTime.TryParseExact(objRhsValue.ToString(), "yyyy.MM.dd hh:MM:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out tmpVal3)) return (objLhsValue.ToString()).CompareTo(objRhsValue.ToString()); return ((DateTime)objLhsValue).CompareTo(tmpVal3); case "System.Boolean": if (objRhsValue.GetType() == typeof(bool)) return ((bool)objLhsValue).CompareTo(objRhsValue); bool tmpVal4; if (!bool.TryParse(objRhsValue.ToString(), out tmpVal4)) return (objLhsValue.ToString()).CompareTo(objRhsValue.ToString()); return ((bool)objLhsValue).CompareTo(tmpVal4); case "Magix.Core.Node": return ((Node)objLhsValue).Equals(objRhsValue) ? 0 : -1; default: return (objLhsValue.ToString()).CompareTo(objRhsValue.ToString()); } } } }
/*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.Project { /// <summary> /// Provides support for single file generator. /// </summary> internal class SingleFileGenerator : ISingleFileGenerator, IVsGeneratorProgress { #region fields private bool gettingCheckoutStatus; private bool runningGenerator; private ProjectNode projectMgr; #endregion #region ctors /// <summary> /// Overloadde ctor. /// </summary> /// <param name="ProjectNode">The associated project</param> internal SingleFileGenerator(ProjectNode projectMgr) { this.projectMgr = projectMgr; } #endregion #region IVsGeneratorProgress Members public virtual int GeneratorError(int warning, uint level, string err, uint line, uint col) { return VSConstants.E_NOTIMPL; } public virtual int Progress(uint complete, uint total) { return VSConstants.E_NOTIMPL; } #endregion #region ISingleFileGenerator /// <summary> /// Runs the generator on the current project item. /// </summary> /// <param name="document"></param> /// <returns></returns> public virtual void RunGenerator(string document) { // Go run the generator on that node, but only if the file is dirty // in the running document table. Otherwise there is no need to rerun // the generator because if the original document is not dirty then // the generated output should be already up to date. uint itemid = VSConstants.VSITEMID_NIL; IVsHierarchy hier = (IVsHierarchy)this.projectMgr; if(document != null && hier != null && ErrorHandler.Succeeded(hier.ParseCanonicalName((string)document, out itemid))) { IVsHierarchy rdtHier; IVsPersistDocData perDocData; uint cookie; if(this.VerifyFileDirtyInRdt((string)document, out rdtHier, out perDocData, out cookie)) { // Run the generator on the indicated document FileNode node = (FileNode)this.projectMgr.NodeFromItemId(itemid); this.InvokeGenerator(node); } } } #endregion #region virtual methods /// <summary> /// Invokes the specified generator /// </summary> /// <param name="fileNode">The node on which to invoke the generator.</param> protected internal virtual void InvokeGenerator(FileNode fileNode) { if(fileNode == null) { throw new ArgumentNullException("fileNode"); } SingleFileGeneratorNodeProperties nodeproperties = fileNode.NodeProperties as SingleFileGeneratorNodeProperties; if(nodeproperties == null) { throw new InvalidOperationException(); } string customToolProgID = nodeproperties.CustomTool; if(string.IsNullOrEmpty(customToolProgID)) { return; } string customToolNamespace = nodeproperties.CustomToolNamespace; try { if(!this.runningGenerator) { //Get the buffer contents for the current node string moniker = fileNode.GetMkDocument(); this.runningGenerator = true; //Get the generator IVsSingleFileGenerator generator; int generateDesignTimeSource; int generateSharedDesignTimeSource; int generateTempPE; SingleFileGeneratorFactory factory = new SingleFileGeneratorFactory(this.projectMgr.ProjectGuid, this.projectMgr.Site); ErrorHandler.ThrowOnFailure(factory.CreateGeneratorInstance(customToolProgID, out generateDesignTimeSource, out generateSharedDesignTimeSource, out generateTempPE, out generator)); //Check to see if the generator supports siting IObjectWithSite objWithSite = generator as IObjectWithSite; if(objWithSite != null) { objWithSite.SetSite(fileNode.OleServiceProvider); } //Determine the namespace if(string.IsNullOrEmpty(customToolNamespace)) { customToolNamespace = this.ComputeNamespace(moniker); } //Run the generator IntPtr[] output = new IntPtr[1]; output[0] = IntPtr.Zero; uint outPutSize; string extension; ErrorHandler.ThrowOnFailure(generator.DefaultExtension(out extension)); //Find if any dependent node exists string dependentNodeName = Path.GetFileNameWithoutExtension(fileNode.FileName) + extension; HierarchyNode dependentNode = fileNode.FirstChild; while(dependentNode != null) { if(string.Compare(dependentNode.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon), fileNode.FileName, StringComparison.OrdinalIgnoreCase) == 0) { dependentNodeName = ((FileNode)dependentNode).FileName; break; } dependentNode = dependentNode.NextSibling; } //If you found a dependent node. if(dependentNode != null) { //Then check out the node and dependent node from SCC if(!this.CanEditFile(dependentNode.GetMkDocument())) { throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED); } } else //It is a new node to be added to the project { // Check out the project file if necessary. if(!this.projectMgr.QueryEditProjectFile(false)) { throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED); } } IVsTextStream stream; string inputFileContents = this.GetBufferContents(moniker, out stream); ErrorHandler.ThrowOnFailure(generator.Generate(moniker, inputFileContents, customToolNamespace, output, out outPutSize, this)); byte[] data = new byte[outPutSize]; if(output[0] != IntPtr.Zero) { Marshal.Copy(output[0], data, 0, (int)outPutSize); Marshal.FreeCoTaskMem(output[0]); } //Todo - Create a file and add it to the Project this.UpdateGeneratedCodeFile(fileNode, data, (int)outPutSize, dependentNodeName); } } finally { this.runningGenerator = false; } } /// <summary> /// Computes the names space based on the folder for the ProjectItem. It just replaces DirectorySeparatorCharacter /// with "." for the directory in which the file is located. /// </summary> /// <returns>Returns the computed name space</returns> protected virtual string ComputeNamespace(string projectItemPath) { if(String.IsNullOrEmpty(projectItemPath)) { throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "projectItemPath"); } string nspace = ""; string filePath = Path.GetDirectoryName(projectItemPath); string[] toks = filePath.Split(new char[] { ':', '\\' }); foreach(string tok in toks) { if(!String.IsNullOrEmpty(tok)) { string temp = tok.Replace(" ", ""); nspace += (temp + "."); } } nspace = nspace.Remove(nspace.LastIndexOf(".", StringComparison.Ordinal), 1); return nspace; } /// <summary> /// This is called after the single file generator has been invoked to create or update the code file. /// </summary> /// <param name="fileNode">The node associated to the generator</param> /// <param name="data">data to update the file with</param> /// <param name="size">size of the data</param> /// <param name="fileName">Name of the file to update or create</param> /// <returns>full path of the file</returns> protected virtual string UpdateGeneratedCodeFile(FileNode fileNode, byte[] data, int size, string fileName) { string filePath = Path.Combine(Path.GetDirectoryName(fileNode.GetMkDocument()), fileName); IVsRunningDocumentTable rdt = this.projectMgr.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; // (kberes) Shouldn't this be an InvalidOperationException instead with some not to annoying errormessage to the user? if(rdt == null) { ErrorHandler.ThrowOnFailure(VSConstants.E_FAIL); } IVsHierarchy hier; uint cookie; uint itemid; IntPtr docData = IntPtr.Zero; ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)(_VSRDTFLAGS.RDT_NoLock), filePath, out hier, out itemid, out docData, out cookie)); if(docData != IntPtr.Zero) { Marshal.Release(docData); IVsTextStream srpStream = null; if(srpStream != null) { int oldLen = 0; int hr = srpStream.GetSize(out oldLen); if(ErrorHandler.Succeeded(hr)) { IntPtr dest = IntPtr.Zero; try { dest = Marshal.AllocCoTaskMem(data.Length); Marshal.Copy(data, 0, dest, data.Length); ErrorHandler.ThrowOnFailure(srpStream.ReplaceStream(0, oldLen, dest, size / 2)); } finally { if(dest != IntPtr.Zero) { Marshal.Release(dest); } } } } } else { using(FileStream generatedFileStream = File.Open(filePath, FileMode.OpenOrCreate)) { generatedFileStream.Write(data, 0, size); } EnvDTE.ProjectItem projectItem = fileNode.GetAutomationObject() as EnvDTE.ProjectItem; if(projectItem != null && (this.projectMgr.FindChild(fileNode.FileName) == null)) { projectItem.ProjectItems.AddFromFile(filePath); } } return filePath; } #endregion #region helpers /// <summary> /// Returns the buffer contents for a moniker. /// </summary> /// <returns>Buffer contents</returns> private string GetBufferContents(string fileName, out IVsTextStream srpStream) { Guid CLSID_VsTextBuffer = new Guid("{8E7B96A8-E33D-11d0-A6D5-00C04FB67F6A}"); string bufferContents = ""; srpStream = null; IVsRunningDocumentTable rdt = this.projectMgr.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if(rdt != null) { IVsHierarchy hier; IVsPersistDocData persistDocData; uint itemid, cookie; bool docInRdt = true; IntPtr docData = IntPtr.Zero; int hr = NativeMethods.E_FAIL; try { //Getting a read lock on the document. Must be released later. hr = rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, fileName, out hier, out itemid, out docData, out cookie); if(ErrorHandler.Failed(hr) || docData == IntPtr.Zero) { Guid iid = VSConstants.IID_IUnknown; cookie = 0; docInRdt = false; ILocalRegistry localReg = this.projectMgr.GetService(typeof(SLocalRegistry)) as ILocalRegistry; ErrorHandler.ThrowOnFailure(localReg.CreateInstance(CLSID_VsTextBuffer, null, ref iid, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out docData)); } persistDocData = Marshal.GetObjectForIUnknown(docData) as IVsPersistDocData; } finally { if(docData != IntPtr.Zero) { Marshal.Release(docData); } } //Try to get the Text lines IVsTextLines srpTextLines = persistDocData as IVsTextLines; if(srpTextLines == null) { // Try getting a text buffer provider first IVsTextBufferProvider srpTextBufferProvider = persistDocData as IVsTextBufferProvider; if(srpTextBufferProvider != null) { hr = srpTextBufferProvider.GetTextBuffer(out srpTextLines); } } if(ErrorHandler.Succeeded(hr)) { srpStream = srpTextLines as IVsTextStream; if(srpStream != null) { // QI for IVsBatchUpdate and call FlushPendingUpdates if they support it IVsBatchUpdate srpBatchUpdate = srpStream as IVsBatchUpdate; if(srpBatchUpdate != null) ErrorHandler.ThrowOnFailure(srpBatchUpdate.FlushPendingUpdates(0)); int lBufferSize = 0; hr = srpStream.GetSize(out lBufferSize); if(ErrorHandler.Succeeded(hr)) { IntPtr dest = IntPtr.Zero; try { // Note that GetStream returns Unicode to us so we don't need to do any conversions dest = Marshal.AllocCoTaskMem((lBufferSize + 1) * 2); ErrorHandler.ThrowOnFailure(srpStream.GetStream(0, lBufferSize, dest)); //Get the contents bufferContents = Marshal.PtrToStringUni(dest); } finally { if(dest != IntPtr.Zero) Marshal.FreeCoTaskMem(dest); } } } } // Unlock the document in the RDT if necessary if(docInRdt && rdt != null) { ErrorHandler.ThrowOnFailure(rdt.UnlockDocument((uint)(_VSRDTFLAGS.RDT_ReadLock | _VSRDTFLAGS.RDT_Unlock_NoSave), cookie)); } if(ErrorHandler.Failed(hr)) { // If this failed then it's probably not a text file. In that case, // we just read the file as a binary bufferContents = File.ReadAllText(fileName); } } return bufferContents; } /// <summary> /// Returns TRUE if open and dirty. Note that documents can be open without a /// window frame so be careful. Returns the DocData and doc cookie if requested /// </summary> /// <param name="document">document path</param> /// <param name="pHier">hierarchy</param> /// <param name="ppDocData">doc data associated with document</param> /// <param name="cookie">item cookie</param> /// <returns>True if FIle is dirty</returns> private bool VerifyFileDirtyInRdt(string document, out IVsHierarchy pHier, out IVsPersistDocData ppDocData, out uint cookie) { int ret = 0; pHier = null; ppDocData = null; cookie = 0; IVsRunningDocumentTable rdt = this.projectMgr.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable; if(rdt != null) { IntPtr docData; uint dwCookie = 0; IVsHierarchy srpHier; uint itemid = VSConstants.VSITEMID_NIL; ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, document, out srpHier, out itemid, out docData, out dwCookie)); IVsPersistHierarchyItem srpIVsPersistHierarchyItem = srpHier as IVsPersistHierarchyItem; if(srpIVsPersistHierarchyItem != null) { // Found in the RDT. See if it is dirty try { ErrorHandler.ThrowOnFailure(srpIVsPersistHierarchyItem.IsItemDirty(itemid, docData, out ret)); cookie = dwCookie; ppDocData = Marshal.GetObjectForIUnknown(docData) as IVsPersistDocData; } finally { if(docData != IntPtr.Zero) { Marshal.Release(docData); } pHier = srpHier; } } } return (ret == 1); } #endregion #region QueryEditQuerySave helpers /// <summary> /// This function asks to the QueryEditQuerySave service if it is possible to /// edit the file. /// </summary> private bool CanEditFile(string documentMoniker) { Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "\t**** CanEditFile called ****")); // Check the status of the recursion guard if(this.gettingCheckoutStatus) { return false; } try { // Set the recursion guard this.gettingCheckoutStatus = true; // Get the QueryEditQuerySave service IVsQueryEditQuerySave2 queryEditQuerySave = (IVsQueryEditQuerySave2)this.projectMgr.GetService(typeof(SVsQueryEditQuerySave)); // Now call the QueryEdit method to find the edit status of this file string[] documents = { documentMoniker }; uint result; uint outFlags; // Note that this function can popup a dialog to ask the user to checkout the file. // When this dialog is visible, it is possible to receive other request to change // the file and this is the reason for the recursion guard. int hr = queryEditQuerySave.QueryEditFiles( 0, // Flags 1, // Number of elements in the array documents, // Files to edit null, // Input flags null, // Input array of VSQEQS_FILE_ATTRIBUTE_DATA out result, // result of the checkout out outFlags // Additional flags ); if(ErrorHandler.Succeeded(hr) && (result == (uint)tagVSQueryEditResult.QER_EditOK)) { // In this case (and only in this case) we can return true from this function. return true; } } finally { this.gettingCheckoutStatus = false; } return false; } #endregion } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Serverless.V1.Service { /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Retrieve a list of all Functions. /// </summary> public class ReadFunctionOptions : ReadOptions<FunctionResource> { /// <summary> /// The SID of the Service to read the Function resources from /// </summary> public string PathServiceSid { get; } /// <summary> /// Construct a new ReadFunctionOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Service to read the Function resources from </param> public ReadFunctionOptions(string pathServiceSid) { PathServiceSid = pathServiceSid; } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Retrieve a specific Function resource. /// </summary> public class FetchFunctionOptions : IOptions<FunctionResource> { /// <summary> /// The SID of the Service to fetch the Function resource from /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the Function resource to fetch /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchFunctionOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Service to fetch the Function resource from </param> /// <param name="pathSid"> The SID of the Function resource to fetch </param> public FetchFunctionOptions(string pathServiceSid, string pathSid) { PathServiceSid = pathServiceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Delete a Function resource. /// </summary> public class DeleteFunctionOptions : IOptions<FunctionResource> { /// <summary> /// The SID of the Service to delete the Function resource from /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the Function resource to delete /// </summary> public string PathSid { get; } /// <summary> /// Construct a new DeleteFunctionOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Service to delete the Function resource from </param> /// <param name="pathSid"> The SID of the Function resource to delete </param> public DeleteFunctionOptions(string pathServiceSid, string pathSid) { PathServiceSid = pathServiceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Create a new Function resource. /// </summary> public class CreateFunctionOptions : IOptions<FunctionResource> { /// <summary> /// The SID of the Service to create the Function resource under /// </summary> public string PathServiceSid { get; } /// <summary> /// A string to describe the Function resource /// </summary> public string FriendlyName { get; } /// <summary> /// Construct a new CreateFunctionOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Service to create the Function resource under </param> /// <param name="friendlyName"> A string to describe the Function resource </param> public CreateFunctionOptions(string pathServiceSid, string friendlyName) { PathServiceSid = pathServiceSid; FriendlyName = friendlyName; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } return p; } } /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Update a specific Function resource. /// </summary> public class UpdateFunctionOptions : IOptions<FunctionResource> { /// <summary> /// The SID of the Service to update the Function resource from /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the Function resource to update /// </summary> public string PathSid { get; } /// <summary> /// A string to describe the Function resource /// </summary> public string FriendlyName { get; } /// <summary> /// Construct a new UpdateFunctionOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Service to update the Function resource from </param> /// <param name="pathSid"> The SID of the Function resource to update </param> /// <param name="friendlyName"> A string to describe the Function resource </param> public UpdateFunctionOptions(string pathServiceSid, string pathSid, string friendlyName) { PathServiceSid = pathServiceSid; PathSid = pathSid; FriendlyName = friendlyName; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } return p; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.AppService.Fluent { using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.AppService.Fluent.Models; using Microsoft.Azure.Management.AppService.Fluent.HostNameBinding.Definition; using Microsoft.Azure.Management.AppService.Fluent.HostNameBinding.UpdateDefinition; using Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition; using Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Update; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Update; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions; using Microsoft.Rest; using System.Collections.Generic; internal partial class HostNameBindingImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> { /// <summary> /// Binds to a domain purchased from Azure. /// </summary> /// <param name="domain">The domain purchased from Azure.</param> /// <return>The next stage of the definition.</return> HostNameBinding.Definition.IWithSubDomain<WebAppBase.Definition.IWithCreate<FluentT>> HostNameBinding.Definition.IWithDomain<WebAppBase.Definition.IWithCreate<FluentT>>.WithAzureManagedDomain(IAppServiceDomain domain) { return this.WithAzureManagedDomain(domain); } /// <summary> /// Binds to a 3rd party domain. /// </summary> /// <param name="domain">The 3rd party domain name.</param> /// <return>The next stage of the definition.</return> HostNameBinding.Definition.IWithSubDomain<WebAppBase.Definition.IWithCreate<FluentT>> HostNameBinding.Definition.IWithDomain<WebAppBase.Definition.IWithCreate<FluentT>>.WithThirdPartyDomain(string domain) { return this.WithThirdPartyDomain(domain); } /// <summary> /// Binds to a domain purchased from Azure. /// </summary> /// <param name="domain">The domain purchased from Azure.</param> /// <return>The next stage of the definition.</return> HostNameBinding.UpdateDefinition.IWithSubDomain<WebAppBase.Update.IUpdate<FluentT>> HostNameBinding.UpdateDefinition.IWithDomain<WebAppBase.Update.IUpdate<FluentT>>.WithAzureManagedDomain(IAppServiceDomain domain) { return this.WithAzureManagedDomain(domain); } /// <summary> /// Binds to a 3rd party domain. /// </summary> /// <param name="domain">The 3rd party domain name.</param> /// <return>The next stage of the definition.</return> HostNameBinding.UpdateDefinition.IWithSubDomain<WebAppBase.Update.IUpdate<FluentT>> HostNameBinding.UpdateDefinition.IWithDomain<WebAppBase.Update.IUpdate<FluentT>>.WithThirdPartyDomain(string domain) { return this.WithThirdPartyDomain(domain); } /// <summary> /// Gets the resource ID string. /// </summary> string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasId.Id { get { return this.Id(); } } /// <summary> /// Gets the name of the resource. /// </summary> string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasName.Name { get { return this.Name(); } } /// <summary> /// Specifies the DNS record type. /// </summary> /// <param name="hostNameDnsRecordType">The DNS record type.</param> /// <return>The next stage of the definition.</return> HostNameBinding.Definition.IWithAttach<WebAppBase.Definition.IWithCreate<FluentT>> HostNameBinding.Definition.IWithHostNameDnsRecordType<WebAppBase.Definition.IWithCreate<FluentT>>.WithDnsRecordType(CustomHostNameDnsRecordType hostNameDnsRecordType) { return this.WithDnsRecordType(hostNameDnsRecordType); } /// <summary> /// Specifies the DNS record type. /// </summary> /// <param name="hostNameDnsRecordType">The DNS record type.</param> /// <return>The next stage of the definition.</return> HostNameBinding.UpdateDefinition.IWithAttach<WebAppBase.Update.IUpdate<FluentT>> HostNameBinding.UpdateDefinition.IWithHostNameDnsRecordType<WebAppBase.Update.IUpdate<FluentT>>.WithDnsRecordType(CustomHostNameDnsRecordType hostNameDnsRecordType) { return this.WithDnsRecordType(hostNameDnsRecordType); } /// <summary> /// Gets the hostname to bind to. /// </summary> string Microsoft.Azure.Management.AppService.Fluent.IHostNameBinding.HostName { get { return this.HostName(); } } /// <summary> /// Gets the fully qualified ARM domain resource URI. /// </summary> string Microsoft.Azure.Management.AppService.Fluent.IHostNameBinding.DomainId { get { return this.DomainId(); } } /// <summary> /// Gets Azure resource type. /// </summary> Models.AzureResourceType Microsoft.Azure.Management.AppService.Fluent.IHostNameBinding.AzureResourceType { get { return this.AzureResourceType(); } } /// <summary> /// Gets the host name type. /// </summary> Models.HostNameType Microsoft.Azure.Management.AppService.Fluent.IHostNameBinding.HostNameType { get { return this.HostNameType(); } } /// <summary> /// Gets Azure resource name to bind to. /// </summary> string Microsoft.Azure.Management.AppService.Fluent.IHostNameBinding.AzureResourceName { get { return this.AzureResourceName(); } } /// <summary> /// Gets the web app name. /// </summary> string Microsoft.Azure.Management.AppService.Fluent.IHostNameBinding.WebAppName { get { return this.WebAppName(); } } /// <summary> /// Gets custom DNS record type. /// </summary> Models.CustomHostNameDnsRecordType Microsoft.Azure.Management.AppService.Fluent.IHostNameBinding.DnsRecordType { get { return this.DnsRecordType(); } } /// <summary> /// Attaches the child definition to the parent resource update. /// </summary> /// <return>The next stage of the parent definition.</return> WebAppBase.Update.IUpdate<FluentT> Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Update.IInUpdate<WebAppBase.Update.IUpdate<FluentT>>.Attach() { return this.Attach(); } /// <summary> /// Execute the create request. /// </summary> /// <return>The create resource.</return> Microsoft.Azure.Management.AppService.Fluent.IHostNameBinding Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.ICreatable<Microsoft.Azure.Management.AppService.Fluent.IHostNameBinding>.Create() { return this.Create(); } /// <summary> /// Puts the request into the queue and allow the HTTP client to execute /// it when system resources are available. /// </summary> /// <return>An observable of the request.</return> async Task<IHostNameBinding> Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.ICreatable<Microsoft.Azure.Management.AppService.Fluent.IHostNameBinding>.CreateAsync(CancellationToken cancellationToken, bool multiThreaded) { return await this.CreateAsync(cancellationToken); } /// <summary> /// Attaches the child definition to the parent resource definiton. /// </summary> /// <return>The next stage of the parent definition.</return> WebAppBase.Definition.IWithCreate<FluentT> Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition.IInDefinition<WebAppBase.Definition.IWithCreate<FluentT>>.Attach() { return this.Attach(); } /// <summary> /// Gets the name of the region the resource is in. /// </summary> string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IResource.RegionName { get { return this.RegionName(); } } /// <summary> /// Gets the tags for the resource. /// </summary> System.Collections.Generic.IReadOnlyDictionary<string,string> Microsoft.Azure.Management.ResourceManager.Fluent.Core.IResource.Tags { get { return this.Tags(); } } /// <summary> /// Gets the region the resource is in. /// </summary> Microsoft.Azure.Management.ResourceManager.Fluent.Core.Region Microsoft.Azure.Management.ResourceManager.Fluent.Core.IResource.Region { get { return this.Region(); } } /// <summary> /// Gets the type of the resource. /// </summary> string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IResource.Type { get { return this.Type(); } } /// <summary> /// Specifies the sub-domain to bind to. /// </summary> /// <param name="subDomain">The sub-domain name excluding the top level domain, e.g., "www".</param> /// <return>The next stage of the definition.</return> HostNameBinding.Definition.IWithHostNameDnsRecordType<WebAppBase.Definition.IWithCreate<FluentT>> HostNameBinding.Definition.IWithSubDomain<WebAppBase.Definition.IWithCreate<FluentT>>.WithSubDomain(string subDomain) { return this.WithSubDomain(subDomain); } /// <summary> /// Specifies the sub-domain to bind to. /// </summary> /// <param name="subDomain">The sub-domain name excluding the top level domain, e.g., "www".</param> /// <return>The next stage of the definition.</return> HostNameBinding.UpdateDefinition.IWithHostNameDnsRecordType<WebAppBase.Update.IUpdate<FluentT>> HostNameBinding.UpdateDefinition.IWithSubDomain<WebAppBase.Update.IUpdate<FluentT>>.WithSubDomain(string subDomain) { return this.WithSubDomain(subDomain); } } }
// 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.Xml; using System.IO; using System.Collections.Generic; namespace System.ServiceModel.Channels { public abstract class MessageBuffer : IDisposable { public abstract int BufferSize { get; } void IDisposable.Dispose() { Close(); } public abstract void Close(); public virtual void WriteMessage(Stream stream) { if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(stream))); } Message message = CreateMessage(); using (message) { XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(stream, XD.Dictionary, null, false); using (writer) { message.WriteMessage(writer); } } } public virtual string MessageContentType { get { return FramingEncodingString.Binary; } } public abstract Message CreateMessage(); internal Exception CreateBufferDisposedException() { return new ObjectDisposedException("", SR.MessageBufferIsClosed); } } internal class DefaultMessageBuffer : MessageBuffer { private XmlBuffer _msgBuffer; private KeyValuePair<string, object>[] _properties; private bool[] _understoodHeaders; private bool _closed; private MessageVersion _version; private Uri _to; private string _action; private bool _isNullMessage; public DefaultMessageBuffer(Message message, XmlBuffer msgBuffer) { _msgBuffer = msgBuffer; _version = message.Version; _isNullMessage = message is NullMessage; _properties = new KeyValuePair<string, object>[message.Properties.Count]; ((ICollection<KeyValuePair<string, object>>)message.Properties).CopyTo(_properties, 0); _understoodHeaders = new bool[message.Headers.Count]; for (int i = 0; i < _understoodHeaders.Length; ++i) { _understoodHeaders[i] = message.Headers.IsUnderstood(i); } if (_version == MessageVersion.None) { _to = message.Headers.To; _action = message.Headers.Action; } } private object ThisLock { get { return _msgBuffer; } } public override int BufferSize { get { return _msgBuffer.BufferSize; } } public override void Close() { lock (ThisLock) { if (_closed) { return; } _closed = true; for (int i = 0; i < _properties.Length; i++) { IDisposable disposable = _properties[i].Value as IDisposable; if (disposable != null) { disposable.Dispose(); } } } } public override Message CreateMessage() { if (_closed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateBufferDisposedException()); } Message msg; if (_isNullMessage) { msg = new NullMessage(); } else { msg = Message.CreateMessage(_msgBuffer.GetReader(0), int.MaxValue, _version); } lock (ThisLock) { msg.Properties.CopyProperties(_properties); } for (int i = 0; i < _understoodHeaders.Length; ++i) { if (_understoodHeaders[i]) { msg.Headers.AddUnderstood(i); } } if (_to != null) { msg.Headers.To = _to; } if (_action != null) { msg.Headers.Action = _action; } return msg; } } internal class BufferedMessageBuffer : MessageBuffer { private IBufferedMessageData _messageData; private KeyValuePair<string, object>[] _properties; private bool _closed; private bool[] _understoodHeaders; private bool _understoodHeadersModified; public BufferedMessageBuffer(IBufferedMessageData messageData, KeyValuePair<string, object>[] properties, bool[] understoodHeaders, bool understoodHeadersModified) { _messageData = messageData; _properties = properties; _understoodHeaders = understoodHeaders; _understoodHeadersModified = understoodHeadersModified; messageData.Open(); } public override int BufferSize { get { lock (ThisLock) { if (_closed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateBufferDisposedException()); } return _messageData.Buffer.Count; } } } public override void WriteMessage(Stream stream) { if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(stream))); } lock (ThisLock) { if (_closed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateBufferDisposedException()); } ArraySegment<byte> buffer = _messageData.Buffer; stream.Write(buffer.Array, buffer.Offset, buffer.Count); } } public override string MessageContentType { get { lock (ThisLock) { if (_closed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateBufferDisposedException()); } return _messageData.MessageEncoder.ContentType; } } } private object ThisLock { get; } = new object(); public override void Close() { lock (ThisLock) { if (!_closed) { _closed = true; _messageData.Close(); _messageData = null; } } } public override Message CreateMessage() { lock (ThisLock) { if (_closed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateBufferDisposedException()); } RecycledMessageState recycledMessageState = _messageData.TakeMessageState(); if (recycledMessageState == null) { recycledMessageState = new RecycledMessageState(); } BufferedMessage bufferedMessage = new BufferedMessage(_messageData, recycledMessageState, _understoodHeaders, _understoodHeadersModified); bufferedMessage.Properties.CopyProperties(_properties); _messageData.Open(); return bufferedMessage; } } } internal class BodyWriterMessageBuffer : MessageBuffer { private object _thisLock = new object(); public BodyWriterMessageBuffer(MessageHeaders headers, KeyValuePair<string, object>[] properties, BodyWriter bodyWriter) { BodyWriter = bodyWriter; Headers = new MessageHeaders(headers); Properties = properties; } protected object ThisLock { get { return _thisLock; } } public override int BufferSize { get { return 0; } } public override void Close() { lock (ThisLock) { if (!Closed) { Closed = true; BodyWriter = null; Headers = null; Properties = null; } } } public override Message CreateMessage() { lock (ThisLock) { if (Closed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateBufferDisposedException()); } return new BodyWriterMessage(Headers, Properties, BodyWriter); } } protected BodyWriter BodyWriter { get; private set; } protected MessageHeaders Headers { get; private set; } protected KeyValuePair<string, object>[] Properties { get; private set; } protected bool Closed { get; private set; } } }
namespace Microsoft.Protocols.TestSuites.MS_ASAIRS { using System.Xml; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestSuites.Common.Response; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; using DataStructures = Microsoft.Protocols.TestSuites.Common.DataStructures; using Request = Microsoft.Protocols.TestSuites.Common.Request; /// <summary> /// This scenario is designed to test the BodyPartPreference element and BodyPart element in the AirSyncBase namespace, which is used by the Sync command, Search command and ItemOperations command to identify the data sent by and returned to client. /// </summary> [TestClass] public class S01_BodyPartPreference : TestSuiteBase { #region Class initialize and cleanup /// <summary> /// Initialize the class. /// </summary> /// <param name="testContext">VSTS test context.</param> [ClassInitialize] public static void ClassInitialize(TestContext testContext) { TestClassBase.Initialize(testContext); } /// <summary> /// Clear the class. /// </summary> [ClassCleanup] public static void ClassCleanUp() { TestClassBase.Cleanup(); } #endregion #region MSASAIRS_S01_TC01_BodyPartPreference_AllOrNoneTrue_AllContentReturned /// <summary> /// This case is designed to test when the value of the AllOrNone (BodyPartPreference) element is set to 1 (TRUE) and the content has not been truncated, all of the content is synchronized, searched or retrieved. /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S01_TC01_BodyPartPreference_AllOrNoneTrue_AllContentReturned() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); #region Send an html email and get the non-truncated data string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.HTML, subject, body); DataStructures.Sync allContentItem = this.GetAllContentItem(subject, this.User2Information.InboxCollectionId); #endregion #region Set BodyPartPreference element Request.BodyPartPreference[] bodyPartPreference = new Request.BodyPartPreference[] { new Request.BodyPartPreference() { Type = 2, TruncationSize = 100, TruncationSizeSpecified = true, AllOrNone = true, AllOrNoneSpecified = true } }; #endregion #region Verify Sync command related elements DataStructures.Sync syncItem = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, bodyPartPreference); this.VerifyBodyPartElements(syncItem.Email.BodyPart, true, false, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R373"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R373 Site.CaptureRequirementIfAreEqual<string>( allContentItem.Email.BodyPart.Data, syncItem.Email.BodyPart.Data, 373, @"[In AllOrNone] When the value [of the AllOrNone element] is set to 1 (TRUE) and the content has not been truncated, all of the content is synchronized."); #endregion #region Verify ItemOperations command related elements DataStructures.ItemOperations itemOperationsItem = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItem.ServerId, null, null, bodyPartPreference, null); this.VerifyBodyPartElements(itemOperationsItem.Email.BodyPart, true, false, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R54"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R54 Site.CaptureRequirementIfAreEqual<string>( allContentItem.Email.BodyPart.Data, itemOperationsItem.Email.BodyPart.Data, 54, @"[In AllOrNone] When the value [of the AllOrNone element] is set to 1 (TRUE) and the content has not been truncated, all of the content is retrieved."); #endregion #region Verify Search command related elements DataStructures.Search searchItem = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItem.Email.ConversationId, null, bodyPartPreference); this.VerifyBodyPartElements(searchItem.Email.BodyPart, true, false, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R53"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R53 Site.CaptureRequirementIfAreEqual<string>( allContentItem.Email.BodyPart.Data, searchItem.Email.BodyPart.Data, 53, @"[In AllOrNone] When the value [of the AllOrNone element] is set to 1 (TRUE) and the content has not been truncated, all of the content is searched."); #endregion #region Verify common requirements // According to above steps, requirements MS-ASAIRS_R120 and MS-ASAIRS_R271 can be covered directly. // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R120"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R120 Site.CaptureRequirement( 120, @"[In BodyPart] The BodyPart element MUST be included in a command response when the BodyPartPreference element (section 2.2.2.11) is specified in a request."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R271"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R271 Site.CaptureRequirement( 271, @"[In Status] [The value] 1 [of Status element] means Success."); #endregion } #endregion #region MSASAIRS_S01_TC02_BodyPartPreference_AllOrNoneTrue_AllContentNotReturned /// <summary> /// This case is designed to test when the value of the AllOrNone (BodyPartPreference) element is set to 1 (TRUE) and the content has been truncated, the content is not synchronized, searched or retrieved. /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S01_TC02_BodyPartPreference_AllOrNoneTrue_AllContentNotReturned() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); #region Send an html email string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.HTML, subject, body); #endregion #region Set BodyPartPreference element Request.BodyPartPreference[] bodyPartPreference = new Request.BodyPartPreference[] { new Request.BodyPartPreference() { Type = 2, TruncationSize = 2, TruncationSizeSpecified = true, AllOrNone = true, AllOrNoneSpecified = true } }; #endregion #region Verify Sync command related elements DataStructures.Sync syncItem = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, bodyPartPreference); this.VerifyBodyPartElements(syncItem.Email.BodyPart, true, true, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R376"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R376 Site.CaptureRequirementIfIsNull( syncItem.Email.BodyPart.Data, 376, @"[In AllOrNone] When the value is set to 1 (TRUE) and the content has been truncated, the content is not synchronized. "); #endregion #region Verify ItemOperations command related elements DataStructures.ItemOperations itemOperationsItem = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItem.ServerId, null, null, bodyPartPreference, null); this.VerifyBodyPartElements(itemOperationsItem.Email.BodyPart, true, true, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R377"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R377 Site.CaptureRequirementIfIsNull( itemOperationsItem.Email.BodyPart.Data, 377, @"[In AllOrNone] When the value is set to 1 (TRUE) and the content has been truncated, the content is not retrieved. "); #endregion #region Verify Search command related elements DataStructures.Search searchItem = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItem.Email.ConversationId, null, bodyPartPreference); this.VerifyBodyPartElements(searchItem.Email.BodyPart, true, true, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R375"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R375 Site.CaptureRequirementIfIsNull( searchItem.Email.BodyPart.Data, 375, @"[In AllOrNone] When the value is set to 1 (TRUE) and the content has been truncated, the content is not searched. "); #endregion #region Verify common requirements // According to above steps, requirement MS-ASAIRS_R63 can be covered directly // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R63"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R63 Site.CaptureRequirement( 63, @"[In AllOrNone (BodyPartPreference)] But, if the client also includes the AllOrNone element with a value of 1 (TRUE) along with the TruncationSize element, it is instructing the server not to return a truncated response for that type when the size (in bytes) of the available data exceeds the value of the TruncationSize element."); #endregion } #endregion #region MSASAIRS_S01_TC03_BodyPartPreference_AllOrNoneFalse_TruncatedContentReturned /// <summary> /// This case is designed to test when the value of the AllOrNone (BodyPartPreference) element is set to 0 (FALSE) and the available data exceeds the value of the TruncationSize element, the truncated content is synchronized, searched or retrieved. /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S01_TC03_BodyPartPreference_AllOrNoneFalse_TruncatedContentReturned() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); #region Send an html email and get the non-truncated data string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.HTML, subject, body); this.GetAllContentItem(subject, this.User2Information.InboxCollectionId); XmlElement lastRawResponse = (XmlElement)this.ASAIRSAdapter.LastRawResponseXml; string allData = TestSuiteHelper.GetDataInnerText(lastRawResponse, "BodyPart", "Data", subject); #endregion #region Set BodyPartPreference element Request.BodyPartPreference[] bodyPartPreference = new Request.BodyPartPreference[] { new Request.BodyPartPreference() { Type = 2, TruncationSize = 8, TruncationSizeSpecified = true, AllOrNone = false, AllOrNoneSpecified = true } }; #endregion #region Verify Sync command related elements DataStructures.Sync syncItem = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, bodyPartPreference); lastRawResponse = (XmlElement)this.ASAIRSAdapter.LastRawResponseXml; this.VerifyBodyPartElements(syncItem.Email.BodyPart, false, true, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R378"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R378 Site.CaptureRequirementIfAreEqual<string>( TestSuiteHelper.TruncateData(allData, (int)bodyPartPreference[0].TruncationSize), TestSuiteHelper.GetDataInnerText(lastRawResponse, "BodyPart", "Data", subject), 378, @"[In AllOrNone] When the value is set to 0 (FALSE), the truncated is synchronized. "); #endregion #region Verify ItemOperations command related elements DataStructures.ItemOperations itemOperationsItem = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItem.ServerId, null, null, bodyPartPreference, null); lastRawResponse = (XmlElement)this.ASAIRSAdapter.LastRawResponseXml; this.VerifyBodyPartElements(itemOperationsItem.Email.BodyPart, false, true, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R379"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R379 Site.CaptureRequirementIfAreEqual<string>( TestSuiteHelper.TruncateData(allData, (int)bodyPartPreference[0].TruncationSize), TestSuiteHelper.GetDataInnerText(lastRawResponse, "BodyPart", "Data", subject), 379, @"[In AllOrNone] When the value is set to 0 (FALSE), the truncated is retrieved. "); #endregion #region Verify Search command related elements DataStructures.Search searchItem = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItem.Email.ConversationId, null, bodyPartPreference); lastRawResponse = (XmlElement)this.ASAIRSAdapter.LastRawResponseXml; this.VerifyBodyPartElements(searchItem.Email.BodyPart, false, true, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R55"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R55 Site.CaptureRequirementIfAreEqual<string>( TestSuiteHelper.TruncateData(allData, (int)bodyPartPreference[0].TruncationSize), TestSuiteHelper.GetDataInnerText(lastRawResponse, "BodyPart", "Data", subject), 55, @"[In AllOrNone] When the value is set to 0 (FALSE), the truncated is searched. "); #endregion #region Verify requirement // According to above steps, requirement MS-ASAIRS_R188 can be captured directly // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R188"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R188 Site.CaptureRequirement( 188, @"[In Data (BodyPart)] If the Truncated element (section 2.2.2.39.2) is included in the response, then the data in the Data element is truncated."); #endregion } #endregion #region MSASAIRS_S01_TC04_BodyPartPreference_AllOrNoneFalse_NonTruncatedContentReturned /// <summary> /// This case is designed to test when the value of the AllOrNone (BodyPartPreference) element is set to 0 (FALSE) and the available data doesn't exceed the value of the TruncationSize element, the non-truncated content will be synchronized, searched or retrieved. /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S01_TC04_BodyPartPreference_AllOrNoneFalse_NonTruncatedContentReturned() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); #region Send an html email and get the non-truncated data string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.HTML, subject, body); DataStructures.Sync allContentItem = this.GetAllContentItem(subject, this.User2Information.InboxCollectionId); #endregion #region Set BodyPartPreference element Request.BodyPartPreference[] bodyPartPreference = new Request.BodyPartPreference[] { new Request.BodyPartPreference() { Type = 2, TruncationSize = 100, TruncationSizeSpecified = true, AllOrNone = false, AllOrNoneSpecified = true } }; #endregion #region Verify Sync command related elements DataStructures.Sync syncItem = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, bodyPartPreference); this.VerifyBodyPartElements(syncItem.Email.BodyPart, false, false, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R381"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R381 Site.CaptureRequirementIfAreEqual<string>( allContentItem.Email.BodyPart.Data, syncItem.Email.BodyPart.Data, 381, @"[In AllOrNone] When the value is set to 0 (FALSE), the nontruncated content is synchronized. "); #endregion #region Verify ItemOperations command related elements DataStructures.ItemOperations itemOperationsItem = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItem.ServerId, null, null, bodyPartPreference, null); this.VerifyBodyPartElements(itemOperationsItem.Email.BodyPart, false, false, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R382"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R382 Site.CaptureRequirementIfAreEqual<string>( allContentItem.Email.BodyPart.Data, itemOperationsItem.Email.BodyPart.Data, 382, @"[In AllOrNone] When the value is set to 0 (FALSE), the nontruncated content is retrieved. "); #endregion #region Verify Search command related elements DataStructures.Search searchItem = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItem.Email.ConversationId, null, bodyPartPreference); this.VerifyBodyPartElements(searchItem.Email.BodyPart, false, false, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R380"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R380 Site.CaptureRequirementIfAreEqual<string>( allContentItem.Email.BodyPart.Data, searchItem.Email.BodyPart.Data, 380, @"[In AllOrNone] When the value is set to 0 (FALSE), the nontruncated content is searched. "); #endregion } #endregion #region MSASAIRS_S01_TC05_BodyPartPreference_NoAllOrNone_TruncatedContentReturned /// <summary> /// This case is designed to test if the AllOrNone (BodyPartPreference) element is not included in the request and the available data exceeds the value of the TruncationSize element, the truncated content synchronized, searched or retrieved as if the value was set to 0 (FALSE). /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S01_TC05_BodyPartPreference_NoAllOrNone_TruncatedContentReturned() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); #region Send an html email and get the non-truncated data string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.HTML, subject, body); this.GetAllContentItem(subject, this.User2Information.InboxCollectionId); XmlElement lastRawResponse = (XmlElement)this.ASAIRSAdapter.LastRawResponseXml; string allData = TestSuiteHelper.GetDataInnerText(lastRawResponse, "BodyPart", "Data", subject); #endregion #region Set BodyPreference element Request.BodyPartPreference[] bodyPartPreference = new Request.BodyPartPreference[] { new Request.BodyPartPreference() { Type = 2, TruncationSize = 8, TruncationSizeSpecified = true } }; #endregion #region Verify Sync command related elements DataStructures.Sync syncItem = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, bodyPartPreference); lastRawResponse = (XmlElement)this.ASAIRSAdapter.LastRawResponseXml; this.VerifyBodyPartElements(syncItem.Email.BodyPart, null, true, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R407"); // Verify MS-ASAIRS requirement: Verify MS-ASAIRS_R407 Site.CaptureRequirementIfAreEqual<string>( TestSuiteHelper.TruncateData(allData, (int)bodyPartPreference[0].TruncationSize), TestSuiteHelper.GetDataInnerText(lastRawResponse, "BodyPart", "Data", subject), 407, @"[In AllOrNone (BodyPartPreference)] If the AllOrNone element is not included in the request, the truncated synchronized as if the value was set to 0 (FALSE)."); #endregion #region Verify ItemOperations command related elements DataStructures.ItemOperations itemOperationsItem = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItem.ServerId, null, null, bodyPartPreference, null); lastRawResponse = (XmlElement)this.ASAIRSAdapter.LastRawResponseXml; this.VerifyBodyPartElements(itemOperationsItem.Email.BodyPart, null, true, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R408"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R408 Site.CaptureRequirementIfAreEqual<string>( TestSuiteHelper.TruncateData(allData, (int)bodyPartPreference[0].TruncationSize), TestSuiteHelper.GetDataInnerText(lastRawResponse, "BodyPart", "Data", subject), 408, @"[In AllOrNone (BodyPartPreference)] If the AllOrNone element is not included in the request, the truncated retrieved as if the value was set to 0 (FALSE)."); #endregion #region Verify Search command related elements DataStructures.Search searchItem = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItem.Email.ConversationId, null, bodyPartPreference); lastRawResponse = (XmlElement)this.ASAIRSAdapter.LastRawResponseXml; this.VerifyBodyPartElements(searchItem.Email.BodyPart, null, true, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R392"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R392 Site.CaptureRequirementIfAreEqual<string>( TestSuiteHelper.TruncateData(allData, (int)bodyPartPreference[0].TruncationSize), TestSuiteHelper.GetDataInnerText(lastRawResponse, "BodyPart", "Data", subject), 392, @"[In AllOrNone (BodyPartPreference)] If the AllOrNone element is not included in the request, the truncated searched as if the value was set to 0 (FALSE)."); #endregion #region Verify common requirements // According to above steps, requirements MS-ASAIRS_R62 and MS-ASAIRS_R282 can be captured directly // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R62"); // Verify MS-ASAIRS requirement: Verify MS-ASAIRS_R62 Site.CaptureRequirement( 62, @"[In AllOrNone (BodyPartPreference)] [A client can include multiple BodyPartPreference elements in a command request with different values for the Type element] By default, the server returns the data truncated to the size requested by TruncationSize for the Type element that matches the native storage format of the item's Body element (section 2.2.2.9)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R282"); // Verify MS-ASAIRS requirement: Verify MS-ASAIRS_R282 Site.CaptureRequirement( 282, @"[In Truncated (BodyPart)] If the value [of the Truncated element] is TRUE, then the body of the item has been truncated."); #endregion } #endregion #region MSASAIRS_S01_TC06_BodyPartPreference_NoAllOrNone_NonTruncatedContentReturned /// <summary> /// This case is designed to test if the AllOrNone (BodyPartPreference) element is not included in the request and the available data doesn't exceed the value of the TruncationSize element, the non-truncated content will be synchronized, searched or retrieved as if the value was set to 0 (FALSE). /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S01_TC06_BodyPartPreference_NoAllOrNone_NonTruncatedContentReturned() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); #region Send an html email and get the non-truncated data string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.HTML, subject, body); DataStructures.Sync allContentItem = this.GetAllContentItem(subject, this.User2Information.InboxCollectionId); #endregion #region Set BodyPartPreference element Request.BodyPartPreference[] bodyPartPreference = new Request.BodyPartPreference[] { new Request.BodyPartPreference() { Type = 2, TruncationSize = 100, TruncationSizeSpecified = true } }; #endregion #region Verify Sync command related elements DataStructures.Sync syncItem = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, bodyPartPreference); this.VerifyBodyPartElements(syncItem.Email.BodyPart, null, false, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R410"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R410 Site.CaptureRequirementIfAreEqual<string>( allContentItem.Email.BodyPart.Data, syncItem.Email.BodyPart.Data, 410, @"[In AllOrNone (BodyPartPreference)] If the AllOrNone element is not included in the request, the nontruncated content is synchronized as if the value was set to 0 (FALSE)."); #endregion #region Verify ItemOperations command related elements DataStructures.ItemOperations itemOperationsItem = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItem.ServerId, null, null, bodyPartPreference, null); this.VerifyBodyPartElements(itemOperationsItem.Email.BodyPart, null, false, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R411"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R411 Site.CaptureRequirementIfAreEqual<string>( allContentItem.Email.BodyPart.Data, itemOperationsItem.Email.BodyPart.Data, 411, @"[In AllOrNone (BodyPartPreference)] If the AllOrNone element is not included in the request, the nontruncated content is retrieved as if the value was set to 0 (FALSE)."); #endregion #region Verify Search command related elements DataStructures.Search searchItem = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItem.Email.ConversationId, null, bodyPartPreference); this.VerifyBodyPartElements(searchItem.Email.BodyPart, null, false, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R409"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R409 Site.CaptureRequirementIfAreEqual<string>( allContentItem.Email.BodyPart.Data, searchItem.Email.BodyPart.Data, 409, @"[In AllOrNone (BodyPartPreference)] If the AllOrNone element is not included in the request, the nontruncated content is searched as if the value was set to 0 (FALSE)."); #endregion #region Verify common requirements // According to above steps, requirement MS-ASAIRS_R283 can be captured directly // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R283"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R283 Site.CaptureRequirement( 283, @"[In Truncated (BodyPart)] If the value [of the Truncated element] is FALSE, or there is no Truncated element, then the body of the item has not been truncated."); #endregion } #endregion #region MSASAIRS_S01_TC07_BodyPartPreference_NotIncludedTruncationSize /// <summary> /// This case is designed to test if the TruncationSize (BodyPartPreference) element is not included, the server will return the same response no matter whether AllOrNone is true or false. /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S01_TC07_BodyPartPreference_NotIncludedTruncationSize() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); #region Send an html email and get the non-truncated data string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.HTML, subject, body); DataStructures.Sync allContentItem = this.GetAllContentItem(subject, this.User2Information.InboxCollectionId); #endregion #region Set BodyPartPreference element Request.BodyPartPreference[] bodyPartPreferenceAllOrNoneTrue = new Request.BodyPartPreference[] { new Request.BodyPartPreference() { Type = 2, AllOrNone = true, AllOrNoneSpecified = true } }; Request.BodyPartPreference[] bodyPartPreferenceAllOrNoneFalse = new Request.BodyPartPreference[] { new Request.BodyPartPreference() { Type = 2, AllOrNone = false, AllOrNoneSpecified = true } }; #endregion #region Verify Sync command related elements // Call Sync command with AllOrNone setting to TRUE DataStructures.Sync syncItemAllOrNoneTrue = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, bodyPartPreferenceAllOrNoneTrue); this.VerifyBodyPartElements(syncItemAllOrNoneTrue.Email.BodyPart, true, false, false); // Call Sync command with AllOrNone setting to FALSE DataStructures.Sync syncItemAllOrNoneFalse = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, bodyPartPreferenceAllOrNoneFalse); this.VerifyBodyPartElements(syncItemAllOrNoneFalse.Email.BodyPart, false, false, false); Site.Log.Add( LogEntryKind.Debug, "Entire content: {0}, content for AllOrNone TRUE: {1}, content for AllOrNone FALSE: {2}.", allContentItem.Email.BodyPart.Data, syncItemAllOrNoneTrue.Email.BodyPart.Data, syncItemAllOrNoneFalse.Email.BodyPart.Data); Site.Assert.IsTrue( allContentItem.Email.BodyPart.Data == syncItemAllOrNoneTrue.Email.BodyPart.Data && syncItemAllOrNoneTrue.Email.BodyPart.Data == syncItemAllOrNoneFalse.Email.BodyPart.Data, "Server should return the entire content for the request and same response no matter AllOrNone is true or false if the TruncationSize element is absent in Sync command request."); #endregion #region Verify ItemOperations command related elements // Call ItemOperations command with AllOrNone setting to true DataStructures.ItemOperations itemOperationsItemAllOrNoneTrue = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItemAllOrNoneTrue.ServerId, null, null, bodyPartPreferenceAllOrNoneTrue, null); this.VerifyBodyPartElements(itemOperationsItemAllOrNoneTrue.Email.BodyPart, true, false, false); // Call ItemOperations command with AllOrNone setting to false DataStructures.ItemOperations itemOperationsItemAllOrNoneFalse = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItemAllOrNoneTrue.ServerId, null, null, bodyPartPreferenceAllOrNoneFalse, null); this.VerifyBodyPartElements(itemOperationsItemAllOrNoneFalse.Email.BodyPart, false, false, false); Site.Log.Add( LogEntryKind.Debug, "Entire content: {0}, content for AllOrNone TRUE: {1}, content for AllOrNone FALSE: {2}.", allContentItem.Email.BodyPart.Data, itemOperationsItemAllOrNoneTrue.Email.BodyPart.Data, itemOperationsItemAllOrNoneFalse.Email.BodyPart.Data); Site.Assert.IsTrue( allContentItem.Email.BodyPart.Data == itemOperationsItemAllOrNoneTrue.Email.BodyPart.Data && itemOperationsItemAllOrNoneTrue.Email.BodyPart.Data == itemOperationsItemAllOrNoneFalse.Email.BodyPart.Data, "Server should return the entire content for the request and same response no matter AllOrNone is true or false if the TruncationSize element is absent in ItemOperations command request."); #endregion #region Verify Search command related elements // Call Search command with AllOrNone setting to true DataStructures.Search searchItemAllNoneTrue = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItemAllOrNoneTrue.Email.ConversationId, null, bodyPartPreferenceAllOrNoneTrue); this.VerifyBodyPartElements(searchItemAllNoneTrue.Email.BodyPart, true, false, false); // Call Search command with AllOrNone setting to false DataStructures.Search searchItemAllNoneFalse = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItemAllOrNoneTrue.Email.ConversationId, null, bodyPartPreferenceAllOrNoneFalse); this.VerifyBodyPartElements(searchItemAllNoneFalse.Email.BodyPart, false, false, false); Site.Log.Add( LogEntryKind.Debug, "Entire content: {0}, content for AllOrNone TRUE: {1}, content for AllOrNone FALSE: {2}.", allContentItem.Email.BodyPart.Data, searchItemAllNoneTrue.Email.BodyPart.Data, searchItemAllNoneFalse.Email.BodyPart.Data); Site.Assert.IsTrue( allContentItem.Email.BodyPart.Data == searchItemAllNoneTrue.Email.BodyPart.Data && searchItemAllNoneTrue.Email.BodyPart.Data == searchItemAllNoneFalse.Email.BodyPart.Data, "Server should return the entire content for the request and same response no matter AllOrNone is true or false if the TruncationSize element is absent in Search command request."); #endregion #region Verify requirements // According to above steps, requirements MS-ASAIRS_R294 and MS-ASAIRS_R400 can be captured directly // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R294"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R294 Site.CaptureRequirement( 294, @"[In TruncationSize (BodyPartPreference)] If the TruncationSize element is absent, the entire content is used for the request."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R400"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R400 Site.CaptureRequirement( 400, @"[In AllOrNone (BodyPartPreference)] If the TruncationSize element is not included, the server will return the same response no matter whether AllOrNone is true or false."); #endregion } #endregion #region MSASAIRS_S01_TC08_BodyPart_Preview /// <summary> /// This case is designed to test the Preview (BodyPart) element which contains the Unicode plain text message or message part preview returned to the client. /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S01_TC08_BodyPart_Preview() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); #region Send an html email and get the none truncated data string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.HTML, subject, body); DataStructures.Sync allContentItem = this.GetAllContentItem(subject, this.User2Information.InboxCollectionId); #endregion #region Set BodyPartPreference element Request.BodyPartPreference[] bodyPartPreference = new Request.BodyPartPreference[] { new Request.BodyPartPreference() { Type = 2, Preview = 18, PreviewSpecified = true } }; #endregion #region Verify Sync command related elements DataStructures.Sync syncItem = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, bodyPartPreference); this.VerifyBodyPartPreview(syncItem.Email, allContentItem.Email, bodyPartPreference); #endregion #region Verify ItemOperations command related elements DataStructures.ItemOperations itemOperationsItem = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItem.ServerId, null, null, bodyPartPreference, null); this.VerifyBodyPartPreview(itemOperationsItem.Email, allContentItem.Email, bodyPartPreference); #endregion #region Verify Search command related elements DataStructures.Search searchItem = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItem.Email.ConversationId, null, bodyPartPreference); this.VerifyBodyPartPreview(searchItem.Email, allContentItem.Email, bodyPartPreference); #endregion #region Verify requirements // According to above steps, the following requirements can be captured directly // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R256"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R256 Site.CaptureRequirement( 256, @"[In Preview (BodyPart)] The Preview element MUST be present in a command response if a BodyPartPreference element (section 2.2.2.11) in the request included a Preview element and the server can honor the request."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R253"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R253 Site.CaptureRequirement( 253, @"[In Preview (BodyPart)] The Preview element is an optional child element of the BodyPart element (section 2.2.2.10) that contains the Unicode plain text message or message part preview returned to the client."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R255"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R255 Site.CaptureRequirement( 255, @"[In Preview (BodyPart)] The Preview element in a response MUST contain no more than the number of characters specified in the request."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R2599"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R2599 Site.CaptureRequirement( 2599, @"[In Preview (BodyPartPreference)] [The Preview element] specifies the maximum length of the Unicode plain text message or message part preview to be returned to the client."); #endregion } #endregion #region Private methods /// <summary> /// Verify elements in BodyPart element. /// </summary> /// <param name="bodyPart">The body part of item.</param> /// <param name="allOrNone">The value of AllOrNone element, "null" means the AllOrNone element is not present in request.</param> /// <param name="truncated">Whether the content is truncated.</param> /// <param name="includedTruncationSize">Whether includes the TruncationSize element.</param> private void VerifyBodyPartElements(BodyPart bodyPart, bool? allOrNone, bool truncated, bool includedTruncationSize) { Site.Assert.IsNotNull( bodyPart, "The BodyPart element should be included in response when the BodyPartPreference element is specified in request."); Site.Assert.AreEqual<byte>( 1, bodyPart.Status, "The Status should be 1 to indicate the success of the response in returning Data element content given the BodyPartPreference element settings in the request."); // Verify elements when TruncationSize element is absent if (!includedTruncationSize) { Site.Assert.IsTrue( !bodyPart.TruncatedSpecified || (bodyPart.TruncatedSpecified && !bodyPart.Truncated), "The data should not be truncated when the TruncationSize element is absent."); // Since the AllOrNone will be ignored when TruncationSize is not included in request, return if includedTruncationSize is false return; } if (truncated) { Site.Assert.IsTrue( bodyPart.Truncated, "The data should be truncated when the AllOrNone element value is {0} in the request and the available data exceeds the truncation size.", allOrNone); } else { Site.Assert.IsTrue( !bodyPart.TruncatedSpecified || (bodyPart.TruncatedSpecified && !bodyPart.Truncated), "The data should not be truncated when the AllOrNone element value is {0} in the request and the truncation size exceeds the available data.", allOrNone); } if (bodyPart.Truncated) { if (Common.IsRequirementEnabled(403, this.Site)) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R403"); // Since the EstimatedDataSize element provides an informational estimate of the size of the data associated with the parent element and the body is not null, if the Truncated value is true, the EstimatedDataSize value should not be 0, then requirement MS-ASAIRS_R403 can be captured. // Verify MS-ASAIRS requirement: MS-ASAIRS_R403 Site.CaptureRequirementIfAreNotEqual<uint>( 0, bodyPart.EstimatedDataSize, 403, @"[In Appendix B: Product Behavior] Implementation does include the EstimatedDataSize (BodyPart) element in a response message whenever the Truncated element is set to TRUE. (Exchange Server 2007 SP1 and above follow this behavior.)"); } } } /// <summary> /// Verify the Preview element in BodyPart element. /// </summary> /// <param name="email">The email item got from server.</param> /// <param name="allContentEmail">The email item which has full content.</param> /// <param name="bodyPartPreference">A BodyPartPreference object.</param> private void VerifyBodyPartPreview(DataStructures.Email email, DataStructures.Email allContentEmail, Request.BodyPartPreference[] bodyPartPreference) { Site.Assert.IsNotNull( email.BodyPart, "The BodyPart element should be included in command response when the BodyPartPreference element is specified in command request."); Site.Assert.AreEqual<byte>( 1, email.BodyPart.Status, "The Status should be 1 to indicate the success of the command response in returning Data element content given the BodyPartPreference element settings in the command request."); Site.Assert.IsNotNull( email.BodyPart.Preview, "The Preview element should be present in response if a BodyPartPreference element in the request included a Preview element and the server can honor the request."); Site.Assert.IsTrue( email.BodyPart.Preview.Length <= bodyPartPreference[0].Preview, "The Preview element in a response should contain no more than the number of characters specified in the request. The length of Preview element in response is: {0}.", email.BodyPart.Preview.Length); Site.Assert.IsTrue( allContentEmail.BodyPart.Data.Contains(email.BodyPart.Preview), "The Preview element in a response should contain the message part preview returned to the client."); } #endregion } }
/* * InformationMachineAPI.PCL * * */ using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using InformationMachineAPI.PCL; namespace InformationMachineAPI.PCL.Models { public class UserStore : INotifyPropertyChanged { // These fields hold the values for the public properties. private long id; private long supermarketId; private UserData user; private string storeName; private string username; private string credentialsStatus; private string scrapeStatus; private string type; private bool? accountLocked; private string accountLockCode; private string unlockUrl; private string oauthProvider; private string oauthAuthorizationUrl; private DateTime? createdAt; private DateTime? updatedAt; private double? totalSpent; /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("id")] public long Id { get { return this.id; } set { this.id = value; onPropertyChanged("Id"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("supermarket_id")] public long SupermarketId { get { return this.supermarketId; } set { this.supermarketId = value; onPropertyChanged("SupermarketId"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("user")] public UserData User { get { return this.user; } set { this.user = value; onPropertyChanged("User"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("store_name")] public string StoreName { get { return this.storeName; } set { this.storeName = value; onPropertyChanged("StoreName"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("username")] public string Username { get { return this.username; } set { this.username = value; onPropertyChanged("Username"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("credentials_status")] public string CredentialsStatus { get { return this.credentialsStatus; } set { this.credentialsStatus = value; onPropertyChanged("CredentialsStatus"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("scrape_status")] public string ScrapeStatus { get { return this.scrapeStatus; } set { this.scrapeStatus = value; onPropertyChanged("ScrapeStatus"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("type")] public string Type { get { return this.type; } set { this.type = value; onPropertyChanged("Type"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("account_locked")] public bool? AccountLocked { get { return this.accountLocked; } set { this.accountLocked = value; onPropertyChanged("AccountLocked"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("account_lock_code")] public string AccountLockCode { get { return this.accountLockCode; } set { this.accountLockCode = value; onPropertyChanged("AccountLockCode"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("unlock_url")] public string UnlockUrl { get { return this.unlockUrl; } set { this.unlockUrl = value; onPropertyChanged("UnlockUrl"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("oauth_provider")] public string OauthProvider { get { return this.oauthProvider; } set { this.oauthProvider = value; onPropertyChanged("OauthProvider"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("oauth_authorization_url")] public string OauthAuthorizationUrl { get { return this.oauthAuthorizationUrl; } set { this.oauthAuthorizationUrl = value; onPropertyChanged("OauthAuthorizationUrl"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("created_at")] public DateTime? CreatedAt { get { return this.createdAt; } set { this.createdAt = value; onPropertyChanged("CreatedAt"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("updated_at")] public DateTime? UpdatedAt { get { return this.updatedAt; } set { this.updatedAt = value; onPropertyChanged("UpdatedAt"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("total_spent")] public double? TotalSpent { get { return this.totalSpent; } set { this.totalSpent = value; onPropertyChanged("TotalSpent"); } } /// <summary> /// Property changed event for observer pattern /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises event when a property is changed /// </summary> /// <param name="propertyName">Name of the changed property</param> protected void onPropertyChanged(String propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes.Suppression { internal abstract partial class AbstractSuppressionCodeFixProvider : ISuppressionFixProvider { internal abstract partial class RemoveSuppressionCodeAction { /// <summary> /// Code action to edit/remove/add the pragma directives for removing diagnostic suppression. /// </summary> private class PragmaRemoveAction : RemoveSuppressionCodeAction, IPragmaBasedCodeAction { private readonly Document _document; private readonly SuppressionTargetInfo _suppressionTargetInfo; public static PragmaRemoveAction Create( SuppressionTargetInfo suppressionTargetInfo, Document document, Diagnostic diagnostic, AbstractSuppressionCodeFixProvider fixer) { // We need to normalize the leading trivia on start token to account for // the trailing trivia on its previous token (and similarly normalize trailing trivia for end token). PragmaHelpers.NormalizeTriviaOnTokens(fixer, ref document, ref suppressionTargetInfo); return new PragmaRemoveAction(suppressionTargetInfo, document, diagnostic, fixer); } private PragmaRemoveAction( SuppressionTargetInfo suppressionTargetInfo, Document document, Diagnostic diagnostic, AbstractSuppressionCodeFixProvider fixer, bool forFixMultipleContext = false) : base(diagnostic, fixer, forFixMultipleContext) { _document = document; _suppressionTargetInfo = suppressionTargetInfo; } public override RemoveSuppressionCodeAction CloneForFixMultipleContext() { return new PragmaRemoveAction(_suppressionTargetInfo, _document, _diagnostic, Fixer, forFixMultipleContext: true); } public override SyntaxTree SyntaxTreeToModify => _suppressionTargetInfo.StartToken.SyntaxTree; protected async override Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken) { return await GetChangedDocumentAsync(includeStartTokenChange: true, includeEndTokenChange: true, cancellationToken: cancellationToken).ConfigureAwait(false); } public async Task<Document> GetChangedDocumentAsync(bool includeStartTokenChange, bool includeEndTokenChange, CancellationToken cancellationToken) { bool add = false; bool toggle = false; int indexOfLeadingPragmaDisableToRemove = -1, indexOfTrailingPragmaEnableToRemove = -1; if (CanRemovePragmaTrivia(_suppressionTargetInfo.StartToken, _diagnostic, Fixer, isStartToken: true, indexOfTriviaToRemove: out indexOfLeadingPragmaDisableToRemove) && CanRemovePragmaTrivia(_suppressionTargetInfo.EndToken, _diagnostic, Fixer, isStartToken: false, indexOfTriviaToRemove: out indexOfTrailingPragmaEnableToRemove)) { // Verify if there is no other trivia before the start token would again cause this diagnostic to be suppressed. // If invalidated, then we just toggle existing pragma enable and disable directives before and start of the line. // If not, then we just remove the existing pragma trivia surrounding the line. toggle = await IsDiagnosticSuppressedBeforeLeadingPragmaAsync(indexOfLeadingPragmaDisableToRemove, cancellationToken).ConfigureAwait(false); } else { // Otherwise, just add a pragma enable before the start token and a pragma restore after it. add = true; } Func<SyntaxToken, TextSpan, SyntaxToken> getNewStartToken = (startToken, currentDiagnosticSpan) => includeStartTokenChange ? GetNewTokenWithModifiedPragma(startToken, currentDiagnosticSpan, add, toggle, indexOfLeadingPragmaDisableToRemove, isStartToken: true) : startToken; Func<SyntaxToken, TextSpan, SyntaxToken> getNewEndToken = (endToken, currentDiagnosticSpan) => includeEndTokenChange ? GetNewTokenWithModifiedPragma(endToken, currentDiagnosticSpan, add, toggle, indexOfTrailingPragmaEnableToRemove, isStartToken: false) : endToken; return await PragmaHelpers.GetChangeDocumentWithPragmaAdjustedAsync( _document, _diagnostic.Location.SourceSpan, _suppressionTargetInfo, getNewStartToken, getNewEndToken, cancellationToken).ConfigureAwait(false); } private static SyntaxTriviaList GetTriviaListForSuppression(SyntaxToken token, bool isStartToken, AbstractSuppressionCodeFixProvider fixer) { return isStartToken || fixer.IsEndOfFileToken(token) ? token.LeadingTrivia : token.TrailingTrivia; } private static SyntaxToken UpdateTriviaList(SyntaxToken token, bool isStartToken, SyntaxTriviaList triviaList, AbstractSuppressionCodeFixProvider fixer) { return isStartToken || fixer.IsEndOfFileToken(token) ? token.WithLeadingTrivia(triviaList) : token.WithTrailingTrivia(triviaList); } private static bool CanRemovePragmaTrivia(SyntaxToken token, Diagnostic diagnostic, AbstractSuppressionCodeFixProvider fixer, bool isStartToken, out int indexOfTriviaToRemove) { indexOfTriviaToRemove = -1; var triviaList = GetTriviaListForSuppression(token, isStartToken, fixer); var diagnosticSpan = diagnostic.Location.SourceSpan; Func<SyntaxTrivia, bool> shouldIncludeTrivia = t => isStartToken ? t.FullSpan.End <= diagnosticSpan.Start : t.FullSpan.Start >= diagnosticSpan.End; var filteredTriviaList = triviaList.Where(shouldIncludeTrivia); if (isStartToken) { // Walk bottom up for leading trivia. filteredTriviaList = filteredTriviaList.Reverse(); } foreach (var trivia in filteredTriviaList) { bool isEnableDirective, hasMultipleIds; if (fixer.IsAnyPragmaDirectiveForId(trivia, diagnostic.Id, out isEnableDirective, out hasMultipleIds)) { if (hasMultipleIds) { // Handle only simple cases where we have a single pragma directive with single ID matching ours in the trivia. return false; } // We want to look for leading disable directive and trailing enable directive. if ((isStartToken && !isEnableDirective) || (!isStartToken && isEnableDirective)) { indexOfTriviaToRemove = triviaList.IndexOf(trivia); return true; } return false; } } return false; } private SyntaxToken GetNewTokenWithModifiedPragma(SyntaxToken token, TextSpan currentDiagnosticSpan, bool add, bool toggle, int indexOfTriviaToRemoveOrToggle, bool isStartToken) { return add ? GetNewTokenWithAddedPragma(token, currentDiagnosticSpan, isStartToken) : GetNewTokenWithRemovedOrToggledPragma(token, indexOfTriviaToRemoveOrToggle, isStartToken, toggle); } private SyntaxToken GetNewTokenWithAddedPragma(SyntaxToken token, TextSpan currentDiagnosticSpan, bool isStartToken) { if (isStartToken) { return PragmaHelpers.GetNewStartTokenWithAddedPragma(token, currentDiagnosticSpan, _diagnostic, Fixer, FormatNode, isRemoveSuppression: true); } else { return PragmaHelpers.GetNewEndTokenWithAddedPragma(token, currentDiagnosticSpan, _diagnostic, Fixer, FormatNode, isRemoveSuppression: true); } } private SyntaxToken GetNewTokenWithRemovedOrToggledPragma(SyntaxToken token, int indexOfTriviaToRemoveOrToggle, bool isStartToken, bool toggle) { if (isStartToken) { return GetNewTokenWithPragmaUnsuppress(token, indexOfTriviaToRemoveOrToggle, _diagnostic, Fixer, isStartToken, toggle); } else { return GetNewTokenWithPragmaUnsuppress(token, indexOfTriviaToRemoveOrToggle, _diagnostic, Fixer, isStartToken, toggle); } } private static SyntaxToken GetNewTokenWithPragmaUnsuppress(SyntaxToken token, int indexOfTriviaToRemoveOrToggle, Diagnostic diagnostic, AbstractSuppressionCodeFixProvider fixer, bool isStartToken, bool toggle) { Contract.ThrowIfFalse(indexOfTriviaToRemoveOrToggle >= 0); var triviaList = GetTriviaListForSuppression(token, isStartToken, fixer); if (toggle) { var triviaToToggle = triviaList.ElementAt(indexOfTriviaToRemoveOrToggle); Contract.ThrowIfFalse(triviaToToggle != default(SyntaxTrivia)); var toggledTrivia = fixer.TogglePragmaDirective(triviaToToggle); triviaList = triviaList.Replace(triviaToToggle, toggledTrivia); } else { triviaList = triviaList.RemoveAt(indexOfTriviaToRemoveOrToggle); } return UpdateTriviaList(token, isStartToken, triviaList, fixer); } private async Task<bool> IsDiagnosticSuppressedBeforeLeadingPragmaAsync(int indexOfPragma, CancellationToken cancellationToken) { var model = await _document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var tree = model.SyntaxTree; // get the warning state of this diagnostic ID at the start of the pragma var trivia = _suppressionTargetInfo.StartToken.LeadingTrivia.ElementAt(indexOfPragma); var spanToCheck = new TextSpan( start: Math.Max(0, trivia.Span.Start - 1), length: 1); var locationToCheck = Location.Create(tree, spanToCheck); var dummyDiagnosticWithLocationToCheck = Diagnostic.Create(_diagnostic.Descriptor, locationToCheck); var effectiveDiagnostic = CompilationWithAnalyzers.GetEffectiveDiagnostics(new[] { dummyDiagnosticWithLocationToCheck }, model.Compilation).FirstOrDefault(); return effectiveDiagnostic == null || effectiveDiagnostic.IsSuppressed; } public SyntaxToken StartToken_TestOnly => _suppressionTargetInfo.StartToken; public SyntaxToken EndToken_TestOnly => _suppressionTargetInfo.EndToken; private SyntaxNode FormatNode(SyntaxNode node) { return Formatter.Format(node, _document.Project.Solution.Workspace); } } } } }