context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright 2019 Esri // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ArcGIS.Core.Geometry; using ArcGIS.Desktop.Mapping; using ArcGIS.Desktop.Framework.Threading.Tasks; using ArcGIS.Core.Data; using System.IO; using System.Reflection; using System.Windows.Media.Imaging; using System.Windows.Media; using ArcGIS.Desktop.Framework.Dialogs; using System.Globalization; namespace CustomPopup { /// <summary> /// Implementation of custom pop-up tool. /// </summary> internal class CustomPopupTool : MapTool { /// <summary> /// Define the tool as a sketch tool that draws a rectangle in screen space on the view. /// </summary> public CustomPopupTool() { IsSketchTool = true; SketchType = SketchGeometryType.Rectangle; SketchOutputMode = SketchOutputMode.Screen; //required for 3D selection and identify. } /// <summary> /// Called when a sketch is completed. /// </summary> protected override async Task<bool> OnSketchCompleteAsync(ArcGIS.Core.Geometry.Geometry geometry) { var popupContent = await QueuedTask.Run(() => { var mapView = MapView.Active; if (mapView == null) return null; //Get the features that intersect the sketch geometry. var result = mapView.GetFeatures(geometry); //For each feature in the result create a new instance of our custom popup content class. List<PopupContent> popups = new List<PopupContent>(); foreach (var kvp in result) { kvp.Value.ForEach(id => popups.Add(new DynamicPopupContent(kvp.Key, id))); } //Flash the features that intersected the sketch geometry. mapView.FlashFeature(result); //return the collection of popup content object. return popups; }); //Create the list of custom popup commands to show at the bottom of the pop-up window. var commands = CreateCommands(); //Show the custom pop-up with the custom commands and the default pop-up commands. MapView.Active.ShowCustomPopup(popupContent, CreateCommands(), true); return true; } /// <summary> /// Create and return a new collection of popup commands /// </summary> /// <returns></returns> private List<PopupCommand> CreateCommands() { var commands = new List<PopupCommand> { //Add a new instance of a popup command passing in the delegate to be run when the button is clicked. new PopupCommand(OnPopupCommand, CanExecutePopupCommand, "Show statistics", new BitmapImage(new Uri("pack://application:,,,/CustomPopup;component/Images/GenericButtonRed12.png")) as ImageSource) { IsSeparator = true } }; return commands; } /// <summary> /// The method called when the custom popup command is clicked. /// </summary> void OnPopupCommand(PopupContent content) { //Cast the content parameter to our custom popup content class. DynamicPopupContent dynamicContent = content as DynamicPopupContent; if (dynamicContent == null) return; //Call a method on the custom popup content object to show some statistics for the current popup content. dynamicContent.ShowStatistics(); } /// <summary> /// The method called periodically by the framework to determine if the command should be enabled. /// </summary> bool CanExecutePopupCommand(PopupContent content) { return content != null; } } /// <summary> /// Implementation of a custom popup content class /// </summary> internal class DynamicPopupContent : PopupContent { private Dictionary<FieldDescription, double> _values = new Dictionary<FieldDescription, double>(); /// <summary> /// Constructor initializing the base class with the layer and object id associated with the pop-up content /// </summary> public DynamicPopupContent(MapMember mapMember, long id) : base(mapMember, id) { //Set property indicating the html content will be generated on demand when the content is viewed. IsDynamicContent = true; } /// <summary> /// Called the first time the pop-up content is viewed. This is good practice when you may show a pop-up for multiple items at a time. /// This allows you to delay generating the html content until the item is actually viewed. /// </summary> protected override Task<string> OnCreateHtmlContent() { return QueuedTask.Run(() => { var invalidPopup = "<p>Pop-up content could not be generated for this feature.</p>"; var layer = MapMember as BasicFeatureLayer; if (layer == null) return invalidPopup; //Get all the visible numeric fields for the layer. var fields = layer.GetFieldDescriptions().Where(f => IsNumericFieldType(f.Type) && f.IsVisible); //Create a query filter using the fields found above and a where clause for the object id associated with this pop-up content. var tableDef = layer.GetTable().GetDefinition(); var oidField = tableDef.GetObjectIDField(); var qf = new QueryFilter() { WhereClause = string.Format("{0} = {1}", oidField, ID), SubFields = string.Join(",", fields.Select(f => f.Name)) }; var rows = layer.Search(qf); //Get the first row, there should only be 1 row. if (!rows.MoveNext()) return invalidPopup; using (var row = rows.Current) { //Loop through the fields, extract the value for the row and add to a dictionary. foreach (var field in fields) { var val = row[field.Name]; if (val is DBNull || val == null) continue; double value; if (!Double.TryParse(val.ToString(), out value)) continue; if (value < 0) continue; _values.Add(field, value); } if (_values.Count == 0) return invalidPopup; //Construct a new html string that we will use to update our html template. StringBuilder sb = new StringBuilder(); sb.AppendLine("data.addColumn('string', 'Age')"); //Choose a label that makes sense for the numeric fields shown. sb.AppendLine("data.addColumn('number', 'Number of People')"); //Choose a label that makes sense for the values shown in those fields. sb.AppendLine("data.addColumn('number', 'Percentage')"); sb.AppendLine("data.addRows(["); //Add each value to the html string. foreach (var v in _values) { var percentage = (v.Value / _values.Sum(kvp => kvp.Value)) * 100; sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "['{0}', {{v: {1} }}, {{v: {2} }}],", v.Key.Alias, v.Value, percentage)); } sb.AppendLine("]);"); //Get the html from the template file on disk that we have packaged with our add-in. var htmlPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "template.html"); var html = File.ReadAllText(htmlPath); //Update the template with our custom html and return it to be displayed in the pop-up window. html = html.Replace("//data.addColumn", sb.ToString()); return html; } }); } /// <summary> /// Show a message box with the Min and Max value and associated field. /// </summary> internal void ShowStatistics() { var maxVal = _values.Values.Max(); var minVal = _values.Values.Min(); var maxElements = _values.Where(v => v.Value == maxVal); var minElements = _values.Where(v => v.Value == minVal); StringBuilder sb = new StringBuilder(); sb.AppendLine(string.Format("Max ({0}): {1}", maxElements.First().Value, string.Join(",", maxElements.Select(x => x.Key.Alias)))); sb.Append(string.Format("Min ({0}): {1}", minElements.First().Value, string.Join(",", minElements.Select(x => x.Key.Alias)))); MessageBox.Show(sb.ToString(), "Statistics"); } /// <summary> /// Test if the field is a numeric type. /// </summary> private bool IsNumericFieldType(FieldType type) { switch (type) { case FieldType.Double: case FieldType.Integer: case FieldType.Single: case FieldType.SmallInteger: return true; default: return false; } } } }
using System; using CoreGraphics; using AudioToolbox; using CoreAnimation; using Foundation; using UIKit; using System.Diagnostics; using System.Text; using System.Threading.Tasks; namespace LockScreen { public static class Do { public static readonly Action Nothing = () => { }; } public abstract class LockScreenSettings { public LockScreenAppearence Appearence { get; private set; } public LockScreenMessages Messages { get; private set; } protected LockScreenSettings(LockScreenAppearence appearence, LockScreenMessages messages) { Appearence = appearence; Messages = messages; } } public abstract class LockScreenAppearence { public UIColor BackgroundColor { get; protected set; } public UIColor PinBoxBallColor { get; protected set; } public UIColor InvalidPasswordPinTextColor { get; protected set; } public UIColor ValidPasswordPinTextColor { get; protected set; } public UIColor PinBoxColor { get; protected set; } public UIColor TitleColor { get; protected set; } protected LockScreenAppearence() { BackgroundColor = UIColor.White; TitleColor = UIColor.Black; PinBoxColor = UIColor.LightGray; PinBoxBallColor = UIColor.Black; InvalidPasswordPinTextColor = UIColor.Red; ValidPasswordPinTextColor = UIColor.Green; } } public abstract class LockScreenMessages { public string EnterPasswordTitle { get; protected set; } public string SetPasswordTitle { get; protected set; } public string EnterOldPasswordTitle { get; protected set; } public string ReEnterNewPasswortTitle { get; protected set; } protected LockScreenMessages() { EnterPasswordTitle = "Please enter your password"; SetPasswordTitle = "Enter your new password"; EnterOldPasswordTitle = "Enter your old password"; ReEnterNewPasswortTitle = "Enter your new password again"; } } public sealed class DefaultSettings : LockScreenSettings { public DefaultSettings() : base(new DefaultAppearence(), new DefaultMessages()) { } } public sealed class DefaultAppearence : LockScreenAppearence { } public sealed class DefaultMessages : LockScreenMessages { } public partial class LockScreenController : UIViewController { public enum Mode { CheckPassword, SetPassword, ChangePassword } private static readonly UIImage _normalNumericButtonImage = UIImage.FromBundle("Images/normal.png"); private static readonly UIImage _highlightedNumericButtonImage = UIImage.FromBundle("Images/highlight.png"); private string _previousPasscode; private string _passcode; private UITextView _fakeField; private TaskCompletionSource<string> _passwordEntryFinished; private readonly LockScreenSettings _settings; private Mode _mode = Mode.CheckPassword; private bool _isActivated; static bool IsIPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public LockScreenController(LockScreenSettings settings) : base (IsIPhone ? "LockScreenController_iPhone" : "LockScreenController_iPad", null) { _settings = settings; } public override void ViewDidLoad() { base.ViewDidLoad(); titleLabel.Text = _settings.Messages.EnterPasswordTitle; ChangePinBoxBallColor(_settings.Appearence.PinBoxBallColor); View.BackgroundColor = _settings.Appearence.BackgroundColor; titleLabel.TextColor = _settings.Appearence.TitleColor; pinBox0.BackgroundColor = _settings.Appearence.PinBoxColor; pinBox1.BackgroundColor = _settings.Appearence.PinBoxColor; pinBox2.BackgroundColor = _settings.Appearence.PinBoxColor; pinBox3.BackgroundColor = _settings.Appearence.PinBoxColor; _fakeField = new UITextView(CGRect.Empty) { KeyboardType = UIKeyboardType.NumberPad, SecureTextEntry = true }; if(IsIPhone) { _fakeField.BecomeFirstResponder(); } else { InitializeIPadNumericButton(zero, 0); InitializeIPadNumericButton(one, 1); InitializeIPadNumericButton(two, 2); InitializeIPadNumericButton(three, 3); InitializeIPadNumericButton(four, 4); InitializeIPadNumericButton(five, 5); InitializeIPadNumericButton(six, 6); InitializeIPadNumericButton(seven, 7); InitializeIPadNumericButton(eight, 8); InitializeIPadNumericButton(nine, 9); InitializeIPadNumericButton(back, -1); } _fakeField.Changed += PasswordChanged; View.AddSubview(_fakeField); } private void InitializeIPadNumericButton(UIButton button, int representedNumber) { button.Tag = representedNumber; button.SetBackgroundImage(_normalNumericButtonImage, UIControlState.Normal); button.SetBackgroundImage(_highlightedNumericButtonImage, UIControlState.Highlighted); button.TouchUpInside += NumberButtonTouched; } private void NumberButtonTouched(object sender, EventArgs args) { var number = ((UIButton)sender).Tag; Debug.WriteLine(number); var oldValue = _fakeField.Text; if(number > -1) { _fakeField.Text = (new StringBuilder(oldValue).Append(number)).ToString(); } else { if(oldValue.Length > 0) { _fakeField.Text = oldValue.Remove(oldValue.Length-1, 1); } } PasswordChanged(_fakeField, EventArgs.Empty); } public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations() { return UIInterfaceOrientationMask.Portrait; } public async Task<string> ChangeMode(Mode newMode) { SetMode(newMode); return await PasswordEntered (); } private void SetMode(Mode mode) { _mode = mode; switch (_mode) { case Mode.ChangePassword: titleLabel.Text = _settings.Messages.EnterOldPasswordTitle; break; case Mode.SetPassword: titleLabel.Text = _settings.Messages.SetPasswordTitle; break; default: titleLabel.Text = _settings.Messages.EnterPasswordTitle; break; } } Task<string> PasswordEntered() { _passwordEntryFinished = null; _passwordEntryFinished = new TaskCompletionSource<string> (); return _passwordEntryFinished.Task; } public async Task<string> Activate(UIViewController parent, Mode mode) { _isActivated = true; parent.PresentViewController(this, false, Do.Nothing); if(IsIPhone) _fakeField.BecomeFirstResponder(); ResetPassword(); ResetPinBoxes(); ChangePinBoxBallColor(_settings.Appearence.PinBoxBallColor); SetMode(mode); return await PasswordEntered (); } public bool IsActivated { get { return _isActivated; } } public async Task Deactivate() { if(_isActivated) { _passwordEntryFinished = null; _isActivated = false; ResetPassword(); ResetPinBoxes(); ChangePinBoxBallColor(_settings.Appearence.PinBoxBallColor); SetMode(Mode.CheckPassword); await DismissViewControllerAsync (false); DismissViewController(false, Do.Nothing); } } public async Task DeactivateWithDelay(int milliseconds) { await Task.Delay (TimeSpan.FromMilliseconds (milliseconds)); await Deactivate (); } public async Task<string> AnimateInvalidPassword(bool deactivateAfterAnimation) { ChangePinBoxBallColor(_settings.Appearence.InvalidPasswordPinTextColor); await AnimateInvalidEntryAsync (); if (deactivateAfterAnimation) { await DeactivateWithDelay (200); return null; } else { return await PasswordEntered (); } } public async Task AnimateValidPassword(bool deactivateAfterAnimation) { ChangePinBoxBallColor(_settings.Appearence.ValidPasswordPinTextColor); await AnimateValidEntryAsnyc(); if (_mode == Mode.ChangePassword) { _mode = Mode.SetPassword; titleLabel.Text = _settings.Messages.SetPasswordTitle; await AnimateSetupForSecondEntry (); } if (deactivateAfterAnimation && _mode != Mode.ChangePassword) await DeactivateWithDelay (200); } private async void PasswordChanged(object sender, EventArgs e) { _passcode = _fakeField.Text; switch (_passcode.Length) { case 0: pinBox0.Text = null; pinBox1.Text = null; pinBox2.Text = null; pinBox3.Text = null; break; case 1: pinBox0.Text = "*"; pinBox1.Text = null; pinBox2.Text = null; pinBox3.Text = null; break; case 2: pinBox0.Text = "*"; pinBox1.Text = "*"; pinBox2.Text = null; pinBox3.Text = null; break; case 3: pinBox0.Text = "*"; pinBox1.Text = "*"; pinBox2.Text = "*"; pinBox3.Text = null; break; case 4: pinBox0.Text = "*"; pinBox1.Text = "*"; pinBox2.Text = "*"; pinBox3.Text = "*"; await WhenPasswordEntryFinished(); break; } } private void TrySetPassword(string password) { if (_passwordEntryFinished != null) _passwordEntryFinished.TrySetResult (password); } private async Task WhenPasswordEntryFinished() { switch (_mode) { case Mode.SetPassword: if (_previousPasscode == null) {//passcode has been entered for the first time _previousPasscode = _passcode; titleLabel.Text = _settings.Messages.ReEnterNewPasswortTitle; await AnimateSetupForSecondEntry (); } else { if (_previousPasscode != _passcode) {//passcodes do not match ChangePinBoxBallColor (UIColor.Red); await AnimateInvalidEntryAsync (); titleLabel.Text = _settings.Messages.SetPasswordTitle; } else {//passcodes match TrySetPassword (_passcode); ResetPassword (); await DeactivateWithDelay (100); } } break; default: TrySetPassword (_passcode); break; } } private void ChangePinBoxBallColor(UIColor color) { pinBox0.TextColor = color; pinBox1.TextColor = color; pinBox2.TextColor = color; pinBox3.TextColor = color; } private void ResetPinBoxes() { pinBox0.Text = null; pinBox1.Text = null; pinBox2.Text = null; pinBox3.Text = null; } private void ResetPassword() { _previousPasscode = null; _passcode = null; _fakeField.Text = null; } Task<bool?> AnimateInvalidEntryAsync() { var tcs = new TaskCompletionSource<bool?> (); ResetPassword(); SystemSound.Vibrate.PlaySystemSound(); var animation = CABasicAnimation.FromKeyPath("position"); animation.RemovedOnCompletion = true; animation.AnimationStopped += (s,e) => { ResetPinBoxes(); ChangePinBoxBallColor(_settings.Appearence.PinBoxBallColor); tcs.SetResult(null); }; animation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseOut); animation.Duration = 0.08; animation.RepeatCount = 4; animation.AutoReverses = true; animation.From = NSValue.FromCGPoint (new CGPoint (animationView.Center.X - 10.0f, animationView.Center.Y)); animation.To = NSValue.FromCGPoint(new CGPoint(animationView.Center.X + 10.0f, animationView.Center.Y)); animationView.Layer.AddAnimation(animation, "position"); return tcs.Task; } Task<bool?> AnimateValidEntryAsnyc() { var tcs = new TaskCompletionSource<bool?> (); ResetPassword(); var animation = CABasicAnimation.FromKeyPath("position"); animation.RemovedOnCompletion = true; animation.AnimationStopped += (s, e) => { ResetPinBoxes(); ChangePinBoxBallColor(_settings.Appearence.PinBoxBallColor); tcs.SetResult(null); }; animation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseOut); animation.Duration = 0.08; animation.RepeatCount = 2; animation.AutoReverses = true; animation.From = NSValue.FromCGPoint(new CGPoint(animationView.Center.X, animationView.Center.Y - 10.0f)); animation.To = NSValue.FromCGPoint(new CGPoint(animationView.Center.X, animationView.Center.Y + 10.0f)); animationView.Layer.AddAnimation(animation, "position"); return tcs.Task; } public Task<string> AnimateForAnotherEntry() { var tcs = new TaskCompletionSource<string> (); ResetPinBoxes(); var transition = new CATransition { Type = CAAnimation.TransitionPush, Subtype = CAAnimation.TransitionFromRight, Duration = 0.5, TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut), RemovedOnCompletion = true }; transition.AnimationStopped += (s, e) => { _passcode = null; _fakeField.Text = null; if(IsIPhone) _fakeField.BecomeFirstResponder(); _passwordEntryFinished = tcs; }; View.ExchangeSubview(0, 1); animationView.Layer.AddAnimation(transition, "swipe"); return tcs.Task; } private Task<bool?> AnimateSetupForSecondEntry() { var tcs = new TaskCompletionSource<bool?> (); ResetPinBoxes(); var transition = new CATransition { Type = CAAnimation.TransitionPush, Subtype = CAAnimation.TransitionFromRight, Duration = 0.5, TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut), RemovedOnCompletion = true }; transition.AnimationStopped += (s,e) => { _passcode = null; _fakeField.Text = null; if(IsIPhone) _fakeField.BecomeFirstResponder(); tcs.SetResult(null); }; View.ExchangeSubview(0, 1); animationView.Layer.AddAnimation(transition, "swipe"); return tcs.Task; } } }
using Cirrious.MvvmCross.ViewModels; using MyHealth.Client.Core.ServiceAgents; using MyHealth.Client.Core.Model; using System.Linq; using MvvmCross.Plugins.Messenger; using System.Threading.Tasks; using MyHealth.Client.Core.Helpers; using System.Collections.ObjectModel; using System.Collections.Generic; using System.Globalization; using MyHealth.Client.Core.Messages; namespace MyHealth.Client.Core.ViewModels { public class HomeViewModel : BaseViewModel { static readonly int AmountOfAppointments = 2; static readonly int AmountOfMedicines = 2; readonly IMyHealthClient _myHealthClient; bool _firstMedicineSelected = true; int _firstMedicineCountDown, _secondMedicineCountDown, _countDown; MedicineWithDoses _firstMedicine, _secondMedicine, _currentMedicine; ClinicAppointment _firstAppointment, _secondAppointment; ObservableCollection<Appointment> _appointments; Tip _tip; MvxSubscriptionToken _loggedUserInfoChangedSubscriptionToken; public bool FirstMedicineSelected { get { return _firstMedicineSelected; } set { _firstMedicineSelected = value; RaisePropertyChanged (() => FirstMedicineSelected); } } public int CountDown { get { return _countDown; } set { _countDown = value; RaisePropertyChanged (() => CountDown); } } public int FirstMedicineCountDown { get { return _firstMedicineCountDown; } set { _firstMedicineCountDown = value; RaisePropertyChanged (() => FirstMedicineCountDown); } } public int SecondMedicineCountDown { get { return _secondMedicineCountDown; } set { _secondMedicineCountDown = value; RaisePropertyChanged (() => SecondMedicineCountDown); } } public MedicineWithDoses FirstMedicine { get { return _firstMedicine; } set { _firstMedicine = value; RaisePropertyChanged (() => FirstMedicine); FirstMedicineCountDown = CountdownHelper.CalcCountDownValue (_firstMedicine); } } public MedicineWithDoses SecondMedicine { get { return _secondMedicine; } set { _secondMedicine = value; RaisePropertyChanged (() => SecondMedicine); SecondMedicineCountDown = CountdownHelper.CalcCountDownValue(_secondMedicine); } } public MedicineWithDoses CurrentMedicine { get { return _currentMedicine; } set { _currentMedicine = value; RaisePropertyChanged (() => CurrentMedicine); CountDown = CountdownHelper.CalcCountDownValue(_currentMedicine); } } public ClinicAppointment FirstAppointment { get { return _firstAppointment; } set { _firstAppointment = value; RaisePropertyChanged (() => FirstAppointment); } } public ClinicAppointment SecondAppointment { get { return _secondAppointment; } set { _secondAppointment = value; RaisePropertyChanged (() => SecondAppointment); } } public ObservableCollection<Appointment> Appointments { get { return _appointments; } set { _appointments = value; RaisePropertyChanged(() => Appointments); } } public Tip Tip { get { return _tip; } set { _tip = value; RaisePropertyChanged (() => Tip); } } public IMvxCommand ChangeToFirstMedicineCommand { get { return new MvxCommand(() => UpdateCurrentMedicine(_firstMedicine)); } } public IMvxCommand ChangeToSecondMedicineCommand { get { return new MvxCommand(() => UpdateCurrentMedicine(_secondMedicine)); } } public IMvxCommand ShowAppointmentCommand { get { return new MvxCommand(() => ShowAppointment()); } } public HomeViewModel (IMyHealthClient myHealthClient, IMvxMessenger messenger) : base(messenger) { _myHealthClient = myHealthClient; // If secutiry was enabled in Settings, I'd like this VM to load when auth. happens, // not before (to avoid data seen in background while auth. is happening) if (Settings.SecurityEnabled) { _loggedUserInfoChangedSubscriptionToken = _messenger.Subscribe<LoggedUserInfoChangedMessage> ( _ => ReloadDataAsync ().Forget ()); } } public override void Start() { base.Start(); if (!Settings.SecurityEnabled) ReloadDataAsync().Forget(); } protected override async Task InitializeAsync () { ResetBindableProperties (); var medecinesTask = RetrieveMedecinesAsync (); var appointmentsTask = RetrieveAppointmentsAsync (); var tipTask = _myHealthClient.TipsService.GetNextAsync (); await Task.WhenAll(medecinesTask, appointmentsTask, tipTask); Tip = await tipTask; } async Task RetrieveAppointmentsAsync () { var appointments = await _myHealthClient.AppointmentsService.GetPatientAppointmentsAsync (AppSettings.CurrentPatientId, AmountOfAppointments); if (appointments.Count > 0) FirstAppointment = appointments.First (); if (appointments.Count >= 2) { SecondAppointment = appointments.ElementAt(1); Appointments = new ObservableCollection<Appointment>(appointments.Skip(2)); } } async Task RetrieveMedecinesAsync () { var medicines = await _myHealthClient.MedicinesService.GetMedicinesWithDosesAsync (AppSettings.CurrentPatientId, AmountOfMedicines); if (medicines.Count > 0) FirstMedicine = medicines.First (); if (medicines.Count >= 2) SecondMedicine = medicines.ElementAt (1); if (_firstMedicine != null) CurrentMedicine = _firstMedicine; } void ResetBindableProperties () { FirstMedicine = null; SecondMedicine = null; CurrentMedicine = null; FirstAppointment = null; SecondAppointment = null; Tip = null; } void UpdateCurrentMedicine (MedicineWithDoses medicine) { CurrentMedicine = medicine; FirstMedicineSelected = _firstMedicine == medicine; } private void ShowAppointment() { var parameters = new MvxBundle(new Dictionary<string, string> { ["appointmentId"] = SecondAppointment.AppointmentId.ToString(CultureInfo.InvariantCulture) }); ShowViewModel<AppointmentDetailsViewModel>(parameters); } } }
using UnityEngine; using System.Collections; using System; using System.Runtime.Serialization.Formatters.Binary; using System.IO; public class DataValues : MonoBehaviour { public float totalHunger = 0f; public float totalThirst = 0f; public float totalMorale = 0f; public float totalFood = 200f; public float totalWater = 200f; public float totalWood = 0f; public float repair = 0f; public float maxHunger = 20f; public float maxThirst = 50f; public float maxMorale = 250f; public float maxRepair = 30f; public float maxFood = 500f; public float maxWater = 500f; public float maxWood = 500f; public int defaultDays; public static DataValues instance { get; private set; } void Awake () { instance = this; } // Update is called once per frame void Update () { } public void Save() { BinaryFormatter bf = new BinaryFormatter (); FileStream file = File.Create (Application.persistentDataPath + "/dataValues.dat"); SeasickData data = new SeasickData (); data.curDays = DayNightController.daysPast; data.totalFood = totalFood; data.totalWater = totalWater; data.totalWood = totalWood; data.repair = repair; bf.Serialize (file, data); file.Close(); int i = 1; // foreach (Pirate p in PirateManager.instance.pirates) { // file = File.Create // (Application.persistentDataPath + "/Pirates/pirate" + i + ".dat"); // // PirateData pData = new PirateData(); // // pData.hunger = p.hunger; // pData.morale = p.morale; // pData.name = p.name; // pData.curLocation = p.curLocation; // pData.thirst = p.thirst; // // bf.Serialize(file, data); // file.Close(); // i++; // } } public void Load() { if (File.Exists (Application.persistentDataPath + "/dataValues.dat")) { BinaryFormatter bf = new BinaryFormatter (); FileStream file = File.Open(Application.persistentDataPath + "/dataValues.dat", FileMode.Open); SeasickData data = (SeasickData) bf.Deserialize(file); file.Close (); DayNightController.daysPast = data.curDays; totalFood = data.totalFood; totalWater = data.totalWater; totalWood = data.totalWood; repair = data.repair; } // int i = 1; // foreach (Pirate p in PirateManager.instance.pirates) { // if(File.Exists(Application.persistentDataPath + "/Pirates/pirate" + i + ".dat")) // { // BinaryFormatter bf = new BinaryFormatter (); // FileStream file = File.Open // (Application.persistentDataPath + "/Pirates/pirate" + i + ".dat", // FileMode.Open); // PirateData pData = (PirateData) bf.Deserialize(file); // file.Close(); // // p.hunger = pData.hunger; // p.morale = pData.morale; // p.name = pData.name; // p.transform.position = pData.curLocation; // p.thirst = pData.thirst; // } // i++; // } } public void calculateTotals () { totalHunger = 0; totalThirst = 0; totalMorale = 0; foreach (Pirate e in PirateManager.instance.getPirates()) { totalHunger += e.hunger; totalThirst += e.thirst; totalMorale += e.morale; } } public void setTotalHunger (int effect) { totalHunger = checkValue(totalHunger + effect); // Debug.Log ("Total Hunger: " + totalHunger); } public void setTotalThirst (int effect) { totalThirst += effect; // Debug.Log ("Total Thirst: " + totalThirst); } public void setTotalMorale (int effect) { totalMorale = checkValue(totalMorale + effect); // Debug.Log ("Total Morale: " + totalMorale); } public void setFood (int effect) { totalFood = checkValue(totalFood + effect); // Debug.Log (totalFood); } public void setWater (int effect) { totalWater = checkValue(totalWater + effect); // Debug.Log (totalWater); } public void setWood (int effect) { totalWood = checkValue(totalWood + effect); // Debug.Log (totalWood); } public void setRepair (int effect) { repair = checkValue(repair + effect); } public float getMaxHunger () { return maxHunger; } public float getMaxThirst () { return maxThirst; } public float getMaxMorale () { return maxMorale; } void OnDestroy() { totalHunger = 0f; totalThirst = 0f; totalMorale = 0f; totalFood = 200f; totalWater = 200f; totalWood = 0f; repair = 0f; } public float checkValue(float f) { if (f <= 0f) f = 0; return f; } } [Serializable] class SeasickData { public float totalFood; public float totalWater; public float totalWood; public float repair; public int curDays; public SeasickData() { } } [Serializable] class PirateData { public float hunger; public float thirst; public float morale; public String name; public Vector3 curLocation; }
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; namespace ZXing.Common { /// <summary> /// Common string-related functions. /// </summary> /// <author>Sean Owen</author> /// <author>Alex Dupre</author> public static class StringUtils { #if (WINDOWS_PHONE || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || PORTABLE) private const String PLATFORM_DEFAULT_ENCODING = "UTF-8"; #else private static String PLATFORM_DEFAULT_ENCODING = Encoding.Default.WebName; #endif public static String SHIFT_JIS = "SJIS"; public static String GB2312 = "GB2312"; private const String EUC_JP = "EUC-JP"; private const String UTF8 = "UTF-8"; private const String ISO88591 = "ISO-8859-1"; private static readonly bool ASSUME_SHIFT_JIS = String.Compare(SHIFT_JIS, PLATFORM_DEFAULT_ENCODING, StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(EUC_JP, PLATFORM_DEFAULT_ENCODING, StringComparison.OrdinalIgnoreCase) == 0; /// <summary> /// Guesses the encoding. /// </summary> /// <param name="bytes">bytes encoding a string, whose encoding should be guessed</param> /// <param name="hints">decode hints if applicable</param> /// <returns>name of guessed encoding; at the moment will only guess one of: /// {@link #SHIFT_JIS}, {@link #UTF8}, {@link #ISO88591}, or the platform /// default encoding if none of these can possibly be correct</returns> public static String guessEncoding(byte[] bytes, IDictionary<DecodeHintType, object> hints) { if (hints != null && hints.ContainsKey(DecodeHintType.CHARACTER_SET)) { String characterSet = (String)hints[DecodeHintType.CHARACTER_SET]; if (characterSet != null) { return characterSet; } } // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, // which should be by far the most common encodings. int length = bytes.Length; bool canBeISO88591 = true; bool canBeShiftJIS = true; bool canBeUTF8 = true; int utf8BytesLeft = 0; //int utf8LowChars = 0; int utf2BytesChars = 0; int utf3BytesChars = 0; int utf4BytesChars = 0; int sjisBytesLeft = 0; //int sjisLowChars = 0; int sjisKatakanaChars = 0; //int sjisDoubleBytesChars = 0; int sjisCurKatakanaWordLength = 0; int sjisCurDoubleBytesWordLength = 0; int sjisMaxKatakanaWordLength = 0; int sjisMaxDoubleBytesWordLength = 0; //int isoLowChars = 0; //int isoHighChars = 0; int isoHighOther = 0; bool utf8bom = bytes.Length > 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF; for (int i = 0; i < length && (canBeISO88591 || canBeShiftJIS || canBeUTF8); i++) { int value = bytes[i] & 0xFF; // UTF-8 stuff if (canBeUTF8) { if (utf8BytesLeft > 0) { if ((value & 0x80) == 0) { canBeUTF8 = false; } else { utf8BytesLeft--; } } else if ((value & 0x80) != 0) { if ((value & 0x40) == 0) { canBeUTF8 = false; } else { utf8BytesLeft++; if ((value & 0x20) == 0) { utf2BytesChars++; } else { utf8BytesLeft++; if ((value & 0x10) == 0) { utf3BytesChars++; } else { utf8BytesLeft++; if ((value & 0x08) == 0) { utf4BytesChars++; } else { canBeUTF8 = false; } } } } } //else { //utf8LowChars++; //} } // ISO-8859-1 stuff if (canBeISO88591) { if (value > 0x7F && value < 0xA0) { canBeISO88591 = false; } else if (value > 0x9F) { if (value < 0xC0 || value == 0xD7 || value == 0xF7) { isoHighOther++; } //else { //isoHighChars++; //} } //else { //isoLowChars++; //} } // Shift_JIS stuff if (canBeShiftJIS) { if (sjisBytesLeft > 0) { if (value < 0x40 || value == 0x7F || value > 0xFC) { canBeShiftJIS = false; } else { sjisBytesLeft--; } } else if (value == 0x80 || value == 0xA0 || value > 0xEF) { canBeShiftJIS = false; } else if (value > 0xA0 && value < 0xE0) { sjisKatakanaChars++; sjisCurDoubleBytesWordLength = 0; sjisCurKatakanaWordLength++; if (sjisCurKatakanaWordLength > sjisMaxKatakanaWordLength) { sjisMaxKatakanaWordLength = sjisCurKatakanaWordLength; } } else if (value > 0x7F) { sjisBytesLeft++; //sjisDoubleBytesChars++; sjisCurKatakanaWordLength = 0; sjisCurDoubleBytesWordLength++; if (sjisCurDoubleBytesWordLength > sjisMaxDoubleBytesWordLength) { sjisMaxDoubleBytesWordLength = sjisCurDoubleBytesWordLength; } } else { //sjisLowChars++; sjisCurKatakanaWordLength = 0; sjisCurDoubleBytesWordLength = 0; } } } if (canBeUTF8 && utf8BytesLeft > 0) { canBeUTF8 = false; } if (canBeShiftJIS && sjisBytesLeft > 0) { canBeShiftJIS = false; } // Easy -- if there is BOM or at least 1 valid not-single byte character (and no evidence it can't be UTF-8), done if (canBeUTF8 && (utf8bom || utf2BytesChars + utf3BytesChars + utf4BytesChars > 0)) { return UTF8; } // Easy -- if assuming Shift_JIS or at least 3 valid consecutive not-ascii characters (and no evidence it can't be), done if (canBeShiftJIS && (ASSUME_SHIFT_JIS || sjisMaxKatakanaWordLength >= 3 || sjisMaxDoubleBytesWordLength >= 3)) { return SHIFT_JIS; } // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough for short words. The crude heuristic is: // - If we saw // - only two consecutive katakana chars in the whole text, or // - at least 10% of bytes that could be "upper" not-alphanumeric Latin1, // - then we conclude Shift_JIS, else ISO-8859-1 if (canBeISO88591 && canBeShiftJIS) { return (sjisMaxKatakanaWordLength == 2 && sjisKatakanaChars == 2) || isoHighOther * 10 >= length ? SHIFT_JIS : ISO88591; } // Otherwise, try in order ISO-8859-1, Shift JIS, UTF-8 and fall back to default platform encoding if (canBeISO88591) { return ISO88591; } if (canBeShiftJIS) { return SHIFT_JIS; } if (canBeUTF8) { return UTF8; } // Otherwise, we take a wild guess with platform encoding return PLATFORM_DEFAULT_ENCODING; } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the mobileanalytics-2014-06-05.normal.json service model. */ using System; using System.Collections.Generic; using Amazon.MobileAnalytics.Model; using Amazon.MobileAnalytics.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.MobileAnalytics { /// <summary> /// Implementation for accessing MobileAnalytics /// /// Amazon Mobile Analytics is a service for collecting, visualizing, and understanding /// app usage data at scale. /// </summary> public partial class AmazonMobileAnalyticsClient : AmazonServiceClient, IAmazonMobileAnalytics { #region Constructors /// <summary> /// Constructs AmazonMobileAnalyticsClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> public AmazonMobileAnalyticsClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonMobileAnalyticsConfig()) { } /// <summary> /// Constructs AmazonMobileAnalyticsClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="region">The region to connect.</param> public AmazonMobileAnalyticsClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonMobileAnalyticsConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonMobileAnalyticsClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="config">The AmazonMobileAnalyticsClient Configuration Object</param> public AmazonMobileAnalyticsClient(AmazonMobileAnalyticsConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config) { } /// <summary> /// Constructs AmazonMobileAnalyticsClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonMobileAnalyticsClient(AWSCredentials credentials) : this(credentials, new AmazonMobileAnalyticsConfig()) { } /// <summary> /// Constructs AmazonMobileAnalyticsClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonMobileAnalyticsClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonMobileAnalyticsConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonMobileAnalyticsClient with AWS Credentials and an /// AmazonMobileAnalyticsClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonMobileAnalyticsClient Configuration Object</param> public AmazonMobileAnalyticsClient(AWSCredentials credentials, AmazonMobileAnalyticsConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonMobileAnalyticsClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonMobileAnalyticsClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonMobileAnalyticsConfig()) { } /// <summary> /// Constructs AmazonMobileAnalyticsClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonMobileAnalyticsClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonMobileAnalyticsConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonMobileAnalyticsClient with AWS Access Key ID, AWS Secret Key and an /// AmazonMobileAnalyticsClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonMobileAnalyticsClient Configuration Object</param> public AmazonMobileAnalyticsClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonMobileAnalyticsConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonMobileAnalyticsClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonMobileAnalyticsClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonMobileAnalyticsConfig()) { } /// <summary> /// Constructs AmazonMobileAnalyticsClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonMobileAnalyticsClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonMobileAnalyticsConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonMobileAnalyticsClient with AWS Access Key ID, AWS Secret Key and an /// AmazonMobileAnalyticsClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonMobileAnalyticsClient Configuration Object</param> public AmazonMobileAnalyticsClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonMobileAnalyticsConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region PutEvents /// <summary> /// The PutEvents operation records one or more events. You can have up to 1,500 unique /// custom events per app, any combination of up to 40 attributes and metrics per custom /// event, and any number of attribute or metric values. /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutEvents service method.</param> /// /// <returns>The response from the PutEvents service method, as returned by MobileAnalytics.</returns> /// <exception cref="Amazon.MobileAnalytics.Model.BadRequestException"> /// An exception object returned when a request fails. /// </exception> public PutEventsResponse PutEvents(PutEventsRequest request) { var marshaller = new PutEventsRequestMarshaller(); var unmarshaller = PutEventsResponseUnmarshaller.Instance; return Invoke<PutEventsRequest,PutEventsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the PutEvents operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutEvents operation on AmazonMobileAnalyticsClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutEvents /// operation.</returns> public IAsyncResult BeginPutEvents(PutEventsRequest request, AsyncCallback callback, object state) { var marshaller = new PutEventsRequestMarshaller(); var unmarshaller = PutEventsResponseUnmarshaller.Instance; return BeginInvoke<PutEventsRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the PutEvents operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutEvents.</param> /// /// <returns>Returns a PutEventsResult from MobileAnalytics.</returns> public PutEventsResponse EndPutEvents(IAsyncResult asyncResult) { return EndInvoke<PutEventsResponse>(asyncResult); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Reflection; using System.Xml; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Region.CoreModules.World.Archiver; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using Ionic.Zlib; using GZipStream = Ionic.Zlib.GZipStream; using CompressionMode = Ionic.Zlib.CompressionMode; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { public class InventoryArchiveWriteRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Determine whether this archive will save assets. Default is true. /// </summary> public bool SaveAssets { get; set; } /// <value> /// Used to select all inventory nodes in a folder but not the folder itself /// </value> private const string STAR_WILDCARD = "*"; private InventoryArchiverModule m_module; private UserAccount m_userInfo; private string m_invPath; protected TarArchiveWriter m_archiveWriter; protected UuidGatherer m_assetGatherer; /// <value> /// We only use this to request modules /// </value> protected Scene m_scene; /// <value> /// ID of this request /// </value> protected Guid m_id; /// <value> /// Used to collect the uuids of the assets that we need to save into the archive /// </value> protected Dictionary<UUID, sbyte> m_assetUuids = new Dictionary<UUID, sbyte>(); /// <value> /// Used to collect the uuids of the users that we need to save into the archive /// </value> protected Dictionary<UUID, int> m_userUuids = new Dictionary<UUID, int>(); /// <value> /// The stream to which the inventory archive will be saved. /// </value> private Stream m_saveStream; /// <summary> /// Constructor /// </summary> public InventoryArchiveWriteRequest( Guid id, InventoryArchiverModule module, Scene scene, UserAccount userInfo, string invPath, string savePath) : this( id, module, scene, userInfo, invPath, new GZipStream(new FileStream(savePath, FileMode.Create), CompressionMode.Compress, CompressionLevel.BestCompression)) { } /// <summary> /// Constructor /// </summary> public InventoryArchiveWriteRequest( Guid id, InventoryArchiverModule module, Scene scene, UserAccount userInfo, string invPath, Stream saveStream) { m_id = id; m_module = module; m_scene = scene; m_userInfo = userInfo; m_invPath = invPath; m_saveStream = saveStream; m_assetGatherer = new UuidGatherer(m_scene.AssetService); SaveAssets = true; } protected void ReceivedAllAssets(ICollection<UUID> assetsFoundUuids, ICollection<UUID> assetsNotFoundUuids, bool timedOut) { Exception reportedException = null; bool succeeded = true; try { m_archiveWriter.Close(); } catch (Exception e) { reportedException = e; succeeded = false; } finally { m_saveStream.Close(); } if (timedOut) { succeeded = false; reportedException = new Exception("Loading assets timed out"); } m_module.TriggerInventoryArchiveSaved( m_id, succeeded, m_userInfo, m_invPath, m_saveStream, reportedException); } protected void SaveInvItem(InventoryItemBase inventoryItem, string path, Dictionary<string, object> options, IUserAccountService userAccountService) { if (options.ContainsKey("exclude")) { if (((List<String>)options["exclude"]).Contains(inventoryItem.Name) || ((List<String>)options["exclude"]).Contains(inventoryItem.ID.ToString())) { if (options.ContainsKey("verbose")) { m_log.InfoFormat( "[INVENTORY ARCHIVER]: Skipping inventory item {0} {1} at {2}", inventoryItem.Name, inventoryItem.ID, path); } return; } } if (options.ContainsKey("verbose")) m_log.InfoFormat( "[INVENTORY ARCHIVER]: Saving item {0} {1} (asset UUID {2})", inventoryItem.ID, inventoryItem.Name, inventoryItem.AssetID); string filename = path + CreateArchiveItemName(inventoryItem); // Record the creator of this item for user record purposes (which might go away soon) m_userUuids[inventoryItem.CreatorIdAsUuid] = 1; string serialization = UserInventoryItemSerializer.Serialize(inventoryItem, options, userAccountService); m_archiveWriter.WriteFile(filename, serialization); AssetType itemAssetType = (AssetType)inventoryItem.AssetType; // Don't chase down link asset items as they actually point to their target item IDs rather than an asset if (SaveAssets && itemAssetType != AssetType.Link && itemAssetType != AssetType.LinkFolder) m_assetGatherer.GatherAssetUuids(inventoryItem.AssetID, (sbyte)inventoryItem.AssetType, m_assetUuids); } /// <summary> /// Save an inventory folder /// </summary> /// <param name="inventoryFolder">The inventory folder to save</param> /// <param name="path">The path to which the folder should be saved</param> /// <param name="saveThisFolderItself">If true, save this folder itself. If false, only saves contents</param> /// <param name="options"></param> /// <param name="userAccountService"></param> protected void SaveInvFolder( InventoryFolderBase inventoryFolder, string path, bool saveThisFolderItself, Dictionary<string, object> options, IUserAccountService userAccountService) { if (options.ContainsKey("excludefolders")) { if (((List<String>)options["excludefolders"]).Contains(inventoryFolder.Name) || ((List<String>)options["excludefolders"]).Contains(inventoryFolder.ID.ToString())) { if (options.ContainsKey("verbose")) { m_log.InfoFormat( "[INVENTORY ARCHIVER]: Skipping folder {0} at {1}", inventoryFolder.Name, path); } return; } } if (options.ContainsKey("verbose")) m_log.InfoFormat("[INVENTORY ARCHIVER]: Saving folder {0}", inventoryFolder.Name); if (saveThisFolderItself) { path += CreateArchiveFolderName(inventoryFolder); // We need to make sure that we record empty folders m_archiveWriter.WriteDir(path); } InventoryCollection contents = m_scene.InventoryService.GetFolderContent(inventoryFolder.Owner, inventoryFolder.ID); foreach (InventoryFolderBase childFolder in contents.Folders) { SaveInvFolder(childFolder, path, true, options, userAccountService); } foreach (InventoryItemBase item in contents.Items) { SaveInvItem(item, path, options, userAccountService); } } /// <summary> /// Execute the inventory write request /// </summary> public void Execute(Dictionary<string, object> options, IUserAccountService userAccountService) { if (options.ContainsKey("noassets") && (bool)options["noassets"]) SaveAssets = false; try { InventoryFolderBase inventoryFolder = null; InventoryItemBase inventoryItem = null; InventoryFolderBase rootFolder = m_scene.InventoryService.GetRootFolder(m_userInfo.PrincipalID); bool saveFolderContentsOnly = false; // Eliminate double slashes and any leading / on the path. string[] components = m_invPath.Split( new string[] { InventoryFolderImpl.PATH_DELIMITER }, StringSplitOptions.RemoveEmptyEntries); int maxComponentIndex = components.Length - 1; // If the path terminates with a STAR then later on we want to archive all nodes in the folder but not the // folder itself. This may get more sophisicated later on if (maxComponentIndex >= 0 && components[maxComponentIndex] == STAR_WILDCARD) { saveFolderContentsOnly = true; maxComponentIndex--; } else if (maxComponentIndex == -1) { // If the user has just specified "/", then don't save the root "My Inventory" folder. This is // more intuitive then requiring the user to specify "/*" for this. saveFolderContentsOnly = true; } m_invPath = String.Empty; for (int i = 0; i <= maxComponentIndex; i++) { m_invPath += components[i] + InventoryFolderImpl.PATH_DELIMITER; } // Annoyingly Split actually returns the original string if the input string consists only of delimiters // Therefore if we still start with a / after the split, then we need the root folder if (m_invPath.Length == 0) { inventoryFolder = rootFolder; } else { m_invPath = m_invPath.Remove(m_invPath.LastIndexOf(InventoryFolderImpl.PATH_DELIMITER)); List<InventoryFolderBase> candidateFolders = InventoryArchiveUtils.FindFoldersByPath(m_scene.InventoryService, rootFolder, m_invPath); if (candidateFolders.Count > 0) inventoryFolder = candidateFolders[0]; } // The path may point to an item instead if (inventoryFolder == null) inventoryItem = InventoryArchiveUtils.FindItemByPath(m_scene.InventoryService, rootFolder, m_invPath); if (null == inventoryFolder && null == inventoryItem) { // We couldn't find the path indicated string errorMessage = string.Format("Aborted save. Could not find inventory path {0}", m_invPath); Exception e = new InventoryArchiverException(errorMessage); m_module.TriggerInventoryArchiveSaved(m_id, false, m_userInfo, m_invPath, m_saveStream, e); throw e; } m_archiveWriter = new TarArchiveWriter(m_saveStream); m_log.InfoFormat("[INVENTORY ARCHIVER]: Adding control file to archive."); // Write out control file. This has to be done first so that subsequent loaders will see this file first // XXX: I know this is a weak way of doing it since external non-OAR aware tar executables will not do this // not sure how to fix this though, short of going with a completely different file format. m_archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, CreateControlFile(options)); if (inventoryFolder != null) { m_log.DebugFormat( "[INVENTORY ARCHIVER]: Found folder {0} {1} at {2}", inventoryFolder.Name, inventoryFolder.ID, m_invPath == String.Empty ? InventoryFolderImpl.PATH_DELIMITER : m_invPath); //recurse through all dirs getting dirs and files SaveInvFolder(inventoryFolder, ArchiveConstants.INVENTORY_PATH, !saveFolderContentsOnly, options, userAccountService); } else if (inventoryItem != null) { m_log.DebugFormat( "[INVENTORY ARCHIVER]: Found item {0} {1} at {2}", inventoryItem.Name, inventoryItem.ID, m_invPath); SaveInvItem(inventoryItem, ArchiveConstants.INVENTORY_PATH, options, userAccountService); } // Don't put all this profile information into the archive right now. //SaveUsers(); if (SaveAssets) { m_log.DebugFormat("[INVENTORY ARCHIVER]: Saving {0} assets for items", m_assetUuids.Count); AssetsRequest ar = new AssetsRequest( new AssetsArchiver(m_archiveWriter), m_assetUuids, m_scene.AssetService, m_scene.UserAccountService, m_scene.RegionInfo.ScopeID, options, ReceivedAllAssets); Util.RunThreadNoTimeout(o => ar.Execute(), "AssetsRequest", null); } else { m_log.DebugFormat("[INVENTORY ARCHIVER]: Not saving assets since --noassets was specified"); ReceivedAllAssets(new List<UUID>(), new List<UUID>(), false); } } catch (Exception) { m_saveStream.Close(); throw; } } /// <summary> /// Save information for the users that we've collected. /// </summary> protected void SaveUsers() { m_log.InfoFormat("[INVENTORY ARCHIVER]: Saving user information for {0} users", m_userUuids.Count); foreach (UUID creatorId in m_userUuids.Keys) { // Record the creator of this item UserAccount creator = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, creatorId); if (creator != null) { m_archiveWriter.WriteFile( ArchiveConstants.USERS_PATH + creator.FirstName + " " + creator.LastName + ".xml", UserProfileSerializer.Serialize(creator.PrincipalID, creator.FirstName, creator.LastName)); } else { m_log.WarnFormat("[INVENTORY ARCHIVER]: Failed to get creator profile for {0}", creatorId); } } } /// <summary> /// Create the archive name for a particular folder. /// </summary> /// /// These names are prepended with an inventory folder's UUID so that more than one folder can have the /// same name /// /// <param name="folder"></param> /// <returns></returns> public static string CreateArchiveFolderName(InventoryFolderBase folder) { return CreateArchiveFolderName(folder.Name, folder.ID); } /// <summary> /// Create the archive name for a particular item. /// </summary> /// /// These names are prepended with an inventory item's UUID so that more than one item can have the /// same name /// /// <param name="item"></param> /// <returns></returns> public static string CreateArchiveItemName(InventoryItemBase item) { return CreateArchiveItemName(item.Name, item.ID); } /// <summary> /// Create an archive folder name given its constituent components /// </summary> /// <param name="name"></param> /// <param name="id"></param> /// <returns></returns> public static string CreateArchiveFolderName(string name, UUID id) { return string.Format( "{0}{1}{2}/", InventoryArchiveUtils.EscapeArchivePath(name), ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR, id); } /// <summary> /// Create an archive item name given its constituent components /// </summary> /// <param name="name"></param> /// <param name="id"></param> /// <returns></returns> public static string CreateArchiveItemName(string name, UUID id) { return string.Format( "{0}{1}{2}.xml", InventoryArchiveUtils.EscapeArchivePath(name), ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR, id); } /// <summary> /// Create the control file for the archive /// </summary> /// <param name="options"></param> /// <returns></returns> public string CreateControlFile(Dictionary<string, object> options) { int majorVersion, minorVersion; if (options.ContainsKey("home")) { majorVersion = 1; minorVersion = 2; } else { majorVersion = 0; minorVersion = 3; } m_log.InfoFormat("[INVENTORY ARCHIVER]: Creating version {0}.{1} IAR", majorVersion, minorVersion); StringWriter sw = new StringWriter(); XmlTextWriter xtw = new XmlTextWriter(sw); xtw.Formatting = Formatting.Indented; xtw.WriteStartDocument(); xtw.WriteStartElement("archive"); xtw.WriteAttributeString("major_version", majorVersion.ToString()); xtw.WriteAttributeString("minor_version", minorVersion.ToString()); xtw.WriteElementString("assets_included", SaveAssets.ToString()); xtw.WriteEndElement(); xtw.Flush(); xtw.Close(); String s = sw.ToString(); sw.Close(); return s; } } }
// ------------------------------------------------------------------------------ // Copyright (c) 2014 Microsoft Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // ------------------------------------------------------------------------------ namespace Microsoft.Live { using System; using System.Diagnostics; using System.Globalization; using System.Text; using Microsoft.Live.Operations; /// <summary> /// This is the class that applications use to interact with the Api service. /// </summary> public sealed partial class LiveConnectClient { #region Private Fields private const string DefaultApiEndpoint = "https://apis.live.net/v5.0"; // syncContext is used in the other partial classes. private SynchronizationContextWrapper syncContext; #endregion #region Constructors /// <summary> /// Creates a new LiveConnectClient instance. /// </summary> /// <param name="session">the session object that contains the authentication information.</param> public LiveConnectClient(LiveConnectSession session) { if (session == null) { throw new ArgumentNullException("session"); } this.Session = session; this.syncContext = SynchronizationContextWrapper.Current; #if DEBUG this.ApiEndpoint = string.IsNullOrEmpty(LiveConnectClient.ApiEndpointOverride) ? LiveConnectClient.DefaultApiEndpoint : LiveConnectClient.ApiEndpointOverride; #else this.ApiEndpoint = LiveConnectClient.DefaultApiEndpoint; #endif } #endregion #region Properties /// <summary> /// The current session object. /// </summary> public LiveConnectSession Session { get; internal set; } #if DEBUG /// <summary> /// Allows the application to override the default api endpoint. /// </summary> public static string ApiEndpointOverride { get; set; } #endif /// <summary> /// The current api endpoint. /// </summary> internal string ApiEndpoint { get; set; } #endregion #region Private, Internal Methods internal Uri GetResourceUri(string path, ApiMethod method) { try { if ((path.StartsWith("https://", StringComparison.OrdinalIgnoreCase) && !path.StartsWith(this.ApiEndpoint, StringComparison.OrdinalIgnoreCase)) || path.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) { return new Uri(path, UriKind.Absolute); } StringBuilder sb; if (path.StartsWith(this.ApiEndpoint, StringComparison.OrdinalIgnoreCase)) { sb = new StringBuilder(path); } else { sb = new StringBuilder(this.ApiEndpoint); sb = sb.AppendUrlPath(path); } var resourceUrl = new Uri(sb.ToString(), UriKind.Absolute); sb.Append(string.IsNullOrEmpty(resourceUrl.Query) ? "?" : "&"); if (method != ApiMethod.Download) { sb.AppendQueryParam(QueryParameters.SuppressResponseCodes, "true"); sb.Append("&").AppendQueryParam(QueryParameters.SuppressRedirects, "true"); } return new Uri(sb.ToString(), UriKind.Absolute); } catch (FormatException) { throw new ArgumentException( String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("UrlInvalid"), "path"), "path"); } } private static bool IsAbsolutePath(string path) { return path.StartsWith("https://", StringComparison.OrdinalIgnoreCase) || path.StartsWith("http://", StringComparison.OrdinalIgnoreCase); } private ApiOperation GetApiOperation(string path, ApiMethod method, string body) { if (path == null) { throw new ArgumentNullException("path"); } if (string.IsNullOrWhiteSpace(path)) { throw new ArgumentException("path"); } if (IsAbsolutePath(path)) { throw new ArgumentException( String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("RelativeUrlRequired"), "path"), "path"); } Uri apiUri = this.GetResourceUri(path, method); if (this.Session == null) { throw new LiveConnectException(ApiOperation.ApiClientErrorCode, ResourceHelper.GetString("UserNotLoggedIn")); } ApiOperation operation = null; switch (method) { case ApiMethod.Get: case ApiMethod.Delete: operation = new ApiOperation(this, apiUri, method, null, null); break; case ApiMethod.Post: case ApiMethod.Put: case ApiMethod.Copy: case ApiMethod.Move: if (body == null) { throw new ArgumentNullException("body"); } if (string.IsNullOrWhiteSpace(body)) { throw new ArgumentException("body"); } operation = new ApiWriteOperation(this, apiUri, method, body, null); break; default: Debug.Assert(false, "method not suppported."); break; } return operation; } #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.ComponentModel; using System.Data.Common; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace System.Data.OleDb { public sealed class OleDbCommand : DbCommand, ICloneable, IDbCommand { // command data private string _commandText; private CommandType _commandType; private int _commandTimeout = ADP.DefaultCommandTimeout; private UpdateRowSource _updatedRowSource = UpdateRowSource.Both; private bool _designTimeInvisible; private OleDbConnection _connection; private OleDbTransaction _transaction; private OleDbParameterCollection _parameters; // native information private UnsafeNativeMethods.ICommandText _icommandText; // if executing with a different CommandBehavior.KeyInfo behavior // original ICommandText must be released and a new ICommandText generated private CommandBehavior commandBehavior; private Bindings _dbBindings; internal bool canceling; private bool _isPrepared; private bool _executeQuery; private bool _trackingForClose; private bool _hasDataReader; private IntPtr _recordsAffected; private int _changeID; private int _lastChangeID; public OleDbCommand() : base() { GC.SuppressFinalize(this); } public OleDbCommand(string cmdText) : this() { CommandText = cmdText; } public OleDbCommand(string cmdText, OleDbConnection connection) : this() { CommandText = cmdText; Connection = connection; } public OleDbCommand(string cmdText, OleDbConnection connection, OleDbTransaction transaction) : this() { CommandText = cmdText; Connection = connection; Transaction = transaction; } private OleDbCommand(OleDbCommand from) : this() { // Clone CommandText = from.CommandText; CommandTimeout = from.CommandTimeout; CommandType = from.CommandType; Connection = from.Connection; DesignTimeVisible = from.DesignTimeVisible; UpdatedRowSource = from.UpdatedRowSource; Transaction = from.Transaction; OleDbParameterCollection parameters = Parameters; foreach (object parameter in from.Parameters) { parameters.Add((parameter is ICloneable) ? (parameter as ICloneable).Clone() : parameter); } } private Bindings ParameterBindings { get { return _dbBindings; } set { Bindings bindings = _dbBindings; _dbBindings = value; if ((null != bindings) && (value != bindings)) { bindings.Dispose(); } } } [DefaultValue("")] [RefreshProperties(RefreshProperties.All)] public override string CommandText { get { string value = _commandText; return ((null != value) ? value : string.Empty); } set { if (0 != ADP.SrcCompare(_commandText, value)) { PropertyChanging(); _commandText = value; } } } public override int CommandTimeout { // V1.2.3300, XXXCommand V1.0.5000 get { return _commandTimeout; } set { if (value < 0) { throw ADP.InvalidCommandTimeout(value); } if (value != _commandTimeout) { PropertyChanging(); _commandTimeout = value; } } } public void ResetCommandTimeout() { // V1.2.3300 if (ADP.DefaultCommandTimeout != _commandTimeout) { PropertyChanging(); _commandTimeout = ADP.DefaultCommandTimeout; } } [DefaultValue(System.Data.CommandType.Text)] [RefreshProperties(RefreshProperties.All)] public override CommandType CommandType { get { CommandType cmdType = _commandType; return ((0 != cmdType) ? cmdType : CommandType.Text); } set { switch (value) { // @perfnote: Enum.IsDefined case CommandType.Text: case CommandType.StoredProcedure: case CommandType.TableDirect: PropertyChanging(); _commandType = value; break; default: throw ADP.InvalidCommandType(value); } } } [DefaultValue(null)] public new OleDbConnection Connection { get { return _connection; } set { OleDbConnection connection = _connection; if (value != connection) { PropertyChanging(); ResetConnection(); _connection = value; if (null != value) { _transaction = OleDbTransaction.TransactionUpdate(_transaction); } } } } private void ResetConnection() { OleDbConnection connection = _connection; if (null != connection) { PropertyChanging(); CloseInternal(); if (_trackingForClose) { connection.RemoveWeakReference(this); _trackingForClose = false; } } _connection = null; } protected override DbConnection DbConnection { // V1.2.3300 get { return Connection; } set { Connection = (OleDbConnection)value; } } protected override DbParameterCollection DbParameterCollection { // V1.2.3300 get { return Parameters; } } protected override DbTransaction DbTransaction { // V1.2.3300 get { return Transaction; } set { Transaction = (OleDbTransaction)value; } } // @devnote: By default, the cmd object is visible on the design surface (i.e. VS7 Server Tray) // to limit the number of components that clutter the design surface, // when the DataAdapter design wizard generates the insert/update/delete commands it will // set the DesignTimeVisible property to false so that cmds won't appear as individual objects [ DefaultValue(true), DesignOnly(true), Browsable(false), EditorBrowsable(EditorBrowsableState.Never), ] public override bool DesignTimeVisible { // V1.2.3300, XXXCommand V1.0.5000 get { return !_designTimeInvisible; } set { _designTimeInvisible = !value; TypeDescriptor.Refresh(this); } } [ DesignerSerializationVisibility(DesignerSerializationVisibility.Content) ] public new OleDbParameterCollection Parameters { get { OleDbParameterCollection value = _parameters; if (null == value) { // delay the creation of the OleDbParameterCollection // until user actually uses the Parameters property value = new OleDbParameterCollection(); _parameters = value; } return value; } } private bool HasParameters() { OleDbParameterCollection value = _parameters; return (null != value) && (0 < value.Count); } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public new OleDbTransaction Transaction { get { // find the last non-zombied local transaction object, but not transactions // that may have been started after the current local transaction OleDbTransaction transaction = _transaction; while ((null != transaction) && (null == transaction.Connection)) { transaction = transaction.Parent; _transaction = transaction; } return transaction; } set { _transaction = value; } } [ DefaultValue(System.Data.UpdateRowSource.Both) ] public override UpdateRowSource UpdatedRowSource { // V1.2.3300, XXXCommand V1.0.5000 get { return _updatedRowSource; } set { switch (value) { // @perfnote: Enum.IsDefined case UpdateRowSource.None: case UpdateRowSource.OutputParameters: case UpdateRowSource.FirstReturnedRecord: case UpdateRowSource.Both: _updatedRowSource = value; break; default: throw ADP.InvalidUpdateRowSource(value); } } } // required interface, safe cast private UnsafeNativeMethods.IAccessor IAccessor() { Debug.Assert(null != _icommandText, "IAccessor: null ICommandText"); return (UnsafeNativeMethods.IAccessor)_icommandText; } // required interface, safe cast internal UnsafeNativeMethods.ICommandProperties ICommandProperties() { Debug.Assert(null != _icommandText, "ICommandProperties: null ICommandText"); return (UnsafeNativeMethods.ICommandProperties)_icommandText; } // optional interface, unsafe cast private UnsafeNativeMethods.ICommandPrepare ICommandPrepare() { Debug.Assert(null != _icommandText, "ICommandPrepare: null ICommandText"); return (_icommandText as UnsafeNativeMethods.ICommandPrepare); } // optional interface, unsafe cast private UnsafeNativeMethods.ICommandWithParameters ICommandWithParameters() { Debug.Assert(null != _icommandText, "ICommandWithParameters: null ICommandText"); UnsafeNativeMethods.ICommandWithParameters value = (_icommandText as UnsafeNativeMethods.ICommandWithParameters); if (null == value) { throw ODB.NoProviderSupportForParameters(_connection.Provider, (Exception)null); } return value; } private void CreateAccessor() { Debug.Assert(System.Data.CommandType.Text == CommandType || System.Data.CommandType.StoredProcedure == CommandType, "CreateAccessor: incorrect CommandType"); Debug.Assert(null == _dbBindings, "CreateAccessor: already has dbBindings"); Debug.Assert(HasParameters(), "CreateAccessor: unexpected, no parameter collection"); // do this first in-case the command doesn't support parameters UnsafeNativeMethods.ICommandWithParameters commandWithParameters = ICommandWithParameters(); OleDbParameterCollection collection = _parameters; OleDbParameter[] parameters = new OleDbParameter[collection.Count]; collection.CopyTo(parameters, 0); // _dbBindings is used as a switch during ExecuteCommand, so don't set it until everything okay Bindings bindings = new Bindings(parameters, collection.ChangeID); for (int i = 0; i < parameters.Length; ++i) { bindings.ForceRebind |= parameters[i].BindParameter(i, bindings); } bindings.AllocateForAccessor(null, 0, 0); ApplyParameterBindings(commandWithParameters, bindings.BindInfo); UnsafeNativeMethods.IAccessor iaccessor = IAccessor(); OleDbHResult hr = bindings.CreateAccessor(iaccessor, ODB.DBACCESSOR_PARAMETERDATA); if (hr < 0) { ProcessResults(hr); } _dbBindings = bindings; } private void ApplyParameterBindings(UnsafeNativeMethods.ICommandWithParameters commandWithParameters, tagDBPARAMBINDINFO[] bindInfo) { IntPtr[] ordinals = new IntPtr[bindInfo.Length]; for (int i = 0; i < ordinals.Length; ++i) { ordinals[i] = (IntPtr)(i + 1); } OleDbHResult hr = commandWithParameters.SetParameterInfo((IntPtr)bindInfo.Length, ordinals, bindInfo); if (hr < 0) { ProcessResults(hr); } } public override void Cancel() { unchecked { _changeID++; } UnsafeNativeMethods.ICommandText icmdtxt = _icommandText; if (null != icmdtxt) { OleDbHResult hr = OleDbHResult.S_OK; lock (icmdtxt) { // lock the object to avoid race conditions between using the object and releasing the object // after we acquire the lock, if the class has moved on don't actually call Cancel if (icmdtxt == _icommandText) { hr = icmdtxt.Cancel(); } } if (OleDbHResult.DB_E_CANTCANCEL != hr) { // if the provider can't cancel the command - don't cancel the DataReader this.canceling = true; } // since cancel is allowed to occur at anytime we can't check the connection status // since if it returns as closed then the connection will close causing the reader to close // and that would introduce the possilbility of one thread reading and one thread closing at the same time ProcessResultsNoReset(hr); } else { this.canceling = true; } } public OleDbCommand Clone() { OleDbCommand clone = new OleDbCommand(this); return clone; } object ICloneable.Clone() { return Clone(); } // Connection.Close & Connection.Dispose(true) notification internal void CloseCommandFromConnection(bool canceling) { this.canceling = canceling; CloseInternal(); _trackingForClose = false; _transaction = null; //GC.SuppressFinalize(this); } internal void CloseInternal() { Debug.Assert(null != _connection, "no connection, CloseInternal"); CloseInternalParameters(); CloseInternalCommand(); } // may be called from either // OleDbDataReader.Close/Dispose // via OleDbCommand.Dispose or OleDbConnection.Close internal void CloseFromDataReader(Bindings bindings) { if (null != bindings) { if (canceling) { bindings.Dispose(); Debug.Assert(_dbBindings == bindings, "bindings with two owners"); } else { bindings.ApplyOutputParameters(); ParameterBindings = bindings; } } _hasDataReader = false; } private void CloseInternalCommand() { unchecked { _changeID++; } this.commandBehavior = CommandBehavior.Default; _isPrepared = false; UnsafeNativeMethods.ICommandText ict = Interlocked.Exchange<UnsafeNativeMethods.ICommandText>(ref _icommandText, null); if (null != ict) { lock (ict) { // lock the object to avoid race conditions between using the object and releasing the object Marshal.ReleaseComObject(ict); } } } private void CloseInternalParameters() { Debug.Assert(null != _connection, "no connection, CloseInternalParameters"); Bindings bindings = _dbBindings; _dbBindings = null; if (null != bindings) { bindings.Dispose(); } } public new OleDbParameter CreateParameter() { return new OleDbParameter(); } protected override DbParameter CreateDbParameter() { return CreateParameter(); } protected override void Dispose(bool disposing) { if (disposing) { // release mananged objects // the DataReader takes ownership of the parameter Bindings // this way they don't get destroyed when user calls OleDbCommand.Dispose // when there is an open DataReader unchecked { _changeID++; } // in V1.0, V1.1 the Connection,Parameters,CommandText,Transaction where reset ResetConnection(); _transaction = null; _parameters = null; CommandText = null; } // release unmanaged objects base.Dispose(disposing); // notify base classes } public new OleDbDataReader ExecuteReader() { return ExecuteReader(CommandBehavior.Default); } IDataReader IDbCommand.ExecuteReader() { return ExecuteReader(CommandBehavior.Default); } public new OleDbDataReader ExecuteReader(CommandBehavior behavior) { _executeQuery = true; return ExecuteReaderInternal(behavior, ADP.ExecuteReader); } IDataReader IDbCommand.ExecuteReader(CommandBehavior behavior) { return ExecuteReader(behavior); } protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { return ExecuteReader(behavior); } private OleDbDataReader ExecuteReaderInternal(CommandBehavior behavior, string method) { OleDbDataReader dataReader = null; OleDbException nextResultsFailure = null; int state = ODB.InternalStateClosed; try { ValidateConnectionAndTransaction(method); if (0 != (CommandBehavior.SingleRow & behavior)) { // CommandBehavior.SingleRow implies CommandBehavior.SingleResult behavior |= CommandBehavior.SingleResult; } object executeResult; int resultType; switch (CommandType) { case 0: // uninitialized CommandType.Text case CommandType.Text: case CommandType.StoredProcedure: resultType = ExecuteCommand(behavior, out executeResult); break; case CommandType.TableDirect: resultType = ExecuteTableDirect(behavior, out executeResult); break; default: throw ADP.InvalidCommandType(CommandType); } if (_executeQuery) { try { dataReader = new OleDbDataReader(_connection, this, 0, this.commandBehavior); switch (resultType) { case ODB.ExecutedIMultipleResults: dataReader.InitializeIMultipleResults(executeResult); dataReader.NextResult(); break; case ODB.ExecutedIRowset: dataReader.InitializeIRowset(executeResult, ChapterHandle.DB_NULL_HCHAPTER, _recordsAffected); dataReader.BuildMetaInfo(); dataReader.HasRowsRead(); break; case ODB.ExecutedIRow: dataReader.InitializeIRow(executeResult, _recordsAffected); dataReader.BuildMetaInfo(); break; case ODB.PrepareICommandText: if (!_isPrepared) { PrepareCommandText(2); } OleDbDataReader.GenerateSchemaTable(dataReader, _icommandText, behavior); break; default: Debug.Assert(false, "ExecuteReaderInternal: unknown result type"); break; } executeResult = null; _hasDataReader = true; _connection.AddWeakReference(dataReader, OleDbReferenceCollection.DataReaderTag); // command stays in the executing state until the connection // has a datareader to track for it being closed state = ODB.InternalStateOpen; } finally { if (ODB.InternalStateOpen != state) { this.canceling = true; if (null != dataReader) { ((IDisposable)dataReader).Dispose(); dataReader = null; } } } Debug.Assert(null != dataReader, "ExecuteReader should never return a null DataReader"); } else { // optimized code path for ExecuteNonQuery to not create a OleDbDataReader object try { if (ODB.ExecutedIMultipleResults == resultType) { UnsafeNativeMethods.IMultipleResults multipleResults = (UnsafeNativeMethods.IMultipleResults)executeResult; // may cause a Connection.ResetState which closes connection nextResultsFailure = OleDbDataReader.NextResults(multipleResults, _connection, this, out _recordsAffected); } } finally { try { if (null != executeResult) { Marshal.ReleaseComObject(executeResult); executeResult = null; } CloseFromDataReader(ParameterBindings); } catch (Exception e) { // UNDONE - should not be catching all exceptions!!! if (!ADP.IsCatchableExceptionType(e)) { throw; } if (null != nextResultsFailure) { nextResultsFailure = new OleDbException(nextResultsFailure, e); } else { throw; } } } } } finally { // finally clear executing state try { if ((null == dataReader) && (ODB.InternalStateOpen != state)) { ParameterCleanup(); } } catch (Exception e) { // UNDONE - should not be catching all exceptions!!! if (!ADP.IsCatchableExceptionType(e)) { throw; } if (null != nextResultsFailure) { nextResultsFailure = new OleDbException(nextResultsFailure, e); } else { throw; } } if (null != nextResultsFailure) { throw nextResultsFailure; } } return dataReader; } private int ExecuteCommand(CommandBehavior behavior, out object executeResult) { if (InitializeCommand(behavior, false)) { if (0 != (CommandBehavior.SchemaOnly & this.commandBehavior)) { executeResult = null; return ODB.PrepareICommandText; } return ExecuteCommandText(out executeResult); } return ExecuteTableDirect(behavior, out executeResult); } // dbindings handle can't be freed until the output parameters // have been filled in which occurs after the last rowset is released // dbbindings.FreeDataHandle occurs in Cloe private int ExecuteCommandText(out object executeResult) { int retcode; tagDBPARAMS dbParams = null; RowBinding rowbinding = null; Bindings bindings = ParameterBindings; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { if (null != bindings) { // parameters may be suppressed rowbinding = bindings.RowBinding(); rowbinding.DangerousAddRef(ref mustRelease); // bindings can't be released until after last rowset is released // that is when output parameters are populated // initialize the input parameters to the input databuffer bindings.ApplyInputParameters(); dbParams = new tagDBPARAMS(); dbParams.pData = rowbinding.DangerousGetDataPtr(); dbParams.cParamSets = 1; dbParams.hAccessor = rowbinding.DangerousGetAccessorHandle(); } if ((0 == (CommandBehavior.SingleResult & this.commandBehavior)) && _connection.SupportMultipleResults()) { retcode = ExecuteCommandTextForMultpleResults(dbParams, out executeResult); } else if (0 == (CommandBehavior.SingleRow & this.commandBehavior) || !_executeQuery) { retcode = ExecuteCommandTextForSingleResult(dbParams, out executeResult); } else { retcode = ExecuteCommandTextForSingleRow(dbParams, out executeResult); } } finally { if (mustRelease) { rowbinding.DangerousRelease(); } } return retcode; } private int ExecuteCommandTextForMultpleResults(tagDBPARAMS dbParams, out object executeResult) { Debug.Assert(0 == (CommandBehavior.SingleRow & this.commandBehavior), "SingleRow implies SingleResult"); OleDbHResult hr; hr = _icommandText.Execute(ADP.PtrZero, ref ODB.IID_IMultipleResults, dbParams, out _recordsAffected, out executeResult); if (OleDbHResult.E_NOINTERFACE != hr) { ExecuteCommandTextErrorHandling(hr); return ODB.ExecutedIMultipleResults; } SafeNativeMethods.Wrapper.ClearErrorInfo(); return ExecuteCommandTextForSingleResult(dbParams, out executeResult); } private int ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, out object executeResult) { OleDbHResult hr; // (Microsoft.Jet.OLEDB.4.0 returns 0 for recordsAffected instead of -1) if (_executeQuery) { hr = _icommandText.Execute(ADP.PtrZero, ref ODB.IID_IRowset, dbParams, out _recordsAffected, out executeResult); } else { hr = _icommandText.Execute(ADP.PtrZero, ref ODB.IID_NULL, dbParams, out _recordsAffected, out executeResult); } ExecuteCommandTextErrorHandling(hr); return ODB.ExecutedIRowset; } private int ExecuteCommandTextForSingleRow(tagDBPARAMS dbParams, out object executeResult) { Debug.Assert(_executeQuery, "ExecuteNonQuery should always use ExecuteCommandTextForSingleResult"); if (_connection.SupportIRow(this)) { OleDbHResult hr; hr = _icommandText.Execute(ADP.PtrZero, ref ODB.IID_IRow, dbParams, out _recordsAffected, out executeResult); if (OleDbHResult.DB_E_NOTFOUND == hr) { SafeNativeMethods.Wrapper.ClearErrorInfo(); return ODB.ExecutedIRow; } else if (OleDbHResult.E_NOINTERFACE != hr) { ExecuteCommandTextErrorHandling(hr); return ODB.ExecutedIRow; } } SafeNativeMethods.Wrapper.ClearErrorInfo(); return ExecuteCommandTextForSingleResult(dbParams, out executeResult); } private void ExecuteCommandTextErrorHandling(OleDbHResult hr) { Exception e = OleDbConnection.ProcessResults(hr, _connection, this); if (null != e) { e = ExecuteCommandTextSpecialErrorHandling(hr, e); throw e; } } private Exception ExecuteCommandTextSpecialErrorHandling(OleDbHResult hr, Exception e) { if (((OleDbHResult.DB_E_ERRORSOCCURRED == hr) || (OleDbHResult.DB_E_BADBINDINFO == hr)) && (null != _dbBindings)) { // // this code exist to try for a better user error message by post-morten detection // of invalid parameter types being passed to a provider that doesn't understand // the user specified parameter OleDbType Debug.Assert(null != e, "missing inner exception"); StringBuilder builder = new StringBuilder(); ParameterBindings.ParameterStatus(builder); e = ODB.CommandParameterStatus(builder.ToString(), e); } return e; } public override int ExecuteNonQuery() { _executeQuery = false; ExecuteReaderInternal(CommandBehavior.Default, ADP.ExecuteNonQuery); return ADP.IntPtrToInt32(_recordsAffected); } public override object ExecuteScalar() { object value = null; _executeQuery = true; using (OleDbDataReader reader = ExecuteReaderInternal(CommandBehavior.Default, ADP.ExecuteScalar)) { if (reader.Read() && (0 < reader.FieldCount)) { value = reader.GetValue(0); } } return value; } private int ExecuteTableDirect(CommandBehavior behavior, out object executeResult) { this.commandBehavior = behavior; executeResult = null; OleDbHResult hr = OleDbHResult.S_OK; StringMemHandle sptr = null; bool mustReleaseStringHandle = false; RuntimeHelpers.PrepareConstrainedRegions(); try { sptr = new StringMemHandle(ExpandCommandText()); sptr.DangerousAddRef(ref mustReleaseStringHandle); if (mustReleaseStringHandle) { tagDBID tableID = new tagDBID(); tableID.uGuid = Guid.Empty; tableID.eKind = ODB.DBKIND_NAME; tableID.ulPropid = sptr.DangerousGetHandle(); using (IOpenRowsetWrapper iopenRowset = _connection.IOpenRowset()) { using (DBPropSet propSet = CommandPropertySets()) { if (null != propSet) { bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { propSet.DangerousAddRef(ref mustRelease); hr = iopenRowset.Value.OpenRowset(ADP.PtrZero, tableID, ADP.PtrZero, ref ODB.IID_IRowset, propSet.PropertySetCount, propSet.DangerousGetHandle(), out executeResult); } finally { if (mustRelease) { propSet.DangerousRelease(); } } if (OleDbHResult.DB_E_ERRORSOCCURRED == hr) { hr = iopenRowset.Value.OpenRowset(ADP.PtrZero, tableID, ADP.PtrZero, ref ODB.IID_IRowset, 0, IntPtr.Zero, out executeResult); } } else { hr = iopenRowset.Value.OpenRowset(ADP.PtrZero, tableID, ADP.PtrZero, ref ODB.IID_IRowset, 0, IntPtr.Zero, out executeResult); } } } } } finally { if (mustReleaseStringHandle) { sptr.DangerousRelease(); } } ProcessResults(hr); _recordsAffected = ADP.RecordsUnaffected; return ODB.ExecutedIRowset; } private string ExpandCommandText() { string cmdtxt = CommandText; if (ADP.IsEmpty(cmdtxt)) { return string.Empty; } CommandType cmdtype = CommandType; return cmdtype switch { // do nothing, already expanded by user System.Data.CommandType.Text => cmdtxt, // { ? = CALL SPROC (? ?) }, { ? = CALL SPROC }, { CALL SPRC (? ?) }, { CALL SPROC } System.Data.CommandType.StoredProcedure => ExpandStoredProcedureToText(cmdtxt), // @devnote: Provider=Jolt4.0 doesn't like quoted table names, SQOLEDB requires them // Providers should not require table names to be quoted and should guarantee that // unquoted table names correctly open the specified table, even if the table name // contains special characters, as long as the table can be unambiguously identified // without quoting. System.Data.CommandType.TableDirect => cmdtxt, _ => throw ADP.InvalidCommandType(cmdtype), }; } private string ExpandOdbcMaximumToText(string sproctext, int parameterCount) { StringBuilder builder = new StringBuilder(); if ((0 < parameterCount) && (ParameterDirection.ReturnValue == Parameters[0].Direction)) { parameterCount--; builder.Append("{ ? = CALL "); } else { builder.Append("{ CALL "); } builder.Append(sproctext); switch (parameterCount) { case 0: builder.Append(" }"); break; case 1: builder.Append("( ? ) }"); break; default: builder.Append("( ?, ?"); for (int i = 2; i < parameterCount; ++i) { builder.Append(", ?"); } builder.Append(" ) }"); break; } return builder.ToString(); } private string ExpandOdbcMinimumToText(string sproctext, int parameterCount) { //if ((0 < parameterCount) && (ParameterDirection.ReturnValue == Parameters[0].Direction)) { // Debug.Assert("doesn't support ReturnValue parameters"); //} StringBuilder builder = new StringBuilder(); builder.Append("exec "); builder.Append(sproctext); if (0 < parameterCount) { builder.Append(" ?"); for (int i = 1; i < parameterCount; ++i) { builder.Append(", ?"); } } return builder.ToString(); } private string ExpandStoredProcedureToText(string sproctext) { Debug.Assert(null != _connection, "ExpandStoredProcedureToText: null Connection"); int parameterCount = (null != _parameters) ? _parameters.Count : 0; if (0 == (ODB.DBPROPVAL_SQL_ODBC_MINIMUM & _connection.SqlSupport())) { return ExpandOdbcMinimumToText(sproctext, parameterCount); } return ExpandOdbcMaximumToText(sproctext, parameterCount); } private void ParameterCleanup() { Bindings bindings = ParameterBindings; if (null != bindings) { bindings.CleanupBindings(); } } private bool InitializeCommand(CommandBehavior behavior, bool throwifnotsupported) { Debug.Assert(null != _connection, "InitializeCommand: null OleDbConnection"); int changeid = _changeID; if ((0 != (CommandBehavior.KeyInfo & (this.commandBehavior ^ behavior))) || (_lastChangeID != changeid)) { CloseInternalParameters(); // could optimize out CloseInternalCommand(); } this.commandBehavior = behavior; changeid = _changeID; if (!PropertiesOnCommand(false)) { return false; } if ((null != _dbBindings) && _dbBindings.AreParameterBindingsInvalid(_parameters)) { CloseInternalParameters(); } // if we already having bindings - don't create the accessor // if _parameters is null - no parameters exist - don't create the collection // do we actually have parameters since the collection exists if ((null == _dbBindings) && HasParameters()) { // if we setup the parameters before setting cmdtxt then named parameters can happen CreateAccessor(); } if (_lastChangeID != changeid) { OleDbHResult hr; string commandText = ExpandCommandText(); hr = _icommandText.SetCommandText(ref ODB.DBGUID_DEFAULT, commandText); if (hr < 0) { ProcessResults(hr); } } _lastChangeID = changeid; return true; } private void PropertyChanging() { unchecked { _changeID++; } } public override void Prepare() { if (CommandType.TableDirect != CommandType) { ValidateConnectionAndTransaction(ADP.Prepare); _isPrepared = false; if (CommandType.TableDirect != CommandType) { InitializeCommand(0, true); PrepareCommandText(1); } } } private void PrepareCommandText(int expectedExecutionCount) { OleDbParameterCollection parameters = _parameters; if (null != parameters) { foreach (OleDbParameter parameter in parameters) { if (parameter.IsParameterComputed()) { // @devnote: use IsParameterComputed which is called in the normal case // only to call Prepare to throw the specialized error message // reducing the overall number of methods to actually jit parameter.Prepare(this); } } } UnsafeNativeMethods.ICommandPrepare icommandPrepare = ICommandPrepare(); if (null != icommandPrepare) { OleDbHResult hr; hr = icommandPrepare.Prepare(expectedExecutionCount); ProcessResults(hr); } // don't recompute bindings on prepared statements _isPrepared = true; } private void ProcessResults(OleDbHResult hr) { Exception e = OleDbConnection.ProcessResults(hr, _connection, this); if (null != e) { throw e; } } private void ProcessResultsNoReset(OleDbHResult hr) { Exception e = OleDbConnection.ProcessResults(hr, null, this); if (null != e) { throw e; } } internal object GetPropertyValue(Guid propertySet, int propertyID) { if (null != _icommandText) { OleDbHResult hr; tagDBPROP[] dbprops; UnsafeNativeMethods.ICommandProperties icommandProperties = ICommandProperties(); using (PropertyIDSet propidset = new PropertyIDSet(propertySet, propertyID)) { using (DBPropSet propset = new DBPropSet(icommandProperties, propidset, out hr)) { if (hr < 0) { // OLEDB Data Reader masks provider specific errors by raising "Internal Data Provider error 30." // DBPropSet c-tor will register the exception and it will be raised at GetPropertySet call in case of failure SafeNativeMethods.Wrapper.ClearErrorInfo(); } dbprops = propset.GetPropertySet(0, out propertySet); } } if (OleDbPropertyStatus.Ok == dbprops[0].dwStatus) { return dbprops[0].vValue; } return dbprops[0].dwStatus; } return OleDbPropertyStatus.NotSupported; } private bool PropertiesOnCommand(bool throwNotSupported) { if (null != _icommandText) { return true; } Debug.Assert(!_isPrepared, "null command isPrepared"); OleDbConnection connection = _connection; if (null == connection) { connection.CheckStateOpen(ODB.Properties); } if (!_trackingForClose) { _trackingForClose = true; connection.AddWeakReference(this, OleDbReferenceCollection.CommandTag); } _icommandText = connection.ICommandText(); if (null == _icommandText) { if (throwNotSupported || HasParameters()) { throw ODB.CommandTextNotSupported(connection.Provider, null); } return false; } using (DBPropSet propSet = CommandPropertySets()) { if (null != propSet) { UnsafeNativeMethods.ICommandProperties icommandProperties = ICommandProperties(); OleDbHResult hr = icommandProperties.SetProperties(propSet.PropertySetCount, propSet); if (hr < 0) { SafeNativeMethods.Wrapper.ClearErrorInfo(); } } } return true; } private DBPropSet CommandPropertySets() { DBPropSet propSet = null; bool keyInfo = (0 != (CommandBehavior.KeyInfo & this.commandBehavior)); // always set the CommandTimeout value? int count = (_executeQuery ? (keyInfo ? 4 : 2) : 1); if (0 < count) { propSet = new DBPropSet(1); tagDBPROP[] dbprops = new tagDBPROP[count]; dbprops[0] = new tagDBPROP(ODB.DBPROP_COMMANDTIMEOUT, false, CommandTimeout); if (_executeQuery) { // 'Microsoft.Jet.OLEDB.4.0' default is DBPROPVAL_AO_SEQUENTIAL dbprops[1] = new tagDBPROP(ODB.DBPROP_ACCESSORDER, false, ODB.DBPROPVAL_AO_RANDOM); if (keyInfo) { // 'Unique Rows' property required for SQLOLEDB to retrieve things like 'BaseTableName' dbprops[2] = new tagDBPROP(ODB.DBPROP_UNIQUEROWS, false, keyInfo); // otherwise 'Microsoft.Jet.OLEDB.4.0' doesn't support IColumnsRowset dbprops[3] = new tagDBPROP(ODB.DBPROP_IColumnsRowset, false, true); } } propSet.SetPropertySet(0, OleDbPropertySetGuid.Rowset, dbprops); } return propSet; } internal Bindings TakeBindingOwnerShip() { Bindings bindings = _dbBindings; _dbBindings = null; return bindings; } private void ValidateConnection(string method) { if (null == _connection) { throw ADP.ConnectionRequired(method); } _connection.CheckStateOpen(method); // user attempting to execute the command while the first dataReader hasn't returned // use the connection reference collection to see if the dataReader referencing this // command has been garbage collected or not. if (_hasDataReader) { if (_connection.HasLiveReader(this)) { throw ADP.OpenReaderExists(); } _hasDataReader = false; } } private void ValidateConnectionAndTransaction(string method) { ValidateConnection(method); _transaction = _connection.ValidateTransaction(Transaction, method); this.canceling = false; } } }
//ITEM_HOCKEYSTICK datablock AudioProfile(SlapShot) { filename = "./sounds/Hockey_SlapShot.wav"; description = AudioClosest3d; preload = false; }; datablock ItemData(HockeyStickItem) { // Basic Item Properties shapeFile = "Add-Ons/Item_Hockey/sticknohands.dts"; mass = 1; density = 0.2; elasticity = 0.2; friction = 0.6; emap = true; //gui properties uiName = "Hockey Stick"; iconName = "./hockeystick"; doColorShift = false; colorShiftColor = "1.0 0.0 0.0 1.0"; // Dynamic properties defined by the scripts image = HockeyStickImage; canDrop = true; }; datablock ShapeBaseImageData(HockeyStickImage) { // Basic Item properties shapeFile = "Add-Ons/Item_Hockey/stick.dts"; emap = true; // Specify mount point & offset for 3rd person, and eye offset // for first person rendering. mountPoint = 0; offset = "0 0 0"; // When firing from a point offset from the eye, muzzle correction // will adjust the muzzle vector to point to the eye LOS point. // Since this weapon doesn't actually fire from the muzzle point, // we need to turn this off. correctMuzzleVector = false; // Add the WeaponImage namespace as a parent, WeaponImage namespace // provides some hooks into the inventory system. className = "WeaponImage"; HockeyStick = true; // Projectile && Ammo. item = HockeyStickItem; ammo = " "; //melee particles shoot from eye node for consistancy melee = true; doRetraction = false; //raise your arm up or not armReady = true; showBricks = false; //casing = " "; doColorShift = true; colorShiftColor = HockeyStickItem.colorShiftColor; // Images have a state system which controls how the animations // are run, which sounds are played, script callbacks, etc. This // state system is downloaded to the client so that clients can // predict state changes and animate accordingly. The following // system supports basic ready->fire->reload transitions as // well as a no-ammo->dryfire idle state. // Initial start up state stateName[0] = "Activate"; stateTimeoutValue[0] = 0.0; stateTransitionOnTimeout[0] = "Ready"; stateName[1] = "Ready"; stateTransitionOnTriggerDown[1] = "PreFire"; stateAllowImageChange[1] = true; stateName[2] = "PreFire"; stateScript[2] = "onPreFire"; stateAllowImageChange[2] = true; stateTimeoutValue[2] = 0.01; stateTransitionOnTimeout[2] = "Fire"; stateName[3] = "Fire"; stateTransitionOnTimeout[3] = "CheckFire"; stateTimeoutValue[3] = 0.15; stateFire[3] = true; stateAllowImageChange[3] = true; stateSequence[3] = "Fire"; stateScript[3] = "onFire"; stateWaitForTimeout[3] = true; stateSequence[3] = "Fire"; stateName[4] = "CheckFire"; stateTransitionOnTriggerUp[4] = "StopFire"; stateName[5] = "StopFire"; stateTransitionOnTimeout[5] = "Ready"; stateTimeoutValue[5] = 0.01; stateAllowImageChange[5] = true; stateWaitForTimeout[5] = true; stateSequence[5] = "StopFire"; stateScript[5] = "onStopFire"; }; datablock ShapeBaseImageData(HockeyStickWPuckImage) { // Basic Item properties shapeFile = "Add-Ons/Item_Hockey/stickpuck.dts"; emap = true; // Specify mount point & offset for 3rd person, and eye offset // for first person rendering. mountPoint = 0; offset = "0 0 0"; // When firing from a point offset from the eye, muzzle correction // will adjust the muzzle vector to point to the eye LOS point. // Since this weapon doesn't actually fire from the muzzle point, // we need to turn this off. correctMuzzleVector = false; // Add the WeaponImage namespace as a parent, WeaponImage namespace // provides some hooks into the inventory system. className = "WeaponImage"; HockeyStickWPuck = true; // Projectile && Ammo. item = ""; ammo = " "; projectile = ''; projectileType = ''; //melee particles shoot from eye node for consistancy melee = true; doRetraction = false; //raise your arm up or not armReady = true; showBricks = false; //casing = " "; doColorShift = true; colorShiftColor = HockeyStickItem.colorShiftColor; // Images have a state system which controls how the animations // are run, which sounds are played, script callbacks, etc. This // state system is downloaded to the client so that clients can // predict state changes and animate accordingly. The following // system supports basic ready->fire->reload transitions as // well as a no-ammo->dryfire idle state. // Initial start up state stateName[0] = "Activate"; stateTimeoutValue[0] = 0.0; stateTransitionOnTimeout[0] = "Ready"; stateName[1] = "Ready"; stateTransitionOnTriggerDown[1] = "PreFire"; stateAllowImageChange[1] = true; stateName[2] = "PreFire"; stateScript[2] = "onPreFire"; stateAllowImageChange[2] = true; stateTimeoutValue[2] = 0.01; stateTransitionOnTimeout[2] = "Fire"; stateName[3] = "Fire"; stateTransitionOnTimeout[3] = "CheckFire"; stateTimeoutValue[3] = 0.15; stateFire[3] = true; stateAllowImageChange[3] = true; stateSequence[3] = "Fire"; stateScript[3] = "onFire"; stateWaitForTimeout[3] = true; stateSequence[3] = "Fire"; stateName[4] = "CheckFire"; stateTransitionOnTriggerUp[4] = "StopFire"; stateName[5] = "StopFire"; stateTransitionOnTimeout[5] = "Ready"; stateTimeoutValue[5] = 0.1; stateAllowImageChange[5] = true; stateWaitForTimeout[5] = true; stateSequence[5] = "StopFire"; stateScript[5] = "onStopFire"; }; function HockeyStickImage::onFire(%this,%obj,%slot) { %lengthOfRay = 5; %start = %obj.getEyePoint(); %end = vectorAdd(%start, vectorScale(%obj.getEyeVector(), %lengthOfRay)); %hit = containerRayCast(%start, %end, $TypeMasks::PlayerObjectType, %obj); %obj.playThread(3, shiftUp); if($Sim::Time - %obj.lsteal > 2) { if(isObject(%hit)) %image = %hit.getMountedImage(0); if(isObject(%image) && %image.HockeyStickWPuck) { %hit.playThread(3, shiftUp); %obj.playThread(3, shiftUp); serverPlay3D(Impact1BSound,%hit.getPosition); %hit.hasPuck = false; %hit.hasSportBall = false; %hit.unmountimage( 0 ); %hit.mountimage(HockeyStickImage, 0); %p = new Projectile() { dataBlock = PuckProjectile; initialVelocity = 0; initialPosition = %hit.getMuzzlePoint(%slot); sourceObject = %hit; sourceSlot = %slot; client = %hit.client; }; %obj.lsteal = $Sim::Time; } } } function HockeyStickWPuckImage::onFire(%his,%obj,%slot) { %obj.hasPuck = false; %obj.hasSportBall = false; //echo("no puck :("); serverPlay3D(SlapShot,%obj.getPosition()); %obj.unmountimage( 0 ); %obj.mountimage(HockeyStickImage, 0); %aim = %obj.getMuzzleVector(0); if(getword(%aim, 2) < 0) %aim = getWord(%aim, 0) SPC getWord(%aim, 1) SPC "0"; %posScale = vectorAdd(vectorScale(%aim,0.1 * vectorLen(%obj.getVelocity())),vectorScale(%aim,3)); %position = vectorAdd(%posScale,%obj.getPosition()); %velocity = vectorScale(%aim,60); //%velocity = vectorAdd(%velScale,vectorLen(%obj.getVelocity())); %p = new item() { dataBlock = PuckPickupItem; lifetime = 40000; position = %position; sourceObject = %obj; sourceSlot = 0; client = %obj.client; }; %p.setVelocity(%velocity); } //Loop for the puck function GreenHockeyLoop(%obj) { //echo("loop"); if(%obj.hasPuck) { //echo("green"); commandToClient(%obj.client,'BottomPrint',"<color:00FF00>__________________________________________________________________",true,true); schedule(500,0,GreenHockeyLoop,%obj); } } function RedHockeyLoop(%obj) { //echo("loop"); if(isObject(%obj.getMountedImage(0))) { if(%obj.getMountedImage(0).getname() $= "HockeyStickImage") { //echo("red"); commandToClient(%obj.client,'BottomPrint',"__________________________________________________________________",true,true); schedule(500,0,RedHockeyLoop,%obj); } } } //Say he has balls eheh function HockeyStickWPuckImage::onMount(%this,%obj) { %obj.hideNode(RHand); %obj.hideNode(LHand); %obj.hasSportBall = true; %obj.hasPuck = true; GreenHockeyLoop(%obj); parent::onMount(%this,%obj); } function HockeyStickImage::onMount(%this,%obj) { %obj.hideNode(RHand); %obj.hideNode(LHand); //echo("mount"); if(%obj.hasPuck) { //echo("u has puck"); %obj.unmountimage( 0 ); %obj.mountimage(HockeyStickWPuckImage,0); } else { RedHockeyLoop(%obj); } } function HockeyStickImage::onUnMount(%this,%obj) { %obj.unHideNode(RHand); %obj.unHideNode(LHand); } function HockeyStickWPuckImage::onUnMount(%this,%obj) { %obj.unHideNode(RHand); %obj.unHideNode(LHand); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Reflection.Internal; namespace System.Reflection.Metadata.Ecma335 { /// <summary> /// Provides extension methods for working with certain raw elements of the ECMA-335 metadata tables and heaps. /// </summary> public static class MetadataReaderExtensions { /// <summary> /// Returns the number of rows in the specified table. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="tableIndex"/> is not a valid table index.</exception> public static int GetTableRowCount(this MetadataReader reader, TableIndex tableIndex) { if (reader == null) { Throw.ArgumentNull(nameof(reader)); } if ((int)tableIndex >= TableIndexExtensions.Count) { Throw.TableIndexOutOfRange(); } return reader.TableRowCounts[(int)tableIndex]; } /// <summary> /// Returns the size of a row in the specified table. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="tableIndex"/> is not a valid table index.</exception> public static int GetTableRowSize(this MetadataReader reader, TableIndex tableIndex) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } switch (tableIndex) { case TableIndex.Module: return reader.ModuleTable.RowSize; case TableIndex.TypeRef: return reader.TypeRefTable.RowSize; case TableIndex.TypeDef: return reader.TypeDefTable.RowSize; case TableIndex.FieldPtr: return reader.FieldPtrTable.RowSize; case TableIndex.Field: return reader.FieldTable.RowSize; case TableIndex.MethodPtr: return reader.MethodPtrTable.RowSize; case TableIndex.MethodDef: return reader.MethodDefTable.RowSize; case TableIndex.ParamPtr: return reader.ParamPtrTable.RowSize; case TableIndex.Param: return reader.ParamTable.RowSize; case TableIndex.InterfaceImpl: return reader.InterfaceImplTable.RowSize; case TableIndex.MemberRef: return reader.MemberRefTable.RowSize; case TableIndex.Constant: return reader.ConstantTable.RowSize; case TableIndex.CustomAttribute: return reader.CustomAttributeTable.RowSize; case TableIndex.FieldMarshal: return reader.FieldMarshalTable.RowSize; case TableIndex.DeclSecurity: return reader.DeclSecurityTable.RowSize; case TableIndex.ClassLayout: return reader.ClassLayoutTable.RowSize; case TableIndex.FieldLayout: return reader.FieldLayoutTable.RowSize; case TableIndex.StandAloneSig: return reader.StandAloneSigTable.RowSize; case TableIndex.EventMap: return reader.EventMapTable.RowSize; case TableIndex.EventPtr: return reader.EventPtrTable.RowSize; case TableIndex.Event: return reader.EventTable.RowSize; case TableIndex.PropertyMap: return reader.PropertyMapTable.RowSize; case TableIndex.PropertyPtr: return reader.PropertyPtrTable.RowSize; case TableIndex.Property: return reader.PropertyTable.RowSize; case TableIndex.MethodSemantics: return reader.MethodSemanticsTable.RowSize; case TableIndex.MethodImpl: return reader.MethodImplTable.RowSize; case TableIndex.ModuleRef: return reader.ModuleRefTable.RowSize; case TableIndex.TypeSpec: return reader.TypeSpecTable.RowSize; case TableIndex.ImplMap: return reader.ImplMapTable.RowSize; case TableIndex.FieldRva: return reader.FieldRvaTable.RowSize; case TableIndex.EncLog: return reader.EncLogTable.RowSize; case TableIndex.EncMap: return reader.EncMapTable.RowSize; case TableIndex.Assembly: return reader.AssemblyTable.RowSize; case TableIndex.AssemblyProcessor: return reader.AssemblyProcessorTable.RowSize; case TableIndex.AssemblyOS: return reader.AssemblyOSTable.RowSize; case TableIndex.AssemblyRef: return reader.AssemblyRefTable.RowSize; case TableIndex.AssemblyRefProcessor: return reader.AssemblyRefProcessorTable.RowSize; case TableIndex.AssemblyRefOS: return reader.AssemblyRefOSTable.RowSize; case TableIndex.File: return reader.FileTable.RowSize; case TableIndex.ExportedType: return reader.ExportedTypeTable.RowSize; case TableIndex.ManifestResource: return reader.ManifestResourceTable.RowSize; case TableIndex.NestedClass: return reader.NestedClassTable.RowSize; case TableIndex.GenericParam: return reader.GenericParamTable.RowSize; case TableIndex.MethodSpec: return reader.MethodSpecTable.RowSize; case TableIndex.GenericParamConstraint: return reader.GenericParamConstraintTable.RowSize; // debug tables case TableIndex.Document: return reader.DocumentTable.RowSize; case TableIndex.MethodDebugInformation: return reader.MethodDebugInformationTable.RowSize; case TableIndex.LocalScope: return reader.LocalScopeTable.RowSize; case TableIndex.LocalVariable: return reader.LocalVariableTable.RowSize; case TableIndex.LocalConstant: return reader.LocalConstantTable.RowSize; case TableIndex.ImportScope: return reader.ImportScopeTable.RowSize; case TableIndex.StateMachineMethod: return reader.StateMachineMethodTable.RowSize; case TableIndex.CustomDebugInformation: return reader.CustomDebugInformationTable.RowSize; default: throw new ArgumentOutOfRangeException(nameof(tableIndex)); } } /// <summary> /// Returns the offset from the start of metadata to the specified table. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="tableIndex"/> is not a valid table index.</exception> public static unsafe int GetTableMetadataOffset(this MetadataReader reader, TableIndex tableIndex) { if (reader == null) { Throw.ArgumentNull(nameof(reader)); } return (int)(reader.GetTableMetadataBlock(tableIndex).Pointer - reader.Block.Pointer); } private static MemoryBlock GetTableMetadataBlock(this MetadataReader reader, TableIndex tableIndex) { Debug.Assert(reader != null); switch (tableIndex) { case TableIndex.Module: return reader.ModuleTable.Block; case TableIndex.TypeRef: return reader.TypeRefTable.Block; case TableIndex.TypeDef: return reader.TypeDefTable.Block; case TableIndex.FieldPtr: return reader.FieldPtrTable.Block; case TableIndex.Field: return reader.FieldTable.Block; case TableIndex.MethodPtr: return reader.MethodPtrTable.Block; case TableIndex.MethodDef: return reader.MethodDefTable.Block; case TableIndex.ParamPtr: return reader.ParamPtrTable.Block; case TableIndex.Param: return reader.ParamTable.Block; case TableIndex.InterfaceImpl: return reader.InterfaceImplTable.Block; case TableIndex.MemberRef: return reader.MemberRefTable.Block; case TableIndex.Constant: return reader.ConstantTable.Block; case TableIndex.CustomAttribute: return reader.CustomAttributeTable.Block; case TableIndex.FieldMarshal: return reader.FieldMarshalTable.Block; case TableIndex.DeclSecurity: return reader.DeclSecurityTable.Block; case TableIndex.ClassLayout: return reader.ClassLayoutTable.Block; case TableIndex.FieldLayout: return reader.FieldLayoutTable.Block; case TableIndex.StandAloneSig: return reader.StandAloneSigTable.Block; case TableIndex.EventMap: return reader.EventMapTable.Block; case TableIndex.EventPtr: return reader.EventPtrTable.Block; case TableIndex.Event: return reader.EventTable.Block; case TableIndex.PropertyMap: return reader.PropertyMapTable.Block; case TableIndex.PropertyPtr: return reader.PropertyPtrTable.Block; case TableIndex.Property: return reader.PropertyTable.Block; case TableIndex.MethodSemantics: return reader.MethodSemanticsTable.Block; case TableIndex.MethodImpl: return reader.MethodImplTable.Block; case TableIndex.ModuleRef: return reader.ModuleRefTable.Block; case TableIndex.TypeSpec: return reader.TypeSpecTable.Block; case TableIndex.ImplMap: return reader.ImplMapTable.Block; case TableIndex.FieldRva: return reader.FieldRvaTable.Block; case TableIndex.EncLog: return reader.EncLogTable.Block; case TableIndex.EncMap: return reader.EncMapTable.Block; case TableIndex.Assembly: return reader.AssemblyTable.Block; case TableIndex.AssemblyProcessor: return reader.AssemblyProcessorTable.Block; case TableIndex.AssemblyOS: return reader.AssemblyOSTable.Block; case TableIndex.AssemblyRef: return reader.AssemblyRefTable.Block; case TableIndex.AssemblyRefProcessor: return reader.AssemblyRefProcessorTable.Block; case TableIndex.AssemblyRefOS: return reader.AssemblyRefOSTable.Block; case TableIndex.File: return reader.FileTable.Block; case TableIndex.ExportedType: return reader.ExportedTypeTable.Block; case TableIndex.ManifestResource: return reader.ManifestResourceTable.Block; case TableIndex.NestedClass: return reader.NestedClassTable.Block; case TableIndex.GenericParam: return reader.GenericParamTable.Block; case TableIndex.MethodSpec: return reader.MethodSpecTable.Block; case TableIndex.GenericParamConstraint: return reader.GenericParamConstraintTable.Block; // debug tables case TableIndex.Document: return reader.DocumentTable.Block; case TableIndex.MethodDebugInformation: return reader.MethodDebugInformationTable.Block; case TableIndex.LocalScope: return reader.LocalScopeTable.Block; case TableIndex.LocalVariable: return reader.LocalVariableTable.Block; case TableIndex.LocalConstant: return reader.LocalConstantTable.Block; case TableIndex.ImportScope: return reader.ImportScopeTable.Block; case TableIndex.StateMachineMethod: return reader.StateMachineMethodTable.Block; case TableIndex.CustomDebugInformation: return reader.CustomDebugInformationTable.Block; default: throw new ArgumentOutOfRangeException(nameof(tableIndex)); } } /// <summary> /// Returns the size of the specified heap. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="heapIndex"/> is not a valid heap index.</exception> public static int GetHeapSize(this MetadataReader reader, HeapIndex heapIndex) { if (reader == null) { Throw.ArgumentNull(nameof(reader)); } return reader.GetMetadataBlock(heapIndex).Length; } /// <summary> /// Returns the offset from the start of metadata to the specified heap. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="heapIndex"/> is not a valid heap index.</exception> public static unsafe int GetHeapMetadataOffset(this MetadataReader reader, HeapIndex heapIndex) { if (reader == null) { Throw.ArgumentNull(nameof(reader)); } return (int)(reader.GetMetadataBlock(heapIndex).Pointer - reader.Block.Pointer); } /// <summary> /// Returns the size of the specified heap. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="heapIndex"/> is not a valid heap index.</exception> private static MemoryBlock GetMetadataBlock(this MetadataReader reader, HeapIndex heapIndex) { Debug.Assert(reader != null); switch (heapIndex) { case HeapIndex.UserString: return reader.UserStringStream.Block; case HeapIndex.String: return reader.StringStream.Block; case HeapIndex.Blob: return reader.BlobStream.Block; case HeapIndex.Guid: return reader.GuidStream.Block; default: throw new ArgumentOutOfRangeException(nameof(heapIndex)); } } /// <summary> /// Returns the a handle to the UserString that follows the given one in the UserString heap or a nil handle if it is the last one. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> public static UserStringHandle GetNextHandle(this MetadataReader reader, UserStringHandle handle) { if (reader == null) { Throw.ArgumentNull(nameof(reader)); } return reader.UserStringStream.GetNextHandle(handle); } /// <summary> /// Returns the a handle to the Blob that follows the given one in the Blob heap or a nil handle if it is the last one. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> public static BlobHandle GetNextHandle(this MetadataReader reader, BlobHandle handle) { if (reader == null) { Throw.ArgumentNull(nameof(reader)); } return reader.BlobStream.GetNextHandle(handle); } /// <summary> /// Returns the a handle to the String that follows the given one in the String heap or a nil handle if it is the last one. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> public static StringHandle GetNextHandle(this MetadataReader reader, StringHandle handle) { if (reader == null) { Throw.ArgumentNull(nameof(reader)); } return reader.StringStream.GetNextHandle(handle); } /// <summary> /// Enumerates entries of EnC log. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> public static IEnumerable<EditAndContinueLogEntry> GetEditAndContinueLogEntries(this MetadataReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } for (int rid = 1; rid <= reader.EncLogTable.NumberOfRows; rid++) { yield return new EditAndContinueLogEntry( new EntityHandle(reader.EncLogTable.GetToken(rid)), reader.EncLogTable.GetFuncCode(rid)); } } /// <summary> /// Enumerates entries of EnC map. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception> public static IEnumerable<EntityHandle> GetEditAndContinueMapEntries(this MetadataReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } for (int rid = 1; rid <= reader.EncMapTable.NumberOfRows; rid++) { yield return new EntityHandle(reader.EncMapTable.GetToken(rid)); } } /// <summary> /// Enumerate types that define one or more properties. /// </summary> /// <returns> /// The resulting sequence corresponds exactly to entries in PropertyMap table, /// i.e. n-th returned <see cref="TypeDefinitionHandle"/> is stored in n-th row of PropertyMap. /// </returns> public static IEnumerable<TypeDefinitionHandle> GetTypesWithProperties(this MetadataReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } for (int rid = 1; rid <= reader.PropertyMapTable.NumberOfRows; rid++) { yield return reader.PropertyMapTable.GetParentType(rid); } } /// <summary> /// Enumerate types that define one or more events. /// </summary> /// <returns> /// The resulting sequence corresponds exactly to entries in EventMap table, /// i.e. n-th returned <see cref="TypeDefinitionHandle"/> is stored in n-th row of EventMap. /// </returns> public static IEnumerable<TypeDefinitionHandle> GetTypesWithEvents(this MetadataReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } for (int rid = 1; rid <= reader.EventMapTable.NumberOfRows; rid++) { yield return reader.EventMapTable.GetParentType(rid); } } /// <summary> /// Given a type handle and a raw type kind found in a signature blob determines whether the target type is a value type or a reference type. /// </summary> public static SignatureTypeKind ResolveSignatureTypeKind(this MetadataReader reader, EntityHandle typeHandle, byte rawTypeKind) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } var typeKind = (SignatureTypeKind)rawTypeKind; switch (typeKind) { case SignatureTypeKind.Unknown: return SignatureTypeKind.Unknown; case SignatureTypeKind.Class: case SignatureTypeKind.ValueType: break; default: // If read from metadata by the decoder the value would have been checked already. // So it is the callers error to pass in an invalid value, not bad metadata. throw new ArgumentOutOfRangeException(nameof(rawTypeKind)); } switch (typeHandle.Kind) { case HandleKind.TypeDefinition: // WinRT projections don't apply to TypeDefs return typeKind; case HandleKind.TypeReference: var treatment = reader.GetTypeReference((TypeReferenceHandle)typeHandle).SignatureTreatment; switch (treatment) { case TypeRefSignatureTreatment.ProjectedToClass: return SignatureTypeKind.Class; case TypeRefSignatureTreatment.ProjectedToValueType: return SignatureTypeKind.ValueType; case TypeRefSignatureTreatment.None: return typeKind; default: throw ExceptionUtilities.UnexpectedValue(treatment); } case HandleKind.TypeSpecification: // TODO: https://github.com/dotnet/corefx/issues/8139 // We need more work here in differentiating case because instantiations can project class // to value type as in IReference<T> -> Nullable<T>. Unblocking Roslyn work where the differentiation // feature is not used. Note that the use-case of custom-mods will not hit this because there is no // CLASS | VALUETYPE before the modifier token and so it always comes in unresolved. return SignatureTypeKind.Unknown; default: throw new ArgumentOutOfRangeException(nameof(typeHandle), SR.UnexpectedHandleKind); } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ #if !SILVERLIGHT // ComObject #if !CLR2 using System.Linq.Expressions; #else using Microsoft.Scripting.Ast; #endif using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using ComTypes = System.Runtime.InteropServices.ComTypes; using System.Dynamic; namespace System.Management.Automation.ComInterop { /// <summary> /// An object that implements IDispatch /// /// This currently has the following issues: /// 1. If we prefer ComObjectWithTypeInfo over IDispatchComObject, then we will often not /// IDispatchComObject since implementations of IDispatch often rely on a registered type library. /// If we prefer IDispatchComObject over ComObjectWithTypeInfo, users get a non-ideal experience. /// 2. IDispatch cannot distinguish between properties and methods with 0 arguments (and non-0 /// default arguments?). So obj.foo() is ambiguous as it could mean invoking method foo, /// or it could mean invoking the function pointer returned by property foo. /// We are attempting to find whether we need to call a method or a property by examining /// the ITypeInfo associated with the IDispatch. ITypeInfo tell's use what parameters the method /// expects, is it a method or a property, what is the default property of the object, how to /// create an enumerator for collections etc. /// 3. IronPython processes the signature and converts ref arguments into return values. /// However, since the signature of a DispMethod is not available beforehand, this conversion /// is not possible. There could be other signature conversions that may be affected. How does /// VB6 deal with ref arguments and IDispatch? /// /// We also support events for IDispatch objects: /// Background: /// COM objects support events through a mechanism known as Connect Points. /// Connection Points are separate objects created off the actual COM /// object (this is to prevent circular references between event sink /// and event source). When clients want to sink events generated by /// COM object they would implement callback interfaces (aka source /// interfaces) and hand it over (advise) to the Connection Point. /// /// Implementation details: /// When IDispatchComObject.TryGetMember request is received we first check /// whether the requested member is a property or a method. If this check /// fails we will try to determine whether an event is requested. To do /// so we will do the following set of steps: /// 1. Verify the COM object implements IConnectionPointContainer /// 2. Attempt to find COM object's coclass's description /// a. Query the object for IProvideClassInfo interface. Go to 3, if found /// b. From object's IDispatch retrieve primary interface description /// c. Scan coclasses declared in object's type library. /// d. Find coclass implementing this particular primary interface /// 3. Scan coclass for all its source interfaces. /// 4. Check whether to any of the methods on the source interfaces matches /// the request name /// /// Once we determine that TryGetMember requests an event we will return /// an instance of BoundDispEvent class. This class has InPlaceAdd and /// InPlaceSubtract operators defined. Calling InPlaceAdd operator will: /// 1. An instance of ComEventSinksContainer class is created (unless /// RCW already had one). This instance is hanged off the RCW in attempt /// to bind the lifetime of event sinks to the lifetime of the RCW itself, /// meaning event sink will be collected once the RCW is collected (this /// is the same way event sinks lifetime is controlled by PIAs). /// Notice: ComEventSinksContainer contains a Finalizer which will go and /// unadvise all event sinks. /// Notice: ComEventSinksContainer is a list of ComEventSink objects. /// 2. Unless we have already created a ComEventSink for the required /// source interface, we will create and advise a new ComEventSink. Each /// ComEventSink implements a single source interface that COM object /// supports. /// 3. ComEventSink contains a map between method DISPIDs to the /// multicast delegate that will be invoked when the event is raised. /// 4. ComEventSink implements IReflect interface which is exposed as /// custom IDispatch to COM consumers. This allows us to intercept calls /// to IDispatch.Invoke and apply custom logic - in particular we will /// just find and invoke the multicast delegate corresponding to the invoked /// dispid. /// </summary> internal sealed class IDispatchComObject : ComObject, IDynamicMetaObjectProvider { private ComTypeDesc _comTypeDesc; private static readonly Dictionary<Guid, ComTypeDesc> s_cacheComTypeDesc = new Dictionary<Guid, ComTypeDesc>(); internal IDispatchComObject(IDispatch rcw) : base(rcw) { DispatchObject = rcw; } public override string ToString() { ComTypeDesc ctd = _comTypeDesc; string typeName = null; if (ctd != null) { typeName = ctd.TypeName; } if (String.IsNullOrEmpty(typeName)) { typeName = "IDispatch"; } return String.Format(CultureInfo.CurrentCulture, "{0} ({1})", RuntimeCallableWrapper.ToString(), typeName); } public ComTypeDesc ComTypeDesc { get { EnsureScanDefinedMethods(); return _comTypeDesc; } } public IDispatch DispatchObject { get; } private static int GetIDsOfNames(IDispatch dispatch, string name, out int dispId) { int[] dispIds = new int[1]; Guid emtpyRiid = Guid.Empty; int hresult = dispatch.TryGetIDsOfNames( ref emtpyRiid, new string[] { name }, 1, 0, dispIds); dispId = dispIds[0]; return hresult; } private static int Invoke(IDispatch dispatch, int memberDispId, out object result) { Guid emtpyRiid = Guid.Empty; ComTypes.DISPPARAMS dispParams = new ComTypes.DISPPARAMS(); ComTypes.EXCEPINFO excepInfo = new ComTypes.EXCEPINFO(); uint argErr; int hresult = dispatch.TryInvoke( memberDispId, ref emtpyRiid, 0, ComTypes.INVOKEKIND.INVOKE_PROPERTYGET, ref dispParams, out result, out excepInfo, out argErr); return hresult; } internal bool TryGetGetItem(out ComMethodDesc value) { ComMethodDesc methodDesc = _comTypeDesc.GetItem; if (methodDesc != null) { value = methodDesc; return true; } return SlowTryGetGetItem(out value); } private bool SlowTryGetGetItem(out ComMethodDesc value) { EnsureScanDefinedMethods(); ComMethodDesc methodDesc = _comTypeDesc.GetItem; // Without type information, we really don't know whether or not we have a property getter. if (methodDesc == null) { string name = "[PROPERTYGET, DISPID(0)]"; _comTypeDesc.EnsureGetItem(new ComMethodDesc(name, ComDispIds.DISPID_VALUE, ComTypes.INVOKEKIND.INVOKE_PROPERTYGET)); methodDesc = _comTypeDesc.GetItem; } value = methodDesc; return true; } internal bool TryGetSetItem(out ComMethodDesc value) { ComMethodDesc methodDesc = _comTypeDesc.SetItem; if (methodDesc != null) { value = methodDesc; return true; } return SlowTryGetSetItem(out value); } private bool SlowTryGetSetItem(out ComMethodDesc value) { EnsureScanDefinedMethods(); ComMethodDesc methodDesc = _comTypeDesc.SetItem; // Without type information, we really don't know whether or not we have a property setter. if (methodDesc == null) { string name = "[PROPERTYPUT, DISPID(0)]"; _comTypeDesc.EnsureSetItem(new ComMethodDesc(name, ComDispIds.DISPID_VALUE, ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT)); methodDesc = _comTypeDesc.SetItem; } value = methodDesc; return true; } internal bool TryGetMemberMethod(string name, out ComMethodDesc method) { EnsureScanDefinedMethods(); return _comTypeDesc.TryGetFunc(name, out method); } internal bool TryGetMemberEvent(string name, out ComEventDesc @event) { EnsureScanDefinedEvents(); return _comTypeDesc.TryGetEvent(name, out @event); } internal bool TryGetMemberMethodExplicit(string name, out ComMethodDesc method) { EnsureScanDefinedMethods(); int dispId; int hresult = GetIDsOfNames(DispatchObject, name, out dispId); if (hresult == ComHresults.S_OK) { ComMethodDesc cmd = new ComMethodDesc(name, dispId, ComTypes.INVOKEKIND.INVOKE_FUNC); _comTypeDesc.AddFunc(name, cmd); method = cmd; return true; } else if (hresult == ComHresults.DISP_E_UNKNOWNNAME) { method = null; return false; } else { throw Error.CouldNotGetDispId(name, String.Format(CultureInfo.InvariantCulture, "0x{0:X})", hresult)); } } internal bool TryGetPropertySetterExplicit(string name, out ComMethodDesc method, Type limitType, bool holdsNull) { EnsureScanDefinedMethods(); int dispId; int hresult = GetIDsOfNames(DispatchObject, name, out dispId); if (hresult == ComHresults.S_OK) { // we do not know whether we have put or putref here // and we will not guess and pretend we found both. ComMethodDesc put = new ComMethodDesc(name, dispId, ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT); _comTypeDesc.AddPut(name, put); ComMethodDesc putref = new ComMethodDesc(name, dispId, ComTypes.INVOKEKIND.INVOKE_PROPERTYPUTREF); _comTypeDesc.AddPutRef(name, putref); if (ComBinderHelpers.PreferPut(limitType, holdsNull)) { method = put; } else { method = putref; } return true; } else if (hresult == ComHresults.DISP_E_UNKNOWNNAME) { method = null; return false; } else { throw Error.CouldNotGetDispId(name, String.Format(CultureInfo.InvariantCulture, "0x{0:X})", hresult)); } } internal override IList<string> GetMemberNames(bool dataOnly) { EnsureScanDefinedMethods(); EnsureScanDefinedEvents(); return ComTypeDesc.GetMemberNames(dataOnly); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] internal override IList<KeyValuePair<string, object>> GetMembers(IEnumerable<string> names) { if (names == null) { names = GetMemberNames(true); } Type comType = RuntimeCallableWrapper.GetType(); var members = new List<KeyValuePair<string, object>>(); foreach (string name in names) { if (name == null) { continue; } ComMethodDesc method; if (ComTypeDesc.TryGetFunc(name, out method) && method.IsDataMember) { try { object value = comType.InvokeMember( method.Name, BindingFlags.GetProperty, null, RuntimeCallableWrapper, Utils.EmptyArray<object>(), CultureInfo.InvariantCulture ); members.Add(new KeyValuePair<string, object>(method.Name, value)); //evaluation failed for some reason. pass exception out } catch (Exception ex) { members.Add(new KeyValuePair<string, object>(method.Name, ex)); } } } return members.ToArray(); } DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) { EnsureScanDefinedMethods(); return new IDispatchMetaObject(parameter, this); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")] private static void GetFuncDescForDescIndex(ComTypes.ITypeInfo typeInfo, int funcIndex, out ComTypes.FUNCDESC funcDesc, out IntPtr funcDescHandle) { IntPtr pFuncDesc = IntPtr.Zero; typeInfo.GetFuncDesc(funcIndex, out pFuncDesc); // GetFuncDesc should never return null, this is just to be safe if (pFuncDesc == IntPtr.Zero) { throw Error.CannotRetrieveTypeInformation(); } funcDesc = (ComTypes.FUNCDESC)Marshal.PtrToStructure(pFuncDesc, typeof(ComTypes.FUNCDESC)); funcDescHandle = pFuncDesc; } private void EnsureScanDefinedEvents() { // _comTypeDesc.Events is null if we have not yet attempted // to scan the object for events. if (_comTypeDesc != null && _comTypeDesc.Events != null) { return; } // check type info in the type descriptions cache ComTypes.ITypeInfo typeInfo = ComRuntimeHelpers.GetITypeInfoFromIDispatch(DispatchObject, true); if (typeInfo == null) { _comTypeDesc = ComTypeDesc.CreateEmptyTypeDesc(); return; } ComTypes.TYPEATTR typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo); if (_comTypeDesc == null) { lock (s_cacheComTypeDesc) { if (s_cacheComTypeDesc.TryGetValue(typeAttr.guid, out _comTypeDesc) == true && _comTypeDesc.Events != null) { return; } } } ComTypeDesc typeDesc = ComTypeDesc.FromITypeInfo(typeInfo, typeAttr); ComTypes.ITypeInfo classTypeInfo = null; Dictionary<string, ComEventDesc> events = null; var cpc = RuntimeCallableWrapper as ComTypes.IConnectionPointContainer; if (cpc == null) { // No ICPC - this object does not support events events = ComTypeDesc.EmptyEvents; } else if ((classTypeInfo = GetCoClassTypeInfo(this.RuntimeCallableWrapper, typeInfo)) == null) { // no class info found - this object may support events // but we could not discover those events = ComTypeDesc.EmptyEvents; } else { events = new Dictionary<string, ComEventDesc>(); ComTypes.TYPEATTR classTypeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(classTypeInfo); for (int i = 0; i < classTypeAttr.cImplTypes; i++) { int hRefType; classTypeInfo.GetRefTypeOfImplType(i, out hRefType); ComTypes.ITypeInfo interfaceTypeInfo; classTypeInfo.GetRefTypeInfo(hRefType, out interfaceTypeInfo); ComTypes.IMPLTYPEFLAGS flags; classTypeInfo.GetImplTypeFlags(i, out flags); if ((flags & ComTypes.IMPLTYPEFLAGS.IMPLTYPEFLAG_FSOURCE) != 0) { ScanSourceInterface(interfaceTypeInfo, ref events); } } if (events.Count == 0) { events = ComTypeDesc.EmptyEvents; } } lock (s_cacheComTypeDesc) { ComTypeDesc cachedTypeDesc; if (s_cacheComTypeDesc.TryGetValue(typeAttr.guid, out cachedTypeDesc)) { _comTypeDesc = cachedTypeDesc; } else { _comTypeDesc = typeDesc; s_cacheComTypeDesc.Add(typeAttr.guid, _comTypeDesc); } _comTypeDesc.Events = events; } } private static void ScanSourceInterface(ComTypes.ITypeInfo sourceTypeInfo, ref Dictionary<string, ComEventDesc> events) { ComTypes.TYPEATTR sourceTypeAttribute = ComRuntimeHelpers.GetTypeAttrForTypeInfo(sourceTypeInfo); for (int index = 0; index < sourceTypeAttribute.cFuncs; index++) { IntPtr funcDescHandleToRelease = IntPtr.Zero; try { ComTypes.FUNCDESC funcDesc; GetFuncDescForDescIndex(sourceTypeInfo, index, out funcDesc, out funcDescHandleToRelease); // we are not interested in hidden or restricted functions for now. if ((funcDesc.wFuncFlags & (int)ComTypes.FUNCFLAGS.FUNCFLAG_FHIDDEN) != 0) { continue; } if ((funcDesc.wFuncFlags & (int)ComTypes.FUNCFLAGS.FUNCFLAG_FRESTRICTED) != 0) { continue; } string name = ComRuntimeHelpers.GetNameOfMethod(sourceTypeInfo, funcDesc.memid); name = name.ToUpper(System.Globalization.CultureInfo.InvariantCulture); // Sometimes coclass has multiple source interfaces. Usually this is caused by // adding new events and putting them on new interfaces while keeping the // old interfaces around. This may cause name collisioning which we are // resolving by keeping only the first event with the same name. if (events.ContainsKey(name) == false) { ComEventDesc eventDesc = new ComEventDesc(); eventDesc.dispid = funcDesc.memid; eventDesc.sourceIID = sourceTypeAttribute.guid; events.Add(name, eventDesc); } } finally { if (funcDescHandleToRelease != IntPtr.Zero) { sourceTypeInfo.ReleaseFuncDesc(funcDescHandleToRelease); } } } } private static ComTypes.ITypeInfo GetCoClassTypeInfo(object rcw, ComTypes.ITypeInfo typeInfo) { Debug.Assert(typeInfo != null); IProvideClassInfo provideClassInfo = rcw as IProvideClassInfo; if (provideClassInfo != null) { IntPtr typeInfoPtr = IntPtr.Zero; try { provideClassInfo.GetClassInfo(out typeInfoPtr); if (typeInfoPtr != IntPtr.Zero) { return Marshal.GetObjectForIUnknown(typeInfoPtr) as ComTypes.ITypeInfo; } } finally { if (typeInfoPtr != IntPtr.Zero) { Marshal.Release(typeInfoPtr); } } } // retrieving class information through IPCI has failed - // we can try scanning the typelib to find the coclass ComTypes.ITypeLib typeLib; int typeInfoIndex; typeInfo.GetContainingTypeLib(out typeLib, out typeInfoIndex); string typeName = ComRuntimeHelpers.GetNameOfType(typeInfo); ComTypeLibDesc typeLibDesc = ComTypeLibDesc.GetFromTypeLib(typeLib); ComTypeClassDesc coclassDesc = typeLibDesc.GetCoClassForInterface(typeName); if (coclassDesc == null) { return null; } ComTypes.ITypeInfo typeInfoCoClass; Guid coclassGuid = coclassDesc.Guid; typeLib.GetTypeInfoOfGuid(ref coclassGuid, out typeInfoCoClass); return typeInfoCoClass; } private void EnsureScanDefinedMethods() { if (_comTypeDesc != null && _comTypeDesc.Funcs != null) { return; } ComTypes.ITypeInfo typeInfo = ComRuntimeHelpers.GetITypeInfoFromIDispatch(DispatchObject, true); if (typeInfo == null) { _comTypeDesc = ComTypeDesc.CreateEmptyTypeDesc(); return; } ComTypes.TYPEATTR typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo); if (_comTypeDesc == null) { lock (s_cacheComTypeDesc) { if (s_cacheComTypeDesc.TryGetValue(typeAttr.guid, out _comTypeDesc) == true && _comTypeDesc.Funcs != null) { return; } } } if (typeAttr.typekind == ComTypes.TYPEKIND.TKIND_INTERFACE) { //We have typeinfo for custom interface. Get typeinfo for Dispatch interface. typeInfo = ComTypeInfo.GetDispatchTypeInfoFromCustomInterfaceTypeInfo(typeInfo); typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo); } if (typeAttr.typekind == ComTypes.TYPEKIND.TKIND_COCLASS) { //We have typeinfo for the COClass. Find the default interface and get typeinfo for default interface. typeInfo = ComTypeInfo.GetDispatchTypeInfoFromCoClassTypeInfo(typeInfo); typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo); } ComTypeDesc typeDesc = ComTypeDesc.FromITypeInfo(typeInfo, typeAttr); ComMethodDesc getItem = null; ComMethodDesc setItem = null; Hashtable funcs = new Hashtable(typeAttr.cFuncs); Hashtable puts = new Hashtable(); Hashtable putrefs = new Hashtable(); for (int definedFuncIndex = 0; definedFuncIndex < typeAttr.cFuncs; definedFuncIndex++) { IntPtr funcDescHandleToRelease = IntPtr.Zero; try { ComTypes.FUNCDESC funcDesc; GetFuncDescForDescIndex(typeInfo, definedFuncIndex, out funcDesc, out funcDescHandleToRelease); if ((funcDesc.wFuncFlags & (int)ComTypes.FUNCFLAGS.FUNCFLAG_FRESTRICTED) != 0) { // This function is not meant for the script user to use. continue; } ComMethodDesc method = new ComMethodDesc(typeInfo, funcDesc); string name = method.Name.ToUpper(System.Globalization.CultureInfo.InvariantCulture); if ((funcDesc.invkind & ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT) != 0) { // If there is a getter for this put, use that ReturnType as the // PropertyType. if (funcs.ContainsKey(name)) { method.InputType = ((ComMethodDesc)funcs[name]).ReturnType; } puts.Add(name, method); // for the special dispId == 0, we need to store // the method descriptor for the Do(SetItem) binder. if (method.DispId == ComDispIds.DISPID_VALUE && setItem == null) { setItem = method; } continue; } if ((funcDesc.invkind & ComTypes.INVOKEKIND.INVOKE_PROPERTYPUTREF) != 0) { // If there is a getter for this put, use that ReturnType as the // PropertyType. if (funcs.ContainsKey(name)) { method.InputType = ((ComMethodDesc)funcs[name]).ReturnType; } putrefs.Add(name, method); // for the special dispId == 0, we need to store // the method descriptor for the Do(SetItem) binder. if (method.DispId == ComDispIds.DISPID_VALUE && setItem == null) { setItem = method; } continue; } if (funcDesc.memid == ComDispIds.DISPID_NEWENUM) { funcs.Add("GETENUMERATOR", method); continue; } // If there is a setter for this put, update the InputType from our // ReturnType. if (puts.ContainsKey(name)) { ((ComMethodDesc)puts[name]).InputType = method.ReturnType; } if (putrefs.ContainsKey(name)) { ((ComMethodDesc)putrefs[name]).InputType = method.ReturnType; } funcs.Add(name, method); // for the special dispId == 0, we need to store the method descriptor // for the Do(GetItem) binder. if (funcDesc.memid == ComDispIds.DISPID_VALUE) { getItem = method; } } finally { if (funcDescHandleToRelease != IntPtr.Zero) { typeInfo.ReleaseFuncDesc(funcDescHandleToRelease); } } } lock (s_cacheComTypeDesc) { ComTypeDesc cachedTypeDesc; if (s_cacheComTypeDesc.TryGetValue(typeAttr.guid, out cachedTypeDesc)) { _comTypeDesc = cachedTypeDesc; } else { _comTypeDesc = typeDesc; s_cacheComTypeDesc.Add(typeAttr.guid, _comTypeDesc); } _comTypeDesc.Funcs = funcs; _comTypeDesc.Puts = puts; _comTypeDesc.PutRefs = putrefs; _comTypeDesc.EnsureGetItem(getItem); _comTypeDesc.EnsureSetItem(setItem); } } internal bool TryGetPropertySetter(string name, out ComMethodDesc method, Type limitType, bool holdsNull) { EnsureScanDefinedMethods(); if (ComBinderHelpers.PreferPut(limitType, holdsNull)) { return _comTypeDesc.TryGetPut(name, out method) || _comTypeDesc.TryGetPutRef(name, out method); } else { return _comTypeDesc.TryGetPutRef(name, out method) || _comTypeDesc.TryGetPut(name, out method); } } } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Runtime; using System.ServiceModel.Diagnostics; using System.ServiceModel.Diagnostics.Application; using System.Threading; namespace System.ServiceModel.Channels { public abstract class IdlingCommunicationPool<TKey, TItem> : CommunicationPool<TKey, TItem> where TKey : class where TItem : class { private TimeSpan _idleTimeout; private TimeSpan _leaseTimeout; protected IdlingCommunicationPool(int maxCount, TimeSpan idleTimeout, TimeSpan leaseTimeout) : base(maxCount) { _idleTimeout = idleTimeout; _leaseTimeout = leaseTimeout; } public TimeSpan IdleTimeout { get { return _idleTimeout; } } protected TimeSpan LeaseTimeout { get { return _leaseTimeout; } } protected override void CloseItemAsync(TItem item, TimeSpan timeout) { // Default behavior is sync. Derived classes can override. this.CloseItem(item, timeout); } protected override EndpointConnectionPool CreateEndpointConnectionPool(TKey key) { if (_idleTimeout != TimeSpan.MaxValue || _leaseTimeout != TimeSpan.MaxValue) { return new IdleTimeoutEndpointConnectionPool(this, key); } else { return base.CreateEndpointConnectionPool(key); } } protected class IdleTimeoutEndpointConnectionPool : EndpointConnectionPool { private IdleTimeoutIdleConnectionPool _connections; public IdleTimeoutEndpointConnectionPool(IdlingCommunicationPool<TKey, TItem> parent, TKey key) : base(parent, key) { _connections = new IdleTimeoutIdleConnectionPool(this, this.ThisLock); } protected override IdleConnectionPool GetIdleConnectionPool() { return _connections; } protected override void AbortItem(TItem item) { _connections.OnItemClosing(item); base.AbortItem(item); } protected override void CloseItemAsync(TItem item, TimeSpan timeout) { _connections.OnItemClosing(item); base.CloseItemAsync(item, timeout); } protected override void CloseItem(TItem item, TimeSpan timeout) { _connections.OnItemClosing(item); base.CloseItem(item, timeout); } public override void Prune(List<TItem> itemsToClose) { if (_connections != null) { _connections.Prune(itemsToClose, false); } } protected class IdleTimeoutIdleConnectionPool : PoolIdleConnectionPool { // for performance reasons we don't just blindly start a timer up to clean up // idle connections. However, if we're above a certain threshold of connections private const int timerThreshold = 1; private IdleTimeoutEndpointConnectionPool _parent; private TimeSpan _idleTimeout; private TimeSpan _leaseTimeout; private Timer _idleTimer; private static Action<object> s_onIdle; private object _thisLock; private Exception _pendingException; // Note that Take/Add/Return are already synchronized by ThisLock, so we don't need an extra // lock around our Dictionary access private Dictionary<TItem, IdlingConnectionSettings> _connectionMapping; public IdleTimeoutIdleConnectionPool(IdleTimeoutEndpointConnectionPool parent, object thisLock) : base(parent.Parent.MaxIdleConnectionPoolCount) { _parent = parent; IdlingCommunicationPool<TKey, TItem> idlingCommunicationPool = ((IdlingCommunicationPool<TKey, TItem>)parent.Parent); _idleTimeout = idlingCommunicationPool._idleTimeout; _leaseTimeout = idlingCommunicationPool._leaseTimeout; _thisLock = thisLock; _connectionMapping = new Dictionary<TItem, IdlingConnectionSettings>(); } public override bool Add(TItem connection) { this.ThrowPendingException(); bool result = base.Add(connection); if (result) { _connectionMapping.Add(connection, new IdlingConnectionSettings()); StartTimerIfNecessary(); } return result; } public override bool Return(TItem connection) { this.ThrowPendingException(); if (!_connectionMapping.ContainsKey(connection)) { return false; } bool result = base.Return(connection); if (result) { _connectionMapping[connection].LastUsage = DateTime.UtcNow; StartTimerIfNecessary(); } return result; } public override TItem Take(out bool closeItem) { this.ThrowPendingException(); DateTime now = DateTime.UtcNow; TItem item = base.Take(out closeItem); if (!closeItem) { closeItem = IdleOutConnection(item, now); } return item; } public void OnItemClosing(TItem connection) { this.ThrowPendingException(); lock (_thisLock) { _connectionMapping.Remove(connection); } } private void CancelTimer() { if (_idleTimer != null) { _idleTimer.Change(TimeSpan.FromMilliseconds(-1), TimeSpan.FromMilliseconds(-1)); } } private void StartTimerIfNecessary() { if (this.Count > timerThreshold) { if (_idleTimer == null) { if (s_onIdle == null) { s_onIdle = new Action<object>(OnIdle); } _idleTimer = new Timer(new TimerCallback(new Action<object>(s_onIdle)), this, _idleTimeout, TimeSpan.FromMilliseconds(-1)); } else { _idleTimer.Change(_idleTimeout, TimeSpan.FromMilliseconds(-1)); } } } private static void OnIdle(object state) { IdleTimeoutIdleConnectionPool pool = (IdleTimeoutIdleConnectionPool)state; pool.OnIdle(); } private void OnIdle() { List<TItem> itemsToClose = new List<TItem>(); lock (_thisLock) { try { this.Prune(itemsToClose, true); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } _pendingException = e; this.CancelTimer(); } } // allocate half the idle timeout for our graceful shutdowns TimeoutHelper timeoutHelper = new TimeoutHelper(TimeoutHelper.Divide(_idleTimeout, 2)); for (int i = 0; i < itemsToClose.Count; i++) { _parent.CloseIdleConnection(itemsToClose[i], timeoutHelper.RemainingTime()); } } public void Prune(List<TItem> itemsToClose, bool calledFromTimer) { if (!calledFromTimer) { this.ThrowPendingException(); } if (this.Count == 0) return; DateTime now = DateTime.UtcNow; bool setTimer = false; lock (_thisLock) { TItem[] connectionsCopy = new TItem[this.Count]; for (int i = 0; i < connectionsCopy.Length; i++) { bool closeItem; connectionsCopy[i] = base.Take(out closeItem); Fx.Assert(connectionsCopy[i] != null, "IdleConnections should only be modified under thisLock"); if (closeItem || IdleOutConnection(connectionsCopy[i], now)) { itemsToClose.Add(connectionsCopy[i]); connectionsCopy[i] = null; } } for (int i = 0; i < connectionsCopy.Length; i++) { if (connectionsCopy[i] != null) { bool successfulReturn = base.Return(connectionsCopy[i]); Fx.Assert(successfulReturn, "IdleConnections should only be modified under thisLock"); } } setTimer = (this.Count > 0); } if (calledFromTimer && setTimer) { _idleTimer.Change(_idleTimeout, TimeSpan.FromMilliseconds(-1)); } } private bool IdleOutConnection(TItem connection, DateTime now) { if (connection == null) { return false; } bool result = false; IdlingConnectionSettings idlingSettings = _connectionMapping[connection]; if (now > (idlingSettings.LastUsage + _idleTimeout)) { TraceConnectionIdleTimeoutExpired(); result = true; } else if (now - idlingSettings.CreationTime >= _leaseTimeout) { TraceConnectionLeaseTimeoutExpired(); result = true; } return result; } private void ThrowPendingException() { if (_pendingException != null) { lock (_thisLock) { if (_pendingException != null) { Exception exceptionToThrow = _pendingException; _pendingException = null; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exceptionToThrow); } } } } private void TraceConnectionLeaseTimeoutExpired() { if (TD.LeaseTimeoutIsEnabled()) { TD.LeaseTimeout(SR.Format(SR.TraceCodeConnectionPoolLeaseTimeoutReached, _leaseTimeout), _parent.Key.ToString()); } } private void TraceConnectionIdleTimeoutExpired() { if (TD.IdleTimeoutIsEnabled()) { TD.IdleTimeout(SR.Format(SR.TraceCodeConnectionPoolIdleTimeoutReached, _idleTimeout), _parent.Key.ToString()); } } internal class IdlingConnectionSettings { private DateTime _creationTime; private DateTime _lastUsage; public IdlingConnectionSettings() { _creationTime = DateTime.UtcNow; _lastUsage = _creationTime; } public DateTime CreationTime { get { return _creationTime; } } public DateTime LastUsage { get { return _lastUsage; } set { _lastUsage = value; } } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer; using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer { using System; public class MyClass { public int Field = 0; } public struct MyStruct { public int Number; } public enum MyEnum { First = 1, Second = 2, Third = 3 } public class MemberClass<T> { [ThreadStatic] public static int t_status; public bool? this[string p1, float p2, short[] p3] { get { MemberClass<T>.t_status = 1; return null; } set { MemberClass<T>.t_status = 2; } } public byte this[dynamic[] p1, ulong[] p2, dynamic p3] { get { MemberClass<T>.t_status = 1; return (byte)3; } set { MemberClass<T>.t_status = 2; } } public dynamic this[MyClass p1, char? p2, MyEnum[] p3] { get { MemberClass<T>.t_status = 1; return p1; } set { MemberClass<T>.t_status = 2; } } public dynamic[] this[MyClass p1, MyStruct? p2, MyEnum[] p3] { get { MemberClass<T>.t_status = 1; return new dynamic[] { p1, p2 } ; } set { MemberClass<T>.t_status = 2; } } public double[] this[float p1] { get { MemberClass<T>.t_status = 1; return new double[] { 1.4, double.Epsilon, double.NaN } ; } set { MemberClass<T>.t_status = 2; } } public dynamic this[int?[] p1] { get { MemberClass<T>.t_status = 1; return p1; } set { MemberClass<T>.t_status = 2; } } public MyClass[] this[MyEnum p1] { get { MemberClass<T>.t_status = 1; return new MyClass[] { null, new MyClass() { Field = 3 } } ; } set { MemberClass<T>.t_status = 2; } } public T this[string p1] { get { MemberClass<T>.t_status = 1; return default(T); } set { MemberClass<T>.t_status = 2; } } public MyClass this[string p1, T p2] { get { MemberClass<T>.t_status = 1; return new MyClass(); } set { MemberClass<T>.t_status = 2; } } public dynamic this[T p1] { get { MemberClass<T>.t_status = 1; return default(T); } set { MemberClass<T>.t_status = 2; } } public T this[dynamic p1, T p2] { get { MemberClass<T>.t_status = 1; return default(T); } set { MemberClass<T>.t_status = 2; } } public T this[T p1, short p2, dynamic p3, string p4] { get { MemberClass<T>.t_status = 1; return default(T); } set { MemberClass<T>.t_status = 2; } } } public class MemberClassMultipleParams<T, U, V> { public static int Status; public T this[V v, U u] { get { MemberClassMultipleParams<T, U, V>.Status = 1; return default(T); } set { MemberClassMultipleParams<T, U, V>.Status = 2; } } } public class MemberClassWithClassConstraint<T> where T : class { [ThreadStatic] public static int t_status; public int this[int x] { get { MemberClassWithClassConstraint<T>.t_status = 3; return 1; } set { MemberClassWithClassConstraint<T>.t_status = 4; } } public T this[decimal dec, dynamic d] { get { MemberClassWithClassConstraint<T>.t_status = 1; return null; } set { MemberClassWithClassConstraint<T>.t_status = 2; } } } public class MemberClassWithNewConstraint<T> where T : new() { [ThreadStatic] public static int t_status; public dynamic this[T t] { get { MemberClassWithNewConstraint<T>.t_status = 1; return new T(); } set { MemberClassWithNewConstraint<T>.t_status = 2; } } } public class MemberClassWithAnotherTypeConstraint<T, U> where T : U { public static int Status; public U this[dynamic d] { get { MemberClassWithAnotherTypeConstraint<T, U>.Status = 3; return default(U); } set { MemberClassWithAnotherTypeConstraint<T, U>.Status = 4; } } public dynamic this[int x, U u, dynamic d] { get { MemberClassWithAnotherTypeConstraint<T, U>.Status = 1; return default(T); } set { MemberClassWithAnotherTypeConstraint<T, U>.Status = 2; } } } #region Negative tests - you should not be able to construct this with a dynamic object public class C { } public interface I { } public class MemberClassWithUDClassConstraint<T> where T : C, new() { public static int Status; public C this[T t] { get { MemberClassWithUDClassConstraint<T>.Status = 1; return new T(); } set { MemberClassWithUDClassConstraint<T>.Status = 2; } } } public class MemberClassWithStructConstraint<T> where T : struct { public static int Status; public dynamic this[int x] { get { MemberClassWithStructConstraint<T>.Status = 1; return x; } set { MemberClassWithStructConstraint<T>.Status = 2; } } } public class MemberClassWithInterfaceConstraint<T> where T : I { public static int Status; public dynamic this[int x, T v] { get { MemberClassWithInterfaceConstraint<T>.Status = 1; return default(T); } set { MemberClassWithInterfaceConstraint<T>.Status = 2; } } } #endregion } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass001.genclass001 { // <Title> Tests generic class indexer used in + operator.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void PlusOperator() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass001.genclass001 dynamic dy = new MemberClass<int>(); string p1 = null; int result = dy[string.Empty] + dy[p1] + 1; Assert.Equal(1, result); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass002.genclass002 { // <Title> Tests generic class indexer used in implicit operator.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //<Expects Status=warning>\(15,20\).*CS0649</Expects> //<Expects Status=warning>\(29,20\).*CS0649</Expects> public class Test { public class ClassWithImplicitOperator { public static implicit operator EmptyClass(ClassWithImplicitOperator t1) { dynamic dy = new MemberClass<ClassWithImplicitOperator>(); ClassWithImplicitOperator p2 = t1; return dy[dy, p2]; } } public class EmptyClass { } [Fact] public static void ImplicitOperator() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass002.genclass002 ClassWithImplicitOperator target = new ClassWithImplicitOperator(); EmptyClass result = target; //implicit Assert.Null(result); Assert.Equal(1, MemberClass<ClassWithImplicitOperator>.t_status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass003.genclass003 { // <Title> Tests generic class indexer used in implicit operator.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { public class ClassWithExplicitOperator { public byte field; public static explicit operator ClassWithExplicitOperator(byte t1) { dynamic dy = new MemberClass<int>(); dynamic[] p1 = null; ulong[] p2 = null; dynamic p3 = null; dy[p1, p2, p3] = (byte)10; return new ClassWithExplicitOperator { field = dy[p1, p2, p3] }; } } [Fact] public static void ExplicitOperator() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass003.genclass003 byte b = 1; ClassWithExplicitOperator result = (ClassWithExplicitOperator)b; Assert.Equal(3, result.field); Assert.Equal(1, MemberClass<int>.t_status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass005.genclass005 { // <Title> Tests generic class indexer used in using block and using expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.IO; public class Test { [Fact] public static void DynamicCSharpRunTest() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass005.genclass005 dynamic dy = new MemberClass<string>(); dynamic dy2 = new MemberClass<bool>(); string result = null; using (MemoryStream sm = new MemoryStream()) { using (StreamWriter sw = new StreamWriter(sm)) { sw.Write((string)(dy[string.Empty] ?? "Test")); sw.Flush(); sm.Position = 0; using (StreamReader sr = new StreamReader(sm, (bool)dy2[false])) { result = sr.ReadToEnd(); } } } Assert.Equal("Test", result); Assert.Equal(1, MemberClass<string>.t_status); Assert.Equal(1, MemberClass<bool>.t_status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass006.genclass006 { // <Title> Tests generic class indexer used in the for-condition.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void ForStatement_MultipleParameters() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass006.genclass006 MemberClassMultipleParams<int, string, Test> mc = new MemberClassMultipleParams<int, string, Test>(); dynamic dy = mc; string u = null; Test v = null; int index1 = 10; for (int i = 10; i > dy[v, u]; i--) { index1--; } Assert.Equal(0, index1); Assert.Equal(1, MemberClassMultipleParams<int, string, Test>.Status); } [Fact] public void ForStatement_ClassConstraints() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass006.genclass006 dynamic dy = new MemberClassWithClassConstraint<Test>(); int index = 0; for (int i = 0; i < 10; i = i + dy[i]) { dy[i] = i; index++; } Assert.Equal(10, index); Assert.Equal(3, MemberClassWithClassConstraint<Test>.t_status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass008.genclass008 { // <Title> Tests generic class indexer used in the while/do expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DoWhileExpression() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass008.genclass008 dynamic dy = new MemberClass<int>(); string p1 = null; float p2 = 1.23f; short[] p3 = null; int index = 0; do { index++; if (index == 10) break; } while (dy[p1, p2, p3] ?? true); Assert.Equal(10, index); Assert.Equal(1, MemberClass<int>.t_status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass009.genclass009 { // <Title> Tests generic class indexer used in switch expression.</Title> // <Description> Won't fix: no dynamic in switch expression </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void SwitchExpression() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass009.genclass009 dynamic dy = new MemberClass<int>(); bool isChecked = false; switch ((int)dy["Test"]) { case 0: isChecked = true; break; default: break; } Assert.True(isChecked); Assert.Equal(1, MemberClass<int>.t_status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass010.genclass010 { // <Title> Tests generic class indexer used in switch section statement list.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void SwitchSectionStatementList() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass010.genclass010 dynamic dy = new MemberClass<int>(); string a = "Test"; MyClass p1 = new MyClass() { Field = 10 }; char? p2 = null; MyEnum[] p3 = new MyEnum[] { MyEnum.Second }; dynamic result = null; switch (a) { case "Test": dy[p1, p2, p3] = 10; result = dy[p1, p2, p3]; break; default: break; } Assert.Equal(10, ((MyClass)result).Field); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass011.genclass011 { // <Title> Tests generic class indexer used in switch default section statement list.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void SwitchDefaultSectionStatementList() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass011.genclass011 MemberClass<int> mc = new MemberClass<int>(); dynamic dy = mc; string a = "Test1"; MyClass p1 = new MyClass() { Field = 10 }; MyStruct? p2 = new MyStruct() { Number = 11 }; MyEnum[] p3 = new MyEnum[10]; dynamic[] result = null; switch (a) { case "Test": break; default: result = dy[p1, p2, p3]; dy[p1, p2, p3] = new dynamic[10]; break; } Assert.Equal(2, result.Length); Assert.Equal(10, ((MyClass)result[0]).Field); Assert.Equal(11, ((MyStruct)result[1]).Number); Assert.Equal(2, MemberClass<int>.t_status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass014.genclass014 { // <Title> Tests generic class indexer used in try/catch/finally.</Title> // <Description> // try/catch/finally that uses an anonymous method and refer two dynamic parameters. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void TryCatchFinally() { dynamic dy = new MemberClass<int>(); dynamic result = -1; bool threwException = true; try { Func<string, dynamic> func = delegate (string x) { throw new TimeoutException(dy[x].ToString()); }; result = func("Test"); threwException = false; } catch (TimeoutException e) { Assert.Equal("0", e.Message); } finally { result = dy[new int?[3]]; } Assert.True(threwException); Assert.Equal(new int?[] { null, null, null }, result); Assert.Equal(1, MemberClass<int>.t_status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass015.genclass015 { // <Title> Tests generic class indexer used in iterator that calls to a lambda expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Collections; public class Test { private static dynamic s_dy = new MemberClass<string>(); private static int s_num = 0; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic t = new Test(); foreach (MyClass[] me in t.Increment()) { if (MemberClass<string>.t_status != 1 || me.Length != 2) return 1; } return 0; } public IEnumerable Increment() { while (s_num++ < 4) { Func<MyEnum, MyClass[]> func = (MyEnum p1) => s_dy[p1]; yield return func((MyEnum)s_num); } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass016.genclass016 { // <Title> Tests generic class indexer used in object initializer inside a collection initializer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class Test { private string _field = string.Empty; [Fact] public static void ObjectInitializerInsideCollectionInitializer() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass016.genclass016 dynamic dy = new MemberClassWithClassConstraint<string>(); decimal dec = 123M; List<Test> list = new List<Test>() { new Test() { _field = dy[dec, dy] } }; Assert.Equal(1, list.Count); Assert.Null(list[0]._field); Assert.Equal(1, MemberClassWithClassConstraint<string>.t_status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass017.genclass017 { // <Title> Tests generic class indexer used in anonymous type.</Title> // <Description> // anonymous type inside a query expression that introduces dynamic variables. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Linq; using System.Collections.Generic; public class Test { private int _field; public Test() { _field = 10; } [Fact] public static void AnonymousTypeInsideQueryExpression() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass017.genclass017 List<string> list = new List<string>() { "0", "4", null, "6", "4", "4", null }; dynamic dy = new MemberClassWithAnotherTypeConstraint<string, string>(); dynamic dy2 = new MemberClassWithNewConstraint<Test>(); Test t = new Test() { _field = 1 }; var result = list.Where(p => p == dy[dy2]).Select(p => new { A = dy2[t], B = dy[dy2] }).ToList(); Assert.Equal(2, result.Count); Assert.Equal(3, MemberClassWithAnotherTypeConstraint<string, string>.Status); Assert.Equal(1, MemberClassWithNewConstraint<Test>.t_status); foreach (var m in result) { Assert.Equal(10, ((Test)m.A)._field); Assert.Null(m.B); } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass018.genclass018 { // <Title> Tests generic class indexer used in static generic method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void StaticGenericMethodBody() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass018.genclass018 StaticGenericMethod<Test>(); } private static void StaticGenericMethod<T>() { dynamic dy = new MemberClassWithNewConstraint<MyClass>(); MyClass p1 = null; dy[p1] = dy; Assert.Equal(2, MemberClassWithNewConstraint<MyClass>.t_status); dynamic p2 = dy[p1]; Assert.IsType<MyClass>(p2); Assert.Equal(1, MemberClassWithNewConstraint<MyClass>.t_status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass020.genclass020 { // <Title> Tests generic class indexer used in static method body.</Title> // <Description> // Negative // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test : C { private int _field; public Test() { _field = 11; } [Fact] public static void StaticMethodBody() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass020.genclass020 dynamic dy = new MemberClassWithUDClassConstraint<Test>(); Test t = null; dy[t] = new C(); Assert.Equal(2, MemberClassWithUDClassConstraint<Test>.Status); t = new Test() { _field = 10 }; Test result = (Test)dy[t]; Assert.Equal(11, result._field); Assert.Equal(1, MemberClassWithUDClassConstraint<Test>.Status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass021.genclass021 { // <Title> Tests generic class indexer used in static method body.</Title> // <Description> // Negative // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void StaticMethodBody() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass021.genclass021 dynamic dy = new MemberClassWithStructConstraint<char>(); dy[int.MinValue] = new Test(); Assert.Equal(2, MemberClassWithStructConstraint<char>.Status); dynamic result = dy[int.MaxValue]; Assert.Equal(int.MaxValue, result); Assert.Equal(1, MemberClassWithStructConstraint<char>.Status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass022.genclass022 { // <Title> Tests generic class indexer used in static method body.</Title> // <Description> // Negative // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test : I { public class InnerTest : Test { } [Fact] public static void StaticMethodBody() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass022.genclass022 dynamic dy = new MemberClassWithInterfaceConstraint<InnerTest>(); dy[int.MinValue, new InnerTest()] = new Test(); Assert.Equal(2, MemberClassWithInterfaceConstraint<InnerTest>.Status); dynamic result = dy[int.MaxValue, null]; Assert.Null(result); Assert.Equal(1, MemberClassWithInterfaceConstraint<InnerTest>.Status); } } //</Code> }
// ------------------------------------------------------------------------------ // Copyright (c) 2014 Microsoft Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // ------------------------------------------------------------------------------ namespace Microsoft.Live { // Reference: http://tools.ietf.org/search/draft-jones-json-web-token-00 // // JWT is made up of 3 parts: Envelope, Claims, Signature. // - Envelope - specifies the token type and signature algorithm used to produce // signature segment. This is in JSON format // - Claims - specifies claims made by the token. This is in JSON format // - Signature - Cryptographic signature use to maintain data integrity. // // To produce a JWT token: // 1. Create Envelope segment in JSON format // 2. Create Claims segment in JSON format // 3. Create signature // 4. Base64url encode each part and append together separated by "." using System; using System.Diagnostics; using System.Collections.Generic; using System.Security.Cryptography; using System.Text.RegularExpressions; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Text; using System.IO; internal class JsonWebToken { #region Properties private static readonly DataContractJsonSerializer ClaimsJsonSerializer = new DataContractJsonSerializer(typeof(JsonWebTokenClaims)); private static readonly DataContractJsonSerializer EnvelopeJsonSerializer = new DataContractJsonSerializer(typeof(JsonWebTokenEnvelope)); private static readonly UTF8Encoding UTF8Encoder = new UTF8Encoding(true, true); private static readonly SHA256Managed SHA256Provider = new SHA256Managed(); private string claimsTokenSegment; private string envelopeTokenSegment; /// <summary> /// Gets the JsonWebToken claims detail. /// </summary> public JsonWebTokenClaims Claims { get; private set; } /// <summary> /// Gets the JsonWebToken envelope data /// </summary> public JsonWebTokenEnvelope Envelope { get; private set; } /// <summary> /// Gets the token signature. /// </summary> public string Signature { get; private set; } /// <summary> /// Gets if the token is already expired. /// </summary> public bool IsExpired { get { return this.Claims.Expiration < DateTime.UtcNow; } } #endregion #region Constructors /// <summary> /// Initializes a new instance of JsonWebToken instance. /// </summary> public JsonWebToken(string token, object secrets) { var keyMap = secrets as IDictionary<int, string>; var key = secrets as string; Debug.Assert(keyMap != null || !string.IsNullOrEmpty(key)); // Get the token segments & perform validation string[] tokenSegments = this.SplitToken(token); // Decode and deserialize the claims this.claimsTokenSegment = tokenSegments[1]; this.Claims = this.GetClaimsFromTokenSegment(this.claimsTokenSegment); // Decode and deserialize the envelope this.envelopeTokenSegment = tokenSegments[0]; this.Envelope = this.GetEnvelopeFromTokenSegment(this.envelopeTokenSegment); // Get the signature this.Signature = tokenSegments[2]; if (keyMap != null) { // If a secret key map is provided, ensure that the token's KeyId exists in the key map. if (!keyMap.ContainsKey(this.Envelope.KeyId)) { throw new Exception(string.Format("Could not find key with id {0}", this.Envelope.KeyId)); } key = keyMap[this.Envelope.KeyId]; } // Validation this.ValidateEnvelope(this.Envelope); this.ValidateSignature(key); } #endregion #region Parsing Methods private JsonWebTokenClaims GetClaimsFromTokenSegment(string claimsTokenSegment) { byte[] claimsData = this.Base64UrlDecode(claimsTokenSegment); using (MemoryStream memoryStream = new MemoryStream(claimsData)) { return ClaimsJsonSerializer.ReadObject(memoryStream) as JsonWebTokenClaims; } } private JsonWebTokenEnvelope GetEnvelopeFromTokenSegment(string envelopeTokenSegment) { byte[] envelopeData = this.Base64UrlDecode(envelopeTokenSegment); using (MemoryStream memoryStream = new MemoryStream(envelopeData)) { return EnvelopeJsonSerializer.ReadObject(memoryStream) as JsonWebTokenEnvelope; } } private string[] SplitToken(string token) { // Expected token format: Envelope.Claims.Signature if (string.IsNullOrEmpty(token)) { throw new Exception("Token is empty or null."); } string[] segments = token.Split('.'); if (segments.Length != 3) { throw new Exception("Invalid token format. Expected Envelope.Claims.Signature"); } if (string.IsNullOrEmpty(segments[0])) { throw new Exception("Invalid token format. Envelope must not be empty"); } if (string.IsNullOrEmpty(segments[1])) { throw new Exception("Invalid token format. Claims must not be empty"); } if (string.IsNullOrEmpty(segments[2])) { throw new Exception("Invalid token format. Signature must not be empty"); } return segments; } #endregion #region Validation Methods private void ValidateEnvelope(JsonWebTokenEnvelope envelope) { if (envelope.Type != "JWT") { throw new Exception("Unsupported token type"); } if (envelope.Algorithm != "HS256") { throw new Exception("Unsupported crypto algorithm"); } } private void ValidateSignature(string key) { // Derive signing key, Signing key = SHA256(secret + "JWTSig") byte[] bytes = UTF8Encoder.GetBytes(key + "JWTSig"); byte[] signingKey = SHA256Provider.ComputeHash(bytes); // To Validate: // // 1. Take the bytes of the UTF-8 representation of the JWT Claim // Segment and calculate an HMAC SHA-256 MAC on them using the // shared key. // // 2. Base64url encode the previously generated HMAC as defined in this // document. // // 3. If the JWT Crypto Segment and the previously calculated value // exactly match in a character by character, case sensitive // comparison, then one has confirmation that the key was used to // generate the HMAC on the JWT and that the contents of the JWT // Claim Segment have not be tampered with. // // 4. If the validation fails, the token MUST be rejected. // UFT-8 representation of the JWT envelope.claim segment byte[] input = UTF8Encoder.GetBytes(this.envelopeTokenSegment + "." + this.claimsTokenSegment); // calculate an HMAC SHA-256 MAC using (HMACSHA256 hashProvider = new HMACSHA256(signingKey)) { byte[] myHashValue = hashProvider.ComputeHash(input); // Base64 url encode the hash string base64urlEncodedHash = this.Base64UrlEncode(myHashValue); // Now compare the two has values if (base64urlEncodedHash != this.Signature) { throw new Exception("Signature does not match."); } } } #endregion #region Base64 Encode / Decode Functions // Reference: http://tools.ietf.org/search/draft-jones-json-web-token-00 private byte[] Base64UrlDecode(string encodedSegment) { string s = encodedSegment; s = s.Replace('-', '+'); // 62nd char of encoding s = s.Replace('_', '/'); // 63rd char of encoding switch (s.Length % 4) // Pad with trailing '='s { case 0: break; // No pad chars in this case case 2: s += "=="; break; // Two pad chars case 3: s += "="; break; // One pad char default: throw new System.Exception("Illegal base64url string"); } return Convert.FromBase64String(s); // Standard base64 decoder } private string Base64UrlEncode(byte[] arg) { string s = Convert.ToBase64String(arg); // Standard base64 encoder s = s.Split('=')[0]; // Remove any trailing '='s s = s.Replace('+', '-'); // 62nd char of encoding s = s.Replace('/', '_'); // 63rd char of encoding return s; } #endregion } }
using System; using System.Text; using System.Xml; using NUnit.Framework; using SIL.TestUtilities; using SIL.WritingSystems.Migration; using SIL.WritingSystems.Migration.WritingSystemsLdmlV0To1Migration; using SIL.Xml; namespace SIL.WritingSystems.Tests.Migration { [TestFixture] public class IcuRulesParserTests { private IcuRulesParser _icuParser; private XmlWriter _writer; private StringBuilder _xmlText; [SetUp] public void SetUp() { _icuParser = new IcuRulesParser(); _xmlText = new StringBuilder(); _writer = XmlWriter.Create(_xmlText, CanonicalXmlSettings.CreateXmlWriterSettings(ConformanceLevel.Fragment)); } private string Environment_OutputString() { _writer.Close(); return _xmlText.ToString(); } [Test] public void EmptyString_ProducesNoRules() { _icuParser.WriteIcuRules(_writer, string.Empty); string result = Environment_OutputString(); Assert.AreEqual("", result); } [Test] public void WhiteSpace_ProducesNoRules() { _icuParser.WriteIcuRules(_writer, " \n\t"); string result = Environment_OutputString(); Assert.AreEqual("", result); } [Test] public void Reset_ProducesResetNode() { _icuParser.WriteIcuRules(_writer, "&a"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='a']" ); } [Test] public void PrimaryDifference_ProducesCorrectXml() { _icuParser.WriteIcuRules(_writer, "&a < b"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='a']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/p[text()='b']" ); } [Test] public void SecondaryDifference_ProducesCorrectXml() { _icuParser.WriteIcuRules(_writer, "&a << b"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='a']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/s[text()='b']" ); } [Test] public void TertiaryDifference_ProducesCorrectXml() { _icuParser.WriteIcuRules(_writer, "&a <<< b"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='a']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/t[text()='b']" ); } [Test] public void NoDifference_ProducesCorrectXml() { _icuParser.WriteIcuRules(_writer, "&a = b"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='a']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/i[text()='b']" ); } [Test] public void Prefix_ProducesCorrectXml() { _icuParser.WriteIcuRules(_writer, "&a < b|c"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='a']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/x/context[text()='b']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/x/p[text()='c']" ); } [Test] public void Expansion_ProducesCorrectXml() { _icuParser.WriteIcuRules(_writer, "&a < b/ c"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='a']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/x/p[text()='b']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/x/extend[text()='c']" ); } [Test] public void PrefixAndExpansion_ProducesCorrectXml() { _icuParser.WriteIcuRules(_writer, "&a < b|c/d"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='a']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/x/context[text()='b']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/x/p[text()='c']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/x/extend[text()='d']" ); } [Test] public void Contraction_ProducesCorrectXml() { _icuParser.WriteIcuRules(_writer, "&ab < cd"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='ab']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset/following-sibling::p[text()='cd']" ); } [Test] public void EscapedUnicode_ProducesCorrectXml() { //Fieldworks issue LT-11999 _icuParser.WriteIcuRules(_writer, "&\\U00008000 < \\u0061"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='\\U00008000']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset/following-sibling::p[text()='\\u0061']" ); } [Test] public void MultiplePrimaryDifferences_ProducesOptimizedXml() { _icuParser.WriteIcuRules(_writer, "&a < b<c"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='a']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/pc[text()='bc']" ); // Assert.AreEqual("<rules><reset>a</reset><pc>bc</pc></rules>", _xmlText.ToString()); } [Test] public void MultipleSecondaryDifferences_ProducesOptimizedXml() { _icuParser.WriteIcuRules(_writer, "&a << b<<c"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='a']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/sc[text()='bc']" ); // Assert.AreEqual("<rules><reset>a</reset><sc>bc</sc></rules>", _xmlText.ToString()); } [Test] public void MultipleTertiaryDifferences_ProducesOptimizedXml() { _icuParser.WriteIcuRules(_writer, "&a <<< b<<<c"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='a']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/tc[text()='bc']" ); // Assert.AreEqual("<rules><reset>a</reset><tc>bc</tc></rules>", _xmlText.ToString()); } [Test] public void MultipleNoDifferences_ProducesOptimizedXml() { _icuParser.WriteIcuRules(_writer, "&a = b=c"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='a']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/ic[text()='bc']" ); // Assert.AreEqual("<rules><reset>a</reset><ic>bc</ic></rules>", _xmlText.ToString()); } [Test] public void FirstTertiaryIgnorable_ProducesCorrectIndirectNode() { _icuParser.WriteIcuRules(_writer, "&[first tertiary ignorable]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset/first_tertiary_ignorable" ); // Assert.AreEqual("<rules><reset><first_tertiary_ignorable /></reset></rules>", _xmlText.ToString()); } [Test] public void LastTertiaryIgnorable_ProducesCorrectIndirectNode() { _icuParser.WriteIcuRules(_writer, "&[last tertiary ignorable]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset/last_tertiary_ignorable" ); // Assert.AreEqual("<rules><reset><last_tertiary_ignorable /></reset></rules>", _xmlText.ToString()); } [Test] public void FirstSecondarygnorable_ProducesCorrectIndirectNode() { _icuParser.WriteIcuRules(_writer, "&[first secondary ignorable]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset/first_secondary_ignorable" ); // Assert.AreEqual("<rules><reset><first_secondary_ignorable /></reset></rules>", _xmlText.ToString()); } [Test] public void LastSecondaryIgnorable_ProducesCorrectIndirectNode() { _icuParser.WriteIcuRules(_writer, "&[last secondary ignorable]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset/last_secondary_ignorable" ); // Assert.AreEqual("<rules><reset><last_secondary_ignorable /></reset></rules>", _xmlText.ToString()); } [Test] public void FirstPrimaryIgnorable_ProducesCorrectIndirectNode() { _icuParser.WriteIcuRules(_writer, "&[first primary ignorable]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset/first_primary_ignorable" ); // Assert.AreEqual("<rules><reset><first_primary_ignorable /></reset></rules>", _xmlText.ToString()); } [Test] public void LastPrimaryIgnorable_ProducesCorrectIndirectNode() { _icuParser.WriteIcuRules(_writer, "&[last primary ignorable]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset/last_primary_ignorable" ); // Assert.AreEqual("<rules><reset><last_primary_ignorable /></reset></rules>", _xmlText.ToString()); } [Test] public void FirstVariable_ProducesCorrectIndirectNode() { _icuParser.WriteIcuRules(_writer, "&[first variable]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset/first_variable" ); // Assert.AreEqual("<rules><reset><first_variable /></reset></rules>", _xmlText.ToString()); } [Test] public void LastVariable_ProducesCorrectIndirectNode() { _icuParser.WriteIcuRules(_writer, "&[last variable]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset/last_variable" ); // Assert.AreEqual("<rules><reset><last_variable /></reset></rules>", _xmlText.ToString()); } [Test] public void FirstRegular_ProducesCorrectIndirectNode() { _icuParser.WriteIcuRules(_writer, "&[first regular]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset/first_non_ignorable" ); // Assert.AreEqual("<rules><reset><first_non_ignorable /></reset></rules>", _xmlText.ToString()); } [Test] public void LastRegular_ProducesCorrectIndirectNode() { _icuParser.WriteIcuRules(_writer, "&[last regular]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset/last_non_ignorable" ); // Assert.AreEqual("<rules><reset><last_non_ignorable /></reset></rules>", _xmlText.ToString()); } [Test] public void FirstTrailing_ProducesCorrectIndirectNode() { _icuParser.WriteIcuRules(_writer, "&[first trailing]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset/first_trailing" ); // Assert.AreEqual("<rules><reset><first_trailing /></reset></rules>", _xmlText.ToString()); } [Test] public void LastTrailing_ProducesCorrectIndirectNode() { _icuParser.WriteIcuRules(_writer, "&[last trailing]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset/last_trailing" ); // Assert.AreEqual("<rules><reset><last_trailing /></reset></rules>", _xmlText.ToString()); } [Test] public void FirstImplicit_ProducesCorrectIndirectNode() { _icuParser.WriteIcuRules(_writer, "&a < [first implicit]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='a']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/p/first_implicit" ); // Assert.AreEqual("<rules><reset>a</reset><p><first_implicit /></p></rules>", _xmlText.ToString()); } [Test] public void LastImplicit_ProducesCorrectIndirectNode() { _icuParser.WriteIcuRules(_writer, "&a < [last implicit]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='a']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/p/last_implicit" ); // Assert.AreEqual("<rules><reset>a</reset><p><last_implicit /></p></rules>", _xmlText.ToString()); } [Test] public void Top_ProducesCorrectIndirectNode() { _icuParser.WriteIcuRules(_writer, "&[top]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset/last_non_ignorable" ); // Assert.AreEqual("<rules><reset><last_non_ignorable /></reset></rules>", _xmlText.ToString()); } [Test] public void Before1_ProducesCorrectResetNode() { _icuParser.WriteIcuRules(_writer, "&[before 1]a"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[@before='primary' and text()='a']" ); // Assert.AreEqual("<rules><reset before=\"primary\">a</reset></rules>", _xmlText.ToString()); } [Test] public void Before2_ProducesCorrectResetNode() { _icuParser.WriteIcuRules(_writer, "&[before 2]a"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[@before='secondary' and text()='a']" ); // Assert.AreEqual("<rules><reset before=\"secondary\">a</reset></rules>", _xmlText.ToString()); } [Test] public void Before3_ProducesCorrectResetNode() { _icuParser.WriteIcuRules(_writer, "&[before 3]a"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[@before='tertiary' and text()='a']" ); // Assert.AreEqual("<rules><reset before=\"tertiary\">a</reset></rules>", _xmlText.ToString()); } [Test] public void TwoRules_ProducesCorrectXml() { _icuParser.WriteIcuRules(_writer, "&a<b \n&c<<d"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[1 and text()='a']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[1]/following-sibling::p[text()='b']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[2 and text()='c']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[2]/following-sibling::s[text()='d']" ); // Assert.AreEqual("<rules><reset>a</reset><p>b</p><reset>c</reset><s>d</s></rules>", _xmlText.ToString()); } [Test] public void AlternateShiftedOption_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[alternate shifted]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath("/settings[@alternate='shifted']"); } [Test] public void AlternateNonIgnorableOption_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[alternate non-ignorable]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath("/settings[@alternate='non-ignorable']"); } [Test] public void Strength1Option_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[strength 1]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/settings[@strength='primary']" ); // Assert.AreEqual("<settings strength=\"primary\" />", _xmlText.ToString()); } [Test] public void Strength2Option_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[strength 2]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/settings[@strength='secondary']" ); // Assert.AreEqual("<settings strength=\"secondary\" />", _xmlText.ToString()); } [Test] public void Strength3Option_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[strength 3]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/settings[@strength='tertiary']" ); // Assert.AreEqual("<settings strength=\"tertiary\" />", _xmlText.ToString()); } [Test] public void Strength4Option_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[strength 4]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/settings[@strength='quaternary']" ); // Assert.AreEqual("<settings strength=\"quaternary\" />", _xmlText.ToString()); } [Test] public void Strength5Option_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[strength 5]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/settings[@strength='identical']" ); // Assert.AreEqual("<settings strength=\"identical\" />", _xmlText.ToString()); } [Test] public void StrengthIOption_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[strength I]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/settings[@strength='identical']" ); // Assert.AreEqual("<settings strength=\"identical\" />", _xmlText.ToString()); } [Test] public void Backwards1_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[backwards 1]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/settings[@backwards='off']" ); // Assert.AreEqual("<settings backwards=\"off\" />", _xmlText.ToString()); } [Test] public void Backwards2_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[backwards 2]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/settings[@backwards='on']" ); // Assert.AreEqual("<settings backwards=\"on\" />", _xmlText.ToString()); } [Test] public void NormalizationOn_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[normalization on]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/settings[@normalization='on']" ); // Assert.AreEqual("<settings normalization=\"on\" />", _xmlText.ToString()); } [Test] public void NormalizationOff_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[normalization off]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/settings[@normalization='off']" ); // Assert.AreEqual("<settings normalization=\"off\" />", _xmlText.ToString()); } [Test] public void CaseLevelOn_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[caseLevel on]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/settings[@caseLevel='on']" ); // Assert.AreEqual("<settings caseLevel=\"on\" />", _xmlText.ToString()); } [Test] public void CaseLevelOff_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[caseLevel off]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/settings[@caseLevel='off']" ); // Assert.AreEqual("<settings caseLevel=\"off\" />", _xmlText.ToString()); } [Test] public void CaseFirstOff_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[caseFirst off]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/settings[@caseFirst='off']" ); // Assert.AreEqual("<settings caseFirst=\"off\" />", _xmlText.ToString()); } [Test] public void CaseFirstLower_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[caseFirst lower]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/settings[@caseFirst='lower']" ); // Assert.AreEqual("<settings caseFirst=\"lower\" />", _xmlText.ToString()); } [Test] public void CaseFirstUpper_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[caseFirst upper]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/settings[@caseFirst='upper']" ); // Assert.AreEqual("<settings caseFirst=\"upper\" />", _xmlText.ToString()); } [Test] public void HiraganaQOff_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[hiraganaQ off]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/settings[@hiraganaQuaternary='off']" ); // Assert.AreEqual("<settings hiraganaQuaternary=\"off\" />", _xmlText.ToString()); } [Test] public void HiraganaQOn_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[hiraganaQ on]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/settings[@hiraganaQuaternary='on']" ); // Assert.AreEqual("<settings hiraganaQuaternary=\"on\" />", _xmlText.ToString()); } [Test] public void NumericOff_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[numeric off]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/settings[@numeric='off']" ); // Assert.AreEqual("<settings numeric=\"off\" />", _xmlText.ToString()); } [Test] public void NumericOn_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "[numeric on]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/settings[@numeric='on']" ); // Assert.AreEqual("<settings numeric=\"on\" />", _xmlText.ToString()); } [Test] public void VariableTop_ProducesCorrectSettingsNode() { _icuParser.WriteIcuRules(_writer, "& A < [variable top]"); string result = "<root>" + Environment_OutputString() + "</root>"; AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/root/settings[@variableTop='u41']" ); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/root/rules/reset[text()='A']" ); // Assert.AreEqual("<settings variableTop=\"u41\" /><rules><reset>A</reset></rules>", _xmlText.ToString()); } [Test] public void SuppressContractions_ProducesCorrectNode() { _icuParser.WriteIcuRules(_writer, "[suppress contractions [abc]]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/suppress_contractions[text()='[abc]']" ); // Assert.AreEqual("<suppress_contractions>[abc]</suppress_contractions>", _xmlText.ToString()); } [Test] public void Optimize_ProducesCorrectNode() { _icuParser.WriteIcuRules(_writer, "[optimize [abc]]"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/optimize[text()='[abc]']" ); // Assert.AreEqual("<optimize>[abc]</optimize>", _xmlText.ToString()); } // Most of these escapes aren't actually handled by ICU - it just treats the character // following backslash as a literal. These tests just check for no other special escape // handling that is invalid. [Test] public void Escape_x_ProducesCorrectCharacter() { _icuParser.WriteIcuRules(_writer, "&\\x41"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='x41']" ); // Assert.AreEqual("<rules><reset>x41</reset></rules>", _xmlText.ToString()); } [Test] public void Escape_octal_ProducesCorrectCharacter() { _icuParser.WriteIcuRules(_writer, "&\\102"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='102']" ); // Assert.AreEqual("<rules><reset>102</reset></rules>", _xmlText.ToString()); } [Test] public void Escape_c_ProducesCorrectCharacter() { _icuParser.WriteIcuRules(_writer, "&\\c\u0083"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='c\u0083']" ); // Assert.AreEqual("<rules><reset>c\u0083</reset></rules>", _xmlText.ToString()); } [Test] public void Escape_a_ProducesCorrectCharacter() { _icuParser.WriteIcuRules(_writer, "&\\a"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='a']" ); // Assert.AreEqual("<rules><reset>a</reset></rules>", _xmlText.ToString()); } [Test] public void Escape_b_ProducesCorrectCharacter() { _icuParser.WriteIcuRules(_writer, "&\\b"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='b']" ); // Assert.AreEqual("<rules><reset>b</reset></rules>", _xmlText.ToString()); } [Test] public void Escape_t_ProducesCorrectCharacter() { _icuParser.WriteIcuRules(_writer, "&\\t"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='t']" ); // Assert.AreEqual("<rules><reset>t</reset></rules>", _xmlText.ToString()); } [Test] public void Escape_n_ProducesCorrectCharacter() { _icuParser.WriteIcuRules(_writer, "&\\n"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='n']" ); // Assert.AreEqual(String.Format("<rules><reset>n</reset></rules>", _writer.Settings.NewLineChars), _xmlText.ToString()); } [Test] public void Escape_v_ProducesCorrectCharacter() { _icuParser.WriteIcuRules(_writer, "&\\v"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='v']" ); // Assert.AreEqual("<rules><reset>v</reset></rules>", _xmlText.ToString()); } [Test] public void Escape_f_ProducesCorrectCharacter() { _icuParser.WriteIcuRules(_writer, "&\\f"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='f']" ); // Assert.AreEqual("<rules><reset>f</reset></rules>", _xmlText.ToString()); } [Test] public void Escape_r_ProducesCorrectCharacter() { _icuParser.WriteIcuRules(_writer, "&\\r"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='r']" ); // Assert.AreEqual("<rules><reset>r</reset></rules>", _xmlText.ToString()); } [Test] public void Escape_OtherChar_ProducesCorrectCharacter() { _icuParser.WriteIcuRules(_writer, "&\\\\"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()='\\']" ); // Assert.AreEqual("<rules><reset>\\</reset></rules>", _xmlText.ToString()); } [Test] public void TwoSingleQuotes_ProducesCorrectCharacter() { _icuParser.WriteIcuRules(_writer, "&''"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()=\"'\"]" ); // Assert.AreEqual("<rules><reset>'</reset></rules>", _xmlText.ToString()); } [Test] public void QuotedString_ProducesCorrectString() { _icuParser.WriteIcuRules(_writer, "&'''\\<&'"); string result = Environment_OutputString(); AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath( "/rules/reset[text()=\"'\\<&\"]" ); // Assert.AreEqual("<rules><reset>'\\&lt;&amp;</reset></rules>", _xmlText.ToString()); } [Test] public void InvalidIcu_Throws() { Assert.Throws<ApplicationException>( () => _icuParser.WriteIcuRules(_writer, "&a <<<< b")); _writer.Close(); } [Test] public void InvalidIcu_NoXmlProduced() { try { _icuParser.WriteIcuRules(_writer, "&a <<<< b"); } // ReSharper disable EmptyGeneralCatchClause catch {} // ReSharper restore EmptyGeneralCatchClause string result = Environment_OutputString(); Assert.IsTrue(String.IsNullOrEmpty(result)); } [Test] public void ValidateIcuRules_ValidIcu_ReturnsTrue() { string message; Assert.IsTrue(_icuParser.ValidateIcuRules("&a < b <<< c < e/g\n&[before 1]m<z", out message)); Assert.AreEqual(string.Empty, message); } [Test] public void ValidateIcuRules_InvalidIcu_ReturnsFalse() { string message; Assert.IsFalse(_icuParser.ValidateIcuRules("&a < b < c(", out message)); Assert.IsNotEmpty(message); } [Test] public void BigCombinedRule_ParsesCorrectly() { // certainly some of this actually doesn't form semantically vaild ICU, but it should be syntactically correct const string icu = "[strength 3] [alternate shifted]\n[backwards 2]&[before 1][ first regular]<b<\\u" + "<'cde'&gh<<p<K|Q/\\<<[last variable]<<4<[variable\ttop]\t<9"; _icuParser.WriteIcuRules(_writer, icu); string result = Environment_OutputString(); string expected = CanonicalXml.ToCanonicalStringFragment( "<settings alternate=\"shifted\" backwards=\"on\" variableTop=\"u34\" strength=\"tertiary\" />" + "<rules><reset before=\"primary\"><first_non_ignorable /></reset>" + "<pc>bu</pc><p>cde</p><reset>gh</reset><s>p</s>" + "<x><context>K</context><p>Q</p><extend>&lt;</extend></x>" + "<p><last_variable /></p><s>4</s><p>9</p></rules>" ); Assert.AreEqual(expected, result); } } }
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // 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. // // The latest version of this file can be found at http://www.codeplex.com/FluentValidation #endregion namespace FluentValidation.Mvc { using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web.Mvc; using Resources; using Results; using Validators; public class FluentValidationModelMetadataProvider : DataAnnotationsModelMetadataProvider { readonly IValidatorFactory factory; public FluentValidationModelMetadataProvider(IValidatorFactory factory) { this.factory = factory; } protected override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, PropertyDescriptor propertyDescriptor) { var attributes = ConvertFVMetaDataToAttributes(containerType, propertyDescriptor.Name); return CreateMetadata(attributes, containerType, modelAccessor, propertyDescriptor.PropertyType, propertyDescriptor.Name); } IEnumerable<Attribute> ConvertFVMetaDataToAttributes(Type type, string name) { var validator = factory.GetValidator(type); if (validator == null) { return Enumerable.Empty<Attribute>(); } IEnumerable<IPropertyValidator> validators; // if (name == null) { //validators = validator.CreateDescriptor().GetMembersWithValidators().SelectMany(x => x); // validators = Enumerable.Empty<IPropertyValidator>(); // } // else { validators = validator.CreateDescriptor().GetValidatorsForMember(name); // } var attributes = validators.OfType<IAttributeMetadataValidator>() .Select(x => x.ToAttribute()) .Concat(SpecialCaseValidatorConversions(validators)); return attributes.ToList(); } IEnumerable<Attribute> SpecialCaseValidatorConversions(IEnumerable<IPropertyValidator> validators) { //Email Validator should be convertible to DataType EmailAddress. var emailValidators = validators .OfType<IEmailValidator>() .Select(x => new DataTypeAttribute(DataType.EmailAddress)) .Cast<Attribute>(); var requiredValidators = validators.OfType<INotNullValidator>().Cast<IPropertyValidator>() .Concat(validators.OfType<INotEmptyValidator>().Cast<IPropertyValidator>()) .Select(x => new RequiredAttribute()) .Cast<Attribute>(); return requiredValidators.Concat(emailValidators); } /*IEnumerable<Attribute> ConvertFVMetaDataToAttributes(Type type) { return ConvertFVMetaDataToAttributes(type, null); }*/ /*public override ModelMetadata GetMetadataForType(Func<object> modelAccessor, Type modelType) { var attributes = ConvertFVMetaDataToAttributes(modelType); return CreateMetadata(attributes, null /* containerType ?1?, modelAccessor, modelType, null /* propertyName ?1?); }*/ } public interface IAttributeMetadataValidator : IPropertyValidator { Attribute ToAttribute(); } internal class AttributeMetadataValidator : IAttributeMetadataValidator { readonly Attribute attribute; public AttributeMetadataValidator(Attribute attributeConverter) { attribute = attributeConverter; } public IStringSource ErrorMessageSource { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public IEnumerable<ValidationFailure> Validate(PropertyValidatorContext context) { return Enumerable.Empty<ValidationFailure>(); } public string ErrorMessageTemplate { get { return null; } set { } } public ICollection<Func<object, object>> CustomMessageFormatArguments { get { return null; } } public bool SupportsStandaloneValidation { get { return false; } } public Func<object, object> CustomStateProvider { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public Attribute ToAttribute() { return attribute; } } } namespace FluentValidation.Mvc.MetadataExtensions { using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; using Validators; public static class MetadataExtensions { public static IRuleBuilder<T, TProperty> HiddenInput<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new HiddenInputAttribute())); } public static IRuleBuilder<T, TProperty> HiddenInput<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, bool displayValue) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new HiddenInputAttribute { DisplayValue = displayValue })); } public static IRuleBuilder<T, TProperty> UIHint<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, string hint) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new UIHintAttribute(hint))); } public static IRuleBuilder<T, TProperty> UIHint<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, string hint, string presentationLayer) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new UIHintAttribute(hint, presentationLayer))); } public static IRuleBuilder<T, TProperty> Scaffold<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, bool scaffold) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new ScaffoldColumnAttribute(scaffold))); } public static IRuleBuilder<T, TProperty> DataType<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, DataType dataType) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new DataTypeAttribute(dataType))); } public static IRuleBuilder<T, TProperty> DataType<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, string customDataType) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new DataTypeAttribute(customDataType))); } public static IRuleBuilder<T, TProperty> DisplayName<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, string name) { #if NET4 return ruleBuilder.SetValidator(new AttributeMetadataValidator(new DisplayAttribute { Name = name })); #else return ruleBuilder.SetValidator(new AttributeMetadataValidator(new DisplayNameAttribute(name))); #endif } public static IDisplayFormatBuilder<T, TProperty> DisplayFormat<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder) { return new DisplayFormatBuilder<T, TProperty>(ruleBuilder); } public static IRuleBuilder<T, TProperty> ReadOnly<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, bool readOnly) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new ReadOnlyAttribute(readOnly))); } public interface IDisplayFormatBuilder<T, TProperty> : IRuleBuilder<T, TProperty> { IDisplayFormatBuilder<T, TProperty> NullDisplayText(string text); IDisplayFormatBuilder<T, TProperty> DataFormatString(string text); IDisplayFormatBuilder<T, TProperty> ApplyFormatInEditMode(bool apply); IDisplayFormatBuilder<T, TProperty> ConvertEmptyStringToNull(bool convert); } private class DisplayFormatBuilder<T, TProperty> : IDisplayFormatBuilder<T, TProperty> { readonly IRuleBuilder<T, TProperty> builder; readonly DisplayFormatAttribute attribute = new DisplayFormatAttribute(); public DisplayFormatBuilder(IRuleBuilder<T, TProperty> builder) { this.builder = builder; builder.SetValidator(new AttributeMetadataValidator(attribute)); } public IRuleBuilderOptions<T, TProperty> SetValidator(IPropertyValidator validator) { return builder.SetValidator(validator); } [Obsolete] public IRuleBuilderOptions<T, TProperty> SetValidator(IValidator validator) { return builder.SetValidator(validator); } public IRuleBuilderOptions<T, TProperty> SetValidator(IValidator<TProperty> validator) { return builder.SetValidator(validator); } public IDisplayFormatBuilder<T, TProperty> NullDisplayText(string text) { attribute.NullDisplayText = text; return this; } public IDisplayFormatBuilder<T, TProperty> DataFormatString(string text) { attribute.DataFormatString = text; return this; } public IDisplayFormatBuilder<T, TProperty> ApplyFormatInEditMode(bool apply) { attribute.ApplyFormatInEditMode = apply; return this; } public IDisplayFormatBuilder<T, TProperty> ConvertEmptyStringToNull(bool convert) { attribute.ConvertEmptyStringToNull = convert; return this; } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection.Emit; namespace System.Management.Automation.Language { /// <summary> /// </summary> #nullable enable public interface ICustomAstVisitor { /// <summary/> object? DefaultVisit(Ast ast) => null; /// <summary/> object? VisitErrorStatement(ErrorStatementAst errorStatementAst) => DefaultVisit(errorStatementAst); /// <summary/> object? VisitErrorExpression(ErrorExpressionAst errorExpressionAst) => DefaultVisit(errorExpressionAst); #region Script Blocks /// <summary/> object? VisitScriptBlock(ScriptBlockAst scriptBlockAst) => DefaultVisit(scriptBlockAst); /// <summary/> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Param")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "param")] object? VisitParamBlock(ParamBlockAst paramBlockAst) => DefaultVisit(paramBlockAst); /// <summary/> object? VisitNamedBlock(NamedBlockAst namedBlockAst) => DefaultVisit(namedBlockAst); /// <summary/> object? VisitTypeConstraint(TypeConstraintAst typeConstraintAst) => DefaultVisit(typeConstraintAst); /// <summary/> object? VisitAttribute(AttributeAst attributeAst) => DefaultVisit(attributeAst); /// <summary/> object? VisitNamedAttributeArgument(NamedAttributeArgumentAst namedAttributeArgumentAst) => DefaultVisit(namedAttributeArgumentAst); /// <summary/> object? VisitParameter(ParameterAst parameterAst) => DefaultVisit(parameterAst); #endregion Script Blocks #region Statements /// <summary/> object? VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) => DefaultVisit(functionDefinitionAst); /// <summary/> object? VisitStatementBlock(StatementBlockAst statementBlockAst) => DefaultVisit(statementBlockAst); /// <summary/> object? VisitIfStatement(IfStatementAst ifStmtAst) => DefaultVisit(ifStmtAst); /// <summary/> object? VisitTrap(TrapStatementAst trapStatementAst) => DefaultVisit(trapStatementAst); /// <summary/> object? VisitSwitchStatement(SwitchStatementAst switchStatementAst) => DefaultVisit(switchStatementAst); /// <summary/> object? VisitDataStatement(DataStatementAst dataStatementAst) => DefaultVisit(dataStatementAst); /// <summary/> object? VisitForEachStatement(ForEachStatementAst forEachStatementAst) => DefaultVisit(forEachStatementAst); /// <summary/> object? VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst) => DefaultVisit(doWhileStatementAst); /// <summary/> object? VisitForStatement(ForStatementAst forStatementAst) => DefaultVisit(forStatementAst); /// <summary/> object? VisitWhileStatement(WhileStatementAst whileStatementAst) => DefaultVisit(whileStatementAst); /// <summary/> object? VisitCatchClause(CatchClauseAst catchClauseAst) => DefaultVisit(catchClauseAst); /// <summary/> object? VisitTryStatement(TryStatementAst tryStatementAst) => DefaultVisit(tryStatementAst); /// <summary/> object? VisitBreakStatement(BreakStatementAst breakStatementAst) => DefaultVisit(breakStatementAst); /// <summary/> object? VisitContinueStatement(ContinueStatementAst continueStatementAst) => DefaultVisit(continueStatementAst); /// <summary/> object? VisitReturnStatement(ReturnStatementAst returnStatementAst) => DefaultVisit(returnStatementAst); /// <summary/> object? VisitExitStatement(ExitStatementAst exitStatementAst) => DefaultVisit(exitStatementAst); /// <summary/> object? VisitThrowStatement(ThrowStatementAst throwStatementAst) => DefaultVisit(throwStatementAst); /// <summary/> object? VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) => DefaultVisit(doUntilStatementAst); /// <summary/> object? VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) => DefaultVisit(assignmentStatementAst); #endregion Statements #region Pipelines /// <summary/> object? VisitPipeline(PipelineAst pipelineAst) => DefaultVisit(pipelineAst); /// <summary/> object? VisitCommand(CommandAst commandAst) => DefaultVisit(commandAst); /// <summary/> object? VisitCommandExpression(CommandExpressionAst commandExpressionAst) => DefaultVisit(commandExpressionAst); /// <summary/> object? VisitCommandParameter(CommandParameterAst commandParameterAst) => DefaultVisit(commandParameterAst); /// <summary/> object? VisitFileRedirection(FileRedirectionAst fileRedirectionAst) => DefaultVisit(fileRedirectionAst); /// <summary/> object? VisitMergingRedirection(MergingRedirectionAst mergingRedirectionAst) => DefaultVisit(mergingRedirectionAst); #endregion Pipelines #region Expressions /// <summary/> object? VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) => DefaultVisit(binaryExpressionAst); /// <summary/> object? VisitUnaryExpression(UnaryExpressionAst unaryExpressionAst) => DefaultVisit(unaryExpressionAst); /// <summary/> object? VisitConvertExpression(ConvertExpressionAst convertExpressionAst) => DefaultVisit(convertExpressionAst); /// <summary/> object? VisitConstantExpression(ConstantExpressionAst constantExpressionAst) => DefaultVisit(constantExpressionAst); /// <summary/> object? VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst) => DefaultVisit(stringConstantExpressionAst); /// <summary/> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "SubExpression")] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "subExpression")] object? VisitSubExpression(SubExpressionAst subExpressionAst) => DefaultVisit(subExpressionAst); /// <summary/> object? VisitUsingExpression(UsingExpressionAst usingExpressionAst) => DefaultVisit(usingExpressionAst); /// <summary/> object? VisitVariableExpression(VariableExpressionAst variableExpressionAst) => DefaultVisit(variableExpressionAst); /// <summary/> object? VisitTypeExpression(TypeExpressionAst typeExpressionAst) => DefaultVisit(typeExpressionAst); /// <summary/> object? VisitMemberExpression(MemberExpressionAst memberExpressionAst) => DefaultVisit(memberExpressionAst); /// <summary/> object? VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst) => DefaultVisit(invokeMemberExpressionAst); /// <summary/> object? VisitArrayExpression(ArrayExpressionAst arrayExpressionAst) => DefaultVisit(arrayExpressionAst); /// <summary/> object? VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst) => DefaultVisit(arrayLiteralAst); /// <summary/> object? VisitHashtable(HashtableAst hashtableAst) => DefaultVisit(hashtableAst); /// <summary/> object? VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) => DefaultVisit(scriptBlockExpressionAst); /// <summary/> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Paren")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "paren")] object? VisitParenExpression(ParenExpressionAst parenExpressionAst) => DefaultVisit(parenExpressionAst); /// <summary/> object? VisitExpandableStringExpression(ExpandableStringExpressionAst expandableStringExpressionAst) => DefaultVisit(expandableStringExpressionAst); /// <summary/> object? VisitIndexExpression(IndexExpressionAst indexExpressionAst) => DefaultVisit(indexExpressionAst); /// <summary/> object? VisitAttributedExpression(AttributedExpressionAst attributedExpressionAst) => DefaultVisit(attributedExpressionAst); /// <summary/> object? VisitBlockStatement(BlockStatementAst blockStatementAst) => DefaultVisit(blockStatementAst); #endregion Expressions } #nullable restore /// <summary/> #nullable enable public interface ICustomAstVisitor2 : ICustomAstVisitor { /// <summary/> object? VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst) => DefaultVisit(typeDefinitionAst); /// <summary/> object? VisitPropertyMember(PropertyMemberAst propertyMemberAst) => DefaultVisit(propertyMemberAst); /// <summary/> object? VisitFunctionMember(FunctionMemberAst functionMemberAst) => DefaultVisit(functionMemberAst); /// <summary/> object? VisitBaseCtorInvokeMemberExpression(BaseCtorInvokeMemberExpressionAst baseCtorInvokeMemberExpressionAst) => DefaultVisit(baseCtorInvokeMemberExpressionAst); /// <summary/> object? VisitUsingStatement(UsingStatementAst usingStatement) => DefaultVisit(usingStatement); /// <summary/> object? VisitConfigurationDefinition(ConfigurationDefinitionAst configurationDefinitionAst) => DefaultVisit(configurationDefinitionAst); /// <summary/> object? VisitDynamicKeywordStatement(DynamicKeywordStatementAst dynamicKeywordAst) => DefaultVisit(dynamicKeywordAst); /// <summary/> object? VisitTernaryExpression(TernaryExpressionAst ternaryExpressionAst) => DefaultVisit(ternaryExpressionAst); /// <summary/> object? VisitPipelineChain(PipelineChainAst statementChainAst) => DefaultVisit(statementChainAst); } #nullable restore #if DEBUG internal class CheckAllParentsSet : AstVisitor2 { internal CheckAllParentsSet(Ast root) { this.Root = root; } private Ast Root { get; } internal AstVisitAction CheckParent(Ast ast) { if (ast != Root) { Diagnostics.Assert(ast.Parent != null, "Parent not set"); } return AstVisitAction.Continue; } public override AstVisitAction VisitErrorStatement(ErrorStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitErrorExpression(ErrorExpressionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitScriptBlock(ScriptBlockAst ast) { return CheckParent(ast); } public override AstVisitAction VisitParamBlock(ParamBlockAst ast) { return CheckParent(ast); } public override AstVisitAction VisitNamedBlock(NamedBlockAst ast) { return CheckParent(ast); } public override AstVisitAction VisitTypeConstraint(TypeConstraintAst ast) { return CheckParent(ast); } public override AstVisitAction VisitAttribute(AttributeAst ast) { return CheckParent(ast); } public override AstVisitAction VisitParameter(ParameterAst ast) { return CheckParent(ast); } public override AstVisitAction VisitTypeExpression(TypeExpressionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitStatementBlock(StatementBlockAst ast) { return CheckParent(ast); } public override AstVisitAction VisitIfStatement(IfStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitTrap(TrapStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitSwitchStatement(SwitchStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitDataStatement(DataStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitForEachStatement(ForEachStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitDoWhileStatement(DoWhileStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitForStatement(ForStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitWhileStatement(WhileStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitCatchClause(CatchClauseAst ast) { return CheckParent(ast); } public override AstVisitAction VisitTryStatement(TryStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitBreakStatement(BreakStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitContinueStatement(ContinueStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitReturnStatement(ReturnStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitExitStatement(ExitStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitThrowStatement(ThrowStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitDoUntilStatement(DoUntilStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitPipeline(PipelineAst ast) { return CheckParent(ast); } public override AstVisitAction VisitCommand(CommandAst ast) { return CheckParent(ast); } public override AstVisitAction VisitCommandExpression(CommandExpressionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitCommandParameter(CommandParameterAst ast) { return CheckParent(ast); } public override AstVisitAction VisitMergingRedirection(MergingRedirectionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitFileRedirection(FileRedirectionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitBinaryExpression(BinaryExpressionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitUnaryExpression(UnaryExpressionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitConvertExpression(ConvertExpressionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitConstantExpression(ConstantExpressionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitStringConstantExpression(StringConstantExpressionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitSubExpression(SubExpressionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitUsingExpression(UsingExpressionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitVariableExpression(VariableExpressionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitMemberExpression(MemberExpressionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitArrayExpression(ArrayExpressionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitArrayLiteral(ArrayLiteralAst ast) { return CheckParent(ast); } public override AstVisitAction VisitHashtable(HashtableAst ast) { return CheckParent(ast); } public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitParenExpression(ParenExpressionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitExpandableStringExpression(ExpandableStringExpressionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitIndexExpression(IndexExpressionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitAttributedExpression(AttributedExpressionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitBlockStatement(BlockStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitNamedAttributeArgument(NamedAttributeArgumentAst ast) { return CheckParent(ast); } public override AstVisitAction VisitTypeDefinition(TypeDefinitionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitFunctionMember(FunctionMemberAst ast) { return CheckParent(ast); } public override AstVisitAction VisitPropertyMember(PropertyMemberAst ast) { return CheckParent(ast); } public override AstVisitAction VisitUsingStatement(UsingStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitConfigurationDefinition(ConfigurationDefinitionAst ast) { return CheckParent(ast); } public override AstVisitAction VisitDynamicKeywordStatement(DynamicKeywordStatementAst ast) { return CheckParent(ast); } public override AstVisitAction VisitTernaryExpression(TernaryExpressionAst ast) => CheckParent(ast); public override AstVisitAction VisitPipelineChain(PipelineChainAst ast) => CheckParent(ast); } /// <summary> /// Check if <see cref="TypeConstraintAst"/> contains <see cref="TypeBuilder "/> type. /// </summary> internal class CheckTypeBuilder : AstVisitor2 { public override AstVisitAction VisitTypeConstraint(TypeConstraintAst ast) { Type type = ast.TypeName.GetReflectionType(); if (type != null) { Diagnostics.Assert(type is not TypeBuilder, "ReflectionType can never be TypeBuilder"); } return AstVisitAction.Continue; } } #endif /// <summary> /// Searches an AST, using the evaluation function provided by either of the constructors. /// </summary> internal class AstSearcher : AstVisitor2 { #region External interface internal static IEnumerable<Ast> FindAll(Ast ast, Func<Ast, bool> predicate, bool searchNestedScriptBlocks) { Diagnostics.Assert(ast != null && predicate != null, "caller to verify arguments"); var searcher = new AstSearcher(predicate, stopOnFirst: false, searchNestedScriptBlocks: searchNestedScriptBlocks); ast.InternalVisit(searcher); return searcher.Results; } internal static Ast FindFirst(Ast ast, Func<Ast, bool> predicate, bool searchNestedScriptBlocks) { Diagnostics.Assert(ast != null && predicate != null, "caller to verify arguments"); var searcher = new AstSearcher(predicate, stopOnFirst: true, searchNestedScriptBlocks: searchNestedScriptBlocks); ast.InternalVisit(searcher); return searcher.Results.FirstOrDefault(); } internal static bool Contains(Ast ast, Func<Ast, bool> predicate, bool searchNestedScriptBlocks) { Diagnostics.Assert(ast != null && predicate != null, "caller to verify arguments"); var searcher = new AstSearcher(predicate, stopOnFirst: true, searchNestedScriptBlocks: searchNestedScriptBlocks); ast.InternalVisit(searcher); return searcher.Results.Count > 0; } internal static bool IsUsingDollarInput(Ast ast) { return (AstSearcher.Contains( ast, ast_ => { var varAst = ast_ as VariableExpressionAst; if (varAst != null) { return varAst.VariablePath.IsVariable && varAst.VariablePath.UnqualifiedPath.Equals(SpecialVariables.Input, StringComparison.OrdinalIgnoreCase); } return false; }, searchNestedScriptBlocks: false)); } #endregion External interface protected AstSearcher(Func<Ast, bool> callback, bool stopOnFirst, bool searchNestedScriptBlocks) { _callback = callback; _stopOnFirst = stopOnFirst; _searchNestedScriptBlocks = searchNestedScriptBlocks; this.Results = new List<Ast>(); } private readonly Func<Ast, bool> _callback; private readonly bool _stopOnFirst; private readonly bool _searchNestedScriptBlocks; protected readonly List<Ast> Results; protected AstVisitAction Check(Ast ast) { if (_callback(ast)) { Results.Add(ast); if (_stopOnFirst) { return AstVisitAction.StopVisit; } } return AstVisitAction.Continue; } protected AstVisitAction CheckScriptBlock(Ast ast) { var action = Check(ast); if (action == AstVisitAction.Continue && !_searchNestedScriptBlocks) { action = AstVisitAction.SkipChildren; } return action; } public override AstVisitAction VisitErrorStatement(ErrorStatementAst ast) { return Check(ast); } public override AstVisitAction VisitErrorExpression(ErrorExpressionAst ast) { return Check(ast); } public override AstVisitAction VisitScriptBlock(ScriptBlockAst ast) { return Check(ast); } public override AstVisitAction VisitParamBlock(ParamBlockAst ast) { return Check(ast); } public override AstVisitAction VisitNamedBlock(NamedBlockAst ast) { return Check(ast); } public override AstVisitAction VisitTypeConstraint(TypeConstraintAst ast) { return Check(ast); } public override AstVisitAction VisitAttribute(AttributeAst ast) { return Check(ast); } public override AstVisitAction VisitParameter(ParameterAst ast) { return Check(ast); } public override AstVisitAction VisitTypeExpression(TypeExpressionAst ast) { return Check(ast); } public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst ast) { return CheckScriptBlock(ast); } public override AstVisitAction VisitStatementBlock(StatementBlockAst ast) { return Check(ast); } public override AstVisitAction VisitIfStatement(IfStatementAst ast) { return Check(ast); } public override AstVisitAction VisitTrap(TrapStatementAst ast) { return CheckScriptBlock(ast); } public override AstVisitAction VisitSwitchStatement(SwitchStatementAst ast) { return Check(ast); } public override AstVisitAction VisitDataStatement(DataStatementAst ast) { return Check(ast); } public override AstVisitAction VisitForEachStatement(ForEachStatementAst ast) { return Check(ast); } public override AstVisitAction VisitDoWhileStatement(DoWhileStatementAst ast) { return Check(ast); } public override AstVisitAction VisitForStatement(ForStatementAst ast) { return Check(ast); } public override AstVisitAction VisitWhileStatement(WhileStatementAst ast) { return Check(ast); } public override AstVisitAction VisitCatchClause(CatchClauseAst ast) { return Check(ast); } public override AstVisitAction VisitTryStatement(TryStatementAst ast) { return Check(ast); } public override AstVisitAction VisitBreakStatement(BreakStatementAst ast) { return Check(ast); } public override AstVisitAction VisitContinueStatement(ContinueStatementAst ast) { return Check(ast); } public override AstVisitAction VisitReturnStatement(ReturnStatementAst ast) { return Check(ast); } public override AstVisitAction VisitExitStatement(ExitStatementAst ast) { return Check(ast); } public override AstVisitAction VisitThrowStatement(ThrowStatementAst ast) { return Check(ast); } public override AstVisitAction VisitDoUntilStatement(DoUntilStatementAst ast) { return Check(ast); } public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst ast) { return Check(ast); } public override AstVisitAction VisitPipeline(PipelineAst ast) { return Check(ast); } public override AstVisitAction VisitCommand(CommandAst ast) { return Check(ast); } public override AstVisitAction VisitCommandExpression(CommandExpressionAst ast) { return Check(ast); } public override AstVisitAction VisitCommandParameter(CommandParameterAst ast) { return Check(ast); } public override AstVisitAction VisitMergingRedirection(MergingRedirectionAst ast) { return Check(ast); } public override AstVisitAction VisitFileRedirection(FileRedirectionAst ast) { return Check(ast); } public override AstVisitAction VisitBinaryExpression(BinaryExpressionAst ast) { return Check(ast); } public override AstVisitAction VisitUnaryExpression(UnaryExpressionAst ast) { return Check(ast); } public override AstVisitAction VisitConvertExpression(ConvertExpressionAst ast) { return Check(ast); } public override AstVisitAction VisitConstantExpression(ConstantExpressionAst ast) { return Check(ast); } public override AstVisitAction VisitStringConstantExpression(StringConstantExpressionAst ast) { return Check(ast); } public override AstVisitAction VisitSubExpression(SubExpressionAst ast) { return Check(ast); } public override AstVisitAction VisitUsingExpression(UsingExpressionAst ast) { return Check(ast); } public override AstVisitAction VisitVariableExpression(VariableExpressionAst ast) { return Check(ast); } public override AstVisitAction VisitMemberExpression(MemberExpressionAst ast) { return Check(ast); } public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst ast) { return Check(ast); } public override AstVisitAction VisitArrayExpression(ArrayExpressionAst ast) { return Check(ast); } public override AstVisitAction VisitArrayLiteral(ArrayLiteralAst ast) { return Check(ast); } public override AstVisitAction VisitHashtable(HashtableAst ast) { return Check(ast); } public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst ast) { return CheckScriptBlock(ast); } public override AstVisitAction VisitParenExpression(ParenExpressionAst ast) { return Check(ast); } public override AstVisitAction VisitExpandableStringExpression(ExpandableStringExpressionAst ast) { return Check(ast); } public override AstVisitAction VisitIndexExpression(IndexExpressionAst ast) { return Check(ast); } public override AstVisitAction VisitAttributedExpression(AttributedExpressionAst ast) { return Check(ast); } public override AstVisitAction VisitNamedAttributeArgument(NamedAttributeArgumentAst ast) { return Check(ast); } public override AstVisitAction VisitTypeDefinition(TypeDefinitionAst ast) { return Check(ast); } public override AstVisitAction VisitPropertyMember(PropertyMemberAst ast) { return Check(ast); } public override AstVisitAction VisitFunctionMember(FunctionMemberAst ast) { return Check(ast); } public override AstVisitAction VisitUsingStatement(UsingStatementAst ast) { return Check(ast); } public override AstVisitAction VisitBlockStatement(BlockStatementAst ast) { return Check(ast); } public override AstVisitAction VisitConfigurationDefinition(ConfigurationDefinitionAst ast) { return Check(ast); } public override AstVisitAction VisitDynamicKeywordStatement(DynamicKeywordStatementAst ast) { return Check(ast); } public override AstVisitAction VisitTernaryExpression(TernaryExpressionAst ast) { return Check(ast); } public override AstVisitAction VisitPipelineChain(PipelineChainAst ast) { return Check(ast); } } /// <summary> /// Default implementation of <see cref="ICustomAstVisitor"/> interface. /// </summary> public abstract class DefaultCustomAstVisitor : ICustomAstVisitor { /// <summary/> public virtual object DefaultVisit(Ast ast) => null; /// <summary/> public virtual object VisitErrorStatement(ErrorStatementAst errorStatementAst) => DefaultVisit(errorStatementAst); /// <summary/> public virtual object VisitErrorExpression(ErrorExpressionAst errorExpressionAst) => DefaultVisit(errorExpressionAst); /// <summary/> public virtual object VisitScriptBlock(ScriptBlockAst scriptBlockAst) => DefaultVisit(scriptBlockAst); /// <summary/> public virtual object VisitParamBlock(ParamBlockAst paramBlockAst) => DefaultVisit(paramBlockAst); /// <summary/> public virtual object VisitNamedBlock(NamedBlockAst namedBlockAst) => DefaultVisit(namedBlockAst); /// <summary/> public virtual object VisitTypeConstraint(TypeConstraintAst typeConstraintAst) => DefaultVisit(typeConstraintAst); /// <summary/> public virtual object VisitAttribute(AttributeAst attributeAst) => DefaultVisit(attributeAst); /// <summary/> public virtual object VisitNamedAttributeArgument(NamedAttributeArgumentAst namedAttributeArgumentAst) => DefaultVisit(namedAttributeArgumentAst); /// <summary/> public virtual object VisitParameter(ParameterAst parameterAst) => DefaultVisit(parameterAst); /// <summary/> public virtual object VisitStatementBlock(StatementBlockAst statementBlockAst) => DefaultVisit(statementBlockAst); /// <summary/> public virtual object VisitIfStatement(IfStatementAst ifStmtAst) => DefaultVisit(ifStmtAst); /// <summary/> public virtual object VisitTrap(TrapStatementAst trapStatementAst) => DefaultVisit(trapStatementAst); /// <summary/> public virtual object VisitSwitchStatement(SwitchStatementAst switchStatementAst) => DefaultVisit(switchStatementAst); /// <summary/> public virtual object VisitDataStatement(DataStatementAst dataStatementAst) => DefaultVisit(dataStatementAst); /// <summary/> public virtual object VisitForEachStatement(ForEachStatementAst forEachStatementAst) => DefaultVisit(forEachStatementAst); /// <summary/> public virtual object VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst) => DefaultVisit(doWhileStatementAst); /// <summary/> public virtual object VisitForStatement(ForStatementAst forStatementAst) => DefaultVisit(forStatementAst); /// <summary/> public virtual object VisitWhileStatement(WhileStatementAst whileStatementAst) => DefaultVisit(whileStatementAst); /// <summary/> public virtual object VisitCatchClause(CatchClauseAst catchClauseAst) => DefaultVisit(catchClauseAst); /// <summary/> public virtual object VisitTryStatement(TryStatementAst tryStatementAst) => DefaultVisit(tryStatementAst); /// <summary/> public virtual object VisitBreakStatement(BreakStatementAst breakStatementAst) => DefaultVisit(breakStatementAst); /// <summary/> public virtual object VisitContinueStatement(ContinueStatementAst continueStatementAst) => DefaultVisit(continueStatementAst); /// <summary/> public virtual object VisitReturnStatement(ReturnStatementAst returnStatementAst) => DefaultVisit(returnStatementAst); /// <summary/> public virtual object VisitExitStatement(ExitStatementAst exitStatementAst) => DefaultVisit(exitStatementAst); /// <summary/> public virtual object VisitThrowStatement(ThrowStatementAst throwStatementAst) => DefaultVisit(throwStatementAst); /// <summary/> public virtual object VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) => DefaultVisit(doUntilStatementAst); /// <summary/> public virtual object VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) => DefaultVisit(assignmentStatementAst); /// <summary/> public virtual object VisitPipeline(PipelineAst pipelineAst) => DefaultVisit(pipelineAst); /// <summary/> public virtual object VisitCommand(CommandAst commandAst) => DefaultVisit(commandAst); /// <summary/> public virtual object VisitCommandExpression(CommandExpressionAst commandExpressionAst) => DefaultVisit(commandExpressionAst); /// <summary/> public virtual object VisitCommandParameter(CommandParameterAst commandParameterAst) => DefaultVisit(commandParameterAst); /// <summary/> public virtual object VisitFileRedirection(FileRedirectionAst fileRedirectionAst) => DefaultVisit(fileRedirectionAst); /// <summary/> public virtual object VisitMergingRedirection(MergingRedirectionAst mergingRedirectionAst) => DefaultVisit(mergingRedirectionAst); /// <summary/> public virtual object VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) => DefaultVisit(binaryExpressionAst); /// <summary/> public virtual object VisitUnaryExpression(UnaryExpressionAst unaryExpressionAst) => DefaultVisit(unaryExpressionAst); /// <summary/> public virtual object VisitConvertExpression(ConvertExpressionAst convertExpressionAst) => DefaultVisit(convertExpressionAst); /// <summary/> public virtual object VisitConstantExpression(ConstantExpressionAst constantExpressionAst) => DefaultVisit(constantExpressionAst); /// <summary/> public virtual object VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst) => DefaultVisit(stringConstantExpressionAst); /// <summary/> public virtual object VisitSubExpression(SubExpressionAst subExpressionAst) => DefaultVisit(subExpressionAst); /// <summary/> public virtual object VisitUsingExpression(UsingExpressionAst usingExpressionAst) => DefaultVisit(usingExpressionAst); /// <summary/> public virtual object VisitVariableExpression(VariableExpressionAst variableExpressionAst) => DefaultVisit(variableExpressionAst); /// <summary/> public virtual object VisitTypeExpression(TypeExpressionAst typeExpressionAst) => DefaultVisit(typeExpressionAst); /// <summary/> public virtual object VisitMemberExpression(MemberExpressionAst memberExpressionAst) => DefaultVisit(memberExpressionAst); /// <summary/> public virtual object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst) => DefaultVisit(invokeMemberExpressionAst); /// <summary/> public virtual object VisitArrayExpression(ArrayExpressionAst arrayExpressionAst) => DefaultVisit(arrayExpressionAst); /// <summary/> public virtual object VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst) => DefaultVisit(arrayLiteralAst); /// <summary/> public virtual object VisitHashtable(HashtableAst hashtableAst) => DefaultVisit(hashtableAst); /// <summary/> public virtual object VisitParenExpression(ParenExpressionAst parenExpressionAst) => DefaultVisit(parenExpressionAst); /// <summary/> public virtual object VisitExpandableStringExpression(ExpandableStringExpressionAst expandableStringExpressionAst) => DefaultVisit(expandableStringExpressionAst); /// <summary/> public virtual object VisitIndexExpression(IndexExpressionAst indexExpressionAst) => DefaultVisit(indexExpressionAst); /// <summary/> public virtual object VisitAttributedExpression(AttributedExpressionAst attributedExpressionAst) => DefaultVisit(attributedExpressionAst); /// <summary/> public virtual object VisitBlockStatement(BlockStatementAst blockStatementAst) => DefaultVisit(blockStatementAst); /// <summary/> public virtual object VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) => DefaultVisit(functionDefinitionAst); /// <summary/> public virtual object VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) => DefaultVisit(scriptBlockExpressionAst); } /// <summary> /// Default implementation of <see cref="ICustomAstVisitor2"/> interface. /// </summary> public abstract class DefaultCustomAstVisitor2 : DefaultCustomAstVisitor, ICustomAstVisitor2 { /// <summary/> public virtual object VisitPropertyMember(PropertyMemberAst propertyMemberAst) => DefaultVisit(propertyMemberAst); /// <summary/> public virtual object VisitBaseCtorInvokeMemberExpression(BaseCtorInvokeMemberExpressionAst baseCtorInvokeMemberExpressionAst) => DefaultVisit(baseCtorInvokeMemberExpressionAst); /// <summary/> public virtual object VisitUsingStatement(UsingStatementAst usingStatement) => DefaultVisit(usingStatement); /// <summary/> public virtual object VisitConfigurationDefinition(ConfigurationDefinitionAst configurationAst) => DefaultVisit(configurationAst); /// <summary/> public virtual object VisitDynamicKeywordStatement(DynamicKeywordStatementAst dynamicKeywordAst) => DefaultVisit(dynamicKeywordAst); /// <summary/> public virtual object VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst) => DefaultVisit(typeDefinitionAst); /// <summary/> public virtual object VisitFunctionMember(FunctionMemberAst functionMemberAst) => DefaultVisit(functionMemberAst); /// <summary/> public virtual object VisitTernaryExpression(TernaryExpressionAst ternaryExpressionAst) => DefaultVisit(ternaryExpressionAst); /// <summary/> public virtual object VisitPipelineChain(PipelineChainAst statementChainAst) => DefaultVisit(statementChainAst); } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// A matrix of type double with 4 columns and 2 rows. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct dmat4x2 : IEnumerable<double>, IEquatable<dmat4x2> { #region Fields /// <summary> /// Column 0, Rows 0 /// </summary> public double m00; /// <summary> /// Column 0, Rows 1 /// </summary> public double m01; /// <summary> /// Column 1, Rows 0 /// </summary> public double m10; /// <summary> /// Column 1, Rows 1 /// </summary> public double m11; /// <summary> /// Column 2, Rows 0 /// </summary> public double m20; /// <summary> /// Column 2, Rows 1 /// </summary> public double m21; /// <summary> /// Column 3, Rows 0 /// </summary> public double m30; /// <summary> /// Column 3, Rows 1 /// </summary> public double m31; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public dmat4x2(double m00, double m01, double m10, double m11, double m20, double m21, double m30, double m31) { this.m00 = m00; this.m01 = m01; this.m10 = m10; this.m11 = m11; this.m20 = m20; this.m21 = m21; this.m30 = m30; this.m31 = m31; } /// <summary> /// Constructs this matrix from a dmat2. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dmat2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = 0.0; this.m21 = 0.0; this.m30 = 0.0; this.m31 = 0.0; } /// <summary> /// Constructs this matrix from a dmat3x2. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dmat3x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = 0.0; this.m31 = 0.0; } /// <summary> /// Constructs this matrix from a dmat4x2. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dmat4x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = m.m30; this.m31 = m.m31; } /// <summary> /// Constructs this matrix from a dmat2x3. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dmat2x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = 0.0; this.m21 = 0.0; this.m30 = 0.0; this.m31 = 0.0; } /// <summary> /// Constructs this matrix from a dmat3. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dmat3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = 0.0; this.m31 = 0.0; } /// <summary> /// Constructs this matrix from a dmat4x3. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dmat4x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = m.m30; this.m31 = m.m31; } /// <summary> /// Constructs this matrix from a dmat2x4. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dmat2x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = 0.0; this.m21 = 0.0; this.m30 = 0.0; this.m31 = 0.0; } /// <summary> /// Constructs this matrix from a dmat3x4. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dmat3x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = 0.0; this.m31 = 0.0; } /// <summary> /// Constructs this matrix from a dmat4. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dmat4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = m.m30; this.m31 = m.m31; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dvec2 c0, dvec2 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m10 = c1.x; this.m11 = c1.y; this.m20 = 0.0; this.m21 = 0.0; this.m30 = 0.0; this.m31 = 0.0; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dvec2 c0, dvec2 c1, dvec2 c2) { this.m00 = c0.x; this.m01 = c0.y; this.m10 = c1.x; this.m11 = c1.y; this.m20 = c2.x; this.m21 = c2.y; this.m30 = 0.0; this.m31 = 0.0; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dvec2 c0, dvec2 c1, dvec2 c2, dvec2 c3) { this.m00 = c0.x; this.m01 = c0.y; this.m10 = c1.x; this.m11 = c1.y; this.m20 = c2.x; this.m21 = c2.y; this.m30 = c3.x; this.m31 = c3.y; } #endregion #region Properties /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public double[,] Values => new[,] { { m00, m01 }, { m10, m11 }, { m20, m21 }, { m30, m31 } }; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public double[] Values1D => new[] { m00, m01, m10, m11, m20, m21, m30, m31 }; /// <summary> /// Gets or sets the column nr 0 /// </summary> public dvec2 Column0 { get { return new dvec2(m00, m01); } set { m00 = value.x; m01 = value.y; } } /// <summary> /// Gets or sets the column nr 1 /// </summary> public dvec2 Column1 { get { return new dvec2(m10, m11); } set { m10 = value.x; m11 = value.y; } } /// <summary> /// Gets or sets the column nr 2 /// </summary> public dvec2 Column2 { get { return new dvec2(m20, m21); } set { m20 = value.x; m21 = value.y; } } /// <summary> /// Gets or sets the column nr 3 /// </summary> public dvec2 Column3 { get { return new dvec2(m30, m31); } set { m30 = value.x; m31 = value.y; } } /// <summary> /// Gets or sets the row nr 0 /// </summary> public dvec4 Row0 { get { return new dvec4(m00, m10, m20, m30); } set { m00 = value.x; m10 = value.y; m20 = value.z; m30 = value.w; } } /// <summary> /// Gets or sets the row nr 1 /// </summary> public dvec4 Row1 { get { return new dvec4(m01, m11, m21, m31); } set { m01 = value.x; m11 = value.y; m21 = value.z; m31 = value.w; } } #endregion #region Static Properties /// <summary> /// Predefined all-zero matrix /// </summary> public static dmat4x2 Zero { get; } = new dmat4x2(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); /// <summary> /// Predefined all-ones matrix /// </summary> public static dmat4x2 Ones { get; } = new dmat4x2(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0); /// <summary> /// Predefined identity matrix /// </summary> public static dmat4x2 Identity { get; } = new dmat4x2(1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0); /// <summary> /// Predefined all-MaxValue matrix /// </summary> public static dmat4x2 AllMaxValue { get; } = new dmat4x2(double.MaxValue, double.MaxValue, double.MaxValue, double.MaxValue, double.MaxValue, double.MaxValue, double.MaxValue, double.MaxValue); /// <summary> /// Predefined diagonal-MaxValue matrix /// </summary> public static dmat4x2 DiagonalMaxValue { get; } = new dmat4x2(double.MaxValue, 0.0, 0.0, double.MaxValue, 0.0, 0.0, 0.0, 0.0); /// <summary> /// Predefined all-MinValue matrix /// </summary> public static dmat4x2 AllMinValue { get; } = new dmat4x2(double.MinValue, double.MinValue, double.MinValue, double.MinValue, double.MinValue, double.MinValue, double.MinValue, double.MinValue); /// <summary> /// Predefined diagonal-MinValue matrix /// </summary> public static dmat4x2 DiagonalMinValue { get; } = new dmat4x2(double.MinValue, 0.0, 0.0, double.MinValue, 0.0, 0.0, 0.0, 0.0); /// <summary> /// Predefined all-Epsilon matrix /// </summary> public static dmat4x2 AllEpsilon { get; } = new dmat4x2(double.Epsilon, double.Epsilon, double.Epsilon, double.Epsilon, double.Epsilon, double.Epsilon, double.Epsilon, double.Epsilon); /// <summary> /// Predefined diagonal-Epsilon matrix /// </summary> public static dmat4x2 DiagonalEpsilon { get; } = new dmat4x2(double.Epsilon, 0.0, 0.0, double.Epsilon, 0.0, 0.0, 0.0, 0.0); /// <summary> /// Predefined all-NaN matrix /// </summary> public static dmat4x2 AllNaN { get; } = new dmat4x2(double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN); /// <summary> /// Predefined diagonal-NaN matrix /// </summary> public static dmat4x2 DiagonalNaN { get; } = new dmat4x2(double.NaN, 0.0, 0.0, double.NaN, 0.0, 0.0, 0.0, 0.0); /// <summary> /// Predefined all-NegativeInfinity matrix /// </summary> public static dmat4x2 AllNegativeInfinity { get; } = new dmat4x2(double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity); /// <summary> /// Predefined diagonal-NegativeInfinity matrix /// </summary> public static dmat4x2 DiagonalNegativeInfinity { get; } = new dmat4x2(double.NegativeInfinity, 0.0, 0.0, double.NegativeInfinity, 0.0, 0.0, 0.0, 0.0); /// <summary> /// Predefined all-PositiveInfinity matrix /// </summary> public static dmat4x2 AllPositiveInfinity { get; } = new dmat4x2(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity); /// <summary> /// Predefined diagonal-PositiveInfinity matrix /// </summary> public static dmat4x2 DiagonalPositiveInfinity { get; } = new dmat4x2(double.PositiveInfinity, 0.0, 0.0, double.PositiveInfinity, 0.0, 0.0, 0.0, 0.0); #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public IEnumerator<double> GetEnumerator() { yield return m00; yield return m01; yield return m10; yield return m11; yield return m20; yield return m21; yield return m30; yield return m31; } /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion /// <summary> /// Returns the number of Fields (4 x 2 = 8). /// </summary> public int Count => 8; /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public double this[int fieldIndex] { get { switch (fieldIndex) { case 0: return m00; case 1: return m01; case 2: return m10; case 3: return m11; case 4: return m20; case 5: return m21; case 6: return m30; case 7: return m31; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } set { switch (fieldIndex) { case 0: this.m00 = value; break; case 1: this.m01 = value; break; case 2: this.m10 = value; break; case 3: this.m11 = value; break; case 4: this.m20 = value; break; case 5: this.m21 = value; break; case 6: this.m30 = value; break; case 7: this.m31 = value; break; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } } /// <summary> /// Gets/Sets a specific 2D-indexed component (a bit slower than direct access). /// </summary> public double this[int col, int row] { get { return this[col * 2 + row]; } set { this[col * 2 + row] = value; } } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(dmat4x2 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m10.Equals(rhs.m10) && m11.Equals(rhs.m11))) && ((m20.Equals(rhs.m20) && m21.Equals(rhs.m21)) && (m30.Equals(rhs.m30) && m31.Equals(rhs.m31)))); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is dmat4x2 && Equals((dmat4x2) obj); } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator ==(dmat4x2 lhs, dmat4x2 rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator !=(dmat4x2 lhs, dmat4x2 rhs) => !lhs.Equals(rhs); /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((((((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m20.GetHashCode()) * 397) ^ m21.GetHashCode()) * 397) ^ m30.GetHashCode()) * 397) ^ m31.GetHashCode(); } } /// <summary> /// Returns a transposed version of this matrix. /// </summary> public dmat2x4 Transposed => new dmat2x4(m00, m10, m20, m30, m01, m11, m21, m31); /// <summary> /// Returns the minimal component of this matrix. /// </summary> public double MinElement => Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(m00, m01), m10), m11), m20), m21), m30), m31); /// <summary> /// Returns the maximal component of this matrix. /// </summary> public double MaxElement => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m10), m11), m20), m21), m30), m31); /// <summary> /// Returns the euclidean length of this matrix. /// </summary> public double Length => (double)Math.Sqrt((((m00*m00 + m01*m01) + (m10*m10 + m11*m11)) + ((m20*m20 + m21*m21) + (m30*m30 + m31*m31)))); /// <summary> /// Returns the squared euclidean length of this matrix. /// </summary> public double LengthSqr => (((m00*m00 + m01*m01) + (m10*m10 + m11*m11)) + ((m20*m20 + m21*m21) + (m30*m30 + m31*m31))); /// <summary> /// Returns the sum of all fields. /// </summary> public double Sum => (((m00 + m01) + (m10 + m11)) + ((m20 + m21) + (m30 + m31))); /// <summary> /// Returns the euclidean norm of this matrix. /// </summary> public double Norm => (double)Math.Sqrt((((m00*m00 + m01*m01) + (m10*m10 + m11*m11)) + ((m20*m20 + m21*m21) + (m30*m30 + m31*m31)))); /// <summary> /// Returns the one-norm of this matrix. /// </summary> public double Norm1 => (((Math.Abs(m00) + Math.Abs(m01)) + (Math.Abs(m10) + Math.Abs(m11))) + ((Math.Abs(m20) + Math.Abs(m21)) + (Math.Abs(m30) + Math.Abs(m31)))); /// <summary> /// Returns the two-norm of this matrix. /// </summary> public double Norm2 => (double)Math.Sqrt((((m00*m00 + m01*m01) + (m10*m10 + m11*m11)) + ((m20*m20 + m21*m21) + (m30*m30 + m31*m31)))); /// <summary> /// Returns the max-norm of this matrix. /// </summary> public double NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m10)), Math.Abs(m11)), Math.Abs(m20)), Math.Abs(m21)), Math.Abs(m30)), Math.Abs(m31)); /// <summary> /// Returns the p-norm of this matrix. /// </summary> public double NormP(double p) => Math.Pow((((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + (Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p))) + ((Math.Pow((double)Math.Abs(m20), p) + Math.Pow((double)Math.Abs(m21), p)) + (Math.Pow((double)Math.Abs(m30), p) + Math.Pow((double)Math.Abs(m31), p)))), 1 / p); /// <summary> /// Executes a matrix-matrix-multiplication dmat4x2 * dmat2x4 -> dmat2. /// </summary> public static dmat2 operator*(dmat4x2 lhs, dmat2x4 rhs) => new dmat2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + (lhs.m20 * rhs.m02 + lhs.m30 * rhs.m03)), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + (lhs.m21 * rhs.m02 + lhs.m31 * rhs.m03)), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + (lhs.m20 * rhs.m12 + lhs.m30 * rhs.m13)), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + (lhs.m21 * rhs.m12 + lhs.m31 * rhs.m13))); /// <summary> /// Executes a matrix-matrix-multiplication dmat4x2 * dmat3x4 -> dmat3x2. /// </summary> public static dmat3x2 operator*(dmat4x2 lhs, dmat3x4 rhs) => new dmat3x2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + (lhs.m20 * rhs.m02 + lhs.m30 * rhs.m03)), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + (lhs.m21 * rhs.m02 + lhs.m31 * rhs.m03)), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + (lhs.m20 * rhs.m12 + lhs.m30 * rhs.m13)), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + (lhs.m21 * rhs.m12 + lhs.m31 * rhs.m13)), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + (lhs.m20 * rhs.m22 + lhs.m30 * rhs.m23)), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + (lhs.m21 * rhs.m22 + lhs.m31 * rhs.m23))); /// <summary> /// Executes a matrix-matrix-multiplication dmat4x2 * dmat4 -> dmat4x2. /// </summary> public static dmat4x2 operator*(dmat4x2 lhs, dmat4 rhs) => new dmat4x2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + (lhs.m20 * rhs.m02 + lhs.m30 * rhs.m03)), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + (lhs.m21 * rhs.m02 + lhs.m31 * rhs.m03)), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + (lhs.m20 * rhs.m12 + lhs.m30 * rhs.m13)), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + (lhs.m21 * rhs.m12 + lhs.m31 * rhs.m13)), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + (lhs.m20 * rhs.m22 + lhs.m30 * rhs.m23)), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + (lhs.m21 * rhs.m22 + lhs.m31 * rhs.m23)), ((lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31) + (lhs.m20 * rhs.m32 + lhs.m30 * rhs.m33)), ((lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31) + (lhs.m21 * rhs.m32 + lhs.m31 * rhs.m33))); /// <summary> /// Executes a matrix-vector-multiplication. /// </summary> public static dvec2 operator*(dmat4x2 m, dvec4 v) => new dvec2(((m.m00 * v.x + m.m10 * v.y) + (m.m20 * v.z + m.m30 * v.w)), ((m.m01 * v.x + m.m11 * v.y) + (m.m21 * v.z + m.m31 * v.w))); /// <summary> /// Executes a component-wise * (multiply). /// </summary> public static dmat4x2 CompMul(dmat4x2 A, dmat4x2 B) => new dmat4x2(A.m00 * B.m00, A.m01 * B.m01, A.m10 * B.m10, A.m11 * B.m11, A.m20 * B.m20, A.m21 * B.m21, A.m30 * B.m30, A.m31 * B.m31); /// <summary> /// Executes a component-wise / (divide). /// </summary> public static dmat4x2 CompDiv(dmat4x2 A, dmat4x2 B) => new dmat4x2(A.m00 / B.m00, A.m01 / B.m01, A.m10 / B.m10, A.m11 / B.m11, A.m20 / B.m20, A.m21 / B.m21, A.m30 / B.m30, A.m31 / B.m31); /// <summary> /// Executes a component-wise + (add). /// </summary> public static dmat4x2 CompAdd(dmat4x2 A, dmat4x2 B) => new dmat4x2(A.m00 + B.m00, A.m01 + B.m01, A.m10 + B.m10, A.m11 + B.m11, A.m20 + B.m20, A.m21 + B.m21, A.m30 + B.m30, A.m31 + B.m31); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static dmat4x2 CompSub(dmat4x2 A, dmat4x2 B) => new dmat4x2(A.m00 - B.m00, A.m01 - B.m01, A.m10 - B.m10, A.m11 - B.m11, A.m20 - B.m20, A.m21 - B.m21, A.m30 - B.m30, A.m31 - B.m31); /// <summary> /// Executes a component-wise + (add). /// </summary> public static dmat4x2 operator+(dmat4x2 lhs, dmat4x2 rhs) => new dmat4x2(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m20 + rhs.m20, lhs.m21 + rhs.m21, lhs.m30 + rhs.m30, lhs.m31 + rhs.m31); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static dmat4x2 operator+(dmat4x2 lhs, double rhs) => new dmat4x2(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m20 + rhs, lhs.m21 + rhs, lhs.m30 + rhs, lhs.m31 + rhs); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static dmat4x2 operator+(double lhs, dmat4x2 rhs) => new dmat4x2(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m20, lhs + rhs.m21, lhs + rhs.m30, lhs + rhs.m31); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static dmat4x2 operator-(dmat4x2 lhs, dmat4x2 rhs) => new dmat4x2(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m20 - rhs.m20, lhs.m21 - rhs.m21, lhs.m30 - rhs.m30, lhs.m31 - rhs.m31); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static dmat4x2 operator-(dmat4x2 lhs, double rhs) => new dmat4x2(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m20 - rhs, lhs.m21 - rhs, lhs.m30 - rhs, lhs.m31 - rhs); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static dmat4x2 operator-(double lhs, dmat4x2 rhs) => new dmat4x2(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m20, lhs - rhs.m21, lhs - rhs.m30, lhs - rhs.m31); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static dmat4x2 operator/(dmat4x2 lhs, double rhs) => new dmat4x2(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m20 / rhs, lhs.m21 / rhs, lhs.m30 / rhs, lhs.m31 / rhs); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static dmat4x2 operator/(double lhs, dmat4x2 rhs) => new dmat4x2(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m20, lhs / rhs.m21, lhs / rhs.m30, lhs / rhs.m31); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static dmat4x2 operator*(dmat4x2 lhs, double rhs) => new dmat4x2(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m20 * rhs, lhs.m21 * rhs, lhs.m30 * rhs, lhs.m31 * rhs); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static dmat4x2 operator*(double lhs, dmat4x2 rhs) => new dmat4x2(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m20, lhs * rhs.m21, lhs * rhs.m30, lhs * rhs.m31); /// <summary> /// Executes a component-wise lesser-than comparison. /// </summary> public static bmat4x2 operator<(dmat4x2 lhs, dmat4x2 rhs) => new bmat4x2(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m20 < rhs.m20, lhs.m21 < rhs.m21, lhs.m30 < rhs.m30, lhs.m31 < rhs.m31); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat4x2 operator<(dmat4x2 lhs, double rhs) => new bmat4x2(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m20 < rhs, lhs.m21 < rhs, lhs.m30 < rhs, lhs.m31 < rhs); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat4x2 operator<(double lhs, dmat4x2 rhs) => new bmat4x2(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m20, lhs < rhs.m21, lhs < rhs.m30, lhs < rhs.m31); /// <summary> /// Executes a component-wise lesser-or-equal comparison. /// </summary> public static bmat4x2 operator<=(dmat4x2 lhs, dmat4x2 rhs) => new bmat4x2(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m20 <= rhs.m20, lhs.m21 <= rhs.m21, lhs.m30 <= rhs.m30, lhs.m31 <= rhs.m31); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat4x2 operator<=(dmat4x2 lhs, double rhs) => new bmat4x2(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m20 <= rhs, lhs.m21 <= rhs, lhs.m30 <= rhs, lhs.m31 <= rhs); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat4x2 operator<=(double lhs, dmat4x2 rhs) => new bmat4x2(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m20, lhs <= rhs.m21, lhs <= rhs.m30, lhs <= rhs.m31); /// <summary> /// Executes a component-wise greater-than comparison. /// </summary> public static bmat4x2 operator>(dmat4x2 lhs, dmat4x2 rhs) => new bmat4x2(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m20 > rhs.m20, lhs.m21 > rhs.m21, lhs.m30 > rhs.m30, lhs.m31 > rhs.m31); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat4x2 operator>(dmat4x2 lhs, double rhs) => new bmat4x2(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m20 > rhs, lhs.m21 > rhs, lhs.m30 > rhs, lhs.m31 > rhs); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat4x2 operator>(double lhs, dmat4x2 rhs) => new bmat4x2(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m20, lhs > rhs.m21, lhs > rhs.m30, lhs > rhs.m31); /// <summary> /// Executes a component-wise greater-or-equal comparison. /// </summary> public static bmat4x2 operator>=(dmat4x2 lhs, dmat4x2 rhs) => new bmat4x2(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m20 >= rhs.m20, lhs.m21 >= rhs.m21, lhs.m30 >= rhs.m30, lhs.m31 >= rhs.m31); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat4x2 operator>=(dmat4x2 lhs, double rhs) => new bmat4x2(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m20 >= rhs, lhs.m21 >= rhs, lhs.m30 >= rhs, lhs.m31 >= rhs); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat4x2 operator>=(double lhs, dmat4x2 rhs) => new bmat4x2(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m20, lhs >= rhs.m21, lhs >= rhs.m30, lhs >= rhs.m31); } }
using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using Palaso.Code; using Palaso.Lift.Parsing; using Palaso.Text; using Palaso.Extensions; using System.Linq; //using Exortech.NetReflector; //using Exortech.NetReflector.Util; namespace Palaso.Lift { /// <summary> /// MultiText holds an array of LanguageForms, indexed by writing system ID. /// </summary> //NO: we haven't been able to do a reasonalbly compact xml representation except with custom deserializer //[ReflectorType("multiText")] [XmlInclude(typeof (LanguageForm))] public class MultiText : MultiTextBase, IPalasoDataObjectProperty, IReportEmptiness, IXmlSerializable { private PalasoDataObject _parent; public List<string> EmbeddedXmlElements = new List<string>(); //Adapter pattern: LiftMultitext has some features we would like to use private static LiftMultiText _liftMultitext; public MultiText(PalasoDataObject parent) { _parent = parent; } public MultiText() {} /// <summary> /// We added this pesky "backreference" solely to enable fast /// searching in db4o (5.5), which could /// find strings fast, but can't be queried for the owner /// quickly, if there is an intervening collection. Since /// each string in WeSay is part of a collection of writing /// system alternatives, that means we can't quickly get /// an answer, for example, to the question Get all /// the Entries that contain a senses which have the reversal "cat". /// /// NOW (2009) it is a TODO to look at removing this. /// /// Using this field, we can do a query asking for all /// the LanguageForms matching "cat". /// This can all be done in a single, fast query. /// In code, we can then follow the /// LanguageForm._parent up to the multitext, then this _parent /// up to it's owner, etc., on up the hierarchy to get the Entries. /// /// Subclasses should provide a property which set the proper class. /// /// 23 Jan 07, note: starting to switch to using these for notifying parent of changes, too. /// </summary> [XmlIgnore] public PalasoDataObject Parent { protected get { return _parent; } set { _parent = value; } } /// <summary> /// Subclasses should provide a "Parent" property which set the proper class. /// </summary> public PalasoDataObject ParentAsObject { get { return Parent; } } ///<summary> /// required by IXmlSerializable ///</summary> public XmlSchema GetSchema() { return null; } ///<summary> /// required by IXmlSerializable. /// This is wierd and sad, but this is tuned to the format we want in OptionLists. ///</summary> public virtual void ReadXml(XmlReader reader) { //enhance: this is a maximally inefficient way to read it, but ok if we're just using it for option lists XmlDocument d = new XmlDocument(); d.LoadXml(reader.ReadOuterXml()); foreach (XmlNode form in d.SelectNodes("*/form")) { string s = form.InnerText.Trim().Replace('\n', ' ').Replace(" ", " "); if (form.Attributes.GetNamedItem("ws") != null) //old style, but out there { SetAlternative(form.Attributes["ws"].Value, s); } else { SetAlternative(form.Attributes["lang"].Value, s); } } //reader.ReadEndElement(); } ///<summary> /// required by IXmlSerializable. /// This is wierd and sad, but this is tuned to the format we want in OptionLists. ///</summary> public void WriteXml(XmlWriter writer) { foreach (LanguageForm form in Forms) { writer.WriteStartElement("form"); writer.WriteAttributeString("lang", form.WritingSystemId); //notice, no <text> wrapper //the following makes us safe against codes like 0x1F, which can be easily //introduced via a right-click menu in a standard edit box (at least on windows) writer.WriteString(form.Form.EscapeAnyUnicodeCharactersIllegalInXml()); writer.WriteEndElement(); } } #region IReportEmptiness Members public bool ShouldHoldUpDeletionOfParentObject { get { return Empty; } } public bool ShouldCountAsFilledForPurposesOfConditionalDisplay { get { return !Empty; } } public bool ShouldBeRemovedFromParentDueToEmptiness { get { return Empty; } } /* /// <summary> /// skip those forms which are in audio writing systems /// </summary> public IList<LanguageForm> GetActualTextForms(WritingSystemCollection writingSytems) { var x= Forms.Where((f) => !writingSytems[f.WritingSystemId].IsAudio); return new List<LanguageForm>(x); } public IList<LanguageForm> GetAudioForms(WritingSystemCollection writingSytems) { var x = Forms.Where((f) => writingSytems[f.WritingSystemId].IsAudio); return new List<LanguageForm>(x); } */ public void RemoveEmptyStuff() { List<LanguageForm> condemened = new List<LanguageForm>(); foreach (LanguageForm f in Forms) { if (string.IsNullOrEmpty(f.Form)) { condemened.Add(f); } } foreach (LanguageForm f in condemened) { RemoveLanguageForm(f); } } #endregion public new static MultiText Create(Dictionary<string, string> forms) { MultiText m = new MultiText(); CopyForms(forms, m); return m; } public static MultiText Create(LiftMultiText liftMultiText) { if(liftMultiText == null) { throw new ArgumentNullException("liftMultiText"); } MultiText m = new MultiText(); Dictionary<string, string> forms = new Dictionary<string, string>(); foreach (KeyValuePair<string, LiftString> pair in liftMultiText) { if (pair.Value != null) { forms.Add(pair.Key, ConvertLiftStringToSimpleStringWithMarkers(pair.Value)); } } CopyForms(forms, m); return m; } public static MultiText Create(Dictionary<string, string> forms, Dictionary<string, List<LiftSpan>> spans) { if (forms == null) throw new ArgumentNullException("forms"); if (spans == null) spans = new Dictionary<string, List<LiftSpan>>(); MultiText m = new MultiText(); CopyForms(forms, m); m.CopySpans(spans); return m; } void CopySpans(Dictionary<string, List<LiftSpan>> spans) { foreach (var key in spans.Keys) { LanguageForm form = Find(key); if (form == null) continue; foreach (var span in spans[key]) { form.AddSpan(span.Index, span.Length, span.Lang, span.Class, span.LinkURL); } } } public static string ConvertLiftStringToSimpleStringWithMarkers(LiftString liftString) { string stringWithSpans = liftString.Text; SortedDictionary<KeyValuePair<int, string>, object> spanSorter= new SortedDictionary<KeyValuePair<int, string>, object>(new SpanPositionComparer()); //Sort the Span markers by position foreach (LiftSpan span in liftString.Spans) { string openMarker = buildOpenMarker(span); spanSorter.Add(new KeyValuePair<int, string>(span.Index, openMarker), null); string closeMarker = "</span>"; spanSorter.Add(new KeyValuePair<int, string>(span.Index + span.Length, closeMarker), null); } //Add the Span Markers one at a time from back to front foreach (KeyValuePair<KeyValuePair<int, string>, object> positionAndSpan in spanSorter) { stringWithSpans = stringWithSpans.Insert(positionAndSpan.Key.Key, positionAndSpan.Key.Value); } return stringWithSpans; } private static string buildOpenMarker(LiftSpan span) { string openMarker = string.Format( "<span"); if (!String.IsNullOrEmpty(span.Lang)) { openMarker += " lang=\"" + span.Lang +"\""; } if (!String.IsNullOrEmpty(span.LinkURL)) { openMarker += " href=\"" + span.LinkURL +"\""; } if (!String.IsNullOrEmpty(span.Class)) { openMarker += " class=\"" + span.Class +"\""; } openMarker += ">"; return openMarker; } private class SpanPositionComparer:IComparer<KeyValuePair<int, string>> { public int Compare(KeyValuePair<int, string> positionAndMarkerX, KeyValuePair<int, string> positionAndMarkerY) { if(positionAndMarkerX.Key < positionAndMarkerY.Key) { return 1; } if (positionAndMarkerX.Key > positionAndMarkerY.Key) { return -1; } else { if(positionAndMarkerX.Value == "</span>") { return 1; } if(positionAndMarkerY.Value == "</span>") { return -1; } else { return 1; } } } } public static string StripMarkers(string textToStrip) { if(string.IsNullOrEmpty(textToStrip)) { throw new ArgumentNullException("textToStrip"); } string wrappedTextToStrip = "<text>" + textToStrip + "</text>"; XmlReaderSettings fragmentReaderSettings = new XmlReaderSettings(); fragmentReaderSettings.ConformanceLevel = ConformanceLevel.Fragment; XmlReader testerForWellFormedness = XmlReader.Create(new StringReader(wrappedTextToStrip)); string strippedString = ""; try { while(testerForWellFormedness.Read()) { strippedString += testerForWellFormedness.ReadString(); } } catch { //If the text is not well formed XML just return it as text strippedString = textToStrip; } return strippedString; } public string GetFormWithoutSpans(string languageId) { return _liftMultitext[languageId].Text; } public bool ContainsEqualForm(string form, string writingSystemId) { return null != this.Forms.FirstOrDefault(f=> f.WritingSystemId ==writingSystemId && f.Form == form); } public virtual IPalasoDataObjectProperty Clone() { var clone = new MultiText(); clone.EmbeddedXmlElements = new List<string>(EmbeddedXmlElements); clone.Forms = Forms.Select(f => (LanguageForm) f.Clone()).ToArray(); return clone; } public virtual bool Equals(IPalasoDataObjectProperty other) { return Equals((MultiText) other); } public override bool Equals(Object obj) { if (obj == null) return false; if (obj.GetType() != typeof(MultiText)) return false; return Equals((MultiText)obj); } public bool Equals(MultiText multiText) { if (ReferenceEquals(null, multiText)) return false; if (ReferenceEquals(this, multiText)) return true; if (EmbeddedXmlElements.Count != multiText.EmbeddedXmlElements.Count) return false; if (!EmbeddedXmlElements.SequenceEqual(multiText.EmbeddedXmlElements)) return false; if (!base.Equals(multiText)) return false; return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Baseline; using LamarCodeGeneration; using Marten.Linq.Fields; using Marten.Schema.Identity; using Marten.Schema.Identity.Sequences; using Marten.Schema.Testing.Documents; using Marten.Schema.Testing.Hierarchies; using Marten.Storage; using Marten.Testing.Harness; using NpgsqlTypes; using Shouldly; using Xunit; namespace Marten.Schema.Testing { public class DocumentMappingTests: IntegrationContext { public class FieldId { public string id; } public abstract class AbstractDoc { public int id; } public interface IDoc { string id { get; set; } } [UseOptimisticConcurrency] public class VersionedDoc { public Guid Id { get; set; } = Guid.NewGuid(); } public class IntId { public int Id; } public class LongId { public long Id; } public class StringId { public string Id; } public class UpperCaseProperty { public Guid Id { get; set; } } public class LowerCaseProperty { public Guid id { get; set; } } public class UpperCaseField { public int Id; } public class LowerCaseField { public int id; } public class MySpecialDocument { public Guid Id { get; set; } } [PropertySearching(PropertySearching.JSON_Locator_Only)] public class Organization { [DuplicateField] public string OtherName; public string OtherProp; public Guid Id { get; set; } [DuplicateField] public string Name { get; set; } public string OtherField { get; set; } } public class CustomIdGeneration: IIdGeneration { public IEnumerable<Type> KeyTypes { get; } public IIdGenerator<T> Build<T>() { throw new NotImplementedException(); } public bool RequiresSequences { get; } = false; public void GenerateCode(GeneratedMethod assign, DocumentMapping mapping) { throw new NotImplementedException(); } } // SAMPLE: ConfigureMarten-generic public class ConfiguresItself { public Guid Id; public static void ConfigureMarten(DocumentMapping mapping) { mapping.Alias = "different"; } } // ENDSAMPLE // SAMPLE: ConfigureMarten-specifically public class ConfiguresItselfSpecifically { public Guid Id; public string Name; public static void ConfigureMarten(DocumentMapping<ConfiguresItselfSpecifically> mapping) { mapping.Duplicate(x => x.Name); } } // ENDSAMPLE [Fact] public void can_replace_hilo_def_settings() { var mapping = DocumentMapping.For<LongId>(); var newDef = new HiloSettings { MaxLo = 33 }; mapping.HiloSettings = newDef; var sequence = mapping.IdStrategy.ShouldBeOfType<HiloIdGeneration>(); sequence.MaxLo.ShouldBe(newDef.MaxLo); } [Fact] public void concrete_type_with_subclasses_is_hierarchy() { var mapping = DocumentMapping.For<User>(); mapping.AddSubClass(typeof(SuperUser)); mapping.IsHierarchy().ShouldBeTrue(); } [Fact] public void default_alias_for_a_type_that_is_not_nested() { var mapping = DocumentMapping.For<User>(); mapping.Alias.ShouldBe("user"); } [Fact] public void default_search_mode_is_jsonb_to_record() { var mapping = DocumentMapping.For<User>(); mapping.PropertySearching.ShouldBe(PropertySearching.JSON_Locator_Only); } [Fact] public void default_table_name() { var mapping = DocumentMapping.For<User>(); mapping.Table.Name.ShouldBe("mt_doc_user"); } [Fact] public void default_table_name_2() { var mapping = DocumentMapping.For<User>(); mapping.Table.QualifiedName.ShouldBe("public.mt_doc_user"); } [Fact] public void default_table_name_on_other_schema() { var mapping = DocumentMapping.For<User>("other"); mapping.Table.QualifiedName.ShouldBe("other.mt_doc_user"); } [Fact] public void default_table_name_on_overriden_schema() { var mapping = DocumentMapping.For<User>("other"); mapping.DatabaseSchemaName = "overriden"; mapping.Table.QualifiedName.ShouldBe("overriden.mt_doc_user"); } [Fact] public void default_table_name_with_different_shema() { var mapping = DocumentMapping.For<User>("other"); mapping.Table.QualifiedName.ShouldBe("other.mt_doc_user"); } [Fact] public void default_table_name_with_schema() { var mapping = DocumentMapping.For<User>(); mapping.Table.QualifiedName.ShouldBe("public.mt_doc_user"); } [Fact] public void default_upsert_name() { var mapping = DocumentMapping.For<User>(); mapping.UpsertFunction.Name.ShouldBe("mt_upsert_user"); } [Fact] public void default_upsert_name_with_different_schema() { var mapping = DocumentMapping.For<User>("other"); mapping.UpsertFunction.QualifiedName.ShouldBe("other.mt_upsert_user"); } [Fact] public void default_upsert_name_with_schema() { var mapping = DocumentMapping.For<User>(); mapping.UpsertFunction.QualifiedName.ShouldBe("public.mt_upsert_user"); } [Theory] [InlineData(EnumStorage.AsInteger)] [InlineData(EnumStorage.AsString)] public void enum_storage_should_be_taken_from_store_options(EnumStorage enumStorage) { var storeOptions = new StoreOptions(); storeOptions.UseDefaultSerialization(enumStorage); var mapping = new DocumentMapping<User>(storeOptions); mapping.EnumStorage.ShouldBe(enumStorage); } [Fact] public void doc_type_with_use_optimistic_concurrency_attribute() { DocumentMapping.For<VersionedDoc>() .UseOptimisticConcurrency.ShouldBeTrue(); } [Fact] public void duplicate_a_field() { var mapping = DocumentMapping.For<User>(); mapping.DuplicateField(nameof(User.FirstName)); mapping.FieldFor(nameof(User.FirstName)).ShouldBeOfType<DuplicatedField>(); // other fields are still the same SpecificationExtensions.ShouldNotBeOfType<DuplicatedField>(mapping.FieldFor(nameof(User.LastName))); } [Theory] [InlineData(EnumStorage.AsInteger, NpgsqlDbType.Integer)] [InlineData(EnumStorage.AsString, NpgsqlDbType.Varchar)] public void duplicated_field_enum_storage_should_be_taken_from_store_options_enum_storage_by_default(EnumStorage enumStorage, NpgsqlDbType expectedNpgsqlDbType) { var storeOptions = new StoreOptions(); storeOptions.UseDefaultSerialization(enumStorage); var mapping = new DocumentMapping<Target>(storeOptions); var duplicatedField = mapping.DuplicateField(nameof(Target.Color)); duplicatedField.DbType.ShouldBe(expectedNpgsqlDbType); } [Theory] [InlineData(EnumStorage.AsInteger, NpgsqlDbType.Integer)] [InlineData(EnumStorage.AsString, NpgsqlDbType.Varchar)] public void duplicated_field_enum_storage_should_be_taken_from_store_options_duplicated_field_enum_storage_when_it_was_changed(EnumStorage enumStorage, NpgsqlDbType expectedNpgsqlDbType) { var storeOptions = new StoreOptions(); storeOptions.DuplicatedFieldEnumStorage = enumStorage; var mapping = new DocumentMapping<Target>(storeOptions); var duplicatedField = mapping.DuplicateField(nameof(Target.Color)); duplicatedField.DbType.ShouldBe(expectedNpgsqlDbType); } [Theory] [InlineData(true, NpgsqlDbType.Timestamp)] [InlineData(false, NpgsqlDbType.TimestampTz)] public void duplicated_field_date_time_db_type_should_be_taken_from_store_options_useTimestampWithoutTimeZoneForDateTime(bool useTimestampWithoutTimeZoneForDateTime, NpgsqlDbType expectedNpgsqlDbType) { var storeOptions = new StoreOptions(); storeOptions.DuplicatedFieldUseTimestampWithoutTimeZoneForDateTime = useTimestampWithoutTimeZoneForDateTime; var mapping = new DocumentMapping<Target>(storeOptions); var duplicatedField = mapping.DuplicateField(nameof(Target.Date)); duplicatedField.DbType.ShouldBe(expectedNpgsqlDbType); } [Fact] public void find_field_for_immediate_field_that_is_not_duplicated() { var mapping = DocumentMapping.For<UpperCaseField>(); var field = mapping.FieldFor("Id"); field.Members.Single().ShouldBeAssignableTo<FieldInfo>() .Name.ShouldBe("Id"); } [Fact] public void find_field_for_immediate_property_that_is_not_duplicated() { var mapping = DocumentMapping.For<UpperCaseProperty>(); var field = mapping.FieldFor("Id"); field.Members.Single().ShouldBeAssignableTo<PropertyInfo>() .Name.ShouldBe("Id"); } [Fact] public void generate_a_table_to_the_database_with_duplicated_field() { using (var store = DocumentStore.For(ConnectionSource.ConnectionString)) { store.Advanced.Clean.CompletelyRemove(typeof(User)); var mapping = store.Tenancy.Default.MappingFor(typeof(User)).As<DocumentMapping>(); mapping.DuplicateField(nameof(User.FirstName)); store.Tenancy.Default.EnsureStorageExists(typeof(User)); store.Tenancy.Default.DbObjects.DocumentTables().ShouldContain(mapping.Table.QualifiedName); } } [Fact] public void get_the_sql_locator_for_the_Id_member() { DocumentMapping.For<User>().FieldFor("Id") .TypedLocator.ShouldBe("d.id"); DocumentMapping.For<FieldId>().FieldFor("id") .TypedLocator.ShouldBe("d.id"); } [Fact] public void is_hierarchy__is_false_for_concrete_type_with_no_subclasses() { DocumentMapping.For<User>().IsHierarchy().ShouldBeFalse(); } [Fact] public void is_hierarchy_always_true_for_abstract_type() { DocumentMapping.For<AbstractDoc>() .IsHierarchy().ShouldBeTrue(); } [Fact] public void is_hierarchy_always_true_for_interface() { DocumentMapping.For<IDoc>().IsHierarchy() .ShouldBeTrue(); } [Fact] public void optimistic_versioning_is_turned_off_by_default() { var mapping = DocumentMapping.For<User>(); mapping.UseOptimisticConcurrency.ShouldBeFalse(); } [Fact] public void override_the_alias() { var mapping = DocumentMapping.For<User>(); mapping.Alias = "users"; mapping.Table.Name.ShouldBe("mt_doc_users"); mapping.UpsertFunction.Name.ShouldBe("mt_upsert_users"); } [Fact] public void override_the_alias_converts_alias_to_lowercase() { var mapping = DocumentMapping.For<User>(); mapping.Alias = "Users"; mapping.Alias.ShouldBe("users"); } [Fact] public void override_the_alias_converts_table_name_to_lowercase() { var mapping = DocumentMapping.For<User>(); mapping.Alias = "Users"; mapping.Table.Name.ShouldBe("mt_doc_users"); } [Fact] public void override_the_alias_converts_tablename_with_different_schema_to_lowercase() { var mapping = DocumentMapping.For<User>("OTHER"); mapping.Alias = "Users"; mapping.Table.QualifiedName.ShouldBe("other.mt_doc_users"); } [Fact] public void override_the_alias_converts_tablename_with_schema_to_lowercase() { var mapping = DocumentMapping.For<User>(); mapping.Alias = "Users"; mapping.Table.QualifiedName.ShouldBe("public.mt_doc_users"); } [Fact] public void override_the_alias_converts_upsertname_to_lowercase() { var mapping = DocumentMapping.For<User>(); mapping.Alias = "Users"; mapping.UpsertFunction.Name.ShouldBe("mt_upsert_users"); } [Fact] public void override_the_alias_converts_upsertname_with_different_schema_to_lowercase() { var mapping = DocumentMapping.For<User>("OTHER"); mapping.Alias = "Users"; mapping.UpsertFunction.QualifiedName.ShouldBe("other.mt_upsert_users"); } [Fact] public void override_the_alias_converts_upsertname_with_schema_to_lowercase() { var mapping = DocumentMapping.For<User>(); mapping.Alias = "Users"; mapping.UpsertFunction.QualifiedName.ShouldBe("public.mt_upsert_users"); } [Fact] public void pick_up_lower_case_field_id() { var mapping = DocumentMapping.For<LowerCaseField>(); mapping.IdMember.ShouldBeAssignableTo<FieldInfo>() .Name.ShouldBe(nameof(LowerCaseField.id)); } [Fact] public void pick_up_lower_case_property_id() { var mapping = DocumentMapping.For<LowerCaseProperty>(); mapping.IdMember.ShouldBeAssignableTo<PropertyInfo>() .Name.ShouldBe(nameof(LowerCaseProperty.id)); } [Fact] public void pick_up_upper_case_field_id() { var mapping = DocumentMapping.For<UpperCaseField>(); mapping.IdMember.ShouldBeAssignableTo<FieldInfo>() .Name.ShouldBe(nameof(UpperCaseField.Id)); } [Fact] public void pick_up_upper_case_property_id() { var mapping = DocumentMapping.For<UpperCaseProperty>(); mapping.IdMember.ShouldBeAssignableTo<PropertyInfo>() .Name.ShouldBe(nameof(UpperCaseProperty.Id)); } [Fact] public void picks_up_marten_attibute_on_document_type() { var mapping = DocumentMapping.For<Organization>(); mapping.PropertySearching.ShouldBe(PropertySearching.JSON_Locator_Only); } [Fact] public void picks_up_searchable_attribute_on_fields() { var mapping = DocumentMapping.For<Organization>(); mapping.FieldFor("OtherName").ShouldBeOfType<DuplicatedField>(); SpecificationExtensions.ShouldNotBeOfType<DuplicatedField>(mapping.FieldFor(nameof(Organization.OtherField))); } [Fact] public void picks_up_searchable_attribute_on_properties() { var mapping = DocumentMapping.For<Organization>(); mapping.FieldFor(nameof(Organization.Name)).ShouldBeOfType<DuplicatedField>(); SpecificationExtensions.ShouldNotBeOfType<DuplicatedField>(mapping.FieldFor(nameof(Organization.OtherProp))); } [Fact] public void select_fields_for_non_hierarchy_mapping() { var mapping = DocumentMapping.For<User>(); mapping.SelectFields().ShouldHaveTheSameElementsAs("data", "id", DocumentMapping.VersionColumn); } [Fact] public void select_fields_with_subclasses() { var mapping = DocumentMapping.For<Squad>(); mapping.AddSubClass(typeof(BaseballTeam)); mapping.SelectFields() .ShouldHaveTheSameElementsAs("data", "id", DocumentMapping.DocumentTypeColumn, DocumentMapping.VersionColumn); } [Fact] public void select_fields_without_subclasses() { var mapping = DocumentMapping.For<User>(); mapping.SelectFields().ShouldHaveTheSameElementsAs("data", "id", DocumentMapping.VersionColumn); } [Fact] public void table_name_for_document() { DocumentMapping.For<MySpecialDocument>().Table.Name .ShouldBe("mt_doc_documentmappingtests_myspecialdocument"); } [Fact] public void table_name_with_schema_for_document() { DocumentMapping.For<MySpecialDocument>().Table.QualifiedName .ShouldBe("public.mt_doc_documentmappingtests_myspecialdocument"); } [Fact] public void table_name_with_schema_for_document_on_other_schema() { DocumentMapping.For<MySpecialDocument>("other").Table.QualifiedName .ShouldBe("other.mt_doc_documentmappingtests_myspecialdocument"); } [Fact] public void table_name_with_schema_for_document_on_overriden_schema() { var documentMapping = DocumentMapping.For<MySpecialDocument>("other"); documentMapping.DatabaseSchemaName = "overriden"; documentMapping.Table.QualifiedName .ShouldBe("overriden.mt_doc_documentmappingtests_myspecialdocument"); } [Fact] public void to_table_columns_with_duplicated_fields() { var mapping = DocumentMapping.For<User>(); mapping.DuplicateField(nameof(User.FirstName)); var table = new DocumentTable(mapping); table.Select(x => x.Name) .ShouldHaveTheSameElementsAs("id", "data", DocumentMapping.LastModifiedColumn, DocumentMapping.VersionColumn, DocumentMapping.DotNetTypeColumn, "first_name"); } [Fact] public void to_table_columns_with_subclasses() { var mapping = DocumentMapping.For<Squad>(); mapping.AddSubClass(typeof(BaseballTeam)); var table = new DocumentTable(mapping); var typeColumn = table.Last(); typeColumn.Name.ShouldBe(DocumentMapping.DocumentTypeColumn); typeColumn.Type.ShouldBe("varchar"); } [Fact] public void to_table_without_subclasses_and_no_duplicated_fields() { var mapping = DocumentMapping.For<IntDoc>(); var table = new DocumentTable(mapping); table.Select(x => x.Name) .ShouldHaveTheSameElementsAs("id", "data", DocumentMapping.LastModifiedColumn, DocumentMapping.VersionColumn, DocumentMapping.DotNetTypeColumn); } [Fact] public void to_upsert_baseline() { var mapping = DocumentMapping.For<Squad>(); var function = new UpsertFunction(mapping); function.Arguments.Select(x => x.Column) .ShouldHaveTheSameElementsAs("id", "data", DocumentMapping.VersionColumn, DocumentMapping.DotNetTypeColumn); } [Fact] public void to_upsert_with_duplicated_fields() { var mapping = DocumentMapping.For<User>(); mapping.DuplicateField(nameof(User.FirstName)); mapping.DuplicateField(nameof(User.LastName)); var function = new UpsertFunction(mapping); var args = function.Arguments.Select(x => x.Column).ToArray(); args.ShouldContain("first_name"); args.ShouldContain("last_name"); } [Fact] public void to_upsert_with_subclasses() { var mapping = DocumentMapping.For<Squad>(); mapping.AddSubClass(typeof(BaseballTeam)); var function = new UpsertFunction(mapping); function.Arguments.Select(x => x.Column) .ShouldHaveTheSameElementsAs("id", "data", DocumentMapping.VersionColumn, DocumentMapping.DotNetTypeColumn, DocumentMapping.DocumentTypeColumn); } [Fact] public void trying_to_replace_the_hilo_settings_when_not_using_hilo_for_the_sequence_throws() { Exception<InvalidOperationException>.ShouldBeThrownBy( () => { DocumentMapping.For<StringId>().HiloSettings = new HiloSettings(); }); } [Fact] public void upsert_name_for_document_type() { DocumentMapping.For<MySpecialDocument>().UpsertFunction.Name .ShouldBe("mt_upsert_documentmappingtests_myspecialdocument"); } [Fact] public void upsert_name_with_schema_for_document_type() { DocumentMapping.For<MySpecialDocument>().UpsertFunction.QualifiedName .ShouldBe("public.mt_upsert_documentmappingtests_myspecialdocument"); } [Fact] public void upsert_name_with_schema_for_document_type_on_other_schema() { DocumentMapping.For<MySpecialDocument>("other").UpsertFunction.QualifiedName .ShouldBe("other.mt_upsert_documentmappingtests_myspecialdocument"); } [Fact] public void upsert_name_with_schema_for_document_type_on_overriden_schema() { var documentMapping = DocumentMapping.For<MySpecialDocument>("other"); documentMapping.DatabaseSchemaName = "overriden"; documentMapping.UpsertFunction.QualifiedName .ShouldBe("overriden.mt_upsert_documentmappingtests_myspecialdocument"); } [Fact] public void use_custom_default_id_generation_for_long_id() { DocumentMapping.For<LongId>(idGeneration: (m, o) => new CustomIdGeneration()) .IdStrategy.ShouldBeOfType<CustomIdGeneration>(); } [Fact] public void use_custom_id_generation_on_mapping_shoudl_be_settable() { var mapping = DocumentMapping.For<LongId>(); mapping.IdStrategy = new CustomIdGeneration(); mapping.IdStrategy.ShouldBeOfType<CustomIdGeneration>(); } [Fact] public void use_guid_id_generation_for_guid_id() { var mapping = DocumentMapping.For<UpperCaseProperty>(); mapping.IdStrategy.ShouldBeOfType<CombGuidIdGeneration>(); } [Fact] public void use_hilo_id_generation_for_int_id() { DocumentMapping.For<IntId>() .IdStrategy.ShouldBeOfType<HiloIdGeneration>(); } [Fact] public void use_hilo_id_generation_for_long_id() { DocumentMapping.For<LongId>() .IdStrategy.ShouldBeOfType<HiloIdGeneration>(); } [Fact] public void use_string_id_generation_for_string() { var mapping = DocumentMapping.For<StringId>(); mapping.IdStrategy.ShouldBeOfType<StringIdGeneration>(); } // ENDSAMPLE [Fact] public void uses_ConfigureMarten_method_to_alter_mapping_upon_construction() { var mapping = DocumentMapping.For<ConfiguresItself>(); mapping.Alias.ShouldBe("different"); } // ENDSAMPLE [Fact] public void uses_ConfigureMarten_method_to_alter_mapping_upon_construction_with_the_generic_signature() { var mapping = DocumentMapping.For<ConfiguresItselfSpecifically>(); mapping.DuplicatedFields.Single().MemberName.ShouldBe(nameof(ConfiguresItselfSpecifically.Name)); } [Fact] public void trying_to_index_deleted_at_when_not_soft_deleted_document_throws() { Exception<InvalidOperationException>.ShouldBeThrownBy(() => DocumentMapping.For<IntId>().AddDeletedAtIndex()); } [Fact] public void no_tenant_id_column_when_not_conjoined_tenancy() { var mapping = DocumentMapping.For<ConfiguresItselfSpecifically>(); var table = new DocumentTable(mapping); table.HasColumn(TenantIdColumn.Name).ShouldBeFalse(); } [Fact] public void add_the_tenant_id_column_when_it_is_conjoined_tenancy() { var options = new StoreOptions(); options.Connection(ConnectionSource.ConnectionString); options.Policies.AllDocumentsAreMultiTenanted(); var mapping = new DocumentMapping(typeof(User), options); mapping.TenancyStyle = TenancyStyle.Conjoined; var table = new DocumentTable(mapping); table.Any(x => x is TenantIdColumn).ShouldBeTrue(); } [Fact] public void no_overwrite_function_if_no_optimistic_concurrency() { var mapping = DocumentMapping.For<User>(); var objects = mapping.As<IFeatureSchema>().Objects; objects.Length.ShouldBe(4); objects.Where(x => x.GetType() == typeof(UpsertFunction)).Single().Identifier.ShouldBe(mapping.UpsertFunction); } [Fact] public void add_overwrite_function_if_optimistic_concurrency() { var mapping = DocumentMapping.For<User>(); mapping.UseOptimisticConcurrency = true; var objects = mapping.As<IFeatureSchema>().Objects; objects.Length.ShouldBe(5); objects.OfType<OverwriteFunction>().Any().ShouldBeTrue(); } } }
using System; using System.Data; using NUnit.Framework; namespace BehaveN.Tests { [TestFixture] public class ValueSetterTests { [Test] public void Invalid() { Assert.That(ValueSetter.CanSetValue(this, "x"), Is.False); ValueSetter setter = ValueSetter.GetValueSetter(this, "x"); Assert.That(setter.CanSetValue(), Is.False); Assert.Throws(typeof(InvalidOperationException), delegate { setter.GetValueType(); }); Assert.Throws(typeof(InvalidOperationException), delegate { setter.SetValue(null); }); } [Test] public void IntField() { ReadWriteInts target = new ReadWriteInts(); Assert.That(ValueSetter.GetValueType(target, "IntField"), Is.SameAs(typeof(int))); Assert.That(ValueSetter.CanSetValue(target, "IntField"), Is.True); ValueSetter.SetValue(target, "IntField", 123); Assert.That(target.IntField, Is.EqualTo(123)); } [Test] public void IntFieldWithWrongCase() { ReadWriteInts target = new ReadWriteInts(); Assert.That(ValueSetter.CanSetValue(target, "iNTfIELD"), Is.True); ValueSetter.SetValue(target, "iNTfIELD", 123); Assert.That(target.IntField, Is.EqualTo(123)); } [Test] public void IntProperty() { ReadWriteInts target = new ReadWriteInts(); Assert.That(ValueSetter.CanSetValue(target, "IntProperty"), Is.True); ValueSetter.SetValue(target, "IntProperty", 123); Assert.That(target.IntProperty, Is.EqualTo(123)); } [Test] public void IntMethod() { ReadWriteInts target = new ReadWriteInts(); Assert.That(ValueSetter.CanSetValue(target, "IntMethod"), Is.True); ValueSetter.SetValue(target, "IntMethod", 123); Assert.That(target.IntMethod(), Is.EqualTo(123)); } [Test] public void ReadOnlyIntField() { ReadOnlyInts target = new ReadOnlyInts(); Assert.That(ValueSetter.CanSetValue(target, "IntField"), Is.False); } [Test] public void ReadOnlyIntProperty() { ReadOnlyInts target = new ReadOnlyInts(); Assert.That(ValueSetter.CanSetValue(target, "IntProperty"), Is.False); } [Test] public void ReadOnlyIntMethod() { ReadOnlyInts target = new ReadOnlyInts(); Assert.That(ValueSetter.CanSetValue(target, "IntMethod"), Is.False); } [Test] public void DataRowView() { DataTable dt = new DataTable(); dt.Columns.Add("IntColumn", typeof(int)); dt.Rows.Add(new object[] { 123 }); DataRowView target = dt.DefaultView[0]; Assert.That(ValueSetter.CanSetValue(target, "IntColumn"), Is.True); Assert.That(ValueSetter.GetValueType(target, "IntColumn"), Is.SameAs(typeof(int))); ValueSetter.SetValue(target, "IntColumn", 456); Assert.That((int)target["IntColumn"], Is.EqualTo(456)); } [Test] public void EnumField() { ReadWriteEnums target = new ReadWriteEnums(); ValueSetter.SetFormattedValue(target, "EnumField", "Bar"); Assert.That(target.EnumField, Is.EqualTo(TestEnum.Bar)); } [Test] public void EnumProperty() { ReadWriteEnums target = new ReadWriteEnums(); ValueSetter.SetFormattedValue(target, "EnumProperty", "Bar"); Assert.That(target.EnumProperty, Is.EqualTo(TestEnum.Bar)); } [Test] public void EnumMethod() { ReadWriteEnums target = new ReadWriteEnums(); ValueSetter.SetFormattedValue(target, "EnumMethod", "Bar"); Assert.That(target.EnumProperty, Is.EqualTo(TestEnum.Bar)); } [Test] public void NullableEnumWhenNull() { // There's no way to pass in null yet. //ReadWriteEnums target = new ReadWriteEnums(); //ValueSetter.SetFormattedValue(target, "NullableEnumField", ""); //Assert.That(target.NullableEnumField, Is.Null); // I think I meant that there's no string representation for null. // This is a problem for both reference and nullable types. } [Test] public void NullableEnumWhenNotNull() { ReadWriteEnums target = new ReadWriteEnums(); ValueSetter.SetFormattedValue(target, "NullableEnumField", "Bar"); Assert.That(target.NullableEnumField, Is.EqualTo(TestEnum.Bar)); } [Test] public void SettingFormattedValueOfNullOnIntFieldSetsItTo0() { ReadWriteInts target = new ReadWriteInts(); target.IntField = 123; ValueSetter.SetFormattedValue(target, "IntField", null); Assert.That(target.IntField, Is.EqualTo(0)); } [Test] public void SettingFormatedValueOfNullOnStringFieldSetsItToNull() { ReadWriteStrings target = new ReadWriteStrings(); target.StringField = "xxx"; ValueSetter.SetFormattedValue(target, "StringField", null); Assert.That(target.StringField, Is.Null); } [Test] public void SettingFormatedValueOnInt32FieldUsesInt32Parser() { ReadWriteInts target = new ReadWriteInts(); target.IntField = int.MinValue; ValueSetter.SetFormattedValue(target, "IntField", "123rd"); Assert.That(target.IntField, Is.EqualTo(123)); } [Test] public void SettingFormatedValueOnDateTimeFieldUsesDateTimeParser() { ReadWriteDateTimes target = new ReadWriteDateTimes(); target.DateTimeField = DateTime.MinValue; ValueSetter.SetFormattedValue(target, "DateTimeField", "Now"); DateTimeParserTests.AssertThatDateTimeIsCloseEnoughToNow(target.DateTimeField); } [Test] public void ListOfIntField() { ReadWriteLists target = new ReadWriteLists(); ValueSetter.SetFormattedValue(target, "ListOfInt", "123, 456"); Assert.That(target.ListOfInt, Is.EquivalentTo(new int[] { 123, 456 })); } [Test] public void IListOfIntField() { ReadWriteLists target = new ReadWriteLists(); ValueSetter.SetFormattedValue(target, "IListOfInt", "123, 456"); Assert.That(target.IListOfInt, Is.EquivalentTo(new int[] { 123, 456 })); } [Test] public void ICollectionOfIntField() { ReadWriteLists target = new ReadWriteLists(); ValueSetter.SetFormattedValue(target, "ICollectionOfInt", "123, 456"); Assert.That(target.ICollectionOfInt, Is.EquivalentTo(new int[] { 123, 456 })); } [Test] public void IEnumerableOfIntField() { ReadWriteLists target = new ReadWriteLists(); ValueSetter.SetFormattedValue(target, "IEnumerableOfInt", "123, 456"); Assert.That(target.IEnumerableOfInt, Is.EquivalentTo(new int[] { 123, 456 })); } } }
using UnityEngine; using System.Collections; public class CommonScript : MonoBehaviour { // Tablet vs phone private const float SCREEN_TABLET_PX = 900f; // Diagonal of a quarter of 1600x900 PC screen is big enough for "tablet" private const float SCREEN_TABLET_INCH = 6f; // Diagonal of most/all Android tablets are 7" or higher // Layer Z-values public const int LAYER_SLIDER = 3; public const int LAYER_NOTES = 4; public const int LAYER_TAPBOX = 5; // Time constants public const float TIME_FPS_UPDATE = 0.5f; // Delay between FPS counter updates public const float TIME_MUSIC_DELAY = -5.0f; // Delay before music starts public const float TIME_LOOKAHEAD = 0.8f; // Duration before loading note public const float TIME_ONSCREEN = 0.6f; // Duration on-screen public const float TIME_ONSCREEN_OPAQ = 0.5f; public const float TIME_ACTIVE = 0.3f; // Duration before time before active public const float TIME_MISS = -0.4f; // Duration after time before miss public const float TIME_REMOVE = -0.1f; // Destroy object after this time public const float TIME_TEXT_FADE = 1.0f; // Duration for combo and accuracy text public const float TIME_SCROLL = 1.355f; // Duration for scroll bar, chosen experimentally // so positions don't change for smooooch (~177 BPM) // Accuracy cutoffs public const float ACC_PRE_MARVEVLOUS = TIME_ACTIVE * 0.1f; public const float ACC_PRE_PERFECT = TIME_ACTIVE * 0.3f; public const float ACC_PRE_GREAT = TIME_ACTIVE * 0.5f; public const float ACC_PRE_GOOD = TIME_ACTIVE * 0.7f; public const float ACC_PRE_ALMOST = TIME_ACTIVE; public const float ACC_POST_MARVELOUS = TIME_MISS * 0.1f; public const float ACC_POST_PERFECT = TIME_MISS * 0.3f; public const float ACC_POST_GREAT = TIME_MISS * 0.5f; public const float ACC_POST_GOOD = TIME_MISS * 0.7f; public const float ACC_POST_ALMOST = TIME_MISS; public enum Accuracy { MARVELOUS, PERFECT, GREAT, GOOD, ALMOST, MISS }; // Current game mode public int modeNum; public bool autoPlay = false; // Music and time public float musicTime; // Assume the delay between Update() is small private AudioSource musicSrc; private bool musicStarted; // Score private int comboCurrent; private int comboMax; private exSpriteFont comboText; private float comboTextFadeTimer; public float comboTextY; private int accuracyTimeDiff; private int[] accuracyTable; private Accuracy accuracyCurrent; private exSpriteFont accuracyText; private float accuracyTextFadeTimer; public float accuracyTextY; private int noteCount; private int timeDiffAvg; private int timeDiffAvgNoteCount; private float timeDiffTotal; private float scorePercent; private exSpriteFont scoreText; private exSpriteFont gameStateText; // Game Over public bool gameOver; private float gameOverFadeTimer; // Tracker public TrackerScript tracker; public string level; public float diagonalInPixels; public float diagonalInInches; // Fading private FadeScript fade; private FeedbackScript feedback; // Use this for initialization void Start () { SetupTracker(); SetupFade(); SetupTime(); SetupScore(); } void SetupTracker() { tracker = GameObject.Find("Tracker").GetComponent<TrackerScript>(); // Determine if tablet or phone string screenType = "?"; if (Application.platform == RuntimePlatform.Android) { float widthInchesSqrd = Mathf.Pow(DisplayMetricsAndroid.WidthPixels / DisplayMetricsAndroid.XDPI, 2); float heightInchesSqrd = Mathf.Pow(DisplayMetricsAndroid.HeightPixels / DisplayMetricsAndroid.YDPI, 2); diagonalInInches = Mathf.Sqrt(widthInchesSqrd + heightInchesSqrd); //Debug.Log(string.Format("diagonalInInches = {0}", diagonalInInches)); if (diagonalInInches < SCREEN_TABLET_INCH) { screenType = "P"; } else { screenType = "T"; } } else { // Lets just use pixels diagonalInPixels = Mathf.Sqrt(Mathf.Pow(Screen.width, 2) + Mathf.Pow(Screen.height, 2)); //Debug.Log(string.Format("diagonalInPixels = {0}", diagonalInPixels)); if (diagonalInPixels < SCREEN_TABLET_PX) { screenType = "P"; } else { screenType = "T"; } } // Level name based on mode number level = string.Format("{0}{1}-{2}", modeNum, screenType, NotesData.DIFFICULTY_LEVEL.Substring(0, 1)); // Song started tracker.Counter(level, "started"); // Force send tracker.Resume(); tracker.Pause(); } // Fade in void SetupFade() { fade = GameObject.Find("Fade").GetComponent<FadeScript>(); fade.FadeIn(); feedback = GameObject.Find("Feedback").GetComponent<FeedbackScript>(); } // Setup music and global time void SetupTime() { musicTime = TIME_MUSIC_DELAY; musicSrc = (AudioSource)this.gameObject.GetComponent<AudioSource>(); } void SetupScore() { // Score comboCurrent = 0; comboMax = 0; accuracyTable = new int[System.Enum.GetNames(typeof(Accuracy)).Length + 1]; comboText = (exSpriteFont)GameObject.Find("ComboText").GetComponent<exSpriteFont>(); comboTextFadeTimer = 0f; comboText.text = ""; comboText.gameObject.transform.position = new Vector3(0, comboTextY, 0); accuracyText = (exSpriteFont)GameObject.Find("AccuracyText").GetComponent<exSpriteFont>(); accuracyTextFadeTimer = 0f; accuracyText.text = ""; accuracyText.gameObject.transform.position = new Vector3(0, accuracyTextY, 0); accuracyTimeDiff = 0; scoreText = (exSpriteFont)GameObject.Find("ScoreText").GetComponent<exSpriteFont>(); scorePercent = 0f; // Game state gameStateText = (exSpriteFont)GameObject.Find("GameStateText").GetComponent<exSpriteFont>(); gameStateText.text = "Ready"; gameOver = false; } // Update is called once per frame void Update () { UpdateTime(); UpdateScore(); } // Update global time void UpdateTime() { if (!musicStarted) { musicTime = Time.timeSinceLevelLoad + TIME_MUSIC_DELAY; if (musicTime > TIME_MUSIC_DELAY / 2) { gameStateText.topColor = new Color(1, 1, 1, musicTime / (TIME_MUSIC_DELAY / 2)); gameStateText.botColor = gameStateText.topColor; System.GC.Collect(); // Try to force cleanups } // Play music once delay over if (musicTime > 0) { musicStarted = true; musicSrc.Play(); gameStateText.text = ""; } } else { musicTime = musicSrc.time; } } // Update score text void UpdateScore() { if (gameOver) { gameOverFadeTimer -= Time.deltaTime; if (gameOverFadeTimer > 0 && gameOverFadeTimer > -TIME_MUSIC_DELAY / 2) { gameStateText.topColor = gameStateText.botColor = gameStateText.topColor = new Color(1, 1, 1, 1 - (gameOverFadeTimer - (-TIME_MUSIC_DELAY / 2))); } else { gameStateText.topColor = gameStateText.botColor = gameStateText.topColor = Color.white; } } if (comboTextFadeTimer > 0 && comboCurrent > 0) { comboText.text = string.Format("{0} Combo", comboCurrent); // Fade out comboTextFadeTimer -= Time.deltaTime; if (comboTextFadeTimer < TIME_TEXT_FADE / 2) { comboText.topColor = new Color(1, 1, 1, comboTextFadeTimer / (TIME_TEXT_FADE / 2)); comboText.botColor = comboText.topColor; } } if (accuracyTextFadeTimer > 0) { //accuracyText.text = string.Format("{0} ({1}ms)", accuracyCurrent.ToString(), accuracyTimeDiff); accuracyText.text = string.Format("{0}", accuracyCurrent.ToString()); // Fade out accuracyTextFadeTimer -= Time.deltaTime; if (accuracyTextFadeTimer < TIME_TEXT_FADE / 2) { accuracyText.topColor = new Color(1, 1, 1, accuracyTextFadeTimer / (TIME_TEXT_FADE / 2)); accuracyText.botColor = accuracyText.topColor; } } scoreText.text = string.Format( "Percent: {0:f1}%\n" + "{1} MARVELOUS\n" + "{2} PERFECT\n" + "{3} GREAT\n" + "{4} GOOD\n" + "{5} ALMOST\n" + "{6} MISS\n" + "{7} Combo MAX", scorePercent, accuracyTable.GetValue((int)Accuracy.MARVELOUS), accuracyTable.GetValue((int)Accuracy.PERFECT), accuracyTable.GetValue((int)Accuracy.GREAT), accuracyTable.GetValue((int)Accuracy.GOOD), accuracyTable.GetValue((int)Accuracy.ALMOST), accuracyTable.GetValue((int)Accuracy.MISS), comboMax ); } // Check accuracy vs values public void SetAccuracy(float timeDiff) { if (timeDiff >= 0) { if (timeDiff < ACC_PRE_MARVEVLOUS) { accuracyCurrent = Accuracy.MARVELOUS; } else if (timeDiff < ACC_PRE_PERFECT) { accuracyCurrent = Accuracy.PERFECT; } else if (timeDiff < ACC_PRE_GREAT) { accuracyCurrent = Accuracy.GREAT; } else if (timeDiff < ACC_PRE_GOOD) { accuracyCurrent = Accuracy.GOOD; } else if (timeDiff < ACC_PRE_ALMOST) { accuracyCurrent = Accuracy.ALMOST; } else { accuracyCurrent = Accuracy.MISS; } } else { if (timeDiff > ACC_POST_MARVELOUS) { accuracyCurrent = Accuracy.MARVELOUS; } else if (timeDiff > ACC_POST_PERFECT) { accuracyCurrent = Accuracy.PERFECT; } else if (timeDiff > ACC_POST_GREAT) { accuracyCurrent = Accuracy.GREAT; } else if (timeDiff > ACC_POST_GOOD) { accuracyCurrent = Accuracy.GOOD; } else if (timeDiff > ACC_POST_ALMOST) { accuracyCurrent = Accuracy.ALMOST; } else { accuracyCurrent = Accuracy.MISS; } } switch (accuracyCurrent) { case Accuracy.MARVELOUS: case Accuracy.PERFECT: case Accuracy.GREAT: // Increase combo comboCurrent++; if (comboCurrent > comboMax) { comboMax = comboCurrent; } comboTextFadeTimer = TIME_TEXT_FADE; comboText.topColor = new Color(1, 1, 1, 1); comboText.botColor = comboText.topColor; break; default: // Reset comboCurrent = 0; comboTextFadeTimer = 0f; comboText.text = ""; break; } accuracyTable[(int)accuracyCurrent]++; accuracyTextFadeTimer = TIME_TEXT_FADE; accuracyText.topColor = new Color(1, 1, 1, 1); accuracyText.botColor = accuracyText.topColor; accuracyTimeDiff = (int)(timeDiff * 1000); noteCount++; if (comboCurrent >= 1) { // Only average good hits timeDiffAvg = (timeDiffAvg * timeDiffAvgNoteCount + accuracyTimeDiff) / (timeDiffAvgNoteCount + 1); timeDiffAvgNoteCount++; } if (timeDiff >= 0) { timeDiffTotal += timeDiff; } else { timeDiffTotal -= timeDiff; } scorePercent = (1 - (timeDiffTotal / (noteCount * (-TIME_MISS)))) * 100f; if (scorePercent < 0) { scorePercent = 0f; } } // Tap down event public void OnTapDown(int id, Vector2 position) { if (gameOver) { feedback.OnTapDown(id, position); } } public void OnBackButton() { fade.FadeLaunch("Launcher"); } // Note hit public void OnNoteHit(NotesScript note){ float timeDiff = note.time - musicTime; SetAccuracy(timeDiff); note.state = NotesScript.NotesState.HIT; note.PlayHitAnim(); note.time_hit = musicTime; } public void OnNoteMiss(NotesScript note) { float timeDiff = note.time - musicTime; SetAccuracy(timeDiff); note.state = NotesScript.NotesState.MISS; note.PlayMissAnim(); } public void OnGameOver() { gameStateText.text = "Complete!"; gameOver = true; gameOverFadeTimer = -TIME_MUSIC_DELAY; ModeLauncherScript.modesDone[this.modeNum - 1] = true; SendTrackerData(); feedback.Show(); } public void SendTrackerData() { // Song finished tracker.Counter(level, "completed"); // Accuracy tracker.Average(level, "scorePercent", Mathf.RoundToInt(scorePercent)); // Rounded is good enough tracker.Average(level, "timeDiffAvg", timeDiffAvg); tracker.Average(level, "hit_5_MARVELOUS", (int)accuracyTable.GetValue((int)Accuracy.MARVELOUS)); tracker.Average(level, "hit_4_PERFECT", (int)accuracyTable.GetValue((int)Accuracy.PERFECT)); tracker.Average(level, "hit_3_GREAT", (int)accuracyTable.GetValue((int)Accuracy.GREAT)); tracker.Average(level, "hit_2_GOOD", (int)accuracyTable.GetValue((int)Accuracy.GOOD)); tracker.Average(level, "hit_1_ALMOST", (int)accuracyTable.GetValue((int)Accuracy.ALMOST)); tracker.Average(level, "hit_0_MISS", (int)accuracyTable.GetValue((int)Accuracy.MISS)); // Max combos tracker.Average(level, "comboMax", comboMax); // Force send tracker.Resume(); } public float GetTimeDiff(NotesScript note) { return note.time - musicTime; } public void CheckAutoPlay(NotesScript note, float timeDiff) { if (autoPlay && note.state == NotesScript.NotesState.ACTIVE) { if (timeDiff < ACC_PRE_MARVEVLOUS / 2) { // Super accuracy! OnNoteHit(note); } } } public void UpdateNoteState(NotesScript note, float timeDiff) { // Update alpha exSprite sprite = note.gameObject.GetComponent<exSprite>(); if (timeDiff > TIME_ONSCREEN_OPAQ) { sprite.color = new Color(1, 1, 1, 1 - (timeDiff - TIME_ONSCREEN_OPAQ) / (TIME_LOOKAHEAD - TIME_ONSCREEN_OPAQ)); } else { sprite.color = new Color(1, 1, 1, 1); } // We assume notes don't skip states (e.g. from DISABLE to MISS) switch(note.state) { case NotesScript.NotesState.DISABLE: if (timeDiff <= TIME_ACTIVE) { note.state = NotesScript.NotesState.ACTIVE; } break; case NotesScript.NotesState.ACTIVE: if (timeDiff <= TIME_MISS) { OnNoteMiss(note); } break; case NotesScript.NotesState.HIT: float hitTimeDiff = note.time_hit - musicTime; if (hitTimeDiff <= TIME_REMOVE) { note.state = NotesScript.NotesState.REMOVE; } break; case NotesScript.NotesState.MISS: // TODO if (timeDiff <= TIME_MISS + TIME_REMOVE) { note.state = NotesScript.NotesState.REMOVE; } break; case NotesScript.NotesState.REMOVE: default: break; } } }
/* * Farseer Physics Engine: * Copyright (c) 2012 Ian Qvist * * Original source Box2D: * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System; using System.Diagnostics; using FarseerPhysics.Collision; using FarseerPhysics.Collision.Shapes; using FarseerPhysics.Common; using Microsoft.Xna.Framework; namespace FarseerPhysics.Dynamics.Contacts { public sealed class ContactPositionConstraint { public Vector2[] localPoints = new Vector2[Settings.MaxManifoldPoints]; public Vector2 localNormal; public Vector2 localPoint; public int indexA; public int indexB; public float invMassA, invMassB; public Vector2 localCenterA, localCenterB; public float invIA, invIB; public ManifoldType type; public float radiusA, radiusB; public int pointCount; } public sealed class VelocityConstraintPoint { public Vector2 rA; public Vector2 rB; public float normalImpulse; public float tangentImpulse; public float normalMass; public float tangentMass; public float velocityBias; } public sealed class ContactVelocityConstraint { public VelocityConstraintPoint[] points = new VelocityConstraintPoint[Settings.MaxManifoldPoints]; public Vector2 normal; public Mat22 normalMass; public Mat22 K; public int indexA; public int indexB; public float invMassA, invMassB; public float invIA, invIB; public float friction; public float restitution; public float tangentSpeed; public int pointCount; public int contactIndex; public ContactVelocityConstraint() { for (int i = 0; i < Settings.MaxManifoldPoints; i++) { points[i] = new VelocityConstraintPoint(); } } } public class ContactSolver { public TimeStep _step; public Position[] _positions; public Velocity[] _velocities; public ContactPositionConstraint[] _positionConstraints; public ContactVelocityConstraint[] _velocityConstraints; public Contact[] _contacts; public int _count; public void Reset(TimeStep step, int count, Contact[] contacts, Position[] positions, Velocity[] velocities, bool warmstarting = Settings.EnableWarmstarting) { _step = step; _count = count; _positions = positions; _velocities = velocities; _contacts = contacts; // grow the array if (_velocityConstraints == null || _velocityConstraints.Length < count) { _velocityConstraints = new ContactVelocityConstraint[count * 2]; _positionConstraints = new ContactPositionConstraint[count * 2]; for (int i = 0; i < _velocityConstraints.Length; i++) { _velocityConstraints[i] = new ContactVelocityConstraint(); } for (int i = 0; i < _positionConstraints.Length; i++) { _positionConstraints[i] = new ContactPositionConstraint(); } } // Initialize position independent portions of the constraints. for (int i = 0; i < _count; ++i) { Contact contact = contacts[i]; Fixture fixtureA = contact.FixtureA; Fixture fixtureB = contact.FixtureB; Shape shapeA = fixtureA.Shape; Shape shapeB = fixtureB.Shape; float radiusA = shapeA.Radius; float radiusB = shapeB.Radius; Body bodyA = fixtureA.Body; Body bodyB = fixtureB.Body; Manifold manifold = contact.Manifold; int pointCount = manifold.PointCount; Debug.Assert(pointCount > 0); ContactVelocityConstraint vc = _velocityConstraints[i]; vc.friction = contact.Friction; vc.restitution = contact.Restitution; vc.tangentSpeed = contact.TangentSpeed; vc.indexA = bodyA.IslandIndex; vc.indexB = bodyB.IslandIndex; vc.invMassA = bodyA._invMass; vc.invMassB = bodyB._invMass; vc.invIA = bodyA._invI; vc.invIB = bodyB._invI; vc.contactIndex = i; vc.pointCount = pointCount; vc.K.SetZero(); vc.normalMass.SetZero(); ContactPositionConstraint pc = _positionConstraints[i]; pc.indexA = bodyA.IslandIndex; pc.indexB = bodyB.IslandIndex; pc.invMassA = bodyA._invMass; pc.invMassB = bodyB._invMass; pc.localCenterA = bodyA._sweep.LocalCenter; pc.localCenterB = bodyB._sweep.LocalCenter; pc.invIA = bodyA._invI; pc.invIB = bodyB._invI; pc.localNormal = manifold.LocalNormal; pc.localPoint = manifold.LocalPoint; pc.pointCount = pointCount; pc.radiusA = radiusA; pc.radiusB = radiusB; pc.type = manifold.Type; for (int j = 0; j < pointCount; ++j) { ManifoldPoint cp = manifold.Points[j]; VelocityConstraintPoint vcp = vc.points[j]; if (Settings.EnableWarmstarting) { vcp.normalImpulse = _step.dtRatio * cp.NormalImpulse; vcp.tangentImpulse = _step.dtRatio * cp.TangentImpulse; } else { vcp.normalImpulse = 0.0f; vcp.tangentImpulse = 0.0f; } vcp.rA = Vector2.Zero; vcp.rB = Vector2.Zero; vcp.normalMass = 0.0f; vcp.tangentMass = 0.0f; vcp.velocityBias = 0.0f; pc.localPoints[j] = cp.LocalPoint; } } } public void InitializeVelocityConstraints() { for (int i = 0; i < _count; ++i) { ContactVelocityConstraint vc = _velocityConstraints[i]; ContactPositionConstraint pc = _positionConstraints[i]; float radiusA = pc.radiusA; float radiusB = pc.radiusB; Manifold manifold = _contacts[vc.contactIndex].Manifold; int indexA = vc.indexA; int indexB = vc.indexB; float mA = vc.invMassA; float mB = vc.invMassB; float iA = vc.invIA; float iB = vc.invIB; Vector2 localCenterA = pc.localCenterA; Vector2 localCenterB = pc.localCenterB; Vector2 cA = _positions[indexA].c; float aA = _positions[indexA].a; Vector2 vA = _velocities[indexA].v; float wA = _velocities[indexA].w; Vector2 cB = _positions[indexB].c; float aB = _positions[indexB].a; Vector2 vB = _velocities[indexB].v; float wB = _velocities[indexB].w; Debug.Assert(manifold.PointCount > 0); Transform xfA = new Transform(); Transform xfB = new Transform(); xfA.q.Set(aA); xfB.q.Set(aB); xfA.p = cA - MathUtils.Mul(xfA.q, localCenterA); xfB.p = cB - MathUtils.Mul(xfB.q, localCenterB); Vector2 normal; FixedArray2<Vector2> points; WorldManifold.Initialize(ref manifold, ref xfA, radiusA, ref xfB, radiusB, out normal, out points); vc.normal = normal; int pointCount = vc.pointCount; for (int j = 0; j < pointCount; ++j) { VelocityConstraintPoint vcp = vc.points[j]; vcp.rA = points[j] - cA; vcp.rB = points[j] - cB; float rnA = MathUtils.Cross(vcp.rA, vc.normal); float rnB = MathUtils.Cross(vcp.rB, vc.normal); float kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; vcp.normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; Vector2 tangent = MathUtils.Cross(vc.normal, 1.0f); float rtA = MathUtils.Cross(vcp.rA, tangent); float rtB = MathUtils.Cross(vcp.rB, tangent); float kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; vcp.tangentMass = kTangent > 0.0f ? 1.0f / kTangent : 0.0f; // Setup a velocity bias for restitution. vcp.velocityBias = 0.0f; float vRel = Vector2.Dot(vc.normal, vB + MathUtils.Cross(wB, vcp.rB) - vA - MathUtils.Cross(wA, vcp.rA)); if (vRel < -Settings.VelocityThreshold) { vcp.velocityBias = -vc.restitution * vRel; } } // If we have two points, then prepare the block solver. if (vc.pointCount == 2) { VelocityConstraintPoint vcp1 = vc.points[0]; VelocityConstraintPoint vcp2 = vc.points[1]; float rn1A = MathUtils.Cross(vcp1.rA, vc.normal); float rn1B = MathUtils.Cross(vcp1.rB, vc.normal); float rn2A = MathUtils.Cross(vcp2.rA, vc.normal); float rn2B = MathUtils.Cross(vcp2.rB, vc.normal); float k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B; float k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B; float k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B; // Ensure a reasonable condition number. const float k_maxConditionNumber = 1000.0f; if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) { // K is safe to invert. vc.K.ex = new Vector2(k11, k12); vc.K.ey = new Vector2(k12, k22); vc.normalMass = vc.K.Inverse; } else { // The constraints are redundant, just use one. // TODO_ERIN use deepest? vc.pointCount = 1; } } } } public void WarmStart() { // Warm start. for (int i = 0; i < _count; ++i) { ContactVelocityConstraint vc = _velocityConstraints[i]; int indexA = vc.indexA; int indexB = vc.indexB; float mA = vc.invMassA; float iA = vc.invIA; float mB = vc.invMassB; float iB = vc.invIB; int pointCount = vc.pointCount; Vector2 vA = _velocities[indexA].v; float wA = _velocities[indexA].w; Vector2 vB = _velocities[indexB].v; float wB = _velocities[indexB].w; Vector2 normal = vc.normal; Vector2 tangent = MathUtils.Cross(normal, 1.0f); for (int j = 0; j < pointCount; ++j) { VelocityConstraintPoint vcp = vc.points[j]; Vector2 P = vcp.normalImpulse * normal + vcp.tangentImpulse * tangent; wA -= iA * MathUtils.Cross(vcp.rA, P); vA -= mA * P; wB += iB * MathUtils.Cross(vcp.rB, P); vB += mB * P; } _velocities[indexA].v = vA; _velocities[indexA].w = wA; _velocities[indexB].v = vB; _velocities[indexB].w = wB; } } public void SolveVelocityConstraints() { for (int i = 0; i < _count; ++i) { ContactVelocityConstraint vc = _velocityConstraints[i]; int indexA = vc.indexA; int indexB = vc.indexB; float mA = vc.invMassA; float iA = vc.invIA; float mB = vc.invMassB; float iB = vc.invIB; int pointCount = vc.pointCount; Vector2 vA = _velocities[indexA].v; float wA = _velocities[indexA].w; Vector2 vB = _velocities[indexB].v; float wB = _velocities[indexB].w; Vector2 normal = vc.normal; Vector2 tangent = MathUtils.Cross(normal, 1.0f); float friction = vc.friction; Debug.Assert(pointCount == 1 || pointCount == 2); // Solve tangent constraints first because non-penetration is more important // than friction. for (int j = 0; j < pointCount; ++j) { VelocityConstraintPoint vcp = vc.points[j]; // Relative velocity at contact Vector2 dv = vB + MathUtils.Cross(wB, vcp.rB) - vA - MathUtils.Cross(wA, vcp.rA); // Compute tangent force float vt = Vector2.Dot(dv, tangent) - vc.tangentSpeed; float lambda = vcp.tangentMass * (-vt); // b2Clamp the accumulated force float maxFriction = friction * vcp.normalImpulse; float newImpulse = MathUtils.Clamp(vcp.tangentImpulse + lambda, -maxFriction, maxFriction); lambda = newImpulse - vcp.tangentImpulse; vcp.tangentImpulse = newImpulse; // Apply contact impulse Vector2 P = lambda * tangent; vA -= mA * P; wA -= iA * MathUtils.Cross(vcp.rA, P); vB += mB * P; wB += iB * MathUtils.Cross(vcp.rB, P); } // Solve normal constraints if (vc.pointCount == 1) { VelocityConstraintPoint vcp = vc.points[0]; // Relative velocity at contact Vector2 dv = vB + MathUtils.Cross(wB, vcp.rB) - vA - MathUtils.Cross(wA, vcp.rA); // Compute normal impulse float vn = Vector2.Dot(dv, normal); float lambda = -vcp.normalMass * (vn - vcp.velocityBias); // b2Clamp the accumulated impulse float newImpulse = Math.Max(vcp.normalImpulse + lambda, 0.0f); lambda = newImpulse - vcp.normalImpulse; vcp.normalImpulse = newImpulse; // Apply contact impulse Vector2 P = lambda * normal; vA -= mA * P; wA -= iA * MathUtils.Cross(vcp.rA, P); vB += mB * P; wB += iB * MathUtils.Cross(vcp.rB, P); } else { // Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite). // Build the mini LCP for this contact patch // // vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2 // // A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n ) // b = vn0 - velocityBias // // The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i // implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases // vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid // solution that satisfies the problem is chosen. // // In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires // that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i). // // Substitute: // // x = a + d // // a := old total impulse // x := new total impulse // d := incremental impulse // // For the current iteration we extend the formula for the incremental impulse // to compute the new total impulse: // // vn = A * d + b // = A * (x - a) + b // = A * x + b - A * a // = A * x + b' // b' = b - A * a; VelocityConstraintPoint cp1 = vc.points[0]; VelocityConstraintPoint cp2 = vc.points[1]; Vector2 a = new Vector2(cp1.normalImpulse, cp2.normalImpulse); Debug.Assert(a.X >= 0.0f && a.Y >= 0.0f); // Relative velocity at contact Vector2 dv1 = vB + MathUtils.Cross(wB, cp1.rB) - vA - MathUtils.Cross(wA, cp1.rA); Vector2 dv2 = vB + MathUtils.Cross(wB, cp2.rB) - vA - MathUtils.Cross(wA, cp2.rA); // Compute normal velocity float vn1 = Vector2.Dot(dv1, normal); float vn2 = Vector2.Dot(dv2, normal); Vector2 b = new Vector2(); b.X = vn1 - cp1.velocityBias; b.Y = vn2 - cp2.velocityBias; // Compute b' b -= MathUtils.Mul(ref vc.K, a); const float k_errorTol = 1e-3f; //B2_NOT_USED(k_errorTol); for (; ; ) { // // Case 1: vn = 0 // // 0 = A * x + b' // // Solve for x: // // x = - inv(A) * b' // Vector2 x = -MathUtils.Mul(ref vc.normalMass, b); if (x.X >= 0.0f && x.Y >= 0.0f) { // Get the incremental impulse Vector2 d = x - a; // Apply incremental impulse Vector2 P1 = d.X * normal; Vector2 P2 = d.Y * normal; vA -= mA * (P1 + P2); wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2)); vB += mB * (P1 + P2); wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2)); // Accumulate cp1.normalImpulse = x.X; cp2.normalImpulse = x.Y; #if B2_DEBUG_SOLVER // Postconditions dv1 = vB + MathUtils.Cross(wB, cp1.rB) - vA - MathUtils.Cross(wA, cp1.rA); dv2 = vB + MathUtils.Cross(wB, cp2.rB) - vA - MathUtils.Cross(wA, cp2.rA); // Compute normal velocity vn1 = Vector2.Dot(dv1, normal); vn2 = Vector2.Dot(dv2, normal); b2Assert(b2Abs(vn1 - cp1.velocityBias) < k_errorTol); b2Assert(b2Abs(vn2 - cp2.velocityBias) < k_errorTol); #endif break; } // // Case 2: vn1 = 0 and x2 = 0 // // 0 = a11 * x1 + a12 * 0 + b1' // vn2 = a21 * x1 + a22 * 0 + b2' // x.X = -cp1.normalMass * b.X; x.Y = 0.0f; vn1 = 0.0f; vn2 = vc.K.ex.Y * x.X + b.Y; if (x.X >= 0.0f && vn2 >= 0.0f) { // Get the incremental impulse Vector2 d = x - a; // Apply incremental impulse Vector2 P1 = d.X * normal; Vector2 P2 = d.Y * normal; vA -= mA * (P1 + P2); wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2)); vB += mB * (P1 + P2); wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2)); // Accumulate cp1.normalImpulse = x.X; cp2.normalImpulse = x.Y; #if B2_DEBUG_SOLVER // Postconditions dv1 = vB + MathUtils.Cross(wB, cp1.rB) - vA - MathUtils.Cross(wA, cp1.rA); // Compute normal velocity vn1 = Vector2.Dot(dv1, normal); b2Assert(b2Abs(vn1 - cp1.velocityBias) < k_errorTol); #endif break; } // // Case 3: vn2 = 0 and x1 = 0 // // vn1 = a11 * 0 + a12 * x2 + b1' // 0 = a21 * 0 + a22 * x2 + b2' // x.X = 0.0f; x.Y = -cp2.normalMass * b.Y; vn1 = vc.K.ey.X * x.Y + b.X; vn2 = 0.0f; if (x.Y >= 0.0f && vn1 >= 0.0f) { // Resubstitute for the incremental impulse Vector2 d = x - a; // Apply incremental impulse Vector2 P1 = d.X * normal; Vector2 P2 = d.Y * normal; vA -= mA * (P1 + P2); wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2)); vB += mB * (P1 + P2); wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2)); // Accumulate cp1.normalImpulse = x.X; cp2.normalImpulse = x.Y; #if B2_DEBUG_SOLVER // Postconditions dv2 = vB + MathUtils.Cross(wB, cp2.rB) - vA - MathUtils.Cross(wA, cp2.rA); // Compute normal velocity vn2 = Vector2.Dot(dv2, normal); b2Assert(b2Abs(vn2 - cp2.velocityBias) < k_errorTol); #endif break; } // // Case 4: x1 = 0 and x2 = 0 // // vn1 = b1 // vn2 = b2; x.X = 0.0f; x.Y = 0.0f; vn1 = b.X; vn2 = b.Y; if (vn1 >= 0.0f && vn2 >= 0.0f) { // Resubstitute for the incremental impulse Vector2 d = x - a; // Apply incremental impulse Vector2 P1 = d.X * normal; Vector2 P2 = d.Y * normal; vA -= mA * (P1 + P2); wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2)); vB += mB * (P1 + P2); wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2)); // Accumulate cp1.normalImpulse = x.X; cp2.normalImpulse = x.Y; break; } // No solution, give up. This is hit sometimes, but it doesn't seem to matter. break; } } _velocities[indexA].v = vA; _velocities[indexA].w = wA; _velocities[indexB].v = vB; _velocities[indexB].w = wB; } } public void StoreImpulses() { for (int i = 0; i < _count; ++i) { ContactVelocityConstraint vc = _velocityConstraints[i]; Manifold manifold = _contacts[vc.contactIndex].Manifold; for (int j = 0; j < vc.pointCount; ++j) { ManifoldPoint point = manifold.Points[j]; point.NormalImpulse = vc.points[j].normalImpulse; point.TangentImpulse = vc.points[j].tangentImpulse; manifold.Points[j] = point; } _contacts[vc.contactIndex].Manifold = manifold; } } public bool SolvePositionConstraints() { float minSeparation = 0.0f; for (int i = 0; i < _count; ++i) { ContactPositionConstraint pc = _positionConstraints[i]; int indexA = pc.indexA; int indexB = pc.indexB; Vector2 localCenterA = pc.localCenterA; float mA = pc.invMassA; float iA = pc.invIA; Vector2 localCenterB = pc.localCenterB; float mB = pc.invMassB; float iB = pc.invIB; int pointCount = pc.pointCount; Vector2 cA = _positions[indexA].c; float aA = _positions[indexA].a; Vector2 cB = _positions[indexB].c; float aB = _positions[indexB].a; // Solve normal constraints for (int j = 0; j < pointCount; ++j) { Transform xfA = new Transform(); Transform xfB = new Transform(); xfA.q.Set(aA); xfB.q.Set(aB); xfA.p = cA - MathUtils.Mul(xfA.q, localCenterA); xfB.p = cB - MathUtils.Mul(xfB.q, localCenterB); Vector2 normal; Vector2 point; float separation; PositionSolverManifold.Initialize(pc, xfA, xfB, j, out normal, out point, out separation); Vector2 rA = point - cA; Vector2 rB = point - cB; // Track max constraint error. minSeparation = Math.Min(minSeparation, separation); // Prevent large corrections and allow slop. float C = MathUtils.Clamp(Settings.Baumgarte * (separation + Settings.LinearSlop), -Settings.MaxLinearCorrection, 0.0f); // Compute the effective mass. float rnA = MathUtils.Cross(rA, normal); float rnB = MathUtils.Cross(rB, normal); float K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; // Compute normal impulse float impulse = K > 0.0f ? -C / K : 0.0f; Vector2 P = impulse * normal; cA -= mA * P; aA -= iA * MathUtils.Cross(rA, P); cB += mB * P; aB += iB * MathUtils.Cross(rB, P); } _positions[indexA].c = cA; _positions[indexA].a = aA; _positions[indexB].c = cB; _positions[indexB].a = aB; } // We can't expect minSpeparation >= -b2_linearSlop because we don't // push the separation above -b2_linearSlop. return minSeparation >= -3.0f * Settings.LinearSlop; } // Sequential position solver for position constraints. public bool SolveTOIPositionConstraints(int toiIndexA, int toiIndexB) { float minSeparation = 0.0f; for (int i = 0; i < _count; ++i) { ContactPositionConstraint pc = _positionConstraints[i]; int indexA = pc.indexA; int indexB = pc.indexB; Vector2 localCenterA = pc.localCenterA; Vector2 localCenterB = pc.localCenterB; int pointCount = pc.pointCount; float mA = 0.0f; float iA = 0.0f; if (indexA == toiIndexA || indexA == toiIndexB) { mA = pc.invMassA; iA = pc.invIA; } float mB = 0.0f; float iB = 0.0f; if (indexB == toiIndexA || indexB == toiIndexB) { mB = pc.invMassB; iB = pc.invIB; } Vector2 cA = _positions[indexA].c; float aA = _positions[indexA].a; Vector2 cB = _positions[indexB].c; float aB = _positions[indexB].a; // Solve normal constraints for (int j = 0; j < pointCount; ++j) { Transform xfA = new Transform(); Transform xfB = new Transform(); xfA.q.Set(aA); xfB.q.Set(aB); xfA.p = cA - MathUtils.Mul(xfA.q, localCenterA); xfB.p = cB - MathUtils.Mul(xfB.q, localCenterB); Vector2 normal; Vector2 point; float separation; PositionSolverManifold.Initialize(pc, xfA, xfB, j, out normal, out point, out separation); Vector2 rA = point - cA; Vector2 rB = point - cB; // Track max constraint error. minSeparation = Math.Min(minSeparation, separation); // Prevent large corrections and allow slop. float C = MathUtils.Clamp(Settings.Baumgarte * (separation + Settings.LinearSlop), -Settings.MaxLinearCorrection, 0.0f); // Compute the effective mass. float rnA = MathUtils.Cross(rA, normal); float rnB = MathUtils.Cross(rB, normal); float K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; // Compute normal impulse float impulse = K > 0.0f ? -C / K : 0.0f; Vector2 P = impulse * normal; cA -= mA * P; aA -= iA * MathUtils.Cross(rA, P); cB += mB * P; aB += iB * MathUtils.Cross(rB, P); } _positions[indexA].c = cA; _positions[indexA].a = aA; _positions[indexB].c = cB; _positions[indexB].a = aB; } // We can't expect minSpeparation >= -b2_linearSlop because we don't // push the separation above -b2_linearSlop. return minSeparation >= -1.5f * Settings.LinearSlop; } public static class WorldManifold { /// <summary> /// Evaluate the manifold with supplied transforms. This assumes /// modest motion from the original state. This does not change the /// point count, impulses, etc. The radii must come from the Shapes /// that generated the manifold. /// </summary> /// <param name="manifold">The manifold.</param> /// <param name="xfA">The transform for A.</param> /// <param name="radiusA">The radius for A.</param> /// <param name="xfB">The transform for B.</param> /// <param name="radiusB">The radius for B.</param> /// <param name="normal">World vector pointing from A to B</param> /// <param name="points">Torld contact point (point of intersection).</param> public static void Initialize(ref Manifold manifold, ref Transform xfA, float radiusA, ref Transform xfB, float radiusB, out Vector2 normal, out FixedArray2<Vector2> points) { normal = Vector2.Zero; points = new FixedArray2<Vector2>(); if (manifold.PointCount == 0) { return; } switch (manifold.Type) { case ManifoldType.Circles: { normal = new Vector2(1.0f, 0.0f); Vector2 pointA = MathUtils.Mul(ref xfA, manifold.LocalPoint); Vector2 pointB = MathUtils.Mul(ref xfB, manifold.Points[0].LocalPoint); if (Vector2.DistanceSquared(pointA, pointB) > Settings.Epsilon * Settings.Epsilon) { normal = pointB - pointA; normal.Normalize(); } Vector2 cA = pointA + radiusA * normal; Vector2 cB = pointB - radiusB * normal; points[0] = 0.5f * (cA + cB); } break; case ManifoldType.FaceA: { normal = MathUtils.Mul(xfA.q, manifold.LocalNormal); Vector2 planePoint = MathUtils.Mul(ref xfA, manifold.LocalPoint); for (int i = 0; i < manifold.PointCount; ++i) { Vector2 clipPoint = MathUtils.Mul(ref xfB, manifold.Points[i].LocalPoint); Vector2 cA = clipPoint + (radiusA - Vector2.Dot(clipPoint - planePoint, normal)) * normal; Vector2 cB = clipPoint - radiusB * normal; points[i] = 0.5f * (cA + cB); } } break; case ManifoldType.FaceB: { normal = MathUtils.Mul(xfB.q, manifold.LocalNormal); Vector2 planePoint = MathUtils.Mul(ref xfB, manifold.LocalPoint); for (int i = 0; i < manifold.PointCount; ++i) { Vector2 clipPoint = MathUtils.Mul(ref xfA, manifold.Points[i].LocalPoint); Vector2 cB = clipPoint + (radiusB - Vector2.Dot(clipPoint - planePoint, normal)) * normal; Vector2 cA = clipPoint - radiusA * normal; points[i] = 0.5f * (cA + cB); } // Ensure normal points from A to B. normal = -normal; } break; } } } private static class PositionSolverManifold { public static void Initialize(ContactPositionConstraint pc, Transform xfA, Transform xfB, int index, out Vector2 normal, out Vector2 point, out float separation) { Debug.Assert(pc.pointCount > 0); switch (pc.type) { case ManifoldType.Circles: { Vector2 pointA = MathUtils.Mul(ref xfA, pc.localPoint); Vector2 pointB = MathUtils.Mul(ref xfB, pc.localPoints[0]); normal = pointB - pointA; normal.Normalize(); point = 0.5f * (pointA + pointB); separation = Vector2.Dot(pointB - pointA, normal) - pc.radiusA - pc.radiusB; } break; case ManifoldType.FaceA: { normal = MathUtils.Mul(xfA.q, pc.localNormal); Vector2 planePoint = MathUtils.Mul(ref xfA, pc.localPoint); Vector2 clipPoint = MathUtils.Mul(ref xfB, pc.localPoints[index]); separation = Vector2.Dot(clipPoint - planePoint, normal) - pc.radiusA - pc.radiusB; point = clipPoint; } break; case ManifoldType.FaceB: { normal = MathUtils.Mul(xfB.q, pc.localNormal); Vector2 planePoint = MathUtils.Mul(ref xfB, pc.localPoint); Vector2 clipPoint = MathUtils.Mul(ref xfA, pc.localPoints[index]); separation = Vector2.Dot(clipPoint - planePoint, normal) - pc.radiusA - pc.radiusB; point = clipPoint; // Ensure normal points from A to B normal = -normal; } break; default: normal = Vector2.Zero; point = Vector2.Zero; separation = 0; break; } } } } }
using System; using System.Resources; using System.Reflection; using System.Globalization; using System.Threading; namespace MemHack { /// <summary> /// Summary description for Resources. /// </summary> public class Resources { static ResourceManager rm = new ResourceManager("MemHack.strings", typeof(Resources).Assembly); static public bool ValidateResources = false; static ResourceSet rs = null; static string GetString(string name) { string s; lock(rm) { // ValidateResources allows a caller to ensure that they have configured all the string // values used in the UI. It will throw an exception containing the locale if it can't find // the resources and it will throw an exception if it attempts to load a string that // isn't defined in the resource set (and Test ensures that all strings are defined). if(ValidateResources && rs == null) { rs = rm.GetResourceSet(Thread.CurrentThread.CurrentCulture, false, false); if(rs == null) throw new System.NotImplementedException(Thread.CurrentThread.CurrentCulture.ToString()); } } // ResourceSet.GetString doesn't quite follow the same semantics as ResourceManager.GetString // The former won't fall back to what is in the application resource manifest while the latter will // so if ValidateResources is off, we want to ensure we use that fallback since the manifest // does have them all defined. if(ValidateResources) s = rs.GetString(name); else s = rm.GetString(name); if(string.IsNullOrEmpty(s)) throw new System.NotImplementedException(name); return s; } public static string FindFirst { get{return GetString("FindFirst");} } public static string FindNext { get{return GetString("FindNext");} } public static string ValueLabel { get{return GetString("ValueLabel");} } public static string AddressesFoundLabel { get{return GetString("AddressesFoundLabel");} } public static string MessagesLabel { get{return GetString("MessagesLabel");} } public static string NoAddressesFound { get{return GetString("NoAddressesFound");} } public static string Set { get{return GetString("Set");} } public static string SearchSizeLabel { get{return GetString("SearchSizeLabel");} } public static string Unknown { get{return GetString("Unknown");} } public static string Bytes8 { get{return GetString("8Bytes");} } public static string Bytes4 { get{return GetString("4Bytes");} } public static string Bytes2 { get{return GetString("2Bytes");} } public static string Bytes1 { get{return GetString("1Byte");} } public static string FindFirstValue { get{return GetString("FindFirstValue");} } public static string Address { get{return GetString("Address");} } public static string Value { get{return GetString("Value");} } public static string MemoryHacker { get{return GetString("MemoryHacker");} } public static string MemoryHackerFormatString { get{return GetString("MemoryHackerFormatString");} } public static string SearchSize1Byte { get{return GetString("SearchSize1Byte");} } public static string SearchSize2Bytes { get{return GetString("SearchSize2Bytes");} } public static string SearchSize4Bytes { get{return GetString("SearchSize4Bytes");} } public static string SearchSize8Bytes { get{return GetString("SearchSize8Bytes");} } public static string SearchingForFormatString { get{return GetString("SearchingForFormatString");} } public static string FindFirstFoundFormatString { get{return GetString("FindFirstFoundFormatString");} } public static string FindFirstFailedFormatString { get{return GetString("FindFirstFailedFormatString");} } public static string FindNextFoundFormatString { get{return GetString("FindNextFoundFormatString");} } public static string FindNextFailedFormatString { get{return GetString("FindNextFailedFormatString");} } public static string FindFirstCanceled { get{return GetString("FindFirstCanceled");} } public static string FindNextCanceled { get{return GetString("FindNextCanceled");} } public static string SetValue { get{return GetString("SetValue");} } public static string ErrorInvalidAddressFormatString { get{return GetString("ErrorInvalidAddressFormatString");} } public static string ValueAtAddressFormatString { get{return GetString("ValueAtAddressFormatString");} } public static string ValueAtAddressSetFormatString { get{return GetString("ValueAtAddressSetFormatString");} } public static string ErrorValueNotSetFormatString { get{return GetString("ErrorValueNotSetFormatString");} } public static string ErrorSetValueFailedFormatString { get{return GetString("ErrorSetValueFailedFormatString");} } public static string SetValueCanceled { get{return GetString("SetValueCanceled");} } public static string SelectNext { get{return GetString("SelectNext");} } public static string ErrorFailedToConvert { get{return GetString("ErrorFailedToConvert");} } public static string ErrorProcessSelect { get{return GetString("ErrorProcessSelect");} } public static string ErrorProcessThisOne { get{return GetString("ErrorProcessThisOne");} } public static string ErrorProcessUnmodifiable { get{return GetString("ErrorProcessUnmodifiable");} } public static string ErrorProcessOpenFailed { get{return GetString("ErrorProcessOpenFailed");} } public static string Select { get{return GetString("Select");} } public static string RunningProgramsLabel { get{return GetString("RunningProgramsLabel");} } public static string ProcessNameLabel { get{return GetString("ProcessNameLabel");} } public static string ID { get{return GetString("ID");} } public static string Name { get{return GetString("Name");} } public static string Title { get{return GetString("Title");} } public static string IdleProcessName { get{return GetString("IdleProcessName");} } public static string SystemName { get{return GetString("SystemName");} } public static string ProgressTitle { get{return GetString("ProgressTitle");} } public static string ToolTip_ProcessList { get{return GetString("ToolTip_ProcessList");} } public static string ToolTip_FriendlyNames { get{return GetString("ToolTip_FriendlyNames");} } public static string ToolTip_SelectProcess { get{return GetString("ToolTip_SelectProcess");} } public static string ToolTip_ApplicationPath { get{return GetString("ToolTip_ApplicationPath");} } public static string ToolTip_MemHackDlg { get{return GetString("ToolTip_MemHackDlg");} } public static string ToolTip_AddressList { get{return GetString("ToolTip_AddressList");} } public static string ToolTip_FindFirst { get{return GetString("ToolTip_FindFirst");} } public static string ToolTip_FindNext { get{return GetString("ToolTip_FindNext");} } public static string ToolTip_Set { get{return GetString("ToolTip_Set");} } public static string ToolTip_Messages { get{return GetString("ToolTip_Messages");} } public static string ToolTip_MemDisplayDlg { get{return GetString("ToolTip_MemDisplayDlg");} } public static string ToolTip_FindFirst1Byte { get{return GetString("ToolTip_FindFirst1Byte");} } public static string ToolTip_FindFirst2Bytes { get{return GetString("ToolTip_FindFirst2Bytes");} } public static string ToolTip_FindFirst4Bytes { get{return GetString("ToolTip_FindFirst4Bytes");} } public static string ToolTip_FindFirst8Bytes { get{return GetString("ToolTip_FindFirst8Bytes");} } public static string ToolTip_FindFirstValue { get{return GetString("ToolTip_FindFirstValue");} } public static string ToolTip_FindFirstDlg { get{return GetString("ToolTip_FindFirstDlg");} } public static string ToolTip_FindFirstButton { get{return GetString("ToolTip_FindFirstButton");} } public static string ToolTip_FindNextDlg { get{return GetString("ToolTip_FindNextDlg");} } public static string ToolTip_FindNextValue { get{return GetString("ToolTip_FindNextValue");} } public static string ToolTip_FindNextButton { get{return GetString("ToolTip_FindNextButton");} } public static string ToolTip_SetDlg { get{return GetString("ToolTip_SetDlg");} } public static string ToolTip_SetValue { get{return GetString("ToolTip_SetValue");} } public static string ToolTip_SetButton { get{return GetString("ToolTip_SetButton");} } public static string ToolTip_ProgressFormatString { get{return GetString("ToolTip_ProgressFormatString");} } public static void Test() { // If there is localization information, I like to be sure it is all defined correctly--useful for // external localizers to ensure that all the strings are defined correctly. MethodInfo [] mis = typeof(Resources).GetMethods(BindingFlags.Public | BindingFlags.Static); object [] paramList = new object [0]; string res = string.Empty; foreach(MethodInfo mi in mis) { if(mi.ReturnType != typeof(string) || mi.GetParameters().Length != 0 || mi.IsSpecialName == false || !mi.Name.StartsWith("get_")) continue; // System.Diagnostics.Debug.WriteLine("Testing: " + mi.Name); res = (string) mi.Invoke(null, paramList); } } ~Resources() { rm.ReleaseAllResources(); } } }
namespace System.Collections { using FluentAssertions; using System; using System.Collections.Generic; using Xunit; public class IEnumerableExtensionsTest { [Fact] public void any_should_not_allow_null_sequence() { // arrange var sequence = default( IEnumerable ); // act Action any = () => IEnumerableExtensions.Any( sequence ); // assert any.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be( nameof( sequence ) ); } [Fact] public void any_should_return_true_for_nonX2Dempty_sequence() { // arrange IEnumerable sequence = new List<object>() { new object() }; // act var result = sequence.Any(); // assert result.Should().BeTrue(); } [Fact] public void any_should_return_false_for_empty_sequence() { // arrange IEnumerable sequence = new List<object>(); // act var result = sequence.Any(); // assert result.Should().BeFalse(); } [Fact] public void count_should_not_allow_null_sequence() { // arrange var sequence = default( IEnumerable ); // act Action count = () => IEnumerableExtensions.Count( sequence ); // assert count.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be( nameof( sequence ) ); } [Fact] public void count_should_return_number_of_elements_in_sequence() { // arrange IEnumerable sequence = new List<object>() { new object(), new object(), new object() }; // act var count = sequence.Count(); // assert count.Should().Be( 3 ); } [Fact] public void index_should_not_allow_null_sequence() { // arrange var sequence = default( IEnumerable ); // act Action indexOf = () => IEnumerableExtensions.IndexOf( sequence, default( object ) ); // assert indexOf.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be( nameof( sequence ) ); } [Fact] public void index_of_should_not_allow_null_comparer() { // arrange var comparer = default( IEqualityComparer ); // act Action indexOf = () => IEnumerableExtensions.IndexOf( new ArrayList(), new object(), comparer ); // assert indexOf.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be( nameof( comparer ) ); } [Fact] public void index_of_should_return_expected_value() { // arrange var item = new object(); IEnumerable sequence = new List<object>() { new object(), new object(), item }; IEqualityComparer comparer = EqualityComparer<object>.Default; // act var index = sequence.IndexOf( item, comparer ); // assert index.Should().Be( 2 ); } [Fact] public void index_of_should_return_X2D1_if_not_found() { // arrange IEnumerable sequence = new List<object>() { new object() }; IEqualityComparer comparer = EqualityComparer<object>.Default; // act var index = sequence.IndexOf( new object(), comparer ); // assert index.Should().Be( -1 ); } [Fact] public void element_at_should_not_allow_null_sequence() { // arrange var sequence = default( IEnumerable ); // act Action elementAt = () => IEnumerableExtensions.ElementAt( sequence, 0 ); // assert elementAt.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be( nameof( sequence ) ); } [Theory] [InlineData( -1 )] [InlineData( 1 )] public void element_at_should_not_allow_index_out_of_range( int index ) { // arrange IEnumerable sequence = new List<object>(); // act Action elementAt = () => sequence.ElementAt( index ); // assert elementAt.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( index ) ); } [Fact] public void element_at_should_return_expected_value_from_list() { // arrange var expected = new object(); IEnumerable sequence = new List<object>() { new object(), new object(), expected }; // act var item = sequence.ElementAt( 2 ); // assert item.Should().Be( expected ); } [Fact] public void element_at_should_return_expected_value_from_dictionary() { // arrange ICollection<KeyValuePair<int, object>> dictionary = new Dictionary<int, object>() { [0] = new object(), [1] = new object(), [2] = new object() }; IEnumerable sequence = dictionary; var items = new KeyValuePair<int, object>[3]; dictionary.CopyTo( items, 0 ); var expected = items[2]; // act var item = sequence.ElementAt( 2 ); // assert item.Should().Be( expected ); } [Theory] [InlineData( -1 )] [InlineData( 3 )] public void element_at_or_default_should_return_null_for_index_out_of_range( int index ) { // arrange IEnumerable sequence = new[] { new object(), new object(), new object() }; // act var item = sequence.ElementAtOrDefault( index ); // assert item.Should().BeNull(); } [Fact] public void first_should_return_first_element() { // arrange var expected = new object(); IEnumerable sequence = new[] { expected, new object(), new object() }; // act var item = sequence.First(); // assert item.Should().Be( expected ); } [Fact] public void first_should_throw_exception_when_sequence_is_empty() { // arrange IEnumerable sequence = new object[0]; // act Action first = () => sequence.First(); // assert first.ShouldThrow<InvalidOperationException>().And.Message.Should().Be( "Sequence contains no elements." ); } [Theory] [InlineData( new Type[0], null )] [InlineData( new[] { typeof( object ), typeof( string ), typeof( int ) }, typeof( object ) )] public void first_or_default_should_return_expected_result( IEnumerable sequence, object expected ) { // arrange // act var item = sequence.FirstOrDefault(); // assert item.Should().Be( expected ); } [Fact] public void last_should_return_last_element() { // arrange var expected = new object(); IEnumerable sequence = new[] { new object(), new object(), expected }; // act var item = sequence.Last(); // assert item.Should().Be( expected ); } [Fact] public void last_should_throw_exception_when_sequence_is_empty() { // arrange IEnumerable sequence = new object[0]; // act Action last = () => sequence.Last(); // assert last.ShouldThrow<InvalidOperationException>().And.Message.Should().Be( "Sequence contains no elements." ); } [Theory] [InlineData( new Type[0], null )] [InlineData( new[] { typeof( string ), typeof( int ), typeof( object ) }, typeof( object ) )] public void last_or_default_should_return_expected_result( IEnumerable sequence, object expected ) { // arrange // act var item = sequence.LastOrDefault(); // assert item.Should().Be( expected ); } [Fact] public void single_should_return_exactly_one_element() { // arrange var expected = new object(); IEnumerable sequence = new[] { expected }; // act var item = sequence.Single(); // assert item.Should().Be( expected ); } [Theory] [InlineData( new object[0], "Sequence contains no elements." )] [InlineData( new[] { 1, 2, 3 }, "Sequence contains more than one matching element." )] public void single_should_throw_exception_when_sequence_is_not_exactly_one_element( IEnumerable sequence, string expected ) { // arrange // act Action single = () => sequence.Single(); // assert single.ShouldThrow<InvalidOperationException>().And.Message.Should().Be( expected ); } [Theory] [InlineData( new Type[0], null )] [InlineData( new[] { typeof( object ) }, typeof( object ) )] public void single_or_default_should_return_expected_result( IEnumerable sequence, object expected ) { // arrange // act var item = sequence.SingleOrDefault(); // assert item.Should().Be( expected ); } [Fact] public void single_or_default_should_throw_exception_when_sequence_is_more_than_one_element() { // arrange var sequence = new[] { 1, 2, 3 }; // act Action single = () => sequence.SingleOrDefault(); // assert single.ShouldThrow<InvalidOperationException>().And.Message.Should().Be( "Sequence contains more than one matching element." ); } [Fact] public void to_array_should_return_expected_result() { // arrange IEnumerable sequence = new[] { new object(), new object(), new object() }; // act IEnumerable array = sequence.ToArray(); // assert array.Should().Equal( sequence ).And.Should().NotBeSameAs( sequence ); } [Fact] public void to_list_should_return_expected_result() { // arrange IEnumerable sequence = new[] { new object(), new object(), new object() }; // act IEnumerable list = sequence.ToList(); // assert list.Should().Equal( sequence ).And.Should().NotBeSameAs( sequence ); } [Fact] public void reverse_should_return_expected_result() { // arrange var expected = new[] { new object(), new object(), new object() }; IEnumerable sequence = new[] { expected[2], expected[1], expected[0] }; // act var result = sequence.Reverse(); // assert result.Should().Equal( expected ).And.Should().NotBeSameAs( sequence ); } [Fact] public void skip_should_bypass_expected_elements() { // arrange var expected = new[] { new object(), new object() }; IEnumerable sequence = new[] { new object(), new object(), new object(), expected[0], expected[1] }; // act var result = sequence.Skip( 3 ); // assert result.Should().Equal( expected ); } [Fact] public void take_should_return_expected_elements() { // arrange var expected = new[] { new object(), new object() }; IEnumerable sequence = new[] { expected[0], expected[1], new object(), new object(), new object() }; // act var result = sequence.Take( 2 ); // assert result.Should().Equal( expected ); } [Theory] [InlineData( new object[0], new object[0], true )] [InlineData( new object[] { 1 }, new object[0], false )] [InlineData( new object[0], new object[] { 1 }, false )] [InlineData( new[] { 1, 2, 3 }, new[] { 1, 2, 3 }, true )] public void sequence_equal_should_return_expected_result( IEnumerable first, IEnumerable second, bool expected ) { // arrange // act var result = first.SequenceEqual( second ); // assert result.Should().Be( expected ); } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using SDKTemplate; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using System; using Windows.Devices.PointOfService; using System.Threading.Tasks; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace CashDrawerSample { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class Scenario3_MultipleDrawers : Page { // A pointer back to the main page. This is needed if you want to call methods in MainPage such // as NotifyUser() MainPage rootPage = MainPage.Current; CashDrawer cashDrawerInstance1 = null; CashDrawer cashDrawerInstance2 = null; ClaimedCashDrawer claimedCashDrawerInstance1 = null; ClaimedCashDrawer claimedCashDrawerInstance2 = null; public Scenario3_MultipleDrawers() { this.InitializeComponent(); } /// <summary> /// Enumerator for current active Instance. /// </summary> private enum CashDrawerInstance { Instance1, Instance2 } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { ResetScenarioState(); base.OnNavigatedTo(e); } /// <summary> /// Invoked before the page is unloaded and is no longer the current source of a Frame. /// </summary> /// <param name="e">Event data describing the navigation that was requested.</param> protected override void OnNavigatedFrom(NavigationEventArgs e) { ResetScenarioState(); base.OnNavigatedFrom(e); } /// <summary> /// Creates the default cash drawer. /// </summary> /// <param name="instance">Specifies the cash drawer instance that should be used.</param> /// <returns>True if the cash drawer was created, false otherwise.</returns> private async Task<bool> CreateDefaultCashDrawerObject(CashDrawerInstance instance) { rootPage.NotifyUser("Creating cash drawer object.", NotifyType.StatusMessage); CashDrawer tempDrawer = null; tempDrawer = await CashDrawer.GetDefaultAsync(); if (tempDrawer == null) { rootPage.NotifyUser("Cash drawer not found. Please connect a cash drawer.", NotifyType.ErrorMessage); return false; } switch (instance) { case CashDrawerInstance.Instance1: cashDrawerInstance1 = tempDrawer; break; case CashDrawerInstance.Instance2: cashDrawerInstance2 = tempDrawer; break; default: return false; } return true; } /// <summary> /// Attempt to claim the connected cash drawer. /// </summary> /// <param name="instance">Specifies the cash drawer instance that should be used.</param> /// <returns>True if the cash drawer was successfully claimed, false otherwise.</returns> private async Task<bool> ClaimCashDrawer(CashDrawerInstance instance) { bool claimAsyncStatus = false; switch (instance) { case CashDrawerInstance.Instance1: claimedCashDrawerInstance1 = await cashDrawerInstance1.ClaimDrawerAsync(); if (claimedCashDrawerInstance1 != null) { rootPage.NotifyUser("Successfully claimed instance 1.", NotifyType.StatusMessage); claimAsyncStatus = true; } else { rootPage.NotifyUser("Failed to claim instance 1.", NotifyType.ErrorMessage); } break; case CashDrawerInstance.Instance2: claimedCashDrawerInstance2 = await cashDrawerInstance2.ClaimDrawerAsync(); if (claimedCashDrawerInstance2 != null) { rootPage.NotifyUser("Successfully claimed instance 2.", NotifyType.StatusMessage); claimAsyncStatus = true; } else { rootPage.NotifyUser("Failed to claim instance 2.", NotifyType.ErrorMessage); } break; default: break; } return claimAsyncStatus; } /// <summary> /// Event callback for claim instance 1 button. /// </summary> /// <param name="sender">Button that was clicked.</param> /// <param name="e">Event data associated with click event.</param> private async void ClaimButton1_Click(object sender, RoutedEventArgs e) { if (await CreateDefaultCashDrawerObject(CashDrawerInstance.Instance1)) { if (await ClaimCashDrawer(CashDrawerInstance.Instance1)) { claimedCashDrawerInstance1.ReleaseDeviceRequested += claimedCashDrawerInstance1_ReleaseDeviceRequested; SetClaimedUI(CashDrawerInstance.Instance1); } else { cashDrawerInstance2 = null; } } } /// <summary> /// Event callback for claim instance 2 button. /// </summary> /// <param name="sender">Button that was clicked.</param> /// <param name="e">Event data associated with click event.</param> private async void ClaimButton2_Click(object sender, RoutedEventArgs e) { if (await CreateDefaultCashDrawerObject(CashDrawerInstance.Instance2)) { if (await ClaimCashDrawer(CashDrawerInstance.Instance2)) { claimedCashDrawerInstance2.ReleaseDeviceRequested += claimedCashDrawerInstance2_ReleaseDeviceRequested; SetClaimedUI(CashDrawerInstance.Instance2); } else { cashDrawerInstance2 = null; } } } /// <summary> /// Event callback for release instance 1 button. /// </summary> /// <param name="sender">Button that was clicked.</param> /// <param name="e">Event data associated with click event.</param> private void ReleaseButton1_Click(object sender, RoutedEventArgs e) { if (claimedCashDrawerInstance1 != null) { claimedCashDrawerInstance1.Dispose(); claimedCashDrawerInstance1 = null; SetReleasedUI(CashDrawerInstance.Instance1); rootPage.NotifyUser("Claimed instance 1 was released.", NotifyType.StatusMessage); } } /// <summary> /// Event callback for release instance 2 button. /// </summary> /// <param name="sender">Button that was clicked.</param> /// <param name="e">Event data associated with click event.</param> private void ReleaseButton2_Click(object sender, RoutedEventArgs e) { if (claimedCashDrawerInstance2 != null) { claimedCashDrawerInstance2.Dispose(); claimedCashDrawerInstance2 = null; SetReleasedUI(CashDrawerInstance.Instance2); rootPage.NotifyUser("Claimed instance 2 was released.", NotifyType.StatusMessage); } } /// <summary> /// Event callback for a release device request for instance 1. /// </summary> /// <param name="sender">The drawer receiving the release device request.</param> /// <param name="e">Unused for ReleaseDeviceRequested events.</param> private async void claimedCashDrawerInstance1_ReleaseDeviceRequested(ClaimedCashDrawer sender, object e) { await MainPage.Current.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => { rootPage.NotifyUser("Release instance 1 requested.", NotifyType.StatusMessage); if (RetainCheckBox1.IsChecked == true) { if (await claimedCashDrawerInstance1.RetainDeviceAsync() == false) rootPage.NotifyUser("Cash drawer instance 1 retain failed.", NotifyType.ErrorMessage); } else { claimedCashDrawerInstance1.Dispose(); claimedCashDrawerInstance1 = null; SetReleasedUI(CashDrawerInstance.Instance1); } }); } /// <summary> /// Event callback for a release device request for instance 2. /// </summary> /// <param name="sender">The drawer receiving the release device request.</param> /// <param name="e">Unused for ReleaseDeviceRequested events.</param> private async void claimedCashDrawerInstance2_ReleaseDeviceRequested(ClaimedCashDrawer drawer, object e) { await MainPage.Current.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => { rootPage.NotifyUser("Release instance 2 requested.", NotifyType.StatusMessage); if (RetainCheckBox2.IsChecked == true) { if (await claimedCashDrawerInstance2.RetainDeviceAsync() == false) rootPage.NotifyUser("Cash drawer instance 2 retain failed.", NotifyType.ErrorMessage); } else { claimedCashDrawerInstance2.Dispose(); claimedCashDrawerInstance2 = null; SetReleasedUI(CashDrawerInstance.Instance2); } }); } /// <summary> /// Resets the display elements to original state /// </summary> private void ResetScenarioState() { cashDrawerInstance1 = null; cashDrawerInstance2 = null; if (claimedCashDrawerInstance1 != null) { claimedCashDrawerInstance1.Dispose(); claimedCashDrawerInstance1 = null; } if (claimedCashDrawerInstance2 != null) { claimedCashDrawerInstance2.Dispose(); claimedCashDrawerInstance2 = null; } ClaimButton1.IsEnabled = true; ClaimButton2.IsEnabled = true; ReleaseButton1.IsEnabled = false; ReleaseButton2.IsEnabled = false; RetainCheckBox1.IsChecked = true; RetainCheckBox2.IsChecked = true; rootPage.NotifyUser("Click a claim button to begin.", NotifyType.StatusMessage); } /// <summary> /// Sets the UI elements to a state corresponding to the specified instace being claimed. /// </summary> /// <param name="instance">Corresponds to instance that has been claimed.</param> private void SetClaimedUI(CashDrawerInstance instance) { switch (instance) { case CashDrawerInstance.Instance1: ClaimButton1.IsEnabled = false; ClaimButton2.IsEnabled = true; ReleaseButton1.IsEnabled = true; ReleaseButton2.IsEnabled = false; break; case CashDrawerInstance.Instance2: ClaimButton1.IsEnabled = true; ClaimButton2.IsEnabled = false; ReleaseButton1.IsEnabled = false; ReleaseButton2.IsEnabled = true; break; default: break; } } /// <summary> /// Sets the UI elements to a state corresponding to the specified instace being released. /// </summary> /// <param name="instance">Corresponds to instance that has been released.</param> private void SetReleasedUI(CashDrawerInstance instance) { switch (instance) { case CashDrawerInstance.Instance1: ClaimButton1.IsEnabled = true; ReleaseButton1.IsEnabled = false; break; case CashDrawerInstance.Instance2: ClaimButton2.IsEnabled = true; ReleaseButton2.IsEnabled = false; break; default: break; } } } }
// // GameData.cs // // Copyright (c) 2016 Takashi OTSUKI // // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php // using AIWolf.Lib; using System.Collections.Generic; using System.Linq; namespace AIWolf.Server { public class GameData { int talkIdx = 0; int whisperIdx = 0; Agent attackedDead; Agent cursedFox; Agent executed; GameSetting gameSetting; /// <summary> /// The day. /// </summary> public int Day { get; private set; } /// <summary> /// The map between the agent and its status. /// </summary> public IDictionary<Agent, Status> StatusMap { get; private set; } = new Dictionary<Agent, Status>(); /// <summary> /// The map between the agent and its role. /// </summary> public IDictionary<Agent, Role> RoleMap { get; private set; } = new Dictionary<Agent, Role>(); /// <summary> /// The list of talks. /// </summary> public IList<Talk> TalkList { get; } = new List<Talk>(); /// <summary> /// The list of whispers. /// </summary> public IList<Whisper> WhisperList { get; } = new List<Whisper>(); /// <summary> /// The list of votes. /// </summary> public IList<Vote> VoteList { get; } = new List<Vote>(); /// <summary> /// The list of the latest votes. /// </summary> public IList<Vote> LatestVoteList { get; set; } = new List<Vote>(); /// <summary> /// The list of votes for attack. /// </summary> public IList<Vote> AttackVoteList { get; } = new List<Vote>(); /// <summary> /// The list of the latest votes for attack. /// </summary> public IList<Vote> LatestAttackVoteList { get; set; } = new List<Vote>(); /// <summary> /// The map between the agent and its chances of talk remaining. /// </summary> public IDictionary<Agent, int> RemainTalkMap { get; } = new Dictionary<Agent, int>(); /// <summary> /// Thae map between the agent and its chances of whispers remaining. /// </summary> public IDictionary<Agent, int> RemainWhisperMap { get; } = new Dictionary<Agent, int>(); /// <summary> /// The latest divination. /// </summary> public Judge Divine { get; set; } /// <summary> /// The latest guard. /// </summary> public Guard Guard { get; set; } /// <summary> /// The agent executed yesterday. /// </summary> public Agent Executed { get => executed; set => executed = SetDead(value); } /// <summary> /// The agent killed by the wolf yesterday. /// </summary> public Agent AttackedDead { get => attackedDead; set => attackedDead = SetDead(value); } /// <summary> /// The agent attacked by the wolf yesterday. (No matter whether or not the attack succeeded.) /// </summary> public Agent Attacked { get; set; } /// <summary> /// The fox killed by curse yesterday. /// </summary> public Agent CursedFox { get => cursedFox; set => cursedFox = SetDead(value); } /// <summary> /// The list of agents that died yesterday. /// </summary> IList<Agent> LastDeadAgentList { get; } = new List<Agent>(); /// <summary> /// The game data of yesterday. /// </summary> public GameData DayBefore { get; private set; } /// <summary> /// The list of agents. /// </summary> public IList<Agent> AgentList => new List<Agent>(RoleMap.Keys); /// <summary> /// GameData for tomorrow. /// </summary> public GameData NextDay { get { GameData gameData = new GameData(gameSetting) { Day = Day + 1, StatusMap = new Dictionary<Agent, Status>(StatusMap), RoleMap = new Dictionary<Agent, Role>(RoleMap), DayBefore = this }; foreach (Agent agent in gameData.AgentList.Where(a => StatusMap[a] == Status.ALIVE)) { gameData.RemainTalkMap[agent] = gameSetting.MaxTalk; if (RoleMap[agent] == Role.WEREWOLF) { gameData.RemainWhisperMap[agent] = gameSetting.MaxWhisper; } } return gameData; } } public int NextTalkIdx => talkIdx++; public int NextWhisperIdx => whisperIdx++; /// <summary> /// Initializes a new instance of this class. /// </summary> /// <param name="gameSetting">The setting of the game.</param> public GameData(GameSetting gameSetting) { this.gameSetting = gameSetting; } /// <summary> /// Generates a GameInfo. /// </summary> /// <param name="agent">The owner of the GameInfo.</param> /// <returns>The instance of GameInfo.</returns> /// <remarks>If agent is null, stuff the GameInfo with the all information available.</remarks> public GameInfo GetGameInfo(Agent agent) { Role role = agent != null ? RoleMap[agent] : Role.UNC; GameInfo gameInfo = new GameInfo() { Agent = agent, LatestVoteList = gameSetting.VoteVisible ? LatestVoteList : null, LatestExecutedAgent = Executed, LatestAttackVoteList = agent == null || role == Role.WEREWOLF ? LatestAttackVoteList : null, TalkList = TalkList, StatusMap = StatusMap, ExistingRoleList = RoleMap.Values.Distinct().ToList(), RemainTalkMap = RemainTalkMap, RemainWhisperMap = role == Role.WEREWOLF ? RemainWhisperMap : null, WhisperList = agent == null || role == Role.WEREWOLF ? WhisperList : null, Day = Day }; if (role == Role.WEREWOLF) { gameInfo.RoleMap = AgentList.Where(a => RoleMap[a] == Role.WEREWOLF).ToDictionary(a => a, a => Role.WEREWOLF); } else if (role == Role.FREEMASON) { gameInfo.RoleMap = AgentList.Where(a => RoleMap[a] == Role.FREEMASON).ToDictionary(a => a, a => Role.FREEMASON); } else { gameInfo.RoleMap = new Dictionary<Agent, Role>() { { agent, role } }; } if (DayBefore != null) { gameInfo.ExecutedAgent = DayBefore.Executed; gameInfo.LastDeadAgentList = DayBefore.LastDeadAgentList; gameInfo.VoteList = gameSetting.VoteVisible ? DayBefore.VoteList : null; gameInfo.MediumResult = role == Role.MEDIUM && DayBefore.Executed != null ? new Judge(Day, agent, DayBefore.Executed, DayBefore.RoleMap[DayBefore.Executed].GetSpecies()) : null; gameInfo.DivineResult = agent == null || role == Role.SEER ? DayBefore.Divine : null; if (agent == null || role == Role.WEREWOLF) { gameInfo.AttackedAgent = DayBefore.Attacked; gameInfo.AttackVoteList = DayBefore.AttackVoteList; } gameInfo.GuardedAgent = (agent == null || role == Role.BODYGUARD) && DayBefore.Guard != null ? DayBefore.Guard.Target : null; gameInfo.CursedFox = agent == null ? DayBefore.CursedFox : null; } return gameInfo; } /// <summary> /// Generates the GameInfo containing the complete agent-role mapping. /// </summary> /// <param name="agent">The owner of the GameInfo.</param> /// <returns>The instance of GameInfo.</returns> /// <remarks>If agent is null, stuff the GameInfo with the all information available.</remarks> public GameInfo GetFinalGameInfo(Agent agent) { GameInfo gameInfo = GetGameInfo(agent); gameInfo.RoleMap = RoleMap; return gameInfo; } /// <summary> /// Adds a new agent to the game. /// </summary> /// <param name="agent">The agent to be added.</param> /// <param name="status">The agent's status.</param> /// <param name="role">The agent's role.</param> public void AddAgent(Agent agent, Status status, Role role) { RoleMap[agent] = role; StatusMap[agent] = status; RemainTalkMap[agent] = gameSetting.MaxTalk; if (role == Role.WEREWOLF) { RemainWhisperMap[agent] = gameSetting.MaxWhisper; } } /// <summary> /// Adds a talk to TalkList. /// </summary> /// <param name="agent">The talker.</param> /// <param name="talk">The uttered talk.</param> public void AddTalk(Agent agent, Talk talk) { if (talk.Text != Talk.OVER && talk.Text != Talk.SKIP) { if (RemainTalkMap[agent] == 0) { throw new System.Exception(agent + " has no chance to talk remaining."); } RemainTalkMap[agent]--; } TalkList.Add(talk); } /// <summary> /// Adds a whisper to WhisperList. /// </summary> /// <param name="agent">The whisperer.</param> /// <param name="whisper">The uttered whisper.</param> public void AddWhisper(Agent agent, Whisper whisper) { if (whisper.Text != Talk.OVER && whisper.Text != Talk.SKIP) { if (RemainWhisperMap[agent] == 0) { throw new System.Exception(agent + " has no chance to whisper remaining."); } RemainWhisperMap[agent]--; } WhisperList.Add(whisper); } /// <summary> /// Adds a agent to LastDeadAgentList. /// </summary> /// <param name="agent">The agent to be added.</param> public void AddLastDeadAgent(Agent agent) { if (!LastDeadAgentList.Contains(agent)) { LastDeadAgentList.Add(SetDead(agent)); } } Agent SetDead(Agent agent) { if (agent != null) { StatusMap[agent] = Status.DEAD; } return agent; } } }
// // ModuleDefinition.cs // // Author: // Jb Evain ([email protected]) // // (C) 2005 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // namespace Mono.Cecil { using System; using SR = System.Reflection; using SS = System.Security; using SSP = System.Security.Permissions; using System.Text; using Mono.Cecil.Cil; using Mono.Cecil.Binary; using Mono.Cecil.Metadata; public sealed class ModuleDefinition : ModuleReference, ICustomAttributeProvider, IMetadataScope, IReflectionStructureVisitable, IReflectionVisitable { Guid m_mvid; bool m_main; bool m_manifestOnly; AssemblyNameReferenceCollection m_asmRefs; ModuleReferenceCollection m_modRefs; ResourceCollection m_res; TypeDefinitionCollection m_types; TypeReferenceCollection m_refs; ExternTypeCollection m_externs; MemberReferenceCollection m_members; CustomAttributeCollection m_customAttrs; AssemblyDefinition m_asm; Image m_image; ImageReader m_imgReader; ReflectionController m_controller; SecurityDeclarationReader m_secReader; public Guid Mvid { get { return m_mvid; } set { m_mvid = value; } } public bool Main { get { return m_main; } set { m_main = value; } } public AssemblyNameReferenceCollection AssemblyReferences { get { return m_asmRefs; } } public ModuleReferenceCollection ModuleReferences { get { return m_modRefs; } } public ResourceCollection Resources { get { return m_res; } } public TypeDefinitionCollection Types { get { return m_types; } } public TypeReferenceCollection TypeReferences { get { return m_refs; } } public MemberReferenceCollection MemberReferences { get { return m_members; } } public ExternTypeCollection ExternTypes { get { if (m_externs == null) m_externs = new ExternTypeCollection (this); return m_externs; } } public CustomAttributeCollection CustomAttributes { get { if (m_customAttrs == null) m_customAttrs = new CustomAttributeCollection (this); return m_customAttrs; } } public AssemblyDefinition Assembly { get { return m_asm; } } internal ReflectionController Controller { get { return m_controller; } } internal ImageReader ImageReader { get { return m_imgReader; } } public Image Image { get { return m_image; } set { m_image = value; m_secReader = null; } } public ModuleDefinition (string name, AssemblyDefinition asm) : this (name, asm, null, false) { } public ModuleDefinition (string name, AssemblyDefinition asm, bool main) : this (name, asm, null, main) { } internal ModuleDefinition (string name, AssemblyDefinition asm, StructureReader reader) : this (name, asm, reader, false) { } internal ModuleDefinition (string name, AssemblyDefinition asm, StructureReader reader, bool main) : base (name) { if (asm == null) throw new ArgumentNullException ("asm"); if (name == null || name.Length == 0) throw new ArgumentNullException ("name"); m_asm = asm; m_main = main; #if !CF_1_0 m_mvid = Guid.NewGuid (); #endif if (reader != null) { m_image = reader.Image; m_imgReader = reader.ImageReader; m_manifestOnly = reader.ManifestOnly; } else m_image = Image.CreateImage (); m_modRefs = new ModuleReferenceCollection (this); m_asmRefs = new AssemblyNameReferenceCollection (this); m_res = new ResourceCollection (this); m_types = new TypeDefinitionCollection (this); m_refs = new TypeReferenceCollection (this); m_members = new MemberReferenceCollection (this); m_controller = new ReflectionController (this); } public IMetadataTokenProvider LookupByToken (MetadataToken token) { return m_controller.Reader.LookupByToken (token); } public IMetadataTokenProvider LookupByToken (TokenType table, int rid) { return LookupByToken (new MetadataToken (table, (uint) rid)); } void CheckContext (TypeDefinition context) { if (context == null) throw new ArgumentNullException ("context"); if (context.Module != this) throw new ArgumentException ("The context parameter does not belongs to this module"); if (context.GenericParameters.Count == 0) throw new ArgumentException ("The context parameter is not a generic type"); } ImportContext GetContext () { return new ImportContext (m_controller.Importer); } static ImportContext GetContext (IImporter importer) { return new ImportContext (importer); } ImportContext GetContext (TypeDefinition context) { return new ImportContext (m_controller.Importer, context); } static ImportContext GetContext (IImporter importer, TypeDefinition context) { return new ImportContext (importer, context); } public TypeReference Import (Type type) { if (type == null) throw new ArgumentNullException ("type"); return m_controller.Helper.ImportSystemType (type, GetContext ()); } public TypeReference Import (Type type, TypeDefinition context) { if (type == null) throw new ArgumentNullException ("type"); CheckContext (context); return m_controller.Helper.ImportSystemType (type, GetContext (context)); } public MethodReference Import (SR.MethodBase meth) { if (meth == null) throw new ArgumentNullException ("meth"); if (meth is SR.ConstructorInfo) return m_controller.Helper.ImportConstructorInfo ( meth as SR.ConstructorInfo, GetContext ()); else return m_controller.Helper.ImportMethodInfo ( meth as SR.MethodInfo, GetContext ()); } public MethodReference Import (SR.MethodBase meth, TypeDefinition context) { if (meth == null) throw new ArgumentNullException ("meth"); CheckContext (context); if (meth is SR.ConstructorInfo) return m_controller.Helper.ImportConstructorInfo ( meth as SR.ConstructorInfo, GetContext (context)); else return m_controller.Helper.ImportMethodInfo ( meth as SR.MethodInfo, GetContext (context)); } public FieldReference Import (SR.FieldInfo field) { if (field == null) throw new ArgumentNullException ("field"); return m_controller.Helper.ImportFieldInfo (field, GetContext ()); } public FieldReference Import (SR.FieldInfo field, TypeDefinition context) { if (field == null) throw new ArgumentNullException ("field"); CheckContext (context); return m_controller.Helper.ImportFieldInfo (field, GetContext (context)); } public TypeReference Import (TypeReference type) { if (type == null) throw new ArgumentNullException ("type"); return m_controller.Importer.ImportTypeReference (type, GetContext ()); } public TypeReference Import (TypeReference type, TypeDefinition context) { if (type == null) throw new ArgumentNullException ("type"); CheckContext (context); return m_controller.Importer.ImportTypeReference (type, GetContext (context)); } public MethodReference Import (MethodReference meth) { if (meth == null) throw new ArgumentNullException ("meth"); return m_controller.Importer.ImportMethodReference (meth, GetContext ()); } public MethodReference Import (MethodReference meth, TypeDefinition context) { if (meth == null) throw new ArgumentNullException ("meth"); CheckContext (context); return m_controller.Importer.ImportMethodReference (meth, GetContext (context)); } public FieldReference Import (FieldReference field) { if (field == null) throw new ArgumentNullException ("field"); return m_controller.Importer.ImportFieldReference (field, GetContext ()); } public FieldReference Import (FieldReference field, TypeDefinition context) { if (field == null) throw new ArgumentNullException ("field"); CheckContext (context); return m_controller.Importer.ImportFieldReference (field, GetContext (context)); } static FieldDefinition ImportFieldDefinition (FieldDefinition field, ImportContext context) { return FieldDefinition.Clone (field, context); } static MethodDefinition ImportMethodDefinition (MethodDefinition meth, ImportContext context) { return MethodDefinition.Clone (meth, context); } static TypeDefinition ImportTypeDefinition (TypeDefinition type, ImportContext context) { return TypeDefinition.Clone (type, context); } public TypeDefinition Inject (TypeDefinition type) { return Inject (type, m_controller.Importer); } public TypeDefinition Inject (TypeDefinition type, IImporter importer) { if (type == null) throw new ArgumentNullException ("type"); if (importer == null) throw new ArgumentNullException ("importer"); TypeDefinition definition = ImportTypeDefinition (type, GetContext (importer)); this.Types.Add (definition); return definition; } public TypeDefinition Inject (TypeDefinition type, TypeDefinition context) { return Inject (type, context, m_controller.Importer); } public TypeDefinition Inject (TypeDefinition type, TypeDefinition context, IImporter importer) { Check (type, context, importer); TypeDefinition definition = ImportTypeDefinition (type, GetContext (importer, context)); context.NestedTypes.Add (definition); return definition; } public MethodDefinition Inject (MethodDefinition meth, TypeDefinition context) { return Inject (meth, context, m_controller.Importer); } void Check (IMemberDefinition definition, TypeDefinition context, IImporter importer) { if (definition == null) throw new ArgumentNullException ("definition"); if (context == null) throw new ArgumentNullException ("context"); if (importer == null) throw new ArgumentNullException ("importer"); if (context.Module != this) throw new ArgumentException ("The context parameter does not belongs to this module"); } public MethodDefinition Inject (MethodDefinition meth, TypeDefinition context, IImporter importer) { Check (meth, context, importer); MethodDefinition definition = ImportMethodDefinition (meth, GetContext (importer, context)); context.Methods.Add (definition); return definition; } public FieldDefinition Inject (FieldDefinition field, TypeDefinition context, IImporter importer) { Check (field, context, importer); FieldDefinition definition = ImportFieldDefinition (field, GetContext (importer, context)); context.Fields.Add (definition); return definition; } public void FullLoad () { if (m_manifestOnly) m_controller.Reader.VisitModuleDefinition (this); foreach (TypeDefinition type in this.Types) { foreach (MethodDefinition meth in type.Methods) meth.LoadBody (); foreach (MethodDefinition ctor in type.Constructors) ctor.LoadBody (); } if (m_controller.Reader.SymbolReader == null) return; m_controller.Reader.SymbolReader.Dispose (); m_controller.Reader.SymbolReader = null; } public void LoadSymbols () { m_controller.Reader.SymbolReader = SymbolStoreHelper.GetReader (this); } public void LoadSymbols (ISymbolReader reader) { m_controller.Reader.SymbolReader = reader; } public void SaveSymbols () { m_controller.Writer.SaveSymbols = true; } public void SaveSymbols (ISymbolWriter writer) { SaveSymbols (); m_controller.Writer.SymbolWriter = writer; } public void SaveSymbols (string outputDirectory) { SaveSymbols (); m_controller.Writer.OutputFile = outputDirectory; } public void SaveSymbols (string outputDirectory, ISymbolWriter writer) { SaveSymbols (outputDirectory); m_controller.Writer.SymbolWriter = writer; } public byte [] GetAsByteArray (CustomAttribute ca) { CustomAttribute customAttr = ca; if (!ca.Resolved) if (customAttr.Blob != null) return customAttr.Blob; else return new byte [0]; return m_controller.Writer.SignatureWriter.CompressCustomAttribute ( ReflectionWriter.GetCustomAttributeSig (ca), ca.Constructor); } public byte [] GetAsByteArray (SecurityDeclaration dec) { // TODO - add support for 2.0 format // note: the 1.x format is still supported in 2.0 so this isn't an immediate problem if (!dec.Resolved) return dec.Blob; #if !CF_1_0 && !CF_2_0 if (dec.PermissionSet != null) return Encoding.Unicode.GetBytes (dec.PermissionSet.ToXml ().ToString ()); #endif return new byte [0]; } public CustomAttribute FromByteArray (MethodReference ctor, byte [] data) { return m_controller.Reader.GetCustomAttribute (ctor, data); } public SecurityDeclaration FromByteArray (SecurityAction action, byte [] declaration) { if (m_secReader == null) m_secReader = new SecurityDeclarationReader (Image.MetadataRoot, m_controller.Reader); return m_secReader.FromByteArray (action, declaration); } public override void Accept (IReflectionStructureVisitor visitor) { visitor.VisitModuleDefinition (this); this.AssemblyReferences.Accept (visitor); this.ModuleReferences.Accept (visitor); this.Resources.Accept (visitor); } public void Accept (IReflectionVisitor visitor) { visitor.VisitModuleDefinition (this); this.Types.Accept (visitor); this.TypeReferences.Accept (visitor); } public override string ToString () { string s = (m_main ? "(main), Mvid=" : "Mvid="); return s + m_mvid; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Globalization; using System.Threading; namespace System.Globalization { // This calendar recognizes two era values: // 0 CurrentEra (AD) // 1 BeforeCurrentEra (BC) public class GregorianCalendar : Calendar { /* A.D. = anno Domini */ public const int ADEra = 1; // // This is the max Gregorian year can be represented by DateTime class. The limitation // is derived from DateTime class. // internal const int MaxYear = 9999; internal GregorianCalendarTypes m_type; internal static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; internal static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; private static volatile Calendar s_defaultInstance; public override DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of GregorianCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ internal static Calendar GetDefaultInstance() { if (s_defaultInstance == null) { s_defaultInstance = new GregorianCalendar(); } return (s_defaultInstance); } // Construct an instance of gregorian calendar. public GregorianCalendar() : this(GregorianCalendarTypes.Localized) { } public GregorianCalendar(GregorianCalendarTypes type) { if ((int)type < (int)GregorianCalendarTypes.Localized || (int)type > (int)GregorianCalendarTypes.TransliteratedFrench) { throw new ArgumentOutOfRangeException( nameof(type), SR.Format(SR.ArgumentOutOfRange_Range, GregorianCalendarTypes.Localized, GregorianCalendarTypes.TransliteratedFrench)); } this.m_type = type; } public virtual GregorianCalendarTypes CalendarType { get { return (m_type); } set { VerifyWritable(); switch (value) { case GregorianCalendarTypes.Localized: case GregorianCalendarTypes.USEnglish: case GregorianCalendarTypes.MiddleEastFrench: case GregorianCalendarTypes.Arabic: case GregorianCalendarTypes.TransliteratedEnglish: case GregorianCalendarTypes.TransliteratedFrench: m_type = value; break; default: throw new ArgumentOutOfRangeException("m_type", SR.ArgumentOutOfRange_Enum); } } } internal override CalendarId ID { get { // By returning different ID for different variations of GregorianCalendar, // we can support the Transliterated Gregorian calendar. // DateTimeFormatInfo will use this ID to get formatting information about // the calendar. return ((CalendarId)m_type); } } /*=================================GetAbsoluteDate========================== **Action: Gets the absolute date for the given Gregorian date. The absolute date means ** the number of days from January 1st, 1 A.D. **Returns: the absolute date **Arguments: ** year the Gregorian year ** month the Gregorian month ** day the day **Exceptions: ** ArgumentOutOfRangException if year, month, day value is valid. **Note: ** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars. ** Number of Days in Prior Years (both common and leap years) + ** Number of Days in Prior Months of Current Year + ** Number of Days in Current Month ** ============================================================================*/ internal static long GetAbsoluteDate(int year, int month, int day) { if (year >= 1 && year <= MaxYear && month >= 1 && month <= 12) { int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366 : DaysToMonth365; if (day >= 1 && (day <= days[month] - days[month - 1])) { int y = year - 1; int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1; return (absoluteDate); } } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } // Returns the tick count corresponding to the given year, month, and day. // Will check the if the parameters are valid. internal virtual long DateToTicks(int year, int month, int day) { return (GetAbsoluteDate(year, month, day) * TicksPerDay); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( nameof(months), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, -120000, 120000)); } time.GetDatePart(out int y, out int m, out int d); 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)) ? DaysToMonth366 : 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)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public override DateTime AddYears(DateTime time, int years) { return (AddMonths(time, years * 12)); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public override int GetDayOfMonth(DateTime time) { return time.Day; } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public override DayOfWeek GetDayOfWeek(DateTime time) { return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7)); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public override int GetDayOfYear(DateTime time) { return time.DayOfYear; } // Returns the number of days in the month given by the year and // month arguments. // public override int GetDaysInMonth(int year, int month, int era) { if (era == CurrentEra || era == ADEra) { if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException(nameof(year), SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxYear)); } if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month); } int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365); return (days[month] - days[month - 1]); } throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } // Returns the number of days in the year given by the year argument for the current era. // public override int GetDaysInYear(int year, int era) { if (era == CurrentEra || era == ADEra) { if (year >= 1 && year <= MaxYear) { return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366 : 365); } throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } // Returns the era for the specified DateTime value. public override int GetEra(DateTime time) { return (ADEra); } public override int[] Eras { get { return (new int[] { ADEra }); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public override int GetMonth(DateTime time) { return time.Month; } // Returns the number of months in the specified year and era. public override int GetMonthsInYear(int year, int era) { if (era == CurrentEra || era == ADEra) { if (year >= 1 && year <= MaxYear) { return (12); } throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public override int GetYear(DateTime time) { return time.Year; } internal override bool IsValidYear(int year, int era) => year >= 1 && year <= MaxYear; internal override bool IsValidDay(int year, int month, int day, int era) { if ((era != CurrentEra && era != ADEra) || year < 1 || year > MaxYear || month < 1 || month > 12 || day < 1) { return false; } int[] days = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365; return day <= (days[month] - days[month - 1]); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public override bool IsLeapDay(int year, int month, int day, int era) { if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), SR.Format(SR.ArgumentOutOfRange_Range, 1, 12)); } if (era != CurrentEra && era != ADEra) { throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxYear)); } if (day < 1 || day > GetDaysInMonth(year, month)) { throw new ArgumentOutOfRangeException(nameof(day), SR.Format(SR.ArgumentOutOfRange_Range, 1, GetDaysInMonth(year, month))); } if (!IsLeapYear(year)) { return (false); } if (month == 2 && day == 29) { return (true); } 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. // public override int GetLeapMonth(int year, int era) { if (era != CurrentEra && era != ADEra) { throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } return (0); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public override bool IsLeapMonth(int year, int month, int era) { if (era != CurrentEra && era != ADEra) { throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), SR.Format(SR.ArgumentOutOfRange_Range, 1, 12)); } 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) { if (era == CurrentEra || era == ADEra) { if (year >= 1 && year <= MaxYear) { return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); } throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { if (era == CurrentEra || era == ADEra) { return new DateTime(year, month, day, hour, minute, second, millisecond); } throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } internal override Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) { if (era == CurrentEra || era == ADEra) { try { result = new DateTime(year, month, day, hour, minute, second, millisecond); return true; } catch (ArgumentOutOfRangeException) { result = DateTime.Now; return false; } catch (ArgumentException) { result = DateTime.Now; return false; } } result = DateTime.MinValue; return false; } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 2029; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } 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(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } if (year > MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } return (base.ToFourDigitYear(year)); } } }
using System; namespace DjvuNet.Graphics { /// <summary> /// A general class for rectange shapes. /// </summary> public class Rectangle { #region Public Properties #region Left private int _left; /// <summary> /// Gets or sets the left edge of the rectangle - xmax /// </summary> public int Left { get { return _left; } set { if (Left != value) { _left = value; } } } #endregion Left #region XMax /// <summary> /// Gets or sets the XMax value /// </summary> public int XMax { get { return Left; } set { if (XMax != value) { Left = value; //if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("XMax")); } } } #endregion XMax #region Right private int _right; /// <summary> /// Gets or sets the right edge of the rectangle - xmin /// </summary> public int Right { get { return _right; } set { if (Right != value) { _right = value; } } } #endregion Right #region XMin /// <summary> /// Gets or sets the x min value /// </summary> public int XMin { get { return Right; } set { if (XMin != value) { Right = value; //if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("XMin")); } } } #endregion XMin #region Top private int _top; /// <summary> /// Gets or sets the top edge of the rectangle - ymax /// </summary> public int Top { get { return _top; } set { if (Top != value) { _top = value; } } } #endregion Top #region YMax /// <summary> /// Gets or sets the y max value /// </summary> public int YMax { get { return Top; } set { if (YMax != value) { Top = value; //if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("YMax")); } } } #endregion YMax #region Bottom private int _bottom; /// <summary> /// Gets or sets the bottom of the rectangle - ymin /// </summary> public int Bottom { get { return _bottom; } set { if (Bottom != value) { _bottom = value; } } } #endregion Bottom #region YMin /// <summary> /// Gets or sets the y min value /// </summary> public int YMin { get { return Bottom; } set { if (YMin != value) { Bottom = value; //if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("YMin")); } } } #endregion YMin #region Empty /// <summary> /// True if the rectangle is empty, false otherwise /// </summary> public bool Empty { get { return (Right >= Left) || (Bottom >= Top); } } #endregion Empty #region Area /// <summary> /// Gets the area of the rectangle /// </summary> public long Area { get { return (Left - Right) * (long)(Top - Bottom); } } #endregion Area #region Height /// <summary> /// Gets the height of the rectangle /// </summary> public int Height { get { return Top - Bottom; } } #endregion Height #region Width /// <summary> /// Gets the width of the rectangle /// </summary> public int Width { get { return Left - Right; } } #endregion Width #endregion Public Properties #region Constructors /// <summary> Creates a new Rectangle object.</summary> public Rectangle() { Right = Left = Bottom = Top = 0; } /// <summary> Creates a new Rectangle object. /// /// </summary> /// <param name="right">left edge /// </param> /// <param name="bottom">bottom edge /// </param> /// <param name="width">horizontal length /// </param> /// <param name="height">vertical length /// </param> public Rectangle(int right, int bottom, int width, int height) { Right = right; Bottom = bottom; Left = right + width; Top = bottom + height; } #endregion Constructors #region Public Methods /// <summary> Create a clone of this rectangle. /// /// </summary> /// <returns> the newly created copy /// </returns> public Rectangle Duplicate() { return new Rectangle { Left = Left, Right = Right, Top = Top, Bottom = Bottom }; } /// <summary> Reset this rectange with all edges at the origin.</summary> public virtual void Clear() { Right = Left = Bottom = Top = 0; } /// <summary> Test if a point is contained in this rectangle. /// /// </summary> /// <param name="x">horizontal coordinate /// </param> /// <param name="y">vertical coordinate /// /// </param> /// <returns> true if the point is within this rectangle /// </returns> public virtual bool Contains(int x, int y) { return (x >= Right) && (x < Left) && (y >= Bottom) && (y < Top); } /// <summary> Test if a rectangle is contained within this rectangle. /// /// </summary> /// <param name="rect">rectangle to test /// /// </param> /// <returns> true if the rectangle is contained /// </returns> public virtual bool Contains(Rectangle rect) { return rect.Empty || (Contains(rect.Right, rect.Bottom) && Contains(rect.Left - 1, rect.Top - 1)); } /// <summary> Test if two rectangles are equal. /// /// </summary> /// <param name="ref">reference rectangle to compare with /// /// </param> /// <returns> true if all the edges are equal /// </returns> public override bool Equals(Object ref_Renamed) { if (ref_Renamed is Rectangle) { Rectangle r = (Rectangle)ref_Renamed; bool isempty1 = Empty; bool isempty2 = r.Empty; return ((isempty1 || isempty2) && isempty1 && isempty2) || ((Right == r.Right) && (Left == r.Left) && (Bottom == r.Bottom) && (Top == r.Top)); } return false; } /// <summary> Grow the size of this rectangle by moving all the edges outwards. /// /// </summary> /// <param name="dx">Amount to grow the horizontal edges /// </param> /// <param name="dy">Amount to grow the vertical edges /// /// </param> /// <returns> true if not empty. /// </returns> public virtual bool Inflate(int dx, int dy) { Right -= dx; Left += dx; Bottom -= dy; Top += dy; if (!Empty) { return true; } else { Right = Bottom = Left = Top = 0; return false; } } /// <summary> Set this rectangle as the intersection of two rectangles. /// /// </summary> /// <param name="rect1">rectangle to intersect /// </param> /// <param name="rect2">rectangle to intersect /// /// </param> /// <returns> true if the intersection is not empty /// </returns> public virtual bool Intersect(Rectangle rect1, Rectangle rect2) { Right = Math.Max(rect1.Right, rect2.Right); Left = Math.Min(rect1.Left, rect2.Left); Bottom = Math.Max(rect1.Bottom, rect2.Bottom); Top = Math.Min(rect1.Top, rect2.Top); if (Empty) { Right = Bottom = Left = Top = 0; return false; } return true; } /// <summary> /// Set this rectangle as the union of two rectangles. /// </summary> /// <param name="rect1">rectangle to union /// </param> /// <param name="rect2">rectangle to union /// /// </param> /// <returns> true if the results are non-empty /// </returns> public virtual bool Recthull(Rectangle rect1, Rectangle rect2) { if (rect1.Empty) { Right = rect2.Right; Left = rect2.Left; Bottom = rect2.Bottom; Top = rect2.Top; return !Empty; } if (rect2.Empty) { Right = rect1.Right; Left = rect1.Left; Bottom = rect1.Bottom; Top = rect1.Top; return !Empty; } Right = Math.Min(rect1.Right, rect2.Right); Left = Math.Max(rect1.Left, rect2.Left); Bottom = Math.Min(rect1.Bottom, rect2.Bottom); Top = Math.Max(rect1.Top, rect2.Top); return true; } /// <summary> Shift this rectangle /// /// </summary> /// <param name="dx">horizontal distance to shift /// </param> /// <param name="dy">vertical distance to shift /// /// </param> /// <returns> true if not empty /// </returns> public virtual bool Translate(int dx, int dy) { if (!Empty) { Right += dx; Left += dx; Bottom += dy; Top += dy; return true; } Right = Bottom = Left = Top = 0; return false; } /// <summary> /// Implicit conversion to drawing rectangle /// </summary> /// <param name="rect"></param> /// <returns></returns> public static implicit operator System.Drawing.Rectangle(Rectangle rect) { return new System.Drawing.Rectangle(rect.Left, rect.Top, rect.Width, rect.Height); } #endregion Public Methods } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Gateway.Tests.Load { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using DotNetty.Buffers; using DotNetty.Codecs.Mqtt; using DotNetty.Codecs.Mqtt.Packets; using DotNetty.Common.Concurrency; using DotNetty.Handlers.Tls; using DotNetty.Transport.Bootstrapping; using DotNetty.Transport.Channels; using DotNetty.Transport.Channels.Sockets; using Microsoft.Azure.Devices; using Microsoft.Azure.Devices.Common.Security; using Microsoft.Azure.Devices.Gateway.Tests; abstract class DeviceRunner { const int MaxPayloadSize = 16 * 1024; static readonly ThreadLocal<Random> ThreadLocalRandom = new ThreadLocal<Random>(() => new Random((int)DateTime.UtcNow.ToFileTimeUtc())); static readonly byte[][] Payloads = GeneratePayloads(MaxPayloadSize); static readonly TimeSpan CommunicationTimeout = TimeSpan.FromSeconds(60); readonly IotHubConnectionStringBuilder connectionStringBuilder; readonly string deviceKey; readonly IPEndPoint endpoint; readonly string tlsHostName; readonly Bootstrap bootstrap; protected DeviceRunner(IEventLoopGroup eventLoopGroup, string deviceKey, string iotHubConnectionString, IPEndPoint endpoint, string tlsHostName) { this.deviceKey = deviceKey; this.endpoint = endpoint; this.tlsHostName = tlsHostName; this.connectionStringBuilder = IotHubConnectionStringBuilder.Create(iotHubConnectionString.Contains("DeviceId=") ? iotHubConnectionString : iotHubConnectionString + ";DeviceId=abc"); this.bootstrap = new Bootstrap() .Group(eventLoopGroup) .Channel<TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, false); } public async Task<Task> StartAsync(string deviceId, CancellationToken cancellationToken) { string deviceSas = new SharedAccessSignatureBuilder { Key = this.deviceKey, Target = string.Format("{0}/devices/{1}", this.connectionStringBuilder.HostName, deviceId), TimeToLive = TimeSpan.FromDays(3) } .ToSignature(); var taskCompletionSource = new TaskCompletionSource(); var b = (Bootstrap)this.bootstrap.Clone(); b.Handler(new ActionChannelInitializer<ISocketChannel>( ch => { ch.Pipeline.AddLast( TlsHandler.Client(this.tlsHostName, null, (sender, certificate, chain, errors) => true), MqttEncoder.Instance, new MqttDecoder(false, 256 * 1024), new TestScenarioRunner( cmf => this.GetCompleteScenario(cmf, deviceId, deviceSas, cancellationToken), taskCompletionSource, CommunicationTimeout, CommunicationTimeout), ConsoleLoggingHandler.Instance); })); await b.ConnectAsync(this.endpoint); return taskCompletionSource.Task; } public async virtual Task<bool> OnClosedAsync(string deviceId, Exception exception, bool onStart) { Console.WriteLine("Error running client: id: {0}, onStart: {1}, exception({2}): {3}", deviceId, onStart, exception.GetType().Name, exception.Message); await Task.Delay(TimeSpan.FromSeconds(60)); return true; } IEnumerable<TestScenarioStep> GetCompleteScenario(Func<object> currentMessageFunc, string clientId, string password, CancellationToken cancellationToken) { yield return TestScenarioStep.Write(new ConnectPacket { ClientId = clientId, CleanSession = false, HasUsername = true, Username = clientId, HasPassword = true, Password = password, KeepAliveInSeconds = 120 }); object message = currentMessageFunc(); var connackPacket = message as ConnAckPacket; if (connackPacket == null) { throw new InvalidOperationException(string.Format("{1}: Expected CONNACK, received {0}", message, clientId)); } else if (connackPacket.ReturnCode != ConnectReturnCode.Accepted) { throw new InvalidOperationException(string.Format("{1}: Expected successful CONNACK, received CONNACK with return code of {0}", connackPacket.ReturnCode, clientId)); } foreach (TestScenarioStep step in this.GetScenario(currentMessageFunc, clientId, cancellationToken)) { yield return step; } } protected virtual IEnumerable<TestScenarioStep> GetScenario(Func<object> currentMessageFunc, string clientId, CancellationToken cancellationToken) { return this.GetScenarioNested(currentMessageFunc, clientId, cancellationToken).SelectMany(_ => _); } protected virtual IEnumerable<IEnumerable<TestScenarioStep>> GetScenarioNested(Func<object> currentMessageFunc, string clientId, CancellationToken cancellationToken) { yield break; } protected abstract string Name { get; } public RunnerConfiguration CreateConfiguration(int count, TimeSpan rampUpPeriod) { return new RunnerConfiguration(this.Name, this.StartAsync, this.OnClosedAsync, count, rampUpPeriod); } #region scenario composition utils /// <summary> /// Thread local Random object. /// </summary> protected static Random Random { get { return ThreadLocalRandom.Value; } } static byte[][] GeneratePayloads(int maxSize) { var result = new byte[maxSize + 1][]; for (int i = 0; i <= maxSize; i++) { var item = new byte[i]; Random.NextBytes(item); result[i] = item; } return result; } protected static IByteBuffer GetPayloadBuffer(int size) { Contract.Requires(size < MaxPayloadSize); return Unpooled.WrappedBuffer(Payloads[size]); } protected static IEnumerable<TestScenarioStep> GetSubscribeSteps(Func<object> currentMessageFunc, string clientId) { return GetSubscribeSteps(currentMessageFunc, clientId, "devices/{0}/messages/devicebound"); } protected static IEnumerable<TestScenarioStep> GetSubscribeSteps(Func<object> currentMessageFunc, string clientId, string topicNamePattern) { int subscribePacketId = Random.Next(1, ushort.MaxValue); yield return TestScenarioStep.Write( new SubscribePacket( subscribePacketId, new SubscriptionRequest(string.Format(topicNamePattern, clientId), QualityOfService.ExactlyOnce))); object message = currentMessageFunc(); var subackPacket = message as SubAckPacket; if (subackPacket == null) { throw new InvalidOperationException(string.Format("{1}: Expected SUBACK, received {0}", message, clientId)); } else if (subackPacket.PacketId == subscribePacketId && subackPacket.ReturnCodes[0] > QualityOfService.ExactlyOnce) { throw new InvalidOperationException(string.Format("{3}: Expected successful SUBACK({0}), received SUBACK({1}) with QoS={2}", subscribePacketId, subackPacket.PacketId, subackPacket.ReturnCodes[0], clientId)); } } protected static IEnumerable<TestScenarioStep> GetPublishSteps(Func<object> currentMessageFunc, string clientId, QualityOfService qos, string topicNamePattern, int count, int minPayloadSize, int maxPayloadSize) { Contract.Requires(count > 0); Contract.Requires(qos < QualityOfService.ExactlyOnce); PublishPacket[] publishPackets = Enumerable.Repeat(0, count) .Select(_ => new PublishPacket(qos, false, false) { TopicName = string.Format(topicNamePattern, clientId), PacketId = Random.Next(1, ushort.MaxValue), Payload = GetPayloadBuffer(Random.Next(minPayloadSize, maxPayloadSize)) }) .ToArray(); yield return TestScenarioStep.Write(qos > QualityOfService.AtMostOnce, publishPackets); if (qos == QualityOfService.AtMostOnce) { yield break; } int acked = 0; do { object receivedMessage = currentMessageFunc(); var pubackPacket = receivedMessage as PubAckPacket; if (pubackPacket == null || pubackPacket.PacketId != publishPackets[acked].PacketId) { throw new InvalidOperationException(string.Format("{0}: Expected PUBACK({1}), received {2}", clientId, publishPackets[acked].PacketId, receivedMessage)); } if (acked < count - 1) { yield return TestScenarioStep.ReadMore(); } acked++; } while (acked < count); } #endregion } }
using EIDSS.Reports.Parameterized.Human.DToChangedD; using EIDSS.Reports.Parameterized.Human.DToChangedD.DToChangedDDataSetTableAdapters; namespace EIDSS.Reports.Parameterized.Human.ARM.Report { partial class FormN85MonthlyReport { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormN85MonthlyReport)); DevExpress.XtraReports.UI.XRSummary xrSummary1 = new DevExpress.XtraReports.UI.XRSummary(); this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand(); this.CustomDetail = new DevExpress.XtraReports.UI.DetailBand(); this.TableDetail = new DevExpress.XtraReports.UI.XRTable(); this.TableRowDetail = new DevExpress.XtraReports.UI.XRTableRow(); this.CellDisease = new DevExpress.XtraReports.UI.XRTableCell(); this.CellNo = new DevExpress.XtraReports.UI.XRTableCell(); this.CellICD = new DevExpress.XtraReports.UI.XRTableCell(); this.CellTotal = new DevExpress.XtraReports.UI.XRTableCell(); this.CellChildren = new DevExpress.XtraReports.UI.XRTableCell(); this.CustomReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.TableHeader = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell(); this.lblYearMonth = new DevExpress.XtraReports.UI.XRLabel(); this.lblReportPeriod = new DevExpress.XtraReports.UI.XRLabel(); this.lblCustomReportName = new DevExpress.XtraReports.UI.XRLabel(); this.CustomReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand(); this.TableFooter = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell(); this.spRepHumFormN85MonthlyTableAdapter = new EIDSS.Reports.Parameterized.Human.ARM.DataSet.FormN85MontlyDataSetTableAdapters.spRepHumFormN85MonthlyTableAdapter(); this.formN85MontlyDataSet = new EIDSS.Reports.Parameterized.Human.ARM.DataSet.FormN85MontlyDataSet(); ((System.ComponentModel.ISupportInitialize)(this.xrTable4)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.TableDetail)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.TableHeader)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.TableFooter)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.formN85MontlyDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // xrTable4 // resources.ApplyResources(this.xrTable4, "xrTable4"); this.xrTable4.StylePriority.UseBorders = false; this.xrTable4.StylePriority.UseFont = false; this.xrTable4.StylePriority.UsePadding = false; // // cellLanguage // this.cellLanguage.StylePriority.UseTextAlignment = false; // // lblReportName // resources.ApplyResources(this.lblReportName, "lblReportName"); this.lblReportName.StylePriority.UseBorders = false; this.lblReportName.StylePriority.UseBorderWidth = false; this.lblReportName.StylePriority.UseFont = false; this.lblReportName.StylePriority.UsePadding = false; this.lblReportName.StylePriority.UseTextAlignment = false; // // Detail // this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UsePadding = false; // // PageHeader // resources.ApplyResources(this.PageHeader, "PageHeader"); this.PageHeader.StylePriority.UseFont = false; this.PageHeader.StylePriority.UsePadding = false; // // PageFooter // resources.ApplyResources(this.PageFooter, "PageFooter"); this.PageFooter.StylePriority.UseBorders = false; // // ReportHeader // resources.ApplyResources(this.ReportHeader, "ReportHeader"); // // xrPageInfo1 // resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1"); this.xrPageInfo1.StylePriority.UseBorders = false; // // cellReportHeader // this.cellReportHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.cellReportHeader.StylePriority.UseBorders = false; this.cellReportHeader.StylePriority.UseFont = false; this.cellReportHeader.StylePriority.UsePadding = false; this.cellReportHeader.StylePriority.UseTextAlignment = false; this.cellReportHeader.Weight = 2.2994485515985108D; // // cellBaseSite // this.cellBaseSite.StylePriority.UseBorders = false; this.cellBaseSite.StylePriority.UseFont = false; this.cellBaseSite.StylePriority.UseTextAlignment = false; this.cellBaseSite.Weight = 2.2994485515985104D; // // cellBaseCountry // this.cellBaseCountry.StylePriority.UseFont = false; this.cellBaseCountry.Weight = 1.6891816919536407D; // // cellBaseLeftHeader // this.cellBaseLeftHeader.Weight = 1.6891816919536407D; // // tableBaseHeader // resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader"); this.tableBaseHeader.StylePriority.UseBorders = false; this.tableBaseHeader.StylePriority.UseBorderWidth = false; this.tableBaseHeader.StylePriority.UseFont = false; this.tableBaseHeader.StylePriority.UsePadding = false; this.tableBaseHeader.StylePriority.UseTextAlignment = false; // // DetailReport // this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.CustomDetail, this.CustomReportHeader, this.CustomReportFooter}); this.DetailReport.DataAdapter = this.spRepHumFormN85MonthlyTableAdapter; this.DetailReport.DataMember = "spRepHumFormN85Monthly"; this.DetailReport.DataSource = this.formN85MontlyDataSet; this.DetailReport.Level = 0; this.DetailReport.Name = "DetailReport"; // // CustomDetail // this.CustomDetail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.TableDetail}); resources.ApplyResources(this.CustomDetail, "CustomDetail"); this.CustomDetail.KeepTogether = true; this.CustomDetail.Name = "CustomDetail"; // // TableDetail // this.TableDetail.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.TableDetail, "TableDetail"); this.TableDetail.Name = "TableDetail"; this.TableDetail.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.TableDetail.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.TableRowDetail}); this.TableDetail.StylePriority.UseBorders = false; this.TableDetail.StylePriority.UsePadding = false; this.TableDetail.StylePriority.UseTextAlignment = false; // // TableRowDetail // this.TableRowDetail.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.CellDisease, this.CellNo, this.CellICD, this.CellTotal, this.CellChildren}); this.TableRowDetail.Name = "TableRowDetail"; this.TableRowDetail.StylePriority.UseBorders = false; this.TableRowDetail.StylePriority.UseTextAlignment = false; this.TableRowDetail.Weight = 1D; // // CellDisease // this.CellDisease.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN85Monthly.strDisease")}); this.CellDisease.Name = "CellDisease"; resources.ApplyResources(this.CellDisease, "CellDisease"); this.CellDisease.Weight = 1.0578280177217185D; // // CellNo // this.CellNo.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN85Monthly.strDisease")}); this.CellNo.Name = "CellNo"; xrSummary1.Func = DevExpress.XtraReports.UI.SummaryFunc.RecordNumber; xrSummary1.Running = DevExpress.XtraReports.UI.SummaryRunning.Report; this.CellNo.Summary = xrSummary1; resources.ApplyResources(this.CellNo, "CellNo"); this.CellNo.Weight = 0.38081821550921535D; // // CellICD // this.CellICD.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN85Monthly.strICD")}); this.CellICD.Name = "CellICD"; resources.ApplyResources(this.CellICD, "CellICD"); this.CellICD.Weight = 0.46121295116197081D; // // CellTotal // this.CellTotal.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN85Monthly.intTotal")}); this.CellTotal.Name = "CellTotal"; resources.ApplyResources(this.CellTotal, "CellTotal"); this.CellTotal.Weight = 0.55007044008589689D; this.CellTotal.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.Cell_BeforePrint); // // CellChildren // this.CellChildren.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN85Monthly.intIncludingChildren")}); this.CellChildren.Name = "CellChildren"; resources.ApplyResources(this.CellChildren, "CellChildren"); this.CellChildren.Weight = 0.55007037552119853D; this.CellChildren.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.Cell_BeforePrint); // // CustomReportHeader // this.CustomReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.TableHeader, this.lblYearMonth, this.lblReportPeriod, this.lblCustomReportName}); resources.ApplyResources(this.CustomReportHeader, "CustomReportHeader"); this.CustomReportHeader.Name = "CustomReportHeader"; // // TableHeader // this.TableHeader.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.TableHeader, "TableHeader"); this.TableHeader.Name = "TableHeader"; this.TableHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.TableHeader.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow1, this.xrTableRow2, this.xrTableRow3}); this.TableHeader.StylePriority.UseBorders = false; this.TableHeader.StylePriority.UsePadding = false; this.TableHeader.StylePriority.UseTextAlignment = false; // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell1, this.xrTableCell4, this.xrTableCell2, this.xrTableCell3}); this.xrTableRow1.Name = "xrTableRow1"; this.xrTableRow1.Weight = 1D; // // xrTableCell1 // this.xrTableCell1.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); this.xrTableCell1.Name = "xrTableCell1"; this.xrTableCell1.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell1, "xrTableCell1"); this.xrTableCell1.Weight = 1.0578280177217185D; // // xrTableCell4 // this.xrTableCell4.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); this.xrTableCell4.Name = "xrTableCell4"; this.xrTableCell4.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell4, "xrTableCell4"); this.xrTableCell4.Weight = 0.38081808637981862D; // // xrTableCell2 // this.xrTableCell2.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); this.xrTableCell2.Name = "xrTableCell2"; this.xrTableCell2.StylePriority.UseBorders = false; this.xrTableCell2.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell2, "xrTableCell2"); this.xrTableCell2.Weight = 0.46121301572666917D; // // xrTableCell3 // this.xrTableCell3.Name = "xrTableCell3"; resources.ApplyResources(this.xrTableCell3, "xrTableCell3"); this.xrTableCell3.Weight = 1.1001408801717938D; // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell5, this.xrTableCell6, this.xrTableCell7, this.xrTableCell9, this.xrTableCell8}); this.xrTableRow2.Name = "xrTableRow2"; this.xrTableRow2.Weight = 2.4D; // // xrTableCell5 // this.xrTableCell5.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell5.Name = "xrTableCell5"; this.xrTableCell5.StylePriority.UseBorders = false; this.xrTableCell5.StylePriority.UseTextAlignment = false; this.xrTableCell5.Weight = 1.0578280177217185D; // // xrTableCell6 // this.xrTableCell6.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell6.Name = "xrTableCell6"; this.xrTableCell6.StylePriority.UseBorders = false; this.xrTableCell6.Weight = 0.38081821550921535D; // // xrTableCell7 // this.xrTableCell7.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell7.Name = "xrTableCell7"; this.xrTableCell7.StylePriority.UseBorders = false; this.xrTableCell7.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell7, "xrTableCell7"); this.xrTableCell7.Weight = 0.46121295116197081D; // // xrTableCell9 // this.xrTableCell9.Name = "xrTableCell9"; this.xrTableCell9.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell9, "xrTableCell9"); this.xrTableCell9.Weight = 0.55007056921529363D; // // xrTableCell8 // this.xrTableCell8.Multiline = true; this.xrTableCell8.Name = "xrTableCell8"; this.xrTableCell8.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell8, "xrTableCell8"); this.xrTableCell8.Weight = 0.5500702463918018D; // // xrTableRow3 // this.xrTableRow3.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell10, this.xrTableCell11, this.xrTableCell12, this.xrTableCell13, this.xrTableCell14}); this.xrTableRow3.Name = "xrTableRow3"; this.xrTableRow3.StylePriority.UseBorders = false; this.xrTableRow3.StylePriority.UseTextAlignment = false; this.xrTableRow3.Weight = 1D; // // xrTableCell10 // this.xrTableCell10.Name = "xrTableCell10"; resources.ApplyResources(this.xrTableCell10, "xrTableCell10"); this.xrTableCell10.Weight = 1.0578280177217185D; // // xrTableCell11 // this.xrTableCell11.Name = "xrTableCell11"; resources.ApplyResources(this.xrTableCell11, "xrTableCell11"); this.xrTableCell11.Weight = 0.380818150944517D; // // xrTableCell12 // this.xrTableCell12.Name = "xrTableCell12"; resources.ApplyResources(this.xrTableCell12, "xrTableCell12"); this.xrTableCell12.Weight = 0.46121301572666917D; // // xrTableCell13 // this.xrTableCell13.Name = "xrTableCell13"; resources.ApplyResources(this.xrTableCell13, "xrTableCell13"); this.xrTableCell13.Weight = 0.55007069834469025D; // // xrTableCell14 // this.xrTableCell14.Name = "xrTableCell14"; resources.ApplyResources(this.xrTableCell14, "xrTableCell14"); this.xrTableCell14.Weight = 0.55007011726240518D; // // lblYearMonth // this.lblYearMonth.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN85Monthly.strReportedPeriod")}); resources.ApplyResources(this.lblYearMonth, "lblYearMonth"); this.lblYearMonth.Name = "lblYearMonth"; this.lblYearMonth.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); // // lblReportPeriod // resources.ApplyResources(this.lblReportPeriod, "lblReportPeriod"); this.lblReportPeriod.Name = "lblReportPeriod"; this.lblReportPeriod.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); // // lblCustomReportName // resources.ApplyResources(this.lblCustomReportName, "lblCustomReportName"); this.lblCustomReportName.Multiline = true; this.lblCustomReportName.Name = "lblCustomReportName"; this.lblCustomReportName.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.lblCustomReportName.StylePriority.UseFont = false; this.lblCustomReportName.StylePriority.UseTextAlignment = false; // // CustomReportFooter // this.CustomReportFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.TableFooter}); resources.ApplyResources(this.CustomReportFooter, "CustomReportFooter"); this.CustomReportFooter.Name = "CustomReportFooter"; // // TableFooter // resources.ApplyResources(this.TableFooter, "TableFooter"); this.TableFooter.Name = "TableFooter"; this.TableFooter.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.TableFooter.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow4, this.xrTableRow5, this.xrTableRow6, this.xrTableRow7, this.xrTableRow8, this.xrTableRow9, this.xrTableRow11, this.xrTableRow12, this.xrTableRow13}); this.TableFooter.StylePriority.UseFont = false; this.TableFooter.StylePriority.UsePadding = false; // // xrTableRow4 // this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell15, this.xrTableCell17}); this.xrTableRow4.Name = "xrTableRow4"; this.xrTableRow4.Weight = 1.3090898788152345D; // // xrTableCell15 // this.xrTableCell15.Name = "xrTableCell15"; resources.ApplyResources(this.xrTableCell15, "xrTableCell15"); this.xrTableCell15.Weight = 0.17138148050714111D; // // xrTableCell17 // this.xrTableCell17.Name = "xrTableCell17"; resources.ApplyResources(this.xrTableCell17, "xrTableCell17"); this.xrTableCell17.Weight = 2.828618519492859D; // // xrTableRow5 // this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell16, this.xrTableCell18}); this.xrTableRow5.Name = "xrTableRow5"; this.xrTableRow5.Weight = 1.3090898788152343D; // // xrTableCell16 // this.xrTableCell16.Name = "xrTableCell16"; resources.ApplyResources(this.xrTableCell16, "xrTableCell16"); this.xrTableCell16.Weight = 0.17138148050714111D; // // xrTableCell18 // this.xrTableCell18.Name = "xrTableCell18"; resources.ApplyResources(this.xrTableCell18, "xrTableCell18"); this.xrTableCell18.Weight = 2.828618519492859D; // // xrTableRow6 // this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell19, this.xrTableCell20}); this.xrTableRow6.Name = "xrTableRow6"; this.xrTableRow6.Weight = 1.8701283554092578D; // // xrTableCell19 // this.xrTableCell19.Name = "xrTableCell19"; resources.ApplyResources(this.xrTableCell19, "xrTableCell19"); this.xrTableCell19.Weight = 0.17138148050714111D; // // xrTableCell20 // this.xrTableCell20.Name = "xrTableCell20"; resources.ApplyResources(this.xrTableCell20, "xrTableCell20"); this.xrTableCell20.Weight = 2.828618519492859D; // // xrTableRow7 // this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell21, this.xrTableCell22}); this.xrTableRow7.Name = "xrTableRow7"; this.xrTableRow7.Weight = 1.3090898726819276D; // // xrTableCell21 // this.xrTableCell21.Name = "xrTableCell21"; resources.ApplyResources(this.xrTableCell21, "xrTableCell21"); this.xrTableCell21.Weight = 0.17138148050714111D; // // xrTableCell22 // this.xrTableCell22.Name = "xrTableCell22"; resources.ApplyResources(this.xrTableCell22, "xrTableCell22"); this.xrTableCell22.Weight = 2.828618519492859D; // // xrTableRow8 // this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell23, this.xrTableCell24}); this.xrTableRow8.Name = "xrTableRow8"; this.xrTableRow8.Weight = 1.3090898726819276D; // // xrTableCell23 // this.xrTableCell23.Name = "xrTableCell23"; resources.ApplyResources(this.xrTableCell23, "xrTableCell23"); this.xrTableCell23.Weight = 0.17138148050714111D; // // xrTableCell24 // this.xrTableCell24.Name = "xrTableCell24"; resources.ApplyResources(this.xrTableCell24, "xrTableCell24"); this.xrTableCell24.Weight = 2.828618519492859D; // // xrTableRow9 // this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell25, this.xrTableCell26}); this.xrTableRow9.Name = "xrTableRow9"; this.xrTableRow9.Weight = 2.0935055318540812D; // // xrTableCell25 // this.xrTableCell25.Name = "xrTableCell25"; resources.ApplyResources(this.xrTableCell25, "xrTableCell25"); this.xrTableCell25.Weight = 0.17138148050714111D; // // xrTableCell26 // this.xrTableCell26.Name = "xrTableCell26"; resources.ApplyResources(this.xrTableCell26, "xrTableCell26"); this.xrTableCell26.Weight = 2.828618519492859D; // // xrTableRow11 // this.xrTableRow11.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell27, this.xrTableCell28}); this.xrTableRow11.Name = "xrTableRow11"; this.xrTableRow11.Weight = 1.1999989193196903D; // // xrTableCell27 // this.xrTableCell27.Name = "xrTableCell27"; this.xrTableCell27.Weight = 1.7330310827240347D; // // xrTableCell28 // this.xrTableCell28.Name = "xrTableCell28"; resources.ApplyResources(this.xrTableCell28, "xrTableCell28"); this.xrTableCell28.Weight = 1.2669689172759655D; // // xrTableRow12 // this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell29, this.xrTableCell30}); this.xrTableRow12.Name = "xrTableRow12"; this.xrTableRow12.Weight = 2.9999971905902441D; // // xrTableCell29 // this.xrTableCell29.Name = "xrTableCell29"; resources.ApplyResources(this.xrTableCell29, "xrTableCell29"); this.xrTableCell29.Weight = 1.7330310827240347D; // // xrTableCell30 // this.xrTableCell30.Name = "xrTableCell30"; resources.ApplyResources(this.xrTableCell30, "xrTableCell30"); this.xrTableCell30.Weight = 1.2669689172759655D; // // xrTableRow13 // this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell31, this.xrTableCell32}); this.xrTableRow13.Name = "xrTableRow13"; this.xrTableRow13.Weight = 0.99999911140073983D; // // xrTableCell31 // this.xrTableCell31.Borders = DevExpress.XtraPrinting.BorderSide.Top; this.xrTableCell31.Name = "xrTableCell31"; this.xrTableCell31.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell31, "xrTableCell31"); this.xrTableCell31.Weight = 1.7330310827240347D; // // xrTableCell32 // this.xrTableCell32.Name = "xrTableCell32"; this.xrTableCell32.Weight = 1.2669689172759655D; // // spRepHumFormN85MonthlyTableAdapter // this.spRepHumFormN85MonthlyTableAdapter.ClearBeforeFill = true; // // formN85MontlyDataSet // this.formN85MontlyDataSet.DataSetName = "FormN85MontlyDataSet"; this.formN85MontlyDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // FormN85MonthlyReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.PageHeader, this.PageFooter, this.DetailReport, this.ReportHeader}); this.Landscape = false; this.PageHeight = 1169; this.PageWidth = 827; this.Version = "11.1"; this.Controls.SetChildIndex(this.ReportHeader, 0); this.Controls.SetChildIndex(this.DetailReport, 0); this.Controls.SetChildIndex(this.PageFooter, 0); this.Controls.SetChildIndex(this.PageHeader, 0); this.Controls.SetChildIndex(this.Detail, 0); ((System.ComponentModel.ISupportInitialize)(this.xrTable4)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.TableDetail)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.TableHeader)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.TableFooter)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.formN85MontlyDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailReportBand DetailReport; private DevExpress.XtraReports.UI.DetailBand CustomDetail; private DevExpress.XtraReports.UI.ReportHeaderBand CustomReportHeader; private DevExpress.XtraReports.UI.XRLabel lblReportPeriod; private DevExpress.XtraReports.UI.XRLabel lblCustomReportName; private DevExpress.XtraReports.UI.XRLabel lblYearMonth; private DevExpress.XtraReports.UI.ReportFooterBand CustomReportFooter; private DevExpress.XtraReports.UI.XRTable TableHeader; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell3; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRTableCell xrTableCell7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell8; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; private DevExpress.XtraReports.UI.XRTableRow xrTableRow3; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private DevExpress.XtraReports.UI.XRTableCell xrTableCell11; private DevExpress.XtraReports.UI.XRTableCell xrTableCell12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell13; private DevExpress.XtraReports.UI.XRTableCell xrTableCell14; private DevExpress.XtraReports.UI.XRTable TableDetail; private DevExpress.XtraReports.UI.XRTableRow TableRowDetail; private DevExpress.XtraReports.UI.XRTableCell CellDisease; private DevExpress.XtraReports.UI.XRTableCell CellNo; private DevExpress.XtraReports.UI.XRTableCell CellICD; private DevExpress.XtraReports.UI.XRTableCell CellTotal; private DevExpress.XtraReports.UI.XRTableCell CellChildren; private DevExpress.XtraReports.UI.XRTable TableFooter; private DevExpress.XtraReports.UI.XRTableRow xrTableRow4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell15; private DevExpress.XtraReports.UI.XRTableCell xrTableCell17; private DevExpress.XtraReports.UI.XRTableRow xrTableRow5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell16; private DevExpress.XtraReports.UI.XRTableCell xrTableCell18; private DevExpress.XtraReports.UI.XRTableRow xrTableRow6; private DevExpress.XtraReports.UI.XRTableCell xrTableCell19; private DevExpress.XtraReports.UI.XRTableCell xrTableCell20; private DevExpress.XtraReports.UI.XRTableRow xrTableRow7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell21; private DevExpress.XtraReports.UI.XRTableCell xrTableCell22; private DevExpress.XtraReports.UI.XRTableRow xrTableRow8; private DevExpress.XtraReports.UI.XRTableCell xrTableCell23; private DevExpress.XtraReports.UI.XRTableCell xrTableCell24; private DevExpress.XtraReports.UI.XRTableRow xrTableRow9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell25; private DevExpress.XtraReports.UI.XRTableCell xrTableCell26; private DevExpress.XtraReports.UI.XRTableRow xrTableRow11; private DevExpress.XtraReports.UI.XRTableCell xrTableCell27; private DevExpress.XtraReports.UI.XRTableCell xrTableCell28; private DevExpress.XtraReports.UI.XRTableRow xrTableRow12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell29; private DevExpress.XtraReports.UI.XRTableCell xrTableCell30; private DevExpress.XtraReports.UI.XRTableRow xrTableRow13; private DevExpress.XtraReports.UI.XRTableCell xrTableCell31; private DevExpress.XtraReports.UI.XRTableCell xrTableCell32; private EIDSS.Reports.Parameterized.Human.ARM.DataSet.FormN85MontlyDataSetTableAdapters.spRepHumFormN85MonthlyTableAdapter spRepHumFormN85MonthlyTableAdapter; private EIDSS.Reports.Parameterized.Human.ARM.DataSet.FormN85MontlyDataSet formN85MontlyDataSet; } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Text; namespace Es.Splay { public sealed class SplayTree<T> : ISplayTree<T> where T : IComparable<T> { private const int MaxRecursionDepth = 80; internal Node Root; internal sealed class Node { public readonly T Data; public Node Parent; public Node Left; public Node Right; public int LeftCount; public int RightCount; public Node(T t) { Data = t; Left = null; LeftCount = 0; Right = null; RightCount = 0; Parent = null; } [ExcludeFromCodeCoverage] // only used for testing public override string ToString() { return $"{Data} ({LeftCount}|{RightCount})"; } } public int Count { get; internal set; } public bool IsReadOnly { get; } = false; public void Clear() { Root = null; Count = 0; } public bool Contains(T item) { return Find(item) != null; } public void CopyTo(T[] array, int arrayIndex) { Traverse(Root, n => { array[arrayIndex++] = n.Data; return true; }); } [ExcludeFromCodeCoverage] // for debugging only. public void Validate() { #if DEBUG if (Root == null) return; var seen = new HashSet<Node>(); Debug.Assert(1 + Root.LeftCount + Root.RightCount == Count); Traverse(Root, n => { if (seen.Contains(n)) return false; seen.Add(n); if (n.Parent != null) if (n.Parent.Left==n) Debug.Assert(n.Parent.LeftCount == 1 + n.LeftCount + n.RightCount); else Debug.Assert(n.Parent.RightCount == 1 + n.LeftCount + n.RightCount); if (n.Left!=null) Debug.Assert(n.LeftCount == 1 + n.Left.LeftCount + n.Left.RightCount); if (n.Right != null) Debug.Assert(n.RightCount == 1 + n.Right.LeftCount + n.Right.RightCount); return true; }); #endif } private void Splay(Node x) { while (x.Parent != null) { var xIsALeftChild = x.Parent.Left == x; if (x.Parent.Parent == null) { // no grandparent so we're one away from the root. if (xIsALeftChild) RightRotate(x.Parent); // we're left of root, rotating right will make us root else LeftRotate(x.Parent); // we're right of root, rotating left will make us root } else { var parentIsALeftChild = x.Parent.Parent.Left == x.Parent; if (xIsALeftChild) { if (parentIsALeftChild) { RightRotate(x.Parent.Parent); RightRotate(x.Parent); } else // parentIsARightChild { RightRotate(x.Parent); LeftRotate(x.Parent); } } else // xIsARightChild { if (parentIsALeftChild) { LeftRotate(x.Parent); RightRotate(x.Parent); } else // parentIsARightChild { LeftRotate(x.Parent.Parent); LeftRotate(x.Parent); } } } } } private Node Find(T data) { var u = Root; while (u != null) { var cmp = u.Data.CompareTo(data); if (cmp == 0) { return u; } u = cmp < 0 ? u.Right : u.Left; } return null; } private Node FindNear(T data) { var u = Root; var p = u; while (u != null) { var cmp = u.Data.CompareTo(data); if (cmp == 0) { return u; } p = u; u = cmp < 0 ? u.Right : u.Left; } return p; } private void Add(Node z) { Debug.Assert(z.LeftCount == 0); Debug.Assert(z.RightCount == 0); var u = Root; var p = u; while (u != null) { var cmp = u.Data.CompareTo(z.Data); p = u; if (cmp < 0) { ++u.RightCount; u = u.Right; } else { ++u.LeftCount; u = u.Left; } } z.Parent = p; if (p == null) { Root = z; } else if (p.Data.CompareTo(z.Data)<0) { Debug.Assert(p.Right == null); p.Right = z; p.RightCount = 1; } else { Debug.Assert(p.Left == null); p.Left = z; p.LeftCount = 1; } ++Count; Splay(z); } public void Add(T data) { var z = Find(data); if (z == null) { Add(new Node(data)); } else { throw new InvalidOperationException("Values must be unique"); } if (Root != null) { Debug.Assert(Count == 1 + Root.LeftCount + Root.RightCount); } } public IEnumerable<T> NearBy(T data, int before, int after) { var p = FindNear(data); if (p == null) { return Enumerable.Empty<T>(); } Splay(p); return Near(before, after); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private IEnumerable<T> Near(int before, int after) { var p = Root; var l = new List<T>(before + after + 1) {p.Data}; if (p.Left != null) { var previous = p.Left; while (previous.Right != null) { previous = previous.Right; } ReverseOrderTraverseNodes( previous, n => { if (before <= 0) return false; l.Add(n.Data); --before; return true; } ); } if (p.Right != null) { var next = p.Right; while (next.Left != null) { next = next.Left; } ForwardOrderTraverseNodes( next, n => { if (after <= 0) return false; l.Add(n.Data); --after; return true; } ); } l.Sort(); return l; } public bool Remove(T data) { var z = Find(data); if (z == null) { return false; } Remove(z); return true; } public T Best() { var x = LeftMost(); if (x==null) throw new InvalidOperationException("Can't find the Best entry in an empty tree"); return x.Data; } private Node LeftMost() { var x = Root; while (x?.Left != null) { x = x.Left; } return x; } public T Worst() { var x = Root; while (x?.Right != null) { x = x.Right; } if (x == null) throw new InvalidOperationException("Can't find the Woest entry in an empty tree"); return x.Data; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void Remove(Node z) { Splay(z); #if DEBUG var totalWeight = 0; if (Root != null) { totalWeight = 1 + Root.LeftCount + Root.RightCount; } #endif if (z.Left == null) { Root = z.Right; //Replace(z, z.Right); } else if (z.Right == null) { Root = z.Left; //Replace(z, z.Left); } else // both z.Left and z.Right are non null { // take z.Right's leftmost and bring it up to become the new root. var zR = z.Right; var zL = z.Left; var u = zR; while (u.Left != null) { --u.LeftCount; // we are removing the left most, so updates the counts as we go. u = u.Left; } var uP = u.Parent; if (uP != z) { var uR = u.Right; uP.LeftCount = u.RightCount; uP.Left = uR; if (uR != null) { uR.Parent = uP; } u.Right = zR; zR.Parent = u; u.RightCount = z.RightCount - 1; // remember, we're removing moveToRoot from the right side. } else { Debug.Assert(u == zR); } Root = u; u.Left = zL; zL.Parent = u; u.LeftCount = z.LeftCount; } if (Root != null) { Root.Parent = null; } z.Parent = null; z.Left = null; z.Right = null; z.LeftCount = 0; z.RightCount = 0; #if DEBUG int totalWeightAfter; if (Root == null) totalWeightAfter = 0; else totalWeightAfter = 1 + Root.LeftCount + Root.RightCount; Debug.Assert(totalWeightAfter == totalWeight - 1); #endif --Count; } private void LeftRotate(Node x) { #if DEBUG var totalWeight = x.Parent == null ? 1 + Root.LeftCount + Root.RightCount : x.Parent.Left == x ? x.Parent.LeftCount : x.Parent.RightCount; Debug.Assert(totalWeight <= Count); Debug.Assert(x.Right != null); #endif var right = x.Right; var parent = x.Parent; var rightLeft = right.Left; var rightLeftCount = right.LeftCount; x.Right = rightLeft; x.RightCount = rightLeftCount; if (rightLeft != null) rightLeft.Parent = x; right.Parent = parent; if (parent == null) Root = right; else if (x == parent.Left) parent.Left = right; else parent.Right = right; right.Left = x; right.LeftCount = 1 + x.LeftCount + x.RightCount; x.Parent = right; #if DEBUG x = right; var totalWeightAfter = x.Parent == null ? 1 + Root.LeftCount + Root.RightCount : x.Parent.Left == x ? x.Parent.LeftCount : x.Parent.RightCount; Debug.Assert(totalWeight == totalWeightAfter); #endif } private void RightRotate(Node x) { #if DEBUG var totalWeight = x.Parent == null ? 1 + Root.LeftCount + Root.RightCount : x.Parent.Left == x ? x.Parent.LeftCount : x.Parent.RightCount; Debug.Assert(totalWeight <= Count); Debug.Assert(x.Left != null); #endif var left = x.Left; var parent = x.Parent; var leftRight = left.Right; var leftRightCount = left.RightCount; x.Left = leftRight; x.LeftCount = leftRightCount; if (leftRight != null) leftRight.Parent = x; left.Parent = parent; if (parent == null) Root = left; else if (x == parent.Right) parent.Right = left; else parent.Left = left; left.Right = x; left.RightCount = 1 + x.RightCount + x.LeftCount; x.Parent = left; #if DEBUG x = left; var totalWeightAfter = x.Parent == null ? 1 + Root.LeftCount + Root.RightCount : x.Parent.Left == x ? x.Parent.LeftCount : x.Parent.RightCount; Debug.Assert(totalWeight == totalWeightAfter); #endif } internal void Traverse(Node n, Func<Node, bool> f) { if (n == null) return; var ln = n.Parent; while (n != null) { if (ln == n.Parent) { // we're descending ln = n; if (n.Left != null) { // we can go left, so go left n = n.Left; continue; } if (!f(n)) // going right or up means all values after this are greater. return; // we can't go left if (n.Right != null) // but we can go right { n = n.Right; continue; } // we have to go back up n = n.Parent; continue; } if (ln == n.Left) // we're ascending from the left side { if (!f(n)) // all values after this are greater. return; ln = n; if (n.Right != null) // we can go right { n = n.Right; continue; } // we have to go back up n = n.Parent; continue; } if (ln == n.Right) // we're ascending from the right side { ln = n; n = n.Parent; continue; } throw new Exception("Invalid Tree"); } } public void ForwardOrderTraverse(T data, Func<T, bool> f) { var n = FindNear(data); if (n == null) return; ForwardOrderTraverseNodes(n,x=>f(x.Data)); } private static void ForwardOrderTraverseNodes(Node n, Func<Node, bool> f) { // go forward from n var ln = n.Left ?? n.Parent; while (n != null) { if (ln == n.Parent) { // we're descending ln = n; if (n.Left != null) { // we can go left, so go left n = n.Left; continue; } if (!f(n)) // going right or up means all values after this are greater. return; // we can't go left if (n.Right != null) // but we can go right { n = n.Right; continue; } // we have to go back up n = n.Parent; continue; } if (ln == n.Left) // we're ascending from the left side { if (!f(n)) // all values after this are greater. return; ln = n; if (n.Right != null) // we can go right { n = n.Right; continue; } // we have to go back up n = n.Parent; continue; } if (ln == n.Right) // we're ascending from the right side { ln = n; n = n.Parent; continue; } throw new Exception("Invalid Tree"); } } public void ReverseOrderTraverse(T data, Func<T, bool> f) { var n = FindNear(data); if (n == null) return; ReverseOrderTraverseNodes(n,x=>f(x.Data)); } private static void ReverseOrderTraverseNodes(Node n, Func<Node, bool> f) { // go reverse from n var ln = n.Right ?? n.Parent; while (n != null) { if (ln == n.Parent) { // we're descending ln = n; if (n.Right != null) { // we can go right, so go right n = n.Right; continue; } if (!f(n)) // going Left or up means all values after this are lesser. return; // we can't go right if (n.Left != null) // but we can go left { n = n.Left; continue; } // we have to go back up n = n.Parent; continue; } if (ln == n.Right) // we're ascending from the right side { if (!f(n)) // all values after this are lesser. return; ln = n; if (n.Left != null) // we can go Left { n = n.Left; continue; } // we have to go back up n = n.Parent; continue; } if (ln == n.Left) // we're ascending from the Left side { ln = n; n = n.Parent; continue; } throw new Exception("Invalid Tree"); } } public bool TryGetRank(T data, out int rank) { rank = 0; var n = Find(data); if (n == null) return false; Splay(n); rank = n.LeftCount; return true; } public IEnumerator<T> GetEnumerator() { if (Root == null) return Enumerable.Empty<T>().GetEnumerator(); var n = LeftMost(); Splay(n); return Near(0, Count).GetEnumerator(); } [ExcludeFromCodeCoverage] // only used for debugging public override string ToString() { var sb = new StringBuilder(); var ids = new Dictionary<Node,string>(); var seen = new HashSet<Node>(); var nullId = 0; var nodeId = 0; Func<Node, string> idfor = x => ids.Vivify(x, () => "o" + nodeId++); sb.Append("digraph t {"); if (Root == null) { sb.AppendFormat("\"Root\" -> \"null\";"); } else { sb.Append($"\"Root\" -> \"{idfor(Root)}\";"); } try { Traverse(Root, n => { if (seen.Contains(n)) { sb.Append($"\"CYCLE\" [label=\"{n.Data}\"];"); return false; } seen.Add(n); var id = idfor(n); Debug.Assert(n.Data != null); sb.Append($"\"{id}\" [label=\"{n.Data}:{n.LeftCount},{n.RightCount}\"];"); if (n.Parent != null) { sb.Append($"\"{id}\"->\"{idfor(n.Parent)}\" [label=\"P\"];"); } if (n.Left == null && n.Right == null) return true; if (n.Left == null) { sb.Append($"\"n{nullId}\" [label=\"null\"];"); sb.Append($"\"{id}\"->\"n{nullId}\" [label=\"L\"];"); ++nullId; } else { Debug.Assert(n.Left.Data != null); sb.Append($"\"{id}\"->\"{idfor(n.Left)}\" [label=\"L\"];"); } if (n.Right == null) { sb.Append($"\"n{nullId}\" [label=\"null\"];"); sb.Append($"\"{id}\"->\"n{nullId}\" [label=\"R\"];"); ++nullId; } else { Debug.Assert(n.Right.Data != null); sb.Append($"\"{id}\"->\"{idfor(n.Right)}\" [label=\"R\"];"); } return true; }); } catch { sb.Append($"\"CYCLE\" [label=\"INVALID TREE\"];"); } sb.Append("}"); return sb.ToString(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Balance() { if (Count < 3) return 0; return Root == null ? 0 : Balance(Root, 1, MaxRecursionDepth); } public int Prune(int newDesiredCount, Func<T, bool> locked = null) { if (Count == 0 || Count < newDesiredCount) return 0; Balance(); return Prune(Root, Count - newDesiredCount, locked); } private int Prune(Node n, int toRemove, Func<T, bool> locked) { Debug.Assert(n != null); Debug.Assert(toRemove > 0); var totalChildCount = n.LeftCount + n.RightCount; Debug.Assert(totalChildCount > 0); var removed = 0; // split remaining removal amount across left and right children int removeLeft; int removeRight; if (n.LeftCount <= n.RightCount) { removeLeft = (int)(((long)toRemove * n.LeftCount) / totalChildCount); removeRight = toRemove - removeLeft; // lump remainder to the right since it has more or the same (slight bias here) } else { removeRight = (int)(((long)toRemove * n.RightCount) / totalChildCount); removeLeft = toRemove - removeRight; // lump remainder to the left since it has more } Debug.Assert(removeRight + removeLeft == toRemove); if (removeLeft > 0 && n.LeftCount > 1) { var removedFromLeft = Prune(n.Left, removeLeft, locked); n.LeftCount -= removedFromLeft; Debug.Assert(n.LeftCount >= 0); removed += removedFromLeft; toRemove -= removedFromLeft; } if (removeRight > 0 && n.RightCount > 1) { var removedFromRight = Prune(n.Right, removeRight, locked); n.RightCount -= removedFromRight; Debug.Assert(n.RightCount >= 0); removed += removedFromRight; toRemove -= removedFromRight; } if (toRemove == 0) return removed; // it's now possible our left or right is a 1 count and we still have more to remove so try them. if (n.RightCount == 1 && (locked == null || !locked(n.Right.Data))) { Debug.Assert(n.Right != null); n.RightCount = 0; n.Right = null; ++removed; --toRemove; } if (toRemove == 0) return removed; if (n.LeftCount == 1 && (locked == null || !locked(n.Left.Data))) { Debug.Assert(n.Left != null); n.LeftCount = 0; n.Left = null; ++removed; --toRemove; } return removed; } private int Balance(Node n, int h, int maxH) { // since we're dealing with weight and not height this may not be a perfect balance, // we do a BalanceChildren before and after to limit the recursion depth (after would be // more normal, as Prune does) if (n == null || n.Left == null && n.Right == null || h >= maxH) { return h; } BalanceChildren(ref n); var lh = Balance(n.Left, h + 1, maxH); var rh = Balance(n.Right, h + 1, maxH); BalanceChildren(ref n); return lh > rh ? lh : rh; } private void BalanceChildren(ref Node n) { var l = n.Left; var r = n.Right; for (;;) { var diff = n.LeftCount - n.RightCount; if (diff > 1) // Left weighs more than Right { Debug.Assert(l != null); var newLeftCount = l.LeftCount; var newRightCount = 1 + l.RightCount + n.RightCount; var newDiff = newLeftCount - newRightCount; // if we rotated right this would be the new diff if (newDiff < 0) newDiff = -newDiff; if (newDiff >= diff) // if the new diff is worse or the same don't bother return; RightRotate(n); // left -> right n = l; Debug.Assert(n.LeftCount == newLeftCount); Debug.Assert(n.RightCount == newRightCount); } else if (diff < -1) // right weighs more than left { Debug.Assert(r != null); diff = -diff; var newLeftCount = 1 + r.LeftCount + n.LeftCount; var newRightCount = r.RightCount; var newDiff = newRightCount - newLeftCount; // if we rotated left this would be the new diff if (newDiff < 0) newDiff = -newDiff; if (newDiff >= diff) // if the new diff is worse or the same don't bother return; LeftRotate(n); // right -> left n = r; Debug.Assert(n.LeftCount == newLeftCount); Debug.Assert(n.RightCount == newRightCount); } else { return; } l = n.Left; r = n.Right; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes { using Microsoft.CodeAnalysis.ErrorLogger; using DiagnosticId = String; using LanguageKind = String; [Export(typeof(ICodeFixService)), Shared] internal partial class CodeFixService : ICodeFixService { private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>> _workspaceFixersMap; private readonly ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>> _projectFixersMap; // Shared by project fixers and workspace fixers. private ImmutableDictionary<CodeFixProvider, ImmutableArray<DiagnosticId>> _fixerToFixableIdsMap = ImmutableDictionary<CodeFixProvider, ImmutableArray<DiagnosticId>>.Empty; private readonly ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>> _fixerPriorityMap; private readonly ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider> _analyzerReferenceToFixersMap; private readonly ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>.CreateValueCallback _createProjectCodeFixProvider; private readonly ImmutableDictionary<LanguageKind, Lazy<ISuppressionFixProvider>> _suppressionProvidersMap; private readonly IEnumerable<Lazy<IErrorLoggerService>> _errorLoggers; private ImmutableDictionary<CodeFixProvider, FixAllProviderInfo> _fixAllProviderMap; [ImportingConstructor] public CodeFixService( IDiagnosticAnalyzerService service, [ImportMany]IEnumerable<Lazy<IErrorLoggerService>> loggers, [ImportMany]IEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> fixers, [ImportMany]IEnumerable<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>> suppressionProviders) { _errorLoggers = loggers; _diagnosticService = service; var fixersPerLanguageMap = fixers.ToPerLanguageMapWithMultipleLanguages(); var suppressionProvidersPerLanguageMap = suppressionProviders.ToPerLanguageMapWithMultipleLanguages(); _workspaceFixersMap = GetFixerPerLanguageMap(fixersPerLanguageMap, null); _suppressionProvidersMap = GetSuppressionProvidersPerLanguageMap(suppressionProvidersPerLanguageMap); // REVIEW: currently, fixer's priority is statically defined by the fixer itself. might considering making it more dynamic or configurable. _fixerPriorityMap = GetFixerPriorityPerLanguageMap(fixersPerLanguageMap); // Per-project fixers _projectFixersMap = new ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, ImmutableDictionary<string, List<CodeFixProvider>>>(); _analyzerReferenceToFixersMap = new ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>(); _createProjectCodeFixProvider = new ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>.CreateValueCallback(r => new ProjectCodeFixProvider(r)); _fixAllProviderMap = ImmutableDictionary<CodeFixProvider, FixAllProviderInfo>.Empty; } public async Task<FirstDiagnosticResult> GetFirstDiagnosticWithFixAsync(Document document, TextSpan range, bool considerSuppressionFixes, CancellationToken cancellationToken) { if (document == null || !document.IsOpen()) { return default(FirstDiagnosticResult); } using (var diagnostics = SharedPools.Default<List<DiagnosticData>>().GetPooledObject()) { var fullResult = await _diagnosticService.TryAppendDiagnosticsForSpanAsync(document, range, diagnostics.Object, cancellationToken).ConfigureAwait(false); foreach (var diagnostic in diagnostics.Object) { cancellationToken.ThrowIfCancellationRequested(); if (!range.IntersectsWith(diagnostic.TextSpan)) { continue; } // REVIEW: 2 possible designs. // 1. find the first fix and then return right away. if the lightbulb is actually expanded, find all fixes for the line synchronously. or // 2. kick off a task that finds all fixes for the given range here but return once we find the first one. // at the same time, let the task to run to finish. if the lightbulb is expanded, we just simply use the task to get all fixes. // // first approach is simpler, so I will implement that first. if the first approach turns out to be not good enough, then // I will try the second approach which will be more complex but quicker var hasFix = await ContainsAnyFix(document, diagnostic, considerSuppressionFixes, cancellationToken).ConfigureAwait(false); if (hasFix) { return new FirstDiagnosticResult(!fullResult, hasFix, diagnostic); } } return new FirstDiagnosticResult(!fullResult, false, default(DiagnosticData)); } } public async Task<IEnumerable<CodeFixCollection>> GetFixesAsync(Document document, TextSpan range, bool includeSuppressionFixes, CancellationToken cancellationToken) { // REVIEW: this is the first and simplest design. basically, when ctrl+. is pressed, it asks diagnostic service to give back // current diagnostics for the given span, and it will use that to get fixes. internally diagnostic service will either return cached information // (if it is up-to-date) or synchronously do the work at the spot. // // this design's weakness is that each side don't have enough information to narrow down works to do. it will most likely always do more works than needed. // sometimes way more than it is needed. (compilation) Dictionary<TextSpan, List<DiagnosticData>> aggregatedDiagnostics = null; foreach (var diagnostic in await _diagnosticService.GetDiagnosticsForSpanAsync(document, range, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); aggregatedDiagnostics = aggregatedDiagnostics ?? new Dictionary<TextSpan, List<DiagnosticData>>(); aggregatedDiagnostics.GetOrAdd(diagnostic.TextSpan, _ => new List<DiagnosticData>()).Add(diagnostic); } var result = new List<CodeFixCollection>(); if (aggregatedDiagnostics == null) { return result; } foreach (var spanAndDiagnostic in aggregatedDiagnostics) { result = await AppendFixesAsync(document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, result, cancellationToken).ConfigureAwait(false); } if (result.Any()) { // sort the result to the order defined by the fixers var priorityMap = _fixerPriorityMap[document.Project.Language].Value; result.Sort((d1, d2) => priorityMap.ContainsKey((CodeFixProvider)d1.Provider) ? (priorityMap.ContainsKey((CodeFixProvider)d2.Provider) ? priorityMap[(CodeFixProvider)d1.Provider] - priorityMap[(CodeFixProvider)d2.Provider] : -1) : 1); } if (includeSuppressionFixes) { foreach (var spanAndDiagnostic in aggregatedDiagnostics) { result = await AppendSuppressionsAsync(document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, result, cancellationToken).ConfigureAwait(false); } } return result; } private async Task<List<CodeFixCollection>> AppendFixesAsync( Document document, TextSpan span, IEnumerable<DiagnosticData> diagnosticDataCollection, List<CodeFixCollection> result, CancellationToken cancellationToken) { Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> fixerMap; bool hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out fixerMap); var projectFixersMap = GetProjectFixers(document.Project); var hasAnyProjectFixer = projectFixersMap.Any(); if (!hasAnySharedFixer && !hasAnyProjectFixer) { return result; } ImmutableArray<CodeFixProvider> workspaceFixers; List<CodeFixProvider> projectFixers; var allFixers = new List<CodeFixProvider>(); foreach (var diagnosticId in diagnosticDataCollection.Select(d => d.Id).Distinct()) { cancellationToken.ThrowIfCancellationRequested(); if (hasAnySharedFixer && fixerMap.Value.TryGetValue(diagnosticId, out workspaceFixers)) { allFixers.AddRange(workspaceFixers); } if (hasAnyProjectFixer && projectFixersMap.TryGetValue(diagnosticId, out projectFixers)) { allFixers.AddRange(projectFixers); } } var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var diagnostics = diagnosticDataCollection.Select(data => data.ToDiagnostic(tree)).ToImmutableArray(); var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>(); foreach (var fixer in allFixers.Distinct()) { cancellationToken.ThrowIfCancellationRequested(); Func<Diagnostic, bool> hasFix = (d) => this.GetFixableDiagnosticIds(fixer, extensionManager).Contains(d.Id); Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes = async (dxs) => { var fixes = new List<CodeFix>(); var context = new CodeFixContext(document, span, dxs, // TODO: Can we share code between similar lambdas that we pass to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs? (a, d) => { // Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from. lock (fixes) { fixes.Add(new CodeFix(a, d)); } }, verifyArguments: false, cancellationToken: cancellationToken); var task = fixer.RegisterCodeFixesAsync(context) ?? SpecializedTasks.EmptyTask; await task.ConfigureAwait(false); return fixes; }; await AppendFixesOrSuppressionsAsync(document, span, diagnostics, result, fixer, hasFix, getFixes, cancellationToken).ConfigureAwait(false); } return result; } private async Task<List<CodeFixCollection>> AppendSuppressionsAsync( Document document, TextSpan span, IEnumerable<DiagnosticData> diagnosticDataCollection, List<CodeFixCollection> result, CancellationToken cancellationToken) { Lazy<ISuppressionFixProvider> lazySuppressionProvider; if (!_suppressionProvidersMap.TryGetValue(document.Project.Language, out lazySuppressionProvider) || lazySuppressionProvider.Value == null) { return result; } var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var diagnostics = diagnosticDataCollection.Select(data => data.ToDiagnostic(tree)); Func<Diagnostic, bool> hasFix = (d) => lazySuppressionProvider.Value.CanBeSuppressed(d); Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes = (dxs) => lazySuppressionProvider.Value.GetSuppressionsAsync(document, span, dxs, cancellationToken); await AppendFixesOrSuppressionsAsync(document, span, diagnostics, result, lazySuppressionProvider.Value, hasFix, getFixes, cancellationToken).ConfigureAwait(false); return result; } private async Task<List<CodeFixCollection>> AppendFixesOrSuppressionsAsync( Document document, TextSpan span, IEnumerable<Diagnostic> diagnosticsWithSameSpan, List<CodeFixCollection> result, object fixer, Func<Diagnostic, bool> hasFix, Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes, CancellationToken cancellationToken) { var diagnostics = diagnosticsWithSameSpan.Where(d => hasFix(d)).OrderByDescending(d => d.Severity).ToImmutableArray(); if (diagnostics.Length <= 0) { // this can happen for suppression case where all diagnostics can't be suppressed return result; } var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>(); var fixes = await extensionManager.PerformFunctionAsync(fixer, () => getFixes(diagnostics), defaultValue: SpecializedCollections.EmptyEnumerable<CodeFix>()).ConfigureAwait(false); if (fixes != null && fixes.Any()) { FixAllCodeActionContext fixAllContext = null; var codeFixProvider = fixer as CodeFixProvider; if (codeFixProvider != null) { // If the codeFixProvider supports fix all occurrences, then get the corresponding FixAllProviderInfo and fix all context. var fixAllProviderInfo = extensionManager.PerformFunction(codeFixProvider, () => ImmutableInterlocked.GetOrAdd(ref _fixAllProviderMap, codeFixProvider, FixAllProviderInfo.Create), defaultValue: null); if (fixAllProviderInfo != null) { fixAllContext = FixAllCodeActionContext.Create(document, fixAllProviderInfo, codeFixProvider, diagnostics, this.GetDocumentDiagnosticsAsync, this.GetProjectDiagnosticsAsync, cancellationToken); } } result = result ?? new List<CodeFixCollection>(); var codeFix = new CodeFixCollection(fixer, span, fixes, fixAllContext); result.Add(codeFix); } return result; } private async Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken) { Contract.ThrowIfNull(document); var solution = document.Project.Solution; var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var diagnostics = await _diagnosticService.GetDiagnosticsForIdsAsync(solution, null, document.Id, diagnosticIds, cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId != null)); return diagnostics.Select(d => d.ToDiagnostic(tree)); } private async Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, bool includeAllDocumentDiagnostics, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken) { Contract.ThrowIfNull(project); if (includeAllDocumentDiagnostics) { // Get all diagnostics for the entire project, including document diagnostics. var diagnostics = await _diagnosticService.GetDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds: diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false); var documentIdsToTreeMap = await GetDocumentIdsToTreeMapAsync(project, cancellationToken).ConfigureAwait(false); return diagnostics.Select(d => d.DocumentId != null ? d.ToDiagnostic(documentIdsToTreeMap[d.DocumentId]) : d.ToDiagnostic(null)); } else { // Get all no-location diagnostics for the project, doesn't include document diagnostics. var diagnostics = await _diagnosticService.GetProjectDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId == null)); return diagnostics.Select(d => d.ToDiagnostic(null)); } } private static async Task<ImmutableDictionary<DocumentId, SyntaxTree>> GetDocumentIdsToTreeMapAsync(Project project, CancellationToken cancellationToken) { var builder = ImmutableDictionary.CreateBuilder<DocumentId, SyntaxTree>(); foreach (var document in project.Documents) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); builder.Add(document.Id, tree); } return builder.ToImmutable(); } private async Task<bool> ContainsAnyFix(Document document, DiagnosticData diagnostic, bool considerSuppressionFixes, CancellationToken cancellationToken) { ImmutableArray<CodeFixProvider> workspaceFixers = ImmutableArray<CodeFixProvider>.Empty; List<CodeFixProvider> projectFixers = null; Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> fixerMap; bool hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out fixerMap) && fixerMap.Value.TryGetValue(diagnostic.Id, out workspaceFixers); var hasAnyProjectFixer = GetProjectFixers(document.Project).TryGetValue(diagnostic.Id, out projectFixers); Lazy<ISuppressionFixProvider> lazySuppressionProvider = null; var hasSuppressionFixer = considerSuppressionFixes && _suppressionProvidersMap.TryGetValue(document.Project.Language, out lazySuppressionProvider) && lazySuppressionProvider.Value != null; if (!hasAnySharedFixer && !hasAnyProjectFixer && !hasSuppressionFixer) { return false; } var allFixers = ImmutableArray<CodeFixProvider>.Empty; if (hasAnySharedFixer) { allFixers = workspaceFixers; } if (hasAnyProjectFixer) { allFixers = allFixers.AddRange(projectFixers); } var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var dx = diagnostic.ToDiagnostic(tree); if (hasSuppressionFixer && lazySuppressionProvider.Value.CanBeSuppressed(dx)) { return true; } var fixes = new List<CodeFix>(); var context = new CodeFixContext(document, dx, // TODO: Can we share code between similar lambdas that we pass to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs? (a, d) => { // Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from. lock (fixes) { fixes.Add(new CodeFix(a, d)); } }, verifyArguments: false, cancellationToken: cancellationToken); var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>(); // we do have fixer. now let's see whether it actually can fix it foreach (var fixer in allFixers) { await extensionManager.PerformActionAsync(fixer, () => fixer.RegisterCodeFixesAsync(context) ?? SpecializedTasks.EmptyTask).ConfigureAwait(false); if (!fixes.Any()) { continue; } return true; } return false; } private static readonly Func<DiagnosticId, List<CodeFixProvider>> s_createList = _ => new List<CodeFixProvider>(); private ImmutableArray<DiagnosticId> GetFixableDiagnosticIds(CodeFixProvider fixer, IExtensionManager extensionManager) { // If we are passed a null extension manager it means we do not have access to a document so there is nothing to // show the user. In this case we will log any exceptions that occur, but the user will not see them. if (extensionManager != null) { return extensionManager.PerformFunction( fixer, () => ImmutableInterlocked.GetOrAdd(ref _fixerToFixableIdsMap, fixer, f => f.FixableDiagnosticIds), defaultValue: ImmutableArray<DiagnosticId>.Empty); } try { return ImmutableInterlocked.GetOrAdd(ref _fixerToFixableIdsMap, fixer, f => f.FixableDiagnosticIds); } catch (OperationCanceledException) { throw; } catch (Exception e) { foreach (var logger in _errorLoggers) { logger.Value.LogException(fixer, e); } return ImmutableArray<DiagnosticId>.Empty; } } private ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>> GetFixerPerLanguageMap( Dictionary<LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>> fixersPerLanguage, IExtensionManager extensionManager) { var fixerMap = ImmutableDictionary.Create<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>>(); foreach (var languageKindAndFixers in fixersPerLanguage) { var lazyMap = new Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>(() => { var mutableMap = new Dictionary<DiagnosticId, List<CodeFixProvider>>(); foreach (var fixer in languageKindAndFixers.Value) { foreach (var id in this.GetFixableDiagnosticIds(fixer.Value, extensionManager)) { if (string.IsNullOrWhiteSpace(id)) { continue; } var list = mutableMap.GetOrAdd(id, s_createList); list.Add(fixer.Value); } } var immutableMap = ImmutableDictionary.CreateBuilder<DiagnosticId, ImmutableArray<CodeFixProvider>>(); foreach (var diagnosticIdAndFixers in mutableMap) { immutableMap.Add(diagnosticIdAndFixers.Key, diagnosticIdAndFixers.Value.AsImmutableOrEmpty()); } return immutableMap.ToImmutable(); }, isThreadSafe: true); fixerMap = fixerMap.Add(languageKindAndFixers.Key, lazyMap); } return fixerMap; } private static ImmutableDictionary<LanguageKind, Lazy<ISuppressionFixProvider>> GetSuppressionProvidersPerLanguageMap( Dictionary<LanguageKind, List<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>>> suppressionProvidersPerLanguage) { var suppressionFixerMap = ImmutableDictionary.Create<LanguageKind, Lazy<ISuppressionFixProvider>>(); foreach (var languageKindAndFixers in suppressionProvidersPerLanguage) { var suppressionFixerLazyMap = new Lazy<ISuppressionFixProvider>(() => languageKindAndFixers.Value.SingleOrDefault().Value); suppressionFixerMap = suppressionFixerMap.Add(languageKindAndFixers.Key, suppressionFixerLazyMap); } return suppressionFixerMap; } private static ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>> GetFixerPriorityPerLanguageMap( Dictionary<LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>> fixersPerLanguage) { var languageMap = ImmutableDictionary.CreateBuilder<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>>(); foreach (var languageAndFixers in fixersPerLanguage) { var lazyMap = new Lazy<ImmutableDictionary<CodeFixProvider, int>>(() => { var priorityMap = ImmutableDictionary.CreateBuilder<CodeFixProvider, int>(); var fixers = ExtensionOrderer.Order(languageAndFixers.Value); for (var i = 0; i < fixers.Count; i++) { priorityMap.Add(fixers[i].Value, i); } return priorityMap.ToImmutable(); }, isThreadSafe: true); languageMap.Add(languageAndFixers.Key, lazyMap); } return languageMap.ToImmutable(); } private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> GetProjectFixers(Project project) { return _projectFixersMap.GetValue(project.AnalyzerReferences, pId => ComputeProjectFixers(project)); } private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> ComputeProjectFixers(Project project) { var extensionManager = project.Solution.Workspace.Services.GetService<IExtensionManager>(); ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Builder builder = null; foreach (var reference in project.AnalyzerReferences) { var projectCodeFixerProvider = _analyzerReferenceToFixersMap.GetValue(reference, _createProjectCodeFixProvider); foreach (var fixer in projectCodeFixerProvider.GetFixers(project.Language)) { var fixableIds = this.GetFixableDiagnosticIds(fixer, extensionManager); foreach (var id in fixableIds) { if (string.IsNullOrWhiteSpace(id)) { continue; } builder = builder ?? ImmutableDictionary.CreateBuilder<DiagnosticId, List<CodeFixProvider>>(); var list = builder.GetOrAdd(id, s_createList); list.Add(fixer); } } } if (builder == null) { return ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Empty; } return builder.ToImmutable(); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ViolationCache.cs" company="Microsoft"> // (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary> // MSAGL class for caching of most-violated constraints for Projection Solver. // </summary> // -------------------------------------------------------------------------------------------------------------------- // Remove this from project build and uncomment here to selectively enable per-class. //#define VERBOSE #if VERIFY || VERBOSE // Ensure accuracy. #define VERIFY_MIN_CONSTRAINT #else //#define VERIFY_MIN_CONSTRAINT #endif // VERIFY || VERBOSE //#define Inline_Violation using System; using System.Diagnostics; namespace Microsoft.Msagl.Core.ProjectionSolver { // The ViolationCache stores the top N maximum violations initially, allowing // a reduction in the number of times we do a full search of all constraints. // (It is not guaranteed to retain the max-N violations strictly after the first // block is processed following a cache fill, but the approximation is sufficient // to provide significant benefit). internal struct ViolationCache { // Minimize blocks/variables traversed when Project() calls GetMaxViolatedConstraint by repeating the // search over the block just modified on the next pass and then checking for out-of-block constraints // that are higher. This repeats until constraints is empty and then it's refilled and repeats. // There is a shutoff in Project() for this when we get to a point where it's faster to go with the // "enumerate all constraints" approach. // Note: A priority queue might be better for larger s_cMaxConstraints, but we use a small value, // and we need arbitrary-index removal/replacement also. Profiling is not showing the cache to be // taking noticeable time at 20 items and we don't seem to gain cache hits past that. private Constraint[] constraints; // Must be >= 2 for Insert() dblNextLowVio logic; > 20 seems to yield little increase in hits. internal const int MaxConstraints = 20; // Number of constraints actually present. private int numConstraints; // The lowest violation in the cache. internal double LowViolation { get; private set; } internal bool IsFull { get { return this.numConstraints == MaxConstraints; } } internal void Clear() { LowViolation = 0.0; this.numConstraints = 0; if (null == this.constraints) { this.constraints = new Constraint[MaxConstraints]; } } internal bool FilterBlock(Block blockToFilter) { // Note: The cache does not try to retain strict accordance with highest violation. // Doing so lowers the hit rate, probably because if LastModifiedBlock has enough variables, // then it has enough high violations to flush all other blocks out of the cache, and // thus the next call to FilterBlock removes all for the current block (which per the following // paragraph results in calling SearchAllConstraints). As it turns out, it doesn't // really matter what order we process the constraints in, other than the perf benefit of // doing the largest violations first, so using the max violation in LastModifiedBlock in this // situation seems to be good enough to win the tradeoff. // // If it becomes necessary to maintain strict "cache always contains the highest violations" // compliance, then we would have to return false if the filtering removed all elements of // the cache, because then we wouldn't know if there were any non-blockToFilter-related constraints // with a higher violation (currently we return true in that case because it is good enough to know // there is a good chance that this is true). Also, SearchViolationCache would need a verification in // at least VERIFY mode to verify there are no higher violations in allConstraints. // Iterate in reverse to remove constraints belonging to LastModifiedBlock. // Note: Enumerators and .Where are not used because they are much slower. LowViolation = double.MaxValue; bool fRet = this.numConstraints > 0; for (int ii = this.numConstraints - 1; ii >= 0; --ii) { var constraint = this.constraints[ii]; // Also remove any constraint that may have been activated by MergeBlocks or marked unsatisfiable // by Block.Expand. if ((constraint.Left.Block == blockToFilter) || (constraint.Right.Block == blockToFilter) || constraint.IsActive || constraint.IsUnsatisfiable) { // If there are any items after this one, then they are ones we want to keep, // so swap in the last one in the array before decrementing the count. if (ii < (this.numConstraints - 1)) { this.constraints[ii] = this.constraints[this.numConstraints - 1]; } --this.numConstraints; } else { #if Inline_Violation double violation = constraint.Violation; // Inline_Violation #else // Inline_Violation double violation = (constraint.Left.ActualPos * constraint.Left.Scale) + constraint.Gap - (constraint.Right.ActualPos * constraint.Right.Scale); Debug.Assert(constraint.Violation == violation, "LeftConstraints: constraint.Violation must == violation"); #endif // Inline_Violation if (violation < LowViolation) { LowViolation = violation; } } } if (0 == this.numConstraints) { LowViolation = 0.0; } return fRet; } // Find the highest constraint with a greater violation than targetViolation. internal Constraint FindIfGreater(double targetViolation) { Constraint maxViolatedConstraint = null; for (int ii = 0; ii < this.numConstraints; ++ii) { var constraint = this.constraints[ii]; #if Inline_Violation double violation = constraint.Violation; // Inline_Violation #else // Inline_Violation double violation = (constraint.Left.ActualPos * constraint.Left.Scale) + constraint.Gap - (constraint.Right.ActualPos * constraint.Right.Scale); Debug.Assert(constraint.Violation == violation, "constraint.Violation must == violation"); #endif // Inline_Violation if (violation > targetViolation) { targetViolation = violation; maxViolatedConstraint = constraint; } } // Remains null if none was found. return maxViolatedConstraint; } internal void Insert(Constraint constraintToInsert, double insertViolation) { // This should be checked by the caller (instead of here, for perf reasons). Debug.Assert(constraintToInsert.Violation > LowViolation, "constraintToInsert.Violation must be > LowViolation"); Debug.Assert(constraintToInsert.Violation == insertViolation, "constraintToInsert.Violation must == insertViolation"); int indexOfLowestViolation = 0; double lowViolation = insertViolation; double nextLowViolation = insertViolation; for (int ii = 0; ii < this.numConstraints; ++ii) { var constraint = this.constraints[ii]; #if Inline_Violation double cacheViolation = constraint.Violation; // Inline_Violation #else // Inline_Violation double cacheViolation = (constraint.Left.ActualPos * constraint.Left.Scale) + constraint.Gap - (constraint.Right.ActualPos * constraint.Right.Scale); Debug.Assert(constraint.Violation == cacheViolation, "constraint.Violation must == cacheViolation"); #endif // Inline_Violation if (cacheViolation < lowViolation) { // If we don't replace an existing block pair, then we'll replace the lowest // violation in the cache, so will need to know the next-lowest violation. nextLowViolation = lowViolation; indexOfLowestViolation = ii; lowViolation = cacheViolation; } else if (cacheViolation < nextLowViolation) { nextLowViolation = cacheViolation; } } // endfor each constraint // If the cache isn't full yet, add the new one, else replace the lowest violation in the list. if (!IsFull) { // Add to the cache. this.constraints[this.numConstraints++] = constraintToInsert; if (IsFull) { this.LowViolation = lowViolation; } } else { // Replace in the cache. this.constraints[indexOfLowestViolation] = constraintToInsert; this.LowViolation = nextLowViolation; } #if VERIFY_MIN_CONSTRAINT VerifyMinConstraint(); #endif // VERIFY_MIN_CONSTRAINT } // end Insert() #if VERIFY_MIN_CONSTRAINT // Dev-time routine only. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] private void VerifyMinConstraint() { // Verify the above optimized lowest-violation tracking. This also catches // any bad indexing that leaves a null or stale constraint. if (MaxConstraints == this.numConstraints) { double lowViolation = this.constraints[0].Violation; for (int ii = 1; ii < this.numConstraints; ++ii) { if ((null == this.constraints[ii]) || (this.constraints[ii].Violation <= 0.0)) { throw new InvalidOperationException( #if DEBUG "NULL or stale constraint found in cache" #endif // DEBUG ); } if (this.constraints[ii].Violation < lowViolation) { lowViolation = this.constraints[ii].Violation; } } if (lowViolation != this.LowViolation) { throw new InvalidOperationException( #if DEBUG "Mismatched Low Violation" #endif // DEBUG ); } } } #endif // VERIFY_MIN_CONSTRAINT #if CACHE_STATS internal struct CacheStats { internal int NumberOfCalls; internal int NumberOfHits; internal void Clear() { this.NumberOfCalls = 0; this.NumberOfHits = 0; } internal void Print() { Console.WriteLine("GetMaxViolationCalls = {0}; ViolationCacheHits = {1}", this.NumberOfCalls, this.NumberOfHits); } } // end struct CacheStats #endif // CACHE_STATS } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Threading; using System.Linq; using Crestron; using Crestron.Logos.SplusLibrary; using Crestron.Logos.SplusObjects; using Crestron.SimplSharp; namespace UserModule_BSS_SOUNDWEB_LONDON_MATRIX_ROUTER { public class UserModuleClass_BSS_SOUNDWEB_LONDON_MATRIX_ROUTER : SplusObject { static CCriticalSection g_criticalSection = new CCriticalSection(); Crestron.Logos.SplusObjects.DigitalInput SUBSCRIBE__DOLLAR__; Crestron.Logos.SplusObjects.DigitalInput UNSUBSCRIBE__DOLLAR__; InOutArray<Crestron.Logos.SplusObjects.DigitalInput> OUTPUT_MUTE__DOLLAR__; Crestron.Logos.SplusObjects.AnalogInput INPUT__DOLLAR__; Crestron.Logos.SplusObjects.BufferInput RX__DOLLAR__; InOutArray<Crestron.Logos.SplusObjects.DigitalOutput> OUTPUT_MUTE_FB__DOLLAR__; Crestron.Logos.SplusObjects.StringOutput TX__DOLLAR__; StringParameter OBJECTID__DOLLAR__; UShortParameter IMAXOUTPUT; object OUTPUT_MUTE__DOLLAR___OnPush_0 ( Object __EventInfo__ ) { Crestron.Logos.SplusObjects.SignalEventArgs __SignalEventArg__ = (Crestron.Logos.SplusObjects.SignalEventArgs)__EventInfo__; try { SplusExecutionContext __context__ = SplusThreadStartCode(__SignalEventArg__); __context__.SourceCodeLine = 162; _SplusNVRAM.STATEVARONOFF = (ushort) ( Functions.GetLastModifiedArrayIndex( __SignalEventArg__ ) ) ; __context__.SourceCodeLine = 163; _SplusNVRAM.STATEVARONOFF = (ushort) ( (((_SplusNVRAM.STATEVARONOFF - 1) * 128) + (_SplusNVRAM.INPUT - 1)) ) ; __context__.SourceCodeLine = 164; MakeString ( TX__DOLLAR__ , "\u0088\u0000\u0000\u0003{0}{1}{2}\u0000\u0000\u0000\u0001\u0003\u0003\u0003\u0003\u0003", OBJECTID__DOLLAR__ , Functions.Chr ( (int) ( Functions.High( (ushort) _SplusNVRAM.STATEVARONOFF ) ) ) , Functions.Chr ( (int) ( Functions.Low( (ushort) _SplusNVRAM.STATEVARONOFF ) ) ) ) ; __context__.SourceCodeLine = 166; if ( Functions.TestForTrue ( ( _SplusNVRAM.SUBSCRIBE) ) ) { __context__.SourceCodeLine = 168; MakeString ( TX__DOLLAR__ , "\u0089\u0000\u0000\u0003{0}{1}{2}\u0000\u0000\u0000\u0000\u0003\u0003\u0003\u0003\u0003", OBJECTID__DOLLAR__ , Functions.Chr ( (int) ( Functions.High( (ushort) _SplusNVRAM.STATEVARONOFF ) ) ) , Functions.Chr ( (int) ( Functions.Low( (ushort) _SplusNVRAM.STATEVARONOFF ) ) ) ) ; __context__.SourceCodeLine = 169; Functions.ProcessLogic ( ) ; } } catch(Exception e) { ObjectCatchHandler(e); } finally { ObjectFinallyHandler( __SignalEventArg__ ); } return this; } object OUTPUT_MUTE__DOLLAR___OnRelease_1 ( Object __EventInfo__ ) { Crestron.Logos.SplusObjects.SignalEventArgs __SignalEventArg__ = (Crestron.Logos.SplusObjects.SignalEventArgs)__EventInfo__; try { SplusExecutionContext __context__ = SplusThreadStartCode(__SignalEventArg__); __context__.SourceCodeLine = 174; _SplusNVRAM.STATEVARONOFF = (ushort) ( Functions.GetLastModifiedArrayIndex( __SignalEventArg__ ) ) ; __context__.SourceCodeLine = 175; _SplusNVRAM.STATEVARONOFF = (ushort) ( (((_SplusNVRAM.STATEVARONOFF - 1) * 128) + (_SplusNVRAM.INPUT - 1)) ) ; __context__.SourceCodeLine = 176; MakeString ( TX__DOLLAR__ , "\u0088\u0000\u0000\u0003{0}{1}{2}\u0000\u0000\u0000\u0000\u0003\u0003\u0003\u0003\u0003", OBJECTID__DOLLAR__ , Functions.Chr ( (int) ( Functions.High( (ushort) _SplusNVRAM.STATEVARONOFF ) ) ) , Functions.Chr ( (int) ( Functions.Low( (ushort) _SplusNVRAM.STATEVARONOFF ) ) ) ) ; __context__.SourceCodeLine = 178; if ( Functions.TestForTrue ( ( _SplusNVRAM.SUBSCRIBE) ) ) { __context__.SourceCodeLine = 180; MakeString ( TX__DOLLAR__ , "\u0089\u0000\u0000\u0003{0}{1}{2}\u0000\u0000\u0000\u0000\u0003\u0003\u0003\u0003\u0003", OBJECTID__DOLLAR__ , Functions.Chr ( (int) ( Functions.High( (ushort) _SplusNVRAM.STATEVARONOFF ) ) ) , Functions.Chr ( (int) ( Functions.Low( (ushort) _SplusNVRAM.STATEVARONOFF ) ) ) ) ; __context__.SourceCodeLine = 181; Functions.ProcessLogic ( ) ; } } catch(Exception e) { ObjectCatchHandler(e); } finally { ObjectFinallyHandler( __SignalEventArg__ ); } return this; } object SUBSCRIBE__DOLLAR___OnPush_2 ( Object __EventInfo__ ) { Crestron.Logos.SplusObjects.SignalEventArgs __SignalEventArg__ = (Crestron.Logos.SplusObjects.SignalEventArgs)__EventInfo__; try { SplusExecutionContext __context__ = SplusThreadStartCode(__SignalEventArg__); __context__.SourceCodeLine = 188; CreateWait ( "__SPLS_TMPVAR__WAITLABEL_0__" , 20 , __SPLS_TMPVAR__WAITLABEL_0___Callback ) ; } catch(Exception e) { ObjectCatchHandler(e); } finally { ObjectFinallyHandler( __SignalEventArg__ ); } return this; } public void __SPLS_TMPVAR__WAITLABEL_0___CallbackFn( object stateInfo ) { try { Wait __LocalWait__ = (Wait)stateInfo; SplusExecutionContext __context__ = SplusThreadStartCode(__LocalWait__); __LocalWait__.RemoveFromList(); __context__.SourceCodeLine = 190; if ( Functions.TestForTrue ( ( _SplusNVRAM.XOKSUBSCRIBE) ) ) { __context__.SourceCodeLine = 192; _SplusNVRAM.XOKSUBSCRIBE = (ushort) ( 0 ) ; __context__.SourceCodeLine = 193; _SplusNVRAM.STATEVARSUB = (ushort) ( (_SplusNVRAM.INPUT - 1) ) ; __context__.SourceCodeLine = 194; ushort __FN_FORSTART_VAL__1 = (ushort) ( 1 ) ; ushort __FN_FOREND_VAL__1 = (ushort)IMAXOUTPUT .Value; int __FN_FORSTEP_VAL__1 = (int)1; for ( _SplusNVRAM.I = __FN_FORSTART_VAL__1; (__FN_FORSTEP_VAL__1 > 0) ? ( (_SplusNVRAM.I >= __FN_FORSTART_VAL__1) && (_SplusNVRAM.I <= __FN_FOREND_VAL__1) ) : ( (_SplusNVRAM.I <= __FN_FORSTART_VAL__1) && (_SplusNVRAM.I >= __FN_FOREND_VAL__1) ) ; _SplusNVRAM.I += (ushort)__FN_FORSTEP_VAL__1) { __context__.SourceCodeLine = 196; _SplusNVRAM.STATEVARSUB = (ushort) ( ((_SplusNVRAM.INPUT - 1) + ((_SplusNVRAM.I - 1) * 128)) ) ; __context__.SourceCodeLine = 197; MakeString ( TX__DOLLAR__ , "\u0089\u0000\u0000\u0003{0}{1}{2}\u0000\u0000\u0000\u0000\u0003\u0003\u0003\u0003\u0003", OBJECTID__DOLLAR__ , Functions.Chr ( (int) ( Functions.High( (ushort) _SplusNVRAM.STATEVARSUB ) ) ) , Functions.Chr ( (int) ( Functions.Low( (ushort) _SplusNVRAM.STATEVARSUB ) ) ) ) ; __context__.SourceCodeLine = 198; Functions.ProcessLogic ( ) ; __context__.SourceCodeLine = 199; Functions.Delay ( (int) ( 5 ) ) ; __context__.SourceCodeLine = 194; } __context__.SourceCodeLine = 202; _SplusNVRAM.SUBSCRIBE = (ushort) ( 1 ) ; __context__.SourceCodeLine = 203; _SplusNVRAM.XOKSUBSCRIBE = (ushort) ( 1 ) ; } } catch(Exception e) { ObjectCatchHandler(e); } finally { ObjectFinallyHandler(); } } object UNSUBSCRIBE__DOLLAR___OnPush_3 ( Object __EventInfo__ ) { Crestron.Logos.SplusObjects.SignalEventArgs __SignalEventArg__ = (Crestron.Logos.SplusObjects.SignalEventArgs)__EventInfo__; try { SplusExecutionContext __context__ = SplusThreadStartCode(__SignalEventArg__); __context__.SourceCodeLine = 212; if ( Functions.TestForTrue ( ( _SplusNVRAM.XOKSUBSCRIBE) ) ) { __context__.SourceCodeLine = 214; _SplusNVRAM.XOKSUBSCRIBE = (ushort) ( 0 ) ; __context__.SourceCodeLine = 215; _SplusNVRAM.STATEVARSUB = (ushort) ( (_SplusNVRAM.INPUT - 1) ) ; __context__.SourceCodeLine = 216; ushort __FN_FORSTART_VAL__1 = (ushort) ( 1 ) ; ushort __FN_FOREND_VAL__1 = (ushort)IMAXOUTPUT .Value; int __FN_FORSTEP_VAL__1 = (int)1; for ( _SplusNVRAM.I = __FN_FORSTART_VAL__1; (__FN_FORSTEP_VAL__1 > 0) ? ( (_SplusNVRAM.I >= __FN_FORSTART_VAL__1) && (_SplusNVRAM.I <= __FN_FOREND_VAL__1) ) : ( (_SplusNVRAM.I <= __FN_FORSTART_VAL__1) && (_SplusNVRAM.I >= __FN_FOREND_VAL__1) ) ; _SplusNVRAM.I += (ushort)__FN_FORSTEP_VAL__1) { __context__.SourceCodeLine = 218; _SplusNVRAM.STATEVARSUB = (ushort) ( ((_SplusNVRAM.INPUT - 1) + ((_SplusNVRAM.I - 1) * 128)) ) ; __context__.SourceCodeLine = 219; MakeString ( TX__DOLLAR__ , "\u008A\u0000\u0000\u0003{0}{1}{2}\u0000\u0000\u0000\u0000\u0003\u0003\u0003\u0003\u0003", OBJECTID__DOLLAR__ , Functions.Chr ( (int) ( Functions.High( (ushort) _SplusNVRAM.STATEVARSUB ) ) ) , Functions.Chr ( (int) ( Functions.Low( (ushort) _SplusNVRAM.STATEVARSUB ) ) ) ) ; __context__.SourceCodeLine = 220; Functions.ProcessLogic ( ) ; __context__.SourceCodeLine = 221; Functions.Delay ( (int) ( 5 ) ) ; __context__.SourceCodeLine = 216; } __context__.SourceCodeLine = 224; _SplusNVRAM.SUBSCRIBE = (ushort) ( 0 ) ; __context__.SourceCodeLine = 225; _SplusNVRAM.XOKSUBSCRIBE = (ushort) ( 1 ) ; } } catch(Exception e) { ObjectCatchHandler(e); } finally { ObjectFinallyHandler( __SignalEventArg__ ); } return this; } object INPUT__DOLLAR___OnChange_4 ( Object __EventInfo__ ) { Crestron.Logos.SplusObjects.SignalEventArgs __SignalEventArg__ = (Crestron.Logos.SplusObjects.SignalEventArgs)__EventInfo__; try { SplusExecutionContext __context__ = SplusThreadStartCode(__SignalEventArg__); __context__.SourceCodeLine = 232; if ( Functions.TestForTrue ( ( Functions.BoolToInt ( INPUT__DOLLAR__ .UshortValue > 0 )) ) ) { __context__.SourceCodeLine = 233; _SplusNVRAM.INPUT = (ushort) ( INPUT__DOLLAR__ .UshortValue ) ; } else { __context__.SourceCodeLine = 236; _SplusNVRAM.INPUT = (ushort) ( 1 ) ; __context__.SourceCodeLine = 237; Print( "error input for the automixer cannot be 0. set to default of 1") ; } } catch(Exception e) { ObjectCatchHandler(e); } finally { ObjectFinallyHandler( __SignalEventArg__ ); } return this; } object RX__DOLLAR___OnChange_5 ( Object __EventInfo__ ) { Crestron.Logos.SplusObjects.SignalEventArgs __SignalEventArg__ = (Crestron.Logos.SplusObjects.SignalEventArgs)__EventInfo__; try { SplusExecutionContext __context__ = SplusThreadStartCode(__SignalEventArg__); __context__.SourceCodeLine = 251; if ( Functions.TestForTrue ( ( _SplusNVRAM.XOK) ) ) { __context__.SourceCodeLine = 253; _SplusNVRAM.XOK = (ushort) ( 0 ) ; __context__.SourceCodeLine = 254; while ( Functions.TestForTrue ( ( Functions.Length( RX__DOLLAR__ )) ) ) { __context__.SourceCodeLine = 256; if ( Functions.TestForTrue ( ( Functions.Find( "\u0003\u0003\u0003\u0003\u0003" , RX__DOLLAR__ )) ) ) { __context__.SourceCodeLine = 258; _SplusNVRAM.TEMPSTRING .UpdateValue ( Functions.Remove ( "\u0003\u0003\u0003\u0003\u0003" , RX__DOLLAR__ ) ) ; __context__.SourceCodeLine = 259; if ( Functions.TestForTrue ( ( Functions.BoolToInt ( (Functions.TestForTrue ( Functions.BoolToInt (Functions.Mid( _SplusNVRAM.TEMPSTRING , (int)( 6 ) , (int)( 3 ) ) == "\u0000\u0000\u0000") ) || Functions.TestForTrue ( Functions.BoolToInt (Functions.Mid( _SplusNVRAM.TEMPSTRING , (int)( 6 ) , (int)( 3 ) ) == OBJECTID__DOLLAR__ ) )) )) ) ) { __context__.SourceCodeLine = 261; _SplusNVRAM.STATEVARRECEIVE = (ushort) ( ((Byte( _SplusNVRAM.TEMPSTRING , (int)( 9 ) ) * 256) + Byte( _SplusNVRAM.TEMPSTRING , (int)( 10 ) )) ) ; __context__.SourceCodeLine = 262; if ( Functions.TestForTrue ( ( Functions.BoolToInt (Mod( _SplusNVRAM.STATEVARRECEIVE , 128 ) == (_SplusNVRAM.INPUT - 1))) ) ) { __context__.SourceCodeLine = 264; if ( Functions.TestForTrue ( ( Byte( _SplusNVRAM.TEMPSTRING , (int)( 14 ) )) ) ) { __context__.SourceCodeLine = 267; OUTPUT_MUTE_FB__DOLLAR__ [ ((_SplusNVRAM.STATEVARRECEIVE / 128) + 1)] .Value = (ushort) ( 1 ) ; } else { __context__.SourceCodeLine = 271; OUTPUT_MUTE_FB__DOLLAR__ [ ((_SplusNVRAM.STATEVARRECEIVE / 128) + 1)] .Value = (ushort) ( 0 ) ; } } } __context__.SourceCodeLine = 276; Functions.ClearBuffer ( _SplusNVRAM.TEMPSTRING ) ; } __context__.SourceCodeLine = 254; } __context__.SourceCodeLine = 280; _SplusNVRAM.XOK = (ushort) ( 1 ) ; } } catch(Exception e) { ObjectCatchHandler(e); } finally { ObjectFinallyHandler( __SignalEventArg__ ); } return this; } public override object FunctionMain ( object __obj__ ) { try { SplusExecutionContext __context__ = SplusFunctionMainStartCode(); __context__.SourceCodeLine = 300; _SplusNVRAM.XOK = (ushort) ( 1 ) ; __context__.SourceCodeLine = 301; _SplusNVRAM.SUBSCRIBE = (ushort) ( 0 ) ; __context__.SourceCodeLine = 302; _SplusNVRAM.XOKSUBSCRIBE = (ushort) ( 1 ) ; } catch(Exception e) { ObjectCatchHandler(e); } finally { ObjectFinallyHandler(); } return __obj__; } public override void LogosSplusInitialize() { SocketInfo __socketinfo__ = new SocketInfo( 1, this ); InitialParametersClass.ResolveHostName = __socketinfo__.ResolveHostName; _SplusNVRAM = new SplusNVRAM( this ); _SplusNVRAM.TEMPSTRING = new CrestronString( Crestron.Logos.SplusObjects.CrestronStringEncoding.eEncodingASCII, 40, this ); SUBSCRIBE__DOLLAR__ = new Crestron.Logos.SplusObjects.DigitalInput( SUBSCRIBE__DOLLAR____DigitalInput__, this ); m_DigitalInputList.Add( SUBSCRIBE__DOLLAR____DigitalInput__, SUBSCRIBE__DOLLAR__ ); UNSUBSCRIBE__DOLLAR__ = new Crestron.Logos.SplusObjects.DigitalInput( UNSUBSCRIBE__DOLLAR____DigitalInput__, this ); m_DigitalInputList.Add( UNSUBSCRIBE__DOLLAR____DigitalInput__, UNSUBSCRIBE__DOLLAR__ ); OUTPUT_MUTE__DOLLAR__ = new InOutArray<DigitalInput>( 48, this ); for( uint i = 0; i < 48; i++ ) { OUTPUT_MUTE__DOLLAR__[i+1] = new Crestron.Logos.SplusObjects.DigitalInput( OUTPUT_MUTE__DOLLAR____DigitalInput__ + i, OUTPUT_MUTE__DOLLAR____DigitalInput__, this ); m_DigitalInputList.Add( OUTPUT_MUTE__DOLLAR____DigitalInput__ + i, OUTPUT_MUTE__DOLLAR__[i+1] ); } OUTPUT_MUTE_FB__DOLLAR__ = new InOutArray<DigitalOutput>( 48, this ); for( uint i = 0; i < 48; i++ ) { OUTPUT_MUTE_FB__DOLLAR__[i+1] = new Crestron.Logos.SplusObjects.DigitalOutput( OUTPUT_MUTE_FB__DOLLAR____DigitalOutput__ + i, this ); m_DigitalOutputList.Add( OUTPUT_MUTE_FB__DOLLAR____DigitalOutput__ + i, OUTPUT_MUTE_FB__DOLLAR__[i+1] ); } INPUT__DOLLAR__ = new Crestron.Logos.SplusObjects.AnalogInput( INPUT__DOLLAR____AnalogSerialInput__, this ); m_AnalogInputList.Add( INPUT__DOLLAR____AnalogSerialInput__, INPUT__DOLLAR__ ); TX__DOLLAR__ = new Crestron.Logos.SplusObjects.StringOutput( TX__DOLLAR____AnalogSerialOutput__, this ); m_StringOutputList.Add( TX__DOLLAR____AnalogSerialOutput__, TX__DOLLAR__ ); RX__DOLLAR__ = new Crestron.Logos.SplusObjects.BufferInput( RX__DOLLAR____AnalogSerialInput__, 400, this ); m_StringInputList.Add( RX__DOLLAR____AnalogSerialInput__, RX__DOLLAR__ ); IMAXOUTPUT = new UShortParameter( IMAXOUTPUT__Parameter__, this ); m_ParameterList.Add( IMAXOUTPUT__Parameter__, IMAXOUTPUT ); OBJECTID__DOLLAR__ = new StringParameter( OBJECTID__DOLLAR____Parameter__, this ); m_ParameterList.Add( OBJECTID__DOLLAR____Parameter__, OBJECTID__DOLLAR__ ); __SPLS_TMPVAR__WAITLABEL_0___Callback = new WaitFunction( __SPLS_TMPVAR__WAITLABEL_0___CallbackFn ); for( uint i = 0; i < 48; i++ ) OUTPUT_MUTE__DOLLAR__[i+1].OnDigitalPush.Add( new InputChangeHandlerWrapper( OUTPUT_MUTE__DOLLAR___OnPush_0, false ) ); for( uint i = 0; i < 48; i++ ) OUTPUT_MUTE__DOLLAR__[i+1].OnDigitalRelease.Add( new InputChangeHandlerWrapper( OUTPUT_MUTE__DOLLAR___OnRelease_1, false ) ); SUBSCRIBE__DOLLAR__.OnDigitalPush.Add( new InputChangeHandlerWrapper( SUBSCRIBE__DOLLAR___OnPush_2, false ) ); UNSUBSCRIBE__DOLLAR__.OnDigitalPush.Add( new InputChangeHandlerWrapper( UNSUBSCRIBE__DOLLAR___OnPush_3, false ) ); INPUT__DOLLAR__.OnAnalogChange.Add( new InputChangeHandlerWrapper( INPUT__DOLLAR___OnChange_4, false ) ); RX__DOLLAR__.OnSerialChange.Add( new InputChangeHandlerWrapper( RX__DOLLAR___OnChange_5, false ) ); _SplusNVRAM.PopulateCustomAttributeList( true ); NVRAM = _SplusNVRAM; } public override void LogosSimplSharpInitialize() { } public UserModuleClass_BSS_SOUNDWEB_LONDON_MATRIX_ROUTER ( string InstanceName, string ReferenceID, Crestron.Logos.SplusObjects.CrestronStringEncoding nEncodingType ) : base( InstanceName, ReferenceID, nEncodingType ) {} private WaitFunction __SPLS_TMPVAR__WAITLABEL_0___Callback; const uint SUBSCRIBE__DOLLAR____DigitalInput__ = 0; const uint UNSUBSCRIBE__DOLLAR____DigitalInput__ = 1; const uint OUTPUT_MUTE__DOLLAR____DigitalInput__ = 2; const uint INPUT__DOLLAR____AnalogSerialInput__ = 0; const uint RX__DOLLAR____AnalogSerialInput__ = 1; const uint OUTPUT_MUTE_FB__DOLLAR____DigitalOutput__ = 0; const uint TX__DOLLAR____AnalogSerialOutput__ = 0; const uint OBJECTID__DOLLAR____Parameter__ = 10; const uint IMAXOUTPUT__Parameter__ = 11; [SplusStructAttribute(-1, true, false)] public class SplusNVRAM : SplusStructureBase { public SplusNVRAM( SplusObject __caller__ ) : base( __caller__ ) {} [SplusStructAttribute(0, false, true)] public ushort I = 0; [SplusStructAttribute(1, false, true)] public ushort SUBSCRIBE = 0; [SplusStructAttribute(2, false, true)] public ushort INPUT = 0; [SplusStructAttribute(3, false, true)] public ushort XOK = 0; [SplusStructAttribute(4, false, true)] public ushort XOKSUBSCRIBE = 0; [SplusStructAttribute(5, false, true)] public CrestronString TEMPSTRING; [SplusStructAttribute(6, false, true)] public ushort STATEVARONOFF = 0; [SplusStructAttribute(7, false, true)] public ushort STATEVARSUB = 0; [SplusStructAttribute(8, false, true)] public ushort STATEVARRECEIVE = 0; [SplusStructAttribute(9, false, true)] public ushort X = 0; } SplusNVRAM _SplusNVRAM = null; public class __CEvent__ : CEvent { public __CEvent__() {} public void Close() { base.Close(); } public int Reset() { return base.Reset() ? 1 : 0; } public int Set() { return base.Set() ? 1 : 0; } public int Wait( int timeOutInMs ) { return base.Wait( timeOutInMs ) ? 1 : 0; } } public class __CMutex__ : CMutex { public __CMutex__() {} public void Close() { base.Close(); } public void ReleaseMutex() { base.ReleaseMutex(); } public int WaitForMutex() { return base.WaitForMutex() ? 1 : 0; } } public int IsNull( object obj ){ return (obj == null) ? 1 : 0; } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Controls.dll // Description: The Windows Forms user interface controls like the map, legend, toolbox, ribbon and others. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 2/12/2009 10:46:15 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Composition; using System.Drawing; using System.Windows.Forms; using DotSpatial.Controls.Header; namespace DotSpatial.Controls { /// <summary> /// A pre-configured status strip with a thread safe Progress function /// </summary> [ToolboxBitmap(typeof(SpatialStatusStrip), "SpatialStatusStrip.ico")] [PartNotDiscoverable] // Do not allow discover this class by MEF public partial class SpatialStatusStrip : StatusStrip, IStatusControl { private readonly Dictionary<StatusPanel, PanelGuiElements> _panels = new Dictionary<StatusPanel, PanelGuiElements>(); /// <summary> /// Creates a new instance of the StatusStrip which has a built in, thread safe Progress handler /// </summary> public SpatialStatusStrip() { InitializeComponent(); } /// <summary> /// Gets or sets the progress bar. By default, the first ToolStripProgressBar that is added to the tool strip. /// </summary> /// <value> /// The progress bar. /// </value> [Description("Gets or sets the progress bar. By default, the first ToolStripProgressBar that is added to the tool strip.")] public ToolStripProgressBar ProgressBar { get; set; } /// <summary> /// Gets or sets the progress label. By default, the first ToolStripStatusLabel that is added to the tool strip. /// </summary> /// <value> /// The progress label. /// </value> [Description("Gets or sets the progress label. By default, the first ToolStripStatusLabel that is added to the tool strip.")] public ToolStripStatusLabel ProgressLabel { get; set; } #region IProgressHandler Members /// <summary> /// This method is thread safe so that people calling this method don't cause a cross-thread violation /// by updating the progress indicator from a different thread /// </summary> /// <param name="key">A string message with just a description of what is happening, but no percent completion information</param> /// <param name="percent">The integer percent from 0 to 100</param> /// <param name="message">A message</param> public void Progress(string key, int percent, string message) { if (InvokeRequired) { BeginInvoke((Action<int, string>)UpdateProgress, percent, message); } else { UpdateProgress(percent, message); } } #endregion private void UpdateProgress(int percent, string message) { if (ProgressBar != null) ProgressBar.Value = percent; if (ProgressLabel != null) ProgressLabel.Text = message; Refresh(); } /// <summary> /// Raises the <see cref="E:System.Windows.Forms.ToolStrip.ItemAdded"/> event. /// </summary> /// <param name="e">A <see cref="T:System.Windows.Forms.ToolStripItemEventArgs"/> that contains the event data.</param> protected override void OnItemAdded(ToolStripItemEventArgs e) { base.OnItemAdded(e); if (ProgressBar == null) { var pb = e.Item as ToolStripProgressBar; if (pb != null) { ProgressBar = pb; } } if (ProgressLabel == null) { var sl = e.Item as ToolStripStatusLabel; if (sl != null) { ProgressLabel = sl; } } } protected override void OnItemRemoved(ToolStripItemEventArgs e) { base.OnItemRemoved(e); if (ProgressBar == e.Item) ProgressBar = null; if (ProgressLabel == e.Item) ProgressLabel = null; } #region IStatusControl implementation public void Add(StatusPanel panel) { if (panel == null) throw new ArgumentNullException("panel"); ToolStripProgressBar pb = null; var psp = panel as ProgressStatusPanel; if (psp != null) { pb = new ToolStripProgressBar { Name = GetKeyName<ToolStripProgressBar>(panel.Key), Width = 100, Alignment = ToolStripItemAlignment.Left }; Items.Add(pb); } var sl = new ToolStripStatusLabel { Name = GetKeyName<ToolStripStatusLabel>(panel.Key), Text = panel.Caption, Spring = (panel.Width == 0), TextAlign = ContentAlignment.MiddleLeft }; Items.Add(sl); _panels.Add(panel, new PanelGuiElements { Caption = sl, Progress = pb }); panel.PropertyChanged += PanelOnPropertyChanged; } private void PanelOnPropertyChanged(object sender, PropertyChangedEventArgs e) { var panel = (StatusPanel)sender; if (InvokeRequired) { BeginInvoke((Action<StatusPanel, string>)UpdatePanelGuiProps, panel, e.PropertyName); } else { UpdatePanelGuiProps(panel, e.PropertyName); } } private void UpdatePanelGuiProps(StatusPanel sender, string propertyName) { PanelGuiElements panelDesc; if (!_panels.TryGetValue(sender, out panelDesc)) return; switch (propertyName) { case "Caption": if (panelDesc.Caption != null) { panelDesc.Caption.Text = sender.Caption; } break; case "Percent": if (panelDesc.Progress != null && sender is ProgressStatusPanel) { panelDesc.Progress.Value = ((ProgressStatusPanel)sender).Percent; } break; } Refresh(); } public void Remove(StatusPanel panel) { if (panel == null) throw new ArgumentNullException("panel"); panel.PropertyChanged -= PanelOnPropertyChanged; PanelGuiElements panelDesc; if (!_panels.TryGetValue(panel, out panelDesc)) return; if (panelDesc.Caption != null) Items.Remove(panelDesc.Caption); if (panelDesc.Progress != null) Items.Remove(panelDesc.Progress); } private static string GetKeyName<T>(string key) { return typeof(T).Name + key; } #endregion internal class PanelGuiElements { public ToolStripStatusLabel Caption { get; set; } public ToolStripProgressBar Progress { get; set; } } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Storage { using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// The Storage Management Client. /// </summary> public partial class StorageManagementClient : ServiceClient<StorageManagementClient>, IStorageManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets subscription credentials which uniquely identify Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Client Api Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IStorageAccountsOperations. /// </summary> public virtual IStorageAccountsOperations StorageAccounts { get; private set; } /// <summary> /// Gets the IUsageOperations. /// </summary> public virtual IUsageOperations Usage { get; private set; } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected StorageManagementClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected StorageManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected StorageManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected StorageManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { StorageAccounts = new StorageAccountsOperations(this); Usage = new UsageOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2015-06-15"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security.AccessControl; using System.Text; namespace Microsoft.Win32 { /// <summary>Registry encapsulation. To get an instance of a RegistryKey use the Registry class's static members then call OpenSubKey.</summary> #if REGISTRY_ASSEMBLY public #else internal #endif sealed partial class RegistryKey : IDisposable { public static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(unchecked((int)0x80000000)); public static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(unchecked((int)0x80000001)); public static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(unchecked((int)0x80000002)); public static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003)); public static readonly IntPtr HKEY_PERFORMANCE_DATA = new IntPtr(unchecked((int)0x80000004)); public static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(unchecked((int)0x80000005)); /// <summary>Names of keys. This array must be in the same order as the HKEY values listed above.</summary> private static readonly string[] s_hkeyNames = new string[] { "HKEY_CLASSES_ROOT", "HKEY_CURRENT_USER", "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_PERFORMANCE_DATA", "HKEY_CURRENT_CONFIG" }; // MSDN defines the following limits for registry key names & values: // Key Name: 255 characters // Value name: 16,383 Unicode characters // Value: either 1 MB or current available memory, depending on registry format. private const int MaxKeyLength = 255; private const int MaxValueLength = 16383; private volatile SafeRegistryHandle _hkey; private volatile string _keyName; private volatile bool _remoteKey; private volatile StateFlags _state; private volatile RegistryView _regView = RegistryView.Default; /// <summary> /// Creates a RegistryKey. This key is bound to hkey, if writable is <b>false</b> then no write operations will be allowed. /// </summary> private RegistryKey(SafeRegistryHandle hkey, bool writable, RegistryView view) : this(hkey, writable, false, false, false, view) { } /// <summary> /// Creates a RegistryKey. /// This key is bound to hkey, if writable is <b>false</b> then no write operations /// will be allowed. If systemkey is set then the hkey won't be released /// when the object is GC'ed. /// The remoteKey flag when set to true indicates that we are dealing with registry entries /// on a remote machine and requires the program making these calls to have full trust. /// </summary> private RegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey, bool remoteKey, bool isPerfData, RegistryView view) { ValidateKeyView(view); _hkey = hkey; _keyName = ""; _remoteKey = remoteKey; _regView = view; if (systemkey) { _state |= StateFlags.SystemKey; } if (writable) { _state |= StateFlags.WriteAccess; } if (isPerfData) { _state |= StateFlags.PerfData; } } public void Flush() { FlushCore(); } public void Dispose() { if (_hkey != null) { if (!IsSystemKey()) { try { _hkey.Dispose(); } catch (IOException) { // we don't really care if the handle is invalid at this point } finally { _hkey = null; } } else if (IsPerfDataKey()) { ClosePerfDataKey(); } } } /// <summary>Creates a new subkey, or opens an existing one.</summary> /// <param name="subkey">Name or path to subkey to create or open.</param> /// <returns>The subkey, or <b>null</b> if the operation failed.</returns> [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")] public RegistryKey CreateSubKey(string subkey) { return CreateSubKey(subkey, IsWritable()); } public RegistryKey CreateSubKey(string subkey, bool writable) { return CreateSubKeyInternal(subkey, writable, RegistryOptions.None); } public RegistryKey CreateSubKey(string subkey, bool writable, RegistryOptions options) { return CreateSubKeyInternal(subkey, writable, options); } private RegistryKey CreateSubKeyInternal(string subkey, bool writable, RegistryOptions registryOptions) { ValidateKeyOptions(registryOptions); ValidateKeyName(subkey); EnsureWriteable(); subkey = FixupName(subkey); // Fixup multiple slashes to a single slash // only keys opened under read mode is not writable if (!_remoteKey) { RegistryKey key = InternalOpenSubKey(subkey, writable); if (key != null) { // Key already exits return key; } } return CreateSubKeyInternalCore(subkey, writable, registryOptions); } public void DeleteValue(string name, bool throwOnMissingValue) { EnsureWriteable(); DeleteValueCore(name, throwOnMissingValue); } public static RegistryKey OpenBaseKey(RegistryHive hKey, RegistryView view) { ValidateKeyView(view); return OpenBaseKeyCore(hKey, view); } /// <summary> /// Retrieves a subkey. If readonly is <b>true</b>, then the subkey is opened with /// read-only access. /// </summary> /// <returns>the Subkey requested, or <b>null</b> if the operation failed.</returns> public RegistryKey OpenSubKey(string name, bool writable) => OpenSubKey(name, GetRegistryKeyRights(writable)); public RegistryKey OpenSubKey(string name, RegistryRights rights) { ValidateKeyName(name); EnsureNotDisposed(); name = FixupName(name); // Fixup multiple slashes to a single slash return InternalOpenSubKeyCore(name, rights, throwOnPermissionFailure: true); } /// <summary> /// This required no security checks. This is to get around the Deleting SubKeys which only require /// write permission. They call OpenSubKey which required read. Now instead call this function w/o security checks /// </summary> private RegistryKey InternalOpenSubKey(string name, bool writable) { ValidateKeyName(name); EnsureNotDisposed(); return InternalOpenSubKeyCore(name, GetRegistryKeyRights(writable), throwOnPermissionFailure: false); } /// <summary>Returns a subkey with read only permissions.</summary> /// <param name="name">Name or path of subkey to open.</param> /// <returns>The Subkey requested, or <b>null</b> if the operation failed.</returns> public RegistryKey OpenSubKey(string name) { return OpenSubKey(name, false); } /// <summary>Retrieves the count of subkeys.</summary> /// <returns>A count of subkeys.</returns> public int SubKeyCount { get { return InternalSubKeyCount(); } } public RegistryView View { get { EnsureNotDisposed(); return _regView; } } public SafeRegistryHandle Handle { get { EnsureNotDisposed(); return IsSystemKey() ? SystemKeyHandle : _hkey; } } public static RegistryKey FromHandle(SafeRegistryHandle handle) { return FromHandle(handle, RegistryView.Default); } public static RegistryKey FromHandle(SafeRegistryHandle handle, RegistryView view) { if (handle == null) throw new ArgumentNullException(nameof(handle)); ValidateKeyView(view); return new RegistryKey(handle, writable: true, view: view); } private int InternalSubKeyCount() { EnsureNotDisposed(); return InternalSubKeyCountCore(); } /// <summary>Retrieves an array of strings containing all the subkey names.</summary> /// <returns>All subkey names.</returns> public string[] GetSubKeyNames() { return InternalGetSubKeyNames(); } private string[] InternalGetSubKeyNames() { int subkeys = InternalSubKeyCount(); return subkeys > 0 ? InternalGetSubKeyNamesCore(subkeys) : Array.Empty<string>(); } /// <summary>Retrieves the count of values.</summary> /// <returns>A count of values.</returns> public int ValueCount { get { EnsureNotDisposed(); return InternalValueCountCore(); } } /// <summary>Retrieves an array of strings containing all the value names.</summary> /// <returns>All value names.</returns> public string[] GetValueNames() { int values = ValueCount; return values > 0 ? GetValueNamesCore(values) : Array.Empty<string>(); } /// <summary>Retrieves the specified value. <b>null</b> is returned if the value doesn't exist</summary> /// <remarks> /// Note that <var>name</var> can be null or "", at which point the /// unnamed or default value of this Registry key is returned, if any. /// </remarks> /// <param name="name">Name of value to retrieve.</param> /// <returns>The data associated with the value.</returns> public object GetValue(string name) { return InternalGetValue(name, null, false, true); } /// <summary>Retrieves the specified value. <i>defaultValue</i> is returned if the value doesn't exist.</summary> /// <remarks> /// Note that <var>name</var> can be null or "", at which point the /// unnamed or default value of this Registry key is returned, if any. /// The default values for RegistryKeys are OS-dependent. NT doesn't /// have them by default, but they can exist and be of any type. On /// Win95, the default value is always an empty key of type REG_SZ. /// Win98 supports default values of any type, but defaults to REG_SZ. /// </remarks> /// <param name="name">Name of value to retrieve.</param> /// <param name="defaultValue">Value to return if <i>name</i> doesn't exist.</param> /// <returns>The data associated with the value.</returns> public object GetValue(string name, object defaultValue) { return InternalGetValue(name, defaultValue, false, true); } public object GetValue(string name, object defaultValue, RegistryValueOptions options) { if (options < RegistryValueOptions.None || options > RegistryValueOptions.DoNotExpandEnvironmentNames) { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)options), nameof(options)); } bool doNotExpand = (options == RegistryValueOptions.DoNotExpandEnvironmentNames); return InternalGetValue(name, defaultValue, doNotExpand, checkSecurity: true); } public object InternalGetValue(string name, object defaultValue, bool doNotExpand, bool checkSecurity) { if (checkSecurity) { EnsureNotDisposed(); } // Name can be null! It's the most common use of RegQueryValueEx return InternalGetValueCore(name, defaultValue, doNotExpand); } public RegistryValueKind GetValueKind(string name) { EnsureNotDisposed(); return GetValueKindCore(name); } public string Name { get { EnsureNotDisposed(); return _keyName; } } //The actual api is SetValue(string name, object value, RegistryValueKind valueKind) but we only need to set Strings // so this is a cut-down version that supports on that. internal void SetValue(string name, string value) { if (value == null) throw new ArgumentNullException(nameof(value)); if (name != null && name.Length > MaxValueLength) throw new ArgumentException(SR.Arg_RegValStrLenBug, nameof(name)); EnsureWriteable(); SetValueCore(name, value); } /// <summary>Retrieves a string representation of this key.</summary> /// <returns>A string representing the key.</returns> public override string ToString() { EnsureNotDisposed(); return _keyName; } private static string FixupName(string name) { Debug.Assert(name != null, "[FixupName]name!=null"); if (name.IndexOf('\\') == -1) { return name; } StringBuilder sb = new StringBuilder(name); FixupPath(sb); int temp = sb.Length - 1; if (temp >= 0 && sb[temp] == '\\') // Remove trailing slash { sb.Length = temp; } return sb.ToString(); } private static void FixupPath(StringBuilder path) { Debug.Assert(path != null); int length = path.Length; bool fixup = false; char markerChar = (char)0xFFFF; int i = 1; while (i < length - 1) { if (path[i] == '\\') { i++; while (i < length && path[i] == '\\') { path[i] = markerChar; i++; fixup = true; } } i++; } if (fixup) { i = 0; int j = 0; while (i < length) { if (path[i] == markerChar) { i++; continue; } path[j] = path[i]; i++; j++; } path.Length += j - i; } } private void EnsureNotDisposed() { } private void EnsureWriteable() { } private static void ValidateKeyName(string name) { } private static void ValidateKeyOptions(RegistryOptions options) { } private static void ValidateKeyView(RegistryView view) { } private static RegistryRights GetRegistryKeyRights(bool isWritable) { return isWritable ? RegistryRights.ReadKey | RegistryRights.WriteKey : RegistryRights.ReadKey; } /// <summary>Retrieves the current state of the dirty property.</summary> /// <remarks>A key is marked as dirty if any operation has occurred that modifies the contents of the key.</remarks> /// <returns><b>true</b> if the key has been modified.</returns> private bool IsDirty() => (_state & StateFlags.Dirty) != 0; private bool IsSystemKey() => (_state & StateFlags.SystemKey) != 0; private bool IsWritable() => (_state & StateFlags.WriteAccess) != 0; private bool IsPerfDataKey() => (_state & StateFlags.PerfData) != 0; private void SetDirty() => _state |= StateFlags.Dirty; [Flags] private enum StateFlags { /// <summary>Dirty indicates that we have munged data that should be potentially written to disk.</summary> Dirty = 0x0001, /// <summary>SystemKey indicates that this is a "SYSTEMKEY" and shouldn't be "opened" or "closed".</summary> SystemKey = 0x0002, /// <summary>Access</summary> WriteAccess = 0x0004, /// <summary>Indicates if this key is for HKEY_PERFORMANCE_DATA</summary> PerfData = 0x0008 } /** * Closes this key, flushes it to disk if the contents have been modified. */ public void Close() { Dispose(true); } private void Dispose(bool disposing) { if (_hkey != null) { if (!IsSystemKey()) { try { _hkey.Dispose(); } catch (IOException) { // we don't really care if the handle is invalid at this point } finally { _hkey = null; } } else if (disposing && IsPerfDataKey()) { // System keys should never be closed. However, we want to call RegCloseKey // on HKEY_PERFORMANCE_DATA when called from PerformanceCounter.CloseSharedResources // (i.e. when disposing is true) so that we release the PERFLIB cache and cause it // to be refreshed (by re-reading the registry) when accessed subsequently. // This is the only way we can see the just installed perf counter. // NOTE: since HKEY_PERFORMANCE_DATA is process wide, there is inherent race condition in closing // the key asynchronously. While Vista is smart enough to rebuild the PERFLIB resources // in this situation the down level OSes are not. We have a small window between // the dispose below and usage elsewhere (other threads). This is By Design. // This is less of an issue when OS > NT5 (i.e Vista & higher), we can close the perfkey // (to release & refresh PERFLIB resources) and the OS will rebuild PERFLIB as necessary. Interop.mincore.RegCloseKey(RegistryKey.HKEY_PERFORMANCE_DATA); } } } internal static RegistryKey GetBaseKey(IntPtr hKey) { return GetBaseKey(hKey, RegistryView.Default); } internal static RegistryKey GetBaseKey(IntPtr hKey, RegistryView view) { int index = ((int)hKey) & 0x0FFFFFFF; bool isPerf = hKey == HKEY_PERFORMANCE_DATA; // only mark the SafeHandle as ownsHandle if the key is HKEY_PERFORMANCE_DATA. SafeRegistryHandle srh = new SafeRegistryHandle(hKey, isPerf); RegistryKey key = new RegistryKey(srh, true, true, false, isPerf, view); key._keyName = s_hkeyNames[index]; return key; } } }
/* * 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.Linq.Impl { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Apache.Ignite.Core; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Remotion.Linq; using Remotion.Linq.Clauses.StreamedData; using Remotion.Linq.Parsing.Structure; using Remotion.Linq.Utilities; /// <summary> /// Query provider for fields queries (projections). /// </summary> internal class CacheFieldsQueryProvider : IQueryProvider { /** */ private static readonly MethodInfo GenericCreateQueryMethod = typeof (CacheFieldsQueryProvider).GetMethods().Single(m => m.Name == "CreateQuery" && m.IsGenericMethod); /** */ private readonly IQueryParser _parser; /** */ private readonly CacheFieldsQueryExecutor _executor; /** */ private readonly IIgnite _ignite; /** */ private readonly CacheConfiguration _cacheConfiguration; /** */ private readonly string _tableName; /// <summary> /// Initializes a new instance of the <see cref="CacheFieldsQueryProvider"/> class. /// </summary> public CacheFieldsQueryProvider(IQueryParser queryParser, CacheFieldsQueryExecutor executor, IIgnite ignite, CacheConfiguration cacheConfiguration, string tableName, Type cacheValueType) { Debug.Assert(queryParser != null); Debug.Assert(executor != null); Debug.Assert(ignite != null); Debug.Assert(cacheConfiguration != null); Debug.Assert(cacheValueType != null); _parser = queryParser; _executor = executor; _ignite = ignite; _cacheConfiguration = cacheConfiguration; if (tableName != null) { _tableName = tableName; ValidateTableName(); } else _tableName = InferTableName(cacheValueType); } /// <summary> /// Gets the ignite. /// </summary> public IIgnite Ignite { get { return _ignite; } } /// <summary> /// Gets the name of the cache. /// </summary> public CacheConfiguration CacheConfiguration { get { return _cacheConfiguration; } } /// <summary> /// Gets the name of the table. /// </summary> public string TableName { get { return _tableName; } } /// <summary> /// Gets the executor. /// </summary> public CacheFieldsQueryExecutor Executor { get { return _executor; } } /// <summary> /// Generates the query model. /// </summary> public QueryModel GenerateQueryModel(Expression expression) { return _parser.GetParsedQuery(expression); } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0")] public IQueryable CreateQuery(Expression expression) { Debug.Assert(expression != null); var elementType = GetItemTypeOfClosedGenericIEnumerable(expression.Type, "expression"); // Slow, but this method is never called during normal LINQ usage with generics return (IQueryable) GenericCreateQueryMethod.MakeGenericMethod(elementType) .Invoke(this, new object[] {expression}); } /** <inheritdoc /> */ public IQueryable<T> CreateQuery<T>(Expression expression) { return new CacheFieldsQueryable<T>(this, expression); } /** <inheritdoc /> */ object IQueryProvider.Execute(Expression expression) { return Execute(expression); } /** <inheritdoc /> */ public TResult Execute<TResult>(Expression expression) { return (TResult) Execute(expression).Value; } /// <summary> /// Executes the specified expression. /// </summary> private IStreamedData Execute(Expression expression) { var model = GenerateQueryModel(expression); return model.Execute(_executor); } /// <summary> /// Validates the name of the table. /// </summary> private void ValidateTableName() { var validTableNames = GetValidTableNames().Select(x => EscapeTableName(x)).ToArray(); if (!validTableNames.Contains(_tableName, StringComparer.OrdinalIgnoreCase)) { throw new CacheException(string.Format("Invalid table name specified for CacheQueryable: '{0}'; " + "configured table names are: {1}", _tableName, validTableNames.Aggregate((x, y) => x + ", " + y))); } } /// <summary> /// Gets the valid table names for current cache. /// </summary> private string[] GetValidTableNames() { // Split on '.' to throw away Java type namespace var validTableNames = _cacheConfiguration.QueryEntities == null ? null : _cacheConfiguration.QueryEntities.Select(GetTableName).ToArray(); if (validTableNames == null || !validTableNames.Any()) throw new CacheException(string.Format("Queries are not configured for cache '{0}'", _cacheConfiguration.Name ?? "null")); return validTableNames; } /// <summary> /// Gets the name of the SQL table. /// </summary> private static string GetTableName(QueryEntity e) { return e.TableName ?? e.ValueTypeName; } /// <summary> /// Infers the name of the table from cache configuration. /// </summary> /// <param name="cacheValueType"></param> private string InferTableName(Type cacheValueType) { var validTableNames = GetValidTableNames(); if (validTableNames.Length == 1) { return EscapeTableName(validTableNames[0]); } var valueTypeName = cacheValueType.FullName; if (validTableNames.Contains(valueTypeName, StringComparer.OrdinalIgnoreCase)) { return EscapeTableName(valueTypeName); } throw new CacheException(string.Format("Table name cannot be inferred for cache '{0}', " + "please use AsCacheQueryable overload with tableName parameter. " + "Valid table names: {1}", _cacheConfiguration.Name ?? "null", validTableNames.Aggregate((x, y) => x + ", " + y))); } /// <summary> /// Escapes the name of the table: strips namespace and nested class qualifiers. /// </summary> private static string EscapeTableName(string valueTypeName) { var nsIndex = Math.Max(valueTypeName.LastIndexOf('.'), valueTypeName.LastIndexOf('+')); return nsIndex > 0 ? valueTypeName.Substring(nsIndex + 1) : valueTypeName; } /// <summary> /// Gets the item type of closed generic i enumerable. /// </summary> private static Type GetItemTypeOfClosedGenericIEnumerable(Type enumerableType, string argumentName) { Type itemType; if (!ItemTypeReflectionUtility.TryGetItemTypeOfClosedGenericIEnumerable(enumerableType, out itemType)) { var message = string.Format("Expected a closed generic type implementing IEnumerable<T>, " + "but found '{0}'.", enumerableType); throw new ArgumentException(message, argumentName); } return itemType; } } }
using System; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Events; using Umbraco.Core.Models; using umbraco; using umbraco.cms.businesslogic.web; using Umbraco.Core.Persistence.Repositories; namespace Umbraco.Web.Cache { /// <summary> /// Extension methods for <see cref="DistributedCache"/> /// </summary> internal static class DistributedCacheExtensions { #region Public access public static void RefreshPublicAccess(this DistributedCache dc) { dc.RefreshAll(DistributedCache.PublicAccessCacheRefresherGuid); } #endregion #region Application tree cache public static void RefreshAllApplicationTreeCache(this DistributedCache dc) { dc.RefreshAll(DistributedCache.ApplicationTreeCacheRefresherGuid); } #endregion #region Application cache public static void RefreshAllApplicationCache(this DistributedCache dc) { dc.RefreshAll(DistributedCache.ApplicationCacheRefresherGuid); } #endregion #region User type cache public static void RemoveUserTypeCache(this DistributedCache dc, int userTypeId) { dc.Remove(DistributedCache.UserTypeCacheRefresherGuid, userTypeId); } public static void RefreshUserTypeCache(this DistributedCache dc, int userTypeId) { dc.Refresh(DistributedCache.UserTypeCacheRefresherGuid, userTypeId); } public static void RefreshAllUserTypeCache(this DistributedCache dc) { dc.RefreshAll(DistributedCache.UserTypeCacheRefresherGuid); } #endregion #region User cache public static void RemoveUserCache(this DistributedCache dc, int userId) { dc.Remove(DistributedCache.UserCacheRefresherGuid, userId); } public static void RefreshUserCache(this DistributedCache dc, int userId) { dc.Refresh(DistributedCache.UserCacheRefresherGuid, userId); } public static void RefreshAllUserCache(this DistributedCache dc) { dc.RefreshAll(DistributedCache.UserCacheRefresherGuid); } #endregion #region User permissions cache public static void RemoveUserPermissionsCache(this DistributedCache dc, int userId) { dc.Remove(DistributedCache.UserPermissionsCacheRefresherGuid, userId); } public static void RefreshUserPermissionsCache(this DistributedCache dc, int userId) { dc.Refresh(DistributedCache.UserPermissionsCacheRefresherGuid, userId); } public static void RefreshAllUserPermissionsCache(this DistributedCache dc) { dc.RefreshAll(DistributedCache.UserPermissionsCacheRefresherGuid); } #endregion #region Template cache public static void RefreshTemplateCache(this DistributedCache dc, int templateId) { dc.Refresh(DistributedCache.TemplateRefresherGuid, templateId); } public static void RemoveTemplateCache(this DistributedCache dc, int templateId) { dc.Remove(DistributedCache.TemplateRefresherGuid, templateId); } #endregion #region Dictionary cache public static void RefreshDictionaryCache(this DistributedCache dc, int dictionaryItemId) { dc.Refresh(DistributedCache.DictionaryCacheRefresherGuid, dictionaryItemId); } public static void RemoveDictionaryCache(this DistributedCache dc, int dictionaryItemId) { dc.Remove(DistributedCache.DictionaryCacheRefresherGuid, dictionaryItemId); } #endregion #region Data type cache public static void RefreshDataTypeCache(this DistributedCache dc, IDataTypeDefinition dataType) { if (dataType == null) return; dc.RefreshByJson(DistributedCache.DataTypeCacheRefresherGuid, DataTypeCacheRefresher.SerializeToJsonPayload(dataType)); } public static void RemoveDataTypeCache(this DistributedCache dc, IDataTypeDefinition dataType) { if (dataType == null) return; dc.RefreshByJson(DistributedCache.DataTypeCacheRefresherGuid, DataTypeCacheRefresher.SerializeToJsonPayload(dataType)); } #endregion #region Page cache public static void RefreshAllPageCache(this DistributedCache dc) { dc.RefreshAll(DistributedCache.PageCacheRefresherGuid); } public static void RefreshPageCache(this DistributedCache dc, int documentId) { dc.Refresh(DistributedCache.PageCacheRefresherGuid, documentId); } public static void RefreshPageCache(this DistributedCache dc, params IContent[] content) { dc.Refresh(DistributedCache.PageCacheRefresherGuid, x => x.Id, content); } public static void RemovePageCache(this DistributedCache dc, params IContent[] content) { dc.Remove(DistributedCache.PageCacheRefresherGuid, x => x.Id, content); } public static void RemovePageCache(this DistributedCache dc, int documentId) { dc.Remove(DistributedCache.PageCacheRefresherGuid, documentId); } public static void RefreshUnpublishedPageCache(this DistributedCache dc, params IContent[] content) { dc.Refresh(DistributedCache.UnpublishedPageCacheRefresherGuid, x => x.Id, content); } public static void RemoveUnpublishedPageCache(this DistributedCache dc, params IContent[] content) { dc.Remove(DistributedCache.UnpublishedPageCacheRefresherGuid, x => x.Id, content); } public static void RemoveUnpublishedCachePermanently(this DistributedCache dc, params int[] contentIds) { dc.RefreshByJson(DistributedCache.UnpublishedPageCacheRefresherGuid, UnpublishedPageCacheRefresher.SerializeToJsonPayloadForPermanentDeletion(contentIds)); } #endregion #region Member cache public static void RefreshMemberCache(this DistributedCache dc, params IMember[] members) { dc.Refresh(DistributedCache.MemberCacheRefresherGuid, x => x.Id, members); } public static void RemoveMemberCache(this DistributedCache dc, params IMember[] members) { dc.Remove(DistributedCache.MemberCacheRefresherGuid, x => x.Id, members); } [Obsolete("Use the RefreshMemberCache with strongly typed IMember objects instead")] public static void RefreshMemberCache(this DistributedCache dc, int memberId) { dc.Refresh(DistributedCache.MemberCacheRefresherGuid, memberId); } [Obsolete("Use the RemoveMemberCache with strongly typed IMember objects instead")] public static void RemoveMemberCache(this DistributedCache dc, int memberId) { dc.Remove(DistributedCache.MemberCacheRefresherGuid, memberId); } #endregion #region Member group cache public static void RefreshMemberGroupCache(this DistributedCache dc, int memberGroupId) { dc.Refresh(DistributedCache.MemberGroupCacheRefresherGuid, memberGroupId); } public static void RemoveMemberGroupCache(this DistributedCache dc, int memberGroupId) { dc.Remove(DistributedCache.MemberGroupCacheRefresherGuid, memberGroupId); } #endregion #region Media Cache public static void RefreshMediaCache(this DistributedCache dc, params IMedia[] media) { dc.RefreshByJson(DistributedCache.MediaCacheRefresherGuid, MediaCacheRefresher.SerializeToJsonPayload(MediaCacheRefresher.OperationType.Saved, media)); } public static void RefreshMediaCacheAfterMoving(this DistributedCache dc, params MoveEventInfo<IMedia>[] media) { dc.RefreshByJson(DistributedCache.MediaCacheRefresherGuid, MediaCacheRefresher.SerializeToJsonPayloadForMoving(MediaCacheRefresher.OperationType.Saved, media)); } // clearing by Id will never work for load balanced scenarios for media since we require a Path // to clear all of the cache but the media item will be removed before the other servers can // look it up. Only here for legacy purposes. [Obsolete("Ensure to clear with other RemoveMediaCache overload")] public static void RemoveMediaCache(this DistributedCache dc, int mediaId) { dc.Remove(new Guid(DistributedCache.MediaCacheRefresherId), mediaId); } public static void RemoveMediaCacheAfterRecycling(this DistributedCache dc, params MoveEventInfo<IMedia>[] media) { dc.RefreshByJson(DistributedCache.MediaCacheRefresherGuid, MediaCacheRefresher.SerializeToJsonPayloadForMoving(MediaCacheRefresher.OperationType.Trashed, media)); } public static void RemoveMediaCachePermanently(this DistributedCache dc, params int[] mediaIds) { dc.RefreshByJson(DistributedCache.MediaCacheRefresherGuid, MediaCacheRefresher.SerializeToJsonPayloadForPermanentDeletion(mediaIds)); } #endregion #region Macro Cache public static void ClearAllMacroCacheOnCurrentServer(this DistributedCache dc) { var macroRefresher = CacheRefreshersResolver.Current.GetById(DistributedCache.MacroCacheRefresherGuid); macroRefresher.RefreshAll(); } public static void RefreshMacroCache(this DistributedCache dc, IMacro macro) { if (macro == null) return; dc.RefreshByJson(DistributedCache.MacroCacheRefresherGuid, MacroCacheRefresher.SerializeToJsonPayload(macro)); } public static void RemoveMacroCache(this DistributedCache dc, IMacro macro) { if (macro == null) return; dc.RefreshByJson(DistributedCache.MacroCacheRefresherGuid, MacroCacheRefresher.SerializeToJsonPayload(macro)); } public static void RefreshMacroCache(this DistributedCache dc, global::umbraco.cms.businesslogic.macro.Macro macro) { if (macro == null) return; dc.RefreshByJson(DistributedCache.MacroCacheRefresherGuid, MacroCacheRefresher.SerializeToJsonPayload(macro)); } public static void RemoveMacroCache(this DistributedCache dc, global::umbraco.cms.businesslogic.macro.Macro macro) { if (macro == null) return; dc.RefreshByJson(DistributedCache.MacroCacheRefresherGuid, MacroCacheRefresher.SerializeToJsonPayload(macro)); } public static void RemoveMacroCache(this DistributedCache dc, macro macro) { if (macro == null || macro.Model == null) return; dc.RefreshByJson(DistributedCache.MacroCacheRefresherGuid, MacroCacheRefresher.SerializeToJsonPayload(macro)); } #endregion #region Document type cache public static void RefreshContentTypeCache(this DistributedCache dc, IContentType contentType) { if (contentType == null) return; dc.RefreshByJson(DistributedCache.ContentTypeCacheRefresherGuid, ContentTypeCacheRefresher.SerializeToJsonPayload(false, contentType)); } public static void RemoveContentTypeCache(this DistributedCache dc, IContentType contentType) { if (contentType == null) return; dc.RefreshByJson(DistributedCache.ContentTypeCacheRefresherGuid, ContentTypeCacheRefresher.SerializeToJsonPayload(true, contentType)); } #endregion #region Media type cache public static void RefreshMediaTypeCache(this DistributedCache dc, IMediaType mediaType) { if (mediaType == null) return; dc.RefreshByJson(DistributedCache.ContentTypeCacheRefresherGuid, ContentTypeCacheRefresher.SerializeToJsonPayload(false, mediaType)); } public static void RemoveMediaTypeCache(this DistributedCache dc, IMediaType mediaType) { if (mediaType == null) return; dc.RefreshByJson(DistributedCache.ContentTypeCacheRefresherGuid, ContentTypeCacheRefresher.SerializeToJsonPayload(true, mediaType)); } #endregion #region Media type cache public static void RefreshMemberTypeCache(this DistributedCache dc, IMemberType memberType) { if (memberType == null) return; dc.RefreshByJson(DistributedCache.ContentTypeCacheRefresherGuid, ContentTypeCacheRefresher.SerializeToJsonPayload(false, memberType)); } public static void RemoveMemberTypeCache(this DistributedCache dc, IMemberType memberType) { if (memberType == null) return; dc.RefreshByJson(DistributedCache.ContentTypeCacheRefresherGuid, ContentTypeCacheRefresher.SerializeToJsonPayload(true, memberType)); } #endregion #region Stylesheet Cache public static void RefreshStylesheetPropertyCache(this DistributedCache dc, global::umbraco.cms.businesslogic.web.StylesheetProperty styleSheetProperty) { if (styleSheetProperty == null) return; dc.Refresh(DistributedCache.StylesheetPropertyCacheRefresherGuid, styleSheetProperty.Id); } public static void RemoveStylesheetPropertyCache(this DistributedCache dc, global::umbraco.cms.businesslogic.web.StylesheetProperty styleSheetProperty) { if (styleSheetProperty == null) return; dc.Remove(DistributedCache.StylesheetPropertyCacheRefresherGuid, styleSheetProperty.Id); } public static void RefreshStylesheetCache(this DistributedCache dc, StyleSheet styleSheet) { if (styleSheet == null) return; dc.Refresh(DistributedCache.StylesheetCacheRefresherGuid, styleSheet.Id); } public static void RemoveStylesheetCache(this DistributedCache dc, StyleSheet styleSheet) { if (styleSheet == null) return; dc.Remove(DistributedCache.StylesheetCacheRefresherGuid, styleSheet.Id); } public static void RefreshStylesheetCache(this DistributedCache dc, Umbraco.Core.Models.Stylesheet styleSheet) { if (styleSheet == null) return; dc.Refresh(DistributedCache.StylesheetCacheRefresherGuid, styleSheet.Id); } public static void RemoveStylesheetCache(this DistributedCache dc, Umbraco.Core.Models.Stylesheet styleSheet) { if (styleSheet == null) return; dc.Remove(DistributedCache.StylesheetCacheRefresherGuid, styleSheet.Id); } #endregion #region Domain Cache public static void RefreshDomainCache(this DistributedCache dc, IDomain domain) { if (domain == null) return; dc.Refresh(DistributedCache.DomainCacheRefresherGuid, domain.Id); } public static void RemoveDomainCache(this DistributedCache dc, IDomain domain) { if (domain == null) return; dc.Remove(DistributedCache.DomainCacheRefresherGuid, domain.Id); } public static void ClearDomainCacheOnCurrentServer(this DistributedCache dc) { var domainRefresher = CacheRefreshersResolver.Current.GetById(DistributedCache.DomainCacheRefresherGuid); domainRefresher.RefreshAll(); } #endregion #region Language Cache public static void RefreshLanguageCache(this DistributedCache dc, ILanguage language) { if (language == null) return; dc.Refresh(DistributedCache.LanguageCacheRefresherGuid, language.Id); } public static void RemoveLanguageCache(this DistributedCache dc, ILanguage language) { if (language == null) return; dc.Remove(DistributedCache.LanguageCacheRefresherGuid, language.Id); } public static void RefreshLanguageCache(this DistributedCache dc, global::umbraco.cms.businesslogic.language.Language language) { if (language == null) return; dc.Refresh(DistributedCache.LanguageCacheRefresherGuid, language.id); } public static void RemoveLanguageCache(this DistributedCache dc, global::umbraco.cms.businesslogic.language.Language language) { if (language == null) return; dc.Remove(DistributedCache.LanguageCacheRefresherGuid, language.id); } #endregion #region Xslt Cache public static void ClearXsltCacheOnCurrentServer(this DistributedCache dc) { if (UmbracoConfig.For.UmbracoSettings().Content.UmbracoLibraryCacheDuration <= 0) return; ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheObjectTypes("MS.Internal.Xml.XPath.XPathSelectionIterator"); } #endregion #region Relation type cache public static void RefreshRelationTypeCache(this DistributedCache dc, int id) { dc.Refresh(DistributedCache.RelationTypeCacheRefresherGuid, id); } public static void RemoveRelationTypeCache(this DistributedCache dc, int id) { dc.Remove(DistributedCache.RelationTypeCacheRefresherGuid, id); } #endregion } }
#region Apache Notice /***************************************************************************** * $Header: $ * $Revision: $ * $Date: $ * * iBATIS.NET Data Mapper * Copyright (C) 2004 - Gilles Bayon * * * 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.Data; using System.Xml; using System.Xml.Serialization; using IBatisNet.Common.Utilities.Objects; using IBatisNet.DataMapper.Configuration.Serializers; using IBatisNet.DataMapper.Scope; using IBatisNet.DataMapper.TypeHandlers; #endregion namespace IBatisNet.DataMapper.Configuration.ParameterMapping { /// <summary> /// Summary description for ParameterMap. /// </summary> [Serializable] [XmlRoot("parameterMap", Namespace="http://ibatis.apache.org/mapping")] public class ParameterMap { /// <summary> /// Token for xml path to parameter elements. /// </summary> private const string XML_PARAMATER = "parameter"; #region private [NonSerialized] private string _id = string.Empty; [NonSerialized] // Properties list private ArrayList _properties = new ArrayList(); // Same list as _properties but without doubled (Test UpdateAccountViaParameterMap2) [NonSerialized] private ArrayList _propertiesList = new ArrayList(); //(property Name, property) [NonSerialized] private Hashtable _propertiesMap = new Hashtable(); // Corrected ?? Support Request 1043181, move to HashTable [NonSerialized] private string _extendMap = string.Empty; [NonSerialized] private bool _usePositionalParameters =false; #endregion #region Properties /// <summary> /// Identifier used to identify the ParameterMap amongst the others. /// </summary> [XmlAttribute("id")] public string Id { get { return _id; } set { _id = value; } } /// <summary> /// The collection of ParameterProperty /// </summary> [XmlIgnore] public ArrayList Properties { get { // if (_usePositionalParameters) //obdc/oledb // { // return _properties; // } // else // { // return _propertiesList; // } return _properties; } } /// <summary> /// /// </summary> [XmlIgnore] public ArrayList PropertiesList { get { return _propertiesList; } } /// <summary> /// Extend Parametermap attribute /// </summary> /// <remarks>The id of a ParameterMap</remarks> [XmlAttribute("extends")] public string ExtendMap { get { return _extendMap; } set { _extendMap = value; } } #endregion #region Constructor (s) / Destructor /// <summary> /// Do not use direclty, only for serialization. /// </summary> public ParameterMap() {} /// <summary> /// Default constructor /// </summary> /// <param name="usePositionalParameters"></param> public ParameterMap(bool usePositionalParameters) { _usePositionalParameters = usePositionalParameters; } #endregion #region Methods /// <summary> /// Get the ParameterProperty at index. /// </summary> /// <param name="index">Index</param> /// <returns>A ParameterProperty</returns> public ParameterProperty GetProperty(int index) { if (_usePositionalParameters) //obdc/oledb { return (ParameterProperty)_properties[index]; } else { return (ParameterProperty)_propertiesList[index]; } //return (ParameterProperty)_properties[index]; } /// <summary> /// Get a ParameterProperty by his name. /// </summary> /// <param name="name">The name of the ParameterProperty</param> /// <returns>A ParameterProperty</returns> public ParameterProperty GetProperty(string name) { return (ParameterProperty)_propertiesMap[name]; } /// <summary> /// Add a ParameterProperty to the ParameterProperty list. /// </summary> /// <param name="property"></param> public void AddParameterProperty(ParameterProperty property) { // These mappings will replace any mappings that this map // had for any of the keys currently in the specified map. _propertiesMap[property.PropertyName] = property; _properties.Add( property ); if (_propertiesList.Contains(property) == false) { _propertiesList.Add( property ); } } /// <summary> /// Insert a ParameterProperty ine the ParameterProperty list at the specified index.. /// </summary> /// <param name="index"> /// The zero-based index at which ParameterProperty should be inserted. /// </param> /// <param name="property">The ParameterProperty to insert. </param> public void InsertParameterProperty(int index, ParameterProperty property) { // These mappings will replace any mappings that this map // had for any of the keys currently in the specified map. _propertiesMap[property.PropertyName] = property; _properties.Insert( index, property ); if (_propertiesList.Contains(property) == false) { _propertiesList.Insert( index, property ); } } /// <summary> /// Retrieve the index for array property /// </summary> /// <param name="propertyName"></param> /// <returns></returns> public int GetParameterIndex(string propertyName) { int idx = -1; //idx = (Integer) parameterMappingIndex.get(propertyName); idx = Convert.ToInt32(propertyName.Replace("[","").Replace("]","")); return idx; } /// <summary> /// Get all Parameter Property Name /// </summary> /// <returns>A string array</returns> public string[] GetPropertyNameArray() { string[] propertyNameArray = new string[_propertiesMap.Count]; IEnumerator myEnumerator = _propertiesList.GetEnumerator(); int index =0; while ( myEnumerator.MoveNext() ) { propertyNameArray[index] = ((ParameterProperty)myEnumerator.Current).PropertyName; index++; } return (propertyNameArray); } /// <summary> /// Set parameter value, replace the null value if any. /// </summary> /// <param name="mapping"></param> /// <param name="dataParameter"></param> /// <param name="parameterValue"></param> public void SetParameter(ParameterProperty mapping, IDataParameter dataParameter, object parameterValue) { object value = parameterValue; ITypeHandler typeHandler = mapping.TypeHandler; // "The primitive types are Boolean, Byte, SByte, Int16, UInt16, Int32, // UInt32, Int64, UInt64, Char, Double, and Single." if (parameterValue.GetType() != typeof(string) && parameterValue.GetType() != typeof(Guid) && parameterValue.GetType() != typeof(Decimal) && parameterValue.GetType() != typeof(DateTime) && !parameterValue.GetType().IsPrimitive) { value = ObjectProbe.GetPropertyValue(value, mapping.PropertyName); // This code is obsolete // if we realy need it we must put it in the SetParameter method // of theByteArrayTypeHandler // if (value != null && value.GetType() == typeof(byte[])) // { // MemoryStream stream = new MemoryStream((byte[])value); // // value = stream.ToArray(); // } } // Apply Null Value if (mapping.HasNullValue) { if (typeHandler.Equals(value, mapping.NullValue)) { value = null; } } // Set Parameter if (value != null) { typeHandler.SetParameter(dataParameter, value, mapping.DbType); } else if(typeHandler is CustomTypeHandler) { typeHandler.SetParameter(dataParameter, value, mapping.DbType); } else { // When sending a null parameter value to the server, // the user must specify DBNull, not null. dataParameter.Value = DBNull.Value; } } #region Configuration /// <summary> /// Initialize the parameter properties child. /// </summary> /// <param name="configScope"></param> public void Initialize(ConfigurationScope configScope) { _usePositionalParameters = configScope.DataSource.Provider.UsePositionalParameters; GetProperties( configScope ); } /// <summary> /// Get the parameter properties child for the xmlNode parameter. /// </summary> /// <param name="configScope"></param> private void GetProperties(ConfigurationScope configScope) { ParameterProperty property = null; foreach ( XmlNode parameterNode in configScope.NodeContext.SelectNodes(DomSqlMapBuilder.ApplyMappingNamespacePrefix(XML_PARAMATER), configScope.XmlNamespaceManager) ) { property = ParameterPropertyDeSerializer.Deserialize(parameterNode, configScope); AddParameterProperty(property); } } #endregion #endregion } }
//============================================================================= // System : Sandcastle Help File Builder // File : FindAndReplaceWindow.cs // Author : Eric Woodruff ([email protected]) // Updated : 10/10/2008 // Note : Copyright 2008, Eric Woodruff, All rights reserved // Compiler: Microsoft Visual C# // // This file contains the form used to handle search and replace in the text // editor windows. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://SHFB.CodePlex.com. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.8.0.0 10/09/2008 EFW Created the code //============================================================================= using System; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Windows.Forms; using System.Web; using System.Xml; using System.Xml.Xsl; using SandcastleBuilder.Gui.Properties; using SandcastleBuilder.Utils; using WeifenLuo.WinFormsUI.Docking; namespace SandcastleBuilder.Gui.ContentEditors { /// <summary> /// This form is used to handle search and replace in the text editor /// windows. /// </summary> /// <remarks>This is rather crude but it works. It's the best I could /// do after poking around in the editor code. It will do for the time /// being even if it isn't the most efficient way of doing it.</remarks> public partial class FindAndReplaceWindow : BaseContentEditor { #region Constructor //===================================================================== /// <summary> /// Constructor /// </summary> public FindAndReplaceWindow() { InitializeComponent(); } #endregion #region Properties //===================================================================== /// <summary> /// This is used to get or set the find text /// </summary> public string FindText { get { return txtFindText.Text; } set { txtFindText.Text = value; } } /// <summary> /// This is used to get or set the replacement text /// </summary> public string ReplaceWith { get { return txtReplaceWith.Text; } set { txtReplaceWith.Text = value; } } /// <summary> /// This is used to get or set whether the search is case-sensitive /// </summary> public bool CaseSensitive { get { return chkCaseSensitive.Checked; } set { chkCaseSensitive.Checked = value; } } #endregion #region Helper methods //===================================================================== /// <summary> /// Get the active document window /// </summary> /// <returns>The active topic editor window or null if not found</returns> private TopicEditorWindow FindActiveDocumentWindow() { TopicEditorWindow topicWindow = this.DockPanel.ActiveDocument as TopicEditorWindow; if(topicWindow == null) foreach(IDockContent content in this.DockPanel.Documents) { topicWindow = content as TopicEditorWindow; if(topicWindow != null) break; } return topicWindow; } /// <summary> /// This is used to show or hide the Replace controls /// </summary> /// <param name="show">True to show them, false to hide them</param> /// <returns>The prior state of the controls (false for hidden, /// true for visible).</returns> public bool ShowReplaceControls(bool show) { bool priorState = lblReplaceWith.Visible; lblReplaceWith.Visible = txtReplaceWith.Visible = btnReplace.Visible = btnReplaceAll.Visible = show; txtFindText.Focus(); txtFindText.SelectAll(); return priorState; } #endregion #region Event handlers //===================================================================== /// <summary> /// Find the selected text /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void btnFind_Click(object sender, EventArgs e) { TopicEditorWindow topicWindow = this.FindActiveDocumentWindow(); epErrors.Clear(); this.FindActiveDocumentWindow(); if(txtFindText.Text.Length == 0) { epErrors.SetError(txtFindText, "Enter some text to find"); return; } if(topicWindow != null) if(!topicWindow.FindText(txtFindText.Text, chkCaseSensitive.Checked)) MessageBox.Show("The specified text was not found", Constants.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } /// <summary> /// Find and replace the next occurrence of the search text /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void btnReplace_Click(object sender, EventArgs e) { TopicEditorWindow topicWindow = this.FindActiveDocumentWindow(); epErrors.Clear(); this.FindActiveDocumentWindow(); if(txtFindText.Text.Length == 0) { epErrors.SetError(txtFindText, "Enter some text to find"); return; } if(topicWindow != null) if(!topicWindow.ReplaceText(txtFindText.Text, txtReplaceWith.Text, chkCaseSensitive.Checked)) MessageBox.Show("The specified text was not found", Constants.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } /// <summary> /// Find and replace all occurrences of the search text /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void btnReplaceAll_Click(object sender, EventArgs e) { TopicEditorWindow topicWindow = this.FindActiveDocumentWindow(); epErrors.Clear(); this.FindActiveDocumentWindow(); if(txtFindText.Text.Length == 0) { epErrors.SetError(txtFindText, "Enter some text to find"); return; } if(topicWindow != null) if(!topicWindow.ReplaceAll(txtFindText.Text, txtReplaceWith.Text, chkCaseSensitive.Checked)) MessageBox.Show("The specified text was not found", Constants.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } #endregion } }
using Signum.Utilities.Reflection; using Signum.Engine.Maps; using System.IO; using Npgsql; using System.Data.Common; using Microsoft.Data.SqlClient; using Microsoft.Data.SqlClient.Server; namespace Signum.Engine; public class FieldReader { readonly DbDataReader reader; readonly TypeCode[] typeCodes; private const TypeCode tcGuid = (TypeCode)20; private const TypeCode tcTimeSpan = (TypeCode)21; private const TypeCode tcDateTimeOffset = (TypeCode)22; private const TypeCode tcDateOnly = (TypeCode)24; public int? LastOrdinal; public string? LastMethodName; TypeCode GetTypeCode(int ordinal) { Type type = reader.GetFieldType(ordinal); TypeCode tc = Type.GetTypeCode(type); if (tc == TypeCode.Object) { if (type == typeof(Guid)) tc = tcGuid; if (type == typeof(TimeSpan)) tc = tcTimeSpan; if (type == typeof(DateTimeOffset)) tc = tcDateTimeOffset; if (type == typeof(DateOnly)) tc = tcDateOnly; } return tc; } bool isPostgres; public FieldReader(DbDataReader reader) { this.isPostgres = Schema.Current.Settings.IsPostgres; this.reader = reader; this.typeCodes = new TypeCode[reader.FieldCount]; for (int i = 0; i < typeCodes.Length; i++) typeCodes[i] = GetTypeCode(i); } public bool IsNull(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(IsNull); return reader.IsDBNull(ordinal); } public string? GetString(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetString); if (reader.IsDBNull(ordinal)) { return null; } return typeCodes[ordinal] switch { TypeCode.Byte => reader.GetByte(ordinal).ToString(), TypeCode.Int16 => reader.GetInt16(ordinal).ToString(), TypeCode.Int32 => reader.GetInt32(ordinal).ToString(), TypeCode.Int64 => reader.GetInt64(ordinal).ToString(), TypeCode.Double => reader.GetDouble(ordinal).ToString(), TypeCode.Single => reader.GetFloat(ordinal).ToString(), TypeCode.Decimal => reader.GetDecimal(ordinal).ToString(), TypeCode.DateTime => reader.GetDateTime(ordinal).ToString(), tcGuid => reader.GetGuid(ordinal).ToString(), TypeCode.String => reader.GetString(ordinal), _ => reader.GetValue(ordinal).ToString(), }; } public byte[]? GetByteArray(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetByteArray); if (reader.IsDBNull(ordinal)) { return null; } return (byte[])reader.GetValue(ordinal); } public bool GetBoolean(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetBoolean); return typeCodes[ordinal] switch { TypeCode.Boolean => reader.GetBoolean(ordinal), TypeCode.Byte => reader.GetByte(ordinal) != 0, TypeCode.Int16 => reader.GetInt16(ordinal) != 0, TypeCode.Int32 => reader.GetInt32(ordinal) != 0, TypeCode.Int64 => reader.GetInt64(ordinal) != 0, TypeCode.String => bool.Parse(reader.GetString(ordinal)), _ => ReflectionTools.ChangeType<bool>(reader.GetValue(ordinal)), }; } public bool? GetNullableBoolean(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetNullableBoolean); if (reader.IsDBNull(ordinal)) { return null; } return GetBoolean(ordinal); } public Byte GetByte(int ordinal) { LastOrdinal = ordinal; return typeCodes[ordinal] switch { TypeCode.Byte => reader.GetByte(ordinal), TypeCode.Int16 => (Byte)reader.GetInt16(ordinal), TypeCode.Int32 => (Byte)reader.GetInt32(ordinal), TypeCode.Int64 => (Byte)reader.GetInt64(ordinal), TypeCode.Double => (Byte)reader.GetDouble(ordinal), TypeCode.Single => (Byte)reader.GetFloat(ordinal), TypeCode.Decimal => (Byte)reader.GetDecimal(ordinal), _ => ReflectionTools.ChangeType<Byte>(reader.GetValue(ordinal)), }; } public Byte? GetNullableByte(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetNullableByte); if (reader.IsDBNull(ordinal)) { return null; } return GetByte(ordinal); } public Char GetChar(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetChar); return typeCodes[ordinal] switch { TypeCode.Byte => (Char)reader.GetByte(ordinal), TypeCode.Int16 => (Char)reader.GetInt16(ordinal), TypeCode.Int32 => (Char)reader.GetInt32(ordinal), TypeCode.Int64 => (Char)reader.GetInt64(ordinal), TypeCode.Double => (Char)reader.GetDouble(ordinal), TypeCode.Single => (Char)reader.GetFloat(ordinal), TypeCode.Decimal => (Char)reader.GetDecimal(ordinal), _ => ReflectionTools.ChangeType<Char>(reader.GetValue(ordinal)), }; } public Char? GetNullableChar(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetNullableChar); if (reader.IsDBNull(ordinal)) { return null; } return GetChar(ordinal); } public Single GetFloat(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetFloat); return typeCodes[ordinal] switch { TypeCode.Byte => (Single)reader.GetByte(ordinal), TypeCode.Int16 => (Single)reader.GetInt16(ordinal), TypeCode.Int32 => (Single)reader.GetInt32(ordinal), TypeCode.Int64 => (Single)reader.GetInt64(ordinal), TypeCode.Double => (Single)reader.GetDouble(ordinal), TypeCode.Single => reader.GetFloat(ordinal), TypeCode.Decimal => (Single)reader.GetDecimal(ordinal), _ => ReflectionTools.ChangeType<Single>(reader.GetValue(ordinal)), }; } public Single? GetNullableFloat(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetNullableFloat); if (reader.IsDBNull(ordinal)) { return null; } return GetFloat(ordinal); } public Double GetDouble(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetDouble); return typeCodes[ordinal] switch { TypeCode.Byte => (Double)reader.GetByte(ordinal), TypeCode.Int16 => (Double)reader.GetInt16(ordinal), TypeCode.Int32 => (Double)reader.GetInt32(ordinal), TypeCode.Int64 => (Double)reader.GetInt64(ordinal), TypeCode.Double => reader.GetDouble(ordinal), TypeCode.Single => (Double)reader.GetFloat(ordinal), TypeCode.Decimal => (Double)reader.GetDecimal(ordinal), _ => ReflectionTools.ChangeType<Double>(reader.GetValue(ordinal)), }; } public Double? GetNullableDouble(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetNullableDouble); if (reader.IsDBNull(ordinal)) { return null; } return GetDouble(ordinal); } public Decimal GetDecimal(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetDecimal); return typeCodes[ordinal] switch { TypeCode.Byte => (Decimal)reader.GetByte(ordinal), TypeCode.Int16 => (Decimal)reader.GetInt16(ordinal), TypeCode.Int32 => (Decimal)reader.GetInt32(ordinal), TypeCode.Int64 => (Decimal)reader.GetInt64(ordinal), TypeCode.Double => (Decimal)reader.GetDouble(ordinal), TypeCode.Single => (Decimal)reader.GetFloat(ordinal), TypeCode.Decimal => reader.GetDecimal(ordinal), _ => ReflectionTools.ChangeType<Decimal>(reader.GetValue(ordinal)), }; } public Decimal? GetNullableDecimal(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetNullableDecimal); if (reader.IsDBNull(ordinal)) { return null; } return GetDecimal(ordinal); } public Int16 GetInt16(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetInt16); return typeCodes[ordinal] switch { TypeCode.Byte => (Int16)reader.GetByte(ordinal), TypeCode.Int16 => reader.GetInt16(ordinal), TypeCode.Int32 => (Int16)reader.GetInt32(ordinal), TypeCode.Int64 => (Int16)reader.GetInt64(ordinal), TypeCode.Double => (Int16)reader.GetDouble(ordinal), TypeCode.Single => (Int16)reader.GetFloat(ordinal), TypeCode.Decimal => (Int16)reader.GetDecimal(ordinal), _ => ReflectionTools.ChangeType<Int16>(reader.GetValue(ordinal)), }; } public Int16? GetNullableInt16(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetNullableInt16); if (reader.IsDBNull(ordinal)) { return null; } return GetInt16(ordinal); } public Int32 GetInt32(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetInt32); return typeCodes[ordinal] switch { TypeCode.Byte => (Int32)reader.GetByte(ordinal), TypeCode.Int16 => (Int32)reader.GetInt16(ordinal), TypeCode.Int32 => reader.GetInt32(ordinal), TypeCode.Int64 => (Int32)reader.GetInt64(ordinal), TypeCode.Double => (Int32)reader.GetDouble(ordinal), TypeCode.Single => (Int32)reader.GetFloat(ordinal), TypeCode.Decimal => (Int32)reader.GetDecimal(ordinal), _ => ReflectionTools.ChangeType<Int32>(reader.GetValue(ordinal)), }; } public Int32? GetNullableInt32(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetNullableInt32); if (reader.IsDBNull(ordinal)) { return null; } return GetInt32(ordinal); } public Int64 GetInt64(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetInt64); return typeCodes[ordinal] switch { TypeCode.Byte => (Int64)reader.GetByte(ordinal), TypeCode.Int16 => (Int64)reader.GetInt16(ordinal), TypeCode.Int32 => (Int64)reader.GetInt32(ordinal), TypeCode.Int64 => (Int64)reader.GetInt64(ordinal), TypeCode.Double => (Int64)reader.GetDouble(ordinal), TypeCode.Single => (Int64)reader.GetFloat(ordinal), TypeCode.Decimal => (Int64)reader.GetDecimal(ordinal), _ => ReflectionTools.ChangeType<Int64>(reader.GetValue(ordinal)), }; } public Int64? GetNullableInt64(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetNullableInt64); if (reader.IsDBNull(ordinal)) { return null; } return GetInt64(ordinal); } public DateTime GetDateTime(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetDateTime); var dt = typeCodes[ordinal] switch { TypeCode.DateTime => reader.GetDateTime(ordinal), _ => ReflectionTools.ChangeType<DateTime>(reader.GetValue(ordinal)), }; if (Schema.Current.TimeZoneMode == TimeZoneMode.Utc) return new DateTime(dt.Ticks, DateTimeKind.Utc); return new DateTime(dt.Ticks, DateTimeKind.Local); } public DateTime? GetNullableDateTime(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetNullableDateTime); if (reader.IsDBNull(ordinal)) { return null; } return GetDateTime(ordinal); } public DateOnly GetDateOnly(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetDateOnly); var dt = typeCodes[ordinal] switch { TypeCode.DateTime => reader.GetDateTime(ordinal).ToDateOnly(), tcDateOnly => reader.GetFieldValue<DateOnly>(ordinal), _ => reader.GetFieldValue<DateOnly>(ordinal), }; return dt; } public DateOnly? GetNullableDateOnly(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetNullableDateOnly); if (reader.IsDBNull(ordinal)) { return null; } return GetDateOnly(ordinal); } public DateTimeOffset GetDateTimeOffset(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetDateTimeOffset); switch (typeCodes[ordinal]) { case tcDateTimeOffset: if (isPostgres) throw new InvalidOperationException("DateTimeOffset not supported in Postgres"); return ((SqlDataReader)reader).GetDateTimeOffset(ordinal); default: return ReflectionTools.ChangeType<DateTimeOffset>(reader.GetValue(ordinal)); } } public DateTimeOffset? GetNullableDateTimeOffset(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetNullableDateTimeOffset); if (reader.IsDBNull(ordinal)) { return null; } return GetDateTimeOffset(ordinal); } public TimeSpan GetTimeSpan(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetTimeSpan); switch (typeCodes[ordinal]) { case tcTimeSpan: if (isPostgres) return ((NpgsqlDataReader)reader).GetTimeSpan(ordinal); else return ((SqlDataReader)reader).GetTimeSpan(ordinal); default: return ReflectionTools.ChangeType<TimeSpan>(reader.GetValue(ordinal)); } } public TimeSpan? GetNullableTimeSpan(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetNullableTimeSpan); if (reader.IsDBNull(ordinal)) { return null; } return GetTimeSpan(ordinal); } public TimeOnly GetTimeOnly(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetTimeOnly); switch (typeCodes[ordinal]) { case tcTimeSpan: if (isPostgres) return TimeOnly.FromTimeSpan(((NpgsqlDataReader)reader).GetTimeSpan(ordinal)); else return TimeOnly.FromTimeSpan(((SqlDataReader)reader).GetTimeSpan(ordinal)); default: return TimeOnly.FromTimeSpan(ReflectionTools.ChangeType<TimeSpan>(reader.GetValue(ordinal))); } } public TimeOnly? GetNullableTimeOnly(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetNullableTimeOnly); if (reader.IsDBNull(ordinal)) { return null; } return GetTimeOnly(ordinal); } public Guid GetGuid(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetGuid); return typeCodes[ordinal] switch { tcGuid => reader.GetGuid(ordinal), _ => ReflectionTools.ChangeType<Guid>(reader.GetValue(ordinal)), }; } public Guid? GetNullableGuid(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetNullableGuid); if (reader.IsDBNull(ordinal)) { return null; } return GetGuid(ordinal); } static readonly MethodInfo miGetUdt = ReflectionTools.GetMethodInfo((FieldReader r) => r.GetUdt<UdtExample>(0)).GetGenericMethodDefinition(); public T GetUdt<T>(int ordinal) where T : IBinarySerialize { LastOrdinal = ordinal; LastMethodName = nameof(GetUdt) + "<" + typeof(T).Name + ">"; var udt = Activator.CreateInstance<T>(); udt.Read(new BinaryReader(reader.GetStream(ordinal))); return udt; } struct UdtExample : IBinarySerialize { public void Read(BinaryReader r) => throw new NotImplementedException(); public void Write(BinaryWriter w) => throw new NotImplementedException(); } static readonly MethodInfo miGetNullableUdt = ReflectionTools.GetMethodInfo((FieldReader r) => r.GetNullableUdt<UdtExample>(0)).GetGenericMethodDefinition(); public T? GetNullableUdt<T>(int ordinal) where T : struct, IBinarySerialize { LastOrdinal = ordinal; LastMethodName = nameof(GetNullableUdt) + "<" + typeof(T).Name + ">"; if (reader.IsDBNull(ordinal)) { return null; } var udt = Activator.CreateInstance<T>(); udt.Read(new BinaryReader(reader.GetStream(ordinal))); return udt; } static readonly MethodInfo miGetArray = ReflectionTools.GetMethodInfo((FieldReader r) => r.GetArray<int>(0)).GetGenericMethodDefinition(); public T[] GetArray<T>(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetArray) + "<" + typeof(T).Name + ">"; if (reader.IsDBNull(ordinal)) { return (T[])(object)null!; } return (T[])this.reader[ordinal]; } static readonly MethodInfo miNullableGetRange = ReflectionTools.GetMethodInfo((FieldReader r) => r.GetNullableRange<int>(0)).GetGenericMethodDefinition(); public NpgsqlTypes.NpgsqlRange<T>? GetNullableRange<T>(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetNullableRange) + "<" + typeof(T).Name + ">"; if (reader.IsDBNull(ordinal)) { return (NpgsqlTypes.NpgsqlRange<T>)(object)null!; } return (NpgsqlTypes.NpgsqlRange<T>)this.reader[ordinal]; } static readonly MethodInfo miGetRange = ReflectionTools.GetMethodInfo((FieldReader r) => r.GetRange<int>(0)).GetGenericMethodDefinition(); public NpgsqlTypes.NpgsqlRange<T> GetRange<T>(int ordinal) { LastOrdinal = ordinal; LastMethodName = nameof(GetRange) + "<" + typeof(T).Name + ">"; return (NpgsqlTypes.NpgsqlRange<T>)this.reader[ordinal]; } static Dictionary<Type, MethodInfo> methods = typeof(FieldReader).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Where(m => m.Name != "GetExpression" && m.Name != "IsNull") .ToDictionary(a => a.ReturnType); public static Expression GetExpression(Expression reader, int ordinal, Type type) { MethodInfo? mi = methods.TryGetC(type); if (mi != null) return Expression.Call(reader, mi, Expression.Constant(ordinal)); if (typeof(IBinarySerialize).IsAssignableFrom(type.UnNullify())) { if (type.IsNullable()) return Expression.Call(reader, miGetNullableUdt.MakeGenericMethod(type.UnNullify()), Expression.Constant(ordinal)); else return Expression.Call(reader, miGetUdt.MakeGenericMethod(type.UnNullify()), Expression.Constant(ordinal)); } if (type.IsArray) { return Expression.Call(reader, miGetArray.MakeGenericMethod(type.ElementType()!), Expression.Constant(ordinal)); } if (type.IsInstantiationOf(typeof(NpgsqlTypes.NpgsqlRange<>))) { return Expression.Call(reader, miGetRange.MakeGenericMethod(type.GetGenericArguments()[0]!), Expression.Constant(ordinal)); } if (type.IsNullable() && type.UnNullify().IsInstantiationOf(typeof(NpgsqlTypes.NpgsqlRange<>))) { return Expression.Call(reader, miNullableGetRange.MakeGenericMethod(type.UnNullify().GetGenericArguments()[0]!), Expression.Constant(ordinal)); } throw new InvalidOperationException("Type {0} not supported".FormatWith(type)); } static MethodInfo miIsNull = ReflectionTools.GetMethodInfo((FieldReader r) => r.IsNull(0)); public static Expression GetIsNull(Expression reader, int ordinal) { return Expression.Call(reader, miIsNull, Expression.Constant(ordinal)); } internal FieldReaderException CreateFieldReaderException(Exception ex) { return new FieldReaderException(ex, ordinal: LastOrdinal, columnName: LastOrdinal != null ? reader.GetName(LastOrdinal.Value) : null, methodName: LastMethodName ) ; } } public class FieldReaderException : DbException { public int? Ordinal { get; internal set; } public string? ColumnName { get; internal set; } public string? MethodName { get; internal set; } public int Row { get; internal set; } public SqlPreCommand? Command { get; internal set; } public LambdaExpression? Projector { get; internal set; } public FieldReaderException(Exception inner, int? ordinal, string? columnName, string? methodName) : base(null, inner) { this.Ordinal = ordinal; this.ColumnName = columnName; this.MethodName = methodName; } #pragma warning disable CS8618 // Non-nullable field is uninitialized. protected FieldReaderException( #pragma warning restore CS8618 // Non-nullable field is uninitialized. System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } public override string Message { get { string text = "{0}\r\nOrdinal: {1}\r\nColumnName: {2}\r\nRow: {3}".FormatWith(InnerException!.Message, Ordinal, ColumnName, Row); if (Ordinal != null && MethodName != null) text += "\r\nCalling: row.Reader.{0}({1})".FormatWith(MethodName, Ordinal); if (Projector != null) text += "\r\nProjector:\r\n{0}".FormatWith(Projector.ToString().Indent(4)); if(Command != null) text += "\r\nCommand:\r\n{0}".FormatWith(Command.PlainSql().Indent(4)); return text; } } }
// // TreeViewBackend.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; using System.Linq; namespace Xwt.GtkBackend { public class TreeViewBackend: TableViewBackend, ITreeViewBackend { Gtk.TreePath autoExpandPath; uint expandTimer; protected new ITreeViewEventSink EventSink { get { return (ITreeViewEventSink)base.EventSink; } } public override void EnableEvent (object eventId) { base.EnableEvent (eventId); if (eventId is TreeViewEvent) { switch ((TreeViewEvent)eventId) { case TreeViewEvent.RowActivated: Widget.RowActivated += HandleRowActivated; break; case TreeViewEvent.RowExpanding: Widget.TestExpandRow += HandleTestExpandRow; break; case TreeViewEvent.RowExpanded: Widget.RowExpanded += HandleRowExpanded; break; case TreeViewEvent.RowCollapsing: Widget.TestCollapseRow += HandleTestCollapseRow; break; case TreeViewEvent.RowCollapsed: Widget.RowCollapsed += HandleRowCollapsed; break; } } } public override void DisableEvent (object eventId) { base.DisableEvent (eventId); if (eventId is TreeViewEvent) { switch ((TreeViewEvent)eventId) { case TreeViewEvent.RowActivated: Widget.RowActivated -= HandleRowActivated; break; case TreeViewEvent.RowExpanding: Widget.TestExpandRow -= HandleTestExpandRow;; break; case TreeViewEvent.RowExpanded: Widget.RowExpanded -= HandleRowExpanded;; break; case TreeViewEvent.RowCollapsing: Widget.TestCollapseRow -= HandleTestCollapseRow; break; case TreeViewEvent.RowCollapsed: Widget.RowCollapsed -= HandleRowCollapsed; break; } } } void HandleRowExpanded (object o, Gtk.RowExpandedArgs args) { Gtk.TreeIter it; if (Widget.Model.GetIter (out it, args.Path)) { CurrentEventRow = new IterPos (-1, it); ApplicationContext.InvokeUserCode (delegate { EventSink.OnRowExpanded (new IterPos (-1, it)); }); } } void HandleTestExpandRow (object o, Gtk.TestExpandRowArgs args) { Gtk.TreeIter it; if (Widget.Model.GetIter (out it, args.Path)) { CurrentEventRow = new IterPos (-1, it); ApplicationContext.InvokeUserCode (delegate { EventSink.OnRowExpanding (new IterPos (-1, it)); }); } } void HandleRowCollapsed (object o, Gtk.RowCollapsedArgs args) { Gtk.TreeIter it; if (Widget.Model.GetIter (out it, args.Path)) { CurrentEventRow = new IterPos (-1, it); ApplicationContext.InvokeUserCode (delegate { EventSink.OnRowCollapsed (new IterPos (-1, it)); }); } } void HandleTestCollapseRow (object o, Gtk.TestCollapseRowArgs args) { Gtk.TreeIter it; if (Widget.Model.GetIter (out it, args.Path)) { CurrentEventRow = new IterPos (-1, it); ApplicationContext.InvokeUserCode (delegate { EventSink.OnRowCollapsing (new IterPos (-1, it)); }); } } void HandleRowActivated (object o, Gtk.RowActivatedArgs args) { Gtk.TreeIter it; if (Widget.Model.GetIter (out it, args.Path)) { CurrentEventRow = new IterPos (-1, it); ApplicationContext.InvokeUserCode (delegate { EventSink.OnRowActivated (new IterPos (-1, it)); }); } } protected override void OnSetDragTarget (Gtk.TargetEntry[] table, Gdk.DragAction actions) { base.OnSetDragTarget (table, actions); Widget.EnableModelDragDest (table, actions); } protected override void OnSetDragSource (Gdk.ModifierType modifierType, Gtk.TargetEntry[] table, Gdk.DragAction actions) { base.OnSetDragSource (modifierType, table, actions); Widget.EnableModelDragSource (modifierType, table, actions); } protected override void OnSetDragStatus (Gdk.DragContext context, int x, int y, uint time, Gdk.DragAction action) { base.OnSetDragStatus (context, x, y, time, action); // We are overriding the TreeView methods for handling drag & drop, so we need // to manually highlight the selected row Gtk.TreeViewDropPosition tpos; Gtk.TreePath path; if (!Widget.GetDestRowAtPos (x, y, out path, out tpos)) path = null; if (expandTimer == 0 || !object.Equals (autoExpandPath, path)) { if (expandTimer != 0) GLib.Source.Remove (expandTimer); if (path != null) { expandTimer = GLib.Timeout.Add (600, delegate { Widget.ExpandRow (path, false); return false; }); } autoExpandPath = path; } if (path != null && action != 0) Widget.SetDragDestRow (path, tpos); else Widget.SetDragDestRow (null, 0); } protected override void Dispose (bool disposing) { if (expandTimer != 0) GLib.Source.Remove (expandTimer); base.Dispose (disposing); } public void SetSource (ITreeDataSource source, IBackend sourceBackend) { TreeStoreBackend b = sourceBackend as TreeStoreBackend; if (b == null) { CustomTreeModel model = new CustomTreeModel (source); Widget.Model = model.Store; } else Widget.Model = b.Store; } public TreePosition[] SelectedRows { get { var rows = Widget.Selection.GetSelectedRows (); IterPos[] sel = new IterPos [rows.Length]; for (int i = 0; i < rows.Length; i++) { Gtk.TreeIter it; Widget.Model.GetIter (out it, rows[i]); sel[i] = new IterPos (-1, it); } return sel; } } public TreePosition FocusedRow { get { Gtk.TreePath path; Gtk.TreeViewColumn column; Widget.GetCursor (out path, out column); Gtk.TreeIter it; if (path != null && Widget.Model.GetIter (out it, path)) return new IterPos (-1, it); return null; } set { Gtk.TreePath path = new Gtk.TreePath(new [] { int.MaxValue }); // set invalid path to unfocus if (value != null) path = Widget.Model.GetPath (((IterPos)value).Iter); Widget.SetCursor (path, null, false); } } public TreePosition CurrentEventRow { get; internal set; } public void SelectRow (TreePosition pos) { Widget.Selection.SelectIter (((IterPos)pos).Iter); } public void UnselectRow (TreePosition pos) { Widget.Selection.UnselectIter (((IterPos)pos).Iter); } public bool IsRowSelected (TreePosition pos) { return Widget.Selection.IterIsSelected (((IterPos)pos).Iter); } public bool IsRowExpanded (TreePosition pos) { return Widget.GetRowExpanded (Widget.Model.GetPath (((IterPos)pos).Iter)); } public void ExpandRow (TreePosition pos, bool expandedChildren) { Widget.ExpandRow (Widget.Model.GetPath (((IterPos)pos).Iter), expandedChildren); } public void CollapseRow (TreePosition pos) { Widget.CollapseRow (Widget.Model.GetPath (((IterPos)pos).Iter)); } public void ScrollToRow (TreePosition pos) { ScrollToRow (((IterPos)pos).Iter); } public void ExpandToRow (TreePosition pos) { Widget.ExpandToPath (Widget.Model.GetPath (((IterPos)pos).Iter)); } public bool HeadersVisible { get { return Widget.HeadersVisible; } set { Widget.HeadersVisible = value; } } public bool GetDropTargetRow (double x, double y, out RowDropPosition pos, out TreePosition nodePosition) { Gtk.TreeViewDropPosition tpos; Gtk.TreePath path; if (!Widget.GetDestRowAtPos ((int)x, (int)y, out path, out tpos)) { pos = RowDropPosition.Into; nodePosition = null; return false; } Gtk.TreeIter it; Widget.Model.GetIter (out it, path); nodePosition = new IterPos (-1, it); switch (tpos) { case Gtk.TreeViewDropPosition.After: pos = RowDropPosition.After; break; case Gtk.TreeViewDropPosition.Before: pos = RowDropPosition.Before; break; default: pos = RowDropPosition.Into; break; } return true; } public TreePosition GetRowAtPosition (Point p) { Gtk.TreePath path = GetPathAtPosition (p); if (path != null) { Gtk.TreeIter iter; Widget.Model.GetIter (out iter, path); return new IterPos (-1, iter); } return null; } public Rectangle GetCellBounds (TreePosition pos, CellView cell, bool includeMargin) { var col = GetCellColumn (cell); var cr = GetCellRenderer (cell); Gtk.TreeIter iter = ((IterPos)pos).Iter; var rect = includeMargin ? ((ICellRendererTarget)this).GetCellBackgroundBounds (col, cr, iter) : ((ICellRendererTarget)this).GetCellBounds (col, cr, iter); return rect; } public Rectangle GetRowBounds (TreePosition pos, bool includeMargin) { Gtk.TreeIter iter = ((IterPos)pos).Iter; Rectangle rect = includeMargin ? GetRowBackgroundBounds (iter) : GetRowBounds (iter); return rect; } public override void SetCurrentEventRow (string path) { var treeFrontend = (TreeView)Frontend; TreePosition toggledItem = null; var pathParts = path.Split (':').Select (part => int.Parse (part)); foreach (int pathPart in pathParts) { toggledItem = treeFrontend.DataSource.GetChild (toggledItem, pathPart); } CurrentEventRow = toggledItem; } } }
using System; using Csla; using Csla.Data; using DalEf; using Csla.Serialization; using System.ComponentModel.DataAnnotations; using BusinessObjects.Properties; using System.Linq; using BusinessObjects.Common; namespace BusinessObjects.MDEntities { [Serializable] public partial class cMDEntities_Enums_EntityGroup: BusinessObjects.CoreBusinessClasses.CoreBusinessClass<cMDEntities_Enums_EntityGroup> { #region Business Methods public static readonly PropertyInfo< System.Int32 > IdProperty = RegisterProperty< System.Int32 >(p => p.Id, string.Empty); #if !SILVERLIGHT [System.ComponentModel.DataObjectField(true, true)] #endif public System.Int32 Id { get { return GetProperty(IdProperty); } internal set { SetProperty(IdProperty, value); } } private static readonly PropertyInfo<System.Int32> companyUsingServiceIdProperty = RegisterProperty<System.Int32>(p => p.CompanyUsingServiceId, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.Int32 CompanyUsingServiceId { get { return GetProperty(companyUsingServiceIdProperty); } set { SetProperty(companyUsingServiceIdProperty, value); } } private static readonly PropertyInfo<System.String> labelProperty = RegisterProperty<System.String>(p => p.Label, string.Empty); [System.ComponentModel.DataAnnotations.StringLength(20, ErrorMessageResourceName = "ErrorMessageMaxLength", ErrorMessageResourceType = typeof(Resources))] [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.String Label { get { return GetProperty(labelProperty); } set { SetProperty(labelProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo<System.String> nameProperty = RegisterProperty<System.String>(p => p.Name, string.Empty); [System.ComponentModel.DataAnnotations.StringLength(100, ErrorMessageResourceName = "ErrorMessageMaxLength", ErrorMessageResourceType = typeof(Resources))] [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.String Name { get { return GetProperty(nameProperty); } set { SetProperty(nameProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo<System.Int32?> mDEntities_Enums_EntityParentGroupIdProperty = RegisterProperty<System.Int32?>(p => p.MDEntities_Enums_EntityParentGroupId, string.Empty, (System.Int32?)null); public System.Int32? MDEntities_Enums_EntityParentGroupId { get { return GetProperty(mDEntities_Enums_EntityParentGroupIdProperty); } set { SetProperty(mDEntities_Enums_EntityParentGroupIdProperty, value); } } private static readonly PropertyInfo<bool> inactiveProperty = RegisterProperty<bool>(p => p.Inactive, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public bool Inactive { get { return GetProperty(inactiveProperty); } set { SetProperty(inactiveProperty, value); } } private static readonly PropertyInfo<System.DateTime> lastActivityDateProperty = RegisterProperty<System.DateTime>(p => p.LastActivityDate, string.Empty, System.DateTime.Now); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.DateTime LastActivityDate { get { return GetProperty(lastActivityDateProperty); } set { SetProperty(lastActivityDateProperty, value); } } private static readonly PropertyInfo<System.Int32> employeeWhoLastChanedItUserIdProperty = RegisterProperty<System.Int32>(p => p.EmployeeWhoLastChanedItUserId, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.Int32 EmployeeWhoLastChanedItUserId { get { return GetProperty(employeeWhoLastChanedItUserIdProperty); } set { SetProperty(employeeWhoLastChanedItUserIdProperty, value); } } /// <summary> /// Used for optimistic concurrency. /// </summary> [NotUndoable] internal System.Byte[] LastChanged = new System.Byte[8]; #endregion #region Factory Methods public static cMDEntities_Enums_EntityGroup NewMDEntities_Enums_EntityGroup() { return DataPortal.Create<cMDEntities_Enums_EntityGroup>(); } public static cMDEntities_Enums_EntityGroup GetMDEntities_Enums_EntityGroup(int uniqueId) { return DataPortal.Fetch<cMDEntities_Enums_EntityGroup>(new SingleCriteria<cMDEntities_Enums_EntityGroup, int>(uniqueId)); } internal static cMDEntities_Enums_EntityGroup GetMDEntities_Enums_EntityGroup(MDEntities_Enums_EntityGroup data) { return DataPortal.Fetch<cMDEntities_Enums_EntityGroup>(data); } public static void DeleteMDEntities_Enums_EntityGroup(int uniqueId) { DataPortal.Delete<cMDEntities_Enums_EntityGroup>(new SingleCriteria<cMDEntities_Enums_EntityGroup, int>(uniqueId)); } #endregion #region Data Access [RunLocal] protected override void DataPortal_Create() { BusinessRules.CheckRules(); } private void DataPortal_Fetch(SingleCriteria<cMDEntities_Enums_EntityGroup, int> criteria) { using (var ctx = ObjectContextManager<MDEntitiesEntities>.GetManager("MDEntitiesEntities")) { var data = ctx.ObjectContext.MDEntities_Enums_EntityGroup.First(p => p.Id == criteria.Value); LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<int>(companyUsingServiceIdProperty, data.CompanyUsingServiceId); LoadProperty<string>(labelProperty, data.Label); LoadProperty<string>(nameProperty, data.Name); LoadProperty<int?>(mDEntities_Enums_EntityParentGroupIdProperty, data.MDEntities_Enums_EntityParentGroupId); LoadProperty<bool>(inactiveProperty, data.Inactive); LoadProperty<DateTime>(lastActivityDateProperty, data.LastActivityDate); LoadProperty<int>(employeeWhoLastChanedItUserIdProperty, data.EmployeeWhoLastChanedItUserId); LastChanged = data.LastChanged; BusinessRules.CheckRules(); } } private void DataPortal_Fetch(MDEntities_Enums_EntityGroup data) { LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<int>(companyUsingServiceIdProperty, data.CompanyUsingServiceId); LoadProperty<string>(labelProperty, data.Label); LoadProperty<string>(nameProperty, data.Name); LoadProperty<int?>(mDEntities_Enums_EntityParentGroupIdProperty, data.MDEntities_Enums_EntityParentGroupId); LoadProperty<bool>(inactiveProperty, data.Inactive); LoadProperty<DateTime>(lastActivityDateProperty, data.LastActivityDate); LoadProperty<int>(employeeWhoLastChanedItUserIdProperty, data.EmployeeWhoLastChanedItUserId); LastChanged = data.LastChanged; BusinessRules.CheckRules(); MarkAsChild(); } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Insert() { using (var ctx = ObjectContextManager<MDEntitiesEntities>.GetManager("MDEntitiesEntities")) { var data = new MDEntities_Enums_EntityGroup(); data.CompanyUsingServiceId = ReadProperty<int>(companyUsingServiceIdProperty); data.Label = ReadProperty<string>(labelProperty); data.Name = ReadProperty<string>(nameProperty); data.MDEntities_Enums_EntityParentGroupId = ReadProperty<int?>(mDEntities_Enums_EntityParentGroupIdProperty); data.Inactive = ReadProperty<bool>(inactiveProperty); data.LastActivityDate = ReadProperty<DateTime>(lastActivityDateProperty); data.EmployeeWhoLastChanedItUserId = ReadProperty<int>(employeeWhoLastChanedItUserIdProperty); ctx.ObjectContext.AddToMDEntities_Enums_EntityGroup(data); ctx.ObjectContext.SaveChanges(); //Get New id int newId = data.Id; //Load New Id into object LoadProperty(IdProperty, newId); //Load New EntityKey into Object LoadProperty(EntityKeyDataProperty, Serialize(data.EntityKey)); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { using (var ctx = ObjectContextManager<MDEntitiesEntities>.GetManager("MDEntitiesEntities")) { var data = new MDEntities_Enums_EntityGroup(); data.Id = ReadProperty<int>(IdProperty); data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey; ctx.ObjectContext.Attach(data); data.CompanyUsingServiceId = ReadProperty<int>(companyUsingServiceIdProperty); data.Label = ReadProperty<string>(labelProperty); data.Name = ReadProperty<string>(nameProperty); data.MDEntities_Enums_EntityParentGroupId = ReadProperty<int?>(mDEntities_Enums_EntityParentGroupIdProperty); data.Inactive = ReadProperty<bool>(inactiveProperty); data.LastActivityDate = ReadProperty<DateTime>(lastActivityDateProperty); data.EmployeeWhoLastChanedItUserId = ReadProperty<int>(employeeWhoLastChanedItUserIdProperty); ctx.ObjectContext.SaveChanges(); } } [Transactional(TransactionalTypes.TransactionScope)] private void DataPortal_Delete(SingleCriteria<cMDEntities_Enums_EntityGroup, int> criteria) { using (var ctx = ObjectContextManager<MDEntitiesEntities>.GetManager("MDEntitiesEntities")) { var data = ctx.ObjectContext.MDEntities_Enums_EntityGroup.First(p => p.Id == criteria.Value); ctx.ObjectContext.MDEntities_Enums_EntityGroup.DeleteObject(data); ctx.ObjectContext.SaveChanges(); } } #endregion } public partial class cMDEntities_Enums_EntityGroup_List : BusinessListBase<cMDEntities_Enums_EntityGroup_List, cMDEntities_Enums_EntityGroup> { public static cMDEntities_Enums_EntityGroup_List GetcMDEntities_Enums_EntityGroup_List() { return DataPortal.Fetch<cMDEntities_Enums_EntityGroup_List>(); } public static cMDEntities_Enums_EntityGroup_List GetcMDEntities_Enums_EntityGroup_List(int companyId) { return DataPortal.Fetch<cMDEntities_Enums_EntityGroup_List>(new SingleCriteria<cMDEntities_Enums_EntityGroup_List, int>(companyId)); } public static cMDEntities_Enums_EntityGroup_List GetcMDEntities_Enums_EntityGroup_List(int companyId, int includeInactiveId) { return DataPortal.Fetch<cMDEntities_Enums_EntityGroup_List>(new ActiveEnums_Criteria(companyId, includeInactiveId)); } public static cMDEntities_Enums_EntityGroup_List GetcMDEntities_Enums_EntityGroup_List(int companyId, int includeInactiveId, int excludeGroupId) { return DataPortal.Fetch<cMDEntities_Enums_EntityGroup_List>(new EntityGroup_Criteria(companyId, includeInactiveId, excludeGroupId)); } private void DataPortal_Fetch() { using (var ctx = ObjectContextManager<MDEntitiesEntities>.GetManager("MDEntitiesEntities")) { var result = ctx.ObjectContext.MDEntities_Enums_EntityGroup; foreach (var data in result) { var obj = cMDEntities_Enums_EntityGroup.GetMDEntities_Enums_EntityGroup(data); this.Add(obj); } } } private void DataPortal_Fetch(SingleCriteria<cMDEntities_Enums_EntityGroup_List, int> criteria) { using (var ctx = ObjectContextManager<MDEntitiesEntities>.GetManager("MDEntitiesEntities")) { var result = ctx.ObjectContext.MDEntities_Enums_EntityGroup.Where(p=> p.CompanyUsingServiceId == criteria.Value); foreach (var data in result) { var obj = cMDEntities_Enums_EntityGroup.GetMDEntities_Enums_EntityGroup(data); this.Add(obj); } } } private void DataPortal_Fetch(ActiveEnums_Criteria criteria) { using (var ctx = ObjectContextManager<MDEntitiesEntities>.GetManager("MDEntitiesEntities")) { var result = ctx.ObjectContext.MDEntities_Enums_EntityGroup.Where(p => p.CompanyUsingServiceId == criteria.CompanyId && (p.Inactive == false || p.Id == criteria.IncludeInactiveId)); foreach (var data in result) { var obj = cMDEntities_Enums_EntityGroup.GetMDEntities_Enums_EntityGroup(data); this.Add(obj); } } } private void DataPortal_Fetch(EntityGroup_Criteria criteria) { using (var ctx = ObjectContextManager<MDEntitiesEntities>.GetManager("MDEntitiesEntities")) { var result = ctx.ObjectContext.MDEntities_Enums_EntityGroup.Where(p => p.CompanyUsingServiceId == criteria.CompanyId && (p.Inactive == false || p.Id == criteria.IncludeInactiveId) && p.Id != criteria.ExcludeGroupId); foreach (var data in result) { var obj = cMDEntities_Enums_EntityGroup.GetMDEntities_Enums_EntityGroup(data); this.Add(obj); } } } } }
namespace Gu.Wpf.Geometry { using System; using System.Diagnostics; using System.Globalization; using System.Windows; using System.Windows.Data; using System.Windows.Media; using System.Windows.Threading; /// <summary> /// An elliptical balloon. /// </summary> public class EllipseBalloon : BalloonBase { private static readonly DependencyProperty EllipseProperty = DependencyProperty.Register( "Ellipse", typeof(Ellipse), typeof(EllipseBalloon), new PropertyMetadata(default(Ellipse))); /// <inheritdoc/> protected override Geometry GetOrCreateBoxGeometry(Size renderSize) { var ellipse = Ellipse.CreateFromSize(renderSize); this.SetCurrentValue(EllipseProperty, ellipse); if (ellipse.RadiusX <= 0 || ellipse.RadiusY <= 0) { return Geometry.Empty; } if (this.BoxGeometry is EllipseGeometry) { return this.BoxGeometry; } var geometry = new EllipseGeometry(); _ = geometry.Bind(EllipseGeometry.CenterProperty) .OneWayTo(this, EllipseProperty, EllipseCenterConverter.Default); _ = geometry.Bind(EllipseGeometry.RadiusXProperty) .OneWayTo(this, EllipseProperty, EllipseRadiusXConverter.Default); _ = geometry.Bind(EllipseGeometry.RadiusYProperty) .OneWayTo(this, EllipseProperty, EllipseRadiusYConverter.Default); return geometry; } /// <inheritdoc/> protected override Geometry GetOrCreateConnectorGeometry(Size renderSize) { var ellipse = Ellipse.CreateFromSize(renderSize); this.SetCurrentValue(EllipseProperty, ellipse); if (ellipse.IsZero) { return Geometry.Empty; } var direction = this.ConnectorOffset; var ip = ellipse.PointOnCircumference(direction); var vertexPoint = ip + this.ConnectorOffset; var ray = new Ray(vertexPoint, this.ConnectorOffset.Negated()); var p1 = ConnectorPoint.Find(ray, this.ConnectorAngle / 2, this.StrokeThickness, ellipse); var p2 = ConnectorPoint.Find(ray, -this.ConnectorAngle / 2, this.StrokeThickness, ellipse); this.SetCurrentValue(ConnectorVertexPointProperty, vertexPoint); this.SetCurrentValue(ConnectorPoint1Property, p1); this.SetCurrentValue(ConnectorPoint2Property, p2); if (this.ConnectorGeometry is PathGeometry) { return this.ConnectorGeometry; } var figure = this.CreatePathFigureStartingAt(ConnectorPoint1Property); figure.Segments.Add(this.CreateLineSegmentTo(ConnectorVertexPointProperty)); figure.Segments.Add(this.CreateLineSegmentTo(ConnectorPoint2Property)); var geometry = new PathGeometry(); geometry.Figures.Add(figure); return geometry; } /// <inheritdoc/> protected override void UpdateConnectorOffset() { var hasTarget = this.PlacementTarget?.IsVisible == true || !this.PlacementRectangle.IsEmpty; if (this.IsVisible && this.RenderSize.Width > 0 && hasTarget) { if (!this.IsLoaded) { #pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs _ = this.Dispatcher.BeginInvoke(new Action(this.UpdateConnectorOffset), DispatcherPriority.Loaded); #pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs return; } var selfRect = new Rect(new Point(0, 0).ToScreen(this), this.RenderSize).ToScreen(this); var targetRect = this.GetTargetRect(); var ellipse = new Ellipse(selfRect); var tp = this.PlacementOptions?.GetPointOnTarget(selfRect, targetRect); if (tp is null || ellipse.Contains(tp.Value)) { this.InvalidateProperty(ConnectorOffsetProperty); return; } if (ellipse.Contains(tp.Value)) { this.SetCurrentValue(ConnectorOffsetProperty, new Vector(0, 0)); return; } var mp = ellipse.CenterPoint; var ip = new Ray(mp, mp.VectorTo(tp.Value)).FirstIntersectionWith(ellipse); Debug.Assert(ip != null, "Did not find an intersection, bug in the library"); //// ReSharper disable once ConditionIsAlwaysTrueOrFalse if (ip is null) { // failing silently in release this.InvalidateProperty(ConnectorOffsetProperty); } else { var v = tp.Value - ip.Value; // ReSharper disable once CompareOfFloatsByEqualityOperator if (this.PlacementOptions != null && v.Length > 0 && this.PlacementOptions.Offset != 0) { v -= this.PlacementOptions.Offset * v.Normalized(); } this.SetCurrentValue(ConnectorOffsetProperty, v); } } else { this.InvalidateProperty(ConnectorOffsetProperty); } } private PathFigure CreatePathFigureStartingAt(DependencyProperty property) { var figure = new PathFigure { IsClosed = true }; _ = figure.Bind(PathFigure.StartPointProperty) .OneWayTo(this, property); return figure; } private LineSegment CreateLineSegmentTo(DependencyProperty property) { var lineSegment = new LineSegment { IsStroked = true }; _ = lineSegment.Bind(LineSegment.PointProperty) .OneWayTo(this, property); return lineSegment; } private static class ConnectorPoint { internal static Point Find(Ray ray, double angle, double strokeThickness, Ellipse ellipse) { return Find(ray.Rotate(angle), strokeThickness, ellipse); } private static Point Find(Ray ray, double strokeThickness, Ellipse ellipse) { var ip = ray.FirstIntersectionWith(ellipse); if (ip != null) { return ip.Value + (strokeThickness * ray.Direction); } return FindTangentPoint(ray, ellipse); } private static Point FindTangentPoint(Ray toCenter, Ellipse ellipse) { var toEllipseCenter = toCenter.PerpendicularLineTo(ellipse.CenterPoint); Debug.Assert(toEllipseCenter != null, "Ray should not go through ellipse center here"); //// ReSharper disable once ConditionIsAlwaysTrueOrFalse if (toEllipseCenter is null) { // this should never happen but failing silently // the balloons should not throw much returning random point. return ellipse.CenterPoint; } return ellipse.PointOnCircumference(toEllipseCenter.Value.Direction.Negated()); } } private sealed class EllipseCenterConverter : IValueConverter { internal static readonly EllipseCenterConverter Default = new EllipseCenterConverter(); private EllipseCenterConverter() { } public object Convert(object value, Type _, object __, CultureInfo ___) { // ReSharper disable once PossibleNullReferenceException return ((Ellipse)value).CenterPoint; } public object ConvertBack(object _, Type __, object ___, CultureInfo ____) { throw new NotSupportedException(); } } private sealed class EllipseRadiusXConverter : IValueConverter { internal static readonly EllipseRadiusXConverter Default = new EllipseRadiusXConverter(); private EllipseRadiusXConverter() { } public object Convert(object value, Type _, object __, CultureInfo ___) { // ReSharper disable once PossibleNullReferenceException return ((Ellipse)value).RadiusX; } public object ConvertBack(object _, Type __, object ___, CultureInfo ____) { throw new NotSupportedException(); } } private sealed class EllipseRadiusYConverter : IValueConverter { internal static readonly EllipseRadiusYConverter Default = new EllipseRadiusYConverter(); private EllipseRadiusYConverter() { } public object Convert(object value, Type _, object __, CultureInfo ___) { // ReSharper disable once PossibleNullReferenceException return ((Ellipse)value).RadiusY; } public object ConvertBack(object _, Type __, object ___, CultureInfo ____) { throw new NotSupportedException(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Baseline; using Marten.Linq.Parsing; using Marten.Schema; using Marten.Schema.Identity; using Marten.Schema.Identity.Sequences; using Marten.Schema.Indexing.Unique; using Marten.Storage; using Marten.Storage.Metadata; using NpgsqlTypes; using Weasel.Core; using Weasel.Postgresql; using Weasel.Postgresql.Tables; #nullable enable namespace Marten { internal interface IDocumentMappingBuilder { DocumentMapping Build(StoreOptions options); Type DocumentType { get; } void Include(IDocumentMappingBuilder include); } internal class DocumentMappingBuilder<T>: IDocumentMappingBuilder { private readonly IList<Action<DocumentMapping<T>>> _alterations = new List<Action<DocumentMapping<T>>>(); internal Action<DocumentMapping<T>> Alter { set => _alterations.Add(value); } public DocumentMapping Build(StoreOptions options) { var mapping = new DocumentMapping<T>(options); foreach (var alteration in _alterations) alteration(mapping); return mapping; } public Type DocumentType => typeof(T); public void Include(IDocumentMappingBuilder include) { _alterations.AddRange(include.As<DocumentMappingBuilder<T>>()._alterations); } } /// <summary> /// Used to customize or optimize the storage and retrieval of document types /// </summary> public class MartenRegistry { private readonly StoreOptions _storeOptions; internal MartenRegistry(StoreOptions storeOptions) { _storeOptions = storeOptions; } protected MartenRegistry() : this(new StoreOptions()) { } /// <summary> /// Include the declarations from another MartenRegistry type /// </summary> /// <typeparam name="T"></typeparam> public void Include<T>() where T : MartenRegistry, new() { Include(new T()); } /// <summary> /// Include the declarations from another MartenRegistry object /// </summary> /// <param name="registry"></param> public void Include(MartenRegistry registry) { _storeOptions.Storage.IncludeDocumentMappingBuilders(registry._storeOptions.Storage); } /// <summary> /// Configure a single document type /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public DocumentMappingExpression<T> For<T>() { return new DocumentMappingExpression<T>(_storeOptions.Storage.BuilderFor<T>()); } public class DocumentMappingExpression<T> { private readonly DocumentMappingBuilder<T> _builder; internal DocumentMappingExpression(DocumentMappingBuilder<T> builder) { _builder = builder; } /// <summary> /// Specify the property searching mechanism for this document type. The default is /// JSON_Locator_Only /// </summary> /// <param name="searching"></param> /// <returns></returns> public DocumentMappingExpression<T> PropertySearching(PropertySearching searching) { _builder.Alter = m => m.PropertySearching = searching; return this; } /// <summary> /// Override the Postgresql schema alias for this document type in order /// to disambiguate similarly named document types. The default is just /// the document type name to lower case. /// </summary> /// <param name="alias"></param> /// <returns></returns> public DocumentMappingExpression<T> DocumentAlias(string alias) { _builder.Alter = m => m.Alias = alias; return this; } /// <summary> /// Marks a property or field on this document type as a searchable field that is also duplicated in the /// database document table /// </summary> /// <param name="expression"></param> /// <param name="pgType">Optional, overrides the Postgresql column type for the duplicated field</param> /// <param name="configure"> /// Optional, allows you to customize the Postgresql database index configured for the duplicated /// field /// </param> /// <returns></returns> [Obsolete( "Prefer Index() if you just want to optimize querying, or choose Duplicate() if you really want a duplicated field")] public DocumentMappingExpression<T> Searchable(Expression<Func<T, object>> expression, string? pgType = null, NpgsqlDbType? dbType = null, Action<DocumentIndex>? configure = null) { return Duplicate(expression, pgType, dbType, configure); } /// <summary> /// Marks a property or field on this document type as a searchable field that is also duplicated in the /// database document table /// </summary> /// <param name="expression"></param> /// <param name="pgType">Optional, overrides the Postgresql column type for the duplicated field</param> /// <param name="configure"> /// Optional, allows you to customize the Postgresql database index configured for the duplicated /// field /// </param> /// <param name="dbType">Optional, overrides the Npgsql DbType for any parameter usage of this property</param> /// <returns></returns> public DocumentMappingExpression<T> Duplicate(Expression<Func<T, object>> expression, string? pgType = null, NpgsqlDbType? dbType = null, Action<DocumentIndex>? configure = null, bool notNull = false) { _builder.Alter = mapping => { mapping.Duplicate(expression, pgType, dbType, configure, notNull); }; return this; } /// <summary> /// Creates a computed index on this data member within the JSON data storage /// </summary> /// <param name="expression"></param> /// <param name="configure"></param> /// <returns></returns> public DocumentMappingExpression<T> Index(Expression<Func<T, object>> expression, Action<ComputedIndex>? configure = null) { _builder.Alter = m => m.Index(expression, configure); return this; } /// <summary> /// Creates a computed index on this data member within the JSON data storage /// </summary> /// <param name="expressions"></param> /// <param name="configure"></param> /// <returns></returns> public DocumentMappingExpression<T> Index(IReadOnlyCollection<Expression<Func<T, object>>> expressions, Action<ComputedIndex>? configure = null) { _builder.Alter = m => m.Index(expressions, configure); return this; } /// <summary> /// Creates a unique index on this data member within the JSON data storage /// </summary> /// <param name="expressions"></param> /// <returns></returns> public DocumentMappingExpression<T> UniqueIndex(params Expression<Func<T, object>>[] expressions) { _builder.Alter = m => m.UniqueIndex(UniqueIndexType.Computed, null, expressions); return this; } /// <summary> /// Creates a unique index on this data member within the JSON data storage /// </summary> /// <param name="indexName">Name of the index</param> /// <param name="expressions"></param> /// <returns></returns> public DocumentMappingExpression<T> UniqueIndex(string indexName, params Expression<Func<T, object>>[] expressions) { _builder.Alter = m => m.UniqueIndex(UniqueIndexType.Computed, indexName, expressions); return this; } /// <summary> /// Creates a unique index on this data member within the JSON data storage /// </summary> /// <param name="indexType">Type of the index</param> /// <param name="expressions"></param> /// <returns></returns> public DocumentMappingExpression<T> UniqueIndex(UniqueIndexType indexType, params Expression<Func<T, object>>[] expressions) { _builder.Alter = m => m.UniqueIndex(indexType, null, expressions); return this; } /// <summary> /// Creates a unique index on this data member within the JSON data storage /// </summary> /// <param name="indexType">Type of the index</param> /// <param name="indexName">Name of the index</param> /// <param name="expressions"></param> /// <returns></returns> public DocumentMappingExpression<T> UniqueIndex(UniqueIndexType indexType, string indexName, params Expression<Func<T, object>>[] expressions) { _builder.Alter = m => m.UniqueIndex(indexType, indexName, expressions); return this; } /// <summary> /// Creates a unique index on this data member within the JSON data storage /// </summary> /// <param name="indexType">Type of the index</param> /// <param name="indexTenancyStyle">Style of tenancy</param> /// <param name="indexName">Name of the index</param> /// <param name="tenancyScope">Whether the unique index applies on a per tenant basis</param> /// <param name="expressions"></param> /// <returns></returns> public DocumentMappingExpression<T> UniqueIndex(UniqueIndexType indexType, string indexName, TenancyScope tenancyScope = TenancyScope.Global, params Expression<Func<T, object>>[] expressions) { _builder.Alter = m => m.UniqueIndex(indexType, indexName, tenancyScope, expressions); return this; } /// <summary> /// Creates an index on the predefined Last Modified column /// </summary> /// <param name="configure"></param> /// <returns></returns> public DocumentMappingExpression<T> IndexLastModified(Action<DocumentIndex>? configure = null) { _builder.Alter = m => m.AddLastModifiedIndex(configure); return this; } /// <summary> /// Create a full text index /// </summary> /// <param name="regConfig"></param> /// <param name="configure"></param> /// <returns></returns> public DocumentMappingExpression<T> FullTextIndex(string regConfig = Schema.FullTextIndex.DefaultRegConfig, Action<FullTextIndex>? configure = null) { _builder.Alter = m => m.AddFullTextIndex(regConfig, configure); return this; } /// <summary> /// Create a full text index /// </summary> /// <param name="configure"></param> /// <returns></returns> public DocumentMappingExpression<T> FullTextIndex(Action<FullTextIndex> configure) { _builder.Alter = m => m.AddFullTextIndex(Schema.FullTextIndex.DefaultRegConfig, configure); return this; } /// <summary> /// Create a full text index against designated fields on this document /// </summary> /// <param name="expressions"></param> /// <returns></returns> public DocumentMappingExpression<T> FullTextIndex(params Expression<Func<T, object>>[] expressions) { FullTextIndex(Schema.FullTextIndex.DefaultRegConfig, expressions); return this; } /// <summary> /// Create a full text index against designated fields on this document /// </summary> /// <param name="expressions"></param> /// <returns></returns> public DocumentMappingExpression<T> FullTextIndex(string regConfig, params Expression<Func<T, object>>[] expressions) { _builder.Alter = m => m.FullTextIndex(regConfig, expressions); return this; } /// <summary> /// Create a full text index against designated fields on this document /// </summary> /// <param name="expressions"></param> /// <returns></returns> public DocumentMappingExpression<T> FullTextIndex(Action<FullTextIndex> configure, params Expression<Func<T, object>>[] expressions) { _builder.Alter = m => { var index = m.FullTextIndex(Schema.FullTextIndex.DefaultRegConfig, expressions); configure(index); var temp = index; }; return this; } /// <summary> /// Add a foreign key reference to another document type /// </summary> /// <param name="expression"></param> /// <param name="foreignKeyConfiguration"></param> /// <param name="indexConfiguration"></param> /// <typeparam name="TReference"></typeparam> /// <returns></returns> public DocumentMappingExpression<T> ForeignKey<TReference>( Expression<Func<T, object>> expression, Action<DocumentForeignKey>? foreignKeyConfiguration = null, Action<DocumentIndex>? indexConfiguration = null) { _builder.Alter = m => { var visitor = new FindMembers(); visitor.Visit(expression); var foreignKeyDefinition = m.AddForeignKey(visitor.Members.ToArray(), typeof(TReference)); foreignKeyConfiguration?.Invoke(foreignKeyDefinition); var indexDefinition = m.AddIndex(foreignKeyDefinition.ColumnNames[0]); indexConfiguration?.Invoke(indexDefinition); }; return this; } /// <summary> /// Create a foreign key against the designated member of the document /// </summary> /// <param name="expression"></param> /// <param name="schemaName"></param> /// <param name="tableName"></param> /// <param name="columnName"></param> /// <param name="foreignKeyConfiguration"></param> /// <returns></returns> public DocumentMappingExpression<T> ForeignKey(Expression<Func<T, object>> expression, string schemaName, string tableName, string columnName, Action<ForeignKey>? foreignKeyConfiguration = null) { _builder.Alter = m => { var members = FindMembers.Determine(expression); var duplicateField = m.DuplicateField(members); var foreignKey = new ForeignKey($"{m.TableName.Name}_{duplicateField.ColumnName}_fkey") { LinkedTable = new DbObjectName(schemaName ?? m.DatabaseSchemaName, tableName), ColumnNames = new[] {duplicateField.ColumnName}, LinkedNames = new[] {columnName} }; foreignKeyConfiguration?.Invoke(foreignKey); m.ForeignKeys.Add(foreignKey); }; return this; } /// <summary> /// Overrides the Hilo sequence increment and "maximum low" number for document types that /// use numeric id's and the Hilo Id assignment /// </summary> /// <param name="settings"></param> /// <returns></returns> public DocumentMappingExpression<T> HiloSettings(HiloSettings settings) { _builder.Alter = mapping => mapping.HiloSettings = settings; return this; } /// <summary> /// Overrides the database schema name used to store the documents. /// </summary> public DocumentMappingExpression<T> DatabaseSchemaName(string databaseSchemaName) { _builder.Alter = mapping => mapping.DatabaseSchemaName = databaseSchemaName; return this; } /// <summary> /// Overrides the stragtegy used for id generation. /// </summary> public DocumentMappingExpression<T> IdStrategy(IIdGeneration idStrategy) { _builder.Alter = mapping => mapping.IdStrategy = idStrategy; return this; } /// <summary> /// Explicitly choose the identity member for this document type /// </summary> /// <param name="member"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public DocumentMappingExpression<T> Identity(Expression<Func<T, object>> member) { _builder.Alter = mapping => { var members = FindMembers.Determine(member); if (members.Length != 1) throw new InvalidOperationException( $"The expression {member} is not valid as an id column in Marten"); mapping.IdMember = members.Single(); }; return this; } /// <summary> /// Adds a Postgresql Gin index to the JSONB data column for this document type. Leads to faster /// querying, but does add overhead to storage and database writes /// </summary> /// <param name="configureIndex"></param> /// <returns></returns> public DocumentMappingExpression<T> GinIndexJsonData(Action<DocumentIndex>? configureIndex = null) { _builder.Alter = mapping => { var index = mapping.AddGinIndexToData(); configureIndex?.Invoke(index); }; return this; } /// <summary> /// Programmatically directs Marten to map this type to a hierarchy of types /// </summary> /// <param name="subclassType"></param> /// <param name="alias"></param> /// <returns></returns> public DocumentMappingExpression<T> AddSubClass(Type subclassType, string? alias = null) { _builder.Alter = mapping => mapping.SubClasses.Add(subclassType, alias); return this; } /// <summary> /// Programmatically directs Marten to map all the subclasses of <cref name="T" /> to a hierarchy of types /// </summary> /// <param name="allSubclassTypes"> /// All the subclass types of <cref name="T" /> that you wish to map. /// You can use either params of <see cref="Type" /> or <see cref="MappedType" /> or a mix, since Type can implicitly /// convert to MappedType (without an alias) /// </param> /// <returns></returns> public DocumentMappingExpression<T> AddSubClassHierarchy(params MappedType[] allSubclassTypes) { _builder.Alter = m => m.SubClasses.AddHierarchy(allSubclassTypes); return this; } /// <summary> /// Programmatically directs Marten to map all the subclasses of <cref name="T" /> to a hierarchy of types. /// <c>Unadvised in projects with many types.</c> /// </summary> /// <returns></returns> public DocumentMappingExpression<T> AddSubClassHierarchy() { _builder.Alter = m => m.SubClasses.AddHierarchy(); return this; } /// <summary> /// Add a sub class type to this document type so that Marten will store that document in the parent /// table storage /// </summary> /// <param name="alias"></param> /// <typeparam name="TSubclass"></typeparam> /// <returns></returns> public DocumentMappingExpression<T> AddSubClass<TSubclass>(string? alias = null) where TSubclass : T { return AddSubClass(typeof(TSubclass), alias); } /// <summary> /// Directs Marten to use the optimistic versioning checks upon updates /// to this document type /// </summary> /// <returns></returns> public DocumentMappingExpression<T> UseOptimisticConcurrency(bool enabled) { _builder.Alter = m => { m.UseOptimisticConcurrency = enabled; if (enabled) { m.Metadata.Version.Enabled = true; } }; return this; } /// <summary> /// Directs Marten to apply "soft deletes" to this document type /// </summary> /// <returns></returns> public DocumentMappingExpression<T> SoftDeleted() { _builder.Alter = m => m.DeleteStyle = DeleteStyle.SoftDelete; return this; } /// <summary> /// Mark this document type as soft-deleted, with an index on the is_deleted column /// </summary> /// <param name="configure"></param> /// <returns></returns> public DocumentMappingExpression<T> SoftDeletedWithIndex(Action<DocumentIndex>? configure = null) { SoftDeleted(); _builder.Alter = m => m.AddDeletedAtIndex(configure); return this; } /// <summary> /// Direct this document type's DDL to be created with the named template /// </summary> /// <param name="templateName"></param> /// <returns></returns> public DocumentMappingExpression<T> DdlTemplate(string templateName) { _builder.Alter = m => m.DdlTemplate = templateName; return this; } /// <summary> /// Marks just this document type as being stored with conjoined multi-tenancy /// </summary> /// <returns></returns> public DocumentMappingExpression<T> MultiTenanted() { _builder.Alter = m => m.TenancyStyle = TenancyStyle.Conjoined; return this; } /// <summary> /// Opt into the identity key generation strategy /// </summary> /// <returns></returns> public DocumentMappingExpression<T> UseIdentityKey() { _builder.Alter = m => m.IdStrategy = new IdentityKeyGeneration(m, m.HiloSettings); return this; } /// <summary> /// Configure the metadata storage for only this document type /// </summary> /// <param name="configure"></param> /// <returns></returns> public DocumentMappingExpression<T> Metadata(Action<MetadataConfig> configure) { var metadata = new MetadataConfig(this); configure(metadata); return this; } public class MetadataConfig { private readonly DocumentMappingExpression<T> _parent; public MetadataConfig(DocumentMappingExpression<T> parent) { _parent = parent; } /// <summary> /// The current version of this document in the database /// </summary> public Column<Guid> Version => new Column<Guid>(_parent, m => m.Version); /// <summary> /// Timestamp of the last time this document was modified /// </summary> public Column<DateTimeOffset> LastModified => new Column<DateTimeOffset>(_parent, m => m.LastModified); /// <summary> /// The stored tenant id of this document /// </summary> public Column<string> TenantId => new Column<string>(_parent, m => m.TenantId); /// <summary> /// If soft-deleted, whether or not the document is marked as deleted /// </summary> public Column<bool> IsSoftDeleted => new Column<bool>(_parent, m => m.IsSoftDeleted); /// <summary> /// If soft-deleted, the time at which the document was marked as deleted /// </summary> public Column<DateTimeOffset?> SoftDeletedAt => new Column<DateTimeOffset?>(_parent, m => m.SoftDeletedAt); /// <summary> /// If the document is part of a type hierarchy, this designates /// Marten's internal name for the sub type /// </summary> public Column<string> DocumentType => new Column<string>(_parent, m => m.DocumentType); /// <summary> /// The full name of the .Net type that was persisted /// </summary> public Column<string> DotNetType => new Column<string>(_parent, m => m.DotNetType); /// <summary> /// Optional metadata describing the correlation id for a /// unit of work /// </summary> public Column<string> CorrelationId => new Column<string>(_parent, m => m.CorrelationId); /// <summary> /// Optional metadata describing the correlation id for a /// unit of work /// </summary> public Column<string> CausationId => new Column<string>(_parent, m => m.CausationId); /// <summary> /// Optional metadata describing the user name or /// process name for this unit of work /// </summary> public Column<string> LastModifiedBy => new Column<string>(_parent, m => m.LastModifiedBy); /// <summary> /// Optional, user defined headers /// </summary> public Column<Dictionary<string, object>> Headers => new Column<Dictionary<string, object>>(_parent, m => m.Headers); public class Column<TProperty> { private readonly DocumentMappingExpression<T> _parent; private readonly Func<DocumentMetadataCollection, MetadataColumn> _source; internal Column(DocumentMappingExpression<T> parent, Func<DocumentMetadataCollection, MetadataColumn> source) { _parent = parent; _source = source; } /// <summary> /// Is the metadata field enabled. Note that this can not /// be overridden in some cases like the "version" column /// when a document uses optimistic versioning /// </summary> public bool Enabled { set { _parent._builder.Alter = m => _source(m.Metadata).Enabled = value; } } /// <summary> /// Map this metadata information to the designated Field or Property /// on the document type. This will also enable the tracking column /// in the underlying database table /// </summary> /// <param name="memberExpression"></param> public void MapTo(Expression<Func<T, TProperty>> memberExpression) { var member = FindMembers.Determine(memberExpression).Single(); _parent._builder.Alter = m => { var metadataColumn = _source(m.Metadata); metadataColumn.Enabled = true; metadataColumn.Member = member; }; } } /// <summary> /// Turn off the informational metadata columns /// in storage like the last modified, version, and /// dot net type for leaner storage /// </summary> public void DisableInformationalFields() { LastModified.Enabled = false; DotNetType.Enabled = false; Version.Enabled = false; } } } } /// <summary> /// Configures hierarchical type mapping to its parent /// </summary> public class MappedType { public MappedType(Type type, string? alias = null) { Type = type; Alias = alias; } /// <summary> /// The .Net Type /// </summary> public Type Type { get; set; } /// <summary> /// String alias that will be used to persist or load the documents /// from the underlying database /// </summary> public string? Alias { get; set; } public static implicit operator MappedType(Type type) { return new MappedType(type); } } }
// 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.InteropServices; using System.Threading; using System.Reflection.Internal; namespace System.Reflection.Metadata.Ecma335 { internal struct StringStreamReader { private static string[] s_virtualValues; internal readonly MemoryBlock Block; internal StringStreamReader(MemoryBlock block, MetadataKind metadataKind) { if (s_virtualValues == null && metadataKind != MetadataKind.Ecma335) { // Note: // Virtual values shall not contain surrogates, otherwise StartsWith might be inconsistent // when comparing to a text that ends with a high surrogate. var values = new string[(int)StringHandle.VirtualIndex.Count]; values[(int)StringHandle.VirtualIndex.System_Runtime_WindowsRuntime] = "System.Runtime.WindowsRuntime"; values[(int)StringHandle.VirtualIndex.System_Runtime] = "System.Runtime"; values[(int)StringHandle.VirtualIndex.System_ObjectModel] = "System.ObjectModel"; values[(int)StringHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml] = "System.Runtime.WindowsRuntime.UI.Xaml"; values[(int)StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime] = "System.Runtime.InteropServices.WindowsRuntime"; values[(int)StringHandle.VirtualIndex.System_Numerics_Vectors] = "System.Numerics.Vectors"; values[(int)StringHandle.VirtualIndex.Dispose] = "Dispose"; values[(int)StringHandle.VirtualIndex.AttributeTargets] = "AttributeTargets"; values[(int)StringHandle.VirtualIndex.AttributeUsageAttribute] = "AttributeUsageAttribute"; values[(int)StringHandle.VirtualIndex.Color] = "Color"; values[(int)StringHandle.VirtualIndex.CornerRadius] = "CornerRadius"; values[(int)StringHandle.VirtualIndex.DateTimeOffset] = "DateTimeOffset"; values[(int)StringHandle.VirtualIndex.Duration] = "Duration"; values[(int)StringHandle.VirtualIndex.DurationType] = "DurationType"; values[(int)StringHandle.VirtualIndex.EventHandler1] = "EventHandler`1"; values[(int)StringHandle.VirtualIndex.EventRegistrationToken] = "EventRegistrationToken"; values[(int)StringHandle.VirtualIndex.Exception] = "Exception"; values[(int)StringHandle.VirtualIndex.GeneratorPosition] = "GeneratorPosition"; values[(int)StringHandle.VirtualIndex.GridLength] = "GridLength"; values[(int)StringHandle.VirtualIndex.GridUnitType] = "GridUnitType"; values[(int)StringHandle.VirtualIndex.ICommand] = "ICommand"; values[(int)StringHandle.VirtualIndex.IDictionary2] = "IDictionary`2"; values[(int)StringHandle.VirtualIndex.IDisposable] = "IDisposable"; values[(int)StringHandle.VirtualIndex.IEnumerable] = "IEnumerable"; values[(int)StringHandle.VirtualIndex.IEnumerable1] = "IEnumerable`1"; values[(int)StringHandle.VirtualIndex.IList] = "IList"; values[(int)StringHandle.VirtualIndex.IList1] = "IList`1"; values[(int)StringHandle.VirtualIndex.INotifyCollectionChanged] = "INotifyCollectionChanged"; values[(int)StringHandle.VirtualIndex.INotifyPropertyChanged] = "INotifyPropertyChanged"; values[(int)StringHandle.VirtualIndex.IReadOnlyDictionary2] = "IReadOnlyDictionary`2"; values[(int)StringHandle.VirtualIndex.IReadOnlyList1] = "IReadOnlyList`1"; values[(int)StringHandle.VirtualIndex.KeyTime] = "KeyTime"; values[(int)StringHandle.VirtualIndex.KeyValuePair2] = "KeyValuePair`2"; values[(int)StringHandle.VirtualIndex.Matrix] = "Matrix"; values[(int)StringHandle.VirtualIndex.Matrix3D] = "Matrix3D"; values[(int)StringHandle.VirtualIndex.Matrix3x2] = "Matrix3x2"; values[(int)StringHandle.VirtualIndex.Matrix4x4] = "Matrix4x4"; values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedAction] = "NotifyCollectionChangedAction"; values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedEventArgs] = "NotifyCollectionChangedEventArgs"; values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedEventHandler] = "NotifyCollectionChangedEventHandler"; values[(int)StringHandle.VirtualIndex.Nullable1] = "Nullable`1"; values[(int)StringHandle.VirtualIndex.Plane] = "Plane"; values[(int)StringHandle.VirtualIndex.Point] = "Point"; values[(int)StringHandle.VirtualIndex.PropertyChangedEventArgs] = "PropertyChangedEventArgs"; values[(int)StringHandle.VirtualIndex.PropertyChangedEventHandler] = "PropertyChangedEventHandler"; values[(int)StringHandle.VirtualIndex.Quaternion] = "Quaternion"; values[(int)StringHandle.VirtualIndex.Rect] = "Rect"; values[(int)StringHandle.VirtualIndex.RepeatBehavior] = "RepeatBehavior"; values[(int)StringHandle.VirtualIndex.RepeatBehaviorType] = "RepeatBehaviorType"; values[(int)StringHandle.VirtualIndex.Size] = "Size"; values[(int)StringHandle.VirtualIndex.System] = "System"; values[(int)StringHandle.VirtualIndex.System_Collections] = "System.Collections"; values[(int)StringHandle.VirtualIndex.System_Collections_Generic] = "System.Collections.Generic"; values[(int)StringHandle.VirtualIndex.System_Collections_Specialized] = "System.Collections.Specialized"; values[(int)StringHandle.VirtualIndex.System_ComponentModel] = "System.ComponentModel"; values[(int)StringHandle.VirtualIndex.System_Numerics] = "System.Numerics"; values[(int)StringHandle.VirtualIndex.System_Windows_Input] = "System.Windows.Input"; values[(int)StringHandle.VirtualIndex.Thickness] = "Thickness"; values[(int)StringHandle.VirtualIndex.TimeSpan] = "TimeSpan"; values[(int)StringHandle.VirtualIndex.Type] = "Type"; values[(int)StringHandle.VirtualIndex.Uri] = "Uri"; values[(int)StringHandle.VirtualIndex.Vector2] = "Vector2"; values[(int)StringHandle.VirtualIndex.Vector3] = "Vector3"; values[(int)StringHandle.VirtualIndex.Vector4] = "Vector4"; values[(int)StringHandle.VirtualIndex.Windows_Foundation] = "Windows.Foundation"; values[(int)StringHandle.VirtualIndex.Windows_UI] = "Windows.UI"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml] = "Windows.UI.Xaml"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Controls_Primitives] = "Windows.UI.Xaml.Controls.Primitives"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media] = "Windows.UI.Xaml.Media"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation] = "Windows.UI.Xaml.Media.Animation"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Media3D] = "Windows.UI.Xaml.Media.Media3D"; s_virtualValues = values; AssertFilled(); } this.Block = TrimEnd(block); } [Conditional("DEBUG")] private static void AssertFilled() { for (int i = 0; i < s_virtualValues.Length; i++) { Debug.Assert(s_virtualValues[i] != null, "Missing virtual value for StringHandle.VirtualIndex." + (StringHandle.VirtualIndex)i); } } // Trims the alignment padding of the heap. // See StgStringPool::InitOnMem in ndp\clr\src\Utilcode\StgPool.cpp. // This is especially important for EnC. private static MemoryBlock TrimEnd(MemoryBlock block) { if (block.Length == 0) { return block; } int i = block.Length - 1; while (i >= 0 && block.PeekByte(i) == 0) { i--; } // this shouldn't happen in valid metadata: if (i == block.Length - 1) { return block; } // +1 for terminating \0 return block.GetMemoryBlockAt(0, i + 2); } internal string GetVirtualValue(StringHandle.VirtualIndex index) { return s_virtualValues[(int)index]; } internal string GetString(StringHandle handle, MetadataStringDecoder utf8Decoder) { int index = handle.Index; byte[] prefix; if (handle.IsVirtual) { switch (handle.StringKind) { case StringKind.Plain: return s_virtualValues[index]; case StringKind.WinRTPrefixed: prefix = MetadataReader.WinRTPrefix; break; default: Debug.Assert(false, "We should not get here"); return null; } } else { prefix = null; } int bytesRead; char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0'; return this.Block.PeekUtf8NullTerminated(index, prefix, utf8Decoder, out bytesRead, otherTerminator); } internal StringHandle GetNextHandle(StringHandle handle) { if (handle.IsVirtual) { return default(StringHandle); } int terminator = this.Block.IndexOf(0, handle.Index); if (terminator == -1 || terminator == Block.Length - 1) { return default(StringHandle); } return StringHandle.FromIndex((uint)(terminator + 1)); } internal bool Equals(StringHandle handle, string value, MetadataStringDecoder utf8Decoder) { Debug.Assert(value != null); if (handle.IsVirtual) { // TODO:This can allocate unnecessarily for <WinRT> prefixed handles. return GetString(handle, utf8Decoder) == value; } if (handle.IsNil) { return value.Length == 0; } // TODO: MetadataStringComparer needs to use the user-supplied encoding. // Need to pass the decoder down and use in Utf8NullTerminatedEquals. char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0'; return this.Block.Utf8NullTerminatedEquals(handle.Index, value, otherTerminator); } internal bool StartsWith(StringHandle handle, string value, MetadataStringDecoder utf8Decoder) { Debug.Assert(value != null); if (handle.IsVirtual) { // TODO:This can allocate unnecessarily for <WinRT> prefixed handles. return GetString(handle, utf8Decoder).StartsWith(value, StringComparison.Ordinal); } if (handle.IsNil) { return value.Length == 0; } // TODO: MetadataStringComparer needs to use the user-supplied encoding. // Need to pass the decoder down and use in Utf8NullTerminatedEquals. char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0'; return this.Block.Utf8NullTerminatedStartsWith(handle.Index, value, otherTerminator); } /// <summary> /// Returns true if the given raw (non-virtual) handle represents the same string as given ASCII string. /// </summary> internal bool EqualsRaw(StringHandle rawHandle, string asciiString) { Debug.Assert(!rawHandle.IsVirtual); Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported"); return this.Block.CompareUtf8NullTerminatedStringWithAsciiString(rawHandle.Index, asciiString) == 0; } /// <summary> /// Returns the heap index of the given ASCII character or -1 if not found prior null terminator or end of heap. /// </summary> internal int IndexOfRaw(int startIndex, char asciiChar) { Debug.Assert(asciiChar != 0 && asciiChar <= 0x7f); return this.Block.Utf8NullTerminatedOffsetOfAsciiChar(startIndex, asciiChar); } /// <summary> /// Returns true if the given raw (non-virtual) handle represents a string that starts with given ASCII prefix. /// </summary> internal bool StartsWithRaw(StringHandle rawHandle, string asciiPrefix) { Debug.Assert(!rawHandle.IsVirtual); Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported"); return this.Block.Utf8NullTerminatedStringStartsWithAsciiPrefix(rawHandle.Index, asciiPrefix); } /// <summary> /// Equivalent to Array.BinarySearch, searches for given raw (non-virtual) handle in given array of ASCII strings. /// </summary> internal int BinarySearchRaw(string[] asciiKeys, StringHandle rawHandle) { Debug.Assert(!rawHandle.IsVirtual); Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported"); return this.Block.BinarySearch(asciiKeys, rawHandle.Index); } } internal unsafe struct BlobStreamReader { private struct VirtualHeapBlob { public readonly GCHandle Pinned; public readonly byte[] Array; public VirtualHeapBlob(byte[] array) { Pinned = GCHandle.Alloc(array, GCHandleType.Pinned); Array = array; } } // Container for virtual heap blobs that unpins handles on finalization. // This is not handled via dispose because the only resource is managed memory. private sealed class VirtualHeapBlobTable { public readonly Dictionary<BlobHandle, VirtualHeapBlob> Table; public VirtualHeapBlobTable() { Table = new Dictionary<BlobHandle, VirtualHeapBlob>(); } ~VirtualHeapBlobTable() { if (Table != null) { foreach (var blob in Table.Values) { blob.Pinned.Free(); } } } } // Since the number of virtual blobs we need is small (the number of attribute classes in .winmd files) // we can create a pinned handle for each of them. // If we needed many more blobs we could create and pin a single byte[] and allocate blobs there. private VirtualHeapBlobTable _lazyVirtualHeapBlobs; private static byte[][] s_virtualHeapBlobs; internal readonly MemoryBlock Block; internal BlobStreamReader(MemoryBlock block, MetadataKind metadataKind) { _lazyVirtualHeapBlobs = null; this.Block = block; if (s_virtualHeapBlobs == null && metadataKind != MetadataKind.Ecma335) { var blobs = new byte[(int)BlobHandle.VirtualIndex.Count][]; blobs[(int)BlobHandle.VirtualIndex.ContractPublicKeyToken] = new byte[] { 0xB0, 0x3F, 0x5F, 0x7F, 0x11, 0xD5, 0x0A, 0x3A }; blobs[(int)BlobHandle.VirtualIndex.ContractPublicKey] = new byte[] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x07, 0xD1, 0xFA, 0x57, 0xC4, 0xAE, 0xD9, 0xF0, 0xA3, 0x2E, 0x84, 0xAA, 0x0F, 0xAE, 0xFD, 0x0D, 0xE9, 0xE8, 0xFD, 0x6A, 0xEC, 0x8F, 0x87, 0xFB, 0x03, 0x76, 0x6C, 0x83, 0x4C, 0x99, 0x92, 0x1E, 0xB2, 0x3B, 0xE7, 0x9A, 0xD9, 0xD5, 0xDC, 0xC1, 0xDD, 0x9A, 0xD2, 0x36, 0x13, 0x21, 0x02, 0x90, 0x0B, 0x72, 0x3C, 0xF9, 0x80, 0x95, 0x7F, 0xC4, 0xE1, 0x77, 0x10, 0x8F, 0xC6, 0x07, 0x77, 0x4F, 0x29, 0xE8, 0x32, 0x0E, 0x92, 0xEA, 0x05, 0xEC, 0xE4, 0xE8, 0x21, 0xC0, 0xA5, 0xEF, 0xE8, 0xF1, 0x64, 0x5C, 0x4C, 0x0C, 0x93, 0xC1, 0xAB, 0x99, 0x28, 0x5D, 0x62, 0x2C, 0xAA, 0x65, 0x2C, 0x1D, 0xFA, 0xD6, 0x3D, 0x74, 0x5D, 0x6F, 0x2D, 0xE5, 0xF1, 0x7E, 0x5E, 0xAF, 0x0F, 0xC4, 0x96, 0x3D, 0x26, 0x1C, 0x8A, 0x12, 0x43, 0x65, 0x18, 0x20, 0x6D, 0xC0, 0x93, 0x34, 0x4D, 0x5A, 0xD2, 0x93 }; blobs[(int)BlobHandle.VirtualIndex.AttributeUsage_AllowSingle] = new byte[] { // preable: 0x01, 0x00, // target (template parameter): 0x00, 0x00, 0x00, 0x00, // named arg count: 0x01, 0x00, // SERIALIZATION_TYPE_PROPERTY 0x54, // ELEMENT_TYPE_BOOLEAN 0x02, // "AllowMultiple".Length 0x0D, // "AllowMultiple" 0x41, 0x6C, 0x6C, 0x6F, 0x77, 0x4D, 0x75, 0x6C, 0x74, 0x69, 0x70, 0x6C, 0x65, // false 0x00 }; blobs[(int)BlobHandle.VirtualIndex.AttributeUsage_AllowMultiple] = new byte[] { // preable: 0x01, 0x00, // target (template parameter): 0x00, 0x00, 0x00, 0x00, // named arg count: 0x01, 0x00, // SERIALIZATION_TYPE_PROPERTY 0x54, // ELEMENT_TYPE_BOOLEAN 0x02, // "AllowMultiple".Length 0x0D, // "AllowMultiple" 0x41, 0x6C, 0x6C, 0x6F, 0x77, 0x4D, 0x75, 0x6C, 0x74, 0x69, 0x70, 0x6C, 0x65, // true 0x01 }; s_virtualHeapBlobs = blobs; } } internal byte[] GetBytes(BlobHandle handle) { if (handle.IsVirtual) { // consider: if we returned an ImmutableArray we wouldn't need to copy return GetVirtualBlobArray(handle, unique: true); } int offset = handle.Index; int bytesRead; int numberOfBytes = this.Block.PeekCompressedInteger(offset, out bytesRead); if (numberOfBytes == BlobReader.InvalidCompressedInteger) { return EmptyArray<byte>.Instance; } return this.Block.PeekBytes(offset + bytesRead, numberOfBytes); } internal BlobReader GetBlobReader(BlobHandle handle) { if (handle.IsVirtual) { if (_lazyVirtualHeapBlobs == null) { Interlocked.CompareExchange(ref _lazyVirtualHeapBlobs, new VirtualHeapBlobTable(), null); } int index = (int)handle.GetVirtualIndex(); int length = s_virtualHeapBlobs[index].Length; VirtualHeapBlob virtualBlob; lock (_lazyVirtualHeapBlobs) { if (!_lazyVirtualHeapBlobs.Table.TryGetValue(handle, out virtualBlob)) { virtualBlob = new VirtualHeapBlob(GetVirtualBlobArray(handle, unique: false)); _lazyVirtualHeapBlobs.Table.Add(handle, virtualBlob); } } return new BlobReader(new MemoryBlock((byte*)virtualBlob.Pinned.AddrOfPinnedObject(), length)); } int offset, size; Block.PeekHeapValueOffsetAndSize(handle.Index, out offset, out size); return new BlobReader(this.Block.GetMemoryBlockAt(offset, size)); } internal BlobHandle GetNextHandle(BlobHandle handle) { if (handle.IsVirtual) { return default(BlobHandle); } int offset, size; if (!Block.PeekHeapValueOffsetAndSize(handle.Index, out offset, out size)) { return default(BlobHandle); } int nextIndex = offset + size; if (nextIndex >= Block.Length) { return default(BlobHandle); } return BlobHandle.FromIndex((uint)nextIndex); } internal byte[] GetVirtualBlobArray(BlobHandle handle, bool unique) { BlobHandle.VirtualIndex index = handle.GetVirtualIndex(); byte[] result = s_virtualHeapBlobs[(int)index]; switch (index) { case BlobHandle.VirtualIndex.AttributeUsage_AllowMultiple: case BlobHandle.VirtualIndex.AttributeUsage_AllowSingle: result = (byte[])result.Clone(); handle.SubstituteTemplateParameters(result); break; default: if (unique) { result = (byte[])result.Clone(); } break; } return result; } } internal struct GuidStreamReader { internal readonly MemoryBlock Block; internal const int GuidSize = 16; public GuidStreamReader(MemoryBlock block) { this.Block = block; } internal Guid GetGuid(GuidHandle handle) { if (handle.IsNil) { return default(Guid); } // Metadata Spec: The Guid heap is an array of GUIDs, each 16 bytes wide. // Its first element is numbered 1, its second 2, and so on. return this.Block.PeekGuid((handle.Index - 1) * GuidSize); } } internal struct UserStringStreamReader { internal readonly MemoryBlock Block; public UserStringStreamReader(MemoryBlock block) { this.Block = block; } internal string GetString(UserStringHandle handle) { int offset, size; if (!Block.PeekHeapValueOffsetAndSize(handle.Index, out offset, out size)) { return string.Empty; } // Spec: Furthermore, there is an additional terminal byte (so all byte counts are odd, not even). // The size in the blob header is the length of the string in bytes + 1. return this.Block.PeekUtf16(offset, size & ~1); } internal UserStringHandle GetNextHandle(UserStringHandle handle) { int offset, size; if (!Block.PeekHeapValueOffsetAndSize(handle.Index, out offset, out size)) { return default(UserStringHandle); } int nextIndex = offset + size; if (nextIndex >= Block.Length) { return default(UserStringHandle); } return UserStringHandle.FromIndex((uint)nextIndex); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Cdn { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for CustomDomainsOperations. /// </summary> public static partial class CustomDomainsOperationsExtensions { /// <summary> /// Lists all of the existing custom domains within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> public static IPage<CustomDomain> ListByEndpoint(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName) { return operations.ListByEndpointAsync(resourceGroupName, profileName, endpointName).GetAwaiter().GetResult(); } /// <summary> /// Lists all of the existing custom domains within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<CustomDomain>> ListByEndpointAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByEndpointWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets an exisitng custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> public static CustomDomain Get(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName) { return operations.GetAsync(resourceGroupName, profileName, endpointName, customDomainName).GetAwaiter().GetResult(); } /// <summary> /// Gets an exisitng custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CustomDomain> GetAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a new custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='hostName'> /// The host name of the custom domain. Must be a domain name. /// </param> public static CustomDomain Create(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName) { return operations.CreateAsync(resourceGroupName, profileName, endpointName, customDomainName, hostName).GetAwaiter().GetResult(); } /// <summary> /// Creates a new custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='hostName'> /// The host name of the custom domain. Must be a domain name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CustomDomain> CreateAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, hostName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an existing custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> public static CustomDomain Delete(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName) { return operations.DeleteAsync(resourceGroupName, profileName, endpointName, customDomainName).GetAwaiter().GetResult(); } /// <summary> /// Deletes an existing custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CustomDomain> DeleteAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a new custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='hostName'> /// The host name of the custom domain. Must be a domain name. /// </param> public static CustomDomain BeginCreate(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName) { return operations.BeginCreateAsync(resourceGroupName, profileName, endpointName, customDomainName, hostName).GetAwaiter().GetResult(); } /// <summary> /// Creates a new custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='hostName'> /// The host name of the custom domain. Must be a domain name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CustomDomain> BeginCreateAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, hostName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an existing custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> public static CustomDomain BeginDelete(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName) { return operations.BeginDeleteAsync(resourceGroupName, profileName, endpointName, customDomainName).GetAwaiter().GetResult(); } /// <summary> /// Deletes an existing custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CustomDomain> BeginDeleteAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all of the existing custom domains within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<CustomDomain> ListByEndpointNext(this ICustomDomainsOperations operations, string nextPageLink) { return operations.ListByEndpointNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists all of the existing custom domains within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<CustomDomain>> ListByEndpointNextAsync(this ICustomDomainsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByEndpointNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System.Net; using FluentAssertions; using JsonApiDotNetCore.Serialization.Objects; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.RestrictedControllers; public sealed class WriteOnlyControllerTests : IClassFixture<IntegrationTestContext<TestableStartup<RestrictionDbContext>, RestrictionDbContext>> { private readonly IntegrationTestContext<TestableStartup<RestrictionDbContext>, RestrictionDbContext> _testContext; private readonly RestrictionFakers _fakers = new(); public WriteOnlyControllerTests(IntegrationTestContext<TestableStartup<RestrictionDbContext>, RestrictionDbContext> testContext) { _testContext = testContext; testContext.UseController<TablesController>(); } [Fact] public async Task Cannot_get_resources() { // Arrange const string route = "/tables?fields[tables]=legCount"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Forbidden); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.Forbidden); error.Title.Should().Be("The requested endpoint is not accessible."); error.Detail.Should().Be("Endpoint '/tables' is not accessible for GET requests."); } [Fact] public async Task Cannot_get_resource() { // Arrange Table table = _fakers.Table.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Tables.Add(table); await dbContext.SaveChangesAsync(); }); string route = $"/tables/{table.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Forbidden); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.Forbidden); error.Title.Should().Be("The requested endpoint is not accessible."); error.Detail.Should().Be($"Endpoint '{route}' is not accessible for GET requests."); } [Fact] public async Task Cannot_get_secondary_resources() { // Arrange Table table = _fakers.Table.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Tables.Add(table); await dbContext.SaveChangesAsync(); }); string route = $"/tables/{table.StringId}/chairs"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Forbidden); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.Forbidden); error.Title.Should().Be("The requested endpoint is not accessible."); error.Detail.Should().Be($"Endpoint '{route}' is not accessible for GET requests."); } [Fact] public async Task Cannot_get_secondary_resource() { // Arrange Table table = _fakers.Table.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Tables.Add(table); await dbContext.SaveChangesAsync(); }); string route = $"/tables/{table.StringId}/room"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Forbidden); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.Forbidden); error.Title.Should().Be("The requested endpoint is not accessible."); error.Detail.Should().Be($"Endpoint '{route}' is not accessible for GET requests."); } [Fact] public async Task Cannot_get_relationship() { // Arrange Table table = _fakers.Table.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Tables.Add(table); await dbContext.SaveChangesAsync(); }); string route = $"/tables/{table.StringId}/relationships/chairs"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Forbidden); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.Forbidden); error.Title.Should().Be("The requested endpoint is not accessible."); error.Detail.Should().Be($"Endpoint '{route}' is not accessible for GET requests."); } [Fact] public async Task Can_create_resource() { // Arrange var requestBody = new { data = new { type = "tables", attributes = new { } } }; const string route = "/tables"; // Act (HttpResponseMessage httpResponse, _) = await _testContext.ExecutePostAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); } [Fact] public async Task Can_update_resource() { // Arrange Table existingTable = _fakers.Table.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Tables.Add(existingTable); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "tables", id = existingTable.StringId, attributes = new { } } }; string route = $"/tables/{existingTable.StringId}"; // Act (HttpResponseMessage httpResponse, _) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); } [Fact] public async Task Can_delete_resource() { // Arrange Table existingTable = _fakers.Table.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Tables.Add(existingTable); await dbContext.SaveChangesAsync(); }); string route = $"/tables/{existingTable.StringId}"; // Act (HttpResponseMessage httpResponse, _) = await _testContext.ExecuteDeleteAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); } [Fact] public async Task Can_update_relationship() { // Arrange Table existingTable = _fakers.Table.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Tables.Add(existingTable); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = (object?)null }; string route = $"/tables/{existingTable.StringId}/relationships/room"; // Act (HttpResponseMessage httpResponse, _) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); } [Fact] public async Task Can_add_to_ToMany_relationship() { // Arrange Table existingTable = _fakers.Table.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Tables.Add(existingTable); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = Array.Empty<object>() }; string route = $"/tables/{existingTable.StringId}/relationships/chairs"; // Act (HttpResponseMessage httpResponse, _) = await _testContext.ExecutePostAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); } [Fact] public async Task Can_remove_from_ToMany_relationship() { // Arrange Table existingTable = _fakers.Table.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Tables.Add(existingTable); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = Array.Empty<object>() }; string route = $"/tables/{existingTable.StringId}/relationships/chairs"; // Act (HttpResponseMessage httpResponse, _) = await _testContext.ExecuteDeleteAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using size_t = System.UInt64; // TODO: IntPtr namespace System.Net.Http { internal partial class CurlHandler : HttpMessageHandler { private sealed class CurlResponseMessage : HttpResponseMessage { internal readonly EasyRequest _easy; private readonly CurlResponseStream _responseStream; internal CurlResponseMessage(EasyRequest easy) { Debug.Assert(easy != null, "Expected non-null EasyRequest"); _easy = easy; _responseStream = new CurlResponseStream(easy); RequestMessage = easy._requestMessage; Content = new StreamContent(_responseStream); } internal CurlResponseStream ResponseStream { get { return _responseStream; } } } /// <summary> /// Provides a response stream that allows libcurl to transfer data asynchronously to a reader. /// When writing data to the response stream, either all or none of the data will be transferred, /// and if none, libcurl will pause the connection until a reader is waiting to consume the data. /// Readers consume the data via ReadAsync, which registers a read state with the stream, to be /// filled in by a pending write. Read is just a thin wrapper around ReadAsync, since the underlying /// mechanism must be asynchronous to prevent blocking libcurl's processing. /// </summary> private sealed class CurlResponseStream : Stream { /// <summary>A cached task storing the Int32 value 0.</summary> private static readonly Task<int> s_zeroTask = Task.FromResult(0); /// <summary> /// A sentinel object used in the <see cref="_completed"/> field to indicate that /// the stream completed successfully. /// </summary> private static readonly Exception s_completionSentinel = new Exception("s_completionSentinel"); /// <summary>A object used to synchronize all access to state on this response stream.</summary> private readonly object _lockObject = new object(); /// <summary>The associated EasyRequest.</summary> private readonly EasyRequest _easy; /// <summary>Stores whether Dispose has been called on the stream.</summary> private bool _disposed = false; /// <summary> /// Null if the Stream has not been completed, non-null if it has been completed. /// If non-null, it'll either be the <see cref="s_completionSentinel"/> object, meaning the stream completed /// successfully, or it'll be an Exception object representing the error that caused completion. /// That error will be transferred to any subsequent read requests. /// </summary> private Exception _completed; /// <summary> /// The state associated with a pending read request. When a reader requests data, it puts /// its state here for the writer to fill in when data is available. /// </summary> private ReadState _pendingReadRequest; /// <summary> /// When data is provided by libcurl, it must be consumed all or nothing: either all of the data is consumed, or /// we must pause the connection. Since a read could need to be satisfied with only some of the data provided, /// we store the rest here until all reads can consume it. If a subsequent write callback comes in to provide /// more data, the connection will then be paused until this buffer is entirely consumed. /// </summary> private byte[] _remainingData; /// <summary> /// The offset into <see cref="_remainingData"/> from which the next read should occur. /// </summary> private int _remainingDataOffset; /// <summary> /// The remaining number of bytes in <see cref="_remainingData"/> available to be read. /// </summary> private int _remainingDataCount; internal CurlResponseStream(EasyRequest easy) { Debug.Assert(easy != null, "Expected non-null associated EasyRequest"); _easy = easy; } public override bool CanRead { get { return !_disposed; } } public override bool CanWrite { get { return false; } } public override bool CanSeek { get { return false; } } public override long Length { get { CheckDisposed(); throw new NotSupportedException(); } } public override long Position { get { CheckDisposed(); throw new NotSupportedException(); } set { CheckDisposed(); throw new NotSupportedException(); } } public override long Seek(long offset, SeekOrigin origin) { CheckDisposed(); throw new NotSupportedException(); } public override void SetLength(long value) { CheckDisposed(); throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { CheckDisposed(); throw new NotSupportedException(); } public override void Flush() { // Nothing to do. } /// <summary> /// Writes the <paramref name="length"/> bytes starting at <paramref name="pointer"/> to the stream. /// </summary> /// <returns> /// <paramref name="length"/> if all of the data was written, or /// <see cref="Interop.libcurl.CURL_WRITEFUNC_PAUSE"/> if the data wasn't copied and the connection /// should be paused until a reader is available. /// </returns> internal size_t TransferDataToStream(IntPtr pointer, long length) { Debug.Assert(pointer != IntPtr.Zero, "Expected a non-null pointer"); Debug.Assert(length >= 0, "Expected a non-negative length"); VerboseTrace("length: " + length); CheckDisposed(); // If there's no data to write, consider everything transferred. if (length == 0) { return 0; } lock (_lockObject) { VerifyInvariants(); // If there's existing data in the remaining data buffer, or if there's no pending read request, // we need to pause until the existing data is consumed or until there's a waiting read. if (_remainingDataCount > 0 || _pendingReadRequest == null) { VerboseTrace("Pausing due to _remainingDataCount: " + _remainingDataCount + ", _pendingReadRequest: " + (_pendingReadRequest != null)); return Interop.libcurl.CURL_WRITEFUNC_PAUSE; } // There's no data in the buffer and there is a pending read request. // Transfer as much data as we can to the read request, completing it. int numBytesForTask = (int)Math.Min(length, _pendingReadRequest._count); Debug.Assert(numBytesForTask > 0, "We must be copying a positive amount."); Marshal.Copy(pointer, _pendingReadRequest._buffer, _pendingReadRequest._offset, numBytesForTask); _pendingReadRequest.SetResult(numBytesForTask); ClearPendingReadRequest(); VerboseTrace("Copied to task: " + numBytesForTask); // If there's any data left, transfer it to our remaining buffer. libcurl does not support // partial transfers of data, so since we just took some of it to satisfy the read request // we must take the rest of it. (If libcurl then comes back to us subsequently with more data // before this buffered data has been consumed, at that point we won't consume any of the // subsequent offering and will ask libcurl to pause.) if (numBytesForTask < length) { IntPtr remainingPointer = pointer + numBytesForTask; _remainingDataCount = checked((int)(length - numBytesForTask)); _remainingDataOffset = 0; // Make sure our remaining data buffer exists and is big enough to hold the data if (_remainingData == null) { _remainingData = new byte[_remainingDataCount]; } else if (_remainingData.Length < _remainingDataCount) { _remainingData = new byte[Math.Max(_remainingData.Length * 2, _remainingDataCount)]; } VerboseTrace("Allocated new remainingData array of length: " + _remainingData.Length); // Copy the remaining data to the buffer Marshal.Copy(remainingPointer, _remainingData, 0, _remainingDataCount); VerboseTrace("Copied to buffer: " + _remainingDataCount); } // All of the data from libcurl was consumed. return (ulong)length; } } public override int Read(byte[] buffer, int offset, int count) { return ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult(); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0) throw new ArgumentOutOfRangeException("offset"); if (count < 0) throw new ArgumentOutOfRangeException("count"); if (offset > buffer.Length - count) throw new ArgumentException("buffer"); CheckDisposed(); VerboseTrace("buffer: " + buffer.Length + ", offset: " + offset + ", count: " + count); // Check for cancellation if (cancellationToken.IsCancellationRequested) { VerboseTrace("Canceled"); return Task.FromCanceled<int>(cancellationToken); } lock (_lockObject) { VerifyInvariants(); // If there's currently a pending read, fail this read, as we don't support concurrent reads. if (_pendingReadRequest != null) { VerboseTrace("Existing pending read"); return Task.FromException<int>(new InvalidOperationException(SR.net_http_content_no_concurrent_reads)); } // If the stream was already completed with failure, complete the read as a failure. if (_completed != null && _completed != s_completionSentinel) { VerboseTrace("Failing read with " + _completed); OperationCanceledException oce = _completed as OperationCanceledException; return (oce != null && oce.CancellationToken.IsCancellationRequested) ? Task.FromCanceled<int>(oce.CancellationToken) : Task.FromException<int>(_completed); } // Quick check for if no data was actually requested. We do this after the check // for errors so that we can still fail the read and transfer the exception if we should. if (count == 0) { VerboseTrace("Zero count"); return s_zeroTask; } // If there's any data left over from a previous call, grab as much as we can. if (_remainingDataCount > 0) { int bytesToCopy = Math.Min(count, _remainingDataCount); Array.Copy(_remainingData, _remainingDataOffset, buffer, offset, bytesToCopy); _remainingDataOffset += bytesToCopy; _remainingDataCount -= bytesToCopy; Debug.Assert(_remainingDataCount >= 0, "The remaining count should never go negative"); Debug.Assert(_remainingDataOffset <= _remainingData.Length, "The remaining offset should never exceed the buffer size"); VerboseTrace("Copied to task: " + bytesToCopy); return Task.FromResult(bytesToCopy); } // If the stream has already been completed, complete the read immediately. if (_completed == s_completionSentinel) { VerboseTrace("Completed successfully after stream completion"); return s_zeroTask; } // Finally, the stream is still alive, and we want to read some data, but there's no data // in the buffer so we need to register ourself to get the next write. if (cancellationToken.CanBeCanceled) { // If the cancellation token is cancelable, then we need to register for cancellation. // We creat a special CancelableReadState that carries with it additional info: // the cancellation token and the registration with that token. When cancellation // is requested, we schedule a work item that tries to remove the read state // from being pending, canceling it in the process. This needs to happen under the // lock, which is why we schedule the operation to run asynchronously: if it ran // synchronously, it could deadlock due to code on another thread holding the lock // and calling Dispose on the registration concurrently with the call to Cancel // the cancellation token. Dispose on the registration won't return until the action // associated with the registration has completed, but if that action is currently // executing and is blocked on the lock that's held while calling Dispose... deadlock. var crs = new CancelableReadState(buffer, offset, count, this, cancellationToken); crs._registration = cancellationToken.Register(s1 => { ((CancelableReadState)s1)._stream.VerboseTrace("Cancellation invoked. Queueing work item to cancel read state."); Task.Factory.StartNew(s2 => { var crsRef = (CancelableReadState)s2; Debug.Assert(crsRef._token.IsCancellationRequested, "We should only be here if cancellation was requested."); lock (crsRef._stream._lockObject) { if (crsRef._stream._pendingReadRequest == crsRef) { crsRef.TrySetCanceled(crsRef._token); crsRef._stream.ClearPendingReadRequest(); } } }, s1, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); }, crs); _pendingReadRequest = crs; VerboseTrace("Created pending cancelable read"); } else { // The token isn't cancelable. Just create a normal read state. _pendingReadRequest = new ReadState(buffer, offset, count); VerboseTrace("Created pending read"); } _easy._associatedMultiAgent.RequestUnpause(_easy); return _pendingReadRequest.Task; } } /// <summary>Notifies the stream that no more data will be written.</summary> internal void SignalComplete(Exception error = null) { lock (_lockObject) { VerifyInvariants(); // If we already completed, nothing more to do if (_completed != null) { return; } // Mark ourselves as being completed _completed = error != null ? error : s_completionSentinel; // If there's a pending read request, complete it, either with 0 bytes for success // or with the exception/CancellationToken for failure. if (_pendingReadRequest != null) { if (_completed == s_completionSentinel) { VerboseTrace("Completed pending read task with 0 bytes."); _pendingReadRequest.TrySetResult(0); } else { VerboseTrace("Completed pending read task with " + _completed); OperationCanceledException oce = _completed as OperationCanceledException; if (oce != null) { _pendingReadRequest.TrySetCanceled(oce.CancellationToken); } else { _pendingReadRequest.TrySetException(_completed); } } ClearPendingReadRequest(); } } } /// <summary>Clears a pending read request, making sure any cancellation registration is unregistered.</summary> private void ClearPendingReadRequest() { Debug.Assert(Monitor.IsEntered(_lockObject), "Lock object must be held to manipulate _pendingReadRequest"); Debug.Assert(_pendingReadRequest != null, "Should only be clearing the pending read request if there is one"); var crs = _pendingReadRequest as CancelableReadState; if (crs != null) { crs._registration.Dispose(); } _pendingReadRequest = null; } protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; SignalComplete(); } base.Dispose(disposing); } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } [Conditional(VerboseDebuggingConditional)] private void VerboseTrace(string text = null, [CallerMemberName] string memberName = null) { CurlHandler.VerboseTrace(text, memberName, _easy); } /// <summary>Verifies various invariants that must be true about our state.</summary> [Conditional("DEBUG")] private void VerifyInvariants() { Debug.Assert(Monitor.IsEntered(_lockObject), "Can only verify invariants while holding the lock"); Debug.Assert(_remainingDataCount >= 0, "Remaining data count should never be negative."); Debug.Assert(_remainingDataCount == 0 || _remainingData != null, "If there's remaining data, there must be a buffer to store it."); Debug.Assert(_remainingData == null || _remainingDataCount <= _remainingData.Length, "The buffer must be large enough for the data length."); Debug.Assert(_remainingData == null || _remainingDataOffset <= _remainingData.Length, "The offset must not walk off the buffer."); Debug.Assert(!((_remainingDataCount > 0) && (_pendingReadRequest != null)), "We can't have both remaining data and a pending request."); Debug.Assert(!((_completed != null) && (_pendingReadRequest != null)), "We can't both be completed and have a pending request."); Debug.Assert(_pendingReadRequest == null || !_pendingReadRequest.Task.IsCompleted, "A pending read request must not have been completed yet."); } /// <summary>State associated with a pending read request.</summary> private class ReadState : TaskCompletionSource<int> { internal readonly byte[] _buffer; internal readonly int _offset; internal readonly int _count; internal ReadState(byte[] buffer, int offset, int count) : base(TaskCreationOptions.RunContinuationsAsynchronously) { Debug.Assert(buffer != null, "Need non-null buffer"); Debug.Assert(offset >= 0, "Need non-negative offset"); Debug.Assert(count > 0, "Need positive count"); _buffer = buffer; _offset = offset; _count = count; } } /// <summary>State associated with a pending read request that's cancelable.</summary> private sealed class CancelableReadState : ReadState { internal readonly CurlResponseStream _stream; internal readonly CancellationToken _token; internal CancellationTokenRegistration _registration; internal CancelableReadState(byte[] buffer, int offset, int count, CurlResponseStream responseStream, CancellationToken cancellationToken) : base(buffer, offset, count) { _stream = responseStream; _token = cancellationToken; } } } } }
using System; using System.Collections.Generic; using System.Linq; using Autofac; using FizzWare.NBuilder; using Moq; using NUnit.Framework; using ReMi.BusinessEntities.Plugins; using ReMi.TestUtils.UnitTests; using ReMi.Contracts.Plugins.Data; using ReMi.Contracts.Plugins.Data.ReleaseContent; using ReMi.Contracts.Plugins.Services.ReleaseContent; using ReMi.DataAccess.BusinessEntityGateways.Plugins; using ReMi.Plugin.Composites.Services; namespace ReMi.Plugin.Composites.Tests.Services { public class ReleaseContentCompositeTests : TestClassFor<ReleaseContentComposite> { private Mock<IPluginGateway> _pluginGatewayMock; private Mock<IContainer> _containerMock; protected override ReleaseContentComposite ConstructSystemUnderTest() { return new ReleaseContentComposite { Container = _containerMock.Object, PluginGatewayFactory = () => _pluginGatewayMock.Object }; } protected override void TestInitialize() { _containerMock = new Mock<IContainer>(MockBehavior.Strict); _pluginGatewayMock = new Mock<IPluginGateway>(MockBehavior.Strict); _containerMock.SetupResetContainer(); base.TestInitialize(); } [Test] public void UpdateTicket_ShouldUpdateTicketProperPlugin_WhenPluginIsAssignToThePackage() { var packagePluginConfiguration = Builder<PackagePluginConfiguration>.CreateNew() .With(x => x.PluginId, Guid.NewGuid()) .With(x => x.PackageId, Guid.NewGuid()) .Build(); var tickets = Enumerable.Empty<ReleaseContentTicket>(); _pluginGatewayMock.Setup(x => x.GetPackagePluginConfiguration(packagePluginConfiguration.PackageId, PluginType.ReleaseContent)) .Returns(packagePluginConfiguration); _pluginGatewayMock.Setup(x => x.Dispose()); var releaseContentMock = new Mock<IReleaseContent>(MockBehavior.Strict); releaseContentMock.Setup(x => x.UpdateTicket(tickets, packagePluginConfiguration.PackageId)); _containerMock.SetupResolveNamed(packagePluginConfiguration.PluginId.ToString().ToUpper(), releaseContentMock.Object); Sut.UpdateTicket(tickets, packagePluginConfiguration.PackageId); _pluginGatewayMock.Verify(x => x.GetPackagePluginConfiguration(It.IsAny<Guid>(), It.IsAny<PluginType>()), Times.Once); releaseContentMock.Verify(x => x.UpdateTicket(It.IsAny<IEnumerable<ReleaseContentTicket>>(), It.IsAny<Guid>()), Times.Once); } [Test] public void GetTickets_ShouldReturnTicketsForManyPackages_WhenListOfPackagesAreAssignedToMoreThenOnePlugin() { const int packagePluginConfigurationCount = 5; var tickets1 = Builder<ReleaseContentTicket>.CreateListOfSize(1).Build(); var tickets2 = Builder<ReleaseContentTicket>.CreateListOfSize(1).Build(); var tickets3 = Builder<ReleaseContentTicket>.CreateListOfSize(1).Build(); var packagePluginConfigurations = Builder<PackagePluginConfiguration>.CreateListOfSize(packagePluginConfigurationCount) .All() .Do(x => x.PluginId = Guid.NewGuid()) .Do(x => x.PackageId = Guid.NewGuid()) .Build(); packagePluginConfigurations[1].PluginId = packagePluginConfigurations[4].PluginId; packagePluginConfigurations[3].PluginId = null; var group1 = new[] { packagePluginConfigurations[0] }; var group2 = new[] { packagePluginConfigurations[1], packagePluginConfigurations[4] }; var group3 = new[] { packagePluginConfigurations[2] }; foreach (var packagePluginConfiguration in packagePluginConfigurations) { var configuration = packagePluginConfiguration; _pluginGatewayMock.Setup(x => x.GetPackagePluginConfiguration(configuration.PackageId, PluginType.ReleaseContent)) .Returns(packagePluginConfiguration); } _pluginGatewayMock.Setup(x => x.Dispose()); var releaseContentMock1 = new Mock<IReleaseContent>(MockBehavior.Strict); releaseContentMock1.Setup(x => x.GetTickets(It.Is<IEnumerable<Guid>>(ids => ids.All(id => group1.Any(p => p.PackageId == id))))) .Returns(tickets1); _containerMock.SetupResolveNamed(group1.First().PluginId.ToString().ToUpper(), releaseContentMock1.Object); var releaseContentMock2 = new Mock<IReleaseContent>(MockBehavior.Strict); releaseContentMock2.Setup(x => x.GetTickets(It.Is<IEnumerable<Guid>>(ids => ids.All(id => group2.Any(p => p.PackageId == id))))) .Returns(tickets2); _containerMock.SetupResolveNamed(group2.First().PluginId.ToString().ToUpper(), releaseContentMock2.Object); var releaseContentMock3 = new Mock<IReleaseContent>(MockBehavior.Strict); releaseContentMock3.Setup(x => x.GetTickets(It.Is<IEnumerable<Guid>>(ids => ids.All(id => group3.Any(p => p.PackageId == id))))) .Returns(tickets3); _containerMock.SetupResolveNamed(group3.First().PluginId.ToString().ToUpper(), releaseContentMock3.Object); var actual = Sut.GetTickets(packagePluginConfigurations.Select(x => x.PackageId)); Assert.AreEqual(3, actual.Count()); Assert.IsTrue(actual.Contains(tickets1.First())); Assert.IsTrue(actual.Contains(tickets2.First())); Assert.IsTrue(actual.Contains(tickets3.First())); _pluginGatewayMock.Verify(x => x.GetPackagePluginConfiguration(It.IsAny<Guid>(), It.IsAny<PluginType>()), Times.Exactly(packagePluginConfigurationCount)); releaseContentMock1.Verify(x => x.GetTickets(It.IsAny<IEnumerable<Guid>>()), Times.Once); releaseContentMock2.Verify(x => x.GetTickets(It.IsAny<IEnumerable<Guid>>()), Times.Once); releaseContentMock3.Verify(x => x.GetTickets(It.IsAny<IEnumerable<Guid>>()), Times.Once); } [Test] public void GetTickets_ShouldReturnEmptyCollection_WhenPackagesDoesnotHaveReleaseContentPluginAssociated() { const int packagePluginConfigurationCount = 5; var packagePluginConfigurations = Builder<PackagePluginConfiguration>.CreateListOfSize(packagePluginConfigurationCount) .All() .Do(x => x.PluginId = null) .Do(x => x.PackageId = Guid.NewGuid()) .Build(); foreach (var packagePluginConfiguration in packagePluginConfigurations) { var configuration = packagePluginConfiguration; _pluginGatewayMock.Setup(x => x.GetPackagePluginConfiguration(configuration.PackageId, PluginType.ReleaseContent)) .Returns(packagePluginConfiguration); } _pluginGatewayMock.Setup(x => x.Dispose()); var actual = Sut.GetTickets(packagePluginConfigurations.Select(x => x.PackageId)); Assert.IsEmpty(actual); _pluginGatewayMock.Verify(x => x.GetPackagePluginConfiguration(It.IsAny<Guid>(), It.IsAny<PluginType>()), Times.Exactly(packagePluginConfigurationCount)); } [Test] public void GetDefectTickets_ShouldReturnTicketsForManyPackages_WhenListOfPackagesAreAssignedToMoreThenOnePlugin() { const int packagePluginConfigurationCount = 5; var tickets1 = Builder<ReleaseContentTicket>.CreateListOfSize(1).Build(); var tickets2 = Builder<ReleaseContentTicket>.CreateListOfSize(1).Build(); var tickets3 = Builder<ReleaseContentTicket>.CreateListOfSize(1).Build(); var packagePluginConfigurations = Builder<PackagePluginConfiguration>.CreateListOfSize(packagePluginConfigurationCount) .All() .Do(x => x.PluginId = Guid.NewGuid()) .Do(x => x.PackageId = Guid.NewGuid()) .Build(); packagePluginConfigurations[1].PluginId = packagePluginConfigurations[4].PluginId; packagePluginConfigurations[3].PluginId = null; var group1 = new[] { packagePluginConfigurations[0] }; var group2 = new[] { packagePluginConfigurations[1], packagePluginConfigurations[4] }; var group3 = new[] { packagePluginConfigurations[2] }; foreach (var packagePluginConfiguration in packagePluginConfigurations) { var configuration = packagePluginConfiguration; _pluginGatewayMock.Setup(x => x.GetPackagePluginConfiguration(configuration.PackageId, PluginType.ReleaseContent)) .Returns(packagePluginConfiguration); } _pluginGatewayMock.Setup(x => x.Dispose()); var releaseContentMock1 = new Mock<IReleaseContent>(MockBehavior.Strict); releaseContentMock1.Setup(x => x.GetDefectTickets(It.Is<IEnumerable<Guid>>(ids => ids.All(id => group1.Any(p => p.PackageId == id))))) .Returns(tickets1); _containerMock.SetupResolveNamed(group1.First().PluginId.ToString().ToUpper(), releaseContentMock1.Object); var releaseContentMock2 = new Mock<IReleaseContent>(MockBehavior.Strict); releaseContentMock2.Setup(x => x.GetDefectTickets(It.Is<IEnumerable<Guid>>(ids => ids.All(id => group2.Any(p => p.PackageId == id))))) .Returns(tickets2); _containerMock.SetupResolveNamed(group2.First().PluginId.ToString().ToUpper(), releaseContentMock2.Object); var releaseContentMock3 = new Mock<IReleaseContent>(MockBehavior.Strict); releaseContentMock3.Setup(x => x.GetDefectTickets(It.Is<IEnumerable<Guid>>(ids => ids.All(id => group3.Any(p => p.PackageId == id))))) .Returns(tickets3); _containerMock.SetupResolveNamed(group3.First().PluginId.ToString().ToUpper(), releaseContentMock3.Object); var actual = Sut.GetDefectTickets(packagePluginConfigurations.Select(x => x.PackageId)); Assert.AreEqual(3, actual.Count()); Assert.IsTrue(actual.Contains(tickets1.First())); Assert.IsTrue(actual.Contains(tickets2.First())); Assert.IsTrue(actual.Contains(tickets3.First())); _pluginGatewayMock.Verify(x => x.GetPackagePluginConfiguration(It.IsAny<Guid>(), It.IsAny<PluginType>()), Times.Exactly(packagePluginConfigurationCount)); releaseContentMock1.Verify(x => x.GetDefectTickets(It.IsAny<IEnumerable<Guid>>()), Times.Once); releaseContentMock2.Verify(x => x.GetDefectTickets(It.IsAny<IEnumerable<Guid>>()), Times.Once); releaseContentMock3.Verify(x => x.GetDefectTickets(It.IsAny<IEnumerable<Guid>>()), Times.Once); } [Test] public void GetDefectTickets_ShouldReturnEmptyCollection_WhenPackagesDoesnotHaveReleaseContentPluginAssociated() { const int packagePluginConfigurationCount = 5; var packagePluginConfigurations = Builder<PackagePluginConfiguration>.CreateListOfSize(packagePluginConfigurationCount) .All() .Do(x => x.PluginId = null) .Do(x => x.PackageId = Guid.NewGuid()) .Build(); foreach (var packagePluginConfiguration in packagePluginConfigurations) { var configuration = packagePluginConfiguration; _pluginGatewayMock.Setup(x => x.GetPackagePluginConfiguration(configuration.PackageId, PluginType.ReleaseContent)) .Returns(packagePluginConfiguration); } _pluginGatewayMock.Setup(x => x.Dispose()); var actual = Sut.GetDefectTickets(packagePluginConfigurations.Select(x => x.PackageId)); Assert.IsEmpty(actual); _pluginGatewayMock.Verify(x => x.GetPackagePluginConfiguration(It.IsAny<Guid>(), It.IsAny<PluginType>()), Times.Exactly(packagePluginConfigurationCount)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // long chain of methods using System; internal class test { private static int f1(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a1); int sum = f2(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f2(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a2); int sum = f3(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f3(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a3); int sum = f4(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f4(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a4); int sum = f5(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f5(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a5); int sum = f6(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f6(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a6); int sum = f7(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f7(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a7); int sum = f8(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f8(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a8); int sum = f9(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f9(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a9); int sum = f10(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f10(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a10); int sum = f11(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f11(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a11); int sum = f12(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f12(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a12); int sum = f13(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f13(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a13); int sum = f14(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f14(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a14); int sum = f15(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f15(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a15); int sum = f16(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f16(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a16); int sum = f17(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f17(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a17); int sum = f18(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f18(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a18); int sum = f19(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f19(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a19); int sum = f20(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f20(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a20); int sum = f21(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f21(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a21); int sum = f22(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f22(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a22); int sum = f23(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f23(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a23); int sum = f24(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f24(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a24); int sum = f25(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int f25(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { Console.WriteLine(a25); int sum = a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a20 + a21 + a22 + a23 + a24 + a25; return sum; } private static int f(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25) { int sum = f1(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25); return sum; } private static int Main() { Console.WriteLine("Testing method of 25 parameters, all of int data type, long chain of method calls"); int sum = f(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25); Console.WriteLine("The sum is {0}", sum); if (sum == 325) return 100; else return 1; } }
// This file is part of YamlDotNet - A .NET library for YAML. // Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Antoine Aubry // Copyright (c) 2011 Andy Pickett // 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.Text; using YamlDotNet.Core; using YamlDotNet.Core.Events; namespace YamlDotNet.RepresentationModel { /// <summary> /// Represents a mapping node in the YAML document. /// </summary> public class YamlMappingNode : YamlNode, IEnumerable<KeyValuePair<YamlNode, YamlNode>> { private readonly IDictionary<YamlNode, YamlNode> children = new Dictionary<YamlNode, YamlNode>(); /// <summary> /// Gets the children of the current node. /// </summary> /// <value>The children.</value> public IDictionary<YamlNode, YamlNode> Children { get { return children; } } /// <summary> /// Gets or sets the style of the node. /// </summary> /// <value>The style.</value> public MappingStyle Style { get; set; } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> /// <param name="events">The events.</param> /// <param name="state">The state.</param> internal YamlMappingNode(EventReader events, DocumentLoadingState state) { MappingStart mapping = events.Expect<MappingStart>(); Load(mapping, state); bool hasUnresolvedAliases = false; while (!events.Accept<MappingEnd>()) { YamlNode key = ParseNode(events, state); YamlNode value = ParseNode(events, state); try { children.Add(key, value); } catch (ArgumentException err) { throw new YamlException(key.Start, key.End, "Duplicate key", err); } hasUnresolvedAliases |= key is YamlAliasNode || value is YamlAliasNode; } if (hasUnresolvedAliases) { state.AddNodeWithUnresolvedAliases(this); } #if DEBUG else { foreach (var child in children) { if (child.Key is YamlAliasNode) { throw new InvalidOperationException("Error in alias resolution."); } if (child.Value is YamlAliasNode) { throw new InvalidOperationException("Error in alias resolution."); } } } #endif events.Expect<MappingEnd>(); } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> public YamlMappingNode() { } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> public YamlMappingNode(params KeyValuePair<YamlNode, YamlNode>[] children) : this((IEnumerable<KeyValuePair<YamlNode, YamlNode>>)children) { } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> public YamlMappingNode(IEnumerable<KeyValuePair<YamlNode, YamlNode>> children) { foreach (var child in children) { this.children.Add(child); } } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> /// <param name="children">A sequence of <see cref="YamlNode"/> where even elements are keys and odd elements are values.</param> public YamlMappingNode(params YamlNode[] children) : this((IEnumerable<YamlNode>)children) { } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> /// <param name="children">A sequence of <see cref="YamlNode"/> where even elements are keys and odd elements are values.</param> public YamlMappingNode(IEnumerable<YamlNode> children) { using (var enumerator = children.GetEnumerator()) { while (enumerator.MoveNext()) { var key = enumerator.Current; if (!enumerator.MoveNext()) { throw new ArgumentException("When constructing a mapping node with a sequence, the number of elements of the sequence must be even."); } Add(key, enumerator.Current); } } } /// <summary> /// Adds the specified mapping to the <see cref="Children"/> collection. /// </summary> /// <param name="key">The key node.</param> /// <param name="value">The value node.</param> public void Add(YamlNode key, YamlNode value) { children.Add(key, value); } /// <summary> /// Adds the specified mapping to the <see cref="Children"/> collection. /// </summary> /// <param name="key">The key node.</param> /// <param name="value">The value node.</param> public void Add(string key, YamlNode value) { children.Add(new YamlScalarNode(key), value); } /// <summary> /// Adds the specified mapping to the <see cref="Children"/> collection. /// </summary> /// <param name="key">The key node.</param> /// <param name="value">The value node.</param> public void Add(YamlNode key, string value) { children.Add(key, new YamlScalarNode(value)); } /// <summary> /// Adds the specified mapping to the <see cref="Children"/> collection. /// </summary> /// <param name="key">The key node.</param> /// <param name="value">The value node.</param> public void Add(string key, string value) { children.Add(new YamlScalarNode(key), new YamlScalarNode(value)); } /// <summary> /// Resolves the aliases that could not be resolved when the node was created. /// </summary> /// <param name="state">The state of the document.</param> internal override void ResolveAliases(DocumentLoadingState state) { Dictionary<YamlNode, YamlNode> keysToUpdate = null; Dictionary<YamlNode, YamlNode> valuesToUpdate = null; foreach (var entry in children) { if (entry.Key is YamlAliasNode) { if (keysToUpdate == null) { keysToUpdate = new Dictionary<YamlNode, YamlNode>(); } keysToUpdate.Add(entry.Key, state.GetNode(entry.Key.Anchor, true, entry.Key.Start, entry.Key.End)); } if (entry.Value is YamlAliasNode) { if (valuesToUpdate == null) { valuesToUpdate = new Dictionary<YamlNode, YamlNode>(); } valuesToUpdate.Add(entry.Key, state.GetNode(entry.Value.Anchor, true, entry.Value.Start, entry.Value.End)); } } if (valuesToUpdate != null) { foreach (var entry in valuesToUpdate) { children[entry.Key] = entry.Value; } } if (keysToUpdate != null) { foreach (var entry in keysToUpdate) { YamlNode value = children[entry.Key]; children.Remove(entry.Key); children.Add(entry.Value, value); } } } /// <summary> /// Saves the current node to the specified emitter. /// </summary> /// <param name="emitter">The emitter where the node is to be saved.</param> /// <param name="state">The state.</param> internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new MappingStart(Anchor, Tag, true, Style)); foreach (var entry in children) { entry.Key.Save(emitter, state); entry.Value.Save(emitter, state); } emitter.Emit(new MappingEnd()); } /// <summary> /// Accepts the specified visitor by calling the appropriate Visit method on it. /// </summary> /// <param name="visitor"> /// A <see cref="IYamlVisitor"/>. /// </param> public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } /// <summary /> public override bool Equals(object other) { var obj = other as YamlMappingNode; if (obj == null || !Equals(obj) || children.Count != obj.children.Count) { return false; } foreach (var entry in children) { YamlNode otherNode; if (!obj.children.TryGetValue(entry.Key, out otherNode) || !SafeEquals(entry.Value, otherNode)) { return false; } } return true; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { var hashCode = base.GetHashCode(); foreach (var entry in children) { hashCode = CombineHashCodes(hashCode, GetHashCode(entry.Key)); hashCode = CombineHashCodes(hashCode, GetHashCode(entry.Value)); } return hashCode; } /// <summary> /// Gets all nodes from the document, starting on the current node. /// </summary> public override IEnumerable<YamlNode> AllNodes { get { yield return this; foreach (var child in children) { foreach (var node in child.Key.AllNodes) { yield return node; } foreach (var node in child.Value.AllNodes) { yield return node; } } } } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { var text = new StringBuilder("{ "); foreach (var child in children) { if (text.Length > 2) { text.Append(", "); } text.Append("{ ").Append(child.Key).Append(", ").Append(child.Value).Append(" }"); } text.Append(" }"); return text.ToString(); } #region IEnumerable<KeyValuePair<YamlNode,YamlNode>> Members /// <summary /> public IEnumerator<KeyValuePair<YamlNode, YamlNode>> GetEnumerator() { return children.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }
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 WebApiExternalAuth.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>(); } /// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and 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)) { 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="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <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.ActionDescriptor.ReturnType; 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, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Foundation; using ObjCRuntime; using FM; using FM.IceLink; using FM.IceLink.WebRTC; using Xamarin.iOS.Opus; namespace Xamarin.Forms.Conference.WebRTC.iOS.Opus { /// <summary> /// Opus codec wrapper for Xamarin.iOS. /// </summary> class OpusCodec : AudioCodec { private CocoaOpusEncoder _Encoder; private CocoaOpusDecoder _Decoder; private BasicAudioPadep _Padep; /// <summary> /// Gets or sets the loss percentage (0-100) /// before forward error correction (FEC) is /// activated (only if supported by the remote peer). /// Affects encoded data only. /// Defaults to 5. /// </summary> public int PercentLossToTriggerFEC { get; set; } /// <summary> /// Gets or sets a value indicating whether to /// disable forward error correction (FEC) completely. /// If set to true, FEC will never activate. /// Affects encoded data only. /// Defaults to false. /// </summary> public bool DisableFEC { get; set; } /// <summary> /// Gets or sets a value indicating whether forward /// error correction (FEC) is currently active. /// </summary> public bool FecActive { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="OpusCodec"/> class. /// </summary> public OpusCodec() : base(20) { DisableFEC = false; PercentLossToTriggerFEC = 5; _Padep = new BasicAudioPadep(); } /// <summary> /// Encodes a frame. /// </summary> /// <param name="frame">The frame.</param> /// <returns></returns> public override byte[] Encode(AudioBuffer frame) { if (_Encoder == null) { _Encoder = new CocoaOpusEncoder(ClockRate, Channels, PacketTime); _Encoder.Quality = 1.0; _Encoder.Bitrate = 125; } using (var pool = new NSAutoreleasePool()) { GCHandle dataHandle = GCHandle.Alloc(frame.Data, GCHandleType.Pinned); try { IntPtr dataPointer = dataHandle.AddrOfPinnedObject(); using (var buffer = new CocoaOpusBuffer { Data = NSData.FromBytesNoCopy(dataPointer, (uint)frame.Data.Length, false), Index = frame.Index, Length = frame.Length }) { using (var encodedFrameData = _Encoder.EncodeBuffer(buffer)) { return encodedFrameData.ToArray(); } } } finally { dataHandle.Free(); } } } private int CurrentRTPSequenceNumber = -1; private int LastRTPSequenceNumber = -1; /// <summary> /// Decodes an encoded frame. /// </summary> /// <param name="encodedFrame">The encoded frame.</param> /// <returns></returns> public override AudioBuffer Decode(byte[] encodedFrame) { if (_Decoder == null) { _Decoder = new CocoaOpusDecoder(ClockRate, Channels, PacketTime); Link.GetRemoteStream().DisablePLC = true; } if (LastRTPSequenceNumber == -1) { LastRTPSequenceNumber = CurrentRTPSequenceNumber; return DecodeNormal(encodedFrame); } else { var sequenceNumberDelta = RTPPacket.GetSequenceNumberDelta(CurrentRTPSequenceNumber, LastRTPSequenceNumber); LastRTPSequenceNumber = CurrentRTPSequenceNumber; var missingPacketCount = sequenceNumberDelta - 1; var previousFrames = new AudioBuffer[missingPacketCount]; var plcFrameCount = (missingPacketCount > 1) ? missingPacketCount - 1 : 0; if (plcFrameCount > 0) { Log.InfoFormat("Adding {0} frames of loss concealment to incoming audio stream. Packet sequence violated.", plcFrameCount.ToString()); for (var i = 0; i < plcFrameCount; i++) { previousFrames[i] = DecodePLC(); } } var fecFrameCount = (missingPacketCount > 0) ? 1 : 0; if (fecFrameCount > 0) { var fecFrame = DecodeFEC(encodedFrame); var fecFrameIndex = missingPacketCount - 1; if (fecFrame == null) { previousFrames[fecFrameIndex] = DecodePLC(); } else { previousFrames[fecFrameIndex] = fecFrame; } } var frame = DecodeNormal(encodedFrame); frame.PreviousBuffers = previousFrames; return frame; } } private AudioBuffer DecodePLC() { return Decode(null, false); } private AudioBuffer DecodeFEC(byte[] encodedFrame) { return Decode(encodedFrame, true); } private AudioBuffer DecodeNormal(byte[] encodedFrame) { return Decode(encodedFrame, false); } private AudioBuffer Decode(byte[] encodedFrame, bool fec) { using (var pool = new NSAutoreleasePool()) { GCHandle encodedFrameHandle = GCHandle.Alloc(encodedFrame, GCHandleType.Pinned); try { IntPtr encodedFramePointer = encodedFrame == null ? IntPtr.Zero : encodedFrameHandle.AddrOfPinnedObject(); using (var encodedFrameData = encodedFrame == null ? null : NSData.FromBytesNoCopy(encodedFramePointer, (uint)encodedFrame.Length, false)) { using (var buffer = _Decoder.DecodeFrame(encodedFrameData, fec)) { if (buffer == null) { return null; } var frame = new byte[buffer.Length]; Marshal.Copy(buffer.Data.Bytes, frame, buffer.Index, buffer.Length); return new AudioBuffer(frame, 0, frame.Length); } } } finally { encodedFrameHandle.Free(); } } } /// <summary> /// Packetizes an encoded frame. /// </summary> /// <param name="encodedFrame">The encoded frame.</param> /// <returns></returns> public override RTPPacket[] Packetize(byte[] encodedFrame) { return _Padep.Packetize(encodedFrame, ClockRate, PacketTime, ResetTimestamp); } /// <summary> /// Depacketizes a packet. /// </summary> /// <param name="packet">The packet.</param> /// <returns></returns> public override byte[] Depacketize(RTPPacket packet) { CurrentRTPSequenceNumber = packet.SequenceNumber; return _Padep.Depacketize(packet); } private int _LossyCount = 0; private int _LosslessCount = 0; private int _MinimumReportsBeforeFEC = 1; private long _ReportsReceived = 0; /// <summary> /// Processes RTCP packets. /// </summary> /// <param name="packets">The packets to process.</param> public override void ProcessRTCP(RTCPPacket[] packets) { if (_Encoder != null) { foreach (var packet in packets) { if (packet is RTCPReportPacket) { _ReportsReceived++; var report = (RTCPReportPacket)packet; foreach (var block in report.ReportBlocks) { Log.DebugFormat("Opus report: {0} packet loss ({1} cumulative packets lost)", block.PercentLost.ToString("P2"), block.CumulativeNumberOfPacketsLost.ToString()); if (block.PercentLost > 0) { _LosslessCount = 0; _LossyCount++; if (_LossyCount > 5 && _Encoder.Quality > 0.0) { _LossyCount = 0; _Encoder.Quality = MathAssistant.Max(0.0, _Encoder.Quality - 0.1); Log.InfoFormat("Decreasing Opus encoder quality to {0}.", _Encoder.Quality.ToString("P2")); } } else { _LossyCount = 0; _LosslessCount++; if (_LosslessCount > 5 && _Encoder.Quality < 1.0) { _LosslessCount = 0; _Encoder.Quality = MathAssistant.Min(1.0, _Encoder.Quality + 0.1); Log.InfoFormat("Increasing Opus encoder quality to {0}.", _Encoder.Quality.ToString("P2")); } } if (!DisableFEC && !FecActive && _ReportsReceived > _MinimumReportsBeforeFEC) { if ((block.PercentLost * 100) > PercentLossToTriggerFEC) { Log.InfoFormat("Activating FEC for Opus audio stream."); _Encoder.ActivateFEC(PercentLossToTriggerFEC); FecActive = true; } } } } } } } /// <summary> /// Destroys the codec. /// </summary> public override void Destroy() { if (_Encoder != null) { _Encoder.Destroy(); _Encoder.Dispose(); _Encoder = null; } if (_Decoder != null) { _Decoder.Destroy(); _Decoder.Dispose(); _Decoder = null; } } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using CALI.Database.Contracts; using CALI.Database.Contracts.Data; /////////////////////////////////////////////////////////// //Do not modify this file. Use a partial class to extend.// /////////////////////////////////////////////////////////// // This file contains static implementations of the QueryLogic // Add your own static methods by making a new partial class. // You cannot override static methods, instead override the methods // located in QueryLogicBase by making a partial class of QueryLogic // and overriding the base methods. namespace CALI.Database.Logic.Data { public partial class QueryLogic { //Put your code in a separate file. This is auto generated. /// <summary> /// Run Query_Insert. /// </summary> /// <param name="fldText">Value for Text</param> /// <param name="fldPoviderSource">Value for PoviderSource</param> /// <param name="fldProcessorUsed">Value for ProcessorUsed</param> /// <param name="fldExceptions">Value for Exceptions</param> /// <param name="fldIsSuccess">Value for IsSuccess</param> public static int? InsertNow(string fldText , string fldPoviderSource , string fldProcessorUsed , string fldExceptions , bool fldIsSuccess ) { return (new QueryLogic()).Insert(fldText , fldPoviderSource , fldProcessorUsed , fldExceptions , fldIsSuccess ); } /// <summary> /// Run Query_Insert. /// </summary> /// <param name="fldText">Value for Text</param> /// <param name="fldPoviderSource">Value for PoviderSource</param> /// <param name="fldProcessorUsed">Value for ProcessorUsed</param> /// <param name="fldExceptions">Value for Exceptions</param> /// <param name="fldIsSuccess">Value for IsSuccess</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> public static int? InsertNow(string fldText , string fldPoviderSource , string fldProcessorUsed , string fldExceptions , bool fldIsSuccess , SqlConnection connection, SqlTransaction transaction) { return (new QueryLogic()).Insert(fldText , fldPoviderSource , fldProcessorUsed , fldExceptions , fldIsSuccess , connection, transaction); } /// <summary> /// Insert by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public static int InsertNow(QueryContract row) { return (new QueryLogic()).Insert(row); } /// <summary> /// Insert by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int InsertNow(QueryContract row, SqlConnection connection, SqlTransaction transaction) { return (new QueryLogic()).Insert(row, connection, transaction); } /// <summary> /// Insert the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Insert</param> /// <returns>The number of rows affected.</returns> public static int InsertAllNow(List<QueryContract> rows) { return (new QueryLogic()).InsertAll(rows); } /// <summary> /// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Insert</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int InsertAllNow(List<QueryContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new QueryLogic()).InsertAll(rows, connection, transaction); } /// <summary> /// Run Query_Update. /// </summary> /// <param name="fldQueryId">Value for QueryId</param> /// <param name="fldText">Value for Text</param> /// <param name="fldPoviderSource">Value for PoviderSource</param> /// <param name="fldProcessorUsed">Value for ProcessorUsed</param> /// <param name="fldExceptions">Value for Exceptions</param> /// <param name="fldIsSuccess">Value for IsSuccess</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(int fldQueryId , string fldText , string fldPoviderSource , string fldProcessorUsed , string fldExceptions , bool fldIsSuccess ) { return (new QueryLogic()).Update(fldQueryId , fldText , fldPoviderSource , fldProcessorUsed , fldExceptions , fldIsSuccess ); } /// <summary> /// Run Query_Update. /// </summary> /// <param name="fldQueryId">Value for QueryId</param> /// <param name="fldText">Value for Text</param> /// <param name="fldPoviderSource">Value for PoviderSource</param> /// <param name="fldProcessorUsed">Value for ProcessorUsed</param> /// <param name="fldExceptions">Value for Exceptions</param> /// <param name="fldIsSuccess">Value for IsSuccess</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(int fldQueryId , string fldText , string fldPoviderSource , string fldProcessorUsed , string fldExceptions , bool fldIsSuccess , SqlConnection connection, SqlTransaction transaction) { return (new QueryLogic()).Update(fldQueryId , fldText , fldPoviderSource , fldProcessorUsed , fldExceptions , fldIsSuccess , connection, transaction); } /// <summary> /// Update by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(QueryContract row) { return (new QueryLogic()).Update(row); } /// <summary> /// Update by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(QueryContract row, SqlConnection connection, SqlTransaction transaction) { return (new QueryLogic()).Update(row, connection, transaction); } /// <summary> /// Update the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Update</param> /// <returns>The number of rows affected.</returns> public static int UpdateAllNow(List<QueryContract> rows) { return (new QueryLogic()).UpdateAll(rows); } /// <summary> /// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Update</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateAllNow(List<QueryContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new QueryLogic()).UpdateAll(rows, connection, transaction); } /// <summary> /// Run Query_Delete. /// </summary> /// <param name="fldQueryId">Value for QueryId</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(int fldQueryId ) { return (new QueryLogic()).Delete(fldQueryId ); } /// <summary> /// Run Query_Delete. /// </summary> /// <param name="fldQueryId">Value for QueryId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(int fldQueryId , SqlConnection connection, SqlTransaction transaction) { return (new QueryLogic()).Delete(fldQueryId , connection, transaction); } /// <summary> /// Delete by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(QueryContract row) { return (new QueryLogic()).Delete(row); } /// <summary> /// Delete by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(QueryContract row, SqlConnection connection, SqlTransaction transaction) { return (new QueryLogic()).Delete(row, connection, transaction); } /// <summary> /// Delete the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Delete</param> /// <returns>The number of rows affected.</returns> public static int DeleteAllNow(List<QueryContract> rows) { return (new QueryLogic()).DeleteAll(rows); } /// <summary> /// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Delete</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteAllNow(List<QueryContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new QueryLogic()).DeleteAll(rows, connection, transaction); } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldQueryId">Value for QueryId</param> /// <returns>True, if the values exist, or false.</returns> public static bool ExistsNow(int fldQueryId ) { return (new QueryLogic()).Exists(fldQueryId ); } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldQueryId">Value for QueryId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>True, if the values exist, or false.</returns> public static bool ExistsNow(int fldQueryId , SqlConnection connection, SqlTransaction transaction) { return (new QueryLogic()).Exists(fldQueryId , connection, transaction); } /// <summary> /// Run Query_Search, and return results as a list of QueryRow. /// </summary> /// <param name="fldText">Value for Text</param> /// <param name="fldPoviderSource">Value for PoviderSource</param> /// <param name="fldProcessorUsed">Value for ProcessorUsed</param> /// <param name="fldExceptions">Value for Exceptions</param> /// <returns>A collection of QueryRow.</returns> public static List<QueryContract> SearchNow(string fldText , string fldPoviderSource , string fldProcessorUsed , string fldExceptions ) { var driver = new QueryLogic(); driver.Search(fldText , fldPoviderSource , fldProcessorUsed , fldExceptions ); return driver.Results; } /// <summary> /// Run Query_Search, and return results as a list of QueryRow. /// </summary> /// <param name="fldText">Value for Text</param> /// <param name="fldPoviderSource">Value for PoviderSource</param> /// <param name="fldProcessorUsed">Value for ProcessorUsed</param> /// <param name="fldExceptions">Value for Exceptions</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of QueryRow.</returns> public static List<QueryContract> SearchNow(string fldText , string fldPoviderSource , string fldProcessorUsed , string fldExceptions , SqlConnection connection, SqlTransaction transaction) { var driver = new QueryLogic(); driver.Search(fldText , fldPoviderSource , fldProcessorUsed , fldExceptions , connection, transaction); return driver.Results; } /// <summary> /// Run Query_SelectAll, and return results as a list of QueryRow. /// </summary> /// <returns>A collection of QueryRow.</returns> public static List<QueryContract> SelectAllNow() { var driver = new QueryLogic(); driver.SelectAll(); return driver.Results; } /// <summary> /// Run Query_SelectAll, and return results as a list of QueryRow. /// </summary> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of QueryRow.</returns> public static List<QueryContract> SelectAllNow(SqlConnection connection, SqlTransaction transaction) { var driver = new QueryLogic(); driver.SelectAll(connection, transaction); return driver.Results; } /// <summary> /// Run Query_SelectBy_QueryId, and return results as a list of QueryRow. /// </summary> /// <param name="fldQueryId">Value for QueryId</param> /// <returns>A collection of QueryRow.</returns> public static List<QueryContract> SelectBy_QueryIdNow(int fldQueryId ) { var driver = new QueryLogic(); driver.SelectBy_QueryId(fldQueryId ); return driver.Results; } /// <summary> /// Run Query_SelectBy_QueryId, and return results as a list of QueryRow. /// </summary> /// <param name="fldQueryId">Value for QueryId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of QueryRow.</returns> public static List<QueryContract> SelectBy_QueryIdNow(int fldQueryId , SqlConnection connection, SqlTransaction transaction) { var driver = new QueryLogic(); driver.SelectBy_QueryId(fldQueryId , connection, transaction); return driver.Results; } /// <summary> /// Read all Query rows from the provided reader into the list structure of QueryRows /// </summary> /// <param name="reader">The result of running a sql command.</param> /// <returns>A populated QueryRows or an empty QueryRows if there are no results.</returns> public static List<QueryContract> ReadAllNow(SqlDataReader reader) { var driver = new QueryLogic(); driver.ReadAll(reader); return driver.Results; } /// <summary>"); /// Advance one, and read values into a Query /// </summary> /// <param name="reader">The result of running a sql command.</param>"); /// <returns>A Query or null if there are no results.</returns> public static QueryContract ReadOneNow(SqlDataReader reader) { var driver = new QueryLogic(); return driver.ReadOne(reader) ? driver.Results[0] : null; } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <returns>The number of rows affected.</returns> public static int SaveNow(QueryContract row) { if(row.QueryId == null) { return InsertNow(row); } else { return UpdateNow(row); } } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int SaveNow(QueryContract row, SqlConnection connection, SqlTransaction transaction) { if(row.QueryId == null) { return InsertNow(row, connection, transaction); } else { return UpdateNow(row, connection, transaction); } } /// <summary> /// Save the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Save</param> /// <returns>The number of rows affected.</returns> public static int SaveAllNow(List<QueryContract> rows) { return (new QueryLogic()).SaveAll(rows); } /// <summary> /// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int SaveAllNow(List<QueryContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new QueryLogic()).SaveAll(rows, connection, transaction); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /* ** Copyright (c) Microsoft. All rights reserved. ** Licensed under the MIT license. ** See LICENSE file in the project root for full license information. ** ** This program was translated to C# and adapted for xunit-performance. ** New variants of several tests were added to compare class versus ** struct and to compare jagged arrays vs multi-dimensional arrays. */ /* ** BYTEmark (tm) ** BYTE Magazine's Native Mode benchmarks ** Rick Grehan, BYTE Magazine ** ** Create: ** Revision: 3/95 ** ** DISCLAIMER ** The source, executable, and documentation files that comprise ** the BYTEmark benchmarks are made available on an "as is" basis. ** This means that we at BYTE Magazine have made every reasonable ** effort to verify that the there are no errors in the source and ** executable code. We cannot, however, guarantee that the programs ** are error-free. Consequently, McGraw-HIll and BYTE Magazine make ** no claims in regard to the fitness of the source code, executable ** code, and documentation of the BYTEmark. ** ** Furthermore, BYTE Magazine, McGraw-Hill, and all employees ** of McGraw-Hill cannot be held responsible for any damages resulting ** from the use of this code or the results obtained from using ** this code. */ /******************************** ** BACK PROPAGATION NEURAL NET ** ********************************* ** This code is a modified version of the code ** that was submitted to BYTE Magazine by ** Maureen Caudill. It accomanied an article ** that I CANNOT NOW RECALL. ** The author's original heading/comment was ** as follows: ** ** Backpropagation Network ** Written by Maureen Caudill ** in Think C 4.0 on a Macintosh ** ** (c) Maureen Caudill 1988-1991 ** This network will accept 5x7 input patterns ** and produce 8 bit output patterns. ** The source code may be copied or modified without restriction, ** but no fee may be charged for its use. ** ** ++++++++++++++ ** I have modified the code so that it will work ** on systems other than a Macintosh -- RG */ /*********** ** DoNNet ** ************ ** Perform the neural net benchmark. ** Note that this benchmark is one of the few that ** requires an input file. That file is "NNET.DAT" and ** should be on the local directory (from which the ** benchmark program in launched). */ using System; using System.IO; public class NeuralJagged : NNetStruct { public override string Name() { return "NEURAL NET(jagged)"; } /* ** DEFINES */ public static int T = 1; /* TRUE */ public static int F = 0; /* FALSE */ public static int ERR = -1; public static int MAXPATS = 10; /* max number of patterns in data file */ public static int IN_X_SIZE = 5; /* number of neurodes/row of input layer */ public static int IN_Y_SIZE = 7; /* number of neurodes/col of input layer */ public static int IN_SIZE = 35; /* equals IN_X_SIZE*IN_Y_SIZE */ public static int MID_SIZE = 8; /* number of neurodes in middle layer */ public static int OUT_SIZE = 8; /* number of neurodes in output layer */ public static double MARGIN = 0.1; /* how near to 1,0 do we have to come to stop? */ public static double BETA = 0.09; /* beta learning constant */ public static double ALPHA = 0.09; /* momentum term constant */ public static double STOP = 0.1; /* when worst_error less than STOP, training is done */ /* ** MAXNNETLOOPS ** ** This constant sets the max number of loops through the neural ** net that the system will attempt before giving up. This ** is not a critical constant. You can alter it if your system ** has sufficient horsepower. */ public static int MAXNNETLOOPS = 50000; /* ** GLOBALS */ public static double[][] mid_wts = new double[MID_SIZE][]; public static double[][] out_wts = new double[OUT_SIZE][]; public static double[] mid_out = new double[MID_SIZE]; public static double[] out_out = new double[OUT_SIZE]; public static double[] mid_error = new double[MID_SIZE]; public static double[] out_error = new double[OUT_SIZE]; public static double[][] mid_wt_change = new double[MID_SIZE][]; public static double[][] out_wt_change = new double[OUT_SIZE][]; public static double[][] in_pats = new double[MAXPATS][]; public static double[][] out_pats = new double[MAXPATS][]; public static double[] tot_out_error = new double[MAXPATS]; public static double[][] out_wt_cum_change = new double[OUT_SIZE][]; public static double[][] mid_wt_cum_change = new double[MID_SIZE][]; public static double worst_error = 0.0; /* worst error each pass through the data */ public static double average_error = 0.0; /* average error each pass through the data */ public static double[] avg_out_error = new double[MAXPATS]; public static int iteration_count = 0; /* number of passes thru network so far */ public static int numpats = 0; /* number of patterns in data file */ public static int numpasses = 0; /* number of training passes through data file */ public static int learned = 0; /* flag--if TRUE, network has learned all patterns */ /* ** The Neural Net test requires an input data file. ** The name is specified here. */ public static string inpath = "NNET.DAT"; public static void Init() { for (int i = 0; i < MID_SIZE; i++) { mid_wts[i] = new double[IN_SIZE]; mid_wt_cum_change[i] = new double[IN_SIZE]; mid_wt_change[i] = new double[IN_SIZE]; } for (int i = 0; i < OUT_SIZE; i++) { out_wt_change[i] = new double[MID_SIZE]; out_wts[i] = new double[MID_SIZE]; out_wt_cum_change[i] = new double[MID_SIZE]; } for (int i = 0; i < MAXPATS; i++) { in_pats[i] = new double[IN_SIZE]; out_pats[i] = new double[OUT_SIZE]; } } public override double Run() { Init(); return DoNNET(this); } /********************* ** read_data_file() ** ********************** ** Read in the input data file and store the patterns in ** in_pats and out_pats. ** The format for the data file is as follows: ** ** line# data expected ** ----- ------------------------------ ** 1 In-X-size,in-y-size,out-size ** 2 number of patterns in file ** 3 1st X row of 1st input pattern ** 4.. following rows of 1st input pattern pattern ** in-x+2 y-out pattern ** 1st X row of 2nd pattern ** etc. ** ** Each row of data is separated by commas or spaces. ** The data is expected to be ascii text corresponding to ** either a +1 or a 0. ** ** Sample input for a 1-pattern file (The comments to the ** right may NOT be in the file unless more sophisticated ** parsing of the input is done.): ** ** 5,7,8 input is 5x7 grid, output is 8 bits ** 1 one pattern in file ** 0,1,1,1,0 beginning of pattern for "O" ** 1,0,0,0,1 ** 1,0,0,0,1 ** 1,0,0,0,1 ** 1,0,0,0,1 ** 1,0,0,0,0 ** 0,1,1,1,0 ** 0,1,0,0,1,1,1,1 ASCII code for "O" -- 0100 1111 ** ** Clearly, this simple scheme can be expanded or enhanced ** any way you like. ** ** Returns -1 if any file error occurred, otherwise 0. **/ private void read_data_file() { int xinsize = 0, yinsize = 0, youtsize = 0; int patt = 0, element = 0, i = 0, row = 0; int vals_read = 0; int val1 = 0, val2 = 0, val3 = 0, val4 = 0, val5 = 0, val6 = 0, val7 = 0, val8 = 0; Object[] results = new Object[8]; string input = NeuralData.Input; StringReader infile = new StringReader(input); vals_read = Utility.fscanf(infile, "%d %d %d", results); xinsize = (int)results[0]; yinsize = (int)results[1]; youtsize = (int)results[2]; if (vals_read != 3) { throw new Exception("NNET: error reading input"); } vals_read = Utility.fscanf(infile, "%d", results); numpats = (int)results[0]; if (vals_read != 1) { throw new Exception("NNET: error reading input"); } if (numpats > MAXPATS) numpats = MAXPATS; for (patt = 0; patt < numpats; patt++) { element = 0; for (row = 0; row < yinsize; row++) { vals_read = Utility.fscanf(infile, "%d %d %d %d %d", results); val1 = (int)results[0]; val2 = (int)results[1]; val3 = (int)results[2]; val4 = (int)results[3]; val5 = (int)results[4]; if (vals_read != 5) { throw new Exception("NNET: error reading input"); } element = row * xinsize; in_pats[patt][element] = (double)val1; element++; in_pats[patt][element] = (double)val2; element++; in_pats[patt][element] = (double)val3; element++; in_pats[patt][element] = (double)val4; element++; in_pats[patt][element] = (double)val5; element++; } for (i = 0; i < IN_SIZE; i++) { if (in_pats[patt][i] >= 0.9) in_pats[patt][i] = 0.9; if (in_pats[patt][i] <= 0.1) in_pats[patt][i] = 0.1; } element = 0; vals_read = Utility.fscanf(infile, "%d %d %d %d %d %d %d %d", results); val1 = (int)results[0]; val2 = (int)results[1]; val3 = (int)results[2]; val4 = (int)results[3]; val5 = (int)results[4]; val6 = (int)results[5]; val7 = (int)results[6]; val8 = (int)results[7]; out_pats[patt][element] = (double)val1; element++; out_pats[patt][element] = (double)val2; element++; out_pats[patt][element] = (double)val3; element++; out_pats[patt][element] = (double)val4; element++; out_pats[patt][element] = (double)val5; element++; out_pats[patt][element] = (double)val6; element++; out_pats[patt][element] = (double)val7; element++; out_pats[patt][element] = (double)val8; element++; } } private double DoNNET(NNetStruct locnnetstruct) { // string errorcontext = "CPU:NNET"; // int systemerror = 0; long accumtime = 0; double iterations = 0.0; /* ** Init random number generator. ** NOTE: It is important that the random number generator ** be re-initialized for every pass through this test. ** The NNET algorithm uses the random number generator ** to initialize the net. Results are sensitive to ** the initial neural net state. */ ByteMark.randnum(3); /* ** Read in the input and output patterns. We'll do this ** only once here at the beginning. These values don't ** change once loaded. */ read_data_file(); /* ** See if we need to perform self adjustment loop. */ if (locnnetstruct.adjust == 0) { /* ** Do self-adjustment. This involves initializing the ** # of loops and increasing the loop count until we ** get a number of loops that we can use. */ for (locnnetstruct.loops = 1; locnnetstruct.loops < MAXNNETLOOPS; locnnetstruct.loops++) { ByteMark.randnum(3); if (DoNNetIteration(locnnetstruct.loops) > global.min_ticks) break; } } /* ** All's well if we get here. Do the test. */ accumtime = 0L; iterations = (double)0.0; do { ByteMark.randnum(3); /* Gotta do this for Neural Net */ accumtime += DoNNetIteration(locnnetstruct.loops); iterations += (double)locnnetstruct.loops; } while (ByteMark.TicksToSecs(accumtime) < locnnetstruct.request_secs); /* ** Clean up, calculate results, and go home. Be sure to ** show that we don't have to rerun adjustment code. */ locnnetstruct.iterspersec = iterations / ByteMark.TicksToFracSecs(accumtime); if (locnnetstruct.adjust == 0) locnnetstruct.adjust = 1; return locnnetstruct.iterspersec; } /******************** ** DoNNetIteration ** ********************* ** Do a single iteration of the neural net benchmark. ** By iteration, we mean a "learning" pass. */ public static long DoNNetIteration(long nloops) { long elapsed; /* Elapsed time */ int patt; /* ** Run nloops learning cycles. Notice that, counted with ** the learning cycle is the weight randomization and ** zeroing of changes. This should reduce clock jitter, ** since we don't have to stop and start the clock for ** each iteration. */ elapsed = ByteMark.StartStopwatch(); while (nloops-- != 0) { randomize_wts(); zero_changes(); iteration_count = 1; learned = F; numpasses = 0; while (learned == F) { for (patt = 0; patt < numpats; patt++) { worst_error = 0.0; /* reset this every pass through data */ move_wt_changes(); /* move last pass's wt changes to momentum array */ do_forward_pass(patt); do_back_pass(patt); iteration_count++; } numpasses++; learned = check_out_error(); } } return (ByteMark.StopStopwatch(elapsed)); } /************************* ** do_mid_forward(patt) ** ************************** ** Process the middle layer's forward pass ** The activation of middle layer's neurode is the weighted ** sum of the inputs from the input pattern, with sigmoid ** function applied to the inputs. **/ public static void do_mid_forward(int patt) { double sum; int neurode, i; for (neurode = 0; neurode < MID_SIZE; neurode++) { sum = 0.0; for (i = 0; i < IN_SIZE; i++) { /* compute weighted sum of input signals */ sum += mid_wts[neurode][i] * in_pats[patt][i]; } /* ** apply sigmoid function f(x) = 1/(1+exp(-x)) to weighted sum */ sum = 1.0 / (1.0 + Math.Exp(-sum)); mid_out[neurode] = sum; } return; } /********************* ** do_out_forward() ** ********************** ** process the forward pass through the output layer ** The activation of the output layer is the weighted sum of ** the inputs (outputs from middle layer), modified by the ** sigmoid function. **/ public static void do_out_forward() { double sum; int neurode, i; for (neurode = 0; neurode < OUT_SIZE; neurode++) { sum = 0.0; for (i = 0; i < MID_SIZE; i++) { /* ** compute weighted sum of input signals ** from middle layer */ sum += out_wts[neurode][i] * mid_out[i]; } /* ** Apply f(x) = 1/(1+Math.Exp(-x)) to weighted input */ sum = 1.0 / (1.0 + Math.Exp(-sum)); out_out[neurode] = sum; } return; } /************************* ** display_output(patt) ** ************************** ** Display the actual output vs. the desired output of the ** network. ** Once the training is complete, and the "learned" flag set ** to TRUE, then display_output sends its output to both ** the screen and to a text output file. ** ** NOTE: This routine has been disabled in the benchmark ** version. -- RG **/ /* public static void display_output(int patt) { int i; fprintf(outfile,"\n Iteration # %d",iteration_count); fprintf(outfile,"\n Desired Output: "); for (i=0; i<OUT_SIZE; i++) { fprintf(outfile,"%6.3f ",out_pats[patt][i]); } fprintf(outfile,"\n Actual Output: "); for (i=0; i<OUT_SIZE; i++) { fprintf(outfile,"%6.3f ",out_out[i]); } fprintf(outfile,"\n"); return; } */ /********************** ** do_forward_pass() ** *********************** ** control function for the forward pass through the network ** NOTE: I have disabled the call to display_output() in ** the benchmark version -- RG. **/ public static void do_forward_pass(int patt) { do_mid_forward(patt); /* process forward pass, middle layer */ do_out_forward(); /* process forward pass, output layer */ /* display_output(patt); ** display results of forward pass */ return; } /*********************** ** do_out_error(patt) ** ************************ ** Compute the error for the output layer neurodes. ** This is simply Desired - Actual. **/ public static void do_out_error(int patt) { int neurode; double error, tot_error, sum; tot_error = 0.0; sum = 0.0; for (neurode = 0; neurode < OUT_SIZE; neurode++) { out_error[neurode] = out_pats[patt][neurode] - out_out[neurode]; /* ** while we're here, also compute magnitude ** of total error and worst error in this pass. ** We use these to decide if we are done yet. */ error = out_error[neurode]; if (error < 0.0) { sum += -error; if (-error > tot_error) tot_error = -error; /* worst error this pattern */ } else { sum += error; if (error > tot_error) tot_error = error; /* worst error this pattern */ } } avg_out_error[patt] = sum / OUT_SIZE; tot_out_error[patt] = tot_error; return; } /*********************** ** worst_pass_error() ** ************************ ** Find the worst and average error in the pass and save it **/ public static void worst_pass_error() { double error, sum; int i; error = 0.0; sum = 0.0; for (i = 0; i < numpats; i++) { if (tot_out_error[i] > error) error = tot_out_error[i]; sum += avg_out_error[i]; } worst_error = error; average_error = sum / numpats; return; } /******************* ** do_mid_error() ** ******************** ** Compute the error for the middle layer neurodes ** This is based on the output errors computed above. ** Note that the derivative of the sigmoid f(x) is ** f'(x) = f(x)(1 - f(x)) ** Recall that f(x) is merely the output of the middle ** layer neurode on the forward pass. **/ public static void do_mid_error() { double sum; int neurode, i; for (neurode = 0; neurode < MID_SIZE; neurode++) { sum = 0.0; for (i = 0; i < OUT_SIZE; i++) sum += out_wts[i][neurode] * out_error[i]; /* ** apply the derivative of the sigmoid here ** Because of the choice of sigmoid f(I), the derivative ** of the sigmoid is f'(I) = f(I)(1 - f(I)) */ mid_error[neurode] = mid_out[neurode] * (1 - mid_out[neurode]) * sum; } return; } /********************* ** adjust_out_wts() ** ********************** ** Adjust the weights of the output layer. The error for ** the output layer has been previously propagated back to ** the middle layer. ** Use the Delta Rule with momentum term to adjust the weights. **/ public static void adjust_out_wts() { int weight, neurode; double learn, delta, alph; learn = BETA; alph = ALPHA; for (neurode = 0; neurode < OUT_SIZE; neurode++) { for (weight = 0; weight < MID_SIZE; weight++) { /* standard delta rule */ delta = learn * out_error[neurode] * mid_out[weight]; /* now the momentum term */ delta += alph * out_wt_change[neurode][weight]; out_wts[neurode][weight] += delta; /* keep track of this pass's cum wt changes for next pass's momentum */ out_wt_cum_change[neurode][weight] += delta; } } return; } /************************* ** adjust_mid_wts(patt) ** ************************** ** Adjust the middle layer weights using the previously computed ** errors. ** We use the Generalized Delta Rule with momentum term **/ public static void adjust_mid_wts(int patt) { int weight, neurode; double learn, alph, delta; learn = BETA; alph = ALPHA; for (neurode = 0; neurode < MID_SIZE; neurode++) { for (weight = 0; weight < IN_SIZE; weight++) { /* first the basic delta rule */ delta = learn * mid_error[neurode] * in_pats[patt][weight]; /* with the momentum term */ delta += alph * mid_wt_change[neurode][weight]; mid_wts[neurode][weight] += delta; /* keep track of this pass's cum wt changes for next pass's momentum */ mid_wt_cum_change[neurode][weight] += delta; } } return; } /******************* ** do_back_pass() ** ******************** ** Process the backward propagation of error through network. **/ public static void do_back_pass(int patt) { do_out_error(patt); do_mid_error(); adjust_out_wts(); adjust_mid_wts(patt); return; } /********************** ** move_wt_changes() ** *********************** ** Move the weight changes accumulated last pass into the wt-change ** array for use by the momentum term in this pass. Also zero out ** the accumulating arrays after the move. **/ public static void move_wt_changes() { int i, j; for (i = 0; i < MID_SIZE; i++) for (j = 0; j < IN_SIZE; j++) { mid_wt_change[i][j] = mid_wt_cum_change[i][j]; /* ** Zero it out for next pass accumulation. */ mid_wt_cum_change[i][j] = 0.0; } for (i = 0; i < OUT_SIZE; i++) for (j = 0; j < MID_SIZE; j++) { out_wt_change[i][j] = out_wt_cum_change[i][j]; out_wt_cum_change[i][j] = 0.0; } return; } /********************** ** check_out_error() ** *********************** ** Check to see if the error in the output layer is below ** MARGIN*OUT_SIZE for all output patterns. If so, then ** assume the network has learned acceptably well. This ** is simply an arbitrary measure of how well the network ** has learned -- many other standards are possible. **/ public static int check_out_error() { int result, i, error; result = T; error = F; worst_pass_error(); /* identify the worst error in this pass */ for (i = 0; i < numpats; i++) { if (worst_error >= STOP) result = F; if (tot_out_error[i] >= 16.0) error = T; } if (error == T) result = ERR; return (result); } /******************* ** zero_changes() ** ******************** ** Zero out all the wt change arrays **/ public static void zero_changes() { int i, j; for (i = 0; i < MID_SIZE; i++) { for (j = 0; j < IN_SIZE; j++) { mid_wt_change[i][j] = 0.0; mid_wt_cum_change[i][j] = 0.0; } } for (i = 0; i < OUT_SIZE; i++) { for (j = 0; j < MID_SIZE; j++) { out_wt_change[i][j] = 0.0; out_wt_cum_change[i][j] = 0.0; } } return; } /******************** ** randomize_wts() ** ********************* ** Intialize the weights in the middle and output layers to ** random values between -0.25..+0.25 ** Function rand() returns a value between 0 and 32767. ** ** NOTE: Had to make alterations to how the random numbers were ** created. -- RG. **/ public static void randomize_wts() { int neurode, i; double value; /* ** Following not used int benchmark version -- RG ** ** printf("\n Please enter a random number seed (1..32767): "); ** scanf("%d", &i); ** srand(i); */ for (neurode = 0; neurode < MID_SIZE; neurode++) { for (i = 0; i < IN_SIZE; i++) { value = (double)ByteMark.abs_randwc(100000); value = value / (double)100000.0 - (double)0.5; mid_wts[neurode][i] = value / 2; } } for (neurode = 0; neurode < OUT_SIZE; neurode++) { for (i = 0; i < MID_SIZE; i++) { value = (double)ByteMark.abs_randwc(100000); value = value / (double)10000.0 - (double)0.5; out_wts[neurode][i] = value / 2; } } return; } /********************** ** display_mid_wts() ** *********************** ** Display the weights on the middle layer neurodes ** NOTE: This routine is not used in the benchmark ** test -- RG **/ /* static void display_mid_wts() { int neurode, weight, row, col; fprintf(outfile,"\n Weights of Middle Layer neurodes:"); for (neurode=0; neurode<MID_SIZE; neurode++) { fprintf(outfile,"\n Mid Neurode # %d",neurode); for (row=0; row<IN_Y_SIZE; row++) { fprintf(outfile,"\n "); for (col=0; col<IN_X_SIZE; col++) { weight = IN_X_SIZE * row + col; fprintf(outfile," %8.3f ", mid_wts[neurode,weight]); } } } return; } */ /********************** ** display_out_wts() ** *********************** ** Display the weights on the output layer neurodes ** NOTE: This code is not used in the benchmark ** test -- RG */ /* void display_out_wts() { int neurode, weight; fprintf(outfile,"\n Weights of Output Layer neurodes:"); for (neurode=0; neurode<OUT_SIZE; neurode++) { fprintf(outfile,"\n Out Neurode # %d \n",neurode); for (weight=0; weight<MID_SIZE; weight++) { fprintf(outfile," %8.3f ", out_wts[neurode,weight]); } } return; } */ }
// 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.Reflection; using System.Reflection.Emit; using Xunit; namespace System.Linq.Expressions.Tests { public class ListBindTests { private class ListWrapper<T> { public static List<T> StaticListField = new List<T>(); public static List<T> StaticListProperty { get; set; } public readonly List<T> ListField = new List<T>(); public List<T> ListProperty { get { return ListField; } } public HashSet<T> HashSetField = new HashSet<T>(); public List<T> WriteOnlyList { set { } } public List<T> GetList() { return ListField; } public IEnumerable<T> EnumerableProperty { get { return ListField; } } } [Fact] public void MethodInfoNull() { ElementInit elInit = Expression.ElementInit(typeof(List<int>).GetMethod(nameof(List<int>.Add)), Expression.Constant(0)); AssertExtensions.Throws<ArgumentNullException>("propertyAccessor", () => Expression.ListBind(default(MethodInfo), elInit)); AssertExtensions.Throws<ArgumentNullException>("propertyAccessor", () => Expression.ListBind(default(MethodInfo), Enumerable.Repeat(elInit, 1))); } [Fact] public void MemberInfoNull() { ElementInit elInit = Expression.ElementInit(typeof(List<int>).GetMethod(nameof(List<int>.Add)), Expression.Constant(0)); AssertExtensions.Throws<ArgumentNullException>("member", () => Expression.ListBind(default(MemberInfo), elInit)); AssertExtensions.Throws<ArgumentNullException>("member", () => Expression.ListBind(default(MemberInfo), Enumerable.Repeat(elInit, 1))); } [Fact] public void InitializersNull() { PropertyInfo property = typeof(ListWrapper<int>).GetProperty(nameof(ListWrapper<int>.ListProperty)); MemberInfo member = typeof(ListWrapper<int>).GetMember(nameof(ListWrapper<int>.ListProperty))[0]; AssertExtensions.Throws<ArgumentNullException>("initializers", () => Expression.ListBind(property, default(ElementInit[]))); AssertExtensions.Throws<ArgumentNullException>("initializers", () => Expression.ListBind(property, default(IEnumerable<ElementInit>))); AssertExtensions.Throws<ArgumentNullException>("initializers", () => Expression.ListBind(member, default(ElementInit[]))); AssertExtensions.Throws<ArgumentNullException>("initializers", () => Expression.ListBind(member, default(IEnumerable<ElementInit>))); } [Fact] public void MethodForMember() { MethodInfo method = typeof(ListWrapper<int>).GetMethod(nameof(ListWrapper<int>.GetList)); MemberInfo member = typeof(ListWrapper<int>).GetMember(nameof(ListWrapper<int>.GetList))[0]; ElementInit elInit = Expression.ElementInit(typeof(List<int>).GetMethod("Add"), Expression.Constant(0)); AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.ListBind(method, elInit)); AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.ListBind(method, Enumerable.Repeat(elInit, 1))); AssertExtensions.Throws<ArgumentException>("member", () => Expression.ListBind(member, elInit)); AssertExtensions.Throws<ArgumentException>("member", () => Expression.ListBind(member, Enumerable.Repeat(elInit, 1))); } [Fact] public void NonEnumerableListType() { PropertyInfo property = typeof(string).GetProperty(nameof(string.Length)); MemberInfo member = typeof(string).GetMember(nameof(string.Length))[0]; AssertExtensions.Throws<ArgumentException>("member", () => Expression.ListBind(property)); AssertExtensions.Throws<ArgumentException>("member", () => Expression.ListBind(property, Enumerable.Empty<ElementInit>())); AssertExtensions.Throws<ArgumentException>("member", () => Expression.ListBind(member)); AssertExtensions.Throws<ArgumentException>("member", () => Expression.ListBind(member, Enumerable.Empty<ElementInit>())); } private static IEnumerable<object> NonAddableListExpressions() { PropertyInfo property = typeof(ListWrapper<int>).GetProperty(nameof(ListWrapper<int>.EnumerableProperty)); MemberInfo member = typeof(ListWrapper<int>).GetMember(nameof(ListWrapper<int>.EnumerableProperty))[0]; yield return new object[] { Expression.ListBind(property) }; yield return new object[] { Expression.ListBind(property, Enumerable.Empty<ElementInit>()) }; yield return new object[] { Expression.ListBind(member) }; yield return new object[] { Expression.ListBind(member, Enumerable.Empty<ElementInit>()) }; } [Theory, PerCompilationType(nameof(NonAddableListExpressions))] public void NonAddableListType(MemberListBinding listBinding, bool useInterpreter) { Func<ListWrapper<int>> func = Expression.Lambda<Func<ListWrapper<int>>>( Expression.MemberInit( Expression.New(typeof(ListWrapper<int>)), listBinding ) ).Compile(useInterpreter); Assert.Empty(func().EnumerableProperty); } [Fact] public void NullElement() { AssertExtensions.Throws<ArgumentNullException>("initializers", () => Expression.ListBind(typeof(ListWrapper<int>).GetMethod(nameof(ListWrapper<int>.GetList)), null)); } [Fact] public void MismatchingElement() { AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.ListBind(typeof(ListWrapper<int>).GetMethod(nameof(ListWrapper<int>.GetList)), Expression.ElementInit(typeof(HashSet<int>).GetMethod("Add"), Expression.Constant(1)))); } [Fact] public void BindMethodMustBeProperty() { MemberInfo toString = typeof(object).GetMember(nameof(ToString))[0]; MethodInfo toStringMeth = typeof(object).GetMethod(nameof(ToString)); AssertExtensions.Throws<ArgumentException>("member", () => Expression.ListBind(toString)); AssertExtensions.Throws<ArgumentException>("member", () => Expression.ListBind(toString, Enumerable.Empty<ElementInit>())); AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.ListBind(toStringMeth)); AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.ListBind(toStringMeth, Enumerable.Empty<ElementInit>())); } public static IEnumerable<object[]> ZeroInitializerExpressions() { PropertyInfo property = typeof(ListWrapper<int>).GetProperty(nameof(ListWrapper<int>.ListProperty)); MemberInfo member = typeof(ListWrapper<int>).GetMember(nameof(ListWrapper<int>.ListProperty))[0]; MemberInfo fieldMember = typeof(ListWrapper<int>).GetMember(nameof(ListWrapper<int>.ListField))[0]; yield return new object[] { Expression.ListBind(property) }; yield return new object[] { Expression.ListBind(property, Enumerable.Empty<ElementInit>()) }; yield return new object[] { Expression.ListBind(member) }; yield return new object[] { Expression.ListBind(member, Enumerable.Empty<ElementInit>()) }; yield return new object[] { Expression.ListBind(fieldMember) }; yield return new object[] { Expression.ListBind(fieldMember, Enumerable.Empty<ElementInit>()) }; } [Theory] [PerCompilationType("ZeroInitializerExpressions")] public void ZeroInitializersIsValid(MemberListBinding binding, bool useInterpreter) { Func<ListWrapper<int>> func = Expression.Lambda<Func<ListWrapper<int>>>( Expression.MemberInit( Expression.New(typeof(ListWrapper<int>)), binding ) ).Compile(useInterpreter); Assert.Empty(func().ListProperty); } [Fact] public void UnreadableListProperty() { PropertyInfo property = typeof(ListWrapper<int>).GetProperty(nameof(ListWrapper<int>.WriteOnlyList)); MemberInfo member = typeof(ListWrapper<int>).GetMember(nameof(ListWrapper<int>.WriteOnlyList))[0]; AssertExtensions.Throws<ArgumentException>("member", () => Expression.ListBind(property, new ElementInit[0])); AssertExtensions.Throws<ArgumentException>("member", () => Expression.ListBind(property, Enumerable.Empty<ElementInit>())); AssertExtensions.Throws<ArgumentException>("member", () => Expression.ListBind(member, new ElementInit[0])); AssertExtensions.Throws<ArgumentException>("member", () => Expression.ListBind(member, Enumerable.Empty<ElementInit>())); } [Theory, ClassData(typeof(CompilationTypes))] public void StaticListProperty(bool useInterpreter) { PropertyInfo property = typeof(ListWrapper<int>).GetProperty(nameof(ListWrapper<int>.StaticListProperty)); Expression<Func<ListWrapper<int>>> exp = Expression.Lambda<Func<ListWrapper<int>>>( Expression.MemberInit( Expression.New(typeof(ListWrapper<int>)), Expression.ListBind( property, Expression.ElementInit( typeof(List<int>).GetMethod(nameof(List<int>.Add)), Expression.Constant(0) ) ) ) ); Assert.Throws<InvalidProgramException>(() => exp.Compile(useInterpreter)); } [Theory, ClassData(typeof(CompilationTypes))] public void StaticListField(bool useInterpreter) { FieldInfo field = typeof(ListWrapper<int>).GetField(nameof(ListWrapper<int>.StaticListField)); Expression<Func<ListWrapper<int>>> exp = Expression.Lambda<Func<ListWrapper<int>>>( Expression.MemberInit( Expression.New(typeof(ListWrapper<int>)), Expression.ListBind( field, Expression.ElementInit( typeof(List<int>).GetMethod(nameof(List<int>.Add)), Expression.Constant(0) ) ) ) ); Assert.Throws<InvalidProgramException>(() => exp.Compile(useInterpreter)); } [Theory, ClassData(typeof(CompilationTypes))] public void InitializeVoidAdd(bool useInterperter) { Expression<Func<ListWrapper<int>>> listInit = () => new ListWrapper<int> { ListProperty = { 1, 4, 9, 16 } }; Func<ListWrapper<int>> func = listInit.Compile(useInterperter); Assert.Equal(new[] { 1, 4, 9, 16 }, func().ListProperty); } [Theory, ClassData(typeof(CompilationTypes))] public void InitializeNonVoidAdd(bool useInterpreter) { Expression<Func<ListWrapper<int>>> hashInit = () => new ListWrapper<int> { HashSetField = { 1, 4, 9, 16 } }; Func<ListWrapper<int>> func = hashInit.Compile(useInterpreter); Assert.Equal(new[] { 1, 4, 9, 16 }, func().HashSetField.OrderBy(i => i)); } [Fact] public void UpdateDifferentReturnsDifferent() { MemberListBinding binding = Expression.ListBind(typeof(ListWrapper<int>).GetProperty(nameof(ListWrapper<int>.ListProperty)), Enumerable.Range(0, 3).Select(i => Expression.ElementInit(typeof(List<int>).GetMethod("Add"), Expression.Constant(i)))); Assert.NotSame(binding, binding.Update(new[] { Expression.ElementInit(typeof(List<int>).GetMethod(nameof(List<int>.Add)), Expression.Constant(1)) })); } [Fact] public void UpdateDoesntRepeatEnumeration() { MemberListBinding binding = Expression.ListBind( typeof(ListWrapper<int>).GetProperty(nameof(ListWrapper<int>.ListProperty)), Enumerable.Range(0, 3) .Select(i => Expression.ElementInit(typeof(List<int>).GetMethod("Add"), Expression.Constant(i)))); Assert.NotSame( binding, binding.Update( new RunOnceEnumerable<ElementInit>( new[] { Expression.ElementInit( typeof(List<int>).GetMethod(nameof(List<int>.Add)), Expression.Constant(1)) }))); } [Fact] public void UpdateNullThrows() { MemberListBinding binding = Expression.ListBind( typeof(ListWrapper<int>).GetProperty(nameof(ListWrapper<int>.ListProperty)), Enumerable.Range(0, 3) .Select(i => Expression.ElementInit(typeof(List<int>).GetMethod("Add"), Expression.Constant(i)))); AssertExtensions.Throws<ArgumentNullException>("initializers", () => binding.Update(null)); } [Fact] public void UpdateSameReturnsSame() { ElementInit[] initializers = Enumerable.Range(0, 3) .Select(i => Expression.ElementInit(typeof(List<int>).GetMethod("Add"), Expression.Constant(i))) .ToArray(); MemberListBinding binding = Expression.ListBind( typeof(ListWrapper<int>).GetProperty(nameof(ListWrapper<int>.ListProperty)), initializers); Assert.Same(binding, binding.Update(initializers)); } [Fact] public void OpenGenericTypesMembers() { MemberInfo member = typeof(ListWrapper<>).GetMember(nameof(ListWrapper<int>.ListProperty))[0]; PropertyInfo property = typeof(ListWrapper<>).GetProperty(nameof(ListWrapper<int>.ListProperty)); FieldInfo field = typeof(ListWrapper<>).GetField(nameof(ListWrapper<int>.ListField)); MethodInfo method = property.GetMethod; AssertExtensions.Throws<ArgumentException>(null, () => Expression.ListBind(member, Enumerable.Empty<ElementInit>())); AssertExtensions.Throws<ArgumentException>(null, () => Expression.ListBind(member)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.ListBind(property, Enumerable.Empty<ElementInit>())); AssertExtensions.Throws<ArgumentException>(null, () => Expression.ListBind(property)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.ListBind(field, Enumerable.Empty<ElementInit>())); AssertExtensions.Throws<ArgumentException>(null, () => Expression.ListBind(field)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.ListBind(method, Enumerable.Empty<ElementInit>())); AssertExtensions.Throws<ArgumentException>(null, () => Expression.ListBind(method)); } #if FEATURE_COMPILE [Fact] public void GlobalMethod() { ModuleBuilder module = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run).DefineDynamicModule("Module"); MethodBuilder globalMethod = module.DefineGlobalMethod("GlobalMethod", MethodAttributes.Public | MethodAttributes.Static, typeof(List<int>), Type.EmptyTypes); globalMethod.GetILGenerator().Emit(OpCodes.Ret); module.CreateGlobalFunctions(); MethodInfo globalMethodInfo = module.GetMethod(globalMethod.Name); AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.ListBind(globalMethodInfo)); } #endif } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Composition; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { [ExportLanguageService(typeof(ISyntaxFactsService), LanguageNames.CSharp), Shared] internal class CSharpSyntaxFactsService : ISyntaxFactsService { public bool IsAwaitKeyword(SyntaxToken token) { return token.IsKind(SyntaxKind.AwaitKeyword); } public bool IsIdentifier(SyntaxToken token) { return token.IsKind(SyntaxKind.IdentifierToken); } public bool IsGlobalNamespaceKeyword(SyntaxToken token) { return token.IsKind(SyntaxKind.GlobalKeyword); } public bool IsVerbatimIdentifier(SyntaxToken token) { return token.IsVerbatimIdentifier(); } public bool IsOperator(SyntaxToken token) { var kind = token.Kind(); return (SyntaxFacts.IsAnyUnaryExpression(kind) && (token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax); } public bool IsKeyword(SyntaxToken token) { var kind = (SyntaxKind)token.RawKind; return SyntaxFacts.IsKeywordKind(kind); // both contextual and reserved keywords } public bool IsContextualKeyword(SyntaxToken token) { var kind = (SyntaxKind)token.RawKind; return SyntaxFacts.IsContextualKeyword(kind); } public bool IsPreprocessorKeyword(SyntaxToken token) { var kind = (SyntaxKind)token.RawKind; return SyntaxFacts.IsPreprocessorKeyword(kind); } public bool IsHashToken(SyntaxToken token) { return (SyntaxKind)token.RawKind == SyntaxKind.HashToken; } public bool IsInInactiveRegion(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var csharpTree = syntaxTree as SyntaxTree; if (csharpTree == null) { return false; } return csharpTree.IsInInactiveRegion(position, cancellationToken); } public bool IsInNonUserCode(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var csharpTree = syntaxTree as SyntaxTree; if (csharpTree == null) { return false; } return csharpTree.IsInNonUserCode(position, cancellationToken); } public bool IsEntirelyWithinStringOrCharOrNumericLiteral(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var csharpTree = syntaxTree as SyntaxTree; if (csharpTree == null) { return false; } return csharpTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken); } public bool IsDirective(SyntaxNode node) { return node is DirectiveTriviaSyntax; } public bool TryGetExternalSourceInfo(SyntaxNode node, out ExternalSourceInfo info) { var lineDirective = node as LineDirectiveTriviaSyntax; if (lineDirective != null) { if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword) { info = new ExternalSourceInfo(null, ends: true); return true; } else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken && lineDirective.Line.Value is int) { info = new ExternalSourceInfo((int)lineDirective.Line.Value, false); return true; } } info = default(ExternalSourceInfo); return false; } public bool IsRightSideOfQualifiedName(SyntaxNode node) { var name = node as SimpleNameSyntax; return name.IsRightSideOfQualifiedName(); } public bool IsMemberAccessExpressionName(SyntaxNode node) { var name = node as SimpleNameSyntax; return name.IsMemberAccessExpressionName(); } public bool IsObjectCreationExpressionType(SyntaxNode node) { return node.IsParentKind(SyntaxKind.ObjectCreationExpression) && ((ObjectCreationExpressionSyntax)node.Parent).Type == node; } public bool IsAttributeName(SyntaxNode node) { return SyntaxFacts.IsAttributeName(node); } public bool IsInvocationExpression(SyntaxNode node) { return node is InvocationExpressionSyntax; } public bool IsAnonymousFunction(SyntaxNode node) { return node is ParenthesizedLambdaExpressionSyntax || node is SimpleLambdaExpressionSyntax || node is AnonymousMethodExpressionSyntax; } public bool IsGenericName(SyntaxNode node) { return node is GenericNameSyntax; } public bool IsNamedParameter(SyntaxNode node) { return node.CheckParent<NameColonSyntax>(p => p.Name == node); } public bool IsSkippedTokensTrivia(SyntaxNode node) { return node is SkippedTokensTriviaSyntax; } public bool HasIncompleteParentMember(SyntaxNode node) { return node.IsParentKind(SyntaxKind.IncompleteMember); } public SyntaxToken GetIdentifierOfGenericName(SyntaxNode genericName) { var csharpGenericName = genericName as GenericNameSyntax; return csharpGenericName != null ? csharpGenericName.Identifier : default(SyntaxToken); } public bool IsCaseSensitive { get { return true; } } public bool IsUsingDirectiveName(SyntaxNode node) { return node.IsParentKind(SyntaxKind.UsingDirective) && ((UsingDirectiveSyntax)node.Parent).Name == node; } public bool IsForEachStatement(SyntaxNode node) { return node is ForEachStatementSyntax; } public bool IsLockStatement(SyntaxNode node) { return node is LockStatementSyntax; } public bool IsUsingStatement(SyntaxNode node) { return node is UsingStatementSyntax; } public bool IsThisConstructorInitializer(SyntaxToken token) { return token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer) && ((ConstructorInitializerSyntax)token.Parent).ThisOrBaseKeyword == token; } public bool IsBaseConstructorInitializer(SyntaxToken token) { return token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer) && ((ConstructorInitializerSyntax)token.Parent).ThisOrBaseKeyword == token; } public bool IsQueryExpression(SyntaxNode node) { return node is QueryExpressionSyntax; } public bool IsPredefinedType(SyntaxToken token) { PredefinedType actualType; return TryGetPredefinedType(token, out actualType) && actualType != PredefinedType.None; } public bool IsPredefinedType(SyntaxToken token, PredefinedType type) { PredefinedType actualType; return TryGetPredefinedType(token, out actualType) && actualType == type; } public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type) { type = GetPredefinedType(token); return type != PredefinedType.None; } private PredefinedType GetPredefinedType(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.BoolKeyword: return PredefinedType.Boolean; case SyntaxKind.ByteKeyword: return PredefinedType.Byte; case SyntaxKind.SByteKeyword: return PredefinedType.SByte; case SyntaxKind.IntKeyword: return PredefinedType.Int32; case SyntaxKind.UIntKeyword: return PredefinedType.UInt32; case SyntaxKind.ShortKeyword: return PredefinedType.Int16; case SyntaxKind.UShortKeyword: return PredefinedType.UInt16; case SyntaxKind.LongKeyword: return PredefinedType.Int64; case SyntaxKind.ULongKeyword: return PredefinedType.UInt64; case SyntaxKind.FloatKeyword: return PredefinedType.Single; case SyntaxKind.DoubleKeyword: return PredefinedType.Double; case SyntaxKind.DecimalKeyword: return PredefinedType.Decimal; case SyntaxKind.StringKeyword: return PredefinedType.String; case SyntaxKind.CharKeyword: return PredefinedType.Char; case SyntaxKind.ObjectKeyword: return PredefinedType.Object; case SyntaxKind.VoidKeyword: return PredefinedType.Void; default: return PredefinedType.None; } } public bool IsPredefinedOperator(SyntaxToken token) { PredefinedOperator actualOperator; return TryGetPredefinedOperator(token, out actualOperator) && actualOperator != PredefinedOperator.None; } public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op) { PredefinedOperator actualOperator; return TryGetPredefinedOperator(token, out actualOperator) && actualOperator == op; } public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op) { op = GetPredefinedOperator(token); return op != PredefinedOperator.None; } private PredefinedOperator GetPredefinedOperator(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.PlusToken: case SyntaxKind.PlusEqualsToken: return PredefinedOperator.Addition; case SyntaxKind.MinusToken: case SyntaxKind.MinusEqualsToken: return PredefinedOperator.Subtraction; case SyntaxKind.AmpersandToken: case SyntaxKind.AmpersandEqualsToken: return PredefinedOperator.BitwiseAnd; case SyntaxKind.BarToken: case SyntaxKind.BarEqualsToken: return PredefinedOperator.BitwiseOr; case SyntaxKind.MinusMinusToken: return PredefinedOperator.Decrement; case SyntaxKind.PlusPlusToken: return PredefinedOperator.Increment; case SyntaxKind.SlashToken: case SyntaxKind.SlashEqualsToken: return PredefinedOperator.Division; case SyntaxKind.EqualsEqualsToken: return PredefinedOperator.Equality; case SyntaxKind.CaretToken: case SyntaxKind.CaretEqualsToken: return PredefinedOperator.ExclusiveOr; case SyntaxKind.GreaterThanToken: return PredefinedOperator.GreaterThan; case SyntaxKind.GreaterThanEqualsToken: return PredefinedOperator.GreaterThanOrEqual; case SyntaxKind.ExclamationEqualsToken: return PredefinedOperator.Inequality; case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: return PredefinedOperator.LeftShift; case SyntaxKind.LessThanEqualsToken: return PredefinedOperator.LessThanOrEqual; case SyntaxKind.AsteriskToken: case SyntaxKind.AsteriskEqualsToken: return PredefinedOperator.Multiplication; case SyntaxKind.PercentToken: case SyntaxKind.PercentEqualsToken: return PredefinedOperator.Modulus; case SyntaxKind.ExclamationToken: case SyntaxKind.TildeToken: return PredefinedOperator.Complement; case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: return PredefinedOperator.RightShift; } return PredefinedOperator.None; } public string GetText(int kind) { return SyntaxFacts.GetText((SyntaxKind)kind); } public bool IsIdentifierStartCharacter(char c) { return SyntaxFacts.IsIdentifierStartCharacter(c); } public bool IsIdentifierPartCharacter(char c) { return SyntaxFacts.IsIdentifierPartCharacter(c); } public bool IsIdentifierEscapeCharacter(char c) { return c == '@'; } public bool IsValidIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length; } public bool IsVerbatimIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier(); } public bool IsTypeCharacter(char c) { return false; } public bool IsStartOfUnicodeEscapeSequence(char c) { return c == '\\'; } public bool IsLiteral(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.NumericLiteralToken: case SyntaxKind.CharacterLiteralToken: case SyntaxKind.StringLiteralToken: case SyntaxKind.NullKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.InterpolatedStringStartToken: case SyntaxKind.InterpolatedStringEndToken: case SyntaxKind.InterpolatedVerbatimStringStartToken: case SyntaxKind.InterpolatedStringTextToken: return true; } return false; } public bool IsStringLiteral(SyntaxToken token) { return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken); } public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, SyntaxNode parent) { var typedToken = token; var typedParent = parent; if (typedParent.IsKind(SyntaxKind.IdentifierName)) { TypeSyntax declaredType = null; if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration)) { declaredType = ((VariableDeclarationSyntax)typedParent.Parent).Type; } else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration)) { declaredType = ((FieldDeclarationSyntax)typedParent.Parent).Declaration.Type; } return declaredType == typedParent && typedToken.ValueText == "var"; } return false; } public bool IsTypeNamedDynamic(SyntaxToken token, SyntaxNode parent) { var typedParent = parent as ExpressionSyntax; if (typedParent != null) { if (SyntaxFacts.IsInTypeOnlyContext(typedParent) && typedParent.IsKind(SyntaxKind.IdentifierName) && token.ValueText == "dynamic") { return true; } } return false; } public bool IsBindableToken(SyntaxToken token) { if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token)) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.DelegateKeyword: case SyntaxKind.VoidKeyword: return false; } return true; } return false; } public bool IsMemberAccessExpression(SyntaxNode node) { return node is MemberAccessExpressionSyntax && ((MemberAccessExpressionSyntax)node).Kind() == SyntaxKind.SimpleMemberAccessExpression; } public bool IsConditionalMemberAccessExpression(SyntaxNode node) { return node is ConditionalAccessExpressionSyntax; } public bool IsPointerMemberAccessExpression(SyntaxNode node) { return node is MemberAccessExpressionSyntax && ((MemberAccessExpressionSyntax)node).Kind() == SyntaxKind.PointerMemberAccessExpression; } public void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity) { name = null; arity = 0; var simpleName = node as SimpleNameSyntax; if (simpleName != null) { name = simpleName.Identifier.ValueText; arity = simpleName.Arity; } } public SyntaxNode GetExpressionOfMemberAccessExpression(SyntaxNode node) { if (node.IsKind(SyntaxKind.MemberBindingExpression)) { if (node.IsParentKind(SyntaxKind.ConditionalAccessExpression)) { return GetExpressionOfConditionalMemberAccessExpression(node.Parent); } if (node.IsParentKind(SyntaxKind.InvocationExpression) && node.Parent.IsParentKind(SyntaxKind.ConditionalAccessExpression)) { return GetExpressionOfConditionalMemberAccessExpression(node.Parent.Parent); } } return (node as MemberAccessExpressionSyntax)?.Expression; } public SyntaxNode GetExpressionOfConditionalMemberAccessExpression(SyntaxNode node) { return (node as ConditionalAccessExpressionSyntax)?.Expression; } public bool IsInStaticContext(SyntaxNode node) { return node.IsInStaticContext(); } public bool IsInNamespaceOrTypeContext(SyntaxNode node) { return SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax); } public SyntaxNode GetExpressionOfArgument(SyntaxNode node) { return ((ArgumentSyntax)node).Expression; } public RefKind GetRefKindOfArgument(SyntaxNode node) { return (node as ArgumentSyntax).GetRefKind(); } public bool IsInConstantContext(SyntaxNode node) { return (node as ExpressionSyntax).IsInConstantContext(); } public bool IsInConstructor(SyntaxNode node) { return node.GetAncestor<ConstructorDeclarationSyntax>() != null; } public bool IsUnsafeContext(SyntaxNode node) { return node.IsUnsafeContext(); } public SyntaxNode GetNameOfAttribute(SyntaxNode node) { return ((AttributeSyntax)node).Name; } public bool IsAttribute(SyntaxNode node) { return node is AttributeSyntax; } public bool IsAttributeNamedArgumentIdentifier(SyntaxNode node) { var identifier = node as IdentifierNameSyntax; return identifier != null && identifier.IsParentKind(SyntaxKind.NameEquals) && identifier.Parent.IsParentKind(SyntaxKind.AttributeArgument); } public SyntaxNode GetContainingTypeDeclaration(SyntaxNode root, int position) { if (root == null) { throw new ArgumentNullException(nameof(root)); } if (position < 0 || position > root.Span.End) { throw new ArgumentOutOfRangeException(nameof(position)); } return root .FindToken(position) .GetAncestors<SyntaxNode>() .FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax); } public SyntaxNode GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode node) { throw ExceptionUtilities.Unreachable; } public SyntaxToken FindTokenOnLeftOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public SyntaxToken FindTokenOnRightOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public bool IsObjectCreationExpression(SyntaxNode node) { return node is ObjectCreationExpressionSyntax; } public bool IsObjectInitializerNamedAssignmentIdentifier(SyntaxNode node) { var identifier = node as IdentifierNameSyntax; return identifier != null && identifier.IsLeftSideOfAssignExpression() && identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression); } public bool IsElementAccessExpression(SyntaxNode node) { return node.Kind() == SyntaxKind.ElementAccessExpression; } public SyntaxNode ConvertToSingleLine(SyntaxNode node) { return node.ConvertToSingleLine(); } public SyntaxToken ToIdentifierToken(string name) { return name.ToIdentifierToken(); } public SyntaxNode Parenthesize(SyntaxNode expression, bool includeElasticTrivia) { return ((ExpressionSyntax)expression).Parenthesize(includeElasticTrivia); } public bool IsIndexerMemberCRef(SyntaxNode node) { return node.Kind() == SyntaxKind.IndexerMemberCref; } public SyntaxNode GetContainingMemberDeclaration(SyntaxNode root, int position, bool useFullSpan = true) { Contract.ThrowIfNull(root, "root"); Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position"); var end = root.FullSpan.End; if (end == 0) { // empty file return null; } // make sure position doesn't touch end of root position = Math.Min(position, end - 1); var node = root.FindToken(position).Parent; while (node != null) { if (useFullSpan || node.Span.Contains(position)) { if (node is MemberDeclarationSyntax) { return node; } } node = node.Parent; } return null; } public bool IsMethodLevelMember(SyntaxNode node) { return node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseFieldDeclarationSyntax; } public bool IsTopLevelNodeWithMembers(SyntaxNode node) { return node is NamespaceDeclarationSyntax || node is TypeDeclarationSyntax || node is EnumDeclarationSyntax; } public bool TryGetDeclaredSymbolInfo(SyntaxNode node, out DeclaredSymbolInfo declaredSymbolInfo) { switch (node.Kind()) { case SyntaxKind.ClassDeclaration: var classDecl = (ClassDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(classDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Class, classDecl.Identifier.Span); return true; case SyntaxKind.ConstructorDeclaration: var ctorDecl = (ConstructorDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo( ctorDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Constructor, ctorDecl.Identifier.Span, parameterCount: (ushort)(ctorDecl.ParameterList?.Parameters.Count ?? 0)); return true; case SyntaxKind.DelegateDeclaration: var delegateDecl = (DelegateDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(delegateDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Delegate, delegateDecl.Identifier.Span); return true; case SyntaxKind.EnumDeclaration: var enumDecl = (EnumDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(enumDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Enum, enumDecl.Identifier.Span); return true; case SyntaxKind.EnumMemberDeclaration: var enumMember = (EnumMemberDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(enumMember.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.EnumMember, enumMember.Identifier.Span); return true; case SyntaxKind.EventDeclaration: var eventDecl = (EventDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(ExpandExplicitInterfaceName(eventDecl.Identifier.ValueText, eventDecl.ExplicitInterfaceSpecifier), GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Event, eventDecl.Identifier.Span); return true; case SyntaxKind.IndexerDeclaration: var indexerDecl = (IndexerDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(WellKnownMemberNames.Indexer, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Indexer, indexerDecl.ThisKeyword.Span); return true; case SyntaxKind.InterfaceDeclaration: var interfaceDecl = (InterfaceDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(interfaceDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Interface, interfaceDecl.Identifier.Span); return true; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo( ExpandExplicitInterfaceName(method.Identifier.ValueText, method.ExplicitInterfaceSpecifier), GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Method, method.Identifier.Span, parameterCount: (ushort)(method.ParameterList?.Parameters.Count ?? 0), typeParameterCount: (ushort)(method.TypeParameterList?.Parameters.Count ?? 0)); return true; case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(ExpandExplicitInterfaceName(property.Identifier.ValueText, property.ExplicitInterfaceSpecifier), GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Property, property.Identifier.Span); return true; case SyntaxKind.StructDeclaration: var structDecl = (StructDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(structDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Struct, structDecl.Identifier.Span); return true; case SyntaxKind.VariableDeclarator: // could either be part of a field declaration or an event field declaration var variableDeclarator = (VariableDeclaratorSyntax)node; var variableDeclaration = variableDeclarator.Parent as VariableDeclarationSyntax; var fieldDeclaration = variableDeclaration?.Parent as BaseFieldDeclarationSyntax; if (fieldDeclaration != null) { var kind = fieldDeclaration is EventFieldDeclarationSyntax ? DeclaredSymbolInfoKind.Event : fieldDeclaration.Modifiers.Any(m => m.Kind() == SyntaxKind.ConstKeyword) ? DeclaredSymbolInfoKind.Constant : DeclaredSymbolInfoKind.Field; declaredSymbolInfo = new DeclaredSymbolInfo(variableDeclarator.Identifier.ValueText, GetContainerDisplayName(fieldDeclaration.Parent), GetFullyQualifiedContainerName(fieldDeclaration.Parent), kind, variableDeclarator.Identifier.Span); return true; } break; } declaredSymbolInfo = default(DeclaredSymbolInfo); return false; } private static string ExpandExplicitInterfaceName(string identifier, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier) { if (explicitInterfaceSpecifier == null) { return identifier; } else { var builder = new StringBuilder(); ExpandTypeName(explicitInterfaceSpecifier.Name, builder); builder.Append('.'); builder.Append(identifier); return builder.ToString(); } } private static void ExpandTypeName(TypeSyntax type, StringBuilder builder) { switch (type.Kind()) { case SyntaxKind.AliasQualifiedName: var alias = (AliasQualifiedNameSyntax)type; builder.Append(alias.Alias.Identifier.ValueText); break; case SyntaxKind.ArrayType: var array = (ArrayTypeSyntax)type; ExpandTypeName(array.ElementType, builder); for (int i = 0; i < array.RankSpecifiers.Count; i++) { var rankSpecifier = array.RankSpecifiers[i]; builder.Append(rankSpecifier.OpenBracketToken.Text); for (int j = 1; j < rankSpecifier.Sizes.Count; j++) { builder.Append(','); } builder.Append(rankSpecifier.CloseBracketToken.Text); } break; case SyntaxKind.GenericName: var generic = (GenericNameSyntax)type; builder.Append(generic.Identifier.ValueText); if (generic.TypeArgumentList != null) { var arguments = generic.TypeArgumentList.Arguments; builder.Append(generic.TypeArgumentList.LessThanToken.Text); for (int i = 0; i < arguments.Count; i++) { if (i != 0) { builder.Append(','); } ExpandTypeName(arguments[i], builder); } builder.Append(generic.TypeArgumentList.GreaterThanToken.Text); } break; case SyntaxKind.IdentifierName: var identifierName = (IdentifierNameSyntax)type; builder.Append(identifierName.Identifier.ValueText); break; case SyntaxKind.NullableType: var nullable = (NullableTypeSyntax)type; ExpandTypeName(nullable.ElementType, builder); builder.Append(nullable.QuestionToken.Text); break; case SyntaxKind.OmittedTypeArgument: // do nothing since it was omitted, but don't reach the default block break; case SyntaxKind.PointerType: var pointer = (PointerTypeSyntax)type; ExpandTypeName(pointer.ElementType, builder); builder.Append(pointer.AsteriskToken.Text); break; case SyntaxKind.PredefinedType: var predefined = (PredefinedTypeSyntax)type; builder.Append(predefined.Keyword.Text); break; case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)type; ExpandTypeName(qualified.Left, builder); builder.Append(qualified.DotToken.Text); ExpandTypeName(qualified.Right, builder); break; default: Debug.Assert(false, "Unexpected type syntax " + type.Kind()); break; } } private string GetContainerDisplayName(SyntaxNode node) { return GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters); } private string GetFullyQualifiedContainerName(SyntaxNode node) { return GetDisplayName(node, DisplayNameOptions.IncludeNamespaces); } private const string dotToken = "."; public string GetDisplayName(SyntaxNode node, DisplayNameOptions options, string rootNamespace = null) { if (node == null) { return string.Empty; } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; // return type var memberDeclaration = node as MemberDeclarationSyntax; if ((options & DisplayNameOptions.IncludeType) != 0) { var type = memberDeclaration.GetMemberType(); if (type != null && !type.IsMissing) { builder.Append(type); builder.Append(' '); } } var names = ArrayBuilder<string>.GetInstance(); // containing type(s) var parent = (SyntaxNode)node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent; while (parent is TypeDeclarationSyntax) { names.Push(GetName(parent, options)); parent = parent.Parent; } // containing namespace(s) in source (if any) if ((options & DisplayNameOptions.IncludeNamespaces) != 0) { while (parent != null && parent.Kind() == SyntaxKind.NamespaceDeclaration) { names.Add(GetName(parent, options)); parent = parent.Parent; } } while (!names.IsEmpty()) { var name = names.Pop(); if (name != null) { builder.Append(name); builder.Append(dotToken); } } // name (including generic type parameters) builder.Append(GetName(node, options)); // parameter list (if any) if ((options & DisplayNameOptions.IncludeParameters) != 0) { builder.Append(memberDeclaration.GetParameterList()); } return pooled.ToStringAndFree(); } private static string GetName(SyntaxNode node, DisplayNameOptions options) { const string missingTokenPlaceholder = "?"; switch (node.Kind()) { case SyntaxKind.CompilationUnit: return null; case SyntaxKind.IdentifierName: var identifier = ((IdentifierNameSyntax)node).Identifier; return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text; case SyntaxKind.NamespaceDeclaration: return GetName(((NamespaceDeclarationSyntax)node).Name, options); case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)node; return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options); } string name = null; var memberDeclaration = node as MemberDeclarationSyntax; if (memberDeclaration != null) { var nameToken = memberDeclaration.GetNameToken(); if (nameToken == default(SyntaxToken)) { Debug.Assert(memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration); name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString(); } else { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration) { name = "~" + name; } if ((options & DisplayNameOptions.IncludeTypeParameters) != 0) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append(name); AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()); name = pooled.ToStringAndFree(); } } } else { var fieldDeclarator = node as VariableDeclaratorSyntax; if (fieldDeclarator != null) { var nameToken = fieldDeclarator.Identifier; if (nameToken != default(SyntaxToken)) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; } } } Debug.Assert(name != null, "Unexpected node type " + node.Kind()); return name; } private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList) { if (typeParameterList != null && typeParameterList.Parameters.Count > 0) { builder.Append('<'); builder.Append(typeParameterList.Parameters[0].Identifier.ValueText); for (int i = 1; i < typeParameterList.Parameters.Count; i++) { builder.Append(", "); builder.Append(typeParameterList.Parameters[i].Identifier.ValueText); } builder.Append('>'); } } public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode root) { var list = new List<SyntaxNode>(); AppendMethodLevelMembers(root, list); return list; } private void AppendMethodLevelMembers(SyntaxNode node, List<SyntaxNode> list) { foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { AppendMethodLevelMembers(member, list); continue; } if (IsMethodLevelMember(member)) { list.Add(member); } } } public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node) { if (node.Span.IsEmpty) { return default(TextSpan); } var member = GetContainingMemberDeclaration(node, node.SpanStart); if (member == null) { return default(TextSpan); } // TODO: currently we only support method for now var method = member as BaseMethodDeclarationSyntax; if (method != null) { if (method.Body == null) { return default(TextSpan); } return GetBlockBodySpan(method.Body); } return default(TextSpan); } public bool ContainsInMemberBody(SyntaxNode node, TextSpan span) { var constructor = node as ConstructorDeclarationSyntax; if (constructor != null) { return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) || (constructor.Initializer != null && constructor.Initializer.Span.Contains(span)); } var method = node as BaseMethodDeclarationSyntax; if (method != null) { return method.Body != null && GetBlockBodySpan(method.Body).Contains(span); } var property = node as BasePropertyDeclarationSyntax; if (property != null) { return property.AccessorList != null && property.AccessorList.Span.Contains(span); } var @enum = node as EnumMemberDeclarationSyntax; if (@enum != null) { return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span); } var field = node as BaseFieldDeclarationSyntax; if (field != null) { return field.Declaration != null && field.Declaration.Span.Contains(span); } return false; } private TextSpan GetBlockBodySpan(BlockSyntax body) { return TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart); } public int GetMethodLevelMemberId(SyntaxNode root, SyntaxNode node) { Contract.Requires(root.SyntaxTree == node.SyntaxTree); int currentId = 0; SyntaxNode currentNode; Contract.ThrowIfFalse(TryGetMethodLevelMember(root, (n, i) => n == node, ref currentId, out currentNode)); Contract.ThrowIfFalse(currentId >= 0); CheckMemberId(root, node, currentId); return currentId; } public SyntaxNode GetMethodLevelMember(SyntaxNode root, int memberId) { int currentId = 0; SyntaxNode currentNode; if (!TryGetMethodLevelMember(root, (n, i) => i == memberId, ref currentId, out currentNode)) { return null; } Contract.ThrowIfNull(currentNode); CheckMemberId(root, currentNode, memberId); return currentNode; } private bool TryGetMethodLevelMember( SyntaxNode node, Func<SyntaxNode, int, bool> predicate, ref int currentId, out SyntaxNode currentNode) { foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { if (TryGetMethodLevelMember(member, predicate, ref currentId, out currentNode)) { return true; } continue; } if (IsMethodLevelMember(member)) { if (predicate(member, currentId)) { currentNode = member; return true; } currentId++; } } currentNode = null; return false; } [Conditional("DEBUG")] private void CheckMemberId(SyntaxNode root, SyntaxNode node, int memberId) { var list = GetMethodLevelMembers(root); var index = list.IndexOf(node); Contract.ThrowIfFalse(index == memberId); } public SyntaxNode GetBindableParent(SyntaxToken token) { var node = token.Parent; while (node != null) { var parent = node.Parent; // If this node is on the left side of a member access expression, don't ascend // further or we'll end up binding to something else. var memberAccess = parent as MemberAccessExpressionSyntax; if (memberAccess != null) { if (memberAccess.Expression == node) { break; } } // If this node is on the left side of a qualified name, don't ascend // further or we'll end up binding to something else. var qualifiedName = parent as QualifiedNameSyntax; if (qualifiedName != null) { if (qualifiedName.Left == node) { break; } } // If this node is on the left side of a alias-qualified name, don't ascend // further or we'll end up binding to something else. var aliasQualifiedName = parent as AliasQualifiedNameSyntax; if (aliasQualifiedName != null) { if (aliasQualifiedName.Alias == node) { break; } } // If this node is the type of an object creation expression, return the // object creation expression. var objectCreation = parent as ObjectCreationExpressionSyntax; if (objectCreation != null) { if (objectCreation.Type == node) { node = parent; break; } } // The inside of an interpolated string is treated as its own token so we // need to force navigation to the parent expression syntax. if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax) { node = parent; break; } // If this node is not parented by a name, we're done. var name = parent as NameSyntax; if (name == null) { break; } node = parent; } return node; } public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode root, CancellationToken cancellationToken) { var compilationUnit = root as CompilationUnitSyntax; if (compilationUnit == null) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } var constructors = new List<SyntaxNode>(); AppendConstructors(compilationUnit.Members, constructors, cancellationToken); return constructors; } private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); var constructor = member as ConstructorDeclarationSyntax; if (constructor != null) { constructors.Add(constructor); continue; } var @namespace = member as NamespaceDeclarationSyntax; if (@namespace != null) { AppendConstructors(@namespace.Members, constructors, cancellationToken); } var @class = member as ClassDeclarationSyntax; if (@class != null) { AppendConstructors(@class.Members, constructors, cancellationToken); } var @struct = member as StructDeclarationSyntax; if (@struct != null) { AppendConstructors(@struct.Members, constructors, cancellationToken); } } } public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace) { if (token.Kind() == SyntaxKind.CloseBraceToken) { var tuple = token.Parent.GetBraces(); openBrace = tuple.Item1; return openBrace.Kind() == SyntaxKind.OpenBraceToken; } openBrace = default(SyntaxToken); return false; } } }
// 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; using System.Dynamic.Utils; using System.Reflection; namespace System.Linq.Expressions { /// <summary> /// Represents an operation between an expression and a type. /// </summary> [DebuggerTypeProxy(typeof(Expression.TypeBinaryExpressionProxy))] public sealed class TypeBinaryExpression : Expression { private readonly Expression _expression; private readonly Type _typeOperand; private readonly ExpressionType _nodeKind; internal TypeBinaryExpression(Expression expression, Type typeOperand, ExpressionType nodeKind) { _expression = expression; _typeOperand = typeOperand; _nodeKind = nodeKind; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get { return typeof(bool); } } /// <summary> /// Returns the node type of this Expression. Extension nodes should return /// ExpressionType.Extension when overriding this method. /// </summary> /// <returns>The <see cref="ExpressionType"/> of the expression.</returns> public sealed override ExpressionType NodeType { get { return _nodeKind; } } /// <summary> /// Gets the expression operand of a type test operation. /// </summary> public Expression Expression { get { return _expression; } } /// <summary> /// Gets the type operand of a type test operation. /// </summary> public Type TypeOperand { get { return _typeOperand; } } #region Reduce TypeEqual internal Expression ReduceTypeEqual() { Type cType = Expression.Type; // For value types (including Void, but not nullables), we can // determine the result now if (cType.GetTypeInfo().IsValueType && !cType.IsNullableType()) { return Expression.Block(Expression, Expression.Constant(cType == _typeOperand.GetNonNullableType())); } // Can check the value right now for constants. if (Expression.NodeType == ExpressionType.Constant) { return ReduceConstantTypeEqual(); } // If the operand type is a sealed reference type or a nullable // type, it will match if value is not null if (cType.GetTypeInfo().IsSealed && (cType == _typeOperand)) { if (cType.IsNullableType()) { return Expression.NotEqual(Expression, Expression.Constant(null, Expression.Type)); } else { return Expression.ReferenceNotEqual(Expression, Expression.Constant(null, Expression.Type)); } } // expression is a ByVal parameter. Can safely reevaluate. var parameter = Expression as ParameterExpression; if (parameter != null && !parameter.IsByRef) { return ByValParameterTypeEqual(parameter); } // Create a temp so we only evaluate the left side once parameter = Expression.Parameter(typeof(object)); // Convert to object if necessary var expression = Expression; if (!TypeUtils.AreReferenceAssignable(typeof(object), expression.Type)) { expression = Expression.Convert(expression, typeof(object)); } return Expression.Block( new[] { parameter }, Expression.Assign(parameter, expression), ByValParameterTypeEqual(parameter) ); } // Helper that is used when re-eval of LHS is safe. private Expression ByValParameterTypeEqual(ParameterExpression value) { Expression getType = Expression.Call(value, typeof(object).GetMethod("GetType")); // In remoting scenarios, obj.GetType() can return an interface. // But JIT32's optimized "obj.GetType() == typeof(ISomething)" codegen, // causing it to always return false. // We workaround this optimization by generating different, less optimal IL // if TypeOperand is an interface. if (_typeOperand.GetTypeInfo().IsInterface) { var temp = Expression.Parameter(typeof(Type)); getType = Expression.Block(new[] { temp }, Expression.Assign(temp, getType), temp); } // We use reference equality when comparing to null for correctness // (don't invoke a user defined operator), and reference equality // on types for performance (so the JIT can optimize the IL). return Expression.AndAlso( Expression.ReferenceNotEqual(value, Expression.Constant(null)), Expression.ReferenceEqual( getType, Expression.Constant(_typeOperand.GetNonNullableType(), typeof(Type)) ) ); } private Expression ReduceConstantTypeEqual() { ConstantExpression ce = Expression as ConstantExpression; //TypeEqual(null, T) always returns false. if (ce.Value == null) { return Expression.Constant(false); } else { return Expression.Constant(_typeOperand.GetNonNullableType() == ce.Value.GetType()); } } #endregion /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitTypeBinary(this); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="expression">The <see cref="Expression" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public TypeBinaryExpression Update(Expression expression) { if (expression == Expression) { return this; } if (NodeType == ExpressionType.TypeIs) { return Expression.TypeIs(expression, TypeOperand); } return Expression.TypeEqual(expression, TypeOperand); } } public partial class Expression { /// <summary> /// Creates a <see cref="TypeBinaryExpression"/>. /// </summary> /// <param name="expression">An <see cref="Expression"/> to set the <see cref="Expression"/> property equal to.</param> /// <param name="type">A <see cref="Type"/> to set the <see cref="TypeBinaryExpression.TypeOperand"/> property equal to.</param> /// <returns>A <see cref="TypeBinaryExpression"/> for which the <see cref="NodeType"/> property is equal to <see cref="TypeIs"/> and for which the <see cref="Expression"/> and <see cref="TypeBinaryExpression.TypeOperand"/> properties are set to the specified values.</returns> public static TypeBinaryExpression TypeIs(Expression expression, Type type) { RequiresCanRead(expression, "expression"); ContractUtils.RequiresNotNull(type, "type"); if (type.IsByRef) throw Error.TypeMustNotBeByRef(); return new TypeBinaryExpression(expression, type, ExpressionType.TypeIs); } /// <summary> /// Creates a <see cref="TypeBinaryExpression"/> that compares run-time type identity. /// </summary> /// <param name="expression">An <see cref="Expression"/> to set the <see cref="Expression"/> property equal to.</param> /// <param name="type">A <see cref="Type"/> to set the <see cref="TypeBinaryExpression.TypeOperand"/> property equal to.</param> /// <returns>A <see cref="TypeBinaryExpression"/> for which the <see cref="NodeType"/> property is equal to <see cref="TypeEqual"/> and for which the <see cref="Expression"/> and <see cref="TypeBinaryExpression.TypeOperand"/> properties are set to the specified values.</returns> public static TypeBinaryExpression TypeEqual(Expression expression, Type type) { RequiresCanRead(expression, "expression"); ContractUtils.RequiresNotNull(type, "type"); if (type.IsByRef) throw Error.TypeMustNotBeByRef(); return new TypeBinaryExpression(expression, type, ExpressionType.TypeEqual); } } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dataproc.V1.Snippets { using Google.Api.Gax; using Google.Api.Gax.Grpc; using apis = Google.Cloud.Dataproc.V1; using Google.LongRunning; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; /// <summary>Generated snippets</summary> public class GeneratedClusterControllerClientSnippets { /// <summary>Snippet for CreateClusterAsync</summary> public async Task CreateClusterAsync() { // Snippet: CreateClusterAsync(string,string,Cluster,CallSettings) // Additional: CreateClusterAsync(string,string,Cluster,CancellationToken) // Create client ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; string region = ""; Cluster cluster = new Cluster(); // Make the request Operation<Cluster, ClusterOperationMetadata> response = await clusterControllerClient.CreateClusterAsync(projectId, region, cluster); // Poll until the returned long-running operation is complete Operation<Cluster, ClusterOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Cluster result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Cluster, ClusterOperationMetadata> retrievedResponse = await clusterControllerClient.PollOnceCreateClusterAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Cluster retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateCluster</summary> public void CreateCluster() { // Snippet: CreateCluster(string,string,Cluster,CallSettings) // Create client ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create(); // Initialize request argument(s) string projectId = ""; string region = ""; Cluster cluster = new Cluster(); // Make the request Operation<Cluster, ClusterOperationMetadata> response = clusterControllerClient.CreateCluster(projectId, region, cluster); // Poll until the returned long-running operation is complete Operation<Cluster, ClusterOperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Cluster result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Cluster, ClusterOperationMetadata> retrievedResponse = clusterControllerClient.PollOnceCreateCluster(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Cluster retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateClusterAsync</summary> public async Task CreateClusterAsync_RequestObject() { // Snippet: CreateClusterAsync(CreateClusterRequest,CallSettings) // Create client ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync(); // Initialize request argument(s) CreateClusterRequest request = new CreateClusterRequest { ProjectId = "", Region = "", Cluster = new Cluster(), }; // Make the request Operation<Cluster, ClusterOperationMetadata> response = await clusterControllerClient.CreateClusterAsync(request); // Poll until the returned long-running operation is complete Operation<Cluster, ClusterOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Cluster result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Cluster, ClusterOperationMetadata> retrievedResponse = await clusterControllerClient.PollOnceCreateClusterAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Cluster retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateCluster</summary> public void CreateCluster_RequestObject() { // Snippet: CreateCluster(CreateClusterRequest,CallSettings) // Create client ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create(); // Initialize request argument(s) CreateClusterRequest request = new CreateClusterRequest { ProjectId = "", Region = "", Cluster = new Cluster(), }; // Make the request Operation<Cluster, ClusterOperationMetadata> response = clusterControllerClient.CreateCluster(request); // Poll until the returned long-running operation is complete Operation<Cluster, ClusterOperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Cluster result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Cluster, ClusterOperationMetadata> retrievedResponse = clusterControllerClient.PollOnceCreateCluster(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Cluster retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateClusterAsync</summary> public async Task UpdateClusterAsync_RequestObject() { // Snippet: UpdateClusterAsync(UpdateClusterRequest,CallSettings) // Create client ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync(); // Initialize request argument(s) UpdateClusterRequest request = new UpdateClusterRequest { ProjectId = "", Region = "", ClusterName = "", Cluster = new Cluster(), UpdateMask = new FieldMask(), }; // Make the request Operation<Cluster, ClusterOperationMetadata> response = await clusterControllerClient.UpdateClusterAsync(request); // Poll until the returned long-running operation is complete Operation<Cluster, ClusterOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Cluster result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Cluster, ClusterOperationMetadata> retrievedResponse = await clusterControllerClient.PollOnceUpdateClusterAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Cluster retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateCluster</summary> public void UpdateCluster_RequestObject() { // Snippet: UpdateCluster(UpdateClusterRequest,CallSettings) // Create client ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create(); // Initialize request argument(s) UpdateClusterRequest request = new UpdateClusterRequest { ProjectId = "", Region = "", ClusterName = "", Cluster = new Cluster(), UpdateMask = new FieldMask(), }; // Make the request Operation<Cluster, ClusterOperationMetadata> response = clusterControllerClient.UpdateCluster(request); // Poll until the returned long-running operation is complete Operation<Cluster, ClusterOperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Cluster result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Cluster, ClusterOperationMetadata> retrievedResponse = clusterControllerClient.PollOnceUpdateCluster(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Cluster retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteClusterAsync</summary> public async Task DeleteClusterAsync() { // Snippet: DeleteClusterAsync(string,string,string,CallSettings) // Additional: DeleteClusterAsync(string,string,string,CancellationToken) // Create client ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; string region = ""; string clusterName = ""; // Make the request Operation<Empty, ClusterOperationMetadata> response = await clusterControllerClient.DeleteClusterAsync(projectId, region, clusterName); // Poll until the returned long-running operation is complete Operation<Empty, ClusterOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // The long-running operation is now complete. // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, ClusterOperationMetadata> retrievedResponse = await clusterControllerClient.PollOnceDeleteClusterAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // The long-running operation is now complete. } // End snippet } /// <summary>Snippet for DeleteCluster</summary> public void DeleteCluster() { // Snippet: DeleteCluster(string,string,string,CallSettings) // Create client ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create(); // Initialize request argument(s) string projectId = ""; string region = ""; string clusterName = ""; // Make the request Operation<Empty, ClusterOperationMetadata> response = clusterControllerClient.DeleteCluster(projectId, region, clusterName); // Poll until the returned long-running operation is complete Operation<Empty, ClusterOperationMetadata> completedResponse = response.PollUntilCompleted(); // The long-running operation is now complete. // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, ClusterOperationMetadata> retrievedResponse = clusterControllerClient.PollOnceDeleteCluster(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // The long-running operation is now complete. } // End snippet } /// <summary>Snippet for DeleteClusterAsync</summary> public async Task DeleteClusterAsync_RequestObject() { // Snippet: DeleteClusterAsync(DeleteClusterRequest,CallSettings) // Create client ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync(); // Initialize request argument(s) DeleteClusterRequest request = new DeleteClusterRequest { ProjectId = "", Region = "", ClusterName = "", }; // Make the request Operation<Empty, ClusterOperationMetadata> response = await clusterControllerClient.DeleteClusterAsync(request); // Poll until the returned long-running operation is complete Operation<Empty, ClusterOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // The long-running operation is now complete. // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, ClusterOperationMetadata> retrievedResponse = await clusterControllerClient.PollOnceDeleteClusterAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // The long-running operation is now complete. } // End snippet } /// <summary>Snippet for DeleteCluster</summary> public void DeleteCluster_RequestObject() { // Snippet: DeleteCluster(DeleteClusterRequest,CallSettings) // Create client ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create(); // Initialize request argument(s) DeleteClusterRequest request = new DeleteClusterRequest { ProjectId = "", Region = "", ClusterName = "", }; // Make the request Operation<Empty, ClusterOperationMetadata> response = clusterControllerClient.DeleteCluster(request); // Poll until the returned long-running operation is complete Operation<Empty, ClusterOperationMetadata> completedResponse = response.PollUntilCompleted(); // The long-running operation is now complete. // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, ClusterOperationMetadata> retrievedResponse = clusterControllerClient.PollOnceDeleteCluster(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // The long-running operation is now complete. } // End snippet } /// <summary>Snippet for GetClusterAsync</summary> public async Task GetClusterAsync() { // Snippet: GetClusterAsync(string,string,string,CallSettings) // Additional: GetClusterAsync(string,string,string,CancellationToken) // Create client ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; string region = ""; string clusterName = ""; // Make the request Cluster response = await clusterControllerClient.GetClusterAsync(projectId, region, clusterName); // End snippet } /// <summary>Snippet for GetCluster</summary> public void GetCluster() { // Snippet: GetCluster(string,string,string,CallSettings) // Create client ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create(); // Initialize request argument(s) string projectId = ""; string region = ""; string clusterName = ""; // Make the request Cluster response = clusterControllerClient.GetCluster(projectId, region, clusterName); // End snippet } /// <summary>Snippet for GetClusterAsync</summary> public async Task GetClusterAsync_RequestObject() { // Snippet: GetClusterAsync(GetClusterRequest,CallSettings) // Additional: GetClusterAsync(GetClusterRequest,CancellationToken) // Create client ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync(); // Initialize request argument(s) GetClusterRequest request = new GetClusterRequest { ProjectId = "", Region = "", ClusterName = "", }; // Make the request Cluster response = await clusterControllerClient.GetClusterAsync(request); // End snippet } /// <summary>Snippet for GetCluster</summary> public void GetCluster_RequestObject() { // Snippet: GetCluster(GetClusterRequest,CallSettings) // Create client ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create(); // Initialize request argument(s) GetClusterRequest request = new GetClusterRequest { ProjectId = "", Region = "", ClusterName = "", }; // Make the request Cluster response = clusterControllerClient.GetCluster(request); // End snippet } /// <summary>Snippet for ListClustersAsync</summary> public async Task ListClustersAsync() { // Snippet: ListClustersAsync(string,string,string,int?,CallSettings) // Create client ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; string region = ""; // Make the request PagedAsyncEnumerable<ListClustersResponse, Cluster> response = clusterControllerClient.ListClustersAsync(projectId, region); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Cluster item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListClustersResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Cluster item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Cluster> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Cluster item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListClusters</summary> public void ListClusters() { // Snippet: ListClusters(string,string,string,int?,CallSettings) // Create client ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create(); // Initialize request argument(s) string projectId = ""; string region = ""; // Make the request PagedEnumerable<ListClustersResponse, Cluster> response = clusterControllerClient.ListClusters(projectId, region); // Iterate over all response items, lazily performing RPCs as required foreach (Cluster item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListClustersResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Cluster item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Cluster> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Cluster item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListClustersAsync</summary> public async Task ListClustersAsync_RequestObject() { // Snippet: ListClustersAsync(ListClustersRequest,CallSettings) // Create client ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync(); // Initialize request argument(s) ListClustersRequest request = new ListClustersRequest { ProjectId = "", Region = "", }; // Make the request PagedAsyncEnumerable<ListClustersResponse, Cluster> response = clusterControllerClient.ListClustersAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Cluster item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListClustersResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Cluster item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Cluster> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Cluster item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListClusters</summary> public void ListClusters_RequestObject() { // Snippet: ListClusters(ListClustersRequest,CallSettings) // Create client ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create(); // Initialize request argument(s) ListClustersRequest request = new ListClustersRequest { ProjectId = "", Region = "", }; // Make the request PagedEnumerable<ListClustersResponse, Cluster> response = clusterControllerClient.ListClusters(request); // Iterate over all response items, lazily performing RPCs as required foreach (Cluster item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListClustersResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Cluster item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Cluster> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Cluster item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for DiagnoseClusterAsync</summary> public async Task DiagnoseClusterAsync() { // Snippet: DiagnoseClusterAsync(string,string,string,CallSettings) // Additional: DiagnoseClusterAsync(string,string,string,CancellationToken) // Create client ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; string region = ""; string clusterName = ""; // Make the request Operation<Empty, DiagnoseClusterResults> response = await clusterControllerClient.DiagnoseClusterAsync(projectId, region, clusterName); // Poll until the returned long-running operation is complete Operation<Empty, DiagnoseClusterResults> completedResponse = await response.PollUntilCompletedAsync(); // The long-running operation is now complete. // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DiagnoseClusterResults> retrievedResponse = await clusterControllerClient.PollOnceDiagnoseClusterAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // The long-running operation is now complete. } // End snippet } /// <summary>Snippet for DiagnoseCluster</summary> public void DiagnoseCluster() { // Snippet: DiagnoseCluster(string,string,string,CallSettings) // Create client ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create(); // Initialize request argument(s) string projectId = ""; string region = ""; string clusterName = ""; // Make the request Operation<Empty, DiagnoseClusterResults> response = clusterControllerClient.DiagnoseCluster(projectId, region, clusterName); // Poll until the returned long-running operation is complete Operation<Empty, DiagnoseClusterResults> completedResponse = response.PollUntilCompleted(); // The long-running operation is now complete. // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DiagnoseClusterResults> retrievedResponse = clusterControllerClient.PollOnceDiagnoseCluster(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // The long-running operation is now complete. } // End snippet } /// <summary>Snippet for DiagnoseClusterAsync</summary> public async Task DiagnoseClusterAsync_RequestObject() { // Snippet: DiagnoseClusterAsync(DiagnoseClusterRequest,CallSettings) // Create client ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync(); // Initialize request argument(s) DiagnoseClusterRequest request = new DiagnoseClusterRequest { ProjectId = "", Region = "", ClusterName = "", }; // Make the request Operation<Empty, DiagnoseClusterResults> response = await clusterControllerClient.DiagnoseClusterAsync(request); // Poll until the returned long-running operation is complete Operation<Empty, DiagnoseClusterResults> completedResponse = await response.PollUntilCompletedAsync(); // The long-running operation is now complete. // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DiagnoseClusterResults> retrievedResponse = await clusterControllerClient.PollOnceDiagnoseClusterAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // The long-running operation is now complete. } // End snippet } /// <summary>Snippet for DiagnoseCluster</summary> public void DiagnoseCluster_RequestObject() { // Snippet: DiagnoseCluster(DiagnoseClusterRequest,CallSettings) // Create client ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create(); // Initialize request argument(s) DiagnoseClusterRequest request = new DiagnoseClusterRequest { ProjectId = "", Region = "", ClusterName = "", }; // Make the request Operation<Empty, DiagnoseClusterResults> response = clusterControllerClient.DiagnoseCluster(request); // Poll until the returned long-running operation is complete Operation<Empty, DiagnoseClusterResults> completedResponse = response.PollUntilCompleted(); // The long-running operation is now complete. // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DiagnoseClusterResults> retrievedResponse = clusterControllerClient.PollOnceDiagnoseCluster(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // The long-running operation is now complete. } // End snippet } } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using TheArtOfDev.HtmlRenderer.Adapters; using TheArtOfDev.HtmlRenderer.Adapters.Entities; using TheArtOfDev.HtmlRenderer.Core.Utils; using TheArtOfDev.HtmlRenderer.PdfSharp.Utilities; using PdfSharp.Drawing; namespace TheArtOfDev.HtmlRenderer.PdfSharp.Adapters { /// <summary> /// Adapter for WinForms Graphics for core. /// </summary> internal sealed class GraphicsAdapter : RGraphics { #region Fields and Consts /// <summary> /// The wrapped WinForms graphics object /// </summary> private readonly XGraphics _g; /// <summary> /// if to release the graphics object on dispose /// </summary> private readonly bool _releaseGraphics; /// <summary> /// Used to measure and draw strings /// </summary> private static readonly XStringFormat _stringFormat; #endregion static GraphicsAdapter() { _stringFormat = new XStringFormat(); _stringFormat.Alignment = XStringAlignment.Near; _stringFormat.LineAlignment = XLineAlignment.Near; _stringFormat.FormatFlags = XStringFormatFlags.MeasureTrailingSpaces; } /// <summary> /// Init. /// </summary> /// <param name="g">the win forms graphics object to use</param> /// <param name="releaseGraphics">optional: if to release the graphics object on dispose (default - false)</param> public GraphicsAdapter(XGraphics g, bool releaseGraphics = false) : base(PdfSharpAdapter.Instance, new RRect(0, 0, double.MaxValue, double.MaxValue)) { ArgChecker.AssertArgNotNull(g, "g"); _g = g; _releaseGraphics = releaseGraphics; } public override void PopClip() { _clipStack.Pop(); _g.Restore(); } public override void PushClip(RRect rect) { _clipStack.Push(rect); _g.Save(); _g.IntersectClip(Utils.Convert(rect)); } public override void PushClipExclude(RRect rect) { } public override Object SetAntiAliasSmoothingMode() { var prevMode = _g.SmoothingMode; _g.SmoothingMode = XSmoothingMode.AntiAlias; return prevMode; } public override void ReturnPreviousSmoothingMode(Object prevMode) { if (prevMode != null) { _g.SmoothingMode = (XSmoothingMode)prevMode; } } public override RSize MeasureString(string str, RFont font) { var fontAdapter = (FontAdapter)font; var realFont = fontAdapter.Font; var size = _g.MeasureString(str, realFont, _stringFormat); if (font.Height < 0) { var height = realFont.Height; var descent = realFont.Size * realFont.FontFamily.GetCellDescent(realFont.Style) / realFont.FontFamily.GetEmHeight(realFont.Style); fontAdapter.SetMetrics(height, (int)Math.Round((height - descent + 1f))); } return Utils.Convert(size); } public override void MeasureString(string str, RFont font, double maxWidth, out int charFit, out double charFitWidth) { // there is no need for it - used for text selection throw new NotSupportedException(); } public override void DrawString(string str, RFont font, RColor color, RPoint point, RSize size, bool rtl) { var xBrush = ((BrushAdapter)_adapter.GetSolidBrush(color)).Brush; _g.DrawString(str, ((FontAdapter)font).Font, (XBrush)xBrush, point.X, point.Y, _stringFormat); } public override RBrush GetTextureBrush(RImage image, RRect dstRect, RPoint translateTransformLocation) { return new BrushAdapter(new XTextureBrush(((ImageAdapter)image).Image, Utils.Convert(dstRect), Utils.Convert(translateTransformLocation))); } public override RGraphicsPath GetGraphicsPath() { return new GraphicsPathAdapter(); } public override void Dispose() { if (_releaseGraphics) _g.Dispose(); } #region Delegate graphics methods public override void DrawLine(RPen pen, double x1, double y1, double x2, double y2) { _g.DrawLine(((PenAdapter)pen).Pen, x1, y1, x2, y2); } public override void DrawRectangle(RPen pen, double x, double y, double width, double height) { _g.DrawRectangle(((PenAdapter)pen).Pen, x, y, width, height); } public override void DrawRectangle(RBrush brush, double x, double y, double width, double height) { var xBrush = ((BrushAdapter)brush).Brush; var xTextureBrush = xBrush as XTextureBrush; if (xTextureBrush != null) { xTextureBrush.DrawRectangle(_g, x, y, width, height); } else { _g.DrawRectangle((XBrush)xBrush, x, y, width, height); // handle bug in PdfSharp that keeps the brush color for next string draw if (xBrush is XLinearGradientBrush) _g.DrawRectangle(XBrushes.White, 0, 0, 0.1, 0.1); } } public override void DrawImage(RImage image, RRect destRect, RRect srcRect) { _g.DrawImage(((ImageAdapter)image).Image, Utils.Convert(destRect), Utils.Convert(srcRect), XGraphicsUnit.Point); } public override void DrawImage(RImage image, RRect destRect) { _g.DrawImage(((ImageAdapter)image).Image, Utils.Convert(destRect)); } public override void DrawPath(RPen pen, RGraphicsPath path) { _g.DrawPath(((PenAdapter)pen).Pen, ((GraphicsPathAdapter)path).GraphicsPath); } public override void DrawPath(RBrush brush, RGraphicsPath path) { _g.DrawPath((XBrush)((BrushAdapter)brush).Brush, ((GraphicsPathAdapter)path).GraphicsPath); } public override void DrawPolygon(RBrush brush, RPoint[] points) { if (points != null && points.Length > 0) { _g.DrawPolygon((XBrush)((BrushAdapter)brush).Brush, Utils.Convert(points), XFillMode.Winding); } } #endregion } }
/* * CCControlSlider * * Copyright 2011 Yannick Loriot. All rights reserved. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * Converted to c++ / cocos2d-x by Angus C */ using System; using System.Diagnostics; namespace Cocos2D { public class CCControlSlider : CCControl { //maunally put in the setters private CCSprite _backgroundSprite; private float _maximumAllowedValue; private float _maximumValue; private float _minimumAllowedValue; private float _minimumValue; private CCSprite _progressSprite; private CCSprite _thumbSprite; private float _value; public float Value { get { return _value; } set { // set new value with sentinel if (value < _minimumValue) { value = _minimumValue; } if (value > _maximumValue) { value = _maximumValue; } _value = value; NeedsLayout(); SendActionsForControlEvents(CCControlEvent.ValueChanged); } } public float MinimumAllowedValue { get { return _minimumAllowedValue; } set { _minimumAllowedValue = value; } } public float MinimumValue { get { return _minimumValue; } set { _minimumValue = value; _minimumAllowedValue = value; if (_minimumValue >= _maximumValue) { _maximumValue = _minimumValue + 1.0f; } Value = _value; } } public float MaximumAllowedValue { get { return _maximumAllowedValue; } set { _maximumAllowedValue = value; } } public float MaximumValue { get { return _maximumValue; } set { _maximumValue = value; _maximumAllowedValue = value; if (_maximumValue <= _minimumValue) { _minimumValue = _maximumValue - 1.0f; } Value = _value; } } //interval to snap to public float SnappingInterval { get; set; } // maybe this should be read-only public CCSprite ThumbSprite { get { return _thumbSprite; } set { _thumbSprite = value; } } public CCSprite ProgressSprite { get { return _progressSprite; } set { _progressSprite = value; } } public CCSprite BackgroundSprite { get { return _backgroundSprite; } set { _backgroundSprite = value; } } public override bool Enabled { get { return base.Enabled; } set { base.Enabled = value; if (_thumbSprite != null) { _thumbSprite.Opacity = (byte) (value ? 255 : 128); } } } /** * Initializes a slider with a background sprite, a progress bar and a thumb * item. * * @param backgroundSprite CCSprite, that is used as a background. * @param progressSprite CCSprite, that is used as a progress bar. * @param thumbItem CCMenuItem, that is used as a thumb. */ public virtual bool InitWithSprites(CCSprite backgroundSprite, CCSprite progressSprite, CCSprite thumbSprite) { if (base.Init()) { Debug.Assert(backgroundSprite != null, "Background sprite must be not nil"); Debug.Assert(progressSprite != null, "Progress sprite must be not nil"); Debug.Assert(thumbSprite != null, "Thumb sprite must be not nil"); IgnoreAnchorPointForPosition = false; TouchEnabled = true; BackgroundSprite = backgroundSprite; ProgressSprite = progressSprite; ThumbSprite = thumbSprite; // Defines the content size CCRect maxRect = CCControlUtils.CCRectUnion(backgroundSprite.BoundingBox, thumbSprite.BoundingBox); ContentSize = new CCSize(maxRect.Size.Width, maxRect.Size.Height); //setContentSize(CCSizeMake(backgroundSprite->getContentSize().width, thumbItem->getContentSize().height)); // Add the slider background _backgroundSprite.AnchorPoint = new CCPoint(0.5f, 0.5f); _backgroundSprite.Position = new CCPoint(ContentSize.Width / 2, ContentSize.Height / 2); AddChild(_backgroundSprite); // Add the progress bar _progressSprite.AnchorPoint = new CCPoint(0.0f, 0.5f); _progressSprite.Position = new CCPoint(0.0f, ContentSize.Height / 2); AddChild(_progressSprite); // Add the slider thumb _thumbSprite.Position = new CCPoint(0, ContentSize.Height / 2); AddChild(_thumbSprite); // Init default values _minimumValue = 0.0f; _maximumValue = 1.0f; Value = _minimumValue; return true; } return false; } /** * Creates slider with a background filename, a progress filename and a * thumb image filename. */ public CCControlSlider(string bgFile, string progressFile, string thumbFile) { // Prepare background for slider CCSprite backgroundSprite = new CCSprite(bgFile); // Prepare progress for slider CCSprite progressSprite = new CCSprite(progressFile); // Prepare thumb (menuItem) for slider CCSprite thumbSprite = new CCSprite(thumbFile); InitWithSprites(backgroundSprite, progressSprite, thumbSprite); } /** * Creates a slider with a given background sprite and a progress bar and a * thumb item. * * @see initWithBackgroundSprite:progressSprite:thumbMenuItem: */ public CCControlSlider(CCSprite backgroundSprite, CCSprite progressSprite, CCSprite thumbSprite) { InitWithSprites(backgroundSprite, progressSprite, thumbSprite); } protected void SliderBegan(CCPoint location) { Selected = true; ThumbSprite.Color = CCTypes.CCGray; Value = ValueForLocation(location); } protected void SliderMoved(CCPoint location) { Value = ValueForLocation(location); } protected void SliderEnded(CCPoint location) { if (Selected) { Value = ValueForLocation(_thumbSprite.Position); } _thumbSprite.Color = CCTypes.CCWhite; Selected = false; } protected virtual CCPoint LocationFromTouch(CCTouch touch) { CCPoint touchLocation = touch.Location; // Get the touch position touchLocation = ConvertToNodeSpace(touchLocation); // Convert to the node space of this class if (touchLocation.X < 0) { touchLocation.X = 0; } else if (touchLocation.X > _backgroundSprite.ContentSize.Width) { touchLocation.X = _backgroundSprite.ContentSize.Width; } return touchLocation; } public override bool IsTouchInside(CCTouch touch) { CCPoint touchLocation = touch.Location; touchLocation = Parent.ConvertToNodeSpace(touchLocation); CCRect rect = BoundingBox; rect.Size.Width += _thumbSprite.ContentSize.Width; rect.Origin.X -= _thumbSprite.ContentSize.Width / 2; return rect.ContainsPoint(touchLocation); } public override bool TouchBegan(CCTouch touch) { if (!IsTouchInside(touch) || !Enabled || !Visible) return false; CCPoint location = LocationFromTouch(touch); SliderBegan(location); return true; } public override void TouchMoved(CCTouch pTouch) { CCPoint location = LocationFromTouch(pTouch); SliderMoved(location); } public override void TouchEnded(CCTouch pTouch) { SliderEnded(CCPoint.Zero); } public override void NeedsLayout() { if (null == _thumbSprite || null == _backgroundSprite || null == _progressSprite) { return; } // Update thumb position for new value float percent = (_value - _minimumValue) / (_maximumValue - _minimumValue); CCPoint pos = _thumbSprite.Position; pos.X = percent * _backgroundSprite.ContentSize.Width; _thumbSprite.Position = pos; // Stretches content proportional to newLevel CCRect textureRect = _progressSprite.TextureRect; textureRect = new CCRect(textureRect.Origin.X, textureRect.Origin.Y, pos.X, textureRect.Size.Height); _progressSprite.SetTextureRect(textureRect, _progressSprite.IsTextureRectRotated, textureRect.Size); } /** Returns the value for the given location. */ protected float ValueForLocation(CCPoint location) { float percent = location.X / _backgroundSprite.ContentSize.Width; return Math.Max(Math.Min(_minimumValue + percent * (_maximumValue - _minimumValue), _maximumAllowedValue), _minimumAllowedValue); } }; }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace SuggestionSystem.Web.Api.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); } } } }
// // assembly: System // namespace: System.Text.RegularExpressions // file: category.cs // // author: Dan Lewis ([email protected]) // (c) 2002 // // 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.Globalization; namespace System.Text.RegularExpressions { enum Category : ushort { None, // canonical classes Any, // any character except newline . AnySingleline, // any character . (s option) Word, // any word character \w Digit, // any digit character \d WhiteSpace, // any whitespace character \s // ECMAScript classes EcmaAny, EcmaAnySingleline, EcmaWord, // [a-zA-Z_0-9] EcmaDigit, // [0-9] EcmaWhiteSpace, // [ \f\n\r\t\v] // unicode categories UnicodeL, // Letter UnicodeM, // Mark UnicodeN, // Number UnicodeZ, // Separator UnicodeP, // Punctuation UnicodeS, // Symbol UnicodeC, // Other UnicodeLu, // UppercaseLetter UnicodeLl, // LowercaseLetter UnicodeLt, // TitlecaseLetter UnicodeLm, // ModifierLetter UnicodeLo, // OtherLetter UnicodeMn, // NonspacingMark UnicodeMe, // EnclosingMark UnicodeMc, // SpacingMark UnicodeNd, // DecimalNumber UnicodeNl, // LetterNumber UnicodeNo, // OtherNumber UnicodeZs, // SpaceSeparator UnicodeZl, // LineSeparator UnicodeZp, // ParagraphSeparator UnicodePd, // DashPunctuation UnicodePs, // OpenPunctuation UnicodePi, // InitialPunctuation UnicodePe, // ClosePunctuation UnicodePf, // FinalPunctuation UnicodePc, // ConnectorPunctuation UnicodePo, // OtherPunctuation UnicodeSm, // MathSymbol UnicodeSc, // CurrencySymbol UnicodeSk, // ModifierSymbol UnicodeSo, // OtherSymbol UnicodeCc, // Control UnicodeCf, // Format UnicodeCo, // PrivateUse UnicodeCs, // Surrogate UnicodeCn, // Unassigned // unicode block ranges // notes: the categories marked with a star are valid unicode block ranges, // but don't seem to be accepted by the MS parser using the /p{...} format. // any ideas? UnicodeBasicLatin, UnicodeLatin1Supplement, // * UnicodeLatinExtendedA, // * UnicodeLatinExtendedB, // * UnicodeIPAExtensions, UnicodeSpacingModifierLetters, UnicodeCombiningDiacriticalMarks, UnicodeGreek, UnicodeCyrillic, UnicodeArmenian, UnicodeHebrew, UnicodeArabic, UnicodeSyriac, UnicodeThaana, UnicodeDevanagari, UnicodeBengali, UnicodeGurmukhi, UnicodeGujarati, UnicodeOriya, UnicodeTamil, UnicodeTelugu, UnicodeKannada, UnicodeMalayalam, UnicodeSinhala, UnicodeThai, UnicodeLao, UnicodeTibetan, UnicodeMyanmar, UnicodeGeorgian, UnicodeHangulJamo, UnicodeEthiopic, UnicodeCherokee, UnicodeUnifiedCanadianAboriginalSyllabics, UnicodeOgham, UnicodeRunic, UnicodeKhmer, UnicodeMongolian, UnicodeLatinExtendedAdditional, UnicodeGreekExtended, UnicodeGeneralPunctuation, UnicodeSuperscriptsandSubscripts, UnicodeCurrencySymbols, UnicodeCombiningMarksforSymbols, UnicodeLetterlikeSymbols, UnicodeNumberForms, UnicodeArrows, UnicodeMathematicalOperators, UnicodeMiscellaneousTechnical, UnicodeControlPictures, UnicodeOpticalCharacterRecognition, UnicodeEnclosedAlphanumerics, UnicodeBoxDrawing, UnicodeBlockElements, UnicodeGeometricShapes, UnicodeMiscellaneousSymbols, UnicodeDingbats, UnicodeBraillePatterns, UnicodeCJKRadicalsSupplement, UnicodeKangxiRadicals, UnicodeIdeographicDescriptionCharacters, UnicodeCJKSymbolsandPunctuation, UnicodeHiragana, UnicodeKatakana, UnicodeBopomofo, UnicodeHangulCompatibilityJamo, UnicodeKanbun, UnicodeBopomofoExtended, UnicodeEnclosedCJKLettersandMonths, UnicodeCJKCompatibility, UnicodeCJKUnifiedIdeographsExtensionA, UnicodeCJKUnifiedIdeographs, UnicodeYiSyllables, UnicodeYiRadicals, UnicodeHangulSyllables, UnicodeHighSurrogates, UnicodeHighPrivateUseSurrogates, UnicodeLowSurrogates, UnicodePrivateUse, UnicodeCJKCompatibilityIdeographs, UnicodeAlphabeticPresentationForms, UnicodeArabicPresentationFormsA, // * UnicodeCombiningHalfMarks, UnicodeCJKCompatibilityForms, UnicodeSmallFormVariants, UnicodeArabicPresentationFormsB, // * UnicodeSpecials, UnicodeHalfwidthandFullwidthForms, UnicodeOldItalic, UnicodeGothic, UnicodeDeseret, UnicodeByzantineMusicalSymbols, UnicodeMusicalSymbols, UnicodeMathematicalAlphanumericSymbols, UnicodeCJKUnifiedIdeographsExtensionB, UnicodeCJKCompatibilityIdeographsSupplement, UnicodeTags, LastValue // Keep this with the higher value in the enumeration } class CategoryUtils { public static Category CategoryFromName (string name) { try { if (name.StartsWith ("Is")) // remove prefix from block range name = name.Substring (2); return (Category)Enum.Parse (typeof (Category), "Unicode" + name); } catch (ArgumentException) { return Category.None; } } public static bool IsCategory (Category cat, char c) { switch (cat) { case Category.None: return false; case Category.Any: return c != '\n'; case Category.AnySingleline: return true; case Category.Word: return Char.IsLetterOrDigit (c) || IsCategory (UnicodeCategory.ConnectorPunctuation, c); case Category.Digit: return Char.IsDigit (c); case Category.WhiteSpace: return Char.IsWhiteSpace (c); // ECMA categories case Category.EcmaAny: return c != '\n'; case Category.EcmaAnySingleline: return true; case Category.EcmaWord: return 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' || '_' == c; case Category.EcmaDigit: return '0' <= c && c <= '9'; case Category.EcmaWhiteSpace: return c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v'; // Unicode categories... // letter case Category.UnicodeLu: return IsCategory (UnicodeCategory.UppercaseLetter, c); case Category.UnicodeLl: return IsCategory (UnicodeCategory.LowercaseLetter, c); case Category.UnicodeLt: return IsCategory (UnicodeCategory.TitlecaseLetter, c); case Category.UnicodeLm: return IsCategory (UnicodeCategory.ModifierLetter, c); case Category.UnicodeLo: return IsCategory (UnicodeCategory.OtherLetter, c); // mark case Category.UnicodeMn: return IsCategory (UnicodeCategory.NonSpacingMark, c); case Category.UnicodeMe: return IsCategory (UnicodeCategory.EnclosingMark, c); case Category.UnicodeMc: return IsCategory (UnicodeCategory.SpacingCombiningMark, c); case Category.UnicodeNd: return IsCategory (UnicodeCategory.DecimalDigitNumber, c); // number case Category.UnicodeNl: return IsCategory (UnicodeCategory.LetterNumber, c); case Category.UnicodeNo: return IsCategory (UnicodeCategory.OtherNumber, c); // separator case Category.UnicodeZs: return IsCategory (UnicodeCategory.SpaceSeparator, c); case Category.UnicodeZl: return IsCategory (UnicodeCategory.LineSeparator, c); case Category.UnicodeZp: return IsCategory (UnicodeCategory.ParagraphSeparator, c); // punctuation case Category.UnicodePd: return IsCategory (UnicodeCategory.DashPunctuation, c); case Category.UnicodePs: return IsCategory (UnicodeCategory.OpenPunctuation, c); case Category.UnicodePi: return IsCategory (UnicodeCategory.InitialQuotePunctuation, c); case Category.UnicodePe: return IsCategory (UnicodeCategory.ClosePunctuation, c); case Category.UnicodePf: return IsCategory (UnicodeCategory.FinalQuotePunctuation, c); case Category.UnicodePc: return IsCategory (UnicodeCategory.ConnectorPunctuation, c); case Category.UnicodePo: return IsCategory (UnicodeCategory.OtherPunctuation, c); // symbol case Category.UnicodeSm: return IsCategory (UnicodeCategory.MathSymbol, c); case Category.UnicodeSc: return IsCategory (UnicodeCategory.CurrencySymbol, c); case Category.UnicodeSk: return IsCategory (UnicodeCategory.ModifierSymbol, c); case Category.UnicodeSo: return IsCategory (UnicodeCategory.OtherSymbol, c); // other case Category.UnicodeCc: return IsCategory (UnicodeCategory.Control, c); case Category.UnicodeCf: return IsCategory (UnicodeCategory.Format, c); case Category.UnicodeCo: return IsCategory (UnicodeCategory.PrivateUse, c); case Category.UnicodeCs: return IsCategory (UnicodeCategory.Surrogate, c); case Category.UnicodeCn: return IsCategory (UnicodeCategory.OtherNotAssigned, c); case Category.UnicodeL: // letter return IsCategory (UnicodeCategory.UppercaseLetter, c) || IsCategory (UnicodeCategory.LowercaseLetter, c) || IsCategory (UnicodeCategory.TitlecaseLetter, c) || IsCategory (UnicodeCategory.ModifierLetter, c) || IsCategory (UnicodeCategory.OtherLetter, c); case Category.UnicodeM: // mark return IsCategory (UnicodeCategory.NonSpacingMark, c) || IsCategory (UnicodeCategory.EnclosingMark, c) || IsCategory (UnicodeCategory.SpacingCombiningMark, c); case Category.UnicodeN: // number return IsCategory (UnicodeCategory.DecimalDigitNumber, c) || IsCategory (UnicodeCategory.LetterNumber, c) || IsCategory (UnicodeCategory.OtherNumber, c); case Category.UnicodeZ: // separator return IsCategory (UnicodeCategory.SpaceSeparator, c) || IsCategory (UnicodeCategory.LineSeparator, c) || IsCategory (UnicodeCategory.ParagraphSeparator, c); case Category.UnicodeP: // punctuation return IsCategory (UnicodeCategory.DashPunctuation, c) || IsCategory (UnicodeCategory.OpenPunctuation, c) || IsCategory (UnicodeCategory.InitialQuotePunctuation, c) || IsCategory (UnicodeCategory.ClosePunctuation, c) || IsCategory (UnicodeCategory.FinalQuotePunctuation, c) || IsCategory (UnicodeCategory.ConnectorPunctuation, c) || IsCategory (UnicodeCategory.OtherPunctuation, c); case Category.UnicodeS: // symbol return IsCategory (UnicodeCategory.MathSymbol, c) || IsCategory (UnicodeCategory.CurrencySymbol, c) || IsCategory (UnicodeCategory.ModifierSymbol, c) || IsCategory (UnicodeCategory.OtherSymbol, c); case Category.UnicodeC: // other return IsCategory (UnicodeCategory.Control, c) || IsCategory (UnicodeCategory.Format, c) || IsCategory (UnicodeCategory.PrivateUse, c) || IsCategory (UnicodeCategory.Surrogate, c) || IsCategory (UnicodeCategory.OtherNotAssigned, c); // Unicode block ranges... case Category.UnicodeBasicLatin: return '\u0000' <= c && c <= '\u007F'; case Category.UnicodeLatin1Supplement: return '\u0080' <= c && c <= '\u00FF'; case Category.UnicodeLatinExtendedA: return '\u0100' <= c && c <= '\u017F'; case Category.UnicodeLatinExtendedB: return '\u0180' <= c && c <= '\u024F'; case Category.UnicodeIPAExtensions: return '\u0250' <= c && c <= '\u02AF'; case Category.UnicodeSpacingModifierLetters: return '\u02B0' <= c && c <= '\u02FF'; case Category.UnicodeCombiningDiacriticalMarks: return '\u0300' <= c && c <= '\u036F'; case Category.UnicodeGreek: return '\u0370' <= c && c <= '\u03FF'; case Category.UnicodeCyrillic: return '\u0400' <= c && c <= '\u04FF'; case Category.UnicodeArmenian: return '\u0530' <= c && c <= '\u058F'; case Category.UnicodeHebrew: return '\u0590' <= c && c <= '\u05FF'; case Category.UnicodeArabic: return '\u0600' <= c && c <= '\u06FF'; case Category.UnicodeSyriac: return '\u0700' <= c && c <= '\u074F'; case Category.UnicodeThaana: return '\u0780' <= c && c <= '\u07BF'; case Category.UnicodeDevanagari: return '\u0900' <= c && c <= '\u097F'; case Category.UnicodeBengali: return '\u0980' <= c && c <= '\u09FF'; case Category.UnicodeGurmukhi: return '\u0A00' <= c && c <= '\u0A7F'; case Category.UnicodeGujarati: return '\u0A80' <= c && c <= '\u0AFF'; case Category.UnicodeOriya: return '\u0B00' <= c && c <= '\u0B7F'; case Category.UnicodeTamil: return '\u0B80' <= c && c <= '\u0BFF'; case Category.UnicodeTelugu: return '\u0C00' <= c && c <= '\u0C7F'; case Category.UnicodeKannada: return '\u0C80' <= c && c <= '\u0CFF'; case Category.UnicodeMalayalam: return '\u0D00' <= c && c <= '\u0D7F'; case Category.UnicodeSinhala: return '\u0D80' <= c && c <= '\u0DFF'; case Category.UnicodeThai: return '\u0E00' <= c && c <= '\u0E7F'; case Category.UnicodeLao: return '\u0E80' <= c && c <= '\u0EFF'; case Category.UnicodeTibetan: return '\u0F00' <= c && c <= '\u0FFF'; case Category.UnicodeMyanmar: return '\u1000' <= c && c <= '\u109F'; case Category.UnicodeGeorgian: return '\u10A0' <= c && c <= '\u10FF'; case Category.UnicodeHangulJamo: return '\u1100' <= c && c <= '\u11FF'; case Category.UnicodeEthiopic: return '\u1200' <= c && c <= '\u137F'; case Category.UnicodeCherokee: return '\u13A0' <= c && c <= '\u13FF'; case Category.UnicodeUnifiedCanadianAboriginalSyllabics: return '\u1400' <= c && c <= '\u167F'; case Category.UnicodeOgham: return '\u1680' <= c && c <= '\u169F'; case Category.UnicodeRunic: return '\u16A0' <= c && c <= '\u16FF'; case Category.UnicodeKhmer: return '\u1780' <= c && c <= '\u17FF'; case Category.UnicodeMongolian: return '\u1800' <= c && c <= '\u18AF'; case Category.UnicodeLatinExtendedAdditional: return '\u1E00' <= c && c <= '\u1EFF'; case Category.UnicodeGreekExtended: return '\u1F00' <= c && c <= '\u1FFF'; case Category.UnicodeGeneralPunctuation: return '\u2000' <= c && c <= '\u206F'; case Category.UnicodeSuperscriptsandSubscripts: return '\u2070' <= c && c <= '\u209F'; case Category.UnicodeCurrencySymbols: return '\u20A0' <= c && c <= '\u20CF'; case Category.UnicodeCombiningMarksforSymbols: return '\u20D0' <= c && c <= '\u20FF'; case Category.UnicodeLetterlikeSymbols: return '\u2100' <= c && c <= '\u214F'; case Category.UnicodeNumberForms: return '\u2150' <= c && c <= '\u218F'; case Category.UnicodeArrows: return '\u2190' <= c && c <= '\u21FF'; case Category.UnicodeMathematicalOperators: return '\u2200' <= c && c <= '\u22FF'; case Category.UnicodeMiscellaneousTechnical: return '\u2300' <= c && c <= '\u23FF'; case Category.UnicodeControlPictures: return '\u2400' <= c && c <= '\u243F'; case Category.UnicodeOpticalCharacterRecognition: return '\u2440' <= c && c <= '\u245F'; case Category.UnicodeEnclosedAlphanumerics: return '\u2460' <= c && c <= '\u24FF'; case Category.UnicodeBoxDrawing: return '\u2500' <= c && c <= '\u257F'; case Category.UnicodeBlockElements: return '\u2580' <= c && c <= '\u259F'; case Category.UnicodeGeometricShapes: return '\u25A0' <= c && c <= '\u25FF'; case Category.UnicodeMiscellaneousSymbols: return '\u2600' <= c && c <= '\u26FF'; case Category.UnicodeDingbats: return '\u2700' <= c && c <= '\u27BF'; case Category.UnicodeBraillePatterns: return '\u2800' <= c && c <= '\u28FF'; case Category.UnicodeCJKRadicalsSupplement: return '\u2E80' <= c && c <= '\u2EFF'; case Category.UnicodeKangxiRadicals: return '\u2F00' <= c && c <= '\u2FDF'; case Category.UnicodeIdeographicDescriptionCharacters: return '\u2FF0' <= c && c <= '\u2FFF'; case Category.UnicodeCJKSymbolsandPunctuation: return '\u3000' <= c && c <= '\u303F'; case Category.UnicodeHiragana: return '\u3040' <= c && c <= '\u309F'; case Category.UnicodeKatakana: return '\u30A0' <= c && c <= '\u30FF'; case Category.UnicodeBopomofo: return '\u3100' <= c && c <= '\u312F'; case Category.UnicodeHangulCompatibilityJamo: return '\u3130' <= c && c <= '\u318F'; case Category.UnicodeKanbun: return '\u3190' <= c && c <= '\u319F'; case Category.UnicodeBopomofoExtended: return '\u31A0' <= c && c <= '\u31BF'; case Category.UnicodeEnclosedCJKLettersandMonths: return '\u3200' <= c && c <= '\u32FF'; case Category.UnicodeCJKCompatibility: return '\u3300' <= c && c <= '\u33FF'; case Category.UnicodeCJKUnifiedIdeographsExtensionA: return '\u3400' <= c && c <= '\u4DB5'; case Category.UnicodeCJKUnifiedIdeographs: return '\u4E00' <= c && c <= '\u9FFF'; case Category.UnicodeYiSyllables: return '\uA000' <= c && c <= '\uA48F'; case Category.UnicodeYiRadicals: return '\uA490' <= c && c <= '\uA4CF'; case Category.UnicodeHangulSyllables: return '\uAC00' <= c && c <= '\uD7A3'; case Category.UnicodeHighSurrogates: return '\uD800' <= c && c <= '\uDB7F'; case Category.UnicodeHighPrivateUseSurrogates: return '\uDB80' <= c && c <= '\uDBFF'; case Category.UnicodeLowSurrogates: return '\uDC00' <= c && c <= '\uDFFF'; case Category.UnicodePrivateUse: return '\uE000' <= c && c <= '\uF8FF'; case Category.UnicodeCJKCompatibilityIdeographs: return '\uF900' <= c && c <= '\uFAFF'; case Category.UnicodeAlphabeticPresentationForms: return '\uFB00' <= c && c <= '\uFB4F'; case Category.UnicodeArabicPresentationFormsA: return '\uFB50' <= c && c <= '\uFDFF'; case Category.UnicodeCombiningHalfMarks: return '\uFE20' <= c && c <= '\uFE2F'; case Category.UnicodeCJKCompatibilityForms: return '\uFE30' <= c && c <= '\uFE4F'; case Category.UnicodeSmallFormVariants: return '\uFE50' <= c && c <= '\uFE6F'; case Category.UnicodeArabicPresentationFormsB: return '\uFE70' <= c && c <= '\uFEFE'; case Category.UnicodeHalfwidthandFullwidthForms: return '\uFF00' <= c && c <= '\uFFEF'; case Category.UnicodeSpecials: return '\uFEFF' <= c && c <= '\uFEFF' || '\uFFF0' <= c && c <= '\uFFFD'; // these block ranges begin above 0x10000 case Category.UnicodeOldItalic: case Category.UnicodeGothic: case Category.UnicodeDeseret: case Category.UnicodeByzantineMusicalSymbols: case Category.UnicodeMusicalSymbols: case Category.UnicodeMathematicalAlphanumericSymbols: case Category.UnicodeCJKUnifiedIdeographsExtensionB: case Category.UnicodeCJKCompatibilityIdeographsSupplement: case Category.UnicodeTags: return false; default: return false; } } private static bool IsCategory (UnicodeCategory uc, char c) { if (Char.GetUnicodeCategory (c) == uc) return true; return false; } } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.DNSExpressBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBDNSExpressDNSExpressStatistics))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(CommonObjectStatus))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBDNSExpressDNSExpressZoneDBStatistics))] public partial class LocalLBDNSExpress : iControlInterface { public LocalLBDNSExpress() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] public void create( string [] zones, string [] targets ) { this.Invoke("create", new object [] { zones, targets}); } public System.IAsyncResult Begincreate(string [] zones,string [] targets, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { zones, targets}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // create_tsig_key //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] public void create_tsig_key( string [] keys, LocalLBDNSExpressTSIGKeyAlgorithm [] algorithms, string [] secrets ) { this.Invoke("create_tsig_key", new object [] { keys, algorithms, secrets}); } public System.IAsyncResult Begincreate_tsig_key(string [] keys,LocalLBDNSExpressTSIGKeyAlgorithm [] algorithms,string [] secrets, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create_tsig_key", new object[] { keys, algorithms, secrets}, callback, asyncState); } public void Endcreate_tsig_key(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_tsig_keys //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] public void delete_all_tsig_keys( ) { this.Invoke("delete_all_tsig_keys", new object [0]); } public System.IAsyncResult Begindelete_all_tsig_keys(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_tsig_keys", new object[0], callback, asyncState); } public void Enddelete_all_tsig_keys(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_zones //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] public void delete_all_zones( ) { this.Invoke("delete_all_zones", new object [0]); } public System.IAsyncResult Begindelete_all_zones(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_zones", new object[0], callback, asyncState); } public void Enddelete_all_zones(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_tsig_key //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] public void delete_tsig_key( string [] keys ) { this.Invoke("delete_tsig_key", new object [] { keys}); } public System.IAsyncResult Begindelete_tsig_key(string [] keys, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_tsig_key", new object[] { keys}, callback, asyncState); } public void Enddelete_tsig_key(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_zone //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] public void delete_zone( string [] zones ) { this.Invoke("delete_zone", new object [] { zones}); } public System.IAsyncResult Begindelete_zone(string [] zones, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_zone", new object[] { zones}, callback, asyncState); } public void Enddelete_zone(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_all_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBDNSExpressDNSExpressStatistics get_all_statistics( ) { object [] results = this.Invoke("get_all_statistics", new object [0]); return ((LocalLBDNSExpressDNSExpressStatistics)(results[0])); } public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState); } public LocalLBDNSExpressDNSExpressStatistics Endget_all_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBDNSExpressDNSExpressStatistics)(results[0])); } //----------------------------------------------------------------------- // get_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] get_enabled_state( string [] zones ) { object [] results = this.Invoke("get_enabled_state", new object [] { zones}); return ((CommonEnabledState [])(results[0])); } public System.IAsyncResult Beginget_enabled_state(string [] zones, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_enabled_state", new object[] { zones}, callback, asyncState); } public CommonEnabledState [] Endget_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_notify_action //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBDNSExpressNOTIFYAction [] get_notify_action( string [] zones ) { object [] results = this.Invoke("get_notify_action", new object [] { zones}); return ((LocalLBDNSExpressNOTIFYAction [])(results[0])); } public System.IAsyncResult Beginget_notify_action(string [] zones, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_notify_action", new object[] { zones}, callback, asyncState); } public LocalLBDNSExpressNOTIFYAction [] Endget_notify_action(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBDNSExpressNOTIFYAction [])(results[0])); } //----------------------------------------------------------------------- // get_object_status //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonObjectStatus [] get_object_status( string [] zones ) { object [] results = this.Invoke("get_object_status", new object [] { zones}); return ((CommonObjectStatus [])(results[0])); } public System.IAsyncResult Beginget_object_status(string [] zones, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_object_status", new object[] { zones}, callback, asyncState); } public CommonObjectStatus [] Endget_object_status(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonObjectStatus [])(results[0])); } //----------------------------------------------------------------------- // get_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBDNSExpressDNSExpressStatistics get_statistics( string [] zones ) { object [] results = this.Invoke("get_statistics", new object [] { zones}); return ((LocalLBDNSExpressDNSExpressStatistics)(results[0])); } public System.IAsyncResult Beginget_statistics(string [] zones, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistics", new object[] { zones}, callback, asyncState); } public LocalLBDNSExpressDNSExpressStatistics Endget_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBDNSExpressDNSExpressStatistics)(results[0])); } //----------------------------------------------------------------------- // get_transfer_target //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_transfer_target( string [] zones ) { object [] results = this.Invoke("get_transfer_target", new object [] { zones}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_transfer_target(string [] zones, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_transfer_target", new object[] { zones}, callback, asyncState); } public string [] Endget_transfer_target(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_tsig_key //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_tsig_key( string [] zones ) { object [] results = this.Invoke("get_tsig_key", new object [] { zones}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_tsig_key(string [] zones, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_tsig_key", new object[] { zones}, callback, asyncState); } public string [] Endget_tsig_key(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_tsig_key_algorithm //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBDNSExpressTSIGKeyAlgorithm [] get_tsig_key_algorithm( string [] keys ) { object [] results = this.Invoke("get_tsig_key_algorithm", new object [] { keys}); return ((LocalLBDNSExpressTSIGKeyAlgorithm [])(results[0])); } public System.IAsyncResult Beginget_tsig_key_algorithm(string [] keys, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_tsig_key_algorithm", new object[] { keys}, callback, asyncState); } public LocalLBDNSExpressTSIGKeyAlgorithm [] Endget_tsig_key_algorithm(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBDNSExpressTSIGKeyAlgorithm [])(results[0])); } //----------------------------------------------------------------------- // get_tsig_key_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_tsig_key_list( ) { object [] results = this.Invoke("get_tsig_key_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_tsig_key_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_tsig_key_list", new object[0], callback, asyncState); } public string [] Endget_tsig_key_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_tsig_key_secret //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_tsig_key_secret( string [] keys ) { object [] results = this.Invoke("get_tsig_key_secret", new object [] { keys}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_tsig_key_secret(string [] keys, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_tsig_key_secret", new object[] { keys}, callback, asyncState); } public string [] Endget_tsig_key_secret(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_verify_notify_tsig_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] get_verify_notify_tsig_state( string [] zones ) { object [] results = this.Invoke("get_verify_notify_tsig_state", new object [] { zones}); return ((CommonEnabledState [])(results[0])); } public System.IAsyncResult Beginget_verify_notify_tsig_state(string [] zones, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_verify_notify_tsig_state", new object[] { zones}, callback, asyncState); } public CommonEnabledState [] Endget_verify_notify_tsig_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // get_zone_db_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBDNSExpressDNSExpressZoneDBStatistics get_zone_db_statistics( string [] zones, long [] sizes ) { object [] results = this.Invoke("get_zone_db_statistics", new object [] { zones, sizes}); return ((LocalLBDNSExpressDNSExpressZoneDBStatistics)(results[0])); } public System.IAsyncResult Beginget_zone_db_statistics(string [] zones,long [] sizes, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_zone_db_statistics", new object[] { zones, sizes}, callback, asyncState); } public LocalLBDNSExpressDNSExpressZoneDBStatistics Endget_zone_db_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBDNSExpressDNSExpressZoneDBStatistics)(results[0])); } //----------------------------------------------------------------------- // set_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] public void set_enabled_state( string [] zones, CommonEnabledState [] states ) { this.Invoke("set_enabled_state", new object [] { zones, states}); } public System.IAsyncResult Beginset_enabled_state(string [] zones,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_enabled_state", new object[] { zones, states}, callback, asyncState); } public void Endset_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_notify_action //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] public void set_notify_action( string [] zones, LocalLBDNSExpressNOTIFYAction [] actions ) { this.Invoke("set_notify_action", new object [] { zones, actions}); } public System.IAsyncResult Beginset_notify_action(string [] zones,LocalLBDNSExpressNOTIFYAction [] actions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_notify_action", new object[] { zones, actions}, callback, asyncState); } public void Endset_notify_action(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_transfer_target //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] public void set_transfer_target( string [] zones, string [] targets ) { this.Invoke("set_transfer_target", new object [] { zones, targets}); } public System.IAsyncResult Beginset_transfer_target(string [] zones,string [] targets, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_transfer_target", new object[] { zones, targets}, callback, asyncState); } public void Endset_transfer_target(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_tsig_key //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] public void set_tsig_key( string [] zones, string [] keys ) { this.Invoke("set_tsig_key", new object [] { zones, keys}); } public System.IAsyncResult Beginset_tsig_key(string [] zones,string [] keys, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_tsig_key", new object[] { zones, keys}, callback, asyncState); } public void Endset_tsig_key(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_tsig_key_algorithm //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] public void set_tsig_key_algorithm( string [] keys, LocalLBDNSExpressTSIGKeyAlgorithm [] algorithms ) { this.Invoke("set_tsig_key_algorithm", new object [] { keys, algorithms}); } public System.IAsyncResult Beginset_tsig_key_algorithm(string [] keys,LocalLBDNSExpressTSIGKeyAlgorithm [] algorithms, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_tsig_key_algorithm", new object[] { keys, algorithms}, callback, asyncState); } public void Endset_tsig_key_algorithm(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_tsig_key_secret //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] public void set_tsig_key_secret( string [] keys, string [] secrets ) { this.Invoke("set_tsig_key_secret", new object [] { keys, secrets}); } public System.IAsyncResult Beginset_tsig_key_secret(string [] keys,string [] secrets, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_tsig_key_secret", new object[] { keys, secrets}, callback, asyncState); } public void Endset_tsig_key_secret(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_verify_notify_tsig_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSExpress", RequestNamespace="urn:iControl:LocalLB/DNSExpress", ResponseNamespace="urn:iControl:LocalLB/DNSExpress")] public void set_verify_notify_tsig_state( string [] zones, CommonEnabledState [] states ) { this.Invoke("set_verify_notify_tsig_state", new object [] { zones, states}); } public System.IAsyncResult Beginset_verify_notify_tsig_state(string [] zones,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_verify_notify_tsig_state", new object[] { zones, states}, callback, asyncState); } public void Endset_verify_notify_tsig_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.DNSExpress.NOTIFYAction", Namespace = "urn:iControl")] public enum LocalLBDNSExpressNOTIFYAction { DNS_EXPRESS_NOTIFY_ACTION_UNKNOWN, DNS_EXPRESS_NOTIFY_ACTION_CONSUME, DNS_EXPRESS_NOTIFY_ACTION_BYPASS, DNS_EXPRESS_NOTIFY_ACTION_REPEAT, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.DNSExpress.TSIGKeyAlgorithm", Namespace = "urn:iControl")] public enum LocalLBDNSExpressTSIGKeyAlgorithm { KEY_ALGORITHM_UNKNOWN, KEY_ALGORITHM_HMACMD5, KEY_ALGORITHM_HMACSHA1, KEY_ALGORITHM_HMACSHA256, } //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.DNSExpress.DNSExpressStatisticEntry", Namespace = "urn:iControl")] public partial class LocalLBDNSExpressDNSExpressStatisticEntry { private string zoneField; public string zone { get { return this.zoneField; } set { this.zoneField = value; } } private CommonStatistic [] statisticsField; public CommonStatistic [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.DNSExpress.DNSExpressStatistics", Namespace = "urn:iControl")] public partial class LocalLBDNSExpressDNSExpressStatistics { private LocalLBDNSExpressDNSExpressStatisticEntry [] statisticsField; public LocalLBDNSExpressDNSExpressStatisticEntry [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } private CommonTimeStamp time_stampField; public CommonTimeStamp time_stamp { get { return this.time_stampField; } set { this.time_stampField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.DNSExpress.DNSExpressZoneDBEntry", Namespace = "urn:iControl")] public partial class LocalLBDNSExpressDNSExpressZoneDBEntry { private string nameField; public string name { get { return this.nameField; } set { this.nameField = value; } } private CommonULong64 valueField; public CommonULong64 value { get { return this.valueField; } set { this.valueField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.DNSExpress.DNSExpressZoneDBStatisticEntry", Namespace = "urn:iControl")] public partial class LocalLBDNSExpressDNSExpressZoneDBStatisticEntry { private string zoneField; public string zone { get { return this.zoneField; } set { this.zoneField = value; } } private CommonStatistic [] statisticsField; public CommonStatistic [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } private LocalLBDNSExpressDNSExpressZoneDBEntry [] entriesField; public LocalLBDNSExpressDNSExpressZoneDBEntry [] entries { get { return this.entriesField; } set { this.entriesField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.DNSExpress.DNSExpressZoneDBStatistics", Namespace = "urn:iControl")] public partial class LocalLBDNSExpressDNSExpressZoneDBStatistics { private LocalLBDNSExpressDNSExpressZoneDBStatisticEntry [] statisticsField; public LocalLBDNSExpressDNSExpressZoneDBStatisticEntry [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } private CommonTimeStamp time_stampField; public CommonTimeStamp time_stamp { get { return this.time_stampField; } set { this.time_stampField = value; } } }; }
// 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.Immutable; using System.Diagnostics.Contracts; using System.Linq; using Analyzer.Utilities; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Semantics; namespace Microsoft.CodeQuality.Analyzers.Maintainability { /// <summary> /// CA1806: Do not ignore method results /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DoNotIgnoreMethodResultsAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA1806"; private static readonly ImmutableHashSet<string> s_stringMethodNames = ImmutableHashSet.CreateRange( new[] { "ToUpper", "ToLower", "Trim", "TrimEnd", "TrimStart", "ToUpperInvariant", "ToLowerInvariant", "Clone", "Format", "Concat", "Copy", "Insert", "Join", "Normalize", "Remove", "Replace", "Split", "PadLeft", "PadRight", "Substring", }); private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsTitle), MicrosoftMaintainabilityAnalyzersResources.ResourceManager, typeof(MicrosoftMaintainabilityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageObjectCreation = new LocalizableResourceString(nameof(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessageObjectCreation), MicrosoftMaintainabilityAnalyzersResources.ResourceManager, typeof(MicrosoftMaintainabilityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageStringCreation = new LocalizableResourceString(nameof(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessageStringCreation), MicrosoftMaintainabilityAnalyzersResources.ResourceManager, typeof(MicrosoftMaintainabilityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageHResultOrErrorCode = new LocalizableResourceString(nameof(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessageHResultOrErrorCode), MicrosoftMaintainabilityAnalyzersResources.ResourceManager, typeof(MicrosoftMaintainabilityAnalyzersResources)); private static readonly LocalizableString s_localizableMessagePureMethod = new LocalizableResourceString(nameof(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessagePureMethod), MicrosoftMaintainabilityAnalyzersResources.ResourceManager, typeof(MicrosoftMaintainabilityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageTryParse = new LocalizableResourceString(nameof(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessageTryParse), MicrosoftMaintainabilityAnalyzersResources.ResourceManager, typeof(MicrosoftMaintainabilityAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsDescription), MicrosoftMaintainabilityAnalyzersResources.ResourceManager, typeof(MicrosoftMaintainabilityAnalyzersResources)); internal static DiagnosticDescriptor ObjectCreationRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageObjectCreation, DiagnosticCategory.Performance, DiagnosticHelpers.DefaultDiagnosticSeverity, isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultForVsixAndNuget, description: s_localizableDescription, helpLinkUri: "https://msdn.microsoft.com/en-us/library/ms182273.aspx", customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor StringCreationRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageStringCreation, DiagnosticCategory.Performance, DiagnosticHelpers.DefaultDiagnosticSeverity, isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultForVsixAndNuget, description: s_localizableDescription, helpLinkUri: "https://msdn.microsoft.com/en-us/library/ms182273.aspx", customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor HResultOrErrorCodeRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageHResultOrErrorCode, DiagnosticCategory.Performance, DiagnosticHelpers.DefaultDiagnosticSeverity, isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultForVsixAndNuget, description: s_localizableDescription, helpLinkUri: "https://msdn.microsoft.com/en-us/library/ms182273.aspx", customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor PureMethodRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessagePureMethod, DiagnosticCategory.Performance, DiagnosticHelpers.DefaultDiagnosticSeverity, isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultForVsixAndNuget, description: s_localizableDescription, helpLinkUri: "https://msdn.microsoft.com/en-us/library/ms182273.aspx", customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor TryParseRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageTryParse, DiagnosticCategory.Performance, DiagnosticHelpers.DefaultDiagnosticSeverity, isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultForVsixAndNuget, description: s_localizableDescription, helpLinkUri: "https://msdn.microsoft.com/en-us/library/ms182273.aspx", customTags: WellKnownDiagnosticTags.Telemetry); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(ObjectCreationRule, StringCreationRule, HResultOrErrorCodeRule, TryParseRule); public override void Initialize(AnalysisContext analysisContext) { analysisContext.EnableConcurrentExecution(); analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); analysisContext.RegisterOperationBlockStartActionInternal(osContext => { var method = osContext.OwningSymbol as IMethodSymbol; if (method == null) { return; } osContext.RegisterOperationActionInternal(opContext => { IOperation expression = ((IExpressionStatement)opContext.Operation).Expression; DiagnosticDescriptor rule = null; string targetMethodName = null; switch (expression.Kind) { case OperationKind.ObjectCreationExpression: IMethodSymbol ctor = ((IObjectCreationExpression)expression).Constructor; if (ctor != null) { rule = ObjectCreationRule; targetMethodName = ctor.ContainingType.Name; } break; case OperationKind.InvocationExpression: IInvocationExpression invocationExpression = ((IInvocationExpression)expression); IMethodSymbol targetMethod = invocationExpression.TargetMethod; if (targetMethod == null) { break; } if (IsStringCreatingMethod(targetMethod)) { rule = StringCreationRule; } else if (IsTryParseMethod(targetMethod)) { rule = TryParseRule; } else if (IsHResultOrErrorCodeReturningMethod(targetMethod)) { rule = HResultOrErrorCodeRule; } else if (IsPureMethod(targetMethod, opContext.Compilation)) { rule = PureMethodRule; } targetMethodName = targetMethod.Name; break; } if (rule != null) { Diagnostic diagnostic = Diagnostic.Create(rule, expression.Syntax.GetLocation(), method.Name, targetMethodName); opContext.ReportDiagnostic(diagnostic); } }, OperationKind.ExpressionStatement); }); } private static bool IsStringCreatingMethod(IMethodSymbol method) { return method.ContainingType.SpecialType == SpecialType.System_String && s_stringMethodNames.Contains(method.Name); } private static bool IsTryParseMethod(IMethodSymbol method) { return method.Name.StartsWith("TryParse", StringComparison.OrdinalIgnoreCase) && method.ReturnType.SpecialType == SpecialType.System_Boolean && method.Parameters.Length >= 2 && method.Parameters[1].RefKind != RefKind.None; } private static bool IsHResultOrErrorCodeReturningMethod(IMethodSymbol method) { // Tune this method to match the FxCop behavior once https://github.com/dotnet/roslyn/issues/7282 is addressed. return method.GetDllImportData() != null && (method.ReturnType.SpecialType == SpecialType.System_Int32 || method.ReturnType.SpecialType == SpecialType.System_UInt32); } private static bool IsPureMethod(IMethodSymbol method, Compilation compilation) { return method.GetAttributes().Any(attr => attr.AttributeClass.Equals(WellKnownTypes.PureAttribute(compilation))); } } }
/* * 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; namespace Apache.NMS { /// <summary> /// A StreamMessage object is used to send a stream of primitive types in the /// .NET programming language. It is filled and read sequentially. It inherits /// from the Message interface and adds a stream message body. /// /// The primitive types can be read or written explicitly using methods for each /// type. They may also be read or written generically as objects. For instance, /// a call to IStreamMessage.WriteInt32(6) is equivalent to /// StreamMessage.WriteObject( (Int32)6 ). Both forms are provided, because the /// explicit form is convenient for static programming, and the object form is /// needed when types are not known at compile time. /// /// When the message is first created, and when ClearBody is called, the body of /// the message is in write-only mode. After the first call to reset has been made, /// the message body is in read-only mode. After a message has been sent, the /// client that sent it can retain and modify it without affecting the message /// that has been sent. The same message object can be sent multiple times. When a /// message has been received, the provider has called reset so that the message /// body is in read-only mode for the client. /// /// If ClearBody is called on a message in read-only mode, the message body is /// cleared and the message body is in write-only mode. /// /// If a client attempts to read a message in write-only mode, a /// MessageNotReadableException is thrown. /// /// If a client attempts to write a message in read-only mode, a /// MessageNotWriteableException is thrown. /// /// IStreamMessage objects support the following conversion table. The marked cases /// must be supported. The unmarked cases must throw a NMSException. The /// String-to-primitive conversions may throw a runtime exception if the primitive's /// valueOf() method does not accept it as a valid String representation of the /// primitive. /// /// A value written as the row type can be read as the column type. /// /// | | boolean byte short char int long float double String byte[] /// |---------------------------------------------------------------------- /// |boolean | X X /// |byte | X X X X X /// |short | X X X X /// |char | X X /// |int | X X X /// |long | X X /// |float | X X X /// |double | X X /// |String | X X X X X X X X /// |byte[] | X /// |---------------------------------------------------------------------- /// /// </summary> public interface IStreamMessage : IMessage { /// <summary> /// Reads a boolean from the stream message. /// </summary> /// <returns> /// A <see cref="System.Boolean"/> /// </returns> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to read the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageEOFException"> /// if unexpected end of message stream has been reached. /// </exception> /// <exception cref="Apache.NMS.MessageFormatException"> /// if this type conversion is invalid. /// </exception> /// <exception cref="Apache.NMS.MessageNotReadableException"> /// if the message is in write-only mode. /// </exception> bool ReadBoolean(); /// <summary> /// Reads a byte from the stream message. /// </summary> /// <returns> /// A <see cref="System.Byte"/> /// </returns> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to read the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageEOFException"> /// if unexpected end of message stream has been reached. /// </exception> /// <exception cref="Apache.NMS.MessageFormatException"> /// if this type conversion is invalid. /// </exception> /// <exception cref="Apache.NMS.MessageNotReadableException"> /// if the message is in write-only mode. /// </exception> byte ReadByte(); /// <summary> /// Reads a byte array field from the stream message into the specified byte[] /// object (the read buffer). /// /// To read the field value, ReadBytes should be successively called until it returns /// a value less than the length of the read buffer. The value of the bytes in the /// buffer following the last byte read is undefined. /// /// If ReadBytes returns a value equal to the length of the buffer, a subsequent /// ReadBytes call must be made. If there are no more bytes to be read, this call /// returns -1. /// /// If the byte array field value is null, ReadBytes returns -1. /// If the byte array field value is empty, ReadBytes returns 0. /// /// Once the first ReadBytes call on a byte[] field value has been made, the full /// value of the field must be read before it is valid to read the next field. /// An attempt to read the next field before that has been done will throw a /// MessageFormatException. /// /// To read the byte field value into a new byte[] object, use the ReadObject method. /// </summary> /// <param name="value"> /// A <see cref="System.Byte"/> /// </param> /// <returns> /// A <see cref="System.Byte"/> /// the total number of bytes read into the buffer, or -1 if there is no more data /// because the end of the byte field has been reached /// </returns> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to read the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageEOFException"> /// if unexpected end of message stream has been reached. /// </exception> /// <exception cref="Apache.NMS.MessageFormatException"> /// if this type conversion is invalid. /// </exception> /// <exception cref="Apache.NMS.MessageNotReadableException"> /// if the message is in write-only mode. /// </exception> /// <seealso cref="ReadObject"/> int ReadBytes(byte[] value); /// <summary> /// Reads a char from the stream message. /// </summary> /// <returns> /// A <see cref="System.Char"/> /// </returns> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to read the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageEOFException"> /// if unexpected end of message stream has been reached. /// </exception> /// <exception cref="Apache.NMS.MessageFormatException"> /// if this type conversion is invalid. /// </exception> /// <exception cref="Apache.NMS.MessageNotReadableException"> /// if the message is in write-only mode. /// </exception> char ReadChar(); /// <summary> /// Reads a short from the stream message. /// </summary> /// <returns> /// A <see cref="System.Int16"/> /// </returns> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to read the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageEOFException"> /// if unexpected end of message stream has been reached. /// </exception> /// <exception cref="Apache.NMS.MessageFormatException"> /// if this type conversion is invalid. /// </exception> /// <exception cref="Apache.NMS.MessageNotReadableException"> /// if the message is in write-only mode. /// </exception> short ReadInt16(); /// <summary> /// Reads a int from the stream message. /// </summary> /// <returns> /// A <see cref="System.Int32"/> /// </returns> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to read the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageEOFException"> /// if unexpected end of message stream has been reached. /// </exception> /// <exception cref="Apache.NMS.MessageFormatException"> /// if this type conversion is invalid. /// </exception> /// <exception cref="Apache.NMS.MessageNotReadableException"> /// if the message is in write-only mode. /// </exception> int ReadInt32(); /// <summary> /// Reads a long from the stream message. /// </summary> /// <returns> /// A <see cref="System.Int64"/> /// </returns> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to read the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageEOFException"> /// if unexpected end of message stream has been reached. /// </exception> /// <exception cref="Apache.NMS.MessageFormatException"> /// if this type conversion is invalid. /// </exception> /// <exception cref="Apache.NMS.MessageNotReadableException"> /// if the message is in write-only mode. /// </exception> long ReadInt64(); /// <summary> /// Reads a float from the stream message. /// </summary> /// <returns> /// A <see cref="System.Single"/> /// </returns> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to read the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageEOFException"> /// if unexpected end of message stream has been reached. /// </exception> /// <exception cref="Apache.NMS.MessageFormatException"> /// if this type conversion is invalid. /// </exception> /// <exception cref="Apache.NMS.MessageNotReadableException"> /// if the message is in write-only mode. /// </exception> float ReadSingle(); /// <summary> /// Reads a double from the stream message. /// </summary> /// <returns> /// A <see cref="System.Double"/> /// </returns> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to read the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageEOFException"> /// if unexpected end of message stream has been reached. /// </exception> /// <exception cref="Apache.NMS.MessageFormatException"> /// if this type conversion is invalid. /// </exception> /// <exception cref="Apache.NMS.MessageNotReadableException"> /// if the message is in write-only mode. /// </exception> double ReadDouble(); /// <summary> /// Reads a string from the stream message. /// </summary> /// <returns> /// A <see cref="System.String"/> /// </returns> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to read the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageEOFException"> /// if unexpected end of message stream has been reached. /// </exception> /// <exception cref="Apache.NMS.MessageFormatException"> /// if this type conversion is invalid. /// </exception> /// <exception cref="Apache.NMS.MessageNotReadableException"> /// if the message is in write-only mode. /// </exception> string ReadString(); /// <summary> /// Reads a Object from the stream message. /// </summary> /// <returns> /// A <see cref="System.Object"/> /// </returns> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to read the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageEOFException"> /// if unexpected end of message stream has been reached. /// </exception> /// <exception cref="Apache.NMS.MessageFormatException"> /// if this type conversion is invalid. /// </exception> /// <exception cref="Apache.NMS.MessageNotReadableException"> /// if the message is in write-only mode. /// </exception> Object ReadObject(); /// <summary> /// Writes a boolean to the stream message. /// </summary> /// <param name="value"> /// A <see cref="System.Boolean"/> /// </param> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to write to the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageNotWriteableException"> /// if the message is in read-only mode. /// </exception> void WriteBoolean(bool value); /// <summary> /// Writes a byte to the stream message. /// </summary> /// <param name="value"> /// A <see cref="System.Byte"/> /// </param> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to write to the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageNotWriteableException"> /// if the message is in read-only mode. /// </exception> void WriteByte(byte value); /// <summary> /// Writes a byte array field to the stream message. /// /// The byte array value is written to the message as a byte array field. /// Consecutively written byte array fields are treated as two distinct /// fields when the fields are read. /// </summary> /// <param name="value"> /// A <see cref="System.Byte"/> /// </param> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to write to the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageNotWriteableException"> /// if the message is in read-only mode. /// </exception> void WriteBytes(byte[] value); /// <summary> /// Writes a portion of a byte array as a byte array field to the stream message. /// /// The a portion of the byte array value is written to the message as a byte /// array field. Consecutively written byte array fields are treated as two distinct /// fields when the fields are read. /// </summary> /// <param name="value"> /// A <see cref="System.Byte"/> /// </param> /// <param name="offset"> /// A <see cref="System.Int32"/> value that indicates the point in the buffer to /// begin writing to the stream message. /// </param> /// <param name="length"> /// A <see cref="System.Int32"/> value that indicates how many bytes in the buffer /// to write to the stream message. /// </param> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to write to the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageNotWriteableException"> /// if the message is in read-only mode. /// </exception> void WriteBytes(byte[] value, int offset, int length); /// <summary> /// Writes a char to the stream message. /// </summary> /// <param name="value"> /// A <see cref="System.Char"/> /// </param> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to write to the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageNotWriteableException"> /// if the message is in read-only mode. /// </exception> void WriteChar(char value); /// <summary> /// Writes a short to the stream message. /// </summary> /// <param name="value"> /// A <see cref="System.Int16"/> /// </param> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to write to the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageNotWriteableException"> /// if the message is in read-only mode. /// </exception> void WriteInt16(short value); /// <summary> /// Writes a int to the stream message. /// </summary> /// <param name="value"> /// A <see cref="System.Int32"/> /// </param> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to write to the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageNotWriteableException"> /// if the message is in read-only mode. /// </exception> void WriteInt32(int value); /// <summary> /// Writes a long to the stream message. /// </summary> /// <param name="value"> /// A <see cref="System.Int64"/> /// </param> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to write to the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageNotWriteableException"> /// if the message is in read-only mode. /// </exception> void WriteInt64(long value); /// <summary> /// Writes a float to the stream message. /// </summary> /// <param name="value"> /// A <see cref="System.Single"/> /// </param> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to write to the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageNotWriteableException"> /// if the message is in read-only mode. /// </exception> void WriteSingle(float value); /// <summary> /// Writes a double to the stream message. /// </summary> /// <param name="value"> /// A <see cref="System.Double"/> /// </param> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to write to the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageNotWriteableException"> /// if the message is in read-only mode. /// </exception> void WriteDouble(double value); /// <summary> /// Writes a string to the stream message. /// </summary> /// <param name="value"> /// A <see cref="System.String"/> /// </param> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to write to the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageNotWriteableException"> /// if the message is in read-only mode. /// </exception> void WriteString(string value); /// <summary> /// Writes a boolean to the stream message. /// </summary> /// <param name="value"> /// A <see cref="System.Boolean"/> /// </param> /// <exception cref="Apache.NMS.NMSException"> /// if the NMS provider fails to write to the message due to some internal error. /// </exception> /// <exception cref="Apache.NMS.MessageNotWriteableException"> /// if the message is in read-only mode. /// </exception> void WriteObject(Object value); /// <summary> /// Puts the message body in read-only mode and repositions the stream to the beginning. /// </summary> /// <exception cref="Apache.NMS.MessageFormatException"> /// Thrown when the Message has an invalid format. /// </exception> /// <exception cref="Apache.NMS.NMSException"> /// Thrown when there is an unhandled exception thrown from the provider. /// </exception> void Reset(); } }
#region License /* * WebSocketServiceHost.cs * * The MIT License * * Copyright (c) 2012-2014 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 #region Contributors /* * Contributors: * - Juan Manuel Lallana <[email protected]> */ #endregion using System; using WebSocketSharp.Net; using WebSocketSharp.Net.WebSockets; namespace WebSocketSharp.Server { /// <summary> /// Exposes the methods and properties used to access the information in a WebSocket service /// provided by the <see cref="HttpServer"/> or <see cref="WebSocketServer"/>. /// </summary> /// <remarks> /// The WebSocketServiceHost class is an abstract class. /// </remarks> public abstract class WebSocketServiceHost { #region Protected Constructors /// <summary> /// Initializes a new instance of the <see cref="WebSocketServiceHost"/> class. /// </summary> protected WebSocketServiceHost () { } #endregion #region Internal Properties internal ServerState State { get { return Sessions.State; } } #endregion #region Public Properties /// <summary> /// Gets or sets a value indicating whether the WebSocket service cleans up /// the inactive sessions periodically. /// </summary> /// <value> /// <c>true</c> if the service cleans up the inactive sessions periodically; /// otherwise, <c>false</c>. /// </value> public abstract bool KeepClean { get; set; } /// <summary> /// Gets the path to the WebSocket service. /// </summary> /// <value> /// A <see cref="string"/> that represents the absolute path to the service. /// </value> public abstract string Path { get; } /// <summary> /// Gets the access to the sessions in the WebSocket service. /// </summary> /// <value> /// A <see cref="WebSocketSessionManager"/> that manages the sessions in the service. /// </value> public abstract WebSocketSessionManager Sessions { get; } /// <summary> /// Gets the <see cref="System.Type"/> of the behavior of the WebSocket service. /// </summary> /// <value> /// A <see cref="System.Type"/> that represents the type of the behavior of the service. /// </value> public abstract Type Type { get; } /// <summary> /// Gets or sets the wait time for the response to the WebSocket Ping or Close. /// </summary> /// <value> /// A <see cref="TimeSpan"/> that represents the wait time. The default value is /// the same as 1 second. /// </value> public abstract TimeSpan WaitTime { get; set; } #endregion #region Internal Methods internal void Start () { Sessions.Start (); } internal void StartSession (WebSocketContext context) { CreateSession ().Start (context, Sessions); } internal void Stop (ushort code, string reason) { var e = new CloseEventArgs (code, reason); var send = !code.IsReserved (); var bytes = send ? WebSocketFrame.CreateCloseFrame (e.PayloadData, false).ToByteArray () : null; var timeout = send ? WaitTime : TimeSpan.Zero; Sessions.Stop (e, bytes, timeout); } #endregion #region Protected Methods /// <summary> /// Creates a new session in the WebSocket service. /// </summary> /// <returns> /// A <see cref="WebSocketBehavior"/> instance that represents a new session. /// </returns> protected abstract WebSocketBehavior CreateSession (); #endregion } internal class WebSocketServiceHost<TBehavior> : WebSocketServiceHost where TBehavior : WebSocketBehavior { #region Private Fields private Func<TBehavior> _initializer; private Logger _logger; private string _path; private WebSocketSessionManager _sessions; #endregion #region Internal Constructors internal WebSocketServiceHost (string path, Func<TBehavior> initializer, Logger logger) { _path = path; _initializer = initializer; _logger = logger; _sessions = new WebSocketSessionManager (logger); } #endregion #region Public Properties public override bool KeepClean { get { return _sessions.KeepClean; } set { var msg = _sessions.State.CheckIfStartable (); if (msg != null) { _logger.Error (msg); return; } _sessions.KeepClean = value; } } public override string Path { get { return _path; } } public override WebSocketSessionManager Sessions { get { return _sessions; } } public override Type Type { get { return typeof (TBehavior); } } public override TimeSpan WaitTime { get { return _sessions.WaitTime; } set { var msg = _sessions.State.CheckIfStartable () ?? value.CheckIfValidWaitTime (); if (msg != null) { _logger.Error (msg); return; } _sessions.WaitTime = value; } } #endregion #region Protected Methods protected override WebSocketBehavior CreateSession () { return _initializer (); } #endregion } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Design; using System.Windows.Forms.Design; using System.ComponentModel; namespace WeifenLuo.WinFormsUI.Docking { #region DockPanelSkin classes /// <summary> /// The skin to use when displaying the DockPanel. /// The skin allows custom gradient color schemes to be used when drawing the /// DockStrips and Tabs. /// </summary> [TypeConverter(typeof(DockPanelSkinConverter))] public class DockPanelSkin { private AutoHideStripSkin m_autoHideStripSkin; private DockPaneStripSkin m_dockPaneStripSkin; public bool BlueSkin = true; public DockPanelSkin() { m_autoHideStripSkin = new AutoHideStripSkin(); m_dockPaneStripSkin = new DockPaneStripSkin(); } /// <summary> /// The skin used to display the auto hide strips and tabs. /// </summary> public AutoHideStripSkin AutoHideStripSkin { get { return m_autoHideStripSkin; } set { m_autoHideStripSkin = value; } } /// <summary> /// The skin used to display the Document and ToolWindow style DockStrips and Tabs. /// </summary> public DockPaneStripSkin DockPaneStripSkin { get { return m_dockPaneStripSkin; } set { m_dockPaneStripSkin = value; } } } /// <summary> /// The skin used to display the auto hide strip and tabs. /// </summary> [TypeConverter(typeof(AutoHideStripConverter))] public class AutoHideStripSkin { private DockPanelGradient m_dockStripGradient; private TabGradient m_TabGradient; public AutoHideStripSkin() { m_dockStripGradient = new DockPanelGradient(); m_dockStripGradient.StartColor = SystemColors.ControlLight; m_dockStripGradient.EndColor = SystemColors.ControlLight; m_TabGradient = new TabGradient(); m_TabGradient.TextColor = SystemColors.ControlDarkDark; } /// <summary> /// The gradient color skin for the DockStrips. /// </summary> public DockPanelGradient DockStripGradient { get { return m_dockStripGradient; } set { m_dockStripGradient = value; } } /// <summary> /// The gradient color skin for the Tabs. /// </summary> public TabGradient TabGradient { get { return m_TabGradient; } set { m_TabGradient = value; } } } /// <summary> /// The skin used to display the document and tool strips and tabs. /// </summary> [TypeConverter(typeof(DockPaneStripConverter))] public class DockPaneStripSkin { private DockPaneStripGradient m_DocumentGradient; private DockPaneStripToolWindowGradient m_ToolWindowGradient; public DockPaneStripSkin() { m_DocumentGradient = new DockPaneStripGradient(); m_DocumentGradient.DockStripGradient.StartColor = SystemColors.Control; m_DocumentGradient.DockStripGradient.EndColor = SystemColors.Control; m_DocumentGradient.ActiveTabGradient.StartColor = SystemColors.ControlLightLight; m_DocumentGradient.ActiveTabGradient.EndColor = SystemColors.ControlLightLight; m_DocumentGradient.InactiveTabGradient.StartColor = SystemColors.ControlLight; m_DocumentGradient.InactiveTabGradient.EndColor = SystemColors.ControlLight; m_ToolWindowGradient = new DockPaneStripToolWindowGradient(); m_ToolWindowGradient.DockStripGradient.StartColor = SystemColors.ControlLight; m_ToolWindowGradient.DockStripGradient.EndColor = SystemColors.ControlLight; m_ToolWindowGradient.ActiveTabGradient.StartColor = SystemColors.Control; m_ToolWindowGradient.ActiveTabGradient.EndColor = SystemColors.Control; m_ToolWindowGradient.InactiveTabGradient.StartColor = Color.Transparent; m_ToolWindowGradient.InactiveTabGradient.EndColor = Color.Transparent; m_ToolWindowGradient.InactiveTabGradient.TextColor = SystemColors.ControlDarkDark; m_ToolWindowGradient.ActiveCaptionGradient.StartColor = SystemColors.GradientActiveCaption; m_ToolWindowGradient.ActiveCaptionGradient.EndColor = SystemColors.ActiveCaption; m_ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; m_ToolWindowGradient.ActiveCaptionGradient.TextColor = SystemColors.ActiveCaptionText; m_ToolWindowGradient.InactiveCaptionGradient.StartColor = SystemColors.GradientInactiveCaption; m_ToolWindowGradient.InactiveCaptionGradient.EndColor = SystemColors.GradientInactiveCaption; m_ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; m_ToolWindowGradient.InactiveCaptionGradient.TextColor = SystemColors.ControlText; } /// <summary> /// The skin used to display the Document style DockPane strip and tab. /// </summary> public DockPaneStripGradient DocumentGradient { get { return m_DocumentGradient; } set { m_DocumentGradient = value; } } /// <summary> /// The skin used to display the ToolWindow style DockPane strip and tab. /// </summary> public DockPaneStripToolWindowGradient ToolWindowGradient { get { return m_ToolWindowGradient; } set { m_ToolWindowGradient = value; } } } /// <summary> /// The skin used to display the DockPane ToolWindow strip and tab. /// </summary> [TypeConverter(typeof(DockPaneStripGradientConverter))] public class DockPaneStripToolWindowGradient : DockPaneStripGradient { private TabGradient m_activeCaptionGradient; private TabGradient m_inactiveCaptionGradient; public DockPaneStripToolWindowGradient() { m_activeCaptionGradient = new TabGradient(); m_inactiveCaptionGradient = new TabGradient(); } /// <summary> /// The skin used to display the active ToolWindow caption. /// </summary> public TabGradient ActiveCaptionGradient { get { return m_activeCaptionGradient; } set { m_activeCaptionGradient = value; } } /// <summary> /// The skin used to display the inactive ToolWindow caption. /// </summary> public TabGradient InactiveCaptionGradient { get { return m_inactiveCaptionGradient; } set { m_inactiveCaptionGradient = value; } } } /// <summary> /// The skin used to display the DockPane strip and tab. /// </summary> [TypeConverter(typeof(DockPaneStripGradientConverter))] public class DockPaneStripGradient { private DockPanelGradient m_dockStripGradient; private TabGradient m_activeTabGradient; private TabGradient m_inactiveTabGradient; public DockPaneStripGradient() { m_dockStripGradient = new DockPanelGradient(); m_activeTabGradient = new TabGradient(); m_inactiveTabGradient = new TabGradient(); } /// <summary> /// The gradient color skin for the DockStrip. /// </summary> public DockPanelGradient DockStripGradient { get { return m_dockStripGradient; } set { m_dockStripGradient = value; } } /// <summary> /// The skin used to display the active DockPane tabs. /// </summary> public TabGradient ActiveTabGradient { get { return m_activeTabGradient; } set { m_activeTabGradient = value; } } /// <summary> /// The skin used to display the inactive DockPane tabs. /// </summary> public TabGradient InactiveTabGradient { get { return m_inactiveTabGradient; } set { m_inactiveTabGradient = value; } } } /// <summary> /// The skin used to display the dock pane tab /// </summary> [TypeConverter(typeof(DockPaneTabGradientConverter))] public class TabGradient : DockPanelGradient { private Color m_textColor; public TabGradient() { m_textColor = SystemColors.ControlText; } /// <summary> /// The text color. /// </summary> [DefaultValue(typeof(SystemColors), "ControlText")] public Color TextColor { get { return m_textColor; } set { m_textColor = value; } } } /// <summary> /// The gradient color skin. /// </summary> [TypeConverter(typeof(DockPanelGradientConverter))] public class DockPanelGradient { private Color m_startColor; private Color m_endColor; private LinearGradientMode m_linearGradientMode; public DockPanelGradient() { m_startColor = SystemColors.Control; m_endColor = SystemColors.Control; m_linearGradientMode = LinearGradientMode.Horizontal; } /// <summary> /// The beginning gradient color. /// </summary> [DefaultValue(typeof(SystemColors), "Control")] public Color StartColor { get { return m_startColor; } set { m_startColor = value; } } /// <summary> /// The ending gradient color. /// </summary> [DefaultValue(typeof(SystemColors), "Control")] public Color EndColor { get { return m_endColor; } set { m_endColor = value; } } /// <summary> /// The gradient mode to display the colors. /// </summary> [DefaultValue(LinearGradientMode.Horizontal)] public LinearGradientMode LinearGradientMode { get { return m_linearGradientMode; } set { m_linearGradientMode = value; } } } #endregion #region Converters public class DockPanelSkinConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(DockPanelSkin)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is DockPanelSkin) { return "DockPanelSkin"; } return base.ConvertTo(context, culture, value, destinationType); } } public class DockPanelGradientConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(DockPanelGradient)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is DockPanelGradient) { return "DockPanelGradient"; } return base.ConvertTo(context, culture, value, destinationType); } } public class AutoHideStripConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(AutoHideStripSkin)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is AutoHideStripSkin) { return "AutoHideStripSkin"; } return base.ConvertTo(context, culture, value, destinationType); } } public class DockPaneStripConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(DockPaneStripSkin)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is DockPaneStripSkin) { return "DockPaneStripSkin"; } return base.ConvertTo(context, culture, value, destinationType); } } public class DockPaneStripGradientConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(DockPaneStripGradient)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is DockPaneStripGradient) { return "DockPaneStripGradient"; } return base.ConvertTo(context, culture, value, destinationType); } } public class DockPaneTabGradientConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(TabGradient)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is TabGradient) { return "DockPaneTabGradient"; } return base.ConvertTo(context, culture, value, destinationType); } } #endregion }
using UnityEngine; using UnityEngine.UI; using System.Reflection; namespace Fungus { /// <summary> /// Helper class for hiding the many, many ways we might want to show text to the user. /// </summary> public class TextAdapter : IWriterTextDestination { protected Text textUI; protected InputField inputField; protected TextMesh textMesh; #if UNITY_2018_1_OR_NEWER protected TMPro.TMP_Text tmpro; #endif protected Component textComponent; protected PropertyInfo textProperty; protected IWriterTextDestination writerTextDestination; public void InitFromGameObject(GameObject go, bool includeChildren = false) { if (go == null) { return; } if (!includeChildren) { textUI = go.GetComponent<Text>(); inputField = go.GetComponent<InputField>(); textMesh = go.GetComponent<TextMesh>(); #if UNITY_2018_1_OR_NEWER tmpro = go.GetComponent<TMPro.TMP_Text>(); #endif writerTextDestination = go.GetComponent<IWriterTextDestination>(); } else { textUI = go.GetComponentInChildren<Text>(); inputField = go.GetComponentInChildren<InputField>(); textMesh = go.GetComponentInChildren<TextMesh>(); #if UNITY_2018_1_OR_NEWER tmpro = go.GetComponentInChildren<TMPro.TMP_Text>(); #endif writerTextDestination = go.GetComponentInChildren<IWriterTextDestination>(); } // Try to find any component with a text property if (textUI == null && inputField == null && textMesh == null && writerTextDestination == null) { Component[] allcomponents = null; if (!includeChildren) allcomponents = go.GetComponents<Component>(); else allcomponents = go.GetComponentsInChildren<Component>(); for (int i = 0; i < allcomponents.Length; i++) { var c = allcomponents[i]; textProperty = c.GetType().GetProperty("text"); if (textProperty != null) { textComponent = c; break; } } } } public void ForceRichText() { if (textUI != null) { textUI.supportRichText = true; } // Input Field does not support rich text if (textMesh != null) { textMesh.richText = true; } #if UNITY_2018_1_OR_NEWER if(tmpro != null) { tmpro.richText = true; } #endif if (writerTextDestination != null) { writerTextDestination.ForceRichText(); } } public void SetTextColor(Color textColor) { if (textUI != null) { textUI.color = textColor; } else if (inputField != null) { if (inputField.textComponent != null) { inputField.textComponent.color = textColor; } } else if (textMesh != null) { textMesh.color = textColor; } #if UNITY_2018_1_OR_NEWER else if (tmpro != null) { tmpro.color = textColor; } #endif else if (writerTextDestination != null) { writerTextDestination.SetTextColor(textColor); } } public void SetTextAlpha(float textAlpha) { if (textUI != null) { Color tempColor = textUI.color; tempColor.a = textAlpha; textUI.color = tempColor; } else if (inputField != null) { if (inputField.textComponent != null) { Color tempColor = inputField.textComponent.color; tempColor.a = textAlpha; inputField.textComponent.color = tempColor; } } else if (textMesh != null) { Color tempColor = textMesh.color; tempColor.a = textAlpha; textMesh.color = tempColor; } #if UNITY_2018_1_OR_NEWER else if (tmpro != null) { tmpro.alpha = textAlpha; } #endif else if (writerTextDestination != null) { writerTextDestination.SetTextAlpha(textAlpha); } } public bool HasTextObject() { return (textUI != null || inputField != null || textMesh != null || textComponent != null || #if UNITY_2018_1_OR_NEWER tmpro !=null || #endif writerTextDestination != null); } public bool SupportsRichText() { if (textUI != null) { return textUI.supportRichText; } if (inputField != null) { return false; } if (textMesh != null) { return textMesh.richText; } #if UNITY_2018_1_OR_NEWER if (tmpro != null) { return true; } #endif if (writerTextDestination != null) { return writerTextDestination.SupportsRichText(); } return false; } public virtual string Text { get { if (textUI != null) { return textUI.text; } else if (inputField != null) { return inputField.text; } else if (writerTextDestination != null) { return Text; } else if (textMesh != null) { return textMesh.text; } #if UNITY_2018_1_OR_NEWER else if (tmpro != null) { return tmpro.text; } #endif else if (textProperty != null) { return textProperty.GetValue(textComponent, null) as string; } return ""; } set { if (textUI != null) { textUI.text = value; } else if (inputField != null) { inputField.text = value; } else if (writerTextDestination != null) { Text = value; } else if (textMesh != null) { textMesh.text = value; } #if UNITY_2018_1_OR_NEWER else if (tmpro != null) { tmpro.text = value; } #endif else if (textProperty != null) { textProperty.SetValue(textComponent, value, null); } } } } }
using System.Linq; using NUnit.Framework; using Silphid.Showzup.Virtual; using Silphid.Showzup.Virtual.Layout; using Silphid.Tests; using UnityEngine; namespace Silphid.Showzup.Test.Controls.Virtual.Layout { [TestFixture] public class LayoutTest { private class LayoutCollection : ILayoutCollection { private readonly Rect[] _initialRects; private readonly Rect[] _layoutedRects; private readonly bool _isLoaded; public LayoutCollection(Rect[] initialRects, Rect[] layoutedRects, bool isLoaded) { _initialRects = initialRects; _layoutedRects = layoutedRects; _isLoaded = isLoaded; } public int Count => _initialRects.Length; public bool IsLoaded(int index) => _isLoaded; public bool IsLayouted(int index) => false; public Vector2 GetPreferredSize(int index) => _initialRects[index] .size; public Rect GetRect(int index) => _initialRects[index]; public void SetRect(int index, Rect rect) => _layoutedRects[index] = rect; } private const int CountAcross = 3; private readonly Vector2 MarginMin = new Vector2(123, 133); private readonly Vector2 MarginMax = new Vector2(125, 135); private readonly Vector2 AvailableSize = new Vector2(1000, 2000); private readonly Rect ViewportRect = new Rect(0, 0, 1000, 2000); private readonly Vector2 Size = new Vector2(251, 253); private readonly Vector2 SizeA = new Vector2(201, 203); private readonly Vector2 SizeB = new Vector2(221, 223); private readonly Vector2 SizeC = new Vector2(400, 300); private readonly Vector2[] Sizes; private readonly Vector2 Spacing = new Vector2(26, 29); private readonly float[] InitialX = { 100, 400, 700 }; private readonly float[] InitialY = { 150, 500, 850 }; private readonly Rect[] _initialRects; private Rect[] _layoutedRects; private RangeCache _ranges; private DelegatingLayout _layout; public LayoutTest() { Sizes = new[] { SizeA, SizeB, SizeC, SizeB, SizeC, SizeA, SizeC, SizeA }; _initialRects = new Rect[8]; int i = 0; for (int y = 0; y < 3; y++) for (int x = 0; x < 3 && i < 8; x++, i++) _initialRects[i] = new Rect( InitialX[x], InitialY[y], Sizes[i] .x, Sizes[i] .y); } private void SetUpVertical(LayoutCollection collection, SizingAlong sizingAlong, SizingAcross sizingAcross, Alignment alignmentX, Alignment alignmentY) { _ranges = new RangeCache(collection); _layout = new DelegatingLayout( new LayoutInfo { Orientation = Orientation.Vertical, AlignmentAlong = alignmentY, AlignmentAcross = alignmentX, Size = Size, Spacing = Spacing, CountAcross = CountAcross, MinMargin = MarginMin, MaxMargin = MarginMax, SizingAlong = sizingAlong, SizingAcross = sizingAcross }, _ranges); } [SetUp] public void SetUp() { _layoutedRects = new Rect[_initialRects.Length]; } [Test] public void TestVerticalFixedStretch() { var collection = new LayoutCollection(_initialRects, _layoutedRects, true); SetUpVertical(collection, SizingAlong.Fixed, SizingAcross.FixedSize, Alignment.Stretch, Alignment.Stretch); var (requiredSizeAlong, _) = _layout.Perform( LayoutDirection.Forward, collection, ViewportRect, AvailableSize); var x0 = MarginMin.x; var x1 = MarginMin.x + (AvailableSize.x - (MarginMin.x + MarginMax.x + Size.x)) / 2; var x2 = AvailableSize.x - MarginMax.x - Size.x; var y0 = MarginMin.y; var y1 = MarginMin.y + Size.y + Spacing.y; var y2 = MarginMin.y + (Size.y + Spacing.y) * 2; _layoutedRects[0] .Is(x0, y0, Size); _layoutedRects[1] .Is(x1, y0, Size); _layoutedRects[2] .Is(x2, y0, Size); _layoutedRects[3] .Is(x0, y1, Size); _layoutedRects[4] .Is(x1, y1, Size); _layoutedRects[5] .Is(x2, y1, Size); _layoutedRects[6] .Is(x0, y2, Size); _layoutedRects[7] .Is(x1, y2, Size); requiredSizeAlong.Is(y2 + Size.y + MarginMax.y); } [Test] public void TestNoItemsReady() { var collection = new LayoutCollection(_initialRects, _layoutedRects, false); SetUpVertical(collection, SizingAlong.Fixed, SizingAcross.FixedSize, Alignment.Stretch, Alignment.Stretch); var (requiredSizeAlong, _) = _layout.Perform( LayoutDirection.Forward, collection, ViewportRect, AvailableSize); requiredSizeAlong.Is(MarginMin.y + MarginMax.y); } private float GetMaxHeight(int start, int end) => _initialRects.Skip(start) .Take(end - start) .Max(x => x.size.y); [Test] public void TestVerticalVariable() { var collection = new LayoutCollection(_initialRects, _layoutedRects, true); SetUpVertical(collection, SizingAlong.Variable, SizingAcross.FixedSize, Alignment.Stretch, Alignment.Min); var (requiredSizeAlong, _) = _layout.Perform( LayoutDirection.Forward, collection, ViewportRect, AvailableSize); var x0 = MarginMin.x; var x1 = MarginMin.x + (AvailableSize.x - (MarginMin.x + MarginMax.x + Size.x)) / 2; var x2 = AvailableSize.x - MarginMax.x - Size.x; var sizeY0 = GetMaxHeight(0, 3); var sizeY1 = GetMaxHeight(3, 6); var sizeY2 = GetMaxHeight(6, 8); var y0 = MarginMin.y; var y1 = MarginMin.y + sizeY0 + Spacing.y; var y2 = MarginMin.y + sizeY0 + Spacing.y + sizeY1 + Spacing.y; _layoutedRects[0] .Is( x0, y0, Size.x, Sizes[0] .y); _layoutedRects[1] .Is( x1, y0, Size.x, Sizes[1] .y); _layoutedRects[2] .Is( x2, y0, Size.x, Sizes[2] .y); _layoutedRects[3] .Is( x0, y1, Size.x, Sizes[3] .y); _layoutedRects[4] .Is( x1, y1, Size.x, Sizes[4] .y); _layoutedRects[5] .Is( x2, y1, Size.x, Sizes[5] .y); _layoutedRects[6] .Is( x0, y2, Size.x, Sizes[6] .y); _layoutedRects[7] .Is( x1, y2, Size.x, Sizes[7] .y); requiredSizeAlong.Is(y2 + sizeY2 + MarginMax.y); } } }
// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 UnityEngine; using System.Collections; public class quadSection : manipObject { public int ID = 0; int texSize = 64; Texture2D tex, texB; Renderer texrend; Color32[] texpixels; filterDeviceInterface _deviceInterface; float width = .1f; float height = .1f; float depth = .2f; float edgeMin = -.04f; float edgeMax = .26f; public bool toggled = true; float hue = .0875f; public override void Awake() { base.Awake(); _deviceInterface = GetComponentInParent<filterDeviceInterface>(); texrend = GetComponent<Renderer>(); tex = new Texture2D(texSize, texSize, TextureFormat.RGBA32, false); texB = new Texture2D(texSize, texSize, TextureFormat.RGBA32, false); texpixels = new Color32[texSize * texSize]; GenerateOutline(); tex.SetPixels32(texpixels); GenerateFlat(); texB.SetPixels32(texpixels); tex.Apply(false); texB.Apply(false); texrend.material.mainTexture = texB; Color c = Color.HSVToRGB(hue, 182 / 255f, 229 / 255f); texrend.material.SetColor("_TintColor", c); texrend.material.SetFloat("_EmissionGain", .1f); setToggle(toggled); transform.localScale = new Vector3(width, height, depth); } bool outlined = false; void toggleOutline() { outlined = !outlined; if (outlined) texrend.material.mainTexture = tex; else texrend.material.mainTexture = texB; } public void getPercentages(out float percentA, out float percentB) { float amount = edgeMax - edgeMin; float edgeA = transform.localPosition.x - width / 2 - gap; float edgeB = transform.localPosition.x + width / 2 + gap; percentA = (edgeA - edgeMin) / amount; percentB = (edgeB - edgeMin) / amount; } float getX(float per) { return per * (edgeMax - edgeMin) + edgeMin; } void setOutline(bool on) { if (on) texrend.material.mainTexture = tex; else texrend.material.mainTexture = texB; } void GenerateOutline() { for (int i = 0; i < texSize; i++) { for (int i2 = 0; i2 < texSize; i2++) { byte s = 50; if (i == 0 || i == texSize - 1 || i2 == 0 || i2 == texSize - 1) s = 255; texpixels[i2 * texSize + i] = new Color32(s, s, s, s); } } } void GenerateFlat() { for (int i = 0; i < texSize; i++) { for (int i2 = 0; i2 < texSize; i2++) { byte s = 50; texpixels[i2 * texSize + i] = new Color32(s, s, s, s); } } } enum vizstate { off, on, selected_off, selected_on, grab_on, grab_off }; vizstate curvizstate = vizstate.off; void setVizState(vizstate s) { switch (s) { case vizstate.off: setOutline(false); texrend.material.SetFloat("_EmissionGain", .1f); break; case vizstate.on: setOutline(false); texrend.material.SetFloat("_EmissionGain", .3f); break; case vizstate.selected_off: setOutline(true); texrend.material.SetFloat("_EmissionGain", .1f); break; case vizstate.selected_on: setOutline(true); texrend.material.SetFloat("_EmissionGain", .3f); break; case vizstate.grab_off: setOutline(true); texrend.material.SetFloat("_EmissionGain", .15f); break; case vizstate.grab_on: setOutline(true); texrend.material.SetFloat("_EmissionGain", .5f); break; default: break; } } public void setToggle(bool on) { toggled = on; if (curState == manipState.none) setVizState(toggled ? vizstate.on : vizstate.off); else if (curState == manipState.selected) setVizState(toggled ? vizstate.selected_on : vizstate.selected_off); else setVizState(toggled ? vizstate.grab_on : vizstate.grab_off); } bool updateWidth(float w, int dir) { Vector3 p = transform.localPosition; float delta = width; width = Mathf.Clamp(w, .01f, .28f); delta = delta - width; p.x += dir * delta / 2; transform.localScale = new Vector3(width, height, depth); transform.localPosition = p; if (width == .01f) return false; else return true; } float offset = 0; public override void grabUpdate(Transform t) { float modW = transform.parent.InverseTransformPoint(manipulatorObj.position).x - offset; if (ID == 0) { updateWidth(startWidth + modW, -1); Vector3 p = transform.localPosition; _deviceInterface.quads[1].updateEdge(-1, p.x + width / 2 + gap); } else if (ID == 2) { updateWidth(startWidth - modW, 1); Vector3 p = transform.localPosition; _deviceInterface.quads[1].updateEdge(1, p.x - width / 2 - gap); } else { updatePosition(startX + modW); } } float gap = .01f; public void updateEdge(int edge, float xPos) { Vector3 pos = transform.localPosition; float amount = width - ((pos.x + edge * width / 2) - xPos) * edge; bool check = updateWidth(amount, -edge); if (!check && ID == 1) //the middle one is as small as it's going to be so start shifting over { updatePosition(transform.localPosition.x + (width - amount) * -edge); } } public void setupPercents(float p0, float p1) //just for center quad { updateEdge(-1, getX(p0)); updateEdge(1, getX(p1)); updatePosition(getX((p1 - p0) / 2 + p0)); } public void updatePercentage(float p) { if (ID == 1) { p = Mathf.Lerp(edgeMin + gap + width / 2, edgeMax - gap - width / 2, p); updatePosition(p); } else if (ID == 0) { float w = Mathf.Lerp(.01f, .28f - _deviceInterface.quads[2].width, p); updateWidth(w, -1); Vector3 pos = transform.localPosition; _deviceInterface.quads[1].updateEdge(-1, pos.x + width / 2 + gap); } else if (ID == 2) { float w = Mathf.Lerp(.01f, .28f - _deviceInterface.quads[0].width, p); updateWidth(w, 1); Vector3 pos = transform.localPosition; _deviceInterface.quads[1].updateEdge(1, pos.x - width / 2 - gap); } } public void updatePosition(float x) { Vector3 p = transform.localPosition; p.x = Mathf.Clamp(x, edgeMin + gap + width / 2, edgeMax - gap - width / 2); _deviceInterface.quads[0].updateEdge(1, p.x - width / 2 - gap); _deviceInterface.quads[2].updateEdge(-1, p.x + width / 2 + gap); transform.localPosition = p; } float startWidth = 0; float startX = 0; public override void setState(manipState state) { curState = state; if (curState == manipState.none) { setVizState(toggled ? vizstate.on : vizstate.off); } else if (curState == manipState.selected) { setVizState(toggled ? vizstate.selected_on : vizstate.selected_off); } else if (curState == manipState.grabbed) { setVizState(toggled ? vizstate.grab_on : vizstate.grab_off); startWidth = width; startX = transform.localPosition.x; offset = transform.parent.InverseTransformPoint(manipulatorObj.position).x; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime; using System.Runtime.InteropServices; using System.Security.Cryptography; namespace System.Security { public sealed partial class SecureString { internal SecureString(SecureString str) { Debug.Assert(str != null, "Expected non-null SecureString"); Debug.Assert(str._buffer != null, "Expected other SecureString's buffer to be non-null"); Debug.Assert(str._encrypted, "Expected to be used only on encrypted SecureStrings"); AllocateBuffer(str._buffer.Length); SafeBSTRHandle.Copy(str._buffer, _buffer, str._buffer.Length * sizeof(char)); _decryptedLength = str._decryptedLength; _encrypted = str._encrypted; } private unsafe void InitializeSecureString(char* value, int length) { Debug.Assert(length >= 0, $"Expected non-negative length, got {length}"); AllocateBuffer((uint)length); _decryptedLength = length; byte* bufferPtr = null; try { _buffer.AcquirePointer(ref bufferPtr); Buffer.MemoryCopy((byte*)value, bufferPtr, (long)_buffer.ByteLength, length * sizeof(char)); } finally { if (bufferPtr != null) { _buffer.ReleasePointer(); } } ProtectMemory(); } private void AppendCharCore(char c) { UnprotectMemory(); try { EnsureCapacity(_decryptedLength + 1); _buffer.Write<char>((uint)_decryptedLength * sizeof(char), c); _decryptedLength++; } finally { ProtectMemory(); } } private void ClearCore() { _decryptedLength = 0; _buffer.ClearBuffer(); } private void DisposeCore() { if (_buffer != null) { _buffer.Dispose(); _buffer = null; } } private unsafe void InsertAtCore(int index, char c) { byte* bufferPtr = null; UnprotectMemory(); try { EnsureCapacity(_decryptedLength + 1); _buffer.AcquirePointer(ref bufferPtr); char* pBuffer = (char*)bufferPtr; for (int i = _decryptedLength; i > index; i--) { pBuffer[i] = pBuffer[i - 1]; } pBuffer[index] = c; ++_decryptedLength; } finally { ProtectMemory(); if (bufferPtr != null) { _buffer.ReleasePointer(); } } } private unsafe void RemoveAtCore(int index) { byte* bufferPtr = null; UnprotectMemory(); try { _buffer.AcquirePointer(ref bufferPtr); char* pBuffer = (char*)bufferPtr; for (int i = index; i < _decryptedLength - 1; i++) { pBuffer[i] = pBuffer[i + 1]; } pBuffer[--_decryptedLength] = (char)0; } finally { ProtectMemory(); if (bufferPtr != null) { _buffer.ReleasePointer(); } } } private void SetAtCore(int index, char c) { UnprotectMemory(); try { _buffer.Write<char>((uint)index * sizeof(char), c); } finally { ProtectMemory(); } } internal unsafe IntPtr MarshalToBSTRCore() { int length = _decryptedLength; IntPtr ptr = IntPtr.Zero; IntPtr result = IntPtr.Zero; byte* bufferPtr = null; UnprotectMemory(); try { _buffer.AcquirePointer(ref bufferPtr); int resultByteLength = (length + 1) * sizeof(char); ptr = Marshal.AllocBSTR(length); Buffer.MemoryCopy(bufferPtr, (byte*)ptr, resultByteLength, length * sizeof(char)); result = ptr; } finally { ProtectMemory(); // If we failed for any reason, free the new buffer if (result == IntPtr.Zero && ptr != IntPtr.Zero) { RuntimeImports.RhZeroMemory(ptr, (UIntPtr)(length * sizeof(char))); Marshal.FreeBSTR(ptr); } if (bufferPtr != null) { _buffer.ReleasePointer(); } } return result; } internal unsafe IntPtr MarshalToStringCore(bool globalAlloc, bool unicode) { int length = _decryptedLength; IntPtr ptr = IntPtr.Zero; IntPtr result = IntPtr.Zero; byte* bufferPtr = null; UnprotectMemory(); try { _buffer.AcquirePointer(ref bufferPtr); if (unicode) { int resultByteLength = (length + 1) * sizeof(char); ptr = globalAlloc ? Marshal.AllocHGlobal(resultByteLength) : Marshal.AllocCoTaskMem(resultByteLength); Buffer.MemoryCopy(bufferPtr, (byte*)ptr, resultByteLength, length * sizeof(char)); *(length + (char*)ptr) = '\0'; } else { uint defaultChar = '?'; int resultByteLength = 1 + Interop.Kernel32.WideCharToMultiByte( Interop.Kernel32.CP_ACP, Interop.Kernel32.WC_NO_BEST_FIT_CHARS, (char*)bufferPtr, length, null, 0, (IntPtr)(&defaultChar), IntPtr.Zero); ptr = globalAlloc ? Marshal.AllocHGlobal(resultByteLength) : Marshal.AllocCoTaskMem(resultByteLength); Interop.Kernel32.WideCharToMultiByte( Interop.Kernel32.CP_ACP, Interop.Kernel32.WC_NO_BEST_FIT_CHARS, (char*)bufferPtr, length, (byte*)ptr, resultByteLength - 1, (IntPtr)(&defaultChar), IntPtr.Zero); *(resultByteLength - 1 + (byte*)ptr) = 0; } result = ptr; } finally { ProtectMemory(); // If we failed for any reason, free the new buffer if (result == IntPtr.Zero && ptr != IntPtr.Zero) { RuntimeImports.RhZeroMemory(ptr, (UIntPtr)(length * sizeof(char))); MarshalFree(ptr, globalAlloc); } if (bufferPtr != null) { _buffer.ReleasePointer(); } } return result; } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- private const int BlockSize = (int)Interop.Crypt32.CRYPTPROTECTMEMORY_BLOCK_SIZE / sizeof(char); private SafeBSTRHandle _buffer; private bool _encrypted; private void AllocateBuffer(uint size) { _buffer = SafeBSTRHandle.Allocate(GetAlignedSize(size)); } private static uint GetAlignedSize(uint size) => size == 0 || size % BlockSize != 0 ? BlockSize + ((size / BlockSize) * BlockSize) : size; private void EnsureCapacity(int capacity) { if (capacity > MaxLength) { throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_Capacity); } if (((uint)capacity * sizeof(char)) <= _buffer.ByteLength) { return; } var oldBuffer = _buffer; SafeBSTRHandle newBuffer = SafeBSTRHandle.Allocate(GetAlignedSize((uint)capacity)); SafeBSTRHandle.Copy(oldBuffer, newBuffer, (uint)_decryptedLength * sizeof(char)); _buffer = newBuffer; oldBuffer.Dispose(); } private void ProtectMemory() { Debug.Assert(!_buffer.IsInvalid, "Invalid buffer!"); if (_decryptedLength != 0 && !_encrypted && !Interop.Crypt32.CryptProtectMemory(_buffer, _buffer.Length * sizeof(char), Interop.Crypt32.CRYPTPROTECTMEMORY_SAME_PROCESS)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } _encrypted = true; } private void UnprotectMemory() { Debug.Assert(!_buffer.IsInvalid, "Invalid buffer!"); if (_decryptedLength != 0 && _encrypted && !Interop.Crypt32.CryptUnprotectMemory(_buffer, _buffer.Length * sizeof(char), Interop.Crypt32.CRYPTPROTECTMEMORY_SAME_PROCESS)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } _encrypted = false; } } }
/* * OANDA v20 REST API * * The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more. * * OpenAPI spec version: 3.0.15 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace Oanda.RestV20.Model { /// <summary> /// StopLossDetails specifies the details of a Stop Loss Order to be created on behalf of a client. This may happen when an Order is filled that opens a Trade requiring a Stop Loss, or when a Trade&#39;s dependent Stop Loss Order is modified directly through the Trade. /// </summary> [DataContract] public partial class StopLossDetails : IEquatable<StopLossDetails>, IValidatableObject { /// <summary> /// The time in force for the created Stop Loss Order. This may only be GTC, GTD or GFD. /// </summary> /// <value>The time in force for the created Stop Loss Order. This may only be GTC, GTD or GFD.</value> [JsonConverter(typeof(StringEnumConverter))] public enum TimeInForceEnum { /// <summary> /// Enum GTC for "GTC" /// </summary> [EnumMember(Value = "GTC")] GTC, /// <summary> /// Enum GTD for "GTD" /// </summary> [EnumMember(Value = "GTD")] GTD, /// <summary> /// Enum GFD for "GFD" /// </summary> [EnumMember(Value = "GFD")] GFD, /// <summary> /// Enum FOK for "FOK" /// </summary> [EnumMember(Value = "FOK")] FOK, /// <summary> /// Enum IOC for "IOC" /// </summary> [EnumMember(Value = "IOC")] IOC } /// <summary> /// The time in force for the created Stop Loss Order. This may only be GTC, GTD or GFD. /// </summary> /// <value>The time in force for the created Stop Loss Order. This may only be GTC, GTD or GFD.</value> [DataMember(Name="timeInForce", EmitDefaultValue=false)] public TimeInForceEnum? TimeInForce { get; set; } /// <summary> /// Initializes a new instance of the <see cref="StopLossDetails" /> class. /// </summary> /// <param name="Price">The price that the Stop Loss Order will be triggered at..</param> /// <param name="TimeInForce">The time in force for the created Stop Loss Order. This may only be GTC, GTD or GFD..</param> /// <param name="GtdTime">The date when the Stop Loss Order will be cancelled on if timeInForce is GTD..</param> /// <param name="ClientExtensions">ClientExtensions.</param> public StopLossDetails(string Price = default(string), TimeInForceEnum? TimeInForce = default(TimeInForceEnum?), string GtdTime = default(string), ClientExtensions ClientExtensions = default(ClientExtensions)) { this.Price = Price; this.TimeInForce = TimeInForce; this.GtdTime = GtdTime; this.ClientExtensions = ClientExtensions; } /// <summary> /// The price that the Stop Loss Order will be triggered at. /// </summary> /// <value>The price that the Stop Loss Order will be triggered at.</value> [DataMember(Name="price", EmitDefaultValue=false)] public string Price { get; set; } /// <summary> /// The date when the Stop Loss Order will be cancelled on if timeInForce is GTD. /// </summary> /// <value>The date when the Stop Loss Order will be cancelled on if timeInForce is GTD.</value> [DataMember(Name="gtdTime", EmitDefaultValue=false)] public string GtdTime { get; set; } /// <summary> /// Gets or Sets ClientExtensions /// </summary> [DataMember(Name="clientExtensions", EmitDefaultValue=false)] public ClientExtensions ClientExtensions { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class StopLossDetails {\n"); sb.Append(" Price: ").Append(Price).Append("\n"); sb.Append(" TimeInForce: ").Append(TimeInForce).Append("\n"); sb.Append(" GtdTime: ").Append(GtdTime).Append("\n"); sb.Append(" ClientExtensions: ").Append(ClientExtensions).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as StopLossDetails); } /// <summary> /// Returns true if StopLossDetails instances are equal /// </summary> /// <param name="other">Instance of StopLossDetails to be compared</param> /// <returns>Boolean</returns> public bool Equals(StopLossDetails other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Price == other.Price || this.Price != null && this.Price.Equals(other.Price) ) && ( this.TimeInForce == other.TimeInForce || this.TimeInForce != null && this.TimeInForce.Equals(other.TimeInForce) ) && ( this.GtdTime == other.GtdTime || this.GtdTime != null && this.GtdTime.Equals(other.GtdTime) ) && ( this.ClientExtensions == other.ClientExtensions || this.ClientExtensions != null && this.ClientExtensions.Equals(other.ClientExtensions) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Price != null) hash = hash * 59 + this.Price.GetHashCode(); if (this.TimeInForce != null) hash = hash * 59 + this.TimeInForce.GetHashCode(); if (this.GtdTime != null) hash = hash * 59 + this.GtdTime.GetHashCode(); if (this.ClientExtensions != null) hash = hash * 59 + this.ClientExtensions.GetHashCode(); return hash; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Collections.Specialized { [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BitVector32 { public BitVector32(System.Collections.Specialized.BitVector32 value) { throw null; } public BitVector32(int data) { throw null; } public int Data { get { throw null; } } public int this[System.Collections.Specialized.BitVector32.Section section] { get { throw null; } set { } } public bool this[int bit] { get { throw null; } set { } } public static int CreateMask() { throw null; } public static int CreateMask(int previous) { throw null; } public static System.Collections.Specialized.BitVector32.Section CreateSection(short maxValue) { throw null; } public static System.Collections.Specialized.BitVector32.Section CreateSection(short maxValue, System.Collections.Specialized.BitVector32.Section previous) { throw null; } public override bool Equals(object o) { throw null; } public override int GetHashCode() { throw null; } public override string ToString() { throw null; } public static string ToString(System.Collections.Specialized.BitVector32 value) { throw null; } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Section { public short Mask { get { throw null; } } public short Offset { get { throw null; } } public bool Equals(System.Collections.Specialized.BitVector32.Section obj) { throw null; } public override bool Equals(object o) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Collections.Specialized.BitVector32.Section a, System.Collections.Specialized.BitVector32.Section b) { throw null; } public static bool operator !=(System.Collections.Specialized.BitVector32.Section a, System.Collections.Specialized.BitVector32.Section b) { throw null; } public override string ToString() { throw null; } public static string ToString(System.Collections.Specialized.BitVector32.Section value) { throw null; } } } public partial class HybridDictionary : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { public HybridDictionary() { } public HybridDictionary(bool caseInsensitive) { } public HybridDictionary(int initialSize) { } public HybridDictionary(int initialSize, bool caseInsensitive) { } public int Count { get { throw null; } } public bool IsFixedSize { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } public object this[object key] { get { throw null; } set { } } public System.Collections.ICollection Keys { get { throw null; } } public object SyncRoot { get { throw null; } } public System.Collections.ICollection Values { get { throw null; } } public void Add(object key, object value) { } public void Clear() { } public bool Contains(object key) { throw null; } public void CopyTo(System.Array array, int index) { } public System.Collections.IDictionaryEnumerator GetEnumerator() { throw null; } public void Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial interface IOrderedDictionary : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { object this[int index] { get; set; } new System.Collections.IDictionaryEnumerator GetEnumerator(); void Insert(int index, object key, object value); void RemoveAt(int index); } public partial class ListDictionary : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { public ListDictionary() { } public ListDictionary(System.Collections.IComparer comparer) { } public int Count { get { throw null; } } public bool IsFixedSize { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } public object this[object key] { get { throw null; } set { } } public System.Collections.ICollection Keys { get { throw null; } } public object SyncRoot { get { throw null; } } public System.Collections.ICollection Values { get { throw null; } } public void Add(object key, object value) { } public void Clear() { } public bool Contains(object key) { throw null; } public void CopyTo(System.Array array, int index) { } public System.Collections.IDictionaryEnumerator GetEnumerator() { throw null; } public void Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public abstract partial class NameObjectCollectionBase : System.Collections.ICollection, System.Collections.IEnumerable, System.Runtime.Serialization.ISerializable, System.Runtime.Serialization.IDeserializationCallback { protected NameObjectCollectionBase() { } protected NameObjectCollectionBase(System.Collections.IEqualityComparer equalityComparer) { } [System.ObsoleteAttribute("Please use NameObjectCollectionBase(IEqualityComparer) instead.")] protected NameObjectCollectionBase(System.Collections.IHashCodeProvider hashProvider, System.Collections.IComparer comparer) { } protected NameObjectCollectionBase(int capacity) { } protected NameObjectCollectionBase(int capacity, System.Collections.IEqualityComparer equalityComparer) { } [System.ObsoleteAttribute("Please use NameObjectCollectionBase(Int32, IEqualityComparer) instead.")] protected NameObjectCollectionBase(int capacity, System.Collections.IHashCodeProvider hashProvider, System.Collections.IComparer comparer) { } protected NameObjectCollectionBase(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual int Count { get { throw null; } } protected bool IsReadOnly { get { throw null; } set { } } public virtual System.Collections.Specialized.NameObjectCollectionBase.KeysCollection Keys { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } protected void BaseAdd(string name, object value) { } protected void BaseClear() { } protected object BaseGet(int index) { throw null; } protected object BaseGet(string name) { throw null; } protected string[] BaseGetAllKeys() { throw null; } protected object[] BaseGetAllValues() { throw null; } protected object[] BaseGetAllValues(System.Type type) { throw null; } protected string BaseGetKey(int index) { throw null; } protected bool BaseHasKeys() { throw null; } protected void BaseRemove(string name) { } protected void BaseRemoveAt(int index) { } protected void BaseSet(int index, object value) { } protected void BaseSet(string name, object value) { } public virtual System.Collections.IEnumerator GetEnumerator() { throw null; } public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual void OnDeserialization(object sender) { } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } public partial class KeysCollection : System.Collections.ICollection, System.Collections.IEnumerable { internal KeysCollection() { } public int Count { get { throw null; } } public string this[int index] { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public virtual string Get(int index) { throw null; } public System.Collections.IEnumerator GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } } } public partial class NameValueCollection : System.Collections.Specialized.NameObjectCollectionBase { public NameValueCollection() { } public NameValueCollection(System.Collections.IEqualityComparer equalityComparer) { } [System.ObsoleteAttribute("Please use NameValueCollection(IEqualityComparer) instead.")] public NameValueCollection(System.Collections.IHashCodeProvider hashProvider, System.Collections.IComparer comparer) { } public NameValueCollection(System.Collections.Specialized.NameValueCollection col) { } public NameValueCollection(int capacity) { } public NameValueCollection(int capacity, System.Collections.IEqualityComparer equalityComparer) { } [System.ObsoleteAttribute("Please use NameValueCollection(Int32, IEqualityComparer) instead.")] public NameValueCollection(int capacity, System.Collections.IHashCodeProvider hashProvider, System.Collections.IComparer comparer) { } public NameValueCollection(int capacity, System.Collections.Specialized.NameValueCollection col) { } protected NameValueCollection(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual string[] AllKeys { get { throw null; } } public string this[int index] { get { throw null; } } public string this[string name] { get { throw null; } set { } } public void Add(System.Collections.Specialized.NameValueCollection c) { } public virtual void Add(string name, string value) { } public virtual void Clear() { } public void CopyTo(System.Array dest, int index) { } public virtual string Get(int index) { throw null; } public virtual string Get(string name) { throw null; } public virtual string GetKey(int index) { throw null; } public virtual string[] GetValues(int index) { throw null; } public virtual string[] GetValues(string name) { throw null; } public bool HasKeys() { throw null; } protected void InvalidateCachedArrays() { } public virtual void Remove(string name) { } public virtual void Set(string name, string value) { } } public partial class OrderedDictionary : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable, System.Collections.Specialized.IOrderedDictionary, System.Runtime.Serialization.ISerializable, System.Runtime.Serialization.IDeserializationCallback { public OrderedDictionary() { } public OrderedDictionary(System.Collections.IEqualityComparer comparer) { } public OrderedDictionary(int capacity) { } public OrderedDictionary(int capacity, System.Collections.IEqualityComparer comparer) { } protected OrderedDictionary(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public int Count { get { throw null; } } public bool IsReadOnly { get { throw null; } } public object this[int index] { get { throw null; } set { } } public object this[object key] { get { throw null; } set { } } public System.Collections.ICollection Keys { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IDictionary.IsFixedSize { get { throw null; } } public System.Collections.ICollection Values { get { throw null; } } public void Add(object key, object value) { } public System.Collections.Specialized.OrderedDictionary AsReadOnly() { throw null; } public void Clear() { } public bool Contains(object key) { throw null; } public void CopyTo(System.Array array, int index) { } public virtual System.Collections.IDictionaryEnumerator GetEnumerator() { throw null; } public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public void Insert(int index, object key, object value) { } protected virtual void OnDeserialization(object sender) { } void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(object sender) { } public void Remove(object key) { } public void RemoveAt(int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial class StringCollection : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { public StringCollection() { } public int Count { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } public string this[int index] { get { throw null; } set { } } public object SyncRoot { get { throw null; } } bool System.Collections.IList.IsFixedSize { get { throw null; } } bool System.Collections.IList.IsReadOnly { get { throw null; } } object System.Collections.IList.this[int index] { get { throw null; } set { } } public int Add(string value) { throw null; } public void AddRange(string[] value) { } public void Clear() { } public bool Contains(string value) { throw null; } public void CopyTo(string[] array, int index) { } public System.Collections.Specialized.StringEnumerator GetEnumerator() { throw null; } public int IndexOf(string value) { throw null; } public void Insert(int index, string value) { } public void Remove(string value) { } public void RemoveAt(int index) { } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } int System.Collections.IList.Add(object value) { throw null; } bool System.Collections.IList.Contains(object value) { throw null; } int System.Collections.IList.IndexOf(object value) { throw null; } void System.Collections.IList.Insert(int index, object value) { } void System.Collections.IList.Remove(object value) { } } public partial class StringDictionary : System.Collections.IEnumerable { public StringDictionary() { } public virtual int Count { get { throw null; } } public virtual bool IsSynchronized { get { throw null; } } public virtual string this[string key] { get { throw null; } set { } } public virtual System.Collections.ICollection Keys { get { throw null; } } public virtual object SyncRoot { get { throw null; } } public virtual System.Collections.ICollection Values { get { throw null; } } public virtual void Add(string key, string value) { } public virtual void Clear() { } public virtual bool ContainsKey(string key) { throw null; } public virtual bool ContainsValue(string value) { throw null; } public virtual void CopyTo(System.Array array, int index) { } public virtual System.Collections.IEnumerator GetEnumerator() { throw null; } public virtual void Remove(string key) { } } public partial class StringEnumerator { internal StringEnumerator() { } public string Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file=".cs" company="sgmunn"> // (c) sgmunn 2012 // // 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> // -------------------------------------------------------------------------------------------------------------------- namespace MonoKit.UI.PagedViews { using System; using System.Linq; using MonoTouch.UIKit; using System.Drawing; using System.Collections.Generic; using MonoTouch.Foundation; /// <summary> /// Defines a class for handling pages that scroll from left to right (like the photo browser) /// </summary> public class ScrollingPageView : UIView { /// <summary> /// The scrolling page delegate. /// </summary> private WeakReference scrollingPageDelegate; /// <summary> /// The background view. /// </summary> protected UIView backgroundView; /// <summary> /// The scroll view that our pages are hosted in /// </summary> protected UIScrollView pageScrollView; /// <summary> /// A list of the pages that are visible. /// </summary> private List<ScrollPage> visiblePages; /// <summary> /// The list of pages that have been recycled. /// </summary> private List<ScrollPage> recycledPages; /// <summary> /// The index of the current page. /// </summary> private int currentIndex = -1; /// <summary> /// Determines if we show the left part of the next page /// </summary> private bool showNextPagePreview; /// <summary> /// Stores the number of pages returned from the delegate. /// </summary> private int pageCount; private PageControl pageControl; /// <summary> /// Initializes a new instance of the <see cref="MonoKit.UI.PagedViews.ScrollingPageView"/> class. /// </summary> /// <param name='frame'> /// The frame that the view should be in. /// </param> /// <param name='showNextPagePreview'> /// Determines if the view should show a little bit of the left side of the next page /// </param> public ScrollingPageView(RectangleF frame, bool showNextPagePreview) : base(frame) { this.showNextPagePreview = showNextPagePreview; this.visiblePages = new List<ScrollPage>(); this.recycledPages = new List<ScrollPage>(); if (!showNextPagePreview) { var fm = frame; fm.X = 0; fm.Width = frame.Width; fm.Y = frame.Height - 20; fm.Height = 20; this.pageControl = new PageControl(fm); this.pageControl.AutoresizingMask = UIViewAutoresizing.All; this.AddSubview(this.pageControl); } this.Initialize(frame, showNextPagePreview); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (this.visiblePages.Count > 0) { foreach (var page in this.visiblePages) { page.View.RemoveFromSuperview(); page.View.Dispose(); page.View = null; } this.visiblePages.Clear(); } if (this.recycledPages.Count > 0) { foreach (var page in this.recycledPages) { page.View.Dispose(); page.View = null; } this.recycledPages.Clear(); } } /// <summary> /// Gets or sets the delegate to use as a controller for showing pages /// </summary> /// <value> /// The delegate. /// </value> public IScrollingPageViewDelegate Delegate { get { if (this.scrollingPageDelegate == null) { return null; } object t = this.scrollingPageDelegate.Target; return t as IScrollingPageViewDelegate; } set { this.scrollingPageDelegate = new WeakReference(value); } } /// <summary> /// Reloads the pages and updates the view /// </summary> public void ReloadPages() { this.pageCount = this.GetPageCount(); this.currentIndex = -1; var pageFrame = new RectangleF(0, 0, this.Frame.Size.Width, this.Frame.Size.Height); if (this.showNextPagePreview) { pageFrame.Width -= 30; } this.pageScrollView.Frame = pageFrame; this.pageScrollView.ContentSize = new SizeF(pageFrame.Size.Width * this.pageCount, pageFrame.Size.Height); var index = this.PagesScrolled(true); if (this.pageCount > 0) { this.NotifyIndexChanged(index, true); } if (this.pageControl != null) { this.pageControl.Pages = this.pageCount; } } /// <summary> /// Scrolls to a particular page /// </summary> /// <param name='index'> /// The page index to scroll to /// </param> public void ScrollToPage(int index) { if (index < 0) { index = 0; } if (index > this.pageCount - 1) { index = this.pageCount - 1; } var frame = this.pageScrollView.Frame; frame.X = frame.Size.Width * index; this.pageScrollView.ScrollRectToVisible(frame, true); this.currentIndex = index; } /// <summary> /// Creates a page with the given typeKey. The typeKey is used to allow pages to be different view types, and not all the same /// view class. /// </summary> /// <returns> /// Returns a ScrollPage containing the view, and reuse key /// </returns> /// <param name='pageTypeKey'> /// Page type key. /// </param> /// <param name='frame'> /// Frame. /// </param> private ScrollPage CreatePage(string pageTypeKey, RectangleF frame) { var d = this.Delegate; if (d != null) { var v = d.CreateView(pageTypeKey, frame); v.Frame = frame; return new ScrollPage() { View = v, ReuseKey = pageTypeKey }; } throw new NullReferenceException("Delegate is null"); } /// <summary> /// Gets the page count from the Delegate /// </summary> /// <returns> /// The page count. /// </returns> private int GetPageCount() { var d = this.Delegate; if (d != null) { return d.PageCount; } return 0; } /// <summary> /// Notifies that the current page has changed. /// </summary> /// <param name='index'> /// The index of the page that is now the current page /// </param> /// <param name='refreshed'> /// Indicates that the delegate should be notified, even if the page is the same as last time. /// </param> private void NotifyIndexChanged(int index, bool refreshed) { if (refreshed || this.currentIndex != index) { this.currentIndex = index; var d = this.Delegate; if (d != null) { d.PageIndexChanged(index); } } if (this.pageControl != null) { this.pageControl.CurrentPage = index; } } /// <summary> /// Handles the event when the scroll viewer has scrolled and returns the current page index /// </summary> /// <returns> /// Returns the index of the page that is now the current page /// </returns> /// <param name='refreshed'> /// Indicates that the scroll is a result of the pages being refeshed /// </param> private int PagesScrolled(bool refreshed) { // Calculate which pages are visible var visibleBounds = this.pageScrollView.Bounds; var contentBounds = this.pageScrollView.Frame; // get the first and last pages of the scroll view that are visible. we add 1 to the last because // we display the second page unclipped outside the scroll view int firstNeededPageIndex = (int)Math.Floor(visibleBounds.Left / contentBounds.Width); int lastNeededPageIndex = (int)Math.Floor((visibleBounds.Right - 1) / contentBounds.Width) + 1; // make sure these fit inside our page array firstNeededPageIndex = Math.Max(firstNeededPageIndex, 0); lastNeededPageIndex = Math.Min(lastNeededPageIndex, this.pageCount - 1); this.RecyclePagesNotVisible(firstNeededPageIndex, lastNeededPageIndex); // make sure the visible pages are being displayed for (int index = firstNeededPageIndex; index <= lastNeededPageIndex; index++) { if (!this.IsDisplayingPageForIndex(index) || refreshed) { this.UpdatePage(index); } } return firstNeededPageIndex; } /// <summary> /// Recycles the pages are not visible. /// </summary> /// <param name='firstNeededPageIndex'> /// First needed page index. /// </param> /// <param name='lastNeededPageIndex'> /// Last needed page index. /// </param> private void RecyclePagesNotVisible(int firstNeededPageIndex, int lastNeededPageIndex) { foreach (var view in this.visiblePages) { if (view.Index < firstNeededPageIndex || view.Index > lastNeededPageIndex) { this.recycledPages.Add(view); view.View.RemoveFromSuperview(); } } foreach (var view in this.recycledPages) { this.visiblePages.Remove(view); } } /// <summary> /// Updates the page at the given index /// </summary> /// <param name='index'> /// The page index /// </param> private void UpdatePage(int index) { var d = this.Delegate; if (d != null) { var key = d.GetPageTypeKey(index); var page = this.DequeueRecycledView(key); if (page == null) { page = this.CreatePage(key, this.pageScrollView.Frame); } this.UpdatePage(page, index); this.pageScrollView.AddSubview(page.View); this.visiblePages.Add(page); } } /// <summary> /// Dequeues a recycled view with the given pageTypeKey /// </summary> /// <returns> /// The recycled view. /// </returns> /// <param name='pageTypeKey'> /// The type of the page to dequeue /// </param> private ScrollPage DequeueRecycledView(string pageTypeKey) { ScrollPage page = this.recycledPages.FirstOrDefault(p => p.ReuseKey == pageTypeKey); if (page != null) { this.recycledPages.Remove(page); } return page; } /// <summary> /// Determines whether this instance is displaying page for index the specified index. /// </summary> /// <returns> /// <c>true</c> if this instance is displaying page for index the specified index; otherwise, <c>false</c>. /// </returns> /// <param name='index'> /// If set to <c>true</c> index. /// </param> private bool IsDisplayingPageForIndex(int index) { foreach (var page in this.visiblePages) { if (page.Index == index) { return true; } } return false; } /// <summary> /// Updates the page. /// </summary> /// <param name='page'> /// The scroll page to update /// </param> /// <param name='index'> /// The page index that the page is now at. /// </param> private void UpdatePage(ScrollPage page, int index) { page.Index = index; page.View.Frame = this.FrameForPageAtIndex(index); var d = this.Delegate; if (d != null) { d.UpdatePage(index, page.View); } } /// <summary> /// Gets the frame for the page at the specified index /// </summary> /// <returns> /// Returns the frame for the page /// </returns> /// <param name='index'> /// The index of the page that we need to calculate the frame for /// </param> private RectangleF FrameForPageAtIndex(int index) { var pagingScrollViewFrame = this.pageScrollView.Frame; pagingScrollViewFrame.X = (pagingScrollViewFrame.Size.Width * index); return pagingScrollViewFrame; } /// <summary> /// Initialize the view with the frame /// </summary> /// <param name='frame'> /// The frame to initialize the view in /// </param> /// <param name='showNextPagePreview'> /// Allow space to preview the next page /// </param> private void Initialize(RectangleF frame, bool showNextPagePreview) { var newFrame = new RectangleF(0, 0, frame.Size.Width, frame.Size.Height); this.backgroundView = new UIView(newFrame); this.backgroundView.ClipsToBounds = true; this.backgroundView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth; var pageFrame = newFrame; if (showNextPagePreview) { pageFrame.Width -= 30; } this.pageScrollView = new UIScrollView(pageFrame); this.pageScrollView.PagingEnabled = true; this.pageScrollView.ShowsVerticalScrollIndicator = false; this.pageScrollView.ShowsHorizontalScrollIndicator = true; this.pageScrollView.ContentSize = new SizeF(pageFrame.Size.Width * 0, pageFrame.Size.Height); this.pageScrollView.ShowsHorizontalScrollIndicator = false; this.pageScrollView.ClipsToBounds = false; this.pageScrollView.Delegate = new ScrollDelegate(this); this.backgroundView.AddSubview(this.pageScrollView); this.AddSubview(this.backgroundView); if (this.pageControl != null) { this.BringSubviewToFront(this.pageControl); } } /// <summary> /// Stores information about a view, it's current index (when active) and it's reuse key /// </summary> private class ScrollPage { public UIView View { get; set; } public int Index { get; set; } public string ReuseKey{ get; set; } } /// <summary> /// Responds to scrolling events of the scroll viewer /// </summary> private class ScrollDelegate : UIScrollViewDelegate { private WeakReference parent; public ScrollDelegate(ScrollingPageView parent) { this.parent = new WeakReference(parent); } public override void Scrolled(UIScrollView scrollView) { var p = this.parent.Target; if (p != null && this.parent.IsAlive) { (p as ScrollingPageView).PagesScrolled(false); } } public override void DecelerationEnded(UIScrollView scrollView) { var p = this.parent.Target; if (p != null && this.parent.IsAlive) { var realP = p as ScrollingPageView; var visibleBounds = realP.pageScrollView.Bounds; var contentBounds = realP.pageScrollView.Frame; // get the first and last pages of the scroll view that are visible. we add 1 to the last because // we display the second page unclipped outside the scroll view int firstNeededPageIndex = (int)Math.Floor(visibleBounds.Left / contentBounds.Width); firstNeededPageIndex = Math.Max(firstNeededPageIndex, 0); realP.NotifyIndexChanged(firstNeededPageIndex, false); } } } } }
using System; using System.Collections.Generic; namespace Simbiosis { /// <summary> /// The user's submarine (the normal camera location). /// /// PUT THIS IN A DLL OF ITS OWN, TO ALLOW "UPGRADES"??? /// /// class Submarine is the main part, with five sockets (right jet, left jet, right spinner, left spinner, dome) /// and one hotspot (camera, mounted in pilot's window) /// /// PROPULSION / STEERING /// The main sub is negatively bouyant (heavy enough to fall suitably quickly when the dome has zero Buoyancy). /// The dome is positively bouyant and normally counteracts the weight of the sub, making the whole thing neutral. /// The dome's Buoyancy can be increased/decreased under user control for ascent/descent. /// The main engines are the spinners at the back, each of which has a hotspot and produces thrust. Steering drives these /// independently for yaw. /// There are swivelling jets on the sides, which produce pitch. /// Any roll is a result of the dynamics (or collisions) and will be damped out by the dome Buoyancy. /// /// Main body sends control signals to other parts using these nerves: /// Yang 0 (nerve 9) = right jet /// Yang 1 = left jet (kept separate so that they can swivel independently for roll control if appropriate /// Yang 2 = right spinner (propulsion) /// Yang 3 = left spinner /// Yang 4 = dome (Buoyancy) /// /// </summary> /// <summary> /// Main part of sub /// </summary> public class Submarine : Physiology { // Propulsion hotspots float top = 0; float bot = 0; float left = 0; float right = 0; float rightDown = 0; float leftDown = 0; const float YAWRATE = 0.7f; // controls maximum rate of horizontal turn /// <summary> /// Pan and tilt of the observation bubble camera /// </summary> float pan = 0.5f; float tilt = 0.5f; /// <summary> /// ONLY set the physical properties in the constructor. Use Init() for initialisation. /// </summary> public Submarine() { // Define my properties Mass = 10f; // pretty heavy - scatters creatures it hits Resistance = 0.5f; // increase resistance to reduce run-on Buoyancy = -1f; // weight counterbalances Buoyancy of flotation dome // Define my channels channelData = new ChannelData[][] { new ChannelData[] { new ChannelData(ChannelData.Socket.XX, ChannelData.Socket.S0, 1, 0f, "Buoyancy"), new ChannelData(ChannelData.Socket.XX, ChannelData.Socket.S1, 1, 0f, "Right"), new ChannelData(ChannelData.Socket.XX, ChannelData.Socket.S2, 1, 0f, "Left"), new ChannelData(ChannelData.Socket.XX, ChannelData.Socket.S3, 1, 0f, "Top"), new ChannelData(ChannelData.Socket.XX, ChannelData.Socket.S4, 1, 0f, "Bot"), new ChannelData(ChannelData.Socket.XX, ChannelData.Socket.S5, 1, 0f, "RightDown"), new ChannelData(ChannelData.Socket.XX, ChannelData.Socket.S6, 1, 0f, "LeftDown"), } }; } /// <summary> /// Called once .owner etc. have been set up by the cell. Do your main initialisation here. /// </summary> public override void Init() { Output(0, 0.5f); // initially neutral Buoyancy } /// <summary> /// Called on a SlowUpdate tick (about 4 times a second). /// </summary> public override void SlowUpdate() { } /// <summary> /// Called every frame /// </summary> public override void FastUpdate(float elapsedTime) { // Update all our signals base.FastUpdate(elapsedTime); JointOutput[1] = pan; JointOutput[0] = tilt; } /// <summary> /// We've been asked if we will accept the role of camera mount. /// </summary> public override int AssignCamera(IControllable currentOwner, int currentHotspot) { if (owner.CurrentPanel() == 0) return 0; // if panel[0] (main control panel) is showing, our camera looks out the front if (owner.CurrentPanel() == 1) return 1; // if panel[1] (observation bubble) is showing, we look out the top return -1; // else don't accept camera } /// <summary> /// We've been sent some steering control data because we are the ROOT cell of /// an organism that is currently the camera ship. /// </summary> /// <param name="tiller">the joystick/keyboard data relevant to steering camera ships</param> /// <param name="elapsedTime">elapsed time this frame, in case motion/animation needs to be proportional</param> public override void Steer(TillerData tiller, float elapsedTime) { // in panel 1, the joystick controls the pilot's head (camera), to look around the scene from the observation bubble if (owner.CurrentPanel() == 1) { pan -= tiller.Joystick.Y * elapsedTime * 0.3f; if (pan < 0) pan = 0; else if (pan > 1) pan = 1; tilt -= tiller.Joystick.X * elapsedTime * 0.3f; if (tilt < 0) tilt = 0; else if (tilt > 1) tilt = 1; } // In panel 0, the joystick controls the thrusters else { // Convert the joystick xy into four steering thrust values for right, left, top, bottom fans bot = tiller.Joystick.Y * 0.25f; top = -bot; left = tiller.Joystick.X * 0.25f; right = -left; // add main thrust equally to all (NOTE: total of steering + thrust must be in range +/-1 at this point) float thrust = tiller.Thrust * 0.5f; top += thrust; bot += thrust; left += thrust; right += thrust; // supply a bit of the left/right thrust to the downward facing jets to add some roll to the turn leftDown = tiller.Joystick.X * 0.15f; rightDown = -leftDown; // pump the thrust values into the nervous system (as unsigned values, where 0.5 is neutral) Output(2, left / 2f + 0.5f); Output(1, right / 2f + 0.5f); Output(4, bot / 2f + 0.5f); Output(3, top / 2f + 0.5f); Output(6, leftDown / 2f + 0.5f); Output(5, rightDown / 2f + 0.5f); } } /// <summary> /// We've been sent a button command from a control panel because we are the ROOT cell of /// an organism that is currently the camera ship. /// Overload this method if you need to respond to the button(s), e.g. to steer the view camera or a spotlight from the cockpit /// by changing one or more anim# jointframes /// </summary> /// <param name="c">The name of the button or other widget that has been pressed/released/changed</param> /// <param name="state">Widget state (type depends on the button, e.g. bool for pushbuttons, float for knobs)</param> /// <param name="elapsedTime">frame time</param> public override void Command(string c, object state, float elapsedTime) { switch (c) { // A knob on the panel controls our Buoyancy case "buoyancy": Output(0, (float)state); break; // Other panel commands go here } } } /// <summary> /// Submarine propulsion fan /// </summary> public class SubFan : Physiology { private const float RIPPLERANGE = 10.0f; // Maximum distance over which ripples of disturbance from fan can be detected private float rippleCounter = 0; // used to slow down rate of ripple stimuli to once per second /// <summary> /// ONLY set the physical properties in the constructor. Use Init() for initialisation. /// </summary> public SubFan() { // Define my properties Mass = 0.1f; Resistance = 0.4f; // increase resistance to increase roll/pitch stability when thrust is cancelled Buoyancy = 0f; // Define my channels channelData = new ChannelData[][] { new ChannelData[] { new ChannelData(ChannelData.Socket.PL, ChannelData.Socket.XX, 1, 0f, "Speed"), // input channel from plug - controls speed } }; } /// <summary> /// Called once .owner etc. have been set up by the cell. Do your main initialisation here. /// </summary> public override void Init() { } /// <summary> /// Called every frame /// </summary> public override void FastUpdate(float elapsedTime) { // Update nerve signals base.FastUpdate(elapsedTime); // Use input nerve to determine thrust (convert to signed value) float thrust = Input(0) * 2f - 1f; owner.JetPropulsion(0, thrust * 100f); // animate the fan at a speed and direction proportional to thrust JointOutput[0] += thrust * elapsedTime * 16; if (JointOutput[0] > 1.0f) JointOutput[0] = 0; else if (JointOutput[0] < 0) JointOutput[0] = 1; } /// <summary> /// Called on a SlowUpdate tick (about 4 times a second). /// </summary> public override void SlowUpdate() { // About once a second, send out a ripple of disturbance (a stimulus) if the fan is moving, to frighten the fish if (++rippleCounter > 3) { rippleCounter = 0; if ((Input(0)>0.6f)||(Input(0)<0.4f)) Disturbance(Input(0) * RIPPLERANGE); } } } /// <summary> /// Submarine dome - Adds some variable Buoyancy at the top to keep the sub roughly upright and allow control of ascent/descent /// </summary> public class SubDome : Physiology { const float BUOYANCYNEUTRAL = 1f; // neutral Buoyancy is when ours exactly counters that of main sub const float BUOYANCYRANGE = 0.5f; // neutral +/- this amount = permissible range /// <summary> /// ONLY set the physical properties in the constructor. Use Init() for initialisation. /// </summary> public SubDome() { // Define my properties Mass = 0.1f; Resistance = 0.0f; // increase resistance if nose pitched down when power applied Buoyancy = BUOYANCYNEUTRAL; // Define my channels channelData = new ChannelData[][] { new ChannelData[] { new ChannelData(ChannelData.Socket.PL, ChannelData.Socket.XX, 1, 0f, "Buoyancy"), // input channel from plug - controls weight } }; } /// <summary> /// Called once .owner etc. have been set up by the cell. Do your main initialisation here. /// </summary> public override void Init() { } /// <summary> /// no nerves or animation, so just return /// </summary> public override void FastUpdate(float elapsedTime) { // Update nerve signals base.FastUpdate(elapsedTime); // Input nerve controls Buoyancy (cvt into range = +/-1) float input = Input(0) * 2f - 1f; if ((input > -0.1f) && (input < 0.1f)) input = 0; // Create a null zone, so that knob is easier to zero Buoyancy = BUOYANCYNEUTRAL + input * BUOYANCYRANGE; // owner.ConsoleMessage("Buoyancy : "+Buoyancy); } } }
namespace Fonet.Image { using System; using System.IO; using System.Text; using Fonet.DataTypes; /// <summary> /// Parses the contents of a JPEG image header to infer the colour /// space and bits per pixel. /// </summary> internal sealed class JpegParser : IDisposable { public const int M_SOF0 = 0xC0; /* Start Of Frame N */ public const int M_SOF1 = 0xC1; /* N indicates which compression process */ public const int M_SOF2 = 0xC2; /* Only SOF0-SOF2 are now in common use */ public const int M_SOF3 = 0xC3; public const int M_SOF5 = 0xC5; /* NB: codes C4 and CC are NOT SOF markers */ public const int M_SOF6 = 0xC6; public const int M_SOF7 = 0xC7; public const int M_SOF9 = 0xC9; public const int M_SOF10 = 0xCA; public const int M_SOF11 = 0xCB; public const int M_SOF13 = 0xCD; public const int M_SOF14 = 0xCE; public const int M_SOF15 = 0xCF; public const int M_SOI = 0xD8; /* Start Of Image (beginning of datastream) */ public const int M_EOI = 0xD9; /* End Of Image (end of datastream) */ public const int M_SOS = 0xDA; /* Start Of Scan (begins compressed data) */ public const int M_APP0 = 0xE0; /* Application-specific marker, type N */ public const int M_APP1 = 0xE1; public const int M_APP2 = 0xE2; public const int M_APP3 = 0xE3; public const int M_APP4 = 0xE4; public const int M_APP5 = 0xE5; public const int M_APP12 = 0xEC; /* (we don't bother to list all 16 APPn's) */ public const int M_COM = 0xFE; /* COMment */ public const string ICC_PROFILE = "ICC_PROFILE\0"; /// <summary> /// JPEG image data /// </summary> private MemoryStream ms; /// <summary> /// Contains number of bitplanes, color space and optional ICC Profile /// </summary> private JpegInfo headerInfo; /// <summary> /// Raw ICC Profile /// </summary> private MemoryStream iccProfileData; /// <summary> /// Class constructor. /// </summary> /// <param name="data"></param> public JpegParser(byte[] data) { this.ms = new MemoryStream(data); this.headerInfo = new JpegInfo(); } public JpegInfo Parse() { // File must begin with SOI marker if (ReadFirstMarker() != M_SOI) { throw new InvalidOperationException("Expected SOI marker first"); } while (ms.Position < ms.Length) { int marker = ReadNextMarker(); switch (marker) { case M_SOF0: // Baseline case M_SOF1: // Extended sequential, Huffman case M_SOF2: // Progressive, Huffman case M_SOF3: // Lossless, Huffman case M_SOF5: // Differential sequential, Huffman case M_SOF6: // Differential progressive, Huffman case M_SOF7: // Differential lossless, Huffman case M_SOF9: // Extended sequential, Huffman case M_SOF10: // Progressive, arithmetic case M_SOF11: // Lossless, arithmetic case M_SOF13: // Differential sequential, arithmetic case M_SOF14: // Differential progressive, arithmetic case M_SOF15: // Differential lossless, arithmetic ReadHeader(); break; case M_APP2: // ICC Profile ReadICCProfile(); break; default: SkipVariable(); break; } } if (iccProfileData != null) { headerInfo.SetICCProfile(iccProfileData.ToArray()); } return headerInfo; } private void ReadICCProfile() { if (iccProfileData == null) { iccProfileData = new MemoryStream(); } // Length of entire block in bytes int length = ReadInt(); // Should be the string constant "ICC_PROFILE" string iccProfile = ReadString(12); if (!iccProfile.Equals(ICC_PROFILE)) { throw new Exception("Missing ICC_PROFILE identifier in APP2 block"); } ReadByte(); // Sequence number of block ReadByte(); // Total number of markers // Accumulate profile data in temporary memory stream byte[] profileData = new Byte[length - 16]; ms.Read(profileData, 0, profileData.Length); iccProfileData.Write(profileData, 0, profileData.Length); } /// <summary> /// /// </summary> private void ReadHeader() { ReadInt(); // Length of block headerInfo.SetBitsPerSample(ReadByte()); headerInfo.SetHeight(ReadInt()); headerInfo.SetWidth(ReadInt()); headerInfo.SetNumColourComponents(ReadByte()); } /// <summary> /// Reads a 16-bit integer from the underlying stream /// </summary> /// <returns></returns> private int ReadInt() { return (ReadByte() << 8) + ReadByte(); } /// <summary> /// Reads a 32-bit integer from the underlying stream /// </summary> /// <returns></returns> private byte ReadByte() { return (byte)ms.ReadByte(); } /// <summary> /// Reads the specified number of bytes from theunderlying stream /// and converts them to a string using the ASCII encoding. /// </summary> /// <param name="numBytes"></param> /// <returns></returns> private string ReadString(int numBytes) { byte[] name = new byte[numBytes]; ms.Read(name, 0, name.Length); return Encoding.ASCII.GetString(name); } /// <summary> /// Reads the initial marker which should be SOI. /// </summary> /// <remarks> /// After invoking this method the stream will point to the location /// immediately after the fiorst marker. /// </remarks> /// <returns></returns> private int ReadFirstMarker() { int b1 = ms.ReadByte(); int b2 = ms.ReadByte(); if (b1 != 0xFF || b2 != M_SOI) { throw new InvalidOperationException("Not a JPEG file"); } return b2; } /// <summary> /// Reads the next JPEG marker and returns its marker code. /// </summary> /// <returns></returns> private int ReadNextMarker() { // Skip stream contents until we reach a FF tag int b = ms.ReadByte(); while (b != 0xFF) { b = ms.ReadByte(); } // Skip any FF padding bytes do { b = ms.ReadByte(); } while (b == 0xFF); return b; } /// <summary> /// Skips over the parameters for any marker we don't want to process. /// </summary> private void SkipVariable() { int length = ReadInt(); // Length includes itself, therefore it must be at least 2 if (length < 2) { throw new InvalidOperationException("Invalid JPEG marker length"); } // Skip all parameters ms.Seek(length - 2, SeekOrigin.Current); } #region IDisposable members public void Dispose() { this.headerInfo = null; this.iccProfileData = null; if(ms != null) this.ms.Dispose(); ms = null; this.headerInfo = null; } #endregion } internal class JpegInfo : IDisposable { private int colourSpace = ColorSpace.DeviceUnknown; private int bitsPerSample; private int width; private int height; private byte[] profileData; internal void SetNumColourComponents(int colourComponents) { // Translate number of colur components into a ColourSpace constant switch (colourComponents) { case 1: this.colourSpace = ColorSpace.DeviceGray; break; case 3: this.colourSpace = ColorSpace.DeviceRgb; break; case 4: this.colourSpace = ColorSpace.DeviceCmyk; break; default: this.colourSpace = ColorSpace.DeviceUnknown; break; } } internal void SetBitsPerSample(int bitsPerSample) { this.bitsPerSample = bitsPerSample; } internal void SetWidth(int width) { this.width = width; } internal void SetHeight(int height) { this.height = height; } internal void SetICCProfile(byte[] profileData) { this.profileData = profileData; } public byte[] ICCProfileData { get { return profileData; } } public bool HasICCProfile { get { return (profileData != null); } } public int ColourSpace { get { return colourSpace; } } public int BitsPerSample { get { return bitsPerSample; } } public int Width { get { return width; } } public int Height { get { return height; } } #region IDisposable members public void Dispose() { this.profileData = null; } #endregion } }
// Copyright 2008-2011. This work is licensed under the BSD license, available at // http://www.movesinstitute.org/licenses // // Orignal authors: DMcG, Jason Nelson // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - [email protected]) using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace OpenDis.Enumerations.EntityState.Type { /// <summary> /// Enumeration values for SurfacePlatform (es.type.kind.1.domain.3.cat, Platform-Surface Category, /// section 4.2.1.1.3.3) /// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was /// obtained from http://discussions.sisostds.org/default.asp?action=10&amp;fd=31 /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Serializable] public enum SurfacePlatform : byte { /// <summary> /// Other. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Other.")] Other = 0, /// <summary> /// Carrier. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Carrier.")] Carrier = 1, /// <summary> /// Command Ship/Cruiser. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Command Ship/Cruiser.")] CommandShipCruiser = 2, /// <summary> /// Guided Missile Cruiser. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Guided Missile Cruiser.")] GuidedMissileCruiser = 3, /// <summary> /// Guided Missile Destroyer (DDG). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Guided Missile Destroyer (DDG).")] GuidedMissileDestroyerDDG = 4, /// <summary> /// Destroyer (DD). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Destroyer (DD).")] DestroyerDD = 5, /// <summary> /// Guided Missile Frigate (FFG). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Guided Missile Frigate (FFG).")] GuidedMissileFrigateFFG = 6, /// <summary> /// Light/Patrol Craft. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Light/Patrol Craft.")] LightPatrolCraft = 7, /// <summary> /// Mine Countermeasure Ship/Craft. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Mine Countermeasure Ship/Craft.")] MineCountermeasureShipCraft = 8, /// <summary> /// Dock Landing Ship. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Dock Landing Ship.")] DockLandingShip = 9, /// <summary> /// Tank Landing Ship. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Tank Landing Ship.")] TankLandingShip = 10, /// <summary> /// Landing Craft. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Landing Craft.")] LandingCraft = 11, /// <summary> /// Light Carrier. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Light Carrier.")] LightCarrier = 12, /// <summary> /// Cruiser/Helicopter Carrier. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Cruiser/Helicopter Carrier.")] CruiserHelicopterCarrier = 13, /// <summary> /// Hydrofoil. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Hydrofoil.")] Hydrofoil = 14, /// <summary> /// Air Cushion/Surface Effect. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Air Cushion/Surface Effect.")] AirCushionSurfaceEffect = 15, /// <summary> /// Auxiliary. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Auxiliary.")] Auxiliary = 16, /// <summary> /// Auxiliary, Merchant Marine. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Auxiliary, Merchant Marine.")] AuxiliaryMerchantMarine = 17, /// <summary> /// Utility. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Utility.")] Utility = 18, /// <summary> /// Frigate (including Corvette). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Frigate (including Corvette).")] FrigateIncludingCorvette = 50, /// <summary> /// Battleship. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Battleship.")] Battleship = 51, /// <summary> /// Heavy Cruiser. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Heavy Cruiser.")] HeavyCruiser = 52, /// <summary> /// Destroyer Tender. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Destroyer Tender.")] DestroyerTender = 53, /// <summary> /// Amphibious Assault Ship. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Amphibious Assault Ship.")] AmphibiousAssaultShip = 54, /// <summary> /// Amphibious Cargo Ship. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Amphibious Cargo Ship.")] AmphibiousCargoShip = 55, /// <summary> /// Amphibious Transport Dock. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Amphibious Transport Dock.")] AmphibiousTransportDock = 56, /// <summary> /// Ammunition Ship. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Ammunition Ship.")] AmmunitionShip = 57, /// <summary> /// Combat Stores Ship. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Combat Stores Ship.")] CombatStoresShip = 58, /// <summary> /// Surveillance Towed Array Sonar System (SURTASS). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Surveillance Towed Array Sonar System (SURTASS).")] SurveillanceTowedArraySonarSystemSURTASS = 59, /// <summary> /// Fast Combat Support Ship. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Fast Combat Support Ship.")] FastCombatSupportShip = 60, /// <summary> /// Non-Combatant Ship. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Non-Combatant Ship.")] NonCombatantShip = 61, /// <summary> /// Coast Guard Cutters. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Coast Guard Cutters.")] CoastGuardCutters = 62, /// <summary> /// Coast Guard Boats. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Coast Guard Boats.")] CoastGuardBoats = 63 } }
// <copyright file="NativeQuestClient.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS)) namespace GooglePlayGames.Native { using System; using System.Linq; using System.Collections.Generic; using GooglePlayGames.BasicApi; using GooglePlayGames.OurUtils; using GooglePlayGames.BasicApi.Quests; using GooglePlayGames.Native.PInvoke; using Types = GooglePlayGames.Native.Cwrapper.Types; using Status = GooglePlayGames.Native.Cwrapper.CommonErrorStatus; internal class NativeQuestClient : IQuestsClient { private readonly QuestManager mManager; internal NativeQuestClient(QuestManager manager) { this.mManager = Misc.CheckNotNull(manager); } public void Fetch(DataSource source, string questId, Action<ResponseStatus, IQuest> callback) { Misc.CheckNotNull(questId); Misc.CheckNotNull(callback); callback = CallbackUtils.ToOnGameThread(callback); mManager.Fetch(ConversionUtils.AsDataSource(source), questId, response => { var status = ConversionUtils.ConvertResponseStatus(response.ResponseStatus()); if (!response.RequestSucceeded()) { callback(status, null); } else { callback(status, response.Data()); } }); } public void FetchMatchingState(DataSource source, QuestFetchFlags flags, Action<ResponseStatus, List<IQuest>> callback) { Misc.CheckNotNull(callback); callback = CallbackUtils.ToOnGameThread(callback); mManager.FetchList(ConversionUtils.AsDataSource(source), (int)flags, response => { var status = ConversionUtils.ConvertResponseStatus(response.ResponseStatus()); if (!response.RequestSucceeded()) { callback(status, null); } else { callback(status, response.Data().Cast<IQuest>().ToList()); } }); } public void ShowAllQuestsUI(Action<QuestUiResult, IQuest, IQuestMilestone> callback) { Misc.CheckNotNull(callback); callback = CallbackUtils.ToOnGameThread<QuestUiResult, IQuest, IQuestMilestone>(callback); mManager.ShowAllQuestUI(FromQuestUICallback(callback)); } public void ShowSpecificQuestUI(IQuest quest, Action<QuestUiResult, IQuest, IQuestMilestone> callback) { Misc.CheckNotNull(quest); Misc.CheckNotNull(callback); callback = CallbackUtils.ToOnGameThread<QuestUiResult, IQuest, IQuestMilestone>(callback); var convertedQuest = quest as NativeQuest; if (convertedQuest == null) { Logger.e("Encountered quest that was not generated by this IQuestClient"); callback(QuestUiResult.BadInput, null, null); return; } mManager.ShowQuestUI(convertedQuest, FromQuestUICallback(callback)); } private static QuestUiResult UiErrorToQuestUiResult(Status.UIStatus status) { switch (status) { case Status.UIStatus.ERROR_INTERNAL: return QuestUiResult.InternalError; case Status.UIStatus.ERROR_NOT_AUTHORIZED: return QuestUiResult.NotAuthorized; case Status.UIStatus.ERROR_CANCELED: return QuestUiResult.UserCanceled; case Status.UIStatus.ERROR_VERSION_UPDATE_REQUIRED: return QuestUiResult.VersionUpdateRequired; case Status.UIStatus.ERROR_TIMEOUT: return QuestUiResult.Timeout; case Status.UIStatus.ERROR_UI_BUSY: return QuestUiResult.UiBusy; default: Logger.e("Unknown error status: " + status); return QuestUiResult.InternalError; } } private static Action<QuestManager.QuestUIResponse> FromQuestUICallback( Action<QuestUiResult, IQuest, IQuestMilestone> callback) { return response => { if (!response.RequestSucceeded()) { callback(UiErrorToQuestUiResult(response.RequestStatus()), null, null); return; } var acceptedQuest = response.AcceptedQuest(); var milestone = response.MilestoneToClaim(); // If the request succeeded, the user either selected a quest to accept, or a // milestone to claim. Figure out which one this is. if (acceptedQuest != null) { callback(QuestUiResult.UserRequestsQuestAcceptance, acceptedQuest, null); milestone.Dispose(); } else if (milestone != null) { callback(QuestUiResult.UserRequestsMilestoneClaiming, null, response.MilestoneToClaim()); acceptedQuest.Dispose(); } else { Logger.e("Quest UI succeeded without a quest acceptance or milestone claim."); acceptedQuest.Dispose(); milestone.Dispose(); callback(QuestUiResult.InternalError, null, null); } }; } public void Accept(IQuest quest, Action<QuestAcceptStatus, IQuest> callback) { Misc.CheckNotNull(quest); Misc.CheckNotNull(callback); callback = CallbackUtils.ToOnGameThread<QuestAcceptStatus, IQuest>(callback); var convertedQuest = quest as NativeQuest; if (convertedQuest == null) { Logger.e("Encountered quest that was not generated by this IQuestClient"); callback(QuestAcceptStatus.BadInput, null); return; } mManager.Accept(convertedQuest, response => { if (response.RequestSucceeded()) { callback(QuestAcceptStatus.Success, response.AcceptedQuest()); } else { callback(FromAcceptStatus(response.ResponseStatus()), null); } }); } private static QuestAcceptStatus FromAcceptStatus(Status.QuestAcceptStatus status) { switch (status) { case Status.QuestAcceptStatus.ERROR_INTERNAL: return QuestAcceptStatus.InternalError; case Status.QuestAcceptStatus.ERROR_NOT_AUTHORIZED: return QuestAcceptStatus.NotAuthorized; case Status.QuestAcceptStatus.ERROR_QUEST_NOT_STARTED: return QuestAcceptStatus.QuestNotStarted; case Status.QuestAcceptStatus.ERROR_QUEST_NO_LONGER_AVAILABLE: return QuestAcceptStatus.QuestNoLongerAvailable; case Status.QuestAcceptStatus.ERROR_TIMEOUT: return QuestAcceptStatus.Timeout; case Status.QuestAcceptStatus.VALID: return QuestAcceptStatus.Success; default: Logger.e("Encountered unknown status: " + status); return QuestAcceptStatus.InternalError; } } public void ClaimMilestone(IQuestMilestone milestone, Action<QuestClaimMilestoneStatus, IQuest, IQuestMilestone> callback) { Misc.CheckNotNull(milestone); Misc.CheckNotNull(callback); callback = CallbackUtils.ToOnGameThread<QuestClaimMilestoneStatus, IQuest, IQuestMilestone>( callback); var convertedMilestone = milestone as NativeQuestMilestone; if (convertedMilestone == null) { Logger.e("Encountered milestone that was not generated by this IQuestClient"); callback(QuestClaimMilestoneStatus.BadInput, null, null); return; } mManager.ClaimMilestone(convertedMilestone, response => { if (response.RequestSucceeded()) { callback(QuestClaimMilestoneStatus.Success, response.Quest(), response.ClaimedMilestone()); } else { callback(FromClaimStatus(response.ResponseStatus()), null, null); } }); } private static QuestClaimMilestoneStatus FromClaimStatus( Status.QuestClaimMilestoneStatus status) { switch (status) { case Status.QuestClaimMilestoneStatus.VALID: return QuestClaimMilestoneStatus.Success; case Status.QuestClaimMilestoneStatus.ERROR_INTERNAL: return QuestClaimMilestoneStatus.InternalError; case Status.QuestClaimMilestoneStatus.ERROR_MILESTONE_ALREADY_CLAIMED: return QuestClaimMilestoneStatus.MilestoneAlreadyClaimed; case Status.QuestClaimMilestoneStatus.ERROR_MILESTONE_CLAIM_FAILED: return QuestClaimMilestoneStatus.MilestoneClaimFailed; case Status.QuestClaimMilestoneStatus.ERROR_NOT_AUTHORIZED: return QuestClaimMilestoneStatus.NotAuthorized; case Status.QuestClaimMilestoneStatus.ERROR_TIMEOUT: return QuestClaimMilestoneStatus.Timeout; default: Logger.e("Encountered unknown status: " + status); return QuestClaimMilestoneStatus.InternalError; } } } } #endif // #if (UNITY_ANDROID || UNITY_IPHONE)
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Linq; using AutoMapper; using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models; using Microsoft.Rest.Azure; using Newtonsoft.Json; namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery { public static class SiteRecoveryMapperExtension { public static IMappingExpression<TSource, TDestination> ForItems<TSource, TDestination, T>( this IMappingExpression<TSource, TDestination> mapper) where TSource : IEnumerable where TDestination : ICollection<T> { mapper.AfterMap( ( c, s) => { if ((c != null) && (s != null)) { foreach (var t in c) { s.Add(Mapper.Map<T>(t)); } } }); return mapper; } } public class SiteRecoveryAutoMapperProfile : Profile { private static readonly Lazy<bool> initialize; static SiteRecoveryAutoMapperProfile() { initialize = new Lazy<bool>( () => { Mapper.AddProfile<SiteRecoveryAutoMapperProfile>(); return true; }); } public override string ProfileName => "SiteRecoveryAutoMapperProfile"; public static bool Initialize() { return initialize.Value; } protected override void Configure() { var mappingExpression = Mapper .CreateMap<Rest.Azure.AzureOperationResponse, PSSiteRecoveryLongRunningOperation>(); mappingExpression.ForMember( c => c.Location, o => o.MapFrom( r => r.Response.Headers.Contains("Location") ? r.Response.Headers .GetValues("Location") .FirstOrDefault() : "")) .ForMember( c => c.Status, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .Status)) .ForMember( c => c.CorrelationRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-correlation-request-id") ? r.Response .Headers.GetValues("x-ms-correlation-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ClientRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-request-id") ? r.Response.Headers .GetValues("x-ms-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ContentType, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .ContentType)) .ForMember( c => c.RetryAfter, o => o.MapFrom( r => r.Response.Headers.Contains("Retry-After") ? r.Response.Headers .GetValues("Retry-After") .FirstOrDefault() : null)) .ForMember( c => c.Date, o => o.MapFrom( r => r.Response.Headers.Contains("Date") ? r.Response.Headers .GetValues("Date") .FirstOrDefault() : "")) .ForMember( c => c.AsyncOperation, o => o.MapFrom( r => r.Response.Headers.Contains("Azure-AsyncOperation") ? r.Response .Headers.GetValues("Azure-AsyncOperation") .FirstOrDefault() : "")); var mappingExpressionFabric = Mapper .CreateMap<AzureOperationResponse<Fabric>, PSSiteRecoveryLongRunningOperation>(); mappingExpressionFabric.ForMember( c => c.Location, o => o.MapFrom( r => r.Response.Headers.Contains("Location") ? r.Response.Headers .GetValues("Location") .FirstOrDefault() : "")) .ForMember( c => c.Status, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .Status)) .ForMember( c => c.CorrelationRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-correlation-request-id") ? r.Response .Headers.GetValues("x-ms-correlation-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ClientRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-request-id") ? r.Response.Headers .GetValues("x-ms-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ContentType, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .ContentType)) .ForMember( c => c.RetryAfter, o => o.MapFrom( r => r.Response.Headers.Contains("Retry-After") ? r.Response.Headers .GetValues("Retry-After") .FirstOrDefault() : null)) .ForMember( c => c.Date, o => o.MapFrom( r => r.Response.Headers.Contains("Date") ? r.Response.Headers .GetValues("Date") .FirstOrDefault() : "")) .ForMember( c => c.AsyncOperation, o => o.MapFrom( r => r.Response.Headers.Contains("Azure-AsyncOperation") ? r.Response .Headers.GetValues("Azure-AsyncOperation") .FirstOrDefault() : "")); var mappingExpressionPolicy = Mapper .CreateMap<AzureOperationResponse<Policy>, PSSiteRecoveryLongRunningOperation>(); mappingExpressionPolicy.ForMember( c => c.Location, o => o.MapFrom( r => r.Response.Headers.Contains("Location") ? r.Response.Headers .GetValues("Location") .FirstOrDefault() : "")) .ForMember( c => c.Status, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .Status)) .ForMember( c => c.CorrelationRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-correlation-request-id") ? r.Response .Headers.GetValues("x-ms-correlation-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ClientRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-request-id") ? r.Response.Headers .GetValues("x-ms-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ContentType, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .ContentType)) .ForMember( c => c.RetryAfter, o => o.MapFrom( r => r.Response.Headers.Contains("Retry-After") ? r.Response.Headers .GetValues("Retry-After") .FirstOrDefault() : null)) .ForMember( c => c.Date, o => o.MapFrom( r => r.Response.Headers.Contains("Date") ? r.Response.Headers .GetValues("Date") .FirstOrDefault() : "")) .ForMember( c => c.AsyncOperation, o => o.MapFrom( r => r.Response.Headers.Contains("Azure-AsyncOperation") ? r.Response .Headers.GetValues("Azure-AsyncOperation") .FirstOrDefault() : "")); var mappingExpressionProtectionContainer = Mapper .CreateMap<AzureOperationResponse<ProtectionContainer>, PSSiteRecoveryLongRunningOperation>(); mappingExpressionProtectionContainer.ForMember( c => c.Location, o => o.MapFrom( r => r.Response.Headers.Contains("Location") ? r.Response.Headers .GetValues("Location") .FirstOrDefault() : "")) .ForMember( c => c.Status, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .Status)) .ForMember( c => c.CorrelationRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-correlation-request-id") ? r.Response .Headers.GetValues("x-ms-correlation-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ClientRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-request-id") ? r.Response.Headers .GetValues("x-ms-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ContentType, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .ContentType)) .ForMember( c => c.RetryAfter, o => o.MapFrom( r => r.Response.Headers.Contains("Retry-After") ? r.Response.Headers .GetValues("Retry-After") .FirstOrDefault() : null)) .ForMember( c => c.Date, o => o.MapFrom( r => r.Response.Headers.Contains("Date") ? r.Response.Headers .GetValues("Date") .FirstOrDefault() : "")) .ForMember( c => c.AsyncOperation, o => o.MapFrom( r => r.Response.Headers.Contains("Azure-AsyncOperation") ? r.Response .Headers.GetValues("Azure-AsyncOperation") .FirstOrDefault() : "")); var mappingExpressionProtectableItem = Mapper .CreateMap<AzureOperationResponse<ProtectableItem>, PSSiteRecoveryLongRunningOperation>(); mappingExpressionProtectableItem.ForMember( c => c.Location, o => o.MapFrom( r => r.Response.Headers.Contains("Location") ? r.Response.Headers .GetValues("Location") .FirstOrDefault() : "")) .ForMember( c => c.Status, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .Status)) .ForMember( c => c.CorrelationRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-correlation-request-id") ? r.Response .Headers.GetValues("x-ms-correlation-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ClientRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-request-id") ? r.Response.Headers .GetValues("x-ms-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ContentType, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .ContentType)) .ForMember( c => c.RetryAfter, o => o.MapFrom( r => r.Response.Headers.Contains("Retry-After") ? r.Response.Headers .GetValues("Retry-After") .FirstOrDefault() : null)) .ForMember( c => c.Date, o => o.MapFrom( r => r.Response.Headers.Contains("Date") ? r.Response.Headers .GetValues("Date") .FirstOrDefault() : "")) .ForMember( c => c.AsyncOperation, o => o.MapFrom( r => r.Response.Headers.Contains("Azure-AsyncOperation") ? r.Response .Headers.GetValues("Azure-AsyncOperation") .FirstOrDefault() : "")); var mappingExpressionReplicationProtectedItem = Mapper .CreateMap<AzureOperationResponse<ReplicationProtectedItem>, PSSiteRecoveryLongRunningOperation>(); mappingExpressionReplicationProtectedItem.ForMember( c => c.Location, o => o.MapFrom( r => r.Response.Headers.Contains("Location") ? r.Response.Headers .GetValues("Location") .FirstOrDefault() : "")) .ForMember( c => c.Status, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .Status)) .ForMember( c => c.CorrelationRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-correlation-request-id") ? r.Response .Headers.GetValues("x-ms-correlation-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ClientRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-request-id") ? r.Response.Headers .GetValues("x-ms-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ContentType, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .ContentType)) .ForMember( c => c.RetryAfter, o => o.MapFrom( r => r.Response.Headers.Contains("Retry-After") ? r.Response.Headers .GetValues("Retry-After") .FirstOrDefault() : null)) .ForMember( c => c.Date, o => o.MapFrom( r => r.Response.Headers.Contains("Date") ? r.Response.Headers .GetValues("Date") .FirstOrDefault() : "")) .ForMember( c => c.AsyncOperation, o => o.MapFrom( r => r.Response.Headers.Contains("Azure-AsyncOperation") ? r.Response .Headers.GetValues("Azure-AsyncOperation") .FirstOrDefault() : "")); var mappingExpressionRecoveryPlan = Mapper .CreateMap<AzureOperationResponse<RecoveryPlan>, PSSiteRecoveryLongRunningOperation >(); mappingExpressionRecoveryPlan.ForMember( c => c.Location, o => o.MapFrom( r => r.Response.Headers.Contains("Location") ? r.Response.Headers .GetValues("Location") .FirstOrDefault() : "")) .ForMember( c => c.Status, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .Status)) .ForMember( c => c.CorrelationRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-correlation-request-id") ? r.Response .Headers.GetValues("x-ms-correlation-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ClientRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-request-id") ? r.Response.Headers .GetValues("x-ms-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ContentType, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .ContentType)) .ForMember( c => c.RetryAfter, o => o.MapFrom( r => r.Response.Headers.Contains("Retry-After") ? r.Response.Headers .GetValues("Retry-After") .FirstOrDefault() : null)) .ForMember( c => c.Date, o => o.MapFrom( r => r.Response.Headers.Contains("Date") ? r.Response.Headers .GetValues("Date") .FirstOrDefault() : "")) .ForMember( c => c.AsyncOperation, o => o.MapFrom( r => r.Response.Headers.Contains("Azure-AsyncOperation") ? r.Response .Headers.GetValues("Azure-AsyncOperation") .FirstOrDefault() : "")); var mappingExpressionJob = Mapper .CreateMap<AzureOperationResponse<Job>, PSSiteRecoveryLongRunningOperation>(); mappingExpressionJob.ForMember( c => c.Location, o => o.MapFrom( r => r.Response.Headers.Contains("Location") ? r.Response.Headers .GetValues("Location") .FirstOrDefault() : "")) .ForMember( c => c.Status, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .Status)) .ForMember( c => c.CorrelationRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-correlation-request-id") ? r.Response .Headers.GetValues("x-ms-correlation-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ClientRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-request-id") ? r.Response.Headers .GetValues("x-ms-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ContentType, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .ContentType)) .ForMember( c => c.RetryAfter, o => o.MapFrom( r => r.Response.Headers.Contains("Retry-After") ? r.Response.Headers .GetValues("Retry-After") .FirstOrDefault() : null)) .ForMember( c => c.Date, o => o.MapFrom( r => r.Response.Headers.Contains("Date") ? r.Response.Headers .GetValues("Date") .FirstOrDefault() : "")) .ForMember( c => c.AsyncOperation, o => o.MapFrom( r => r.Response.Headers.Contains("Azure-AsyncOperation") ? r.Response .Headers.GetValues("Azure-AsyncOperation") .FirstOrDefault() : "")); var mappingExpressionProtectionContainerMapping = Mapper .CreateMap<AzureOperationResponse<ProtectionContainerMapping>, PSSiteRecoveryLongRunningOperation>(); mappingExpressionProtectionContainerMapping.ForMember( c => c.Location, o => o.MapFrom( r => r.Response.Headers.Contains("Location") ? r.Response.Headers .GetValues("Location") .FirstOrDefault() : "")) .ForMember( c => c.Status, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .Status)) .ForMember( c => c.CorrelationRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-correlation-request-id") ? r.Response .Headers.GetValues("x-ms-correlation-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ClientRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-request-id") ? r.Response.Headers .GetValues("x-ms-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ContentType, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .ContentType)) .ForMember( c => c.RetryAfter, o => o.MapFrom( r => r.Response.Headers.Contains("Retry-After") ? r.Response.Headers .GetValues("Retry-After") .FirstOrDefault() : null)) .ForMember( c => c.Date, o => o.MapFrom( r => r.Response.Headers.Contains("Date") ? r.Response.Headers .GetValues("Date") .FirstOrDefault() : "")) .ForMember( c => c.AsyncOperation, o => o.MapFrom( r => r.Response.Headers.Contains("Azure-AsyncOperation") ? r.Response .Headers.GetValues("Azure-AsyncOperation") .FirstOrDefault() : "")); var mappingExpressionProtectionNetworkMapping = Mapper .CreateMap<AzureOperationResponse<NetworkMapping>, PSSiteRecoveryLongRunningOperation>(); mappingExpressionProtectionNetworkMapping.ForMember( c => c.Location, o => o.MapFrom( r => r.Response.Headers.Contains("Location") ? r.Response.Headers .GetValues("Location") .FirstOrDefault() : "")) .ForMember( c => c.Status, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .Status)) .ForMember( c => c.CorrelationRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-correlation-request-id") ? r.Response .Headers.GetValues("x-ms-correlation-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ClientRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-request-id") ? r.Response.Headers .GetValues("x-ms-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ContentType, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .ContentType)) .ForMember( c => c.RetryAfter, o => o.MapFrom( r => r.Response.Headers.Contains("Retry-After") ? r.Response.Headers .GetValues("Retry-After") .FirstOrDefault() : null)) .ForMember( c => c.Date, o => o.MapFrom( r => r.Response.Headers.Contains("Date") ? r.Response.Headers .GetValues("Date") .FirstOrDefault() : "")) .ForMember( c => c.AsyncOperation, o => o.MapFrom( r => r.Response.Headers.Contains("Azure-AsyncOperation") ? r.Response .Headers.GetValues("Azure-AsyncOperation") .FirstOrDefault() : "")); var mappingExpressionProtectionStorageClassification = Mapper .CreateMap<AzureOperationResponse<StorageClassification>, PSSiteRecoveryLongRunningOperation>(); mappingExpressionProtectionStorageClassification.ForMember( c => c.Location, o => o.MapFrom( r => r.Response.Headers.Contains("Location") ? r.Response.Headers .GetValues("Location") .FirstOrDefault() : "")) .ForMember( c => c.Status, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .Status)) .ForMember( c => c.CorrelationRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-correlation-request-id") ? r.Response .Headers.GetValues("x-ms-correlation-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ClientRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-request-id") ? r.Response.Headers .GetValues("x-ms-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ContentType, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .ContentType)) .ForMember( c => c.RetryAfter, o => o.MapFrom( r => r.Response.Headers.Contains("Retry-After") ? r.Response.Headers .GetValues("Retry-After") .FirstOrDefault() : null)) .ForMember( c => c.Date, o => o.MapFrom( r => r.Response.Headers.Contains("Date") ? r.Response.Headers .GetValues("Date") .FirstOrDefault() : "")) .ForMember( c => c.AsyncOperation, o => o.MapFrom( r => r.Response.Headers.Contains("Azure-AsyncOperation") ? r.Response .Headers.GetValues("Azure-AsyncOperation") .FirstOrDefault() : "")); var mappingExpressionProtectionStorageClassificationMapping = Mapper .CreateMap<AzureOperationResponse<StorageClassificationMapping>, PSSiteRecoveryLongRunningOperation>(); mappingExpressionProtectionStorageClassificationMapping.ForMember( c => c.Location, o => o.MapFrom( r => r.Response.Headers.Contains("Location") ? r.Response.Headers .GetValues("Location") .FirstOrDefault() : "")) .ForMember( c => c.Status, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .Status)) .ForMember( c => c.CorrelationRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-correlation-request-id") ? r.Response .Headers.GetValues("x-ms-correlation-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ClientRequestId, o => o.MapFrom( r => r.Response.Headers.Contains("x-ms-request-id") ? r.Response.Headers .GetValues("x-ms-request-id") .FirstOrDefault() : "")) .ForMember( c => c.ContentType, o => o.MapFrom( r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>( r.Response.Content.ReadAsStringAsync() .Result) .ContentType)) .ForMember( c => c.RetryAfter, o => o.MapFrom( r => r.Response.Headers.Contains("Retry-After") ? r.Response.Headers .GetValues("Retry-After") .FirstOrDefault() : null)) .ForMember( c => c.Date, o => o.MapFrom( r => r.Response.Headers.Contains("Date") ? r.Response.Headers .GetValues("Date") .FirstOrDefault() : "")) .ForMember( c => c.AsyncOperation, o => o.MapFrom( r => r.Response.Headers.Contains("Azure-AsyncOperation") ? r.Response .Headers.GetValues("Azure-AsyncOperation") .FirstOrDefault() : "")); } } }
/*************************************************************************** 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.CodeAnalysis; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.Project { #region structures [StructLayoutAttribute(LayoutKind.Sequential)] internal struct _DROPFILES { public Int32 pFiles; public Int32 X; public Int32 Y; public Int32 fNC; public Int32 fWide; } #endregion #region enums /// <summary> /// The type of build performed. /// </summary> public enum BuildKind { Sync, Async } /// <summary> /// Defines possible types of output that can produced by a language project /// </summary> [PropertyPageTypeConverterAttribute(typeof(OutputTypeConverter))] public enum OutputType { /// <summary> /// The output type is a class library. /// </summary> Library, /// <summary> /// The output type is a windows executable. /// </summary> WinExe, /// <summary> /// The output type is an executable. /// </summary> Exe } /// <summary> /// Debug values used by DebugModeConverter. /// </summary> [PropertyPageTypeConverterAttribute(typeof(DebugModeConverter))] public enum DebugMode { Project, Program, [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URL")] URL } /// <summary> /// An enumeration that describes the type of action to be taken by the build. /// </summary> [PropertyPageTypeConverterAttribute(typeof(BuildActionConverter))] public enum BuildAction { None, Compile, Content, EmbeddedResource } /// <summary> /// Defines the currect state of a property page. /// </summary> [Flags] public enum PropPageStatus { Dirty = 0x1, Validate = 0x2, Clean = 0x4 } [Flags] [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")] public enum ModuleKindFlags { ConsoleApplication, WindowsApplication, DynamicallyLinkedLibrary, ManifestResourceFile, UnmanagedDynamicallyLinkedLibrary } /// <summary> /// Defines the status of the command being queried /// </summary> [Flags] [SuppressMessage("Microsoft.Naming", "CA1714:FlagsEnumsShouldHavePluralNames")] [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")] public enum QueryStatusResult { /// <summary> /// The command is not supported. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "NOTSUPPORTED")] NOTSUPPORTED = 0, /// <summary> /// The command is supported /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SUPPORTED")] SUPPORTED = 1, /// <summary> /// The command is enabled /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ENABLED")] ENABLED = 2, /// <summary> /// The command is toggled on /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "LATCHED")] LATCHED = 4, /// <summary> /// The command is toggled off (the opposite of LATCHED). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "NINCHED")] NINCHED = 8, /// <summary> /// The command is invisible. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "INVISIBLE")] INVISIBLE = 16 } /// <summary> /// Defines the type of item to be added to the hierarchy. /// </summary> public enum HierarchyAddType { AddNewItem, AddExistingItem } /// <summary> /// Defines the component from which a command was issued. /// </summary> public enum CommandOrigin { [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ui")] UiHierarchy, OleCommandTarget } /// <summary> /// Defines the current status of the build process. /// </summary> public enum MSBuildResult { /// <summary> /// The build is currently suspended. /// </summary> Suspended, /// <summary> /// The build has been restarted. /// </summary> Resumed, /// <summary> /// The build failed. /// </summary> Failed, /// <summary> /// The build was successful. /// </summary> Successful, } /// <summary> /// Defines the type of action to be taken in showing the window frame. /// </summary> public enum WindowFrameShowAction { DoNotShow, Show, ShowNoActivate, Hide, } /// <summary> /// Defines drop types /// </summary> internal enum DropDataType { None, Shell, VsStg, VsRef } /// <summary> /// Used by the hierarchy node to decide which element to redraw. /// </summary> [Flags] [SuppressMessage("Microsoft.Naming", "CA1714:FlagsEnumsShouldHavePluralNames")] public enum UIHierarchyElement { None = 0, /// <summary> /// This will be translated to VSHPROPID_IconIndex /// </summary> Icon = 1, /// <summary> /// This will be translated to VSHPROPID_StateIconIndex /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Scc")] SccState = 2, /// <summary> /// This will be translated to VSHPROPID_Caption /// </summary> Caption = 4 } /// <summary> /// Defines the global propeties used by the msbuild project. /// </summary> public enum GlobalProperty { /// <summary> /// Property specifying that we are building inside VS. /// </summary> BuildingInsideVisualStudio, /// <summary> /// The VS installation directory. This is the same as the $(DevEnvDir) macro. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Env")] DevEnvDir, /// <summary> /// The name of the solution the project is created. This is the same as the $(SolutionName) macro. /// </summary> SolutionName, /// <summary> /// The file name of the solution. This is the same as $(SolutionFileName) macro. /// </summary> SolutionFileName, /// <summary> /// The full path of the solution. This is the same as the $(SolutionPath) macro. /// </summary> SolutionPath, /// <summary> /// The directory of the solution. This is the same as the $(SolutionDir) macro. /// </summary> SolutionDir, /// <summary> /// The extension of teh directory. This is the same as the $(SolutionExt) macro. /// </summary> SolutionExt, /// <summary> /// The fxcop installation directory. /// </summary> FxCopDir, /// <summary> /// The ResolvedNonMSBuildProjectOutputs msbuild property /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "VSIDE")] VSIDEResolvedNonMSBuildProjectOutputs, /// <summary> /// The Configuartion property. /// </summary> Configuration, /// <summary> /// The platform property. /// </summary> Platform, /// <summary> /// The RunCodeAnalysisOnce property /// </summary> RunCodeAnalysisOnce, /// <summary> /// The VisualStudioStyleErrors property /// </summary> VisualStudioStyleErrors, } #endregion public class AfterProjectFileOpenedEventArgs : EventArgs { #region fields private bool added; #endregion #region properties /// <summary> /// True if the project is added to the solution after the solution is opened. false if the project is added to the solution while the solution is being opened. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal bool Added { get { return this.added; } } #endregion #region ctor internal AfterProjectFileOpenedEventArgs(bool added) { this.added = added; } #endregion } public class BeforeProjectFileClosedEventArgs : EventArgs { #region fields private bool removed; #endregion #region properties /// <summary> /// true if the project was removed from the solution before the solution was closed. false if the project was removed from the solution while the solution was being closed. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal bool Removed { get { return this.removed; } } #endregion #region ctor internal BeforeProjectFileClosedEventArgs(bool removed) { this.removed = removed; } #endregion } /// <summary> /// This class is used for the events raised by a HierarchyNode object. /// </summary> internal class HierarchyNodeEventArgs : EventArgs { private HierarchyNode child; internal HierarchyNodeEventArgs(HierarchyNode child) { this.child = child; } public HierarchyNode Child { get { return this.child; } } } /// <summary> /// Event args class for triggering file change event arguments. /// </summary> internal class FileChangedOnDiskEventArgs : EventArgs { #region Private fields /// <summary> /// File name that was changed on disk. /// </summary> private string fileName; /// <summary> /// The item ide of the file that has changed. /// </summary> private uint itemID; /// <summary> /// The reason the file has changed on disk. /// </summary> private _VSFILECHANGEFLAGS fileChangeFlag; #endregion /// <summary> /// Constructs a new event args. /// </summary> /// <param name="fileName">File name that was changed on disk.</param> /// <param name="id">The item id of the file that was changed on disk.</param> internal FileChangedOnDiskEventArgs(string fileName, uint id, _VSFILECHANGEFLAGS flag) { this.fileName = fileName; this.itemID = id; this.fileChangeFlag = flag; } /// <summary> /// Gets the file name that was changed on disk. /// </summary> /// <value>The file that was changed on disk.</value> internal string FileName { get { return this.fileName; } } /// <summary> /// Gets item id of the file that has changed /// </summary> /// <value>The file that was changed on disk.</value> internal uint ItemID { get { return this.itemID; } } /// <summary> /// The reason while the file has chnaged on disk. /// </summary> /// <value>The reason while the file has chnaged on disk.</value> internal _VSFILECHANGEFLAGS FileChangeFlag { get { return this.fileChangeFlag; } } } /// <summary> /// Defines the event args for the active configuration chnage event. /// </summary> public class ActiveConfigurationChangedEventArgs : EventArgs { #region Private fields /// <summary> /// The hierarchy whose configuration has changed /// </summary> private IVsHierarchy hierarchy; #endregion /// <summary> /// Constructs a new event args. /// </summary> /// <param name="fileName">The hierarchy that has changed its configuration.</param> internal ActiveConfigurationChangedEventArgs(IVsHierarchy hierarchy) { this.hierarchy = hierarchy; } /// <summary> /// The hierarchy whose configuration has changed /// </summary> internal IVsHierarchy Hierarchy { get { return this.hierarchy; } } } /// <summary> /// Argument of the event raised when a project property is changed. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] public class ProjectPropertyChangedArgs : EventArgs { private string propertyName; private string oldValue; private string newValue; internal ProjectPropertyChangedArgs(string propertyName, string oldValue, string newValue) { this.propertyName = propertyName; this.oldValue = oldValue; this.newValue = newValue; } public string NewValue { get { return newValue; } } public string OldValue { get { return oldValue; } } public string PropertyName { get { return propertyName; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Formatters.Tests; using Xunit; namespace System.Tests { public static class TestExtensionMethod { public static DelegateTests.TestStruct TestFunc(this DelegateTests.TestClass testparam) { return testparam.structField; } public static void IncrementX(this DelegateTests.TestSerializableClass t) { t.x++; } } public static unsafe class DelegateTests { public struct TestStruct { public object o1; public object o2; } public class TestClass { public TestStruct structField; } [Serializable] public class TestSerializableClass { public int x = 1; } private static void EmptyFunc() { } public delegate TestStruct StructReturningDelegate(); [Fact] public static void ClosedStaticDelegate() { TestClass foo = new TestClass(); foo.structField.o1 = new object(); foo.structField.o2 = new object(); StructReturningDelegate testDelegate = foo.TestFunc; TestStruct returnedStruct = testDelegate(); Assert.Same(foo.structField.o1, returnedStruct.o1); Assert.Same(foo.structField.o2, returnedStruct.o2); } public class A { } public class B : A { } public delegate A DynamicInvokeDelegate(A nonRefParam1, B nonRefParam2, ref A refParam, out B outParam); public static A DynamicInvokeTestFunction(A nonRefParam1, B nonRefParam2, ref A refParam, out B outParam) { outParam = (B)refParam; refParam = nonRefParam2; return nonRefParam1; } [Fact] public static void DynamicInvoke() { A a1 = new A(); A a2 = new A(); B b1 = new B(); B b2 = new B(); DynamicInvokeDelegate testDelegate = DynamicInvokeTestFunction; // Check that the delegate behaves as expected A refParam = b2; B outParam = null; A returnValue = testDelegate(a1, b1, ref refParam, out outParam); Assert.Same(returnValue, a1); Assert.Same(refParam, b1); Assert.Same(outParam, b2); // Check dynamic invoke behavior object[] parameters = new object[] { a1, b1, b2, null }; object retVal = testDelegate.DynamicInvoke(parameters); Assert.Same(retVal, a1); Assert.Same(parameters[2], b1); Assert.Same(parameters[3], b2); // Check invoke on a delegate that takes no parameters. Action emptyDelegate = EmptyFunc; emptyDelegate.DynamicInvoke(new object[] { }); emptyDelegate.DynamicInvoke(null); } [Fact] public static void DynamicInvoke_MissingTypeForDefaultParameter_Succeeds() { // Passing Type.Missing with default. Delegate d = new IntIntDelegateWithDefault(IntIntMethod); d.DynamicInvoke(7, Type.Missing); } [Fact] public static void DynamicInvoke_MissingTypeForNonDefaultParameter_ThrowsArgumentException() { Delegate d = new IntIntDelegate(IntIntMethod); AssertExtensions.Throws<ArgumentException>("parameters", () => d.DynamicInvoke(7, Type.Missing)); } [Theory] [InlineData(new object[] { 7 }, new object[] { 8 })] [InlineData(new object[] { null }, new object[] { 1 })] public static void DynamicInvoke_RefValueTypeParameter(object[] args, object[] expected) { Delegate d = new RefIntDelegate(RefIntMethod); d.DynamicInvoke(args); Assert.Equal(expected, args); } [Fact] public static void DynamicInvoke_NullRefValueTypeParameter_ReturnsValueTypeDefault() { Delegate d = new RefValueTypeDelegate(RefValueTypeMethod); object[] args = new object[] { null }; d.DynamicInvoke(args); MyStruct s = (MyStruct)(args[0]); Assert.Equal(s.X, 7); Assert.Equal(s.Y, 8); } [Fact] public static void DynamicInvoke_TypeDoesntExactlyMatchRefValueType_ThrowsArgumentException() { Delegate d = new RefIntDelegate(RefIntMethod); AssertExtensions.Throws<ArgumentException>(null, () => d.DynamicInvoke((uint)7)); AssertExtensions.Throws<ArgumentException>(null, () => d.DynamicInvoke(IntEnum.One)); } [Theory] [InlineData(7, (short)7)] // uint -> int [InlineData(7, IntEnum.Seven)] // Enum (int) -> int [InlineData(7, ShortEnum.Seven)] // Enum (short) -> int public static void DynamicInvoke_ValuePreservingPrimitiveWidening_Succeeds(object o1, object o2) { Delegate d = new IntIntDelegate(IntIntMethod); d.DynamicInvoke(o1, o2); } [Theory] [InlineData(IntEnum.Seven, 7)] [InlineData(IntEnum.Seven, (short)7)] public static void DynamicInvoke_ValuePreservingWideningToEnum_Succeeds(object o1, object o2) { Delegate d = new EnumEnumDelegate(EnumEnumMethod); d.DynamicInvoke(o1, o2); } [Fact] public static void DynamicInvoke_SizePreservingNonVauePreservingConversion_ThrowsArgumentException() { Delegate d = new IntIntDelegate(IntIntMethod); AssertExtensions.Throws<ArgumentException>(null, () => d.DynamicInvoke(7, (uint)7)); AssertExtensions.Throws<ArgumentException>(null, () => d.DynamicInvoke(7, U4.Seven)); } [Fact] public static void DynamicInvoke_NullValueType_Succeeds() { Delegate d = new ValueTypeDelegate(ValueTypeMethod); d.DynamicInvoke(new object[] { null }); } [Fact] public static void DynamicInvoke_ConvertMatchingTToNullable_Succeeds() { Delegate d = new NullableDelegate(NullableMethod); d.DynamicInvoke(7); } [Fact] public static void DynamicInvoke_ConvertNonMatchingTToNullable_ThrowsArgumentException() { Delegate d = new NullableDelegate(NullableMethod); AssertExtensions.Throws<ArgumentException>(null, () => d.DynamicInvoke((short)7)); AssertExtensions.Throws<ArgumentException>(null, () => d.DynamicInvoke(IntEnum.Seven)); } [Fact] public static void DynamicInvoke_DefaultParameter_AllPrimitiveParametersWithMissingValues() { object[] parameters = new object[13]; for (int i = 0; i < parameters.Length; i++) { parameters[i] = Type.Missing; } Assert.Equal( "True, test, c, 2, -1, -3, 4, -5, 6, -7, 8, 9.1, 11.12", (string)(new AllPrimitivesWithDefaultValues(AllPrimitivesMethod)).DynamicInvoke(parameters)); } [Fact] public static void DynamicInvoke_DefaultParameter_AllPrimitiveParametersWithAllExplicitValues() { Assert.Equal( "False, value, d, 102, -101, -103, 104, -105, 106, -107, 108, 109.1, 111.12", (string)(new AllPrimitivesWithDefaultValues(AllPrimitivesMethod)).DynamicInvoke( new object[13] { false, "value", 'd', (byte)102, (sbyte)-101, (short)-103, (ushort)104, (int)-105, (uint)106, (long)-107, (ulong)108, (float)109.1, (double)111.12 } )); } [Fact] public static void DynamicInvoke_DefaultParameter_AllPrimitiveParametersWithSomeExplicitValues() { Assert.Equal( "False, test, d, 2, -101, -3, 104, -5, 106, -7, 108, 9.1, 111.12", (string)(new AllPrimitivesWithDefaultValues(AllPrimitivesMethod)).DynamicInvoke( new object[13] { false, Type.Missing, 'd', Type.Missing, (sbyte)-101, Type.Missing, (ushort)104, Type.Missing, (uint)106, Type.Missing, (ulong)108, Type.Missing, (double)111.12 } )); } [Fact] public static void DynamicInvoke_DefaultParameter_StringParameterWithMissingValue() { Assert.Equal ("test", (string)(new StringWithDefaultValue(StringMethod)).DynamicInvoke(new object[] { Type.Missing })); } [Fact] public static void DynamicInvoke_DefaultParameter_StringParameterWithExplicitValue() { Assert.Equal( "value", (string)(new StringWithDefaultValue(StringMethod)).DynamicInvoke(new object[] { "value" })); } [Fact] public static void DynamicInvoke_DefaultParameter_ReferenceTypeParameterWithMissingValue() { Assert.Null((new ReferenceWithDefaultValue(ReferenceMethod)).DynamicInvoke(new object[] { Type.Missing })); } [Fact] public static void DynamicInvoke_DefaultParameter_ReferenceTypeParameterWithExplicitValue() { CustomReferenceType referenceInstance = new CustomReferenceType(); Assert.Same( referenceInstance, (new ReferenceWithDefaultValue(ReferenceMethod)).DynamicInvoke(new object[] { referenceInstance })); } [Fact] public static void DynamicInvoke_DefaultParameter_ValueTypeParameterWithMissingValue() { Assert.Equal( 0, ((CustomValueType)(new ValueTypeWithDefaultValue(ValueTypeMethod)).DynamicInvoke(new object[] { Type.Missing })).Id); } [Fact] public static void DynamicInvoke_DefaultParameter_ValueTypeParameterWithExplicitValue() { Assert.Equal( 1, ((CustomValueType)(new ValueTypeWithDefaultValue(ValueTypeMethod)).DynamicInvoke(new object[] { new CustomValueType { Id = 1 } })).Id); } [Fact] public static void DynamicInvoke_DefaultParameter_DateTimeParameterWithMissingValue() { Assert.Equal( new DateTime(42), (DateTime)(new DateTimeWithDefaultValueAttribute(DateTimeMethod)).DynamicInvoke(new object[] { Type.Missing })); } [Fact] public static void DynamicInvoke_DefaultParameter_DateTimeParameterWithExplicitValue() { Assert.Equal( new DateTime(43), (DateTime)(new DateTimeWithDefaultValueAttribute(DateTimeMethod)).DynamicInvoke(new object[] { new DateTime(43) })); } [Fact] public static void DynamicInvoke_DefaultParameter_DecimalParameterWithAttributeAndMissingValue() { Assert.Equal( new decimal(4, 3, 2, true, 1), (decimal)(new DecimalWithDefaultValueAttribute(DecimalMethod)).DynamicInvoke(new object[] { Type.Missing })); } [Fact] public static void DynamicInvoke_DefaultParameter_DecimalParameterWithAttributeAndExplicitValue() { Assert.Equal( new decimal(12, 13, 14, true, 1), (decimal)(new DecimalWithDefaultValueAttribute(DecimalMethod)).DynamicInvoke(new object[] { new decimal(12, 13, 14, true, 1) })); } [Fact] public static void DynamicInvoke_DefaultParameter_DecimalParameterWithMissingValue() { Assert.Equal( 3.14m, (decimal)(new DecimalWithDefaultValue(DecimalMethod)).DynamicInvoke(new object[] { Type.Missing })); } [Fact] public static void DynamicInvoke_DefaultParameter_DecimalParameterWithExplicitValue() { Assert.Equal( 103.14m, (decimal)(new DecimalWithDefaultValue(DecimalMethod)).DynamicInvoke(new object[] { 103.14m })); } [Fact] public static void DynamicInvoke_DefaultParameter_NullableIntWithMissingValue() { Assert.Null((int?)(new NullableIntWithDefaultValue(NullableIntMethod)).DynamicInvoke(new object[] { Type.Missing })); } [Fact] public static void DynamicInvoke_DefaultParameter_NullableIntWithExplicitValue() { Assert.Equal( (int?)42, (int?)(new NullableIntWithDefaultValue(NullableIntMethod)).DynamicInvoke(new object[] { (int?)42 })); } [Fact] public static void DynamicInvoke_DefaultParameter_EnumParameterWithMissingValue() { Assert.Equal( IntEnum.Seven, (IntEnum)(new EnumWithDefaultValue(EnumMethod)).DynamicInvoke(new object[] { Type.Missing })); } [Fact] public static void DynamicInvoke_OptionalParameter_WithExplicitValue() { Assert.Equal( "value", (new OptionalObjectParameter(ObjectMethod)).DynamicInvoke(new object[] { "value" })); } [Fact] public static void DynamicInvoke_OptionalParameter_WithMissingValue() { Assert.Equal( Type.Missing, (new OptionalObjectParameter(ObjectMethod)).DynamicInvoke(new object[] { Type.Missing })); } [Fact] public static void DynamicInvoke_OptionalParameterUnassingableFromMissing_WithMissingValue() { AssertExtensions.Throws<ArgumentException>(null, () => (new OptionalStringParameter(StringMethod)).DynamicInvoke(new object[] { Type.Missing })); } [Fact] public static void DynamicInvoke_ParameterSpecification_ArrayOfStrings() { Assert.Equal( "value", (new StringParameter(StringMethod)).DynamicInvoke(new string[] { "value" })); } [Fact] public static void DynamicInvoke_ParameterSpecification_ArrayOfMissing() { Assert.Same( Missing.Value, (new OptionalObjectParameter(ObjectMethod)).DynamicInvoke(new Missing[] { Missing.Value })); } private static void IntIntMethod(int expected, int actual) { Assert.Equal(expected, actual); } private delegate void IntIntDelegate(int expected, int actual); private delegate void IntIntDelegateWithDefault(int expected, int actual = 7); private static void RefIntMethod(ref int i) => i++; private delegate void RefIntDelegate(ref int i); private struct MyStruct { public int X; public int Y; } private static void RefValueTypeMethod(ref MyStruct s) { s.X += 7; s.Y += 8; } private delegate void RefValueTypeDelegate(ref MyStruct s); private static void EnumEnumMethod(IntEnum expected, IntEnum actual) { Assert.Equal(expected, actual); } private delegate void EnumEnumDelegate(IntEnum expected, IntEnum actual); private static void ValueTypeMethod(MyStruct s) { Assert.Equal(s.X, 0); Assert.Equal(s.Y, 0); } private delegate void ValueTypeDelegate(MyStruct s); private static void NullableMethod(int? n) { Assert.True(n.HasValue); Assert.Equal(n.Value, 7); } private delegate void NullableDelegate(int? s); public enum ShortEnum : short { One = 1, Seven = 7, } public enum IntEnum : int { One = 1, Seven = 7, } public enum U4 : uint { One = 1, Seven = 7, } private delegate string AllPrimitivesWithDefaultValues( bool boolean = true, string str = "test", char character = 'c', byte unsignedbyte = 2, sbyte signedbyte = -1, short int16 = -3, ushort uint16 = 4, int int32 = -5, uint uint32 = 6, long int64 = -7, ulong uint64 = 8, float single = (float)9.1, double dbl = 11.12); private static string AllPrimitivesMethod( bool boolean, string str, char character, byte unsignedbyte, sbyte signedbyte, short int16, ushort uint16, int int32, uint uint32, long int64, ulong uint64, float single, double dbl) { return FormattableString.Invariant($"{boolean}, {str}, {character}, {unsignedbyte}, {signedbyte}, {int16}, {uint16}, {int32}, {uint32}, {int64}, {uint64}, {single}, {dbl}"); } private delegate string StringParameter(string parameter); private delegate string StringWithDefaultValue(string parameter = "test"); private static string StringMethod(string parameter) { return parameter; } private class CustomReferenceType { }; private delegate CustomReferenceType ReferenceWithDefaultValue(CustomReferenceType parameter = null); private static CustomReferenceType ReferenceMethod(CustomReferenceType parameter) { return parameter; } private struct CustomValueType { public int Id; }; private delegate CustomValueType ValueTypeWithDefaultValue(CustomValueType parameter = default(CustomValueType)); private static CustomValueType ValueTypeMethod(CustomValueType parameter) { return parameter; } private delegate DateTime DateTimeWithDefaultValueAttribute([DateTimeConstant(42)] DateTime parameter); private static DateTime DateTimeMethod(DateTime parameter) { return parameter; } private delegate decimal DecimalWithDefaultValueAttribute([DecimalConstant(1, 1, 2, 3, 4)] decimal parameter); private delegate decimal DecimalWithDefaultValue(decimal parameter = 3.14m); private static decimal DecimalMethod(decimal parameter) { return parameter; } private delegate int? NullableIntWithDefaultValue(int? parameter = null); private static int? NullableIntMethod(int? parameter) { return parameter; } private delegate IntEnum EnumWithDefaultValue(IntEnum parameter = IntEnum.Seven); private static IntEnum EnumMethod(IntEnum parameter = IntEnum.Seven) { return parameter; } private delegate object OptionalObjectParameter([Optional] object parameter); private static object ObjectMethod(object parameter) { return parameter; } private delegate string OptionalStringParameter([Optional] string parameter); } public static class CreateDelegateTests { #region Tests [Fact] public static void CreateDelegate1_Method_Static() { C c = new C(); MethodInfo mi = typeof(C).GetMethod("S"); Delegate dg = Delegate.CreateDelegate(typeof(D), mi); Assert.Equal(mi, dg.Method); Assert.Null(dg.Target); D d = (D)dg; d(c); } [Fact] public static void CreateDelegate1_Method_Null() { ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("method", () => Delegate.CreateDelegate(typeof(D), (MethodInfo)null)); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate1_Type_Null() { MethodInfo mi = typeof(C).GetMethod("S"); ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("type", () => Delegate.CreateDelegate((Type)null, mi)); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate2() { E e; e = (E)Delegate.CreateDelegate(typeof(E), new B(), "Execute"); Assert.NotNull(e); Assert.Equal(4, e(new C())); e = (E)Delegate.CreateDelegate(typeof(E), new C(), "Execute"); Assert.NotNull(e); Assert.Equal(4, e(new C())); e = (E)Delegate.CreateDelegate(typeof(E), new C(), "DoExecute"); Assert.NotNull(e); Assert.Equal(102, e(new C())); } [Fact] public static void CreateDelegate2_Method_ArgumentsMismatch() { ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "StartExecute")); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate2_Method_CaseMismatch() { ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "ExecutE")); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate2_Method_DoesNotExist() { ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "DoesNotExist")); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate2_Method_Null() { C c = new C(); ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("method", () => Delegate.CreateDelegate(typeof(D), c, (string)null)); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate2_Method_ReturnTypeMismatch() { ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "DoExecute")); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate2_Method_Static() { ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "Run")); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate2_Target_Null() { ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("target", () => Delegate.CreateDelegate(typeof(D), null, "N")); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate2_Target_GenericTypeParameter() { Type theT = typeof(DummyGenericClassForDelegateTests<>).GetTypeInfo().GenericTypeParameters[0]; Type delegateType = typeof(Func<object, object, bool>); AssertExtensions.Throws<ArgumentException>("target", () => Delegate.CreateDelegate(delegateType, theT, "ReferenceEquals")); } [Fact] public static void CreateDelegate2_Type_Null() { C c = new C(); ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("type", () => Delegate.CreateDelegate((Type)null, c, "N")); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate3() { E e; // matching static method e = (E)Delegate.CreateDelegate(typeof(E), typeof(B), "Run"); Assert.NotNull(e); Assert.Equal(5, e(new C())); // matching static method e = (E)Delegate.CreateDelegate(typeof(E), typeof(C), "Run"); Assert.NotNull(e); Assert.Equal(5, e(new C())); // matching static method e = (E)Delegate.CreateDelegate(typeof(E), typeof(C), "DoRun"); Assert.NotNull(e); Assert.Equal(107, e(new C())); } [Fact] public static void CreateDelegate3_Method_ArgumentsMismatch() { ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), typeof(B), "StartRun")); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate3_Method_CaseMismatch() { ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), typeof(B), "RuN")); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate3_Method_DoesNotExist() { ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), typeof(B), "DoesNotExist")); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate3_Method_Instance() { ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), typeof(B), "Execute")); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate3_Method_Null() { ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("method", () => Delegate.CreateDelegate(typeof(D), typeof(C), (string)null)); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate3_Method_ReturnTypeMismatch() { ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), typeof(B), "DoRun")); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate3_Target_Null() { ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("target", () => Delegate.CreateDelegate(typeof(D), (Type)null, "S")); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate3_Type_Null() { ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("type", () => Delegate.CreateDelegate((Type)null, typeof(C), "S")); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate4() { E e; B b = new B(); // instance method, exact case, ignore case e = (E)Delegate.CreateDelegate(typeof(E), b, "Execute", true); Assert.NotNull(e); Assert.Equal(4, e(new C())); // instance method, exact case, do not ignore case e = (E)Delegate.CreateDelegate(typeof(E), b, "Execute", false); Assert.NotNull(e); Assert.Equal(4, e(new C())); // instance method, case mismatch, ignore case e = (E)Delegate.CreateDelegate(typeof(E), b, "ExecutE", true); Assert.NotNull(e); Assert.Equal(4, e(new C())); C c = new C(); // instance method, exact case, ignore case e = (E)Delegate.CreateDelegate(typeof(E), c, "Execute", true); Assert.NotNull(e); Assert.Equal(4, e(new C())); // instance method, exact case, ignore case e = (E)Delegate.CreateDelegate(typeof(E), c, "DoExecute", true); Assert.NotNull(e); Assert.Equal(102, e(new C())); // instance method, exact case, do not ignore case e = (E)Delegate.CreateDelegate(typeof(E), c, "Execute", false); Assert.NotNull(e); Assert.Equal(4, e(new C())); // instance method, case mismatch, ignore case e = (E)Delegate.CreateDelegate(typeof(E), c, "ExecutE", true); Assert.NotNull(e); Assert.Equal(4, e(new C())); } [Fact] public static void CreateDelegate4_Method_ArgumentsMismatch() { ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "StartExecute", false)); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate4_Method_CaseMismatch() { // instance method, case mismatch, do not igore case ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "ExecutE", false)); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate4_Method_DoesNotExist() { ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "DoesNotExist", false)); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate4_Method_Null() { ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("method", () => Delegate.CreateDelegate(typeof(D), new C(), (string)null, true)); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate4_Method_ReturnTypeMismatch() { ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "DoExecute", false)); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate4_Method_Static() { ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "Run", true)); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate4_Target_Null() { ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("target", () => Delegate.CreateDelegate(typeof(D), null, "N", true)); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate4_Type_Null() { C c = new C(); ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("type", () => Delegate.CreateDelegate((Type)null, c, "N", true)); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate9() { E e; // do not ignore case, do not throw bind failure e = (E)Delegate.CreateDelegate(typeof(E), new B(), "Execute", false, false); Assert.NotNull(e); Assert.Equal(4, e(new C())); // do not ignore case, throw bind failure e = (E)Delegate.CreateDelegate(typeof(E), new B(), "Execute", false, true); Assert.NotNull(e); Assert.Equal(4, e(new C())); // ignore case, do not throw bind failure e = (E)Delegate.CreateDelegate(typeof(E), new B(), "Execute", true, false); Assert.NotNull(e); Assert.Equal(4, e(new C())); // ignore case, throw bind failure e = (E)Delegate.CreateDelegate(typeof(E), new B(), "Execute", true, true); Assert.NotNull(e); Assert.Equal(4, e(new C())); // do not ignore case, do not throw bind failure e = (E)Delegate.CreateDelegate(typeof(E), new C(), "Execute", false, false); Assert.NotNull(e); Assert.Equal(4, e(new C())); // do not ignore case, throw bind failure e = (E)Delegate.CreateDelegate(typeof(E), new C(), "Execute", false, true); Assert.NotNull(e); Assert.Equal(4, e(new C())); // ignore case, do not throw bind failure e = (E)Delegate.CreateDelegate(typeof(E), new C(), "Execute", true, false); Assert.NotNull(e); Assert.Equal(4, e(new C())); // ignore case, throw bind failure e = (E)Delegate.CreateDelegate(typeof(E), new C(), "Execute", true, true); Assert.NotNull(e); Assert.Equal(4, e(new C())); // do not ignore case, do not throw bind failure e = (E)Delegate.CreateDelegate(typeof(E), new C(), "DoExecute", false, false); Assert.NotNull(e); Assert.Equal(102, e(new C())); // do not ignore case, throw bind failure e = (E)Delegate.CreateDelegate(typeof(E), new C(), "DoExecute", false, true); Assert.NotNull(e); Assert.Equal(102, e(new C())); // ignore case, do not throw bind failure e = (E)Delegate.CreateDelegate(typeof(E), new C(), "DoExecute", true, false); Assert.NotNull(e); Assert.Equal(102, e(new C())); // ignore case, throw bind failure e = (E)Delegate.CreateDelegate(typeof(E), new C(), "DoExecute", true, true); Assert.NotNull(e); Assert.Equal(102, e(new C())); } [Fact] public static void CreateDelegate9_Method_ArgumentsMismatch() { // throw bind failure ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "StartExecute", false, true)); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); // do not throw on bind failure E e = (E)Delegate.CreateDelegate(typeof(E), new B(), "StartExecute", false, false); Assert.Null(e); } [Fact] public static void CreateDelegate9_Method_CaseMismatch() { E e; // do not ignore case, throw bind failure ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "ExecutE", false, true)); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); // do not ignore case, do not throw bind failure e = (E)Delegate.CreateDelegate(typeof(E), new B(), "ExecutE", false, false); Assert.Null(e); // ignore case, throw bind failure e = (E)Delegate.CreateDelegate(typeof(E), new B(), "ExecutE", true, true); Assert.NotNull(e); Assert.Equal(4, e(new C())); // ignore case, do not throw bind failure e = (E)Delegate.CreateDelegate(typeof(E), new B(), "ExecutE", true, false); Assert.NotNull(e); Assert.Equal(4, e(new C())); } [Fact] public static void CreateDelegate9_Method_DoesNotExist() { // throw bind failure ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "DoesNotExist", false, true)); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); // do not throw on bind failure E e = (E)Delegate.CreateDelegate(typeof(E), new B(), "DoesNotExist", false, false); Assert.Null(e); } [Fact] public static void CreateDelegate9_Method_Null() { ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("method", () => Delegate.CreateDelegate(typeof(E), new B(), (string)null, false, false)); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate9_Method_ReturnTypeMismatch() { // throw bind failure ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "DoExecute", false, true)); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); // do not throw on bind failure E e = (E)Delegate.CreateDelegate(typeof(E), new B(), "DoExecute", false, false); Assert.Null(e); } [Fact] public static void CreateDelegate9_Method_Static() { // throw bind failure ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "Run", true, true)); // Error binding to target method Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); // do not throw on bind failure E e = (E)Delegate.CreateDelegate(typeof(E), new B(), "Run", true, false); Assert.Null(e); } [Fact] public static void CreateDelegate9_Target_Null() { ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("target", () => Delegate.CreateDelegate(typeof(E), (object)null, "Execute", true, false)); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] public static void CreateDelegate9_Type_Null() { ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("type", () => Delegate.CreateDelegate((Type)null, new B(), "Execute", true, false)); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } #endregion Tests #region Test Setup public class B { public virtual string retarg3(string s) { return s; } static int Run(C x) { return 5; } public static void DoRun(C x) { } public static int StartRun(C x, B b) { return 6; } int Execute(C c) { return 4; } public static void DoExecute(C c) { } public int StartExecute(C c, B b) { return 3; } } public class C : B, Iface { public string retarg(string s) { return s; } public string retarg2(Iface iface, string s) { return s + "2"; } public override string retarg3(string s) { return s + "2"; } static void Run(C x) { } public new static int DoRun(C x) { return 107; } void Execute(C c) { } public new int DoExecute(C c) { return 102; } public static void M() { } public static void N(C c) { } public static void S(C c) { } private void PrivateInstance() { } } public interface Iface { string retarg(string s); } public delegate void D(C c); public delegate int E(C c); #endregion Test Setup } } internal class DummyGenericClassForDelegateTests<T> { }
namespace Boxed.AspNetCore.Sitemap { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Xml.Linq; /// <summary> /// Generates site-map XML. /// </summary> public abstract class SitemapGenerator { private const string SitemapsNamespace = "http://www.sitemaps.org/schemas/sitemap/0.9"; /// <summary> /// The maximum number of site-maps a site-map index file can contain. /// </summary> private const int MaximumSitemapCount = 50000; /// <summary> /// The maximum number of site-map nodes allowed in a site-map file. The absolute maximum allowed is 50,000 /// according to the specification. See http://www.sitemaps.org/protocol.html but the file size must also be /// less than 10MB. After some experimentation, a maximum of 25,000 nodes keeps the file size below 10MB. /// </summary> private const int MaximumSitemapNodeCount = 25000; /// <summary> /// The maximum size of a site-map file in bytes (10MB). /// </summary> private const int MaximumSitemapSizeInBytes = 10485760; /// <summary> /// Gets the collection of XML site-map documents for the current site. If there are less than 25,000 site-map /// nodes, only one site-map document will exist in the collection, otherwise a site-map index document will be /// the first entry in the collection and all other entries will be site-map XML documents. /// </summary> /// <param name="sitemapNodes">The site-map nodes for the current site.</param> /// <returns>A collection of XML site-map documents.</returns> protected virtual List<string> GetSitemapDocuments(IReadOnlyCollection<SitemapNode> sitemapNodes) { if (sitemapNodes == null) { throw new ArgumentNullException(nameof(sitemapNodes)); } var sitemapCount = (int)Math.Ceiling(sitemapNodes.Count / (double)MaximumSitemapNodeCount); this.CheckSitemapCount(sitemapCount); var sitemaps = Enumerable .Range(0, sitemapCount) .Select(x => { return new KeyValuePair<int, IEnumerable<SitemapNode>>( x + 1, sitemapNodes.Skip(x * MaximumSitemapNodeCount).Take(MaximumSitemapNodeCount)); }); var sitemapDocuments = new List<string>(sitemapCount); if (sitemapCount > 1) { var xml = this.GetSitemapIndexDocument(sitemaps); sitemapDocuments.Add(xml); } foreach (var sitemap in sitemaps) { var xml = this.GetSitemapDocument(sitemap.Value); sitemapDocuments.Add(xml); } return sitemapDocuments; } /// <summary> /// Gets the URL to the site-map with the specified index. /// </summary> /// <param name="index">The index.</param> /// <returns>The site-map URL.</returns> protected abstract Uri GetSitemapUrl(int index); /// <summary> /// Logs warnings when a site-map exceeds the maximum size of 10MB or if the site-map index file exceeds the /// maximum number of allowed site-maps. No exceptions are thrown in this case as the site-map file is still /// generated correctly and search engines may still read it. /// </summary> /// <param name="exception">The exception to log.</param> protected virtual void LogWarning(Exception exception) { } /// <summary> /// Gets the site-map index XML document, containing links to all the site-map XML documents. /// </summary> /// <param name="sitemaps">The collection of site-maps containing their index and nodes.</param> /// <returns>The site-map index XML document, containing links to all the site-map XML documents.</returns> private string GetSitemapIndexDocument(IEnumerable<KeyValuePair<int, IEnumerable<SitemapNode>>> sitemaps) { var xmlns = XNamespace.Get(SitemapsNamespace); var root = new XElement(xmlns + "sitemapindex"); foreach (var sitemap in sitemaps) { // Get the latest LastModified DateTime from the sitemap nodes or null if there is none. var lastModified = sitemap.Value .Select(x => x.LastModified) .Where(x => x.HasValue) .DefaultIfEmpty() .Max(); var lastModifiedElement = lastModified.HasValue ? new XElement( xmlns + "lastmod", lastModified.Value.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture)) : null; var sitemapElement = new XElement( xmlns + "sitemap", new XElement(xmlns + "loc", this.GetSitemapUrl(sitemap.Key)), lastModifiedElement); root.Add(sitemapElement); } var document = new XDocument(root); var xml = document.ToString(Encoding.UTF8); this.CheckDocumentSize(xml); return xml; } /// <summary> /// Gets the site-map XML document for the specified set of nodes. /// </summary> /// <param name="sitemapNodes">The site-map nodes.</param> /// <returns>The site-map XML document for the specified set of nodes.</returns> private string GetSitemapDocument(IEnumerable<SitemapNode> sitemapNodes) { var xmlns = XNamespace.Get(SitemapsNamespace); var root = new XElement(xmlns + "urlset"); foreach (var sitemapNode in sitemapNodes) { var lastModifiedElement = sitemapNode.LastModified.HasValue ? new XElement( xmlns + "lastmod", sitemapNode.LastModified.Value.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture)) : null; var frequencyElement = sitemapNode.Frequency.HasValue ? new XElement( xmlns + "changefreq", #pragma warning disable CA1308 // Normalize strings to uppercase sitemapNode.Frequency.Value.ToString().ToLowerInvariant()) : #pragma warning restore CA1308 // Normalize strings to uppercase null; var priorityElement = sitemapNode.Priority.HasValue ? new XElement( xmlns + "priority", sitemapNode.Priority.Value.ToString("F1", CultureInfo.InvariantCulture)) : null; var urlElement = new XElement( xmlns + "url", new XElement(xmlns + "loc", Uri.EscapeUriString(sitemapNode.Url.ToString())), lastModifiedElement, frequencyElement, priorityElement); root.Add(urlElement); } var document = new XDocument(root); var xml = document.ToString(Encoding.UTF8); this.CheckDocumentSize(xml); return xml; } /// <summary> /// Checks the size of the XML site-map document. If it is over 10MB, logs an error. /// </summary> /// <param name="sitemapXml">The site-map XML document.</param> private void CheckDocumentSize(string sitemapXml) { if (sitemapXml.Length >= MaximumSitemapSizeInBytes) { this.LogWarning(new SitemapException(FormattableString.Invariant( $"Sitemap exceeds the maximum size of 10MB. This is because you have unusually long URL's. Consider reducing the MaximumSitemapNodeCount. Size:<{sitemapXml.Length}>."))); } } /// <summary> /// Checks the count of the number of site-maps. If it is over 50,000, logs an error. /// </summary> /// <param name="sitemapCount">The site-maps count.</param> private void CheckSitemapCount(int sitemapCount) { if (sitemapCount > MaximumSitemapCount) { this.LogWarning(new SitemapException(FormattableString.Invariant( $"Sitemap index file exceeds the maximum number of allowed sitemaps of 50,000. Count:<{sitemapCount}>"))); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using MathNet.Numerics.LinearAlgebra; using Retia.Interop; using Retia.Helpers; using Retia.Integration; using Retia.Integration.Helpers; using Retia.Mathematics; using Retia.Neural.ErrorFunctions; using Retia.Optimizers; using MatrixExtensions = Retia.Mathematics.MatrixExtensions; namespace Retia.Neural.Layers { public abstract class LayerBase<T> : ICloneable<LayerBase<T>>, IFileWritable where T : struct, IEquatable<T>, IFormattable { protected readonly MathProviderBase<T> MathProvider = MathProvider<T>.Instance; private readonly List<NeuroWeight<T>> _weights = new List<NeuroWeight<T>>(); protected int BatchSize, SeqLen; protected IntPtr GpuLayerPtr = IntPtr.Zero; protected LayerBase() { } protected LayerBase(LayerBase<T> other) { BatchSize = other.BatchSize; SeqLen = other.SeqLen; Inputs = other.Inputs.Select(x => x.CloneMatrix()).ToList(); Outputs = other.Outputs.Select(x => x.CloneMatrix()).ToList(); ErrorFunction = other.ErrorFunction?.Clone(); } protected LayerBase(BinaryReader reader) { BatchSize = reader.ReadInt32(); SeqLen = reader.ReadInt32(); bool hasError = reader.ReadBoolean(); if (hasError) { string errorType = reader.ReadString(); ErrorFunction = (ErrorFunctionBase<T>)Activator.CreateInstance(Type.GetType(errorType)); } } public abstract int InputSize { get; } public abstract int OutputSize { get; } public abstract int TotalParamCount { get; } public ErrorFunctionBase<T> ErrorFunction { get; set; } public List<Matrix<T>> Inputs { get; set; } = new List<Matrix<T>>(); public List<Matrix<T>> Outputs { get; set; } = new List<Matrix<T>>(); public virtual IReadOnlyList<NeuroWeight<T>> Weights => _weights; public abstract void ClampGrads(float limit); public abstract void ClearGradients(); public abstract LayerBase<T> Clone(); public abstract IntPtr CreateGpuLayer(); /// <summary> /// Modifies layer state from a vector of doubles. /// </summary> public abstract void FromVectorState(T[] vector, ref int idx); public abstract void InitSequence(); public abstract void Optimize(OptimizerBase<T> optimizer); public abstract void ResetMemory(); public abstract void ResetOptimizer(); public abstract void TransferWeightsToDevice(); public abstract void TransferWeightsToHost(); /// <summary> /// Forward layer step /// </summary> /// <param name="input">Input matrix</param> /// <param name="inTraining">Store states for back propagation</param> /// <returns>Layer output</returns> public abstract Matrix<T> Step(Matrix<T> input, bool inTraining = false); /// <summary> /// Converts layer state to a vector of doubles. /// </summary> /// <returns>Layer vector state.</returns> public abstract void ToVectorState(T[] destination, ref int idx, bool grad=false); /// <summary> /// Propagates next layer sensitivity to input, accumulating gradients for optimization /// </summary> /// <param name="outSens">Sequence of sensitivity matrices of next layer</param> /// <param name="needInputSens">Calculate input sensitivity for further propagation</param> /// <param name="clearGrad">Clear gradients before backpropagation.</param> /// <returns></returns> public virtual List<Matrix<T>> BackPropagate(List<Matrix<T>> outSens, bool needInputSens = true, bool clearGrad = true) { return outSens; } /// <summary> /// Calculates matched error (out-target) and propagates it through layer to inputs /// </summary> /// <param name="targets">Sequence of targets</param> public virtual List<Matrix<T>> ErrorPropagate(List<Matrix<T>> targets) { if (ErrorFunction == null) { throw new InvalidOperationException("Layer error function is not specified!"); } return ErrorFunction.BackpropagateError(Outputs, targets); } /// <summary> /// Calculates matched layer error. /// </summary> /// <param name="y">Layer output</param> /// <param name="target">Layer target</param> /// <returns></returns> public virtual double LayerError(Matrix<T> y, Matrix<T> target) { if (ErrorFunction == null) { throw new InvalidOperationException("Layer error function is not specified!"); } return ErrorFunction.GetError(y, target); } public virtual void Save(Stream s) { using (var writer = s.NonGreedyWriter()) { writer.Write(BatchSize); writer.Write(SeqLen); writer.Write(ErrorFunction != null); if (ErrorFunction != null) { writer.Write(ErrorFunction.GetType().FullName); } } } public virtual void SetParam(int i, T value) { int refInd = 0; var state = new T[TotalParamCount]; ToVectorState(state, ref refInd); state[i] = value; refInd = 0; FromVectorState(state, ref refInd); } public T GetParam(int i, bool grad = false) { int refInd=0; var state = new T[TotalParamCount]; ToVectorState(state, ref refInd, grad); return state[i]; } public void Save(string filename) { this.SaveObject(filename); } protected virtual void Initialize() { } /// <summary> /// Registers layer weights to return from <see cref="Weights"/>. /// </summary> /// <param name="weights">Weight collection.</param> protected void RegisterWeights(params NeuroWeight<T>[] weights) { _weights.Clear(); _weights.AddRange(weights); } protected unsafe void TransferWeigthsToDevice(bool rowMajor, params NeuroWeight<T>[] weights) { using (var defs = new WeightDefinitionBag<T>(rowMajor, weights)) { fixed (WeightDefinition* ptr = &defs.Definitions[0]) { GpuInterface.TransferLayerStatesToDevice(GpuLayerPtr, ptr, weights.Length); } } } protected unsafe void TransferWeigthsToHost(bool rowMajor, params NeuroWeight<T>[] weights) { using (var defs = new WeightDefinitionBag<T>(rowMajor, weights)) { fixed (WeightDefinition* ptr = &defs.Definitions[0]) { GpuInterface.TransferLayerStatesToHost(GpuLayerPtr, ptr, weights.Length); } } } internal void Initialize(int batchSize, int seqLen) { BatchSize = batchSize; SeqLen = seqLen; Initialize(); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Linq; using Glass.Mapper.Configuration.Attributes; namespace Glass.Mapper.Configuration { /// <summary> /// Represents the configuration for a .Net type /// </summary> [DebuggerDisplay("Type: {Type}")] public abstract class AbstractTypeConfiguration { private IDictionary<ConstructorInfo, Delegate> _constructorMethods; private ConcurrentDictionary<string, AbstractPropertyConfiguration> _properties; private ConcurrentDictionary<string, AbstractPropertyConfiguration> _privateProperties; /// <summary> /// The type this configuration represents /// </summary> /// <value>The type.</value> public Type Type { get; set; } public Cache Cache { get; set; } public AbstractPropertyConfiguration this[string key] { get { AbstractPropertyConfiguration property; _properties.TryGetValue(key, out property); return property; } } public IEnumerable<AbstractPropertyConfiguration> Properties { get { return _properties.Values; } } public IEnumerable<AbstractPropertyConfiguration> PrivateProperties { get { return _privateProperties.Values; } } /// <summary> /// A list of the constructors on a type /// </summary> /// <value>The constructor methods.</value> public IDictionary<ConstructorInfo, Delegate> ConstructorMethods { get { return _constructorMethods; } set { _constructorMethods = value; DefaultConstructor = _constructorMethods.Where(x=>x.Key.GetParameters().Length == 0).Select(x=>x.Value).FirstOrDefault(); } } /// <summary> /// This is the classes default constructor /// </summary> public Delegate DefaultConstructor { get; private set; } /// <summary> /// Indicates properties should be automatically mapped /// </summary> public bool AutoMap { get; set; } /// <summary> /// Initializes a new instance of the <see cref="AbstractTypeConfiguration"/> class. /// </summary> public AbstractTypeConfiguration() { _properties = new ConcurrentDictionary<string, AbstractPropertyConfiguration>(); _privateProperties = new ConcurrentDictionary<string, AbstractPropertyConfiguration>(); } /// <summary> /// Adds the property. /// </summary> /// <param name="property">The property.</param> public virtual void AddProperty(AbstractPropertyConfiguration property) { if (property != null) { var key = property.PropertyInfo.Name; if (property.PropertyInfo.GetMethod!= null && property.PropertyInfo.GetMethod.IsPrivate) { _privateProperties[key] = property; } else { _properties[key] = property; } } } /// <summary> /// Maps the properties to object. /// </summary> /// <param name="obj">The obj.</param> /// <param name="service">The service.</param> /// <param name="context">The context.</param> public void MapPrivatePropertiesToObject(object obj, IAbstractService service, AbstractTypeCreationContext context) { try { if (_privateProperties.Count != 0) { //create properties AbstractDataMappingContext dataMappingContext = context.CreateDataMappingContext(obj); foreach (var property in _privateProperties.Values) { var prop = property; try { prop.Mapper.MapCmsToProperty(dataMappingContext); } catch (MapperStackException) { throw; } catch (Exception e) { throw new MapperException( "Failed to map property {0} on {1}".Formatted(prop.PropertyInfo.Name, prop.PropertyInfo.DeclaringType.FullName), e); } } } } catch (MapperStackException) { throw; } catch (Exception ex) { throw new MapperException( "Failed to map properties on {0}.".Formatted(context.DataSummary()), ex); } } /// <summary> /// Maps the properties to object. /// </summary> /// <param name="obj">The obj.</param> /// <param name="service">The service.</param> /// <param name="context">The context.</param> public void MapPropertiesToObject( object obj, IAbstractService service, AbstractTypeCreationContext context) { try { if (_properties.Count != 0) { //create properties AbstractDataMappingContext dataMappingContext = context.CreateDataMappingContext(obj); foreach (var property in _properties.Values) { var prop = property; try { prop.Mapper.MapCmsToProperty(dataMappingContext); } catch (MapperStackException) { throw; } catch (Exception e) { throw new MapperException( "Failed to map property {0} on {1}".Formatted(prop.PropertyInfo.Name, prop.PropertyInfo.DeclaringType.FullName), e); } } } } catch (MapperStackException) { throw; } catch (Exception ex) { throw new MapperException( "Failed to map properties on {0}.".Formatted(context.DataSummary()), ex); } MapPrivatePropertiesToObject(obj, service, context); } /// <summary> /// Called when the AutoMap property is true. Automatically maps un-specified properties. /// </summary> public void PerformAutoMap() { //we now run the auto-mapping after all the static configuration is loaded if (AutoMap) { var properties = AutoMapProperties(Type); foreach (var propConfig in properties) { AddProperty(propConfig); } } } /// <summary> /// Autoes the map properties. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public virtual IEnumerable<AbstractPropertyConfiguration> AutoMapProperties(Type type) { BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy; IEnumerable<PropertyInfo> properties = type.GetProperties(flags); if (type.IsInterface) { foreach (var inter in type.GetInterfaces()) { properties = properties.Union(inter.GetProperties(flags)); } } var propList = new List<AbstractPropertyConfiguration>(); foreach (var property in properties) { var key = property.Name; var currentProperty = this[key]; if (currentProperty == null) { //skip properties that are actually indexers if (property.GetIndexParameters().Length > 0) { continue; } //check for an attribute var propConfig = AttributeTypeLoader.ProcessProperty(property); if (propConfig == null) { //no attribute then automap propConfig = AutoMapProperty(property); } if (propConfig != null) propList.Add(propConfig); } } return propList; } /// <summary> /// Called to map each property automatically /// </summary> /// <param name="property"></param> /// <returns></returns> protected virtual AbstractPropertyConfiguration AutoMapProperty(PropertyInfo property) { return null; } public virtual void GetTypeOptions(GetOptions options) { if (options.Cache == Cache.Default) { options.Cache = Cache; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Xunit; namespace System.Threading.Tests { /// <summary>The class that contains the unit tests of the ThreadLocal.</summary> public static class ThreadLocalTests { /// <summary>Tests for the Ctor.</summary> /// <returns>True if the tests succeeds, false otherwise.</returns> [Fact] public static void RunThreadLocalTest1_Ctor() { ThreadLocal<object> testObject; testObject = new ThreadLocal<object>(); testObject = new ThreadLocal<object>(true); testObject = new ThreadLocal<object>(() => new object()); testObject = new ThreadLocal<object>(() => new object(), true); } [Fact] public static void RunThreadLocalTest1_Ctor_Negative() { try { new ThreadLocal<object>(null); } catch (ArgumentNullException) { // No other exception should be thrown. // With a previous issue, if the constructor threw an exception, the finalizer would throw an exception as well. } } /// <summary>Tests for the ToString.</summary> /// <returns>True if the tests succeeds, false otherwise.</returns> [Fact] public static void RunThreadLocalTest2_ToString() { ThreadLocal<object> tlocal = new ThreadLocal<object>(() => (object)1); Assert.Equal(1.ToString(), tlocal.ToString()); } /// <summary>Tests for the Initialized property.</summary> /// <returns>True if the tests succeeds, false otherwise.</returns> [Fact] public static void RunThreadLocalTest3_IsValueCreated() { ThreadLocal<string> tlocal = new ThreadLocal<string>(() => "Test"); Assert.False(tlocal.IsValueCreated); string temp = tlocal.Value; Assert.True(tlocal.IsValueCreated); } [Fact] public static void RunThreadLocalTest4_Value() { ThreadLocal<string> tlocal = null; // different threads call Value int numOfThreads = 10; Task[] threads = new Task[numOfThreads]; object alock = new object(); List<string> seenValuesFromAllThreads = new List<string>(); int counter = 0; tlocal = new ThreadLocal<string>(() => (++counter).ToString()); //CancellationToken ct = new CancellationToken(); for (int i = 0; i < threads.Length; ++i) { // We are creating the task using TaskCreationOptions.LongRunning because... // there is no guarantee that the Task will be created on another thread. // There is also no guarantee that using this TaskCreationOption will force // it to be run on another thread. threads[i] = new Task(() => { string value = tlocal.Value; Debug.WriteLine("Val: " + value); seenValuesFromAllThreads.Add(value); }, TaskCreationOptions.LongRunning); threads[i].Start(TaskScheduler.Default); threads[i].Wait(); } Assert.Equal(Enumerable.Range(1, threads.Length).Select(x => x.ToString()), seenValuesFromAllThreads); } [Fact] public static void RunThreadLocalTest4_Value_NegativeCases() { ThreadLocal<string> tlocal = null; Assert.Throws<InvalidOperationException>(() => { int x = 0; tlocal = new ThreadLocal<string>(delegate { if (x++ < 5) return tlocal.Value; else return "Test"; }); string str = tlocal.Value; }); } [Fact] public static void RunThreadLocalTest5_Dispose() { // test recycling the combination index; ThreadLocal<string> tl = new ThreadLocal<string>(() => null); Assert.False(tl.IsValueCreated); Assert.Null(tl.Value); // Test that a value is not kept alive by a departed thread var threadLocal = new ThreadLocal<SetMreOnFinalize>(); var mres = new ManualResetEventSlim(false); // (Careful when editing this test: saving the created thread into a local variable would likely break the // test in Debug build.) // We are creating the task using TaskCreationOptions.LongRunning because... // there is no guarantee that the Task will be created on another thread. // There is also no guarantee that using this TaskCreationOption will force // it to be run on another thread. new Task(() => { threadLocal.Value = new SetMreOnFinalize(mres); }, TaskCreationOptions.LongRunning).Start(TaskScheduler.Default); SpinWait.SpinUntil(() => { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); return mres.IsSet; }, 5000); Assert.True(mres.IsSet); } [Fact] public static void RunThreadLocalTest5_Dispose_Negative() { ThreadLocal<string> tl = new ThreadLocal<string>(() => "dispose test"); string value = tl.Value; tl.Dispose(); Assert.Throws<ObjectDisposedException>(() => { string tmp = tl.Value; }); // Failure Case: The Value property of the disposed ThreadLocal object should throw ODE Assert.Throws<ObjectDisposedException>(() => { bool tmp = tl.IsValueCreated; }); // Failure Case: The IsValueCreated property of the disposed ThreadLocal object should throw ODE Assert.Throws<ObjectDisposedException>(() => { string tmp = tl.ToString(); }); // Failure Case: The ToString method of the disposed ThreadLocal object should throw ODE } [Fact] public static void RunThreadLocalTest6_SlowPath() { // the maximum fast path instances for each type is 16 ^ 3 = 4096, when this number changes in the product code, it should be changed here as well int MaximumFastPathPerInstance = 4096; ThreadLocal<int>[] locals_int = new ThreadLocal<int>[MaximumFastPathPerInstance + 10]; for (int i = 0; i < locals_int.Length; i++) { locals_int[i] = new ThreadLocal<int>(() => i); var val = locals_int[i].Value; } Assert.Equal(Enumerable.Range(0, locals_int.Length), locals_int.Select(x => x.Value)); // The maximum slowpath for all Ts is MaximumFastPathPerInstance * 4; locals_int = new ThreadLocal<int>[4096]; ThreadLocal<long>[] locals_long = new ThreadLocal<long>[4096]; ThreadLocal<float>[] locals_float = new ThreadLocal<float>[4096]; ThreadLocal<double>[] locals_double = new ThreadLocal<double>[4096]; for (int i = 0; i < locals_int.Length; i++) { locals_int[i] = new ThreadLocal<int>(() => i); locals_long[i] = new ThreadLocal<long>(() => i); locals_float[i] = new ThreadLocal<float>(() => i); locals_double[i] = new ThreadLocal<double>(() => i); } ThreadLocal<string> local = new ThreadLocal<string>(() => "slow path"); Assert.Equal("slow path", local.Value); } private class ThreadLocalWeakReferenceTest { private object _foo; private WeakReference _wFoo; [MethodImplAttribute(MethodImplOptions.NoInlining)] private void Method() { _foo = new object(); _wFoo = new WeakReference(_foo); new ThreadLocal<object>() { Value = _foo }.Dispose(); } public void Run() { Method(); _foo = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); // s_foo should have been garbage collected Assert.False(_wFoo.IsAlive); } } [Fact] public static void RunThreadLocalTest7_WeakReference() { var threadLocalWeakReferenceTest = new ThreadLocalWeakReferenceTest(); threadLocalWeakReferenceTest.Run(); } [Fact] public static void RunThreadLocalTest8_Values() { // Test adding values and updating values { var threadLocal = new ThreadLocal<int>(true); Assert.True(threadLocal.Values.Count == 0, "RunThreadLocalTest8_Values: Expected thread local to initially have 0 values"); Assert.True(threadLocal.Value == 0, "RunThreadLocalTest8_Values: Expected initial value of 0"); Assert.True(threadLocal.Values.Count == 1, "RunThreadLocalTest8_Values: Expected values count to now be 1 from initialized value"); Assert.True(threadLocal.Values[0] == 0, "RunThreadLocalTest8_Values: Expected values to contain initialized value"); threadLocal.Value = 1000; Assert.True(threadLocal.Values.Count == 1, "RunThreadLocalTest8_Values: Expected values count to still be 1 after updating existing value"); Assert.True(threadLocal.Values[0] == 1000, "RunThreadLocalTest8_Values: Expected values to contain updated value"); ((IAsyncResult)Task.Run(() => threadLocal.Value = 1001)).AsyncWaitHandle.WaitOne(); Assert.True(threadLocal.Values.Count == 2, "RunThreadLocalTest8_Values: Expected values count to be 2 now that another thread stored a value"); Assert.True(threadLocal.Values.Contains(1000) && threadLocal.Values.Contains(1001), "RunThreadLocalTest8_Values: Expected values to contain both thread's values"); int numTasks = 1000; Task[] allTasks = new Task[numTasks]; for (int i = 0; i < numTasks; i++) { // We are creating the task using TaskCreationOptions.LongRunning because... // there is no guarantee that the Task will be created on another thread. // There is also no guarantee that using this TaskCreationOption will force // it to be run on another thread. var task = Task.Factory.StartNew(() => threadLocal.Value = i, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); task.Wait(); } var values = threadLocal.Values; if (values.Count != 1002) { string message = "RunThreadLocalTest8_Values: Expected values to contain both previous values and 1000 new values. Actual count: " + values.Count + '.'; if (values.Count != 0) { message += " Missing items:"; for (int i = 0; i < 1002; i++) { if (!values.Contains(i)) { message += " " + i; } } } Assert.True(false, message); } for (int i = 0; i < 1000; i++) { Assert.True(values.Contains(i), "RunThreadLocalTest8_Values: Expected values to contain value for thread #: " + i); } threadLocal.Dispose(); } // Test that thread values remain after threads depart { var tl = new ThreadLocal<string>(true); var t = Task.Run(() => tl.Value = "Parallel"); t.Wait(); t = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.True(tl.Values.Count == 1, "RunThreadLocalTest8_Values: Expected values count to be 1 from other thread's initialization"); Assert.True(tl.Values.Contains("Parallel"), "RunThreadLocalTest8_Values: Expected values to contain 'Parallel'"); } } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void RunThreadLocalTest8Helper(ManualResetEventSlim mres) { var tl = new ThreadLocal<object>(true); var t = Task.Run(() => tl.Value = new SetMreOnFinalize(mres)); t.Wait(); t = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.True(tl.Values.Count == 1, "RunThreadLocalTest8_Values: Expected other thread to have set value"); Assert.True(tl.Values[0] is SetMreOnFinalize, "RunThreadLocalTest8_Values: Expected other thread's value to be of the right type"); tl.Dispose(); object values; Assert.Throws<ObjectDisposedException>(() => values = tl.Values); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Mono, "This test requires precise stack scanning")] public static void RunThreadLocalTest8_Values_NegativeCases() { // Test that Dispose works and that objects are released on dispose { var mres = new ManualResetEventSlim(); RunThreadLocalTest8Helper(mres); SpinWait.SpinUntil(() => { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); return mres.IsSet; }, 5000); Assert.True(mres.IsSet, "RunThreadLocalTest8_Values: Expected thread local to release the object and for it to be finalized"); } // Test that Values property throws an exception unless true was passed into the constructor { ThreadLocal<int> t = new ThreadLocal<int>(); t.Value = 5; Exception exceptionCaught = null; try { var randomValue = t.Values.Count; } catch (Exception ex) { exceptionCaught = ex; } Assert.True(exceptionCaught != null, "RunThreadLocalTest8_Values: Expected Values to throw an InvalidOperationException. No exception was thrown."); Assert.True( exceptionCaught != null && exceptionCaught is InvalidOperationException, "RunThreadLocalTest8_Values: Expected Values to throw an InvalidOperationException. Wrong exception was thrown: " + exceptionCaught.GetType().ToString()); } } [Fact] public static void RunThreadLocalTest9_Uninitialized() { for (int iter = 0; iter < 10; iter++) { ThreadLocal<int> t1 = new ThreadLocal<int>(); t1.Value = 177; ThreadLocal<int> t2 = new ThreadLocal<int>(); Assert.True(!t2.IsValueCreated, "RunThreadLocalTest9_Uninitialized: The ThreadLocal instance should have been uninitialized."); } } private class SetMreOnFinalize { private ManualResetEventSlim _mres; public SetMreOnFinalize(ManualResetEventSlim mres) { _mres = mres; } ~SetMreOnFinalize() { _mres.Set(); } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //------------------------------------------------------------------------------ // This code was generated by a tool. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. //------------------------------------------------------------------------------ // To get up to date fundamental definition files for your hedgefund contact [email protected] using System; using System.IO; using Newtonsoft.Json; namespace QuantConnect.Data.Fundamental { /// <summary> /// Definition of the CompanyProfile class /// </summary> public class CompanyProfile { /// <summary> /// The headquarter address as given in the latest report /// </summary> /// <remarks> /// Morningstar DataId: 2100 /// </remarks> [JsonProperty("2100")] public string HeadquarterAddressLine1 { get; set; } /// <summary> /// The headquarter address as given in the latest report /// </summary> /// <remarks> /// Morningstar DataId: 2101 /// </remarks> [JsonProperty("2101")] public string HeadquarterAddressLine2 { get; set; } /// <summary> /// The headquarter address as given in the latest report /// </summary> /// <remarks> /// Morningstar DataId: 2102 /// </remarks> [JsonProperty("2102")] public string HeadquarterAddressLine3 { get; set; } /// <summary> /// The headquarter address as given in the latest report /// </summary> /// <remarks> /// Morningstar DataId: 2103 /// </remarks> [JsonProperty("2103")] public string HeadquarterAddressLine4 { get; set; } /// <summary> /// The headquarter address as given in the latest report /// </summary> /// <remarks> /// Morningstar DataId: 2104 /// </remarks> [JsonProperty("2104")] public string HeadquarterAddressLine5 { get; set; } /// <summary> /// The headquarter city as given in the latest report /// </summary> /// <remarks> /// Morningstar DataId: 2105 /// </remarks> [JsonProperty("2105")] public string HeadquarterCity { get; set; } /// <summary> /// The headquarter state or province as given in the latest report /// </summary> /// <remarks> /// Morningstar DataId: 2106 /// </remarks> [JsonProperty("2106")] public string HeadquarterProvince { get; set; } /// <summary> /// The headquarter country as given in the latest report /// </summary> /// <remarks> /// Morningstar DataId: 2107 /// </remarks> [JsonProperty("2107")] public string HeadquarterCountry { get; set; } /// <summary> /// The headquarter postal code as given in the latest report /// </summary> /// <remarks> /// Morningstar DataId: 2108 /// </remarks> [JsonProperty("2108")] public string HeadquarterPostalCode { get; set; } /// <summary> /// The headquarter phone number as given in the latest report /// </summary> /// <remarks> /// Morningstar DataId: 2109 /// </remarks> [JsonProperty("2109")] public string HeadquarterPhone { get; set; } /// <summary> /// The headquarter fax number as given in the latest report /// </summary> /// <remarks> /// Morningstar DataId: 2110 /// </remarks> [JsonProperty("2110")] public string HeadquarterFax { get; set; } /// <summary> /// The headquarters' website address as given in the latest report /// </summary> /// <remarks> /// Morningstar DataId: 2111 /// </remarks> [JsonProperty("2111")] public string HeadquarterHomepage { get; set; } /// <summary> /// The number of employees as indicated on the latest Annual Report, 10-K filing, Form 20-F or equivalent report indicating the /// employee count at the end of latest fiscal year. /// </summary> /// <remarks> /// Morningstar DataId: 2113 /// </remarks> [JsonProperty("2113")] public int TotalEmployeeNumber { get; set; } /// <summary> /// Company's contact email address /// </summary> /// <remarks> /// Morningstar DataId: 2114 /// </remarks> [JsonProperty("2114")] public string ContactEmail { get; set; } /// <summary> /// Average number of employees from Annual Report /// </summary> /// <remarks> /// Morningstar DataId: 2115 /// </remarks> [JsonProperty("2115")] public int AverageEmployeeNumber { get; set; } /// <summary> /// Details for registered office contact information including address full details, phone and /// </summary> /// <remarks> /// Morningstar DataId: 2116 /// </remarks> [JsonProperty("2116")] public string RegisteredAddressLine1 { get; set; } /// <summary> /// Address for registered office /// </summary> /// <remarks> /// Morningstar DataId: 2117 /// </remarks> [JsonProperty("2117")] public string RegisteredAddressLine2 { get; set; } /// <summary> /// Address for registered office /// </summary> /// <remarks> /// Morningstar DataId: 2118 /// </remarks> [JsonProperty("2118")] public string RegisteredAddressLine3 { get; set; } /// <summary> /// Address for registered office /// </summary> /// <remarks> /// Morningstar DataId: 2119 /// </remarks> [JsonProperty("2119")] public string RegisteredAddressLine4 { get; set; } /// <summary> /// City for registered office /// </summary> /// <remarks> /// Morningstar DataId: 2120 /// </remarks> [JsonProperty("2120")] public string RegisteredCity { get; set; } /// <summary> /// Province for registered office /// </summary> /// <remarks> /// Morningstar DataId: 2121 /// </remarks> [JsonProperty("2121")] public string RegisteredProvince { get; set; } /// <summary> /// Country for registered office /// </summary> /// <remarks> /// Morningstar DataId: 2122 /// </remarks> [JsonProperty("2122")] public string RegisteredCountry { get; set; } /// <summary> /// Postal Code for registered office /// </summary> /// <remarks> /// Morningstar DataId: 2123 /// </remarks> [JsonProperty("2123")] public string RegisteredPostalCode { get; set; } /// <summary> /// Phone number for registered office /// </summary> /// <remarks> /// Morningstar DataId: 2124 /// </remarks> [JsonProperty("2124")] public string RegisteredPhone { get; set; } /// <summary> /// Fax number for registered office /// </summary> /// <remarks> /// Morningstar DataId: 2125 /// </remarks> [JsonProperty("2125")] public string RegisteredFax { get; set; } /// <summary> /// Flag to denote whether head and registered offices are the same /// </summary> /// <remarks> /// Morningstar DataId: 2126 /// </remarks> [JsonProperty("2126")] public bool IsHeadOfficeSameWithRegisteredOfficeFlag { get; set; } /// <summary> /// The latest total shares outstanding reported by the company; most common source of this information is from the cover of the 10K, /// 10Q, or 20F filing. This figure is an aggregated shares outstanding number for a company. It can be used to calculate the most /// accurate market cap, based on each individual share's trading price and the total aggregated shares outstanding figure. /// </summary> /// <remarks> /// Morningstar DataId: 40000 /// </remarks> [JsonProperty("40000")] public long SharesOutstanding { get; set; } /// <summary> /// Price * Total SharesOutstanding. /// The most current market cap for example, would be the most recent closing price x the most recent reported shares outstanding. /// For ADR share classes, market cap is price * (ordinary shares outstanding / adr ratio). /// </summary> /// <remarks> /// Morningstar DataId: 40001 /// </remarks> [JsonProperty("40001")] public long MarketCap { get; set; } /// <summary> /// This number tells you what cash return you would get if you bought the entire company, including its debt. Enterprise Value = /// Market Cap + Preferred stock + Long-Term Debt And Capital Lease + Short Term Debt And Capital Lease + Securities Sold But /// Not Yet Repurchased - Cash, Cash Equivalent And Market Securities - Securities Purchased with Agreement to Resell - Securities /// Borrowed. /// </summary> /// <remarks> /// Morningstar DataId: 40002 /// </remarks> [JsonProperty("40002")] public long EnterpriseValue { get; set; } /// <summary> /// The latest shares outstanding reported by the company of a particular share class; most common source of this information is from /// the cover of the 10K, 10Q, or 20F filing. This figure is an aggregated shares outstanding number for a particular share class of the /// company. /// </summary> /// <remarks> /// Morningstar DataId: 40003 /// </remarks> [JsonProperty("40003")] public long ShareClassLevelSharesOutstanding { get; set; } /// <summary> /// Total shares outstanding reported by the company as of the balance sheet period ended date. The most common source of this /// information is from the 10K, 10Q, or 20F filing. This figure is an aggregated shares outstanding number for a company. /// </summary> /// <remarks> /// Morningstar DataId: 40007 /// </remarks> [JsonProperty("40007")] public long SharesOutstandingWithBalanceSheetEndingDate { get; set; } /// <summary> /// The reason for the change in a company's total shares outstanding from the previous record. Examples could be share issuances or /// share buy-back. This field will only be populated when total shares outstanding is collected from a press release. /// </summary> /// <remarks> /// Morningstar DataId: 40010 /// </remarks> [JsonProperty("40010")] public string ReasonofSharesChange { get; set; } /// <summary> /// Creates an instance of the CompanyProfile class /// </summary> public CompanyProfile() { } /// <summary> /// Applies updated values from <paramref name="update"/> to this instance /// </summary> /// <remarks>Used to apply data updates to the current instance. This WILL overwrite existing values. Default update values are ignored.</remarks> /// <param name="update">The next data update for this instance</param> public void UpdateValues(CompanyProfile update) { if (update == null) return; if (!string.IsNullOrWhiteSpace(update.HeadquarterAddressLine1)) HeadquarterAddressLine1 = update.HeadquarterAddressLine1; if (!string.IsNullOrWhiteSpace(update.HeadquarterAddressLine2)) HeadquarterAddressLine2 = update.HeadquarterAddressLine2; if (!string.IsNullOrWhiteSpace(update.HeadquarterAddressLine3)) HeadquarterAddressLine3 = update.HeadquarterAddressLine3; if (!string.IsNullOrWhiteSpace(update.HeadquarterAddressLine4)) HeadquarterAddressLine4 = update.HeadquarterAddressLine4; if (!string.IsNullOrWhiteSpace(update.HeadquarterAddressLine5)) HeadquarterAddressLine5 = update.HeadquarterAddressLine5; if (!string.IsNullOrWhiteSpace(update.HeadquarterCity)) HeadquarterCity = update.HeadquarterCity; if (!string.IsNullOrWhiteSpace(update.HeadquarterProvince)) HeadquarterProvince = update.HeadquarterProvince; if (!string.IsNullOrWhiteSpace(update.HeadquarterCountry)) HeadquarterCountry = update.HeadquarterCountry; if (!string.IsNullOrWhiteSpace(update.HeadquarterPostalCode)) HeadquarterPostalCode = update.HeadquarterPostalCode; if (!string.IsNullOrWhiteSpace(update.HeadquarterPhone)) HeadquarterPhone = update.HeadquarterPhone; if (!string.IsNullOrWhiteSpace(update.HeadquarterFax)) HeadquarterFax = update.HeadquarterFax; if (!string.IsNullOrWhiteSpace(update.HeadquarterHomepage)) HeadquarterHomepage = update.HeadquarterHomepage; if (update.TotalEmployeeNumber != default(int)) TotalEmployeeNumber = update.TotalEmployeeNumber; if (!string.IsNullOrWhiteSpace(update.ContactEmail)) ContactEmail = update.ContactEmail; if (update.AverageEmployeeNumber != default(int)) AverageEmployeeNumber = update.AverageEmployeeNumber; if (!string.IsNullOrWhiteSpace(update.RegisteredAddressLine1)) RegisteredAddressLine1 = update.RegisteredAddressLine1; if (!string.IsNullOrWhiteSpace(update.RegisteredAddressLine2)) RegisteredAddressLine2 = update.RegisteredAddressLine2; if (!string.IsNullOrWhiteSpace(update.RegisteredAddressLine3)) RegisteredAddressLine3 = update.RegisteredAddressLine3; if (!string.IsNullOrWhiteSpace(update.RegisteredAddressLine4)) RegisteredAddressLine4 = update.RegisteredAddressLine4; if (!string.IsNullOrWhiteSpace(update.RegisteredCity)) RegisteredCity = update.RegisteredCity; if (!string.IsNullOrWhiteSpace(update.RegisteredProvince)) RegisteredProvince = update.RegisteredProvince; if (!string.IsNullOrWhiteSpace(update.RegisteredCountry)) RegisteredCountry = update.RegisteredCountry; if (!string.IsNullOrWhiteSpace(update.RegisteredPostalCode)) RegisteredPostalCode = update.RegisteredPostalCode; if (!string.IsNullOrWhiteSpace(update.RegisteredPhone)) RegisteredPhone = update.RegisteredPhone; if (!string.IsNullOrWhiteSpace(update.RegisteredFax)) RegisteredFax = update.RegisteredFax; if (update.IsHeadOfficeSameWithRegisteredOfficeFlag != default(bool)) IsHeadOfficeSameWithRegisteredOfficeFlag = update.IsHeadOfficeSameWithRegisteredOfficeFlag; if (update.SharesOutstanding != default(long)) SharesOutstanding = update.SharesOutstanding; if (update.MarketCap != default(long)) MarketCap = update.MarketCap; if (update.EnterpriseValue != default(long)) EnterpriseValue = update.EnterpriseValue; if (update.ShareClassLevelSharesOutstanding != default(long)) ShareClassLevelSharesOutstanding = update.ShareClassLevelSharesOutstanding; if (update.SharesOutstandingWithBalanceSheetEndingDate != default(long)) SharesOutstandingWithBalanceSheetEndingDate = update.SharesOutstandingWithBalanceSheetEndingDate; if (!string.IsNullOrWhiteSpace(update.ReasonofSharesChange)) ReasonofSharesChange = update.ReasonofSharesChange; } } }
//----------------------------------------------------------------------- // <copyright file="DataPortalTests.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>no summary</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using Csla.Test.DataBinding; using System.Data; using System.Data.SqlClient; #if NUNIT using NUnit.Framework; using TestClass = NUnit.Framework.TestFixtureAttribute; using TestInitialize = NUnit.Framework.SetUpAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; using TestMethod = NUnit.Framework.TestAttribute; using TestSetup = NUnit.Framework.SetUpAttribute; #elif MSTEST using Microsoft.VisualStudio.TestTools.UnitTesting; #endif namespace Csla.Test.DataPortal { [TestClass()] public class DataPortalTests { //pull from ConfigurationManager private const string CONNECTION_STRING = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|DataPortalTestDatabase.mdf;Integrated Security=True;User Instance=True"; public void ClearDataBase() { SqlConnection cn = new SqlConnection(CONNECTION_STRING); SqlCommand cm = new SqlCommand("DELETE FROM Table2", cn); try { cn.Open(); cm.ExecuteNonQuery(); } catch (Exception) { //do nothing } finally { cn.Close(); } } [TestMethod()] [Ignore] public void TestEnterpriseServicesTransactionalUpdate() { Csla.Test.DataPortal.ESTransactionalRoot tr = Csla.Test.DataPortal.ESTransactionalRoot.NewESTransactionalRoot(); tr.FirstName = "Bill"; tr.LastName = "Johnson"; //setting smallColumn to a string less than or equal to 5 characters will //not cause the transaction to rollback tr.SmallColumn = "abc"; tr = tr.Save(); SqlConnection cn = new SqlConnection(CONNECTION_STRING); SqlCommand cm = new SqlCommand("SELECT * FROM Table2", cn); try { cn.Open(); SqlDataReader dr = cm.ExecuteReader(); //will have rows since no sqlexception was thrown on the insert Assert.AreEqual(true, dr.HasRows); dr.Close(); } catch { //do nothing } finally { cn.Close(); } ClearDataBase(); Csla.Test.DataPortal.ESTransactionalRoot tr2 = Csla.Test.DataPortal.ESTransactionalRoot.NewESTransactionalRoot(); tr2.FirstName = "Jimmy"; tr2.LastName = "Smith"; //intentionally input a string longer than varchar(5) to //cause a sql exception and rollback the transaction tr2.SmallColumn = "this will cause a sql exception"; try { //will throw a sql exception since the SmallColumn property is too long tr2 = tr2.Save(); } catch (Exception ex) { Assert.IsTrue(ex.Message.StartsWith("DataPortal.Update failed"), "Invalid exception message"); } //within the DataPortal_Insert method, two commands are run to insert data into //the database. Here we verify that both commands have been rolled back try { cn.Open(); SqlDataReader dr = cm.ExecuteReader(); //should not have rows since both commands were rolled back Assert.AreEqual(false, dr.HasRows); dr.Close(); } catch { //do nothing } finally { cn.Close(); } ClearDataBase(); } #if DEBUG [TestMethod()] [TestCategory("SkipWhenLiveUnitTesting")] public void TestTransactionScopeUpdate() { Csla.Test.DataPortal.TransactionalRoot tr = Csla.Test.DataPortal.TransactionalRoot.NewTransactionalRoot(); tr.FirstName = "Bill"; tr.LastName = "Johnson"; //setting smallColumn to a string less than or equal to 5 characters will //not cause the transaction to rollback tr.SmallColumn = "abc"; tr = tr.Save(); SqlConnection cn = new SqlConnection(CONNECTION_STRING); SqlCommand cm = new SqlCommand("SELECT * FROM Table2", cn); try { cn.Open(); SqlDataReader dr = cm.ExecuteReader(); //will have rows since no sqlexception was thrown on the insert Assert.AreEqual(true, dr.HasRows); dr.Close(); } catch (Exception ex) { //do nothing } finally { cn.Close(); } ClearDataBase(); Csla.Test.DataPortal.TransactionalRoot tr2 = Csla.Test.DataPortal.TransactionalRoot.NewTransactionalRoot(); tr2.FirstName = "Jimmy"; tr2.LastName = "Smith"; //intentionally input a string longer than varchar(5) to //cause a sql exception and rollback the transaction tr2.SmallColumn = "this will cause a sql exception"; try { //will throw a sql exception since the SmallColumn property is too long tr2 = tr2.Save(); } catch (Exception ex) { Assert.IsTrue(ex.Message.StartsWith("DataPortal.Update failed"), "Invalid exception message"); } //within the DataPortal_Insert method, two commands are run to insert data into //the database. Here we verify that both commands have been rolled back try { cn.Open(); SqlDataReader dr = cm.ExecuteReader(); //should not have rows since both commands were rolled back Assert.AreEqual(false, dr.HasRows); dr.Close(); } catch (Exception ex) { //do nothing } finally { cn.Close(); } ClearDataBase(); } #endif [TestMethod()] [TestCategory("SkipWhenLiveUnitTesting")] public void StronglyTypedDataPortalMethods() { //test strongly-typed DataPortal_Fetch method Csla.ApplicationContext.GlobalContext.Clear(); Csla.Test.DataPortal.StronglyTypedDP root = Csla.Test.DataPortal.StronglyTypedDP.GetStronglyTypedDP(456); Assert.AreEqual("Fetched", Csla.ApplicationContext.GlobalContext["StronglyTypedDP"]); Assert.AreEqual("fetched existing data", root.Data); Assert.AreEqual(456, root.Id); //test strongly-typed DataPortal_Create method Csla.ApplicationContext.GlobalContext.Clear(); Csla.Test.DataPortal.StronglyTypedDP root2 = Csla.Test.DataPortal.StronglyTypedDP.NewStronglyTypedDP(); Assert.AreEqual("Created", Csla.ApplicationContext.GlobalContext["StronglyTypedDP"]); Assert.AreEqual("new default data", root2.Data); Assert.AreEqual(56, root2.Id); //test strongly-typed DataPortal_Delete method Csla.Test.DataPortal.StronglyTypedDP.DeleteStronglyTypedDP(567); Assert.AreEqual(567, Csla.ApplicationContext.GlobalContext["StronglyTypedDP_Criteria"]); } [TestMethod] [TestCategory("SkipWhenLiveUnitTesting")] public void EncapsulatedIsBusyFails() { try { var obj = Csla.DataPortal.Fetch<EncapsulatedBusy>(); } catch (DataPortalException ex) { Assert.IsInstanceOfType(ex.InnerException, typeof(InvalidOperationException)); return; } Assert.Fail("Expected exception"); } [TestMethod] [TestCategory("SkipWhenLiveUnitTesting")] public void FactoryIsBusyFails() { try { var obj = Csla.DataPortal.Fetch<FactoryBusy>(); } catch (DataPortalException ex) { Assert.IsInstanceOfType(ex.InnerException, typeof(InvalidOperationException)); return; } Assert.Fail("Expected exception"); } [TestMethod()] [TestCategory("SkipWhenLiveUnitTesting")] public void DataPortalEvents() { Csla.DataPortal.DataPortalInvoke += new Action<DataPortalEventArgs>(ClientPortal_DataPortalInvoke); Csla.DataPortal.DataPortalInvokeComplete += new Action<DataPortalEventArgs>(ClientPortal_DataPortalInvokeComplete); try { ApplicationContext.GlobalContext.Clear(); DpRoot root = DpRoot.NewRoot(); root.Data = "saved"; Csla.ApplicationContext.GlobalContext.Clear(); root = root.Save(); Assert.IsTrue((bool)ApplicationContext.GlobalContext["dpinvoke"], "DataPortalInvoke not called"); Assert.IsTrue((bool)ApplicationContext.GlobalContext["dpinvokecomplete"], "DataPortalInvokeComplete not called"); Assert.IsTrue((bool)ApplicationContext.GlobalContext["serverinvoke"], "Server DataPortalInvoke not called"); Assert.IsTrue((bool)ApplicationContext.GlobalContext["serverinvokecomplete"], "Server DataPortalInvokeComplete not called"); } finally { Csla.DataPortal.DataPortalInvoke -= new Action<DataPortalEventArgs>(ClientPortal_DataPortalInvoke); Csla.DataPortal.DataPortalInvokeComplete -= new Action<DataPortalEventArgs>(ClientPortal_DataPortalInvokeComplete); } } [TestMethod] [TestCategory("SkipWhenLiveUnitTesting")] public void DataPortalBrokerTests() { ApplicationContext.GlobalContext.Clear(); Csla.Server.DataPortalBroker.DataPortalServer = new CustomDataPortalServer(); try { var single = Csla.Test.DataPortalTest.Single.NewObject(); Assert.AreEqual(ApplicationContext.GlobalContext["Single"], "Created"); Assert.AreEqual(ApplicationContext.GlobalContext["CustomDataPortalServer"], "Create Called"); ApplicationContext.GlobalContext.Clear(); single.Save(); Assert.AreEqual(ApplicationContext.GlobalContext["Single"], "Inserted"); Assert.AreEqual(ApplicationContext.GlobalContext["CustomDataPortalServer"], "Update Called"); ApplicationContext.GlobalContext.Clear(); single = Csla.Test.DataPortalTest.Single.GetObject(1); Assert.AreEqual(ApplicationContext.GlobalContext["Single"], "Fetched"); Assert.AreEqual(ApplicationContext.GlobalContext["CustomDataPortalServer"], "Fetch Called"); ApplicationContext.GlobalContext.Clear(); single.Save(); Assert.AreEqual(ApplicationContext.GlobalContext["Single"], "Updated"); Assert.AreEqual(ApplicationContext.GlobalContext["CustomDataPortalServer"], "Update Called"); ApplicationContext.GlobalContext.Clear(); Csla.Test.DataPortalTest.Single.DeleteObject(1); Assert.AreEqual(ApplicationContext.GlobalContext["Single"], "Deleted"); Assert.AreEqual(ApplicationContext.GlobalContext["CustomDataPortalServer"], "Delete Called"); } finally { ApplicationContext.GlobalContext.Clear(); Csla.Server.DataPortalBroker.DataPortalServer = null; } } [TestMethod] [TestCategory("SkipWhenLiveUnitTesting")] public void CallDataPortalOverrides() { Csla.ApplicationContext.GlobalContext.Clear(); ParentEntity parent = ParentEntity.NewParentEntity(); parent.Data = "something"; Assert.AreEqual(false, parent.IsDeleted); Assert.AreEqual(true, parent.IsValid); Assert.AreEqual(true, parent.IsNew); Assert.AreEqual(true, parent.IsDirty); Assert.AreEqual(true, parent.IsSavable); parent = parent.Save(); Assert.AreEqual("Inserted", Csla.ApplicationContext.GlobalContext["ParentEntity"]); Assert.AreEqual(false, parent.IsDeleted); Assert.AreEqual(true, parent.IsValid); Assert.AreEqual(false, parent.IsNew); Assert.AreEqual(false, parent.IsDirty); Assert.AreEqual(false, parent.IsSavable); parent.Data = "something new"; Assert.AreEqual(false, parent.IsDeleted); Assert.AreEqual(true, parent.IsValid); Assert.AreEqual(false, parent.IsNew); Assert.AreEqual(true, parent.IsDirty); Assert.AreEqual(true, parent.IsSavable); parent = parent.Save(); Assert.AreEqual("Updated", Csla.ApplicationContext.GlobalContext["ParentEntity"]); parent.Delete(); Assert.AreEqual(true, parent.IsDeleted); parent = parent.Save(); Assert.AreEqual("Deleted Self", Csla.ApplicationContext.GlobalContext["ParentEntity"]); ParentEntity.DeleteParentEntity(33); Assert.AreEqual("Deleted", Csla.ApplicationContext.GlobalContext["ParentEntity"]); Assert.AreEqual(false, parent.IsDeleted); Assert.AreEqual(true, parent.IsValid); Assert.AreEqual(true, parent.IsNew); Assert.AreEqual(true, parent.IsDirty); Assert.AreEqual(true, parent.IsSavable); ParentEntity.GetParentEntity(33); Assert.AreEqual("Fetched", Csla.ApplicationContext.GlobalContext["ParentEntity"]); } private void ClientPortal_DataPortalInvoke(DataPortalEventArgs obj) { ApplicationContext.GlobalContext["dpinvoke"] = true; } private void ClientPortal_DataPortalInvokeComplete(DataPortalEventArgs obj) { ApplicationContext.GlobalContext["dpinvokecomplete"] = true; } } [Serializable] public class EncapsulatedBusy : BusinessBase<EncapsulatedBusy> { protected override void DataPortal_Create() { base.DataPortal_Create(); MarkBusy(); } private void DataPortal_Fetch() { MarkBusy(); } } [Serializable] [Csla.Server.ObjectFactory(typeof(FactoryBusyFactory))] public class FactoryBusy : BusinessBase<FactoryBusy> { public void MarkObjectBusy() { MarkBusy(); } } public class FactoryBusyFactory : Csla.Server.ObjectFactory { public FactoryBusy Fetch() { var obj = new FactoryBusy(); MarkOld(obj); obj.MarkObjectBusy(); return obj; } } }
#if !DISABLE_PLAYFABCLIENT_API using PlayFab.ClientModels; namespace PlayFab.Events { public partial class PlayFabEvents { public event PlayFabResultEvent<LoginResult> OnLoginResultEvent; public event PlayFabRequestEvent<AcceptTradeRequest> OnAcceptTradeRequestEvent; public event PlayFabResultEvent<AcceptTradeResponse> OnAcceptTradeResultEvent; public event PlayFabRequestEvent<AddFriendRequest> OnAddFriendRequestEvent; public event PlayFabResultEvent<AddFriendResult> OnAddFriendResultEvent; public event PlayFabRequestEvent<AddGenericIDRequest> OnAddGenericIDRequestEvent; public event PlayFabResultEvent<AddGenericIDResult> OnAddGenericIDResultEvent; public event PlayFabRequestEvent<AddOrUpdateContactEmailRequest> OnAddOrUpdateContactEmailRequestEvent; public event PlayFabResultEvent<AddOrUpdateContactEmailResult> OnAddOrUpdateContactEmailResultEvent; public event PlayFabRequestEvent<AddSharedGroupMembersRequest> OnAddSharedGroupMembersRequestEvent; public event PlayFabResultEvent<AddSharedGroupMembersResult> OnAddSharedGroupMembersResultEvent; public event PlayFabRequestEvent<AddUsernamePasswordRequest> OnAddUsernamePasswordRequestEvent; public event PlayFabResultEvent<AddUsernamePasswordResult> OnAddUsernamePasswordResultEvent; public event PlayFabRequestEvent<AddUserVirtualCurrencyRequest> OnAddUserVirtualCurrencyRequestEvent; public event PlayFabResultEvent<ModifyUserVirtualCurrencyResult> OnAddUserVirtualCurrencyResultEvent; public event PlayFabRequestEvent<AndroidDevicePushNotificationRegistrationRequest> OnAndroidDevicePushNotificationRegistrationRequestEvent; public event PlayFabResultEvent<AndroidDevicePushNotificationRegistrationResult> OnAndroidDevicePushNotificationRegistrationResultEvent; public event PlayFabRequestEvent<AttributeInstallRequest> OnAttributeInstallRequestEvent; public event PlayFabResultEvent<AttributeInstallResult> OnAttributeInstallResultEvent; public event PlayFabRequestEvent<CancelTradeRequest> OnCancelTradeRequestEvent; public event PlayFabResultEvent<CancelTradeResponse> OnCancelTradeResultEvent; public event PlayFabRequestEvent<ConfirmPurchaseRequest> OnConfirmPurchaseRequestEvent; public event PlayFabResultEvent<ConfirmPurchaseResult> OnConfirmPurchaseResultEvent; public event PlayFabRequestEvent<ConsumeItemRequest> OnConsumeItemRequestEvent; public event PlayFabResultEvent<ConsumeItemResult> OnConsumeItemResultEvent; public event PlayFabRequestEvent<ConsumePSNEntitlementsRequest> OnConsumePSNEntitlementsRequestEvent; public event PlayFabResultEvent<ConsumePSNEntitlementsResult> OnConsumePSNEntitlementsResultEvent; public event PlayFabRequestEvent<ConsumeXboxEntitlementsRequest> OnConsumeXboxEntitlementsRequestEvent; public event PlayFabResultEvent<ConsumeXboxEntitlementsResult> OnConsumeXboxEntitlementsResultEvent; public event PlayFabRequestEvent<CreateSharedGroupRequest> OnCreateSharedGroupRequestEvent; public event PlayFabResultEvent<CreateSharedGroupResult> OnCreateSharedGroupResultEvent; public event PlayFabRequestEvent<ExecuteCloudScriptRequest> OnExecuteCloudScriptRequestEvent; public event PlayFabResultEvent<ExecuteCloudScriptResult> OnExecuteCloudScriptResultEvent; public event PlayFabRequestEvent<GetAccountInfoRequest> OnGetAccountInfoRequestEvent; public event PlayFabResultEvent<GetAccountInfoResult> OnGetAccountInfoResultEvent; public event PlayFabRequestEvent<ListUsersCharactersRequest> OnGetAllUsersCharactersRequestEvent; public event PlayFabResultEvent<ListUsersCharactersResult> OnGetAllUsersCharactersResultEvent; public event PlayFabRequestEvent<GetCatalogItemsRequest> OnGetCatalogItemsRequestEvent; public event PlayFabResultEvent<GetCatalogItemsResult> OnGetCatalogItemsResultEvent; public event PlayFabRequestEvent<GetCharacterDataRequest> OnGetCharacterDataRequestEvent; public event PlayFabResultEvent<GetCharacterDataResult> OnGetCharacterDataResultEvent; public event PlayFabRequestEvent<GetCharacterInventoryRequest> OnGetCharacterInventoryRequestEvent; public event PlayFabResultEvent<GetCharacterInventoryResult> OnGetCharacterInventoryResultEvent; public event PlayFabRequestEvent<GetCharacterLeaderboardRequest> OnGetCharacterLeaderboardRequestEvent; public event PlayFabResultEvent<GetCharacterLeaderboardResult> OnGetCharacterLeaderboardResultEvent; public event PlayFabRequestEvent<GetCharacterDataRequest> OnGetCharacterReadOnlyDataRequestEvent; public event PlayFabResultEvent<GetCharacterDataResult> OnGetCharacterReadOnlyDataResultEvent; public event PlayFabRequestEvent<GetCharacterStatisticsRequest> OnGetCharacterStatisticsRequestEvent; public event PlayFabResultEvent<GetCharacterStatisticsResult> OnGetCharacterStatisticsResultEvent; public event PlayFabRequestEvent<GetContentDownloadUrlRequest> OnGetContentDownloadUrlRequestEvent; public event PlayFabResultEvent<GetContentDownloadUrlResult> OnGetContentDownloadUrlResultEvent; public event PlayFabRequestEvent<CurrentGamesRequest> OnGetCurrentGamesRequestEvent; public event PlayFabResultEvent<CurrentGamesResult> OnGetCurrentGamesResultEvent; public event PlayFabRequestEvent<GetFriendLeaderboardRequest> OnGetFriendLeaderboardRequestEvent; public event PlayFabResultEvent<GetLeaderboardResult> OnGetFriendLeaderboardResultEvent; public event PlayFabRequestEvent<GetFriendLeaderboardAroundPlayerRequest> OnGetFriendLeaderboardAroundPlayerRequestEvent; public event PlayFabResultEvent<GetFriendLeaderboardAroundPlayerResult> OnGetFriendLeaderboardAroundPlayerResultEvent; public event PlayFabRequestEvent<GetFriendsListRequest> OnGetFriendsListRequestEvent; public event PlayFabResultEvent<GetFriendsListResult> OnGetFriendsListResultEvent; public event PlayFabRequestEvent<GameServerRegionsRequest> OnGetGameServerRegionsRequestEvent; public event PlayFabResultEvent<GameServerRegionsResult> OnGetGameServerRegionsResultEvent; public event PlayFabRequestEvent<GetLeaderboardRequest> OnGetLeaderboardRequestEvent; public event PlayFabResultEvent<GetLeaderboardResult> OnGetLeaderboardResultEvent; public event PlayFabRequestEvent<GetLeaderboardAroundCharacterRequest> OnGetLeaderboardAroundCharacterRequestEvent; public event PlayFabResultEvent<GetLeaderboardAroundCharacterResult> OnGetLeaderboardAroundCharacterResultEvent; public event PlayFabRequestEvent<GetLeaderboardAroundPlayerRequest> OnGetLeaderboardAroundPlayerRequestEvent; public event PlayFabResultEvent<GetLeaderboardAroundPlayerResult> OnGetLeaderboardAroundPlayerResultEvent; public event PlayFabRequestEvent<GetLeaderboardForUsersCharactersRequest> OnGetLeaderboardForUserCharactersRequestEvent; public event PlayFabResultEvent<GetLeaderboardForUsersCharactersResult> OnGetLeaderboardForUserCharactersResultEvent; public event PlayFabRequestEvent<GetPaymentTokenRequest> OnGetPaymentTokenRequestEvent; public event PlayFabResultEvent<GetPaymentTokenResult> OnGetPaymentTokenResultEvent; public event PlayFabRequestEvent<GetPhotonAuthenticationTokenRequest> OnGetPhotonAuthenticationTokenRequestEvent; public event PlayFabResultEvent<GetPhotonAuthenticationTokenResult> OnGetPhotonAuthenticationTokenResultEvent; public event PlayFabRequestEvent<GetPlayerCombinedInfoRequest> OnGetPlayerCombinedInfoRequestEvent; public event PlayFabResultEvent<GetPlayerCombinedInfoResult> OnGetPlayerCombinedInfoResultEvent; public event PlayFabRequestEvent<GetPlayerProfileRequest> OnGetPlayerProfileRequestEvent; public event PlayFabResultEvent<GetPlayerProfileResult> OnGetPlayerProfileResultEvent; public event PlayFabRequestEvent<GetPlayerSegmentsRequest> OnGetPlayerSegmentsRequestEvent; public event PlayFabResultEvent<GetPlayerSegmentsResult> OnGetPlayerSegmentsResultEvent; public event PlayFabRequestEvent<GetPlayerStatisticsRequest> OnGetPlayerStatisticsRequestEvent; public event PlayFabResultEvent<GetPlayerStatisticsResult> OnGetPlayerStatisticsResultEvent; public event PlayFabRequestEvent<GetPlayerStatisticVersionsRequest> OnGetPlayerStatisticVersionsRequestEvent; public event PlayFabResultEvent<GetPlayerStatisticVersionsResult> OnGetPlayerStatisticVersionsResultEvent; public event PlayFabRequestEvent<GetPlayerTagsRequest> OnGetPlayerTagsRequestEvent; public event PlayFabResultEvent<GetPlayerTagsResult> OnGetPlayerTagsResultEvent; public event PlayFabRequestEvent<GetPlayerTradesRequest> OnGetPlayerTradesRequestEvent; public event PlayFabResultEvent<GetPlayerTradesResponse> OnGetPlayerTradesResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromFacebookIDsRequest> OnGetPlayFabIDsFromFacebookIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromFacebookIDsResult> OnGetPlayFabIDsFromFacebookIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromFacebookInstantGamesIdsRequest> OnGetPlayFabIDsFromFacebookInstantGamesIdsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromFacebookInstantGamesIdsResult> OnGetPlayFabIDsFromFacebookInstantGamesIdsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromGameCenterIDsRequest> OnGetPlayFabIDsFromGameCenterIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromGameCenterIDsResult> OnGetPlayFabIDsFromGameCenterIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromGenericIDsRequest> OnGetPlayFabIDsFromGenericIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromGenericIDsResult> OnGetPlayFabIDsFromGenericIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromGoogleIDsRequest> OnGetPlayFabIDsFromGoogleIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromGoogleIDsResult> OnGetPlayFabIDsFromGoogleIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromKongregateIDsRequest> OnGetPlayFabIDsFromKongregateIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromKongregateIDsResult> OnGetPlayFabIDsFromKongregateIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromNintendoSwitchDeviceIdsRequest> OnGetPlayFabIDsFromNintendoSwitchDeviceIdsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromNintendoSwitchDeviceIdsResult> OnGetPlayFabIDsFromNintendoSwitchDeviceIdsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromPSNAccountIDsRequest> OnGetPlayFabIDsFromPSNAccountIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromPSNAccountIDsResult> OnGetPlayFabIDsFromPSNAccountIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromSteamIDsRequest> OnGetPlayFabIDsFromSteamIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromSteamIDsResult> OnGetPlayFabIDsFromSteamIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromTwitchIDsRequest> OnGetPlayFabIDsFromTwitchIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromTwitchIDsResult> OnGetPlayFabIDsFromTwitchIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromXboxLiveIDsRequest> OnGetPlayFabIDsFromXboxLiveIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromXboxLiveIDsResult> OnGetPlayFabIDsFromXboxLiveIDsResultEvent; public event PlayFabRequestEvent<GetPublisherDataRequest> OnGetPublisherDataRequestEvent; public event PlayFabResultEvent<GetPublisherDataResult> OnGetPublisherDataResultEvent; public event PlayFabRequestEvent<GetPurchaseRequest> OnGetPurchaseRequestEvent; public event PlayFabResultEvent<GetPurchaseResult> OnGetPurchaseResultEvent; public event PlayFabRequestEvent<GetSharedGroupDataRequest> OnGetSharedGroupDataRequestEvent; public event PlayFabResultEvent<GetSharedGroupDataResult> OnGetSharedGroupDataResultEvent; public event PlayFabRequestEvent<GetStoreItemsRequest> OnGetStoreItemsRequestEvent; public event PlayFabResultEvent<GetStoreItemsResult> OnGetStoreItemsResultEvent; public event PlayFabRequestEvent<GetTimeRequest> OnGetTimeRequestEvent; public event PlayFabResultEvent<GetTimeResult> OnGetTimeResultEvent; public event PlayFabRequestEvent<GetTitleDataRequest> OnGetTitleDataRequestEvent; public event PlayFabResultEvent<GetTitleDataResult> OnGetTitleDataResultEvent; public event PlayFabRequestEvent<GetTitleNewsRequest> OnGetTitleNewsRequestEvent; public event PlayFabResultEvent<GetTitleNewsResult> OnGetTitleNewsResultEvent; public event PlayFabRequestEvent<GetTitlePublicKeyRequest> OnGetTitlePublicKeyRequestEvent; public event PlayFabResultEvent<GetTitlePublicKeyResult> OnGetTitlePublicKeyResultEvent; public event PlayFabRequestEvent<GetTradeStatusRequest> OnGetTradeStatusRequestEvent; public event PlayFabResultEvent<GetTradeStatusResponse> OnGetTradeStatusResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserDataResultEvent; public event PlayFabRequestEvent<GetUserInventoryRequest> OnGetUserInventoryRequestEvent; public event PlayFabResultEvent<GetUserInventoryResult> OnGetUserInventoryResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserPublisherDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserPublisherDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserPublisherReadOnlyDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserPublisherReadOnlyDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserReadOnlyDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserReadOnlyDataResultEvent; public event PlayFabRequestEvent<GetWindowsHelloChallengeRequest> OnGetWindowsHelloChallengeRequestEvent; public event PlayFabResultEvent<GetWindowsHelloChallengeResponse> OnGetWindowsHelloChallengeResultEvent; public event PlayFabRequestEvent<GrantCharacterToUserRequest> OnGrantCharacterToUserRequestEvent; public event PlayFabResultEvent<GrantCharacterToUserResult> OnGrantCharacterToUserResultEvent; public event PlayFabRequestEvent<LinkAndroidDeviceIDRequest> OnLinkAndroidDeviceIDRequestEvent; public event PlayFabResultEvent<LinkAndroidDeviceIDResult> OnLinkAndroidDeviceIDResultEvent; public event PlayFabRequestEvent<LinkCustomIDRequest> OnLinkCustomIDRequestEvent; public event PlayFabResultEvent<LinkCustomIDResult> OnLinkCustomIDResultEvent; public event PlayFabRequestEvent<LinkFacebookAccountRequest> OnLinkFacebookAccountRequestEvent; public event PlayFabResultEvent<LinkFacebookAccountResult> OnLinkFacebookAccountResultEvent; public event PlayFabRequestEvent<LinkFacebookInstantGamesIdRequest> OnLinkFacebookInstantGamesIdRequestEvent; public event PlayFabResultEvent<LinkFacebookInstantGamesIdResult> OnLinkFacebookInstantGamesIdResultEvent; public event PlayFabRequestEvent<LinkGameCenterAccountRequest> OnLinkGameCenterAccountRequestEvent; public event PlayFabResultEvent<LinkGameCenterAccountResult> OnLinkGameCenterAccountResultEvent; public event PlayFabRequestEvent<LinkGoogleAccountRequest> OnLinkGoogleAccountRequestEvent; public event PlayFabResultEvent<LinkGoogleAccountResult> OnLinkGoogleAccountResultEvent; public event PlayFabRequestEvent<LinkIOSDeviceIDRequest> OnLinkIOSDeviceIDRequestEvent; public event PlayFabResultEvent<LinkIOSDeviceIDResult> OnLinkIOSDeviceIDResultEvent; public event PlayFabRequestEvent<LinkKongregateAccountRequest> OnLinkKongregateRequestEvent; public event PlayFabResultEvent<LinkKongregateAccountResult> OnLinkKongregateResultEvent; public event PlayFabRequestEvent<LinkNintendoSwitchDeviceIdRequest> OnLinkNintendoSwitchDeviceIdRequestEvent; public event PlayFabResultEvent<LinkNintendoSwitchDeviceIdResult> OnLinkNintendoSwitchDeviceIdResultEvent; public event PlayFabRequestEvent<LinkOpenIdConnectRequest> OnLinkOpenIdConnectRequestEvent; public event PlayFabResultEvent<EmptyResult> OnLinkOpenIdConnectResultEvent; public event PlayFabRequestEvent<LinkPSNAccountRequest> OnLinkPSNAccountRequestEvent; public event PlayFabResultEvent<LinkPSNAccountResult> OnLinkPSNAccountResultEvent; public event PlayFabRequestEvent<LinkSteamAccountRequest> OnLinkSteamAccountRequestEvent; public event PlayFabResultEvent<LinkSteamAccountResult> OnLinkSteamAccountResultEvent; public event PlayFabRequestEvent<LinkTwitchAccountRequest> OnLinkTwitchRequestEvent; public event PlayFabResultEvent<LinkTwitchAccountResult> OnLinkTwitchResultEvent; public event PlayFabRequestEvent<LinkWindowsHelloAccountRequest> OnLinkWindowsHelloRequestEvent; public event PlayFabResultEvent<LinkWindowsHelloAccountResponse> OnLinkWindowsHelloResultEvent; public event PlayFabRequestEvent<LinkXboxAccountRequest> OnLinkXboxAccountRequestEvent; public event PlayFabResultEvent<LinkXboxAccountResult> OnLinkXboxAccountResultEvent; public event PlayFabRequestEvent<LoginWithAndroidDeviceIDRequest> OnLoginWithAndroidDeviceIDRequestEvent; public event PlayFabRequestEvent<LoginWithCustomIDRequest> OnLoginWithCustomIDRequestEvent; public event PlayFabRequestEvent<LoginWithEmailAddressRequest> OnLoginWithEmailAddressRequestEvent; public event PlayFabRequestEvent<LoginWithFacebookRequest> OnLoginWithFacebookRequestEvent; public event PlayFabRequestEvent<LoginWithFacebookInstantGamesIdRequest> OnLoginWithFacebookInstantGamesIdRequestEvent; public event PlayFabRequestEvent<LoginWithGameCenterRequest> OnLoginWithGameCenterRequestEvent; public event PlayFabRequestEvent<LoginWithGoogleAccountRequest> OnLoginWithGoogleAccountRequestEvent; public event PlayFabRequestEvent<LoginWithIOSDeviceIDRequest> OnLoginWithIOSDeviceIDRequestEvent; public event PlayFabRequestEvent<LoginWithKongregateRequest> OnLoginWithKongregateRequestEvent; public event PlayFabRequestEvent<LoginWithNintendoSwitchDeviceIdRequest> OnLoginWithNintendoSwitchDeviceIdRequestEvent; public event PlayFabRequestEvent<LoginWithOpenIdConnectRequest> OnLoginWithOpenIdConnectRequestEvent; public event PlayFabRequestEvent<LoginWithPlayFabRequest> OnLoginWithPlayFabRequestEvent; public event PlayFabRequestEvent<LoginWithPSNRequest> OnLoginWithPSNRequestEvent; public event PlayFabRequestEvent<LoginWithSteamRequest> OnLoginWithSteamRequestEvent; public event PlayFabRequestEvent<LoginWithTwitchRequest> OnLoginWithTwitchRequestEvent; public event PlayFabRequestEvent<LoginWithWindowsHelloRequest> OnLoginWithWindowsHelloRequestEvent; public event PlayFabRequestEvent<LoginWithXboxRequest> OnLoginWithXboxRequestEvent; public event PlayFabRequestEvent<MatchmakeRequest> OnMatchmakeRequestEvent; public event PlayFabResultEvent<MatchmakeResult> OnMatchmakeResultEvent; public event PlayFabRequestEvent<OpenTradeRequest> OnOpenTradeRequestEvent; public event PlayFabResultEvent<OpenTradeResponse> OnOpenTradeResultEvent; public event PlayFabRequestEvent<PayForPurchaseRequest> OnPayForPurchaseRequestEvent; public event PlayFabResultEvent<PayForPurchaseResult> OnPayForPurchaseResultEvent; public event PlayFabRequestEvent<PurchaseItemRequest> OnPurchaseItemRequestEvent; public event PlayFabResultEvent<PurchaseItemResult> OnPurchaseItemResultEvent; public event PlayFabRequestEvent<RedeemCouponRequest> OnRedeemCouponRequestEvent; public event PlayFabResultEvent<RedeemCouponResult> OnRedeemCouponResultEvent; public event PlayFabRequestEvent<RefreshPSNAuthTokenRequest> OnRefreshPSNAuthTokenRequestEvent; public event PlayFabResultEvent<EmptyResponse> OnRefreshPSNAuthTokenResultEvent; public event PlayFabRequestEvent<RegisterForIOSPushNotificationRequest> OnRegisterForIOSPushNotificationRequestEvent; public event PlayFabResultEvent<RegisterForIOSPushNotificationResult> OnRegisterForIOSPushNotificationResultEvent; public event PlayFabRequestEvent<RegisterPlayFabUserRequest> OnRegisterPlayFabUserRequestEvent; public event PlayFabResultEvent<RegisterPlayFabUserResult> OnRegisterPlayFabUserResultEvent; public event PlayFabRequestEvent<RegisterWithWindowsHelloRequest> OnRegisterWithWindowsHelloRequestEvent; public event PlayFabRequestEvent<RemoveContactEmailRequest> OnRemoveContactEmailRequestEvent; public event PlayFabResultEvent<RemoveContactEmailResult> OnRemoveContactEmailResultEvent; public event PlayFabRequestEvent<RemoveFriendRequest> OnRemoveFriendRequestEvent; public event PlayFabResultEvent<RemoveFriendResult> OnRemoveFriendResultEvent; public event PlayFabRequestEvent<RemoveGenericIDRequest> OnRemoveGenericIDRequestEvent; public event PlayFabResultEvent<RemoveGenericIDResult> OnRemoveGenericIDResultEvent; public event PlayFabRequestEvent<RemoveSharedGroupMembersRequest> OnRemoveSharedGroupMembersRequestEvent; public event PlayFabResultEvent<RemoveSharedGroupMembersResult> OnRemoveSharedGroupMembersResultEvent; public event PlayFabRequestEvent<DeviceInfoRequest> OnReportDeviceInfoRequestEvent; public event PlayFabResultEvent<EmptyResponse> OnReportDeviceInfoResultEvent; public event PlayFabRequestEvent<ReportPlayerClientRequest> OnReportPlayerRequestEvent; public event PlayFabResultEvent<ReportPlayerClientResult> OnReportPlayerResultEvent; public event PlayFabRequestEvent<RestoreIOSPurchasesRequest> OnRestoreIOSPurchasesRequestEvent; public event PlayFabResultEvent<RestoreIOSPurchasesResult> OnRestoreIOSPurchasesResultEvent; public event PlayFabRequestEvent<SendAccountRecoveryEmailRequest> OnSendAccountRecoveryEmailRequestEvent; public event PlayFabResultEvent<SendAccountRecoveryEmailResult> OnSendAccountRecoveryEmailResultEvent; public event PlayFabRequestEvent<SetFriendTagsRequest> OnSetFriendTagsRequestEvent; public event PlayFabResultEvent<SetFriendTagsResult> OnSetFriendTagsResultEvent; public event PlayFabRequestEvent<SetPlayerSecretRequest> OnSetPlayerSecretRequestEvent; public event PlayFabResultEvent<SetPlayerSecretResult> OnSetPlayerSecretResultEvent; public event PlayFabRequestEvent<StartGameRequest> OnStartGameRequestEvent; public event PlayFabResultEvent<StartGameResult> OnStartGameResultEvent; public event PlayFabRequestEvent<StartPurchaseRequest> OnStartPurchaseRequestEvent; public event PlayFabResultEvent<StartPurchaseResult> OnStartPurchaseResultEvent; public event PlayFabRequestEvent<SubtractUserVirtualCurrencyRequest> OnSubtractUserVirtualCurrencyRequestEvent; public event PlayFabResultEvent<ModifyUserVirtualCurrencyResult> OnSubtractUserVirtualCurrencyResultEvent; public event PlayFabRequestEvent<UnlinkAndroidDeviceIDRequest> OnUnlinkAndroidDeviceIDRequestEvent; public event PlayFabResultEvent<UnlinkAndroidDeviceIDResult> OnUnlinkAndroidDeviceIDResultEvent; public event PlayFabRequestEvent<UnlinkCustomIDRequest> OnUnlinkCustomIDRequestEvent; public event PlayFabResultEvent<UnlinkCustomIDResult> OnUnlinkCustomIDResultEvent; public event PlayFabRequestEvent<UnlinkFacebookAccountRequest> OnUnlinkFacebookAccountRequestEvent; public event PlayFabResultEvent<UnlinkFacebookAccountResult> OnUnlinkFacebookAccountResultEvent; public event PlayFabRequestEvent<UnlinkFacebookInstantGamesIdRequest> OnUnlinkFacebookInstantGamesIdRequestEvent; public event PlayFabResultEvent<UnlinkFacebookInstantGamesIdResult> OnUnlinkFacebookInstantGamesIdResultEvent; public event PlayFabRequestEvent<UnlinkGameCenterAccountRequest> OnUnlinkGameCenterAccountRequestEvent; public event PlayFabResultEvent<UnlinkGameCenterAccountResult> OnUnlinkGameCenterAccountResultEvent; public event PlayFabRequestEvent<UnlinkGoogleAccountRequest> OnUnlinkGoogleAccountRequestEvent; public event PlayFabResultEvent<UnlinkGoogleAccountResult> OnUnlinkGoogleAccountResultEvent; public event PlayFabRequestEvent<UnlinkIOSDeviceIDRequest> OnUnlinkIOSDeviceIDRequestEvent; public event PlayFabResultEvent<UnlinkIOSDeviceIDResult> OnUnlinkIOSDeviceIDResultEvent; public event PlayFabRequestEvent<UnlinkKongregateAccountRequest> OnUnlinkKongregateRequestEvent; public event PlayFabResultEvent<UnlinkKongregateAccountResult> OnUnlinkKongregateResultEvent; public event PlayFabRequestEvent<UnlinkNintendoSwitchDeviceIdRequest> OnUnlinkNintendoSwitchDeviceIdRequestEvent; public event PlayFabResultEvent<UnlinkNintendoSwitchDeviceIdResult> OnUnlinkNintendoSwitchDeviceIdResultEvent; public event PlayFabRequestEvent<UninkOpenIdConnectRequest> OnUnlinkOpenIdConnectRequestEvent; public event PlayFabResultEvent<EmptyResponse> OnUnlinkOpenIdConnectResultEvent; public event PlayFabRequestEvent<UnlinkPSNAccountRequest> OnUnlinkPSNAccountRequestEvent; public event PlayFabResultEvent<UnlinkPSNAccountResult> OnUnlinkPSNAccountResultEvent; public event PlayFabRequestEvent<UnlinkSteamAccountRequest> OnUnlinkSteamAccountRequestEvent; public event PlayFabResultEvent<UnlinkSteamAccountResult> OnUnlinkSteamAccountResultEvent; public event PlayFabRequestEvent<UnlinkTwitchAccountRequest> OnUnlinkTwitchRequestEvent; public event PlayFabResultEvent<UnlinkTwitchAccountResult> OnUnlinkTwitchResultEvent; public event PlayFabRequestEvent<UnlinkWindowsHelloAccountRequest> OnUnlinkWindowsHelloRequestEvent; public event PlayFabResultEvent<UnlinkWindowsHelloAccountResponse> OnUnlinkWindowsHelloResultEvent; public event PlayFabRequestEvent<UnlinkXboxAccountRequest> OnUnlinkXboxAccountRequestEvent; public event PlayFabResultEvent<UnlinkXboxAccountResult> OnUnlinkXboxAccountResultEvent; public event PlayFabRequestEvent<UnlockContainerInstanceRequest> OnUnlockContainerInstanceRequestEvent; public event PlayFabResultEvent<UnlockContainerItemResult> OnUnlockContainerInstanceResultEvent; public event PlayFabRequestEvent<UnlockContainerItemRequest> OnUnlockContainerItemRequestEvent; public event PlayFabResultEvent<UnlockContainerItemResult> OnUnlockContainerItemResultEvent; public event PlayFabRequestEvent<UpdateAvatarUrlRequest> OnUpdateAvatarUrlRequestEvent; public event PlayFabResultEvent<EmptyResponse> OnUpdateAvatarUrlResultEvent; public event PlayFabRequestEvent<UpdateCharacterDataRequest> OnUpdateCharacterDataRequestEvent; public event PlayFabResultEvent<UpdateCharacterDataResult> OnUpdateCharacterDataResultEvent; public event PlayFabRequestEvent<UpdateCharacterStatisticsRequest> OnUpdateCharacterStatisticsRequestEvent; public event PlayFabResultEvent<UpdateCharacterStatisticsResult> OnUpdateCharacterStatisticsResultEvent; public event PlayFabRequestEvent<UpdatePlayerStatisticsRequest> OnUpdatePlayerStatisticsRequestEvent; public event PlayFabResultEvent<UpdatePlayerStatisticsResult> OnUpdatePlayerStatisticsResultEvent; public event PlayFabRequestEvent<UpdateSharedGroupDataRequest> OnUpdateSharedGroupDataRequestEvent; public event PlayFabResultEvent<UpdateSharedGroupDataResult> OnUpdateSharedGroupDataResultEvent; public event PlayFabRequestEvent<UpdateUserDataRequest> OnUpdateUserDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnUpdateUserDataResultEvent; public event PlayFabRequestEvent<UpdateUserDataRequest> OnUpdateUserPublisherDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnUpdateUserPublisherDataResultEvent; public event PlayFabRequestEvent<UpdateUserTitleDisplayNameRequest> OnUpdateUserTitleDisplayNameRequestEvent; public event PlayFabResultEvent<UpdateUserTitleDisplayNameResult> OnUpdateUserTitleDisplayNameResultEvent; public event PlayFabRequestEvent<ValidateAmazonReceiptRequest> OnValidateAmazonIAPReceiptRequestEvent; public event PlayFabResultEvent<ValidateAmazonReceiptResult> OnValidateAmazonIAPReceiptResultEvent; public event PlayFabRequestEvent<ValidateGooglePlayPurchaseRequest> OnValidateGooglePlayPurchaseRequestEvent; public event PlayFabResultEvent<ValidateGooglePlayPurchaseResult> OnValidateGooglePlayPurchaseResultEvent; public event PlayFabRequestEvent<ValidateIOSReceiptRequest> OnValidateIOSReceiptRequestEvent; public event PlayFabResultEvent<ValidateIOSReceiptResult> OnValidateIOSReceiptResultEvent; public event PlayFabRequestEvent<ValidateWindowsReceiptRequest> OnValidateWindowsStoreReceiptRequestEvent; public event PlayFabResultEvent<ValidateWindowsReceiptResult> OnValidateWindowsStoreReceiptResultEvent; public event PlayFabRequestEvent<WriteClientCharacterEventRequest> OnWriteCharacterEventRequestEvent; public event PlayFabResultEvent<WriteEventResponse> OnWriteCharacterEventResultEvent; public event PlayFabRequestEvent<WriteClientPlayerEventRequest> OnWritePlayerEventRequestEvent; public event PlayFabResultEvent<WriteEventResponse> OnWritePlayerEventResultEvent; public event PlayFabRequestEvent<WriteTitleEventRequest> OnWriteTitleEventRequestEvent; public event PlayFabResultEvent<WriteEventResponse> OnWriteTitleEventResultEvent; } } #endif
#region License // Copyright (c) 2007 James Newton-King // // 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 // UNITY flag based on https://github.com/jilleJr/Newtonsoft.Json-for-Unity #if !(NET20 || NET35 || UNITY) using System.Collections.Generic; using System.Linq; using System.Text; using System; using System.Linq.Expressions; using System.Reflection; using Microsoft.Identity.Json.Serialization; namespace Microsoft.Identity.Json.Utilities { internal class ExpressionReflectionDelegateFactory : ReflectionDelegateFactory { private static readonly ExpressionReflectionDelegateFactory _instance = new ExpressionReflectionDelegateFactory(); internal static ReflectionDelegateFactory Instance => _instance; public override ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method) { ValidationUtils.ArgumentNotNull(method, nameof(method)); Type type = typeof(object); ParameterExpression argsParameterExpression = Expression.Parameter(typeof(object[]), "args"); Expression callExpression = BuildMethodCall(method, type, null, argsParameterExpression); LambdaExpression lambdaExpression = Expression.Lambda(typeof(ObjectConstructor<object>), callExpression, argsParameterExpression); ObjectConstructor<object> compiled = (ObjectConstructor<object>)lambdaExpression.Compile(); return compiled; } public override MethodCall<T, object> CreateMethodCall<T>(MethodBase method) { ValidationUtils.ArgumentNotNull(method, nameof(method)); Type type = typeof(object); ParameterExpression targetParameterExpression = Expression.Parameter(type, "target"); ParameterExpression argsParameterExpression = Expression.Parameter(typeof(object[]), "args"); Expression callExpression = BuildMethodCall(method, type, targetParameterExpression, argsParameterExpression); LambdaExpression lambdaExpression = Expression.Lambda(typeof(MethodCall<T, object>), callExpression, targetParameterExpression, argsParameterExpression); MethodCall<T, object> compiled = (MethodCall<T, object>)lambdaExpression.Compile(); return compiled; } private class ByRefParameter { public Expression Value; public ParameterExpression Variable; public bool IsOut; } private Expression BuildMethodCall(MethodBase method, Type type, ParameterExpression targetParameterExpression, ParameterExpression argsParameterExpression) { ParameterInfo[] parametersInfo = method.GetParameters(); Expression[] argsExpression; IList<ByRefParameter> refParameterMap; if (parametersInfo.Length == 0) { argsExpression = CollectionUtils.ArrayEmpty<Expression>(); refParameterMap = CollectionUtils.ArrayEmpty<ByRefParameter>(); } else { argsExpression = new Expression[parametersInfo.Length]; refParameterMap = new List<ByRefParameter>(); for (int i = 0; i < parametersInfo.Length; i++) { ParameterInfo parameter = parametersInfo[i]; Type parameterType = parameter.ParameterType; bool isByRef = false; if (parameterType.IsByRef) { parameterType = parameterType.GetElementType(); isByRef = true; } Expression indexExpression = Expression.Constant(i); Expression paramAccessorExpression = Expression.ArrayIndex(argsParameterExpression, indexExpression); Expression argExpression = EnsureCastExpression(paramAccessorExpression, parameterType, !isByRef); if (isByRef) { ParameterExpression variable = Expression.Variable(parameterType); refParameterMap.Add(new ByRefParameter {Value = argExpression, Variable = variable, IsOut = parameter.IsOut}); argExpression = variable; } argsExpression[i] = argExpression; } } Expression callExpression; if (method.IsConstructor) { callExpression = Expression.New((ConstructorInfo)method, argsExpression); } else if (method.IsStatic) { callExpression = Expression.Call((MethodInfo)method, argsExpression); } else { Expression readParameter = EnsureCastExpression(targetParameterExpression, method.DeclaringType); callExpression = Expression.Call(readParameter, (MethodInfo)method, argsExpression); } if (method is MethodInfo m) { if (m.ReturnType != typeof(void)) { callExpression = EnsureCastExpression(callExpression, type); } else { callExpression = Expression.Block(callExpression, Expression.Constant(null)); } } else { callExpression = EnsureCastExpression(callExpression, type); } if (refParameterMap.Count > 0) { IList<ParameterExpression> variableExpressions = new List<ParameterExpression>(); IList<Expression> bodyExpressions = new List<Expression>(); foreach (ByRefParameter p in refParameterMap) { if (!p.IsOut) { bodyExpressions.Add(Expression.Assign(p.Variable, p.Value)); } variableExpressions.Add(p.Variable); } bodyExpressions.Add(callExpression); callExpression = Expression.Block(variableExpressions, bodyExpressions); } return callExpression; } public override Func<T> CreateDefaultConstructor<T>(Type type) { ValidationUtils.ArgumentNotNull(type, "type"); // avoid error from expressions compiler because of abstract class if (type.IsAbstract()) { return () => (T)Activator.CreateInstance(type); } try { Type resultType = typeof(T); Expression expression = Expression.New(type); expression = EnsureCastExpression(expression, resultType); LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func<T>), expression); Func<T> compiled = (Func<T>)lambdaExpression.Compile(); return compiled; } catch { // an error can be thrown if constructor is not valid on Win8 // will have INVOCATION_FLAGS_NON_W8P_FX_API invocation flag return () => (T)Activator.CreateInstance(type); } } public override Func<T, object> CreateGet<T>(PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); Type instanceType = typeof(T); Type resultType = typeof(object); ParameterExpression parameterExpression = Expression.Parameter(instanceType, "instance"); Expression resultExpression; MethodInfo getMethod = propertyInfo.GetGetMethod(true); if (getMethod.IsStatic) { resultExpression = Expression.MakeMemberAccess(null, propertyInfo); } else { Expression readParameter = EnsureCastExpression(parameterExpression, propertyInfo.DeclaringType); resultExpression = Expression.MakeMemberAccess(readParameter, propertyInfo); } resultExpression = EnsureCastExpression(resultExpression, resultType); LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func<T, object>), resultExpression, parameterExpression); Func<T, object> compiled = (Func<T, object>)lambdaExpression.Compile(); return compiled; } public override Func<T, object> CreateGet<T>(FieldInfo fieldInfo) { ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); ParameterExpression sourceParameter = Expression.Parameter(typeof(T), "source"); Expression fieldExpression; if (fieldInfo.IsStatic) { fieldExpression = Expression.Field(null, fieldInfo); } else { Expression sourceExpression = EnsureCastExpression(sourceParameter, fieldInfo.DeclaringType); fieldExpression = Expression.Field(sourceExpression, fieldInfo); } fieldExpression = EnsureCastExpression(fieldExpression, typeof(object)); Func<T, object> compiled = Expression.Lambda<Func<T, object>>(fieldExpression, sourceParameter).Compile(); return compiled; } public override Action<T, object> CreateSet<T>(FieldInfo fieldInfo) { ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); // use reflection for structs // expression doesn't correctly set value if (fieldInfo.DeclaringType.IsValueType() || fieldInfo.IsInitOnly) { return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(fieldInfo); } ParameterExpression sourceParameterExpression = Expression.Parameter(typeof(T), "source"); ParameterExpression valueParameterExpression = Expression.Parameter(typeof(object), "value"); Expression fieldExpression; if (fieldInfo.IsStatic) { fieldExpression = Expression.Field(null, fieldInfo); } else { Expression sourceExpression = EnsureCastExpression(sourceParameterExpression, fieldInfo.DeclaringType); fieldExpression = Expression.Field(sourceExpression, fieldInfo); } Expression valueExpression = EnsureCastExpression(valueParameterExpression, fieldExpression.Type); BinaryExpression assignExpression = Expression.Assign(fieldExpression, valueExpression); LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), assignExpression, sourceParameterExpression, valueParameterExpression); Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile(); return compiled; } public override Action<T, object> CreateSet<T>(PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); // use reflection for structs // expression doesn't correctly set value if (propertyInfo.DeclaringType.IsValueType()) { return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(propertyInfo); } Type instanceType = typeof(T); Type valueType = typeof(object); ParameterExpression instanceParameter = Expression.Parameter(instanceType, "instance"); ParameterExpression valueParameter = Expression.Parameter(valueType, "value"); Expression readValueParameter = EnsureCastExpression(valueParameter, propertyInfo.PropertyType); MethodInfo setMethod = propertyInfo.GetSetMethod(true); Expression setExpression; if (setMethod.IsStatic) { setExpression = Expression.Call(setMethod, readValueParameter); } else { Expression readInstanceParameter = EnsureCastExpression(instanceParameter, propertyInfo.DeclaringType); setExpression = Expression.Call(readInstanceParameter, setMethod, readValueParameter); } LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), setExpression, instanceParameter, valueParameter); Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile(); return compiled; } private Expression EnsureCastExpression(Expression expression, Type targetType, bool allowWidening = false) { Type expressionType = expression.Type; // check if a cast or conversion is required if (expressionType == targetType || (!expressionType.IsValueType() && targetType.IsAssignableFrom(expressionType))) { return expression; } if (targetType.IsValueType()) { Expression convert = Expression.Unbox(expression, targetType); if (allowWidening && targetType.IsPrimitive()) { MethodInfo toTargetTypeMethod = typeof(Convert) .GetMethod("To" + targetType.Name, new[] { typeof(object) }); if (toTargetTypeMethod != null) { convert = Expression.Condition( Expression.TypeIs(expression, targetType), convert, Expression.Call(toTargetTypeMethod, expression)); } } return Expression.Condition( Expression.Equal(expression, Expression.Constant(null, typeof(object))), Expression.Default(targetType), convert); } return Expression.Convert(expression, targetType); } } } #endif
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; namespace Orleans.Runtime.Scheduler { [DebuggerDisplay("WorkItemGroup Name={Name} State={state}")] internal class WorkItemGroup : IWorkItem { private enum WorkGroupStatus { Waiting = 0, Runnable = 1, Running = 2, Shutdown = 3 } private readonly ILogger log; private readonly OrleansTaskScheduler masterScheduler; private WorkGroupStatus state; private readonly Object lockable; private readonly Queue<Task> workItems; private long totalItemsEnQueued; // equals total items queued, + 1 private long totalItemsProcessed; private TimeSpan totalQueuingDelay; private Task currentTask; private DateTime currentTaskStarted; private readonly QueueTrackingStatistic queueTracking; private readonly long quantumExpirations; private readonly int workItemGroupStatisticsNumber; private readonly CancellationToken cancellationToken; private readonly SchedulerStatisticsGroup schedulerStatistics; internal ActivationTaskScheduler TaskRunner { get; private set; } public DateTime TimeQueued { get; set; } public TimeSpan TimeSinceQueued { get { return Utils.Since(TimeQueued); } } public ISchedulingContext SchedulingContext { get; set; } public bool IsSystemPriority { get { return SchedulingUtils.IsSystemPriorityContext(SchedulingContext); } } internal bool IsSystemGroup { get { return SchedulingUtils.IsSystemContext(SchedulingContext); } } public string Name { get { return SchedulingContext == null ? "unknown" : SchedulingContext.Name; } } internal int ExternalWorkItemCount { get { lock (lockable) { return WorkItemCount; } } } private Task CurrentTask { get => currentTask; set { currentTask = value; currentTaskStarted = DateTime.UtcNow; } } private int WorkItemCount { get { return workItems.Count; } } internal float AverageQueueLenght { get { return 0; } } internal float NumEnqueuedRequests { get { return 0; } } internal float ArrivalRate { get { return 0; } } private bool IsActive { get { return WorkItemCount != 0; } } // This is the maximum number of work items to be processed in an activation turn. // If this is set to zero or a negative number, then the full work queue is drained (MaxTimePerTurn allowing). private const int MaxWorkItemsPerTurn = 0; // Unlimited // This is a soft time limit on the duration of activation macro-turn (a number of micro-turns). // If a activation was running its micro-turns longer than this, we will give up the thread. // If this is set to zero or a negative number, then the full work queue is drained (MaxWorkItemsPerTurn allowing). public static TimeSpan ActivationSchedulingQuantum { get; set; } // This is the maximum number of waiting threads (blocked in WaitForResponse) allowed // per ActivationWorker. An attempt to wait when there are already too many threads waiting // will result in a TooManyWaitersException being thrown. //private static readonly int MaxWaitingThreads = 500; internal WorkItemGroup( OrleansTaskScheduler sched, ISchedulingContext schedulingContext, ILoggerFactory loggerFactory, CancellationToken ct, SchedulerStatisticsGroup schedulerStatistics, IOptions<StatisticsOptions> statisticsOptions) { masterScheduler = sched; SchedulingContext = schedulingContext; cancellationToken = ct; this.schedulerStatistics = schedulerStatistics; state = WorkGroupStatus.Waiting; workItems = new Queue<Task>(); lockable = new Object(); totalItemsEnQueued = 0; totalItemsProcessed = 0; totalQueuingDelay = TimeSpan.Zero; quantumExpirations = 0; TaskRunner = new ActivationTaskScheduler(this, loggerFactory); log = IsSystemPriority ? loggerFactory.CreateLogger($"{this.GetType().Namespace} {Name}.{this.GetType().Name}") : loggerFactory.CreateLogger<WorkItemGroup>(); if (schedulerStatistics.CollectShedulerQueuesStats) { queueTracking = new QueueTrackingStatistic("Scheduler." + SchedulingContext.Name, statisticsOptions); queueTracking.OnStartExecution(); } if (schedulerStatistics.CollectPerWorkItemStats) { workItemGroupStatisticsNumber = schedulerStatistics.RegisterWorkItemGroup(SchedulingContext.Name, SchedulingContext, () => { var sb = new StringBuilder(); lock (lockable) { sb.Append("QueueLength = " + WorkItemCount); sb.Append(String.Format(", State = {0}", state)); if (state == WorkGroupStatus.Runnable) sb.Append(String.Format("; oldest item is {0} old", workItems.Count >= 0 ? workItems.Peek().ToString() : "null")); } return sb.ToString(); }); } } /// <summary> /// Adds a task to this activation. /// If we're adding it to the run list and we used to be waiting, now we're runnable. /// </summary> /// <param name="task">The work item to add.</param> public void EnqueueTask(Task task) { lock (lockable) { #if DEBUG if (log.IsEnabled(LogLevel.Trace)) log.Trace("EnqueueWorkItem {0} into {1} when TaskScheduler.Current={2}", task, SchedulingContext, TaskScheduler.Current); #endif if (state == WorkGroupStatus.Shutdown) { ReportWorkGroupProblem( String.Format("Enqueuing task {0} to a stopped work item group. Going to ignore and not execute it. " + "The likely reason is that the task is not being 'awaited' properly.", task), ErrorCode.SchedulerNotEnqueuWorkWhenShutdown); task.Ignore(); // Ignore this Task, so in case it is faulted it will not cause UnobservedException. return; } long thisSequenceNumber = totalItemsEnQueued++; int count = WorkItemCount; workItems.Enqueue(task); int maxPendingItemsLimit = masterScheduler.MaxPendingItemsSoftLimit; if (maxPendingItemsLimit > 0 && count > maxPendingItemsLimit) { log.Warn(ErrorCode.SchedulerTooManyPendingItems, String.Format("{0} pending work items for group {1}, exceeding the warning threshold of {2}", count, Name, maxPendingItemsLimit)); } if (state != WorkGroupStatus.Waiting) return; state = WorkGroupStatus.Runnable; #if DEBUG if (log.IsEnabled(LogLevel.Trace)) log.Trace("Add to RunQueue {0}, #{1}, onto {2}", task, thisSequenceNumber, SchedulingContext); #endif masterScheduler.ScheduleExecution(this); } } /// <summary> /// Shuts down this work item group so that it will not process any additional work items, even if they /// have already been queued. /// </summary> internal void Stop() { lock (lockable) { if (IsActive) { ReportWorkGroupProblem( String.Format("WorkItemGroup is being stopped while still active. workItemCount = {0}." + "The likely reason is that the task is not being 'awaited' properly.", WorkItemCount), ErrorCode.SchedulerWorkGroupStopping); } if (state == WorkGroupStatus.Shutdown) { log.Warn(ErrorCode.SchedulerWorkGroupShuttingDown, "WorkItemGroup is already shutting down {0}", this.ToString()); return; } state = WorkGroupStatus.Shutdown; if (this.schedulerStatistics.CollectPerWorkItemStats) this.schedulerStatistics.UnRegisterWorkItemGroup(workItemGroupStatisticsNumber); if (this.schedulerStatistics.CollectGlobalShedulerStats) this.schedulerStatistics.OnWorkItemDrop(WorkItemCount); if (this.schedulerStatistics.CollectShedulerQueuesStats) queueTracking.OnStopExecution(); foreach (Task task in workItems) { // Ignore all queued Tasks, so in case they are faulted they will not cause UnobservedException. task.Ignore(); } workItems.Clear(); } } public WorkItemType ItemType { get { return WorkItemType.WorkItemGroup; } } // Execute one or more turns for this activation. // This method is always called in a single-threaded environment -- that is, no more than one // thread will be in this method at once -- but other asynch threads may still be queueing tasks, etc. public void Execute() { lock (lockable) { if (state == WorkGroupStatus.Shutdown) { if (!IsActive) return; // Don't mind if no work has been queued to this work group yet. ReportWorkGroupProblemWithBacktrace( "Cannot execute work items in a work item group that is in a shutdown state.", ErrorCode.SchedulerNotExecuteWhenShutdown); // Throws InvalidOperationException return; } state = WorkGroupStatus.Running; } var thread = Thread.CurrentThread; try { // Process multiple items -- drain the applicationMessageQueue (up to max items) for this physical activation int count = 0; var stopwatch = new Stopwatch(); stopwatch.Start(); do { lock (lockable) { if (state == WorkGroupStatus.Shutdown) { if (WorkItemCount > 0) log.Warn(ErrorCode.SchedulerSkipWorkStopping, "Thread {0} is exiting work loop due to Shutdown state {1} while still having {2} work items in the queue.", thread.ToString(), this.ToString(), WorkItemCount); else if (log.IsEnabled(LogLevel.Debug)) log.Debug("Thread {0} is exiting work loop due to Shutdown state {1}. Has {2} work items in the queue.", thread.ToString(), this.ToString(), WorkItemCount); break; } // Check the cancellation token (means that the silo is stopping) if (cancellationToken.IsCancellationRequested) { log.Warn(ErrorCode.SchedulerSkipWorkCancelled, "Thread {0} is exiting work loop due to cancellation token. WorkItemGroup: {1}, Have {2} work items in the queue.", thread.ToString(), this.ToString(), WorkItemCount); break; } } // Get the first Work Item on the list Task task; lock (lockable) { if (workItems.Count > 0) CurrentTask = task = workItems.Dequeue(); else // If the list is empty, then we're done break; } #if DEBUG if (log.IsEnabled(LogLevel.Trace)) log.Trace("About to execute task {0} in SchedulingContext={1}", task, SchedulingContext); #endif var taskStart = stopwatch.Elapsed; try { TaskRunner.RunTask(task); } catch (Exception ex) { log.Error(ErrorCode.SchedulerExceptionFromExecute, String.Format("Worker thread caught an exception thrown from Execute by task {0}", task), ex); throw; } finally { totalItemsProcessed++; var taskLength = stopwatch.Elapsed - taskStart; if (taskLength > OrleansTaskScheduler.TurnWarningLengthThreshold) { this.schedulerStatistics.NumLongRunningTurns.Increment(); log.Warn(ErrorCode.SchedulerTurnTooLong3, "Task {0} in WorkGroup {1} took elapsed time {2:g} for execution, which is longer than {3}. Running on thread {4}", OrleansTaskExtentions.ToString(task), SchedulingContext.ToString(), taskLength, OrleansTaskScheduler.TurnWarningLengthThreshold, thread.ToString()); } CurrentTask = null; } count++; } while (((MaxWorkItemsPerTurn <= 0) || (count <= MaxWorkItemsPerTurn)) && ((ActivationSchedulingQuantum <= TimeSpan.Zero) || (stopwatch.Elapsed < ActivationSchedulingQuantum))); stopwatch.Stop(); } catch (Exception ex) { log.Error(ErrorCode.Runtime_Error_100032, String.Format("Worker thread {0} caught an exception thrown from IWorkItem.Execute", thread), ex); } finally { // Now we're not Running anymore. // If we left work items on our run list, we're Runnable, and need to go back on the silo run queue; // If our run list is empty, then we're waiting. lock (lockable) { if (state != WorkGroupStatus.Shutdown) { if (WorkItemCount > 0) { state = WorkGroupStatus.Runnable; masterScheduler.ScheduleExecution(this); } else { state = WorkGroupStatus.Waiting; } } } } } public override string ToString() { return String.Format("{0}WorkItemGroup:Name={1},WorkGroupStatus={2}", IsSystemGroup ? "System*" : "", Name, state); } public string DumpStatus() { lock (lockable) { var sb = new StringBuilder(); sb.Append(this); sb.AppendFormat(". Currently QueuedWorkItems={0}; Total EnQueued={1}; Total processed={2}; Quantum expirations={3}; ", WorkItemCount, totalItemsEnQueued, totalItemsProcessed, quantumExpirations); if (CurrentTask != null) { sb.AppendFormat(" Executing Task Id={0} Status={1} for {2}.", CurrentTask.Id, CurrentTask.Status, Utils.Since(currentTaskStarted)); } if (AverageQueueLenght > 0) { sb.AppendFormat("average queue length at enqueue: {0}; ", AverageQueueLenght); if (!totalQueuingDelay.Equals(TimeSpan.Zero) && totalItemsProcessed > 0) { sb.AppendFormat("average queue delay: {0}ms; ", totalQueuingDelay.Divide(totalItemsProcessed).TotalMilliseconds); } } sb.AppendFormat("TaskRunner={0}; ", TaskRunner); if (SchedulingContext != null) { sb.AppendFormat("Detailed SchedulingContext=<{0}>", SchedulingContext.DetailedStatus()); } return sb.ToString(); } } private void ReportWorkGroupProblemWithBacktrace(string what, ErrorCode errorCode) { var st = Utils.GetStackTrace(); var msg = string.Format("{0} {1}", what, DumpStatus()); log.Warn(errorCode, msg + Environment.NewLine + " Called from " + st); } private void ReportWorkGroupProblem(string what, ErrorCode errorCode) { var msg = string.Format("{0} {1}", what, DumpStatus()); log.Warn(errorCode, msg); } } }
using System; using System.Globalization; using System.IO; using System.Net; using System.Threading.Tasks; using Newtonsoft.Json; using WireMock.Logging; using WireMock.Matchers; using WireMock.RequestBuilders; using WireMock.ResponseBuilders; using WireMock.Server; using WireMock.Settings; using WireMock.Types; using WireMock.Util; namespace WireMock.Net.ConsoleApplication { public interface IHandleBarTransformer { string Name { get; } void Render(TextWriter textWriter, dynamic context, object[] arguments); } public class CustomNameTransformer : IHandleBarTransformer { public string Name => "CustomName"; public void Render(TextWriter writer, dynamic context, object[] parameters) { /* Handlebar logic to render */ } } public static class MainApp { public static void Run() { var s = WireMockServer.Start(); s.Stop(); string url1 = "http://localhost:9091/"; string url2 = "http://localhost:9092/"; string url3 = "https://localhost:9443/"; var server = WireMockServer.Start(new WireMockServerSettings { AllowCSharpCodeMatcher = true, Urls = new[] { url1, url2, url3 }, StartAdminInterface = true, ReadStaticMappings = true, WatchStaticMappings = true, WatchStaticMappingsInSubdirectories = true, //ProxyAndRecordSettings = new ProxyAndRecordSettings //{ // SaveMapping = true //}, PreWireMockMiddlewareInit = app => { System.Console.WriteLine($"PreWireMockMiddlewareInit : {app.GetType()}"); }, PostWireMockMiddlewareInit = app => { System.Console.WriteLine($"PostWireMockMiddlewareInit : {app.GetType()}"); }, #if USE_ASPNETCORE AdditionalServiceRegistration = services => { System.Console.WriteLine($"AdditionalServiceRegistration : {services.GetType()}"); }, #endif Logger = new WireMockConsoleLogger(), HandlebarsRegistrationCallback = (handlebarsContext, fileSystemHandler) => { var transformer = new CustomNameTransformer(); // handlebarsContext.RegisterHelper(transformer.Name, transformer.Render); TODO }, // Uncomment below if you want to use the CustomFileSystemFileHandler // FileSystemHandler = new CustomFileSystemFileHandler() }); System.Console.WriteLine("WireMockServer listening at {0}", string.Join(",", server.Urls)); server.SetBasicAuthentication("a", "b"); //server.SetAzureADAuthentication("6c2a4722-f3b9-4970-b8fc-fac41e29stef", "8587fde1-7824-42c7-8592-faf92b04stef"); // server.AllowPartialMapping(); server.Given(Request.Create().WithPath("/mypath").UsingPost()) .RespondWith(Response.Create() .WithHeader("Content-Type", "application/json") .WithBodyAsJson("{{JsonPath.SelectToken request.body \"..name\"}}") .WithTransformer() ); server .Given(Request.Create().WithPath(p => p.Contains("x")).UsingGet()) .AtPriority(4) .RespondWith(Response.Create() .WithStatusCode(200) .WithHeader("Content-Type", "application/json") .WithBody(@"{ ""result"": ""Contains x with FUNC 200""}")); server .Given(Request.Create() .UsingGet() .WithPath("/proxy-test-keep-alive") ) .RespondWith(Response.Create() .WithHeader("Keep-Alive", "timeout=1, max=1") ); server .Given(Request.Create() .UsingPost() .WithHeader("postmanecho", "post") ) .RespondWith(Response.Create() .WithProxy(new ProxyAndRecordSettings { Url = "http://postman-echo.com" }) ); server .Given(Request.Create() .UsingGet() .WithHeader("postmanecho", "get") ) .RespondWith(Response.Create() .WithProxy(new ProxyAndRecordSettings { Url = "http://postman-echo.com/get" }) ); server .Given(Request.Create() .UsingGet() .WithHeader("postmanecho", "get2") ) .RespondWith(Response.Create() .WithProxy(new ProxyAndRecordSettings { Url = "http://postman-echo.com/get", WebProxySettings = new WebProxySettings { Address = "http://company", UserName = "test", Password = "pwd" } }) ); server .Given(Request.Create() .UsingGet() .WithPath("/proxy-execute-keep-alive") ) .RespondWith(Response.Create() .WithProxy(new ProxyAndRecordSettings { Url = "http://localhost:9999", ExcludedHeaders = new[] { "Keep-Alive" } }) .WithHeader("Keep-Alive-Test", "stef") ); server .Given(Request.Create() .WithPath("/xpath").UsingPost() .WithBody(new XPathMatcher("/todo-list[count(todo-item) = 3]")) ) .RespondWith(Response.Create().WithBody("XPathMatcher!")); server .Given(Request.Create() .WithPath("/xpaths").UsingPost() .WithBody(new[] { new XPathMatcher("/todo-list[count(todo-item) = 3]"), new XPathMatcher("/todo-list[count(todo-item) = 4]") }) ) .RespondWith(Response.Create().WithBody("xpaths!")); server .Given(Request .Create() .WithPath("/jsonthings") .WithBody(new JsonPathMatcher("$.things[?(@.name == 'RequiredThing')]")) .UsingPut()) .RespondWith(Response.Create() .WithBody(@"{ ""result"": ""JsonPathMatcher !!!""}")); server .Given(Request .Create() .WithPath("/jsonbodytest1") .WithBody(new JsonMatcher("{ \"x\": 42, \"s\": \"s\" }")) .UsingPost()) .WithGuid("debaf408-3b23-4c04-9d18-ef1c020e79f2") .RespondWith(Response.Create() .WithBody(@"{ ""result"": ""jsonbodytest1"" }")); server .Given(Request .Create() .WithPath("/jsonbodytest2") .WithBody(new JsonMatcher(new { x = 42, s = "s" })) .UsingPost()) .WithGuid("debaf408-3b23-4c04-9d18-ef1c020e79f3") .RespondWith(Response.Create() .WithBody(@"{ ""result"": ""jsonbodytest2"" }")); server .Given(Request .Create() .WithPath(new WildcardMatcher("/navision/OData/Company('My Company')/School*", true)) .WithParam("$filter", "(substringof(Code, 'WA')") .UsingGet()) .RespondWith(Response.Create() .WithHeader("Content-Type", "application/json") .WithBody(@"{ ""result"": ""odata""}")); server .Given(Request .Create() .WithPath(new WildcardMatcher("/param2", true)) .WithParam("key", "test") .UsingGet()) .RespondWith(Response.Create() .WithHeader("Content-Type", "application/json") .WithBodyAsJson(new { result = "param2" })); server .Given(Request .Create() .WithPath(new WildcardMatcher("/param3", true)) .WithParam("key", new WildcardMatcher("t*")) .UsingGet()) .RespondWith(Response.Create() .WithHeader("Content-Type", "application/json") .WithBodyAsJson(new { result = "param3" })); server .Given(Request.Create().WithPath("/headers", "/headers_test").UsingPost().WithHeader("Content-Type", "application/json*")) .RespondWith(Response.Create() .WithStatusCode(201) .WithHeader("Content-Type", "application/json") .WithBodyAsJson(new { result = "data:headers posted with 201" })); if (!System.IO.File.Exists(@"c:\temp\x.json")) { System.IO.File.WriteAllText(@"c:\temp\x.json", "{ \"hello\": \"world\", \"answer\": 42 }"); } server .Given(Request.Create().WithPath("/file").UsingGet()) .RespondWith(Response.Create() .WithBodyFromFile(@"c:\temp\x.json", false) ); server .Given(Request.Create().WithPath("/filecache").UsingGet()) .RespondWith(Response.Create() .WithBodyFromFile(@"c:\temp\x.json") ); server .Given(Request.Create().WithPath("/file_rel").UsingGet()) .WithGuid("0000aaaa-fcf4-4256-a0d3-1c76e4862947") .RespondWith(Response.Create() .WithHeader("Content-Type", "application/xml") .WithBodyFromFile("WireMock.Net.xml", false) ); server .Given(Request.Create().WithHeader("ProxyThis", "true") .UsingGet()) .RespondWith(Response.Create() .WithProxy("http://www.google.com") ); server .Given(Request.Create().WithHeader("ProxyThisHttps", "true") .UsingGet()) .RespondWith(Response.Create() .WithProxy("https://www.google.com") ); server .Given(Request.Create().WithPath("/bodyasbytes.png") .UsingGet()) .RespondWith(Response.Create() .WithHeader("Content-Type", "image/png") .WithBody(Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAIAAAACUFjqAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTczbp9jAAAAJ0lEQVQoU2NgUPuPD6Hz0RCEAtJoiAxpCCBXGgmRIo0TofORkdp/AMiMdRVnV6O0AAAAAElFTkSuQmCC")) ); server .Given(Request.Create().WithPath("/oauth2/access").UsingPost().WithBody("grant_type=password;username=u;password=p")) .RespondWith(Response.Create() .WithStatusCode(200) .WithHeader("Content-Type", "application/json") .WithBodyAsJson(new { access_token = "AT", refresh_token = "RT" })); server .Given(Request.Create().WithPath("/helloworld").UsingGet().WithHeader("Authorization", new RegexMatcher("^(?i)Bearer AT$"))) .RespondWith(Response.Create() .WithStatusCode(200) .WithBody("hi")); server .Given(Request.Create().WithPath("/data").UsingPost().WithBody(b => b != null && b.Contains("e"))) .AtPriority(999) .RespondWith(Response.Create() .WithStatusCode(201) .WithHeader("Content-Type", "application/json") .WithBodyAsJson(new { result = "data posted with FUNC 201" })); server .Given(Request.Create().WithPath("/json").UsingPost().WithBody(new JsonPathMatcher("$.things[?(@.name == 'RequiredThing')]"))) .RespondWith(Response.Create() .WithStatusCode(201) .WithHeader("Content-Type", "application/json") .WithBody(@"{ ""result"": ""json posted with 201""}")); server .Given(Request.Create().WithPath("/json2").UsingPost().WithBody("x")) .RespondWith(Response.Create() .WithStatusCode(201) .WithHeader("Content-Type", "application/json") .WithBody(@"{ ""result"": ""json posted with x - 201""}")); server .Given(Request.Create().WithPath("/data").UsingDelete()) .RespondWith(Response.Create() .WithStatusCode(200) .WithHeader("Content-Type", "application/json") .WithBody(@"{ ""result"": ""data deleted with 200""}")); server .Given(Request.Create() .WithPath("/needs-a-key") .UsingGet() .WithHeader("api-key", "*", MatchBehaviour.AcceptOnMatch) .UsingAnyMethod()) .RespondWith(Response.Create() .WithStatusCode(HttpStatusCode.OK) .WithBody(@"{ ""result"": ""api-key found""}")); server .Given(Request.Create() .WithPath("/needs-a-key") .UsingGet() .WithHeader("api-key", "*", MatchBehaviour.RejectOnMatch) .UsingAnyMethod()) .RespondWith(Response.Create() .WithStatusCode(HttpStatusCode.Unauthorized) .WithBody(@"{ ""result"": ""api-key missing""}")); server .Given(Request.Create().WithPath("/nobody").UsingGet()) .RespondWith(Response.Create().WithDelay(TimeSpan.FromSeconds(1)) .WithStatusCode(200)); server .Given(Request.Create().WithPath("/partial").UsingPost().WithBody(new SimMetricsMatcher(new[] { "cat", "dog" }))) .RespondWith(Response.Create().WithStatusCode(200).WithBody("partial = 200")); // http://localhost:9091/trans?start=1000&stop=1&stop=2 server .Given(Request.Create().WithPath("/trans").UsingGet()) .WithGuid("90356dba-b36c-469a-a17e-669cd84f1f05") .RespondWith(Response.Create() .WithStatusCode(200) .WithHeader("Content-Type", "application/json") .WithHeader("Transformed-Postman-Token", "token is {{request.headers.Postman-Token}}") .WithHeader("xyz_{{request.headers.Postman-Token}}", "token is {{request.headers.Postman-Token}}") .WithBody(@"{""msg"": ""Hello world CATCH-ALL on /*, {{request.path}}, add={{Math.Add request.query.start.[0] 42}} bykey={{request.query.start}}, bykey={{request.query.stop}}, byidx0={{request.query.stop.[0]}}, byidx1={{request.query.stop.[1]}}"" }") .WithTransformer(TransformerType.Handlebars, true, ReplaceNodeOptions.None) .WithDelay(TimeSpan.FromMilliseconds(100)) ); server .Given(Request.Create().WithPath("/jsonpathtestToken").UsingPost()) .RespondWith(Response.Create() .WithHeader("Content-Type", "application/json") .WithBody("{{JsonPath.SelectToken request.body \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}") .WithTransformer() ); server .Given(Request.Create().WithPath("/zubinix").UsingPost()) .RespondWith(Response.Create() .WithHeader("Content-Type", "application/json") .WithBody("{ \"result\": \"{{JsonPath.SelectToken request.bodyAsJson \"username\"}}\" }") .WithTransformer() ); server .Given(Request.Create().WithPath("/zubinix2").UsingPost()) .RespondWith(Response.Create() .WithHeader("Content-Type", "application/json") .WithBodyAsJson(new { path = "{{request.path}}", result = "{{JsonPath.SelectToken request.bodyAsJson \"username\"}}" }) .WithTransformer() ); server .Given(Request.Create().WithPath("/jsonpathtestTokenJson").UsingPost()) .RespondWith(Response.Create() .WithHeader("Content-Type", "application/json") .WithBodyAsJson(new { status = "OK", url = "{{request.url}}", transformed = "{{JsonPath.SelectToken request.body \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}" }) .WithTransformer() ); server .Given(Request.Create().WithPath("/jsonpathtestTokens").UsingPost()) .RespondWith(Response.Create() .WithHeader("Content-Type", "application/json") .WithBody("[{{#JsonPath.SelectTokens request.body \"$..Products[?(@.Price >= 50)].Name\"}} { \"idx\":{{id}}, \"value\":\"{{value}}\" }, {{/JsonPath.SelectTokens}} {} ]") .WithTransformer() ); server .Given(Request.Create() .WithPath("/state1") .UsingGet()) .InScenario("s1") .WillSetStateTo("Test state 1") .RespondWith(Response.Create() .WithBody("No state msg 1")); server .Given(Request.Create() .WithPath("/foostate1") .UsingGet()) .InScenario("s1") .WhenStateIs("Test state 1") .RespondWith(Response.Create() .WithBody("Test state msg 1")); server .Given(Request.Create() .WithPath("/state2") .UsingGet()) .InScenario("s2") .WillSetStateTo("Test state 2") .RespondWith(Response.Create() .WithBody("No state msg 2")); server .Given(Request.Create() .WithPath("/foostate2") .UsingGet()) .InScenario("s2") .WhenStateIs("Test state 2") .RespondWith(Response.Create() .WithBody("Test state msg 2")); server .Given(Request.Create().WithPath("/encoded-test/a%20b")) .RespondWith(Response.Create() .WithBody("EncodedTest 1 : Path={{request.path}}, Url={{request.url}}") .WithTransformer() ); server .Given(Request.Create().WithPath("/encoded-test/a b")) .RespondWith(Response.Create() .WithBody("EncodedTest 2 : Path={{request.path}}, Url={{request.url}}") .WithTransformer() ); // https://stackoverflow.com/questions/51985089/wiremock-request-matching-with-comparison-between-two-query-parameters server .Given(Request.Create().WithPath("/linq") .WithParam("from", new LinqMatcher("DateTime.Parse(it) > \"2018-03-01 00:00:00\""))) .RespondWith(Response.Create() .WithBody("linq match !!!") ); server .Given(Request.Create().WithPath("/myendpoint").UsingAnyMethod()) .RespondWith(Response.Create() .WithStatusCode(500) .WithBody(requestMessage => { return JsonConvert.SerializeObject(new { Message = "Test error" }); }) ); server .Given(Request.Create().WithPath("/random")) .RespondWith(Response.Create() .WithHeader("Content-Type", "application/json") .WithBodyAsJson(new { Xeger1 = "{{Xeger \"\\w{4}\\d{5}\"}}", Xeger2 = "{{Xeger \"\\d{5}\"}}", TextRegexPostcode = "{{Random Type=\"TextRegex\" Pattern=\"[1-9][0-9]{3}[A-Z]{2}\"}}", Text = "{{Random Type=\"Text\" Min=8 Max=20}}", TextLipsum = "{{Random Type=\"TextLipsum\"}}", IBAN = "{{Random Type=\"IBAN\" CountryCode=\"NL\"}}", TimeSpan1 = "{{Random Type=\"TimeSpan\" Format=\"c\" IncludeMilliseconds=false}}", TimeSpan2 = "{{Random Type=\"TimeSpan\"}}", DateTime1 = "{{Random Type=\"DateTime\"}}", DateTimeNow = DateTime.Now, DateTimeNowToString = DateTime.Now.ToString("s", CultureInfo.InvariantCulture), Guid1 = "{{Random Type=\"Guid\" Uppercase=false}}", Guid2 = "{{Random Type=\"Guid\"}}", Guid3 = "{{Random Type=\"Guid\" Format=\"X\"}}", Boolean = "{{Random Type=\"Boolean\"}}", Integer = "{{Random Type=\"Integer\" Min=1000 Max=9999}}", Long = "{{#Random Type=\"Long\" Min=10000000 Max=99999999}}{{this}}{{/Random}}", Double = "{{Random Type=\"Double\" Min=10 Max=99}}", Float = "{{Random Type=\"Float\" Min=100 Max=999}}", IP4Address = "{{Random Type=\"IPv4Address\" Min=\"10.2.3.4\"}}", IP6Address = "{{Random Type=\"IPv6Address\"}}", MACAddress = "{{Random Type=\"MACAddress\" Separator=\"-\"}}", StringListValue = "{{Random Type=\"StringList\" Values=[\"a\", \"b\", \"c\"]}}" }) .WithTransformer() ); server .Given(Request.Create() .UsingPost() .WithPath("/xpathsoap") .WithBody(new XPathMatcher("//*[local-name() = 'getMyData']")) ) .RespondWith(Response.Create() .WithHeader("Content-Type", "application/xml") .WithBody("<xml>ok</xml>") ); server .Given(Request.Create() .UsingPost() .WithPath("/post_with_query") .WithHeader("PRIVATE-TOKEN", "t") .WithParam("name", "stef") .WithParam("path", "p") .WithParam("visibility", "Private") .WithParam("parent_id", "1") ) .RespondWith(Response.Create() .WithBody("OK : post_with_query") ); server.Given(Request.Create() .WithPath("/services/query/") .WithParam("q", "SELECT Id from User where username='[email protected]'") .UsingGet()) .RespondWith(Response.Create() .WithStatusCode(200) .WithHeader("Content-Type", "application/json") .WithBodyAsJson(new { Id = "5bdf076c-5654-4b3e-842c-7caf1fabf8c9" })); server .Given(Request.Create().WithPath("/random200or505").UsingGet()) .RespondWith(Response.Create().WithCallback(request => { int code = new Random().Next(1, 2) == 1 ? 505 : 200; return new ResponseMessage { BodyData = new BodyData { BodyAsString = "random200or505:" + code, DetectedBodyType = Types.BodyType.String }, StatusCode = code }; })); server .Given(Request.Create().WithPath("/random200or505async").UsingGet()) .RespondWith(Response.Create().WithCallback(async request => { await Task.Delay(1).ConfigureAwait(false); int code = new Random().Next(1, 2) == 1 ? 505 : 200; return new ResponseMessage { BodyData = new BodyData { BodyAsString = "random200or505async:" + code, DetectedBodyType = Types.BodyType.String }, StatusCode = code }; })); System.Console.WriteLine(JsonConvert.SerializeObject(server.MappingModels, Formatting.Indented)); System.Console.WriteLine("Press any key to stop the server"); System.Console.ReadKey(); server.Stop(); System.Console.WriteLine("Displaying all requests"); var allRequests = server.LogEntries; System.Console.WriteLine(JsonConvert.SerializeObject(allRequests, Formatting.Indented)); System.Console.WriteLine("Press any key to quit"); System.Console.ReadKey(); } } }
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 Google.OrTools.LinearSolver { using System; using System.Collections.Generic; public class LinearExpr { public virtual double DoVisit(Dictionary<Variable, double> coefficients, double multiplier) { return 0; } public double Visit(Dictionary<Variable, double> coefficients) { return DoVisit(coefficients, 1.0); } public static LinearExpr operator +(LinearExpr a, double v) { return new SumCst(a, v); } public static LinearExpr operator +(double v, LinearExpr a) { return new SumCst(a, v); } public static LinearExpr operator +(LinearExpr a, LinearExpr b) { return new Sum(a, b); } public static LinearExpr operator -(LinearExpr a, double v) { return new SumCst(a, -v); } public static LinearExpr operator -(double v, LinearExpr a) { return new SumCst(new ProductCst(a, -1.0), v); } public static LinearExpr operator -(LinearExpr a, LinearExpr b) { return new Sum(a, new ProductCst(b, -1.0)); } public static LinearExpr operator -(LinearExpr a) { return new ProductCst(a, -1.0); } public static LinearExpr operator *(LinearExpr a, double v) { return new ProductCst(a, v); } public static LinearExpr operator /(LinearExpr a, double v) { return new ProductCst(a, 1 / v); } public static LinearExpr operator *(double v, LinearExpr a) { return new ProductCst(a, v); } public static RangeConstraint operator ==(LinearExpr a, double v) { return new RangeConstraint(a, v, v); } public static RangeConstraint operator ==(double v, LinearExpr a) { return new RangeConstraint(a, v, v); } public static RangeConstraint operator !=(LinearExpr a, double v) { throw new ArgumentException("Operator != not supported for LinearExpression"); } public static RangeConstraint operator !=(double v, LinearExpr a) { throw new ArgumentException("Operator != not supported for LinearExpression"); } public static Equality operator ==(LinearExpr a, LinearExpr b) { return new Equality(a, b, true); } public static Equality operator !=(LinearExpr a, LinearExpr b) { return new Equality(a, b, false); } public static RangeConstraint operator <=(LinearExpr a, double v) { return new RangeConstraint(a, double.NegativeInfinity, v); } public static RangeConstraint operator >=(LinearExpr a, double v) { return new RangeConstraint(a, v, double.PositiveInfinity); } public static RangeConstraint operator <=(LinearExpr a, LinearExpr b) { return a - b <= 0; } public static RangeConstraint operator >=(LinearExpr a, LinearExpr b) { return a - b >= 0; } public static implicit operator LinearExpr(Variable a) { return new VarWrapper(a); } } public static class LinearExprArrayHelper { public static LinearExpr Sum(this LinearExpr[] exprs) { return new SumArray(exprs); } public static LinearExpr Sum(this Variable[] vars) { return new SumVarArray(vars); } } // def __ge__(self, arg): // if isinstance(arg, (int, long, float)): // return LinearConstraint(self, arg, 1e308) // else: // return LinearConstraint(Sum(self, ProductCst(arg, -1)), 0.0, 1e308) // def __le__(self, arg): // if isinstance(arg, (int, long, float)): // return LinearConstraint(self, -1e308, arg) // else: // return LinearConstraint(Sum(self, ProductCst(arg, -1)), -1e308, 0.0) class ProductCst : LinearExpr { public ProductCst(LinearExpr expr, double coeff) { this.coeff_ = coeff; this.expr_ = expr; } public override String ToString() { return "(" + expr_.ToString() + " * " + coeff_ + ")"; } public override double DoVisit(Dictionary<Variable, double> coefficients, double multiplier) { double current_multiplier = multiplier * coeff_; if (current_multiplier != 0.0) { return expr_.DoVisit(coefficients, current_multiplier); } else { return 0.0; } } private LinearExpr expr_; private double coeff_; } class SumCst : LinearExpr { public SumCst(LinearExpr expr, double coeff) { this.coeff_ = coeff; this.expr_ = expr; } public override String ToString() { return "(" + expr_.ToString() + " + " + coeff_ + ")"; } public override double DoVisit(Dictionary<Variable, double> coefficients, double multiplier) { if (multiplier != 0.0) { return coeff_ * multiplier + expr_.DoVisit(coefficients, multiplier); } else { return 0.0; } } private LinearExpr expr_; private double coeff_; } class VarWrapper : LinearExpr { public VarWrapper(Variable var) { this.var_ = var; } public override String ToString() { return var_.Name(); } public override double DoVisit(Dictionary<Variable, double> coefficients, double multiplier) { if (multiplier != 0.0) { if (coefficients.ContainsKey(var_)) { coefficients[var_] += multiplier; } else { coefficients[var_] = multiplier; } } return 0.0; } private Variable var_; } class Sum : LinearExpr { public Sum(LinearExpr left, LinearExpr right) { this.left_ = left; this.right_ = right; } public override String ToString() { return "(" + left_.ToString() + " + " + right_.ToString() + ")"; } public override double DoVisit(Dictionary<Variable, double> coefficients, double multiplier) { if (multiplier != 0.0) { return left_.DoVisit(coefficients, multiplier) + right_.DoVisit(coefficients, multiplier); } else { return 0.0; } } private LinearExpr left_; private LinearExpr right_; } public class SumArray : LinearExpr { public SumArray(LinearExpr[] array) { this.array_ = array; } public override double DoVisit(Dictionary<Variable, double> coefficients, double multiplier) { if (multiplier != 0.0) { double constant = 0.0; foreach (LinearExpr expr in array_) { constant += expr.DoVisit(coefficients, multiplier); } return constant; } else { return 0.0; } } private LinearExpr[] array_; } public class SumVarArray : LinearExpr { public SumVarArray(Variable[] array) { this.array_ = array; } public override double DoVisit(Dictionary<Variable, double> coefficients, double multiplier) { if (multiplier != 0.0) { foreach (Variable var in array_) { if (coefficients.ContainsKey(var)) { coefficients[var] += multiplier; } else { coefficients[var] = multiplier; } } } return 0.0; } private Variable[] array_; } } // namespace Google.OrTools.LinearSolver
using UnityEngine; using System.Collections; using System.Collections.Generic; [ExecuteInEditMode] // Make water live-update even when not in play mode public class Water : MonoBehaviour { public enum WaterMode { Simple = 0, Reflective = 1, Refractive = 2, }; public WaterMode m_WaterMode = WaterMode.Refractive; public bool m_DisablePixelLights = true; public int m_TextureSize = 256; public float m_ClipPlaneOffset = 0.07f; public LayerMask m_ReflectLayers = -1; public LayerMask m_RefractLayers = -1; private Dictionary<Camera, Camera> m_ReflectionCameras = new Dictionary<Camera, Camera>(); // Camera -> Camera table private Dictionary<Camera, Camera> m_RefractionCameras = new Dictionary<Camera, Camera>(); // Camera -> Camera table private RenderTexture m_ReflectionTexture = null; private RenderTexture m_RefractionTexture = null; private WaterMode m_HardwareWaterSupport = WaterMode.Refractive; private int m_OldReflectionTextureSize = 0; private int m_OldRefractionTextureSize = 0; private static bool s_InsideWater = false; // This is called when it's known that the object will be rendered by some // camera. We render reflections / refractions and do other updates here. // Because the script executes in edit mode, reflections for the scene view // camera will just work! public void OnWillRenderObject() { if( !enabled || !GetComponent<Renderer>() || !GetComponent<Renderer>().sharedMaterial || !GetComponent<Renderer>().enabled ) return; Camera cam = Camera.current; if( !cam ) return; // Safeguard from recursive water reflections. if( s_InsideWater ) return; s_InsideWater = true; // Actual water rendering mode depends on both the current setting AND // the hardware support. There's no point in rendering refraction textures // if they won't be visible in the end. m_HardwareWaterSupport = FindHardwareWaterSupport(); WaterMode mode = GetWaterMode(); Camera reflectionCamera, refractionCamera; CreateWaterObjects( cam, out reflectionCamera, out refractionCamera ); // find out the reflection plane: position and normal in world space Vector3 pos = transform.position; Vector3 normal = transform.up; // Optionally disable pixel lights for reflection/refraction int oldPixelLightCount = QualitySettings.pixelLightCount; if( m_DisablePixelLights ) QualitySettings.pixelLightCount = 0; UpdateCameraModes( cam, reflectionCamera ); UpdateCameraModes( cam, refractionCamera ); // Render reflection if needed if( mode >= WaterMode.Reflective ) { // Reflect camera around reflection plane float d = -Vector3.Dot (normal, pos) - m_ClipPlaneOffset; Vector4 reflectionPlane = new Vector4 (normal.x, normal.y, normal.z, d); Matrix4x4 reflection = Matrix4x4.zero; CalculateReflectionMatrix (ref reflection, reflectionPlane); Vector3 oldpos = cam.transform.position; Vector3 newpos = reflection.MultiplyPoint( oldpos ); reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection; // Setup oblique projection matrix so that near plane is our reflection // plane. This way we clip everything below/above it for free. Vector4 clipPlane = CameraSpacePlane( reflectionCamera, pos, normal, 1.0f ); Matrix4x4 projection = cam.projectionMatrix; CalculateObliqueMatrix (ref projection, clipPlane); reflectionCamera.projectionMatrix = projection; reflectionCamera.cullingMask = ~(1<<4) & m_ReflectLayers.value; // never render water layer reflectionCamera.targetTexture = m_ReflectionTexture; GL.invertCulling = true; reflectionCamera.transform.position = newpos; Vector3 euler = cam.transform.eulerAngles; reflectionCamera.transform.eulerAngles = new Vector3(-euler.x, euler.y, euler.z); reflectionCamera.Render(); reflectionCamera.transform.position = oldpos; GL.invertCulling = false; GetComponent<Renderer>().sharedMaterial.SetTexture( "_ReflectionTex", m_ReflectionTexture ); } // Render refraction if( mode >= WaterMode.Refractive ) { refractionCamera.worldToCameraMatrix = cam.worldToCameraMatrix; // Setup oblique projection matrix so that near plane is our reflection // plane. This way we clip everything below/above it for free. Vector4 clipPlane = CameraSpacePlane( refractionCamera, pos, normal, -1.0f ); Matrix4x4 projection = cam.projectionMatrix; CalculateObliqueMatrix (ref projection, clipPlane); refractionCamera.projectionMatrix = projection; refractionCamera.cullingMask = ~(1<<4) & m_RefractLayers.value; // never render water layer refractionCamera.targetTexture = m_RefractionTexture; refractionCamera.transform.position = cam.transform.position; refractionCamera.transform.rotation = cam.transform.rotation; refractionCamera.Render(); GetComponent<Renderer>().sharedMaterial.SetTexture( "_RefractionTex", m_RefractionTexture ); } // Restore pixel light count if( m_DisablePixelLights ) QualitySettings.pixelLightCount = oldPixelLightCount; // Setup shader keywords based on water mode switch( mode ) { case WaterMode.Simple: Shader.EnableKeyword( "WATER_SIMPLE" ); Shader.DisableKeyword( "WATER_REFLECTIVE" ); Shader.DisableKeyword( "WATER_REFRACTIVE" ); break; case WaterMode.Reflective: Shader.DisableKeyword( "WATER_SIMPLE" ); Shader.EnableKeyword( "WATER_REFLECTIVE" ); Shader.DisableKeyword( "WATER_REFRACTIVE" ); break; case WaterMode.Refractive: Shader.DisableKeyword( "WATER_SIMPLE" ); Shader.DisableKeyword( "WATER_REFLECTIVE" ); Shader.EnableKeyword( "WATER_REFRACTIVE" ); break; } s_InsideWater = false; } // Cleanup all the objects we possibly have created void OnDisable() { if( m_ReflectionTexture ) { DestroyImmediate( m_ReflectionTexture ); m_ReflectionTexture = null; } if( m_RefractionTexture ) { DestroyImmediate( m_RefractionTexture ); m_RefractionTexture = null; } foreach (KeyValuePair<Camera, Camera> kvp in m_ReflectionCameras) DestroyImmediate( (kvp.Value).gameObject ); m_ReflectionCameras.Clear(); foreach (KeyValuePair<Camera, Camera> kvp in m_RefractionCameras) DestroyImmediate( (kvp.Value).gameObject ); m_RefractionCameras.Clear(); } // This just sets up some matrices in the material; for really // old cards to make water texture scroll. void Update() { if( !GetComponent<Renderer>() ) return; Material mat = GetComponent<Renderer>().sharedMaterial; if( !mat ) return; Vector4 waveSpeed = mat.GetVector( "WaveSpeed" ); float waveScale = mat.GetFloat( "_WaveScale" ); Vector4 waveScale4 = new Vector4(waveScale, waveScale, waveScale * 0.4f, waveScale * 0.45f); // Time since level load, and do intermediate calculations with doubles double t = Time.timeSinceLevelLoad / 20.0; Vector4 offsetClamped = new Vector4( (float)System.Math.IEEERemainder(waveSpeed.x * waveScale4.x * t, 1.0), (float)System.Math.IEEERemainder(waveSpeed.y * waveScale4.y * t, 1.0), (float)System.Math.IEEERemainder(waveSpeed.z * waveScale4.z * t, 1.0), (float)System.Math.IEEERemainder(waveSpeed.w * waveScale4.w * t, 1.0) ); mat.SetVector( "_WaveOffset", offsetClamped ); mat.SetVector( "_WaveScale4", waveScale4 ); Vector3 waterSize = GetComponent<Renderer>().bounds.size; Vector3 scale = new Vector3( waterSize.x*waveScale4.x, waterSize.z*waveScale4.y, 1 ); Matrix4x4 scrollMatrix = Matrix4x4.TRS( new Vector3(offsetClamped.x,offsetClamped.y,0), Quaternion.identity, scale ); mat.SetMatrix( "_WaveMatrix", scrollMatrix ); scale = new Vector3( waterSize.x*waveScale4.z, waterSize.z*waveScale4.w, 1 ); scrollMatrix = Matrix4x4.TRS( new Vector3(offsetClamped.z,offsetClamped.w,0), Quaternion.identity, scale ); mat.SetMatrix( "_WaveMatrix2", scrollMatrix ); } private void UpdateCameraModes( Camera src, Camera dest ) { if( dest == null ) return; // set water camera to clear the same way as current camera dest.clearFlags = src.clearFlags; dest.backgroundColor = src.backgroundColor; if( src.clearFlags == CameraClearFlags.Skybox ) { Skybox sky = src.GetComponent(typeof(Skybox)) as Skybox; Skybox mysky = dest.GetComponent(typeof(Skybox)) as Skybox; if( !sky || !sky.material ) { mysky.enabled = false; } else { mysky.enabled = true; mysky.material = sky.material; } } // update other values to match current camera. // even if we are supplying custom camera&projection matrices, // some of values are used elsewhere (e.g. skybox uses far plane) dest.farClipPlane = src.farClipPlane; dest.nearClipPlane = src.nearClipPlane; dest.orthographic = src.orthographic; dest.fieldOfView = src.fieldOfView; dest.aspect = src.aspect; dest.orthographicSize = src.orthographicSize; } // On-demand create any objects we need for water private void CreateWaterObjects( Camera currentCamera, out Camera reflectionCamera, out Camera refractionCamera ) { WaterMode mode = GetWaterMode(); reflectionCamera = null; refractionCamera = null; if( mode >= WaterMode.Reflective ) { // Reflection render texture if( !m_ReflectionTexture || m_OldReflectionTextureSize != m_TextureSize ) { if( m_ReflectionTexture ) DestroyImmediate( m_ReflectionTexture ); m_ReflectionTexture = new RenderTexture( m_TextureSize, m_TextureSize, 16 ); m_ReflectionTexture.name = "__WaterReflection" + GetInstanceID(); m_ReflectionTexture.isPowerOfTwo = true; m_ReflectionTexture.hideFlags = HideFlags.DontSave; m_OldReflectionTextureSize = m_TextureSize; } // Camera for reflection m_ReflectionCameras.TryGetValue(currentCamera, out reflectionCamera); if (!reflectionCamera) // catch both not-in-dictionary and in-dictionary-but-deleted-GO { GameObject go = new GameObject( "Water Refl Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox) ); reflectionCamera = go.GetComponent<Camera>(); reflectionCamera.enabled = false; reflectionCamera.transform.position = transform.position; reflectionCamera.transform.rotation = transform.rotation; reflectionCamera.gameObject.AddComponent<FlareLayer>(); go.hideFlags = HideFlags.HideAndDontSave; m_ReflectionCameras[currentCamera] = reflectionCamera; } } if( mode >= WaterMode.Refractive ) { // Refraction render texture if( !m_RefractionTexture || m_OldRefractionTextureSize != m_TextureSize ) { if( m_RefractionTexture ) DestroyImmediate( m_RefractionTexture ); m_RefractionTexture = new RenderTexture( m_TextureSize, m_TextureSize, 16 ); m_RefractionTexture.name = "__WaterRefraction" + GetInstanceID(); m_RefractionTexture.isPowerOfTwo = true; m_RefractionTexture.hideFlags = HideFlags.DontSave; m_OldRefractionTextureSize = m_TextureSize; } // Camera for refraction m_RefractionCameras.TryGetValue(currentCamera, out refractionCamera); if (!refractionCamera) // catch both not-in-dictionary and in-dictionary-but-deleted-GO { GameObject go = new GameObject( "Water Refr Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox) ); refractionCamera = go.GetComponent<Camera>(); refractionCamera.enabled = false; refractionCamera.transform.position = transform.position; refractionCamera.transform.rotation = transform.rotation; refractionCamera.gameObject.AddComponent<FlareLayer>(); go.hideFlags = HideFlags.HideAndDontSave; m_RefractionCameras[currentCamera] = refractionCamera; } } } private WaterMode GetWaterMode() { if( m_HardwareWaterSupport < m_WaterMode ) return m_HardwareWaterSupport; else return m_WaterMode; } private WaterMode FindHardwareWaterSupport() { if( !SystemInfo.supportsRenderTextures || !GetComponent<Renderer>() ) return WaterMode.Simple; Material mat = GetComponent<Renderer>().sharedMaterial; if( !mat ) return WaterMode.Simple; string mode = mat.GetTag("WATERMODE", false); if( mode == "Refractive" ) return WaterMode.Refractive; if( mode == "Reflective" ) return WaterMode.Reflective; return WaterMode.Simple; } // Extended sign: returns -1, 0 or 1 based on sign of a private static float sgn(float a) { if (a > 0.0f) return 1.0f; if (a < 0.0f) return -1.0f; return 0.0f; } // Given position/normal of the plane, calculates plane in camera space. private Vector4 CameraSpacePlane (Camera cam, Vector3 pos, Vector3 normal, float sideSign) { Vector3 offsetPos = pos + normal * m_ClipPlaneOffset; Matrix4x4 m = cam.worldToCameraMatrix; Vector3 cpos = m.MultiplyPoint( offsetPos ); Vector3 cnormal = m.MultiplyVector( normal ).normalized * sideSign; return new Vector4( cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos,cnormal) ); } // Adjusts the given projection matrix so that near plane is the given clipPlane // clipPlane is given in camera space. See article in Game Programming Gems 5 and // http://aras-p.info/texts/obliqueortho.html private static void CalculateObliqueMatrix (ref Matrix4x4 projection, Vector4 clipPlane) { Vector4 q = projection.inverse * new Vector4( sgn(clipPlane.x), sgn(clipPlane.y), 1.0f, 1.0f ); Vector4 c = clipPlane * (2.0F / (Vector4.Dot (clipPlane, q))); // third row = clip plane - fourth row projection[2] = c.x - projection[3]; projection[6] = c.y - projection[7]; projection[10] = c.z - projection[11]; projection[14] = c.w - projection[15]; } // Calculates reflection matrix around the given plane private static void CalculateReflectionMatrix (ref Matrix4x4 reflectionMat, Vector4 plane) { reflectionMat.m00 = (1F - 2F*plane[0]*plane[0]); reflectionMat.m01 = ( - 2F*plane[0]*plane[1]); reflectionMat.m02 = ( - 2F*plane[0]*plane[2]); reflectionMat.m03 = ( - 2F*plane[3]*plane[0]); reflectionMat.m10 = ( - 2F*plane[1]*plane[0]); reflectionMat.m11 = (1F - 2F*plane[1]*plane[1]); reflectionMat.m12 = ( - 2F*plane[1]*plane[2]); reflectionMat.m13 = ( - 2F*plane[3]*plane[1]); reflectionMat.m20 = ( - 2F*plane[2]*plane[0]); reflectionMat.m21 = ( - 2F*plane[2]*plane[1]); reflectionMat.m22 = (1F - 2F*plane[2]*plane[2]); reflectionMat.m23 = ( - 2F*plane[3]*plane[2]); reflectionMat.m30 = 0F; reflectionMat.m31 = 0F; reflectionMat.m32 = 0F; reflectionMat.m33 = 1F; } }
using System; using System.ComponentModel; using System.IO; using System.Windows.Forms; using FileHelpers; namespace FileHelpersSamples { /// <summary> /// Read a fixed length file as a DataTable and /// show it on a grid. /// <para/> /// This is useful for Crystal reports. /// </summary> public class frmEasyToDataTable : frmFather { private TextBox txtData; private Button cmdRun; private Label label1; private Label label3; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label4; private System.Windows.Forms.DataGrid DataGridDatos; /// <summary> /// Required designer variable. /// </summary> private Container components = null; public frmEasyToDataTable() { // // Required for Windows Form Designer support // InitializeComponent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof (frmEasyToDataTable)); this.txtData = new System.Windows.Forms.TextBox(); this.cmdRun = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.DataGridDatos = new System.Windows.Forms.DataGrid(); this.SuspendLayout(); // // pictureBox3 // this.pictureBox3.Location = new System.Drawing.Point(578, 7); // // txtData // this.txtData.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.txtData.Location = new System.Drawing.Point(8, 328); this.txtData.Multiline = true; this.txtData.Name = "txtData"; this.txtData.ReadOnly = true; this.txtData.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.txtData.Size = new System.Drawing.Size(664, 136); this.txtData.TabIndex = 1; this.txtData.Text = resources.GetString("txtData.Text"); this.txtData.WordWrap = false; // // cmdRun // this.cmdRun.BackColor = System.Drawing.Color.FromArgb(((int) (((byte) (0)))), ((int) (((byte) (0)))), ((int) (((byte) (110))))); this.cmdRun.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.cmdRun.ForeColor = System.Drawing.Color.Gainsboro; this.cmdRun.Location = new System.Drawing.Point(336, 8); this.cmdRun.Name = "cmdRun"; this.cmdRun.Size = new System.Drawing.Size(152, 32); this.cmdRun.TabIndex = 0; this.cmdRun.Text = "RUN >>"; this.cmdRun.Click += new System.EventHandler(this.cmdRun_Click); // // label1 // this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label1.ForeColor = System.Drawing.Color.White; this.label1.Location = new System.Drawing.Point(8, 117); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(216, 16); this.label1.TabIndex = 8; this.label1.Text = "Output DataTable"; // // label3 // this.label3.BackColor = System.Drawing.Color.Transparent; this.label3.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label3.ForeColor = System.Drawing.Color.White; this.label3.Location = new System.Drawing.Point(8, 312); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(264, 16); this.label3.TabIndex = 9; this.label3.Text = "Input Data to the FileHelperEngine"; // // textBox1 // this.textBox1.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.textBox1.Location = new System.Drawing.Point(8, 75); this.textBox1.Multiline = true; this.textBox1.Name = "textBox1"; this.textBox1.ReadOnly = true; this.textBox1.Size = new System.Drawing.Size(664, 39); this.textBox1.TabIndex = 13; this.textBox1.Text = "FileHelpersEngine engine = new FileHelpersEngine(typeof(CustomerFixed));\r\nDataGri" + "dDatos.DataSource = engine.ReadFileAsDT(\"infile.txt\");"; this.textBox1.WordWrap = false; // // label4 // this.label4.BackColor = System.Drawing.Color.Transparent; this.label4.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label4.ForeColor = System.Drawing.Color.White; this.label4.Location = new System.Drawing.Point(8, 56); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(152, 16); this.label4.TabIndex = 12; this.label4.Text = "Code to Read the File"; // // DataGridDatos // this.DataGridDatos.CaptionVisible = false; this.DataGridDatos.DataMember = ""; this.DataGridDatos.GridLineColor = System.Drawing.Color.FromArgb(((int) (((byte) (224)))), ((int) (((byte) (224)))), ((int) (((byte) (224))))); this.DataGridDatos.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.DataGridDatos.Location = new System.Drawing.Point(8, 134); this.DataGridDatos.Name = "DataGridDatos"; this.DataGridDatos.ParentRowsVisible = false; this.DataGridDatos.ReadOnly = true; this.DataGridDatos.Size = new System.Drawing.Size(664, 170); this.DataGridDatos.TabIndex = 14; // // frmEasyToDataTable // this.AutoScaleBaseSize = new System.Drawing.Size(5, 14); this.ClientSize = new System.Drawing.Size(680, 496); this.Controls.Add(this.DataGridDatos); this.Controls.Add(this.label4); this.Controls.Add(this.label1); this.Controls.Add(this.cmdRun); this.Controls.Add(this.txtData); this.Controls.Add(this.label3); this.Controls.Add(this.textBox1); this.Name = "frmEasyToDataTable"; this.Text = "FileHelpers - Read as DataTable"; this.Controls.SetChildIndex(this.pictureBox3, 0); this.Controls.SetChildIndex(this.textBox1, 0); this.Controls.SetChildIndex(this.label3, 0); this.Controls.SetChildIndex(this.txtData, 0); this.Controls.SetChildIndex(this.cmdRun, 0); this.Controls.SetChildIndex(this.label1, 0); this.Controls.SetChildIndex(this.label4, 0); this.Controls.SetChildIndex(this.DataGridDatos, 0); this.ResumeLayout(false); this.PerformLayout(); } #endregion /// <summary> /// Read the file as a data table /// </summary> private void cmdRun_Click(object sender, EventArgs e) { FileHelperEngine engine = new FileHelperEngine(typeof (CustomersFixed)); DataGridDatos.DataSource = engine.ReadStringAsDT(txtData.Text); ; } } }