context
stringlengths
2.52k
185k
gt
stringclasses
1 value
//------------------------------------------------------------------------------ // <copyright file="BaseDataList.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design; using System.Web; using System.Web.UI; using System.Web.Util; /// <devdoc> /// <para>Serves as the abstract base class for the <see cref='System.Web.UI.WebControls.DataList'/> and <see cref='System.Web.UI.WebControls.DataGrid'/> /// controls and implements the selection semantics which are common to both /// controls.</para> /// </devdoc> [ DefaultEvent("SelectedIndexChanged"), DefaultProperty("DataSource"), Designer("System.Web.UI.Design.WebControls.BaseDataListDesigner, " + AssemblyRef.SystemDesign) ] public abstract class BaseDataList : WebControl { private static readonly object EventSelectedIndexChanged = new object(); internal const string ItemCountViewStateKey = "_!ItemCount"; private object dataSource; private DataKeyCollection dataKeysCollection; private bool _requiresDataBinding; private bool _inited; private bool _throwOnDataPropertyChange; private DataSourceView _currentView; private bool _currentViewIsFromDataSourceID; private bool _currentViewValid; private DataSourceSelectArguments _arguments; private bool _pagePreLoadFired; [ DefaultValue(""), Localizable(true), WebCategory("Accessibility"), WebSysDescription(SR.DataControls_Caption) ] public virtual string Caption { get { string s = (string)ViewState["Caption"]; return (s != null) ? s : String.Empty; } set { ViewState["Caption"] = value; } } [ DefaultValue(TableCaptionAlign.NotSet), WebCategory("Accessibility"), WebSysDescription(SR.WebControl_CaptionAlign) ] public virtual TableCaptionAlign CaptionAlign { get { object o = ViewState["CaptionAlign"]; return (o != null) ? (TableCaptionAlign)o : TableCaptionAlign.NotSet; } set { if ((value < TableCaptionAlign.NotSet) || (value > TableCaptionAlign.Right)) { throw new ArgumentOutOfRangeException("value"); } ViewState["CaptionAlign"] = value; } } /// <devdoc> /// <para>Indicates the amount of space between cells.</para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(-1), WebSysDescription(SR.BaseDataList_CellPadding) ] public virtual int CellPadding { get { if (ControlStyleCreated == false) { return -1; } return ((TableStyle)ControlStyle).CellPadding; } set { ((TableStyle)ControlStyle).CellPadding = value; } } /// <devdoc> /// <para>Gets or sets the amount of space between the contents of /// a cell and the cell's border.</para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(0), WebSysDescription(SR.BaseDataList_CellSpacing) ] public virtual int CellSpacing { get { if (ControlStyleCreated == false) { return 0; } return ((TableStyle)ControlStyle).CellSpacing; } set { ((TableStyle)ControlStyle).CellSpacing = value; } } public override ControlCollection Controls { get { EnsureChildControls(); return base.Controls; } } /// <devdoc> /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), WebSysDescription(SR.BaseDataList_DataKeys) ] public DataKeyCollection DataKeys { get { if (dataKeysCollection == null) { dataKeysCollection = new DataKeyCollection(this.DataKeysArray); } return dataKeysCollection; } } /// <devdoc> /// </devdoc> protected ArrayList DataKeysArray { get { object o = ViewState["DataKeys"]; if (o == null) { o = new ArrayList(); ViewState["DataKeys"] = o; } return(ArrayList)o; } } /// <devdoc> /// <para>Indicatesthe primary key field in the data source referenced by <see cref='System.Web.UI.WebControls.BaseDataList.DataSource'/>.</para> /// </devdoc> [ DefaultValue(""), Themeable(false), WebCategory("Data"), WebSysDescription(SR.BaseDataList_DataKeyField) ] public virtual string DataKeyField { get { object o = ViewState["DataKeyField"]; if (o != null) return(string)o; return String.Empty; } set { ViewState["DataKeyField"] = value; } } /// <devdoc> /// </devdoc> [ DefaultValue(""), Themeable(false), WebCategory("Data"), WebSysDescription(SR.BaseDataList_DataMember) ] public string DataMember { get { object o = ViewState["DataMember"]; if (o != null) return (string)o; return String.Empty; } set { ViewState["DataMember"] = value; OnDataPropertyChanged(); } } /// <devdoc> /// <para>Gets /// or sets the source to a list of values used to populate /// the items within the control.</para> /// </devdoc> [ Bindable(true), DefaultValue(null), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Themeable(false), WebCategory("Data"), WebSysDescription(SR.BaseDataBoundControl_DataSource), ] public virtual object DataSource { get { return dataSource; } set { if ((value == null) || (value is IListSource) || (value is IEnumerable)) { dataSource = value; OnDataPropertyChanged(); } else { throw new ArgumentException(SR.GetString(SR.Invalid_DataSource_Type, ID)); } } } /// <summary> /// The ID of the DataControl that this control should use to retrieve /// its data source. When the control is bound to a DataControl, it /// can retrieve a data source instance on-demand, and thereby attempt /// to work in auto-DataBind mode. /// </summary> [ DefaultValue(""), IDReferenceProperty(typeof(DataSourceControl)), Themeable(false), WebCategory("Data"), WebSysDescription(SR.BaseDataBoundControl_DataSourceID) ] public virtual string DataSourceID { get { object o = ViewState["DataSourceID"]; if (o != null) { return (string)o; } return String.Empty; } set { ViewState["DataSourceID"] = value; OnDataPropertyChanged(); } } /// <devdoc> /// <para>Gets or sets a value that specifies the grid line style.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(GridLines.Both), WebSysDescription(SR.DataControls_GridLines) ] public virtual GridLines GridLines { get { if (ControlStyleCreated == false) { return GridLines.Both; } return ((TableStyle)ControlStyle).GridLines; } set { ((TableStyle)ControlStyle).GridLines = value; } } /// <devdoc> /// <para>Gets or sets a value that specifies the alignment of a rows with respect /// surrounding text.</para> /// </devdoc> [ Category("Layout"), DefaultValue(HorizontalAlign.NotSet), WebSysDescription(SR.WebControl_HorizontalAlign) ] public virtual HorizontalAlign HorizontalAlign { get { if (ControlStyleCreated == false) { return HorizontalAlign.NotSet; } return ((TableStyle)ControlStyle).HorizontalAlign; } set { ((TableStyle)ControlStyle).HorizontalAlign = value; } } protected bool Initialized { get { return _inited; } } protected bool IsBoundUsingDataSourceID { get { return (DataSourceID.Length > 0); } } public override bool SupportsDisabledAttribute { get { return RenderingCompatibility < VersionUtil.Framework40; } } protected bool RequiresDataBinding { get { return _requiresDataBinding; } set { _requiresDataBinding = value; } } protected DataSourceSelectArguments SelectArguments { get { if (_arguments == null) { _arguments = CreateDataSourceSelectArguments(); } return _arguments; } } [ DefaultValue(false), WebCategory("Accessibility"), WebSysDescription(SR.Table_UseAccessibleHeader) ] public virtual bool UseAccessibleHeader { get { object b = ViewState["UseAccessibleHeader"]; return (b != null) ? (bool)b : false; } set { ViewState["UseAccessibleHeader"] = value; } } /// <devdoc> /// <para>Occurs when an item on the list is selected.</para> /// </devdoc> [ WebCategory("Action"), WebSysDescription(SR.BaseDataList_OnSelectedIndexChanged) ] public event EventHandler SelectedIndexChanged { add { Events.AddHandler(EventSelectedIndexChanged, value); } remove { Events.RemoveHandler(EventSelectedIndexChanged, value); } } /// <devdoc> /// <para> Not coded yet.</para> /// </devdoc> protected override void AddParsedSubObject(object obj) { return; } /// <devdoc> /// Connects this data bound control to the appropriate DataSourceView /// and hooks up the appropriate event listener for the /// DataSourceViewChanged event. The return value is the new view (if /// any) that was connected to. An exception is thrown if there is /// a problem finding the requested view or data source. /// </devdoc> private DataSourceView ConnectToDataSourceView() { if (_currentViewValid && !DesignMode) { // If the current view is correct, there is no need to reconnect return _currentView; } // Disconnect from old view, if necessary if ((_currentView != null) && (_currentViewIsFromDataSourceID)) { // We only care about this event if we are bound through the DataSourceID property _currentView.DataSourceViewChanged -= new EventHandler(OnDataSourceViewChanged); } // Connect to new view IDataSource ds = null; string dataSourceID = DataSourceID; if (dataSourceID.Length != 0) { // Try to find a DataSource control with the ID specified in DataSourceID Control control = DataBoundControlHelper.FindControl(this, dataSourceID); if (control == null) { throw new HttpException(SR.GetString(SR.DataControl_DataSourceDoesntExist, ID, dataSourceID)); } ds = control as IDataSource; if (ds == null) { throw new HttpException(SR.GetString(SR.DataControl_DataSourceIDMustBeDataControl, ID, dataSourceID)); } } if (ds == null) { // DataSource control was not found, construct a temporary data source to wrap the data ds = new ReadOnlyDataSource(DataSource, DataMember); } else { // Ensure that both DataSourceID as well as DataSource are not set at the same time if (DataSource != null) { throw new InvalidOperationException(SR.GetString(SR.DataControl_MultipleDataSources, ID)); } } // IDataSource was found, extract the appropriate view and return it DataSourceView newView = ds.GetView(DataMember); if (newView == null) { throw new InvalidOperationException(SR.GetString(SR.DataControl_ViewNotFound, ID)); } _currentViewIsFromDataSourceID = IsBoundUsingDataSourceID; _currentView = newView; if ((_currentView != null) && (_currentViewIsFromDataSourceID)) { // We only care about this event if we are bound through the DataSourceID property _currentView.DataSourceViewChanged += new EventHandler(OnDataSourceViewChanged); } _currentViewValid = true; return _currentView; } /// <internalonly/> /// <devdoc> /// <para>Creates a child control using the view state.</para> /// </devdoc> protected internal override void CreateChildControls() { Controls.Clear(); if (ViewState[ItemCountViewStateKey] == null) { if (RequiresDataBinding) { EnsureDataBound(); } } else { // create the control hierarchy using the view state (and // not the datasource) CreateControlHierarchy(false); ClearChildViewState(); } } protected abstract void CreateControlHierarchy(bool useDataSource); public override void DataBind() { // Don't databind to a data source control when the control is in the designer but not top-level if (IsBoundUsingDataSourceID && DesignMode && (Site == null)) { return; } // do our own databinding RequiresDataBinding = false; OnDataBinding(EventArgs.Empty); } protected virtual DataSourceSelectArguments CreateDataSourceSelectArguments() { return DataSourceSelectArguments.Empty; } protected void EnsureDataBound() { try { _throwOnDataPropertyChange = true; if (RequiresDataBinding && DataSourceID.Length > 0) { DataBind(); } } finally { _throwOnDataPropertyChange = false; } } /// <devdoc> /// Returns an IEnumerable that is the DataSource, which either came /// from the DataSource property or from the control bound via the /// DataSourceID property. /// </devdoc> protected virtual IEnumerable GetData() { ConnectToDataSourceView(); Debug.Assert(_currentViewValid); if (_currentView != null) { return _currentView.ExecuteSelect(SelectArguments); } return null; } /// <devdoc> /// <para>Determines if the specified data type can be bound to.</para> /// </devdoc> public static bool IsBindableType(Type type) { return(type.IsPrimitive || (type == typeof(string)) || (type == typeof(DateTime)) || (type == typeof(Decimal))); } /// <internalonly/> /// <devdoc> /// <para>Raises the <see langword='DataBinding '/>event of a <see cref='System.Web.UI.WebControls.BaseDataList'/> /// .</para> /// </devdoc> protected override void OnDataBinding(EventArgs e) { base.OnDataBinding(e); // reset the control state Controls.Clear(); ClearChildViewState(); // and create the control hierarchy using the datasource dataKeysCollection = null; CreateControlHierarchy(true); ChildControlsCreated = true; TrackViewState(); } /// <devdoc> /// This method is called when DataMember, DataSource, or DataSourceID is changed. /// </devdoc> protected virtual void OnDataPropertyChanged() { if (_throwOnDataPropertyChange) { throw new HttpException(SR.GetString(SR.DataBoundControl_InvalidDataPropertyChange, ID)); } if (_inited) { RequiresDataBinding = true; } _currentViewValid = false; } protected virtual void OnDataSourceViewChanged(object sender, EventArgs e) { RequiresDataBinding = true; } protected internal override void OnInit(EventArgs e) { base.OnInit(e); if (Page != null) { Page.PreLoad += new EventHandler(this.OnPagePreLoad); if (!IsViewStateEnabled && Page.IsPostBack) { RequiresDataBinding = true; } } } protected internal override void OnLoad(EventArgs e) { _inited = true; // just in case we were added to the page after PreLoad ConnectToDataSourceView(); if (Page != null && !_pagePreLoadFired && ViewState[ItemCountViewStateKey] == null) { // If the control was added after PagePreLoad, we still need to databind it because it missed its // first change in PagePreLoad. If this control was created by a call to a parent control's DataBind // in Page_Load (with is relatively common), this control will already have been databound even // though pagePreLoad never fired and the page isn't a postback. if (!Page.IsPostBack) { RequiresDataBinding = true; } // If the control was added to the page after page.PreLoad, we'll never get the event and we'll // never databind the control. So if we're catching up and Load happens but PreLoad never happened, // call DataBind. This may make the control get databound twice if the user called DataBind on the control // directly in Page.OnLoad, but better to bind twice than never to bind at all. else if (IsViewStateEnabled) { RequiresDataBinding = true; } } base.OnLoad(e); } private void OnPagePreLoad(object sender, EventArgs e) { _inited = true; if (Page != null) { Page.PreLoad -= new EventHandler(this.OnPagePreLoad); // Setting RequiresDataBinding to true in OnLoad is too late because the OnLoad page event // happens before the control.OnLoad method gets called. So a page_load handler on the page // that calls DataBind won't prevent DataBind from getting called again in PreRender. if (!Page.IsPostBack) { RequiresDataBinding = true; } // If this is a postback and viewstate is enabled, but we have never bound the control // before, it is probably because its visibility was changed in the postback. In this // case, we need to bind the control or it will never appear. This is a common scenario // for Wizard and MultiView. if (Page.IsPostBack && IsViewStateEnabled && ViewState[ItemCountViewStateKey] == null) { RequiresDataBinding = true; } } _pagePreLoadFired = true; } protected internal override void OnPreRender(EventArgs e) { EnsureDataBound(); base.OnPreRender(e); } /// <devdoc> /// <para>Raises the <see cref='System.Web.UI.WebControls.BaseDataList.SelectedIndexChanged'/>event of a <see cref='System.Web.UI.WebControls.BaseDataList'/>.</para> /// </devdoc> protected virtual void OnSelectedIndexChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[EventSelectedIndexChanged]; if (handler != null) handler(this, e); } protected internal abstract void PrepareControlHierarchy(); /// <internalonly/> /// <devdoc> /// <para>Displays the control on the client.</para> /// </devdoc> protected internal override void Render(HtmlTextWriter writer) { PrepareControlHierarchy(); RenderContents(writer); } } }
using UnityEngine; using System.Collections; public class RandFuncs { // Return an array of integers containing the numbers from zero to num. public static int[] Indices(int num) { int[] result = new int[num]; for (int i = 0; i < result.Length; i++) { result[i] = i; } return result; } // Uniform random number, 0..1 range. public static float Rnd() { return Random.value; } // Random integer in the range first..last-1. public static int RndRange(int first, int last) { return Random.Range(first, last); } // As above, but the start of the range is assumed to be zero. public static int RndRange(int last) { return Random.Range(0, last); } // Random shuffling of the supplied integer array. public static void Shuffle(int[] ints) { int temp; for (int i = 0; i < ints.Length; i++) { temp = ints[i]; int swapIndex = RndRange(ints.Length); ints[i] = ints[swapIndex]; ints[swapIndex] = temp; } } // Sum of the values in the supplied integer array. public static int Sum(int[] ints) { int result = 0; for (int i = 0; i < ints.Length; i++) { result += ints[i]; } return result; } // Sum of the values in the supplied float array. public static float Sum(float[] floats) { float result = 0f; for (int i = 0; i < floats.Length; i++) { result += floats[i]; } return result; } // Choose an integer at random, according to the supplied distribution. public static int Sample(float[] distro, float total) { float randVal = total * Rnd(); for (int i = 0; i < distro.Length; i++) { if (randVal < distro[i]) { return i; } randVal -= distro[i]; } return distro.Length - 1; } // As above, but calculate the total too. public static int Sample(float[] distro) { float total = Sum(distro); return Sample(distro, total); } // Sample several items without replacement. public static int[] SampleRemove(int maxNum, int numSamples) { int[] result = new int[numSamples]; int numNeeded = numSamples; for (int numLeft = maxNum; numLeft > 0; numLeft--) { float chance = (float) numNeeded / (float) numLeft; if (Rnd() < chance) { result[--numNeeded] = numLeft - 1; } if (numNeeded == 0) { break; } } if (numNeeded != 0) { result[0] = 0; } return result; } // Make a string representation of an integer array. public static string Dump(int[] ints) { if (ints.Length == 0) { return "<Empty>"; } string result = ints[0].ToString(); for (int i = 1; i < ints.Length; i++) { result += ", " + ints[i].ToString(); } return result; } // Make a string representation of a float array. public static string Dump(float[] floats) { if (floats.Length == 0) { return "<Empty>"; } string result = floats[0].ToString(); for (int i = 1; i < floats.Length; i++) { result += ", " + floats[i].ToString(); } return result; } } // Class to perform fast sampling without replacement from a distribution. This // has a linear time preprocessing step that is performed before sampling // takes place. public class FastSample { float[] distro; int[] aliases; float mean; public FastSample(params float[] initDistro) { distro = new float[initDistro.Length]; float total = 0f; for (int i = 0; i < distro.Length; i++) { distro[i] = initDistro[i]; total += distro[i]; } Debug.Log(string.Format("Distro: {0}", RandFuncs.Dump(distro))); mean = total / (float) distro.Length; Debug.Log(string.Format("Mean: {0}", mean)); int[] sep = new int[distro.Length]; int shortMarker = 0; int tallMarker = sep.Length - 1; for (int i = 0; i < distro.Length; i++) { if (distro[i] < mean) { sep[shortMarker++] = i; } else { sep[tallMarker--] = i; } } Debug.Log(string.Format("Sep: {0}", RandFuncs.Dump(sep))); tallMarker++; Debug.Log(string.Format("Tall marker: {0}", tallMarker)); aliases = new int[distro.Length]; for (int i = 0; i < (sep.Length - 1); i++) { int curr = sep[i]; float shortfall = mean - distro[curr]; int firstTall = sep[tallMarker]; distro[firstTall] -= shortfall; aliases[curr] = firstTall; if (distro[firstTall] < mean) { tallMarker++; } } aliases[sep[sep.Length - 1]] = sep[sep.Length - 1]; } public int Next() { float rndVal = RandFuncs.Rnd() * (float) distro.Length; int slotNum = Mathf.Min(Mathf.FloorToInt(rndVal), distro.Length - 1); float fracPart = (rndVal - (float) slotNum) * mean; if (fracPart < distro[slotNum]) { return slotNum; } else { return aliases[slotNum]; } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.IO; using System.Windows.Forms; using FileHelpers; namespace FileHelpersSamples { /// <summary> /// Run the engine over a delimited file and /// show the result in a grid /// </summary> public class frmEasySampleDelimited : frmFather { private TextBox txtClass; private TextBox txtData; private PropertyGrid grid1; private Button cmdRun; private Label label2; private Label label1; private Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox textBox1; /// <summary> /// Required designer variable. /// </summary> private Container components = null; public frmEasySampleDelimited() { // // 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 (frmEasySampleDelimited)); this.txtClass = new System.Windows.Forms.TextBox(); this.txtData = new System.Windows.Forms.TextBox(); this.grid1 = new System.Windows.Forms.PropertyGrid(); this.cmdRun = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // pictureBox3 // // // txtClass // this.txtClass.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.txtClass.Location = new System.Drawing.Point(8, 136); this.txtClass.Multiline = true; this.txtClass.Name = "txtClass"; this.txtClass.ReadOnly = true; this.txtClass.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtClass.Size = new System.Drawing.Size(328, 160); this.txtClass.TabIndex = 0; this.txtClass.Text = resources.GetString("txtClass.Text"); this.txtClass.WordWrap = false; // // 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, 320); 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, 144); this.txtData.TabIndex = 1; this.txtData.Text = resources.GetString("txtData.Text"); this.txtData.WordWrap = false; // // grid1 // this.grid1.HelpVisible = false; this.grid1.LineColor = System.Drawing.SystemColors.ScrollBar; this.grid1.Location = new System.Drawing.Point(344, 136); this.grid1.Name = "grid1"; this.grid1.PropertySort = System.Windows.Forms.PropertySort.Alphabetical; this.grid1.Size = new System.Drawing.Size(320, 160); this.grid1.TabIndex = 2; this.grid1.ToolbarVisible = 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.White; 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.UseVisualStyleBackColor = false; this.cmdRun.Click += new System.EventHandler(this.cmdRun_Click); // // label2 // this.label2.BackColor = System.Drawing.Color.Transparent; this.label2.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label2.ForeColor = System.Drawing.Color.White; this.label2.Location = new System.Drawing.Point(8, 120); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(216, 16); this.label2.TabIndex = 7; this.label2.Text = "Code of the Mapping Class"; // // 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(344, 120); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(216, 16); this.label1.TabIndex = 8; this.label1.Text = "Output Array"; // // 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, 304); 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"; // // 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 = 10; this.label4.Text = "Code to Read the File"; // // 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, 72); this.textBox1.Multiline = true; this.textBox1.Name = "textBox1"; this.textBox1.ReadOnly = true; this.textBox1.Size = new System.Drawing.Size(656, 40); this.textBox1.TabIndex = 11; this.textBox1.Text = "var engine = new FileHelperEngine<CustomersVerticalBar>();\r\n ... = engine.ReadFi" + "le(\"infile.txt\")"; this.textBox1.WordWrap = false; // // frmEasySampleDelimited // this.AutoScaleBaseSize = new System.Drawing.Size(5, 14); this.ClientSize = new System.Drawing.Size(680, 496); this.Controls.Add(this.textBox1); this.Controls.Add(this.label4); this.Controls.Add(this.label1); this.Controls.Add(this.label2); this.Controls.Add(this.cmdRun); this.Controls.Add(this.grid1); this.Controls.Add(this.txtData); this.Controls.Add(this.txtClass); this.Controls.Add(this.label3); this.Name = "frmEasySampleDelimited"; this.Text = "FileHelpers - Easy Example"; this.Controls.SetChildIndex(this.label3, 0); this.Controls.SetChildIndex(this.txtClass, 0); this.Controls.SetChildIndex(this.txtData, 0); this.Controls.SetChildIndex(this.grid1, 0); this.Controls.SetChildIndex(this.cmdRun, 0); this.Controls.SetChildIndex(this.label2, 0); this.Controls.SetChildIndex(this.label1, 0); this.Controls.SetChildIndex(this.label4, 0); this.Controls.SetChildIndex(this.textBox1, 0); this.ResumeLayout(false); this.PerformLayout(); } #endregion /// <summary> /// Run the engine into an array and show data on a grid /// </summary> private void cmdRun_Click(object sender, EventArgs e) { var engine = new FileHelperEngine<CustomersVerticalBar>(); CustomersVerticalBar[] res = (CustomersVerticalBar[]) engine.ReadString(txtData.Text); grid1.SelectedObject = res; } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Data; using System.Data.SqlClient; using System.Drawing.Text; using System.Net.Mail; using System.Threading; using System.Threading.Tasks; namespace AssignmentNotificationEmailWKKI { public class NotificationEmailDb : IUnsentEmailProvider<AlaCarteAssignmentModel> { //private object syncroot = new object(); private int operating = 0; public SqlConnection Connection { get; private set; } public NotificationEmailDb(string connectionString) { Connection = new SqlConnection(connectionString); } ~NotificationEmailDb() { //Dispose(false); } public ImmutableArray<AlaCarteAssignmentModel> GetUnsentEmails() { if (SpinWait.SpinUntil(() => Interlocked.CompareExchange(ref operating, 1, 0) != 0, TimeSpan.FromSeconds(30))) { try { bool alreadyOpen = Connection.State == ConnectionState.Open; if (!alreadyOpen) Connection.Open(); try { IList<Exception> exceptions = null; IList<AlaCarteAssignmentModel> emails = new List<AlaCarteAssignmentModel>(); using (var command = CreateCommand(Connection)) using (var reader = command.ExecuteReader()) { while (reader.Read()) { try { var email = Load(reader); emails.Add(email); } catch(Exception ex) { (exceptions ?? (exceptions = new List<Exception>(1))).Add(ex); } } } return emails.ToImmutableArray(); } finally { if (!alreadyOpen && Connection != null) Connection.Close(); } } finally { Interlocked.CompareExchange(ref operating, 0, 1); } } return ImmutableArray<AlaCarteAssignmentModel>.Empty; } private static AlaCarteAssignmentModel Load(IDataRecord record, AlaCarteAssignmentModel model = null) { model = model ?? new AlaCarteAssignmentModel(); model.NotificationID = GetInt32(record, "NotificationID") ?? 0; model.EmployeeID = GetString(record, "EmployeeID"); var toName = GetString(record, "EmployeeName"); var toEmail = GetString(record, "EmployeeEmail"); if (!String.IsNullOrWhiteSpace(toEmail)) { if (!String.IsNullOrWhiteSpace(toName)) model.AddToAddress(new MailAddress(toEmail, toName)); else model.AddToAddress(new MailAddress(toEmail)); } model.AssignedBy = GetString(record, "AssignedByName"); model.AssignmentName = GetString(record, "QuizTopic"); model.DueDate = GetDateTime(record, "DueDate") ?? DateTime.Today; return model; } private static int? GetInt32(IDataRecord record, string fieldName) { var ordinal = GetOrdinal(record, fieldName); return ordinal.HasValue ? record.GetInt32(ordinal.Value) : (int?)null; } private static string GetString(IDataRecord record, string fieldName) { var ordinal = GetOrdinal(record, fieldName); return ordinal.HasValue ? record.GetString(ordinal.Value) : null; } private static DateTime? GetDateTime(IDataRecord record, string fieldName) { var ordinal = GetOrdinal(record, fieldName); return ordinal.HasValue ? record.GetDateTime(ordinal.Value) : (DateTime?)null; } private static int? GetOrdinal(IDataRecord record, string fieldName) { for (var i=0;i<record.FieldCount;i++) if (record.GetName(i).Equals(fieldName, StringComparison.OrdinalIgnoreCase)) return i; return null; } private static SqlCommand CreateCommand(SqlConnection connection = null) { const string proc = "NeedsNotificationEmail"; return new SqlCommand(proc) { CommandType = CommandType.StoredProcedure, Connection = connection }; } public Task<ImmutableArray<AlaCarteAssignmentModel>> GetUnsentEmailsAsync() { return GetUnsentEmailsAsync(CancellationToken.None); } public async Task<ImmutableArray<AlaCarteAssignmentModel>> GetUnsentEmailsAsync(CancellationToken token) { if (SpinWait.SpinUntil(() => Interlocked.CompareExchange(ref operating, 1, 0) != 0, TimeSpan.FromSeconds(30))) { try { IList<Exception> exceptions = null; IList<AlaCarteAssignmentModel> emails = new List<AlaCarteAssignmentModel>(); bool alreadyOpen = Connection.State == ConnectionState.Open; if (!alreadyOpen) await Connection.OpenAsync(token).ConfigureAwait(false); try { using (var command = CreateCommand(Connection)) using (var reader = await command.ExecuteReaderAsync(token)) { while (await reader.ReadAsync(token)) { try { var email = Load(reader); emails.Add(email); } catch(Exception ex) { (exceptions ?? (exceptions = new List<Exception>(1))).Add(ex); } } } } finally { if (!alreadyOpen && Connection != null) Connection.Close(); } return emails.ToImmutableArray(); } finally { Interlocked.CompareExchange(ref operating, 0, 1); } } return ImmutableArray<AlaCarteAssignmentModel>.Empty; } public void Dispose() { try { Dispose(true); } finally { GC.SuppressFinalize(this); } } private int _disposed; public virtual void Dispose(bool disposing) { try { if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 0) { if (disposing) { if (Connection != null) Connection.Dispose(); Connection = null; } } } finally { //base.Dispose(disposing); } } public bool UpdateEmailAsSent() { throw new NotImplementedException(); } public Task UpdateEmailAsSentAsync(CancellationToken token) { throw new NotImplementedException(); } } }
using System; using System.Runtime.InteropServices; using System.Text; namespace DbgEng.NoExceptions { [ComImport, ComConversionLoss, Guid("C65FA83E-1E69-475E-8E0E-B5D79E9CC17E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDebugSymbols5 : IDebugSymbols4 { #pragma warning disable CS0108 // XXX hides inherited member. This is COM default. #region IDebugSymbols [PreserveSig] int GetSymbolOptions( [Out] out uint Options); [PreserveSig] int AddSymbolOptions( [In] uint Options); [PreserveSig] int RemoveSymbolOptions( [In] uint Options); [PreserveSig] int SetSymbolOptions( [In] uint Options); [PreserveSig] int GetNameByOffset( [In] ulong Offset, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize, [Out] out ulong Displacement); [PreserveSig] int GetOffsetByName( [In, MarshalAs(UnmanagedType.LPStr)] string Symbol, [Out] out ulong Offset); [PreserveSig] int GetNearNameByOffset( [In] ulong Offset, [In] int Delta, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize, [Out] out ulong Displacement); [PreserveSig] int GetLineByOffset( [In] ulong Offset, [Out] out uint Line, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder FileBuffer, [In] uint FileBufferSize, [Out] out uint FileSize, [Out] out ulong Displacement); [PreserveSig] int GetOffsetByLine( [In] uint Line, [In, MarshalAs(UnmanagedType.LPStr)] string File, [Out] out ulong Offset); [PreserveSig] int GetNumberModules( [Out] out uint Loaded, [Out] out uint Unloaded); [PreserveSig] int GetModuleByIndex( [In] uint Index, [Out] out ulong Base); [PreserveSig] int GetModuleByModuleName( [In, MarshalAs(UnmanagedType.LPStr)] string Name, [In] uint StartIndex, [Out] out uint Index, [Out] out ulong Base); [PreserveSig] int GetModuleByOffset( [In] ulong Offset, [In] uint StartIndex, [Out] out uint Index, [Out] out ulong Base); [PreserveSig] int GetModuleNames( [In] uint Index, [In] ulong Base, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder ImageNameBuffer, [In] uint ImageNameBufferSize, [Out] out uint ImageNameSize, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder ModuleNameBuffer, [In] uint ModuleNameBufferSize, [Out] out uint ModuleNameSize, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder LoadedImageNameBuffer, [In] uint LoadedImageNameBufferSize, [Out] out uint LoadedImageNameSize); [PreserveSig] int GetModuleParameters( [In] uint Count, [In] ref ulong Bases, [In] uint Start = default(uint), [Out, MarshalAs(UnmanagedType.LPArray)] _DEBUG_MODULE_PARAMETERS[] Params = null); [PreserveSig] int GetSymbolModule( [In, MarshalAs(UnmanagedType.LPStr)] string Symbol, [Out] out ulong Base); [PreserveSig] int GetTypeName( [In] ulong Module, [In] uint TypeId, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize); [PreserveSig] int GetTypeId( [In] ulong Module, [In, MarshalAs(UnmanagedType.LPStr)] string Name, [Out] out uint Id); [PreserveSig] int GetTypeSize( [In] ulong Module, [In] uint TypeId, [Out] out uint Size); [PreserveSig] int GetFieldOffset( [In] ulong Module, [In] uint TypeId, [In, MarshalAs(UnmanagedType.LPStr)] string Field, [Out] out uint Offset); [PreserveSig] int GetSymbolTypeId( [In, MarshalAs(UnmanagedType.LPStr)] string Symbol, [Out] out uint TypeId, [Out] out ulong Module); [PreserveSig] int GetOffsetTypeId( [In] ulong Offset, [Out] out uint TypeId, [Out] out ulong Module); [PreserveSig] int ReadTypedDataVirtual( [In] ulong Offset, [In] ulong Module, [In] uint TypeId, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] Buffer, [In] uint BufferSize, [Out] out uint BytesRead); [PreserveSig] int WriteTypedDataVirtual( [In] ulong Offset, [In] ulong Module, [In] uint TypeId, [In] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesWritten); [PreserveSig] int OutputTypedDataVirtual( [In] uint OutputControl, [In] ulong Offset, [In] ulong Module, [In] uint TypeId, [In] uint Flags); [PreserveSig] int ReadTypedDataPhysical( [In] ulong Offset, [In] ulong Module, [In] uint TypeId, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesRead); [PreserveSig] int WriteTypedDataPhysical( [In] ulong Offset, [In] ulong Module, [In] uint TypeId, [In] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesWritten); [PreserveSig] int OutputTypedDataPhysical( [In] uint OutputControl, [In] ulong Offset, [In] ulong Module, [In] uint TypeId, [In] uint Flags); [PreserveSig] int GetScope( [Out] out ulong InstructionOffset, [Out] out _DEBUG_STACK_FRAME ScopeFrame, [Out] IntPtr ScopeContext = default(IntPtr), [In] uint ScopeContextSize = default(uint)); [PreserveSig] int SetScope( [In] ulong InstructionOffset, [In] ref _DEBUG_STACK_FRAME ScopeFrame, [In] IntPtr ScopeContext = default(IntPtr), [In] uint ScopeContextSize = default(uint)); [PreserveSig] int ResetScope(); [PreserveSig] int GetScopeSymbolGroup( [In] uint Flags, [In, MarshalAs(UnmanagedType.Interface)] IDebugSymbolGroup Update, [Out, MarshalAs(UnmanagedType.Interface)] out IDebugSymbolGroup Symbols); [PreserveSig] int CreateSymbolGroup( [Out, MarshalAs(UnmanagedType.Interface)] out IDebugSymbolGroup Symbols); [PreserveSig] int StartSymbolMatch( [In, MarshalAs(UnmanagedType.LPStr)] string Pattern, [Out] out ulong Handle); [PreserveSig] int GetNextSymbolMatch( [In] ulong Handle, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint MatchSize, [Out] out ulong Offset); [PreserveSig] int EndSymbolMatch( [In] ulong Handle); [PreserveSig] int Reload( [In, MarshalAs(UnmanagedType.LPStr)] string Module); [PreserveSig] int GetSymbolPath( [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint PathSize); [PreserveSig] int SetSymbolPath( [In, MarshalAs(UnmanagedType.LPStr)] string Path); [PreserveSig] int AppendSymbolPath( [In, MarshalAs(UnmanagedType.LPStr)] string Addition); [PreserveSig] int GetImagePath( [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint PathSize); [PreserveSig] int SetImagePath( [In, MarshalAs(UnmanagedType.LPStr)] string Path); [PreserveSig] int AppendImagePath( [In, MarshalAs(UnmanagedType.LPStr)] string Addition); [PreserveSig] int GetSourcePath( [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint PathSize); [PreserveSig] int GetSourcePathElement( [In] uint Index, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint ElementSize); [PreserveSig] int SetSourcePath( [In, MarshalAs(UnmanagedType.LPStr)] string Path); [PreserveSig] int AppendSourcePath( [In, MarshalAs(UnmanagedType.LPStr)] string Addition); [PreserveSig] int FindSourceFile( [In] uint StartElement, [In, MarshalAs(UnmanagedType.LPStr)] string File, [In] uint Flags, [Out] out uint FoundElement, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint FoundSize); [PreserveSig] int GetSourceFileLineOffsets( [In, MarshalAs(UnmanagedType.LPStr)] string File, [Out] out ulong Buffer, [In] uint BufferLines, [Out] out uint FileLines); #endregion #region IDebugSymbols2 [PreserveSig] int GetModuleVersionInformation( [In] uint Index, [In] ulong Base, [In, MarshalAs(UnmanagedType.LPStr)] string Item, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint VerInfoSize); [PreserveSig] int GetModuleNameString( [In] uint Which, [In] uint Index, [In] ulong Base, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint NameSize); [PreserveSig] int GetConstantName( [In] ulong Module, [In] uint TypeId, [In] ulong Value, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize); [PreserveSig] int GetFieldName( [In] ulong Module, [In] uint TypeId, [In] uint FieldIndex, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize); [PreserveSig] int GetTypeOptions( [Out] out uint Options); [PreserveSig] int AddTypeOptions( [In] uint Options); [PreserveSig] int RemoveTypeOptions( [In] uint Options); [PreserveSig] int SetTypeOptions( [In] uint Options); #endregion #region IDebugSymbols3 [PreserveSig] int GetNameByOffsetWide( [In] ulong Offset, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize, [Out] out ulong Displacement); [PreserveSig] int GetOffsetByNameWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Symbol, [Out] out ulong Offset); [PreserveSig] int GetNearNameByOffsetWide( [In] ulong Offset, [In] int Delta, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize, [Out] out ulong Displacement); [PreserveSig] int GetLineByOffsetWide( [In] ulong Offset, [Out] out uint Line, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder FileBuffer, [In] uint FileBufferSize, [Out] out uint FileSize, [Out] out ulong Displacement); [PreserveSig] int GetOffsetByLineWide( [In] uint Line, [In, MarshalAs(UnmanagedType.LPWStr)] string File, [Out] out ulong Offset); [PreserveSig] int GetModuleByModuleNameWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Name, [In] uint StartIndex, [Out] out uint Index, [Out] out ulong Base); [PreserveSig] int GetSymbolModuleWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Symbol, [Out] out ulong Base); [PreserveSig] int GetTypeNameWide( [In] ulong Module, [In] uint TypeId, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize); [PreserveSig] int GetTypeIdWide( [In] ulong Module, [In, MarshalAs(UnmanagedType.LPWStr)] string Name, [Out] out uint Id); [PreserveSig] int GetFieldOffsetWide( [In] ulong Module, [In] uint TypeId, [In, MarshalAs(UnmanagedType.LPWStr)] string Field, [Out] out uint Offset); [PreserveSig] int GetSymbolTypeIdWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Symbol, [Out] out uint TypeId, [Out] out ulong Module); [PreserveSig] int GetScopeSymbolGroup2( [In] uint Flags, [In, MarshalAs(UnmanagedType.Interface)] IDebugSymbolGroup2 Update, [Out, MarshalAs(UnmanagedType.Interface)] out IDebugSymbolGroup2 Symbols); [PreserveSig] int CreateSymbolGroup2( [Out, MarshalAs(UnmanagedType.Interface)] out IDebugSymbolGroup2 Symbols); [PreserveSig] int StartSymbolMatchWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Pattern, [Out] out ulong Handle); [PreserveSig] int GetNextSymbolMatchWide( [In] ulong Handle, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint MatchSize, [Out] out ulong Offset); [PreserveSig] int ReloadWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Module); [PreserveSig] int GetSymbolPathWide( [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint PathSize); [PreserveSig] int SetSymbolPathWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Path); [PreserveSig] int AppendSymbolPathWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Addition); [PreserveSig] int GetImagePathWide( [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint PathSize); [PreserveSig] int SetImagePathWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Path); [PreserveSig] int AppendImagePathWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Addition); [PreserveSig] int GetSourcePathWide( [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint PathSize); [PreserveSig] int GetSourcePathElementWide( [In] uint Index, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint ElementSize); [PreserveSig] int SetSourcePathWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Path); [PreserveSig] int AppendSourcePathWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Addition); [PreserveSig] int FindSourceFileWide( [In] uint StartElement, [In, MarshalAs(UnmanagedType.LPWStr)] string File, [In] uint Flags, [Out] out uint FoundElement, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint FoundSize); [PreserveSig] int GetSourceFileLineOffsetsWide( [In, MarshalAs(UnmanagedType.LPWStr)] string File, [Out] out ulong Buffer, [In] uint BufferLines, [Out] out uint FileLines); [PreserveSig] int GetModuleVersionInformationWide( [In] uint Index, [In] ulong Base, [In, MarshalAs(UnmanagedType.LPWStr)] string Item, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint VerInfoSize); [PreserveSig] int GetModuleNameStringWide( [In] uint Which, [In] uint Index, [In] ulong Base, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint NameSize); [PreserveSig] int GetConstantNameWide( [In] ulong Module, [In] uint TypeId, [In] ulong Value, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize); [PreserveSig] int GetFieldNameWide( [In] ulong Module, [In] uint TypeId, [In] uint FieldIndex, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize); [PreserveSig] int IsManagedModule( [In] uint Index, [In] ulong Base); [PreserveSig] int GetModuleByModuleName2( [In, MarshalAs(UnmanagedType.LPStr)] string Name, [In] uint StartIndex, [In] uint Flags, [Out] out uint Index, [Out] out ulong Base); [PreserveSig] int GetModuleByModuleName2Wide( [In, MarshalAs(UnmanagedType.LPWStr)] string Name, [In] uint StartIndex, [In] uint Flags, [Out] out uint Index, [Out] out ulong Base); [PreserveSig] int GetModuleByOffset2( [In] ulong Offset, [In] uint StartIndex, [In] uint Flags, [Out] out uint Index, [Out] out ulong Base); [PreserveSig] int AddSyntheticModule( [In] ulong Base, [In] uint Size, [In, MarshalAs(UnmanagedType.LPStr)] string ImagePath, [In, MarshalAs(UnmanagedType.LPStr)] string ModuleName, [In] uint Flags); [PreserveSig] int AddSyntheticModuleWide( [In] ulong Base, [In] uint Size, [In, MarshalAs(UnmanagedType.LPWStr)] string ImagePath, [In, MarshalAs(UnmanagedType.LPWStr)] string ModuleName, [In] uint Flags); [PreserveSig] int RemoveSyntheticModule( [In] ulong Base); [PreserveSig] int GetCurrentScopeFrameIndex( [Out] out uint Index); [PreserveSig] int SetScopeFrameByIndex( [In] uint Index); [PreserveSig] int SetScopeFromJitDebugInfo( [In] uint OutputControl, [In] ulong InfoOffset); [PreserveSig] int SetScopeFromStoredEvent(); [PreserveSig] int OutputSymbolByOffset( [In] uint OutputControl, [In] uint Flags, [In] ulong Offset); [PreserveSig] int GetFunctionEntryByOffset( [In] ulong Offset, [In] uint Flags, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BufferNeeded); [PreserveSig] int GetFieldTypeAndOffset( [In] ulong Module, [In] uint ContainerTypeId, [In, MarshalAs(UnmanagedType.LPStr)] string Field, [Out] out uint FieldTypeId, [Out] out uint Offset); [PreserveSig] int GetFieldTypeAndOffsetWide( [In] ulong Module, [In] uint ContainerTypeId, [In, MarshalAs(UnmanagedType.LPWStr)] string Field, [Out] out uint FieldTypeId, [Out] out uint Offset); [PreserveSig] int AddSyntheticSymbol( [In] ulong Offset, [In] uint Size, [In, MarshalAs(UnmanagedType.LPStr)] string Name, [In] uint Flags, [Out] out _DEBUG_MODULE_AND_ID Id); [PreserveSig] int AddSyntheticSymbolWide( [In] ulong Offset, [In] uint Size, [In, MarshalAs(UnmanagedType.LPWStr)] string Name, [In] uint Flags, [Out] out _DEBUG_MODULE_AND_ID Id); [PreserveSig] int RemoveSyntheticSymbol( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_MODULE_AND_ID Id); [PreserveSig] int GetSymbolEntriesByOffset( [In] ulong Offset, [In] uint Flags, [Out, MarshalAs(UnmanagedType.LPArray)] _DEBUG_MODULE_AND_ID[] Ids, [Out, MarshalAs(UnmanagedType.LPArray)] ulong[] Displacements, [In] uint IdsCount, [Out] out uint Entries); [PreserveSig] int GetSymbolEntriesByName( [In, MarshalAs(UnmanagedType.LPStr)] string Symbol, [In] uint Flags, [Out, MarshalAs(UnmanagedType.LPArray)] _DEBUG_MODULE_AND_ID[] Ids, [In] uint IdsCount, [Out] out uint Entries); [PreserveSig] int GetSymbolEntriesByNameWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Symbol, [In] uint Flags, [Out, MarshalAs(UnmanagedType.LPArray)] _DEBUG_MODULE_AND_ID[] Ids, [In] uint IdsCount, [Out] out uint Entries); [PreserveSig] int GetSymbolEntryByToken( [In] ulong ModuleBase, [In] uint Token, [Out] out _DEBUG_MODULE_AND_ID Id); [PreserveSig] int GetSymbolEntryInformation( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_MODULE_AND_ID Id, [Out] out _DEBUG_SYMBOL_ENTRY Info); [PreserveSig] int GetSymbolEntryString( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_MODULE_AND_ID Id, [In] uint Which, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint StringSize); [PreserveSig] int GetSymbolEntryStringWide( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_MODULE_AND_ID Id, [In] uint Which, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint StringSize); [PreserveSig] int GetSymbolEntryOffsetRegions( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_MODULE_AND_ID Id, [In] uint Flags, [Out] IntPtr Regions, [In] uint RegionsCount, [Out] out uint RegionsAvail); [PreserveSig] int GetSymbolEntryBySymbolEntry( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_MODULE_AND_ID FromId, [In] uint Flags, [Out] out _DEBUG_MODULE_AND_ID Id); [PreserveSig] int GetSourceEntriesByOffset( [In] ulong Offset, [In] uint Flags, [Out, MarshalAs(UnmanagedType.LPArray)] _DEBUG_SYMBOL_SOURCE_ENTRY[] Entries, [In] uint EntriesCount, [Out] out uint EntriesAvail); [PreserveSig] int GetSourceEntriesByLine( [In] uint Line, [In, MarshalAs(UnmanagedType.LPStr)] string File, [In] uint Flags, [Out, MarshalAs(UnmanagedType.LPArray)] _DEBUG_SYMBOL_SOURCE_ENTRY[] Entries, [In] uint EntriesCount, [Out] out uint EntriesAvail); [PreserveSig] int GetSourceEntriesByLineWide( [In] uint Line, [In, MarshalAs(UnmanagedType.LPWStr)] string File, [In] uint Flags, [Out, MarshalAs(UnmanagedType.LPArray)] _DEBUG_SYMBOL_SOURCE_ENTRY[] Entries, [In] uint EntriesCount, [Out] out uint EntriesAvail); [PreserveSig] int GetSourceEntryString( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_SYMBOL_SOURCE_ENTRY Entry, [In] uint Which, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint StringSize); [PreserveSig] int GetSourceEntryStringWide( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_SYMBOL_SOURCE_ENTRY Entry, [In] uint Which, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint StringSize); [PreserveSig] int GetSourceEntryOffsetRegions( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_SYMBOL_SOURCE_ENTRY Entry, [In] uint Flags, [Out] IntPtr Regions, [In] uint RegionsCount, [Out] out uint RegionsAvail); [PreserveSig] int GetSourceEntryBySourceEntry( [In, MarshalAs(UnmanagedType.LPStruct)] _DEBUG_SYMBOL_SOURCE_ENTRY FromEntry, [In] uint Flags, [Out] out _DEBUG_SYMBOL_SOURCE_ENTRY ToEntry); #endregion #region IDebugSymbols4 [PreserveSig] int GetScopeEx( [Out] out ulong InstructionOffset, [Out] out _DEBUG_STACK_FRAME_EX ScopeFrame, [Out] IntPtr ScopeContext = default(IntPtr), [In] uint ScopeContextSize = default(uint)); [PreserveSig] int SetScopeEx( [In] ulong InstructionOffset, [In] ref _DEBUG_STACK_FRAME_EX ScopeFrame, [In] IntPtr ScopeContext = default(IntPtr), [In] uint ScopeContextSize = default(uint)); [PreserveSig] int GetNameByInlineContext( [In] ulong Offset, [In] uint InlineContext, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize, [Out] out ulong Displacement); [PreserveSig] int GetNameByInlineContextWide( [In] ulong Offset, [In] uint InlineContext, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize, [Out] out ulong Displacement); [PreserveSig] int GetLineByInlineContext( [In] ulong Offset, [In] uint InlineContext, [Out] out uint Line, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder FileBuffer, [In] uint FileBufferSize, [Out] out uint FileSize, [Out] out ulong Displacement); [PreserveSig] int GetLineByInlineContextWide( [In] ulong Offset, [In] uint InlineContext, [Out] out uint Line, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder FileBuffer, [In] uint FileBufferSize, [Out] out uint FileSize, [Out] out ulong Displacement); [PreserveSig] int OutputSymbolByInlineContext( [In] uint OutputControl, [In] uint Flags, [In] ulong Offset, [In] uint InlineContext); #endregion #pragma warning restore CS0108 // XXX hides inherited member. This is COM default. [PreserveSig] int GetCurrentScopeFrameIndexEx( [In] uint Flags, [Out] out uint Index); [PreserveSig] int SetScopeFrameByIndexEx( [In] uint Flags, [In] uint Index); } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class PELoader { // // State // private String m_path; private byte[] m_peImage; private DOSHeader m_dosHeader; private NTHeader m_ntHeader; private COMHeader m_comHeader; private SectionHeader[] m_sectionArray; // // Constructor Methods // public PELoader( String path , byte[] peImage ) { m_path = path; m_peImage = peImage; loadPEHeaders(); } // // Access Methods // internal ArrayReader getStream() { return new ArrayReader( m_peImage ); } internal int getEntryPoint() { return m_comHeader.entryPointToken; } internal int getMetaDataOffset() { return this.VaToOffset( m_comHeader.metaData.virtualAddress ); } internal int getMetaDataSize() { return m_comHeader.metaData.size; } internal int getResourceOffset() { return this.VaToOffsetSafe( m_comHeader.resources.virtualAddress ); } internal int getRelocationOffset() { int limit = m_ntHeader.numberOfSections; for(int i = 0; i < limit; i++) { SectionHeader section = m_sectionArray[i]; if(section.name.StartsWith( ".reloc" )) { return this.VaToOffset( section.virtualAddress ); } } return 0; } internal int getVtableFixupOffset() { return this.VaToOffsetSafe( m_comHeader.vtableFixups.virtualAddress ); } internal int getDelayIATOffset() { return this.VaToOffsetSafe( m_ntHeader.dataDirectory[DirectoryEntry.DELAYLOADIMPORTADDRESSTABLE].virtualAddress ); } internal long getImageBase() { return m_ntHeader.imageBase; } internal int getResourceSize() { return m_comHeader.resources.size; } internal int getVtableFixupSize() { return m_comHeader.vtableFixups.size; } internal int getDelayIATSize() { return m_ntHeader.dataDirectory[DirectoryEntry.DELAYLOADIMPORTADDRESSTABLE].size; } internal bool IsExecutableImage() { return ((m_ntHeader.characteristics & NTHeader.IMAGE_FILE_EXECUTABLE_IMAGE) != 0) && ((m_ntHeader.characteristics & NTHeader.IMAGE_FILE_DLL ) == 0); } // Output Routines public void DumpHeader( LogWriter outputStream ) { outputStream.WriteLine( "// DOS Header:" ); outputStream.WriteLine(); m_dosHeader.DumpLimitedToStream( outputStream ); outputStream.WriteLine( "// PE Header:" ); outputStream.WriteLine(); m_ntHeader.DumpLimitedToStream( outputStream ); this.DumpIAT( outputStream, "Import directory" , m_ntHeader.dataDirectory[DirectoryEntry.IMPORT ] ); this.DumpIAT( outputStream, "Import Address Table" , m_ntHeader.dataDirectory[DirectoryEntry.IMPORTADDRESSTABLE ] ); this.DumpIAT( outputStream, "Delay Load Import Address Table", m_ntHeader.dataDirectory[DirectoryEntry.DELAYLOADIMPORTADDRESSTABLE] ); m_comHeader.DumpHeader( outputStream ); } internal void DumpCodeManager( LogWriter outputStream ) { outputStream.WriteLine( "// Code Manager Table" ); if(m_comHeader.codeManagerTable.size == 0) { outputStream.WriteLine( "// default" ); return; } // BUGBUG throw new NotYetImplemented( "DumpCodeManager" ); } internal void DumpVTables( LogWriter outputStream ) { outputStream.WriteLine( "// VTableFixup Directory:" ); if(m_comHeader.vtableFixups.virtualAddress == 0) { outputStream.WriteLine( "// No data." ); return; } // BUGBUG throw new NotYetImplemented( "DumpVTables" ); } internal void DumpEATTable( LogWriter outputStream ) { outputStream.WriteLine( "// Export Address Table Jumps:" ); if(m_comHeader.exportAddressTableJumps.virtualAddress == 0) { outputStream.WriteLine( "// No data." ); return; } // BUGBUG throw new NotYetImplemented( "DumpEATTable" ); } internal void DumpStatistics( LogWriter outputStream ) { throw new NotYetImplemented( "DumpStatistics" ); } public override String ToString() { return "PELoader(" + m_path + ")"; } // // Private Helper Methods // private void loadPEHeaders() { ArrayReader reader = new ArrayReader( m_peImage ); m_dosHeader = new DOSHeader( reader ); reader.Position = m_dosHeader.lfanew; m_ntHeader = new NTHeader( reader ); // Load the sections int sectionCount = m_ntHeader.numberOfSections; SectionHeader[] sectionArray = new SectionHeader[sectionCount]; m_sectionArray = sectionArray; for(int i = 0; i < sectionCount; i++) { m_sectionArray[i] = new SectionHeader( reader ); int startAddr = sectionArray[i].virtualAddress; int endAddr = sectionArray[i].virtualAddress + sectionArray[i].sizeOfRawData; int delta = sectionArray[i].pointerToRawData - sectionArray[i].virtualAddress; } // Load the COM/COR20 header DirectoryEntry entry = m_ntHeader.dataDirectory[DirectoryEntry.CLRHEADER]; int comOffset = this.VaToOffsetSafe( entry.virtualAddress ); if(comOffset == -1) { throw new MissingCLRheaderException( "Missing CLR header in " + m_path ); } reader.Position = comOffset; m_comHeader = new COMHeader( reader ); } internal int VaToOffset( int virtualAddress ) { int result = VaToOffsetSafe( virtualAddress ); if(result == -1) { throw new IllegalPEFormatException( "Unknown VA " + virtualAddress ); } return result; } internal int VaToOffsetSafe( int virtualAddress ) { int limit = m_ntHeader.numberOfSections; for(int i = 0; i < limit; i++) { SectionHeader section = m_sectionArray[i]; if(virtualAddress >= section.virtualAddress && virtualAddress < (section.virtualAddress + section.sizeOfRawData)) { return (virtualAddress - section.virtualAddress + section.pointerToRawData); } } return -1; } private void DumpIAT( LogWriter outputStream , String title , DirectoryEntry entry ) { outputStream.WriteLine( "// " + title ); if(entry.size == 0) { outputStream.WriteLine( "// No data." ); outputStream.WriteLine(); return; } if(entry.size < ImportDescriptor.SIZE) { outputStream.WriteLine( "Not enough data for IMAGE_IMPORT_DESCRIPTOR" ); return; } int importOffset = this.VaToOffset( entry.virtualAddress ); ArrayReader reader = new ArrayReader( m_peImage ); while(true) { reader.Position = importOffset; ImportDescriptor importDescriptor = new ImportDescriptor( reader ); if(importDescriptor.firstChunk == 0) { return; } String name = null; if(importDescriptor.name != 0) { int nameOffset = this.VaToOffset( importDescriptor.name ); reader.Position = nameOffset; name = reader.ReadZeroTerminatedUInt8String(); } outputStream.WriteLine( "// " + name ); importDescriptor.DumpToStream( outputStream ); outputStream.WriteLine( "//" ); int importTableOffset = this.VaToOffset( importDescriptor.firstChunk ); while(true) { reader.Position = importTableOffset; int importTableID = reader.ReadInt32(); if(importTableID == 0) { break; } outputStream.WriteLine( "importTableID is " + importTableID.ToString( "x" ) ); outputStream.Flush(); int nameStringOffset = this.VaToOffset( importTableID & 0x7fffffff ); reader.Position = nameStringOffset; if((importTableID & 0x8000000) != 0) { outputStream.WriteLine( "// " + reader.ReadInt16().ToString( "x8" ) + " by ordinal " + (importTableID & 0x7ffffff) ); } else { outputStream.WriteLine( "// " + reader.ReadInt16().ToString( "x8" ) + " " + reader.ReadZeroTerminatedUInt8String() ); } importTableOffset += 4; } outputStream.WriteLine(); importOffset += ImportDescriptor.SIZE; } } internal Section[] loadSections() { ArrayReader reader = new ArrayReader( m_peImage ); Section[] sections = new Section[m_sectionArray.Length]; for(int i = 0; i < m_sectionArray.Length; i++) { Section section = new Section( m_sectionArray[i] ); section.LoadSection( this, reader ); sections[i] = section; } return sections; } // Nested classes internal class DOSHeader { // Corresponds to the WinNT IMAGE_DOS_HEADER data structure internal const short IMAGE_DOS_SIGNATURE = 0x5A4D; // // State // internal short magic; // Magic number internal short cblp; // Bytes on last page of file internal short cp; // Pages in file internal short crlc; // Relocations internal short cparhdr; // Size of header in paragraphs internal short minalloc; // Minimum extra paragraphs needed internal short maxalloc; // Maximum extra paragraphs needed internal short ss; // Initial (relative) SS value internal short sp; // Initial SP value internal short csum; // Checksum internal short ip; // Initial IP value internal short cs; // Initial (relative) CS value internal short lfarlc; // File address of relocation table internal short ovno; // Overlay number internal short res_0; // Reserved words internal short res_1; internal short res_2; internal short res_3; internal short oemid; // OEM identifier (for e_oeminfo) internal short oeminfo; // OEM information; e_oemid specific internal short res2_0; // Reserved words internal short res2_1; internal short res2_2; internal short res2_3; internal short res2_4; internal short res2_5; internal short res2_6; internal short res2_7; internal short res2_8; internal short res2_9; internal int lfanew; // File address of new exe header // // Constructor Methods // internal DOSHeader( ArrayReader reader ) { // We could just read the magic and lfanew fields, but let's read everything for now this.magic = reader.ReadInt16(); this.cblp = reader.ReadInt16(); this.cp = reader.ReadInt16(); this.crlc = reader.ReadInt16(); this.cparhdr = reader.ReadInt16(); this.minalloc = reader.ReadInt16(); this.maxalloc = reader.ReadInt16(); this.ss = reader.ReadInt16(); this.sp = reader.ReadInt16(); this.csum = reader.ReadInt16(); this.ip = reader.ReadInt16(); this.cs = reader.ReadInt16(); this.lfarlc = reader.ReadInt16(); this.ovno = reader.ReadInt16(); this.res_0 = reader.ReadInt16(); this.res_1 = reader.ReadInt16(); this.res_2 = reader.ReadInt16(); this.res_3 = reader.ReadInt16(); this.oemid = reader.ReadInt16(); this.oeminfo = reader.ReadInt16(); this.res2_0 = reader.ReadInt16(); this.res2_1 = reader.ReadInt16(); this.res2_2 = reader.ReadInt16(); this.res2_3 = reader.ReadInt16(); this.res2_4 = reader.ReadInt16(); this.res2_5 = reader.ReadInt16(); this.res2_6 = reader.ReadInt16(); this.res2_7 = reader.ReadInt16(); this.res2_8 = reader.ReadInt16(); this.res2_9 = reader.ReadInt16(); this.lfanew = reader.ReadInt32(); // Verify that we have a correct DOS header and a valid // pointer to the NT header if(this.magic != DOSHeader.IMAGE_DOS_SIGNATURE || this.lfanew <= 0) { throw new IllegalPEFormatException( "DOS header problems" ); } } // Output Routines internal void DumpLimitedToStream( LogWriter outputStream ) { outputStream.WriteLine( "// Magic: {0:X2}", this.magic ); // TODO: More here } } internal class NTHeader { // Corresponds to the WinNT IMAGE_NT_HEADERS data structure internal const int IMAGE_NT_SIGNATURE = 0x00004550; // PE00 internal const short IMAGE_SIZEOF_NT_OPTIONAL32_HEADER = 224; internal const short IMAGE_SIZEOF_NT_OPTIONAL32PLUS_HEADER = 240; internal const short IMAGE_NT_OPTIONAL_HDR32_MAGIC = 0x010B; internal const short IMAGE_NT_OPTIONAL_HDR32PLUS_MAGIC = 0x020B; internal const short IMAGE_FILE_EXECUTABLE_IMAGE = 0x0002; // File is executable (i.e. no unresolved external references). internal const short IMAGE_FILE_DLL = 0x2000; // File is a DLL. // // State // internal int signature; // IMAGE_FILE_HEADER internal short machine; internal short numberOfSections; internal int timeDateStamp; internal int pointerToSymbolTable; internal int numberOfSymbols; internal short sizeOfOptionalHeader; internal short characteristics; // IMAGE_OPTIONAL_HEADER32 internal short magic; internal Byte majorLinkerVersion; internal Byte minorLinkerVersion; internal int sizeOfCode; internal int sizeOfInitializedData; internal int sizeOfUninitializedData; internal int addressOfEntryPoint; internal int baseOfCode; private int baseOfData; //this is not used on x64 internal long imageBase; internal int sectionAlignment; internal int fileAlignment; internal short majorOperatingSystemVersion; internal short minorOperatingSystemVersion; internal short majorImageVersion; internal short minorImageVersion; internal short majorSubsystemVersion; internal short minorSubsystemVersion; internal int win32VersionValue; internal int sizeOfImage; internal int sizeOfHeaders; internal int checkSum; internal short subsystem; internal short dllCharacteristics; internal long sizeOfStackReserve; internal long sizeOfStackCommit; internal long sizeOfHeapReserve; internal long sizeOfHeapCommit; internal int loaderFlags; internal int numberOfRvaAndSizes; // IMAGE_DATA_DIRECTORY internal DirectoryEntry[] dataDirectory; //whether or not image is PE32+ (determined from magic number) internal bool isPe32Plus; // // Constructor Methods // internal NTHeader( ArrayReader reader ) { // We could read a selection of these, but read every // field for now. this.signature = reader.ReadInt32(); this.machine = reader.ReadInt16(); this.numberOfSections = reader.ReadInt16(); this.timeDateStamp = reader.ReadInt32(); this.pointerToSymbolTable = reader.ReadInt32(); this.numberOfSymbols = reader.ReadInt32(); this.sizeOfOptionalHeader = reader.ReadInt16(); this.characteristics = reader.ReadInt16(); this.magic = reader.ReadInt16(); this.isPe32Plus = (magic == NTHeader.IMAGE_NT_OPTIONAL_HDR32PLUS_MAGIC); this.majorLinkerVersion = reader.ReadUInt8(); this.minorLinkerVersion = reader.ReadUInt8(); this.sizeOfCode = reader.ReadInt32(); this.sizeOfInitializedData = reader.ReadInt32(); this.sizeOfUninitializedData = reader.ReadInt32(); this.addressOfEntryPoint = reader.ReadInt32(); this.baseOfCode = reader.ReadInt32(); if(!this.isPe32Plus) { this.baseOfData = reader.ReadInt32(); } else { this.baseOfData = 0; } this.imageBase = readIntPtr( reader ); this.sectionAlignment = reader.ReadInt32(); this.fileAlignment = reader.ReadInt32(); this.majorOperatingSystemVersion = reader.ReadInt16(); this.minorOperatingSystemVersion = reader.ReadInt16(); this.majorImageVersion = reader.ReadInt16(); this.minorImageVersion = reader.ReadInt16(); this.majorSubsystemVersion = reader.ReadInt16(); this.minorSubsystemVersion = reader.ReadInt16(); this.win32VersionValue = reader.ReadInt32(); this.sizeOfImage = reader.ReadInt32(); this.sizeOfHeaders = reader.ReadInt32(); this.checkSum = reader.ReadInt32(); this.subsystem = reader.ReadInt16(); this.dllCharacteristics = reader.ReadInt16(); this.sizeOfStackReserve = readIntPtr( reader ); this.sizeOfStackCommit = readIntPtr( reader ); this.sizeOfHeapReserve = readIntPtr( reader ); this.sizeOfHeapCommit = readIntPtr( reader ); this.loaderFlags = reader.ReadInt32(); int count = reader.ReadInt32(); this.numberOfRvaAndSizes = count; DirectoryEntry[] directoryArray = new DirectoryEntry[count]; this.dataDirectory = directoryArray; for(int i = 0; i < count; i++) { directoryArray[i] = new DirectoryEntry( reader ); } int iSizeOfOptionalHeader = this.isPe32Plus ? NTHeader.IMAGE_SIZEOF_NT_OPTIONAL32PLUS_HEADER : NTHeader.IMAGE_SIZEOF_NT_OPTIONAL32_HEADER; int iMagic = this.isPe32Plus ? NTHeader.IMAGE_NT_OPTIONAL_HDR32PLUS_MAGIC : NTHeader.IMAGE_NT_OPTIONAL_HDR32_MAGIC; // Verify that we have a valid NT header if(this.signature != NTHeader.IMAGE_NT_SIGNATURE || this.sizeOfOptionalHeader != iSizeOfOptionalHeader || this.magic != iMagic || this.numberOfRvaAndSizes != 16 ) { throw new IllegalPEFormatException( "NT header problems" ); } } // Output Routines internal void DumpLimitedToStream( LogWriter outputStream ) { outputStream.WriteLine( "// Subsystem: {0:X8}", this.subsystem ); outputStream.WriteLine( "// Native entry point address: {0:X8}", this.addressOfEntryPoint ); outputStream.WriteLine( "// Image base: {0:X8}", this.imageBase ); outputStream.WriteLine( "// Section alignment: {0:X8}", this.sectionAlignment ); outputStream.WriteLine( "// File alignment: {0:X8}", this.fileAlignment ); outputStream.WriteLine( "// Stack reserve size: {0:X8}", this.sizeOfStackReserve ); outputStream.WriteLine( "// Stack commit size: {0:X8}", this.sizeOfStackCommit ); outputStream.WriteLine( "// Directories: {0:X8}", this.numberOfRvaAndSizes ); this.dataDirectory[DirectoryEntry.EXPORT ].DumpToStream( outputStream, "of Export directory " ); this.dataDirectory[DirectoryEntry.IMPORT ].DumpToStream( outputStream, "of Import directory" ); this.dataDirectory[DirectoryEntry.RESOURCE ].DumpToStream( outputStream, "of Resource directory" ); this.dataDirectory[DirectoryEntry.EXCEPTION ].DumpToStream( outputStream, "of Exception directory" ); this.dataDirectory[DirectoryEntry.SECURITY ].DumpToStream( outputStream, "of Security directory" ); this.dataDirectory[DirectoryEntry.BASERELOCATIONTABLE ].DumpToStream( outputStream, "of Base Relocation Table" ); this.dataDirectory[DirectoryEntry.DEBUG ].DumpToStream( outputStream, "of Debug directory" ); this.dataDirectory[DirectoryEntry.ARCHITECTURE ].DumpToStream( outputStream, "of Architecture specific" ); this.dataDirectory[DirectoryEntry.GLOBALPOINTER ].DumpToStream( outputStream, "of Global pointer directory" ); this.dataDirectory[DirectoryEntry.TLS ].DumpToStream( outputStream, "of TLS directory " ); this.dataDirectory[DirectoryEntry.LOADCONFIG ].DumpToStream( outputStream, "of Load config directory" ); this.dataDirectory[DirectoryEntry.BOUNDIMPORT ].DumpToStream( outputStream, "of Bound import directory" ); this.dataDirectory[DirectoryEntry.IMPORTADDRESSTABLE ].DumpToStream( outputStream, "of Import Address Table" ); this.dataDirectory[DirectoryEntry.DELAYLOADIMPORTADDRESSTABLE].DumpToStream( outputStream, "of Delay Load IAT" ); this.dataDirectory[DirectoryEntry.CLRHEADER ].DumpToStream( outputStream, "of CLR Header" ); } private long readIntPtr( ArrayReader reader ) { if(this.isPe32Plus) { return reader.ReadInt64(); } else { return (long)reader.ReadInt32(); } } } internal struct DirectoryEntry { internal const int EXPORT = 0; internal const int IMPORT = 1; internal const int RESOURCE = 2; internal const int EXCEPTION = 3; internal const int SECURITY = 4; internal const int BASERELOCATIONTABLE = 5; internal const int DEBUG = 6; internal const int ARCHITECTURE = 7; internal const int GLOBALPOINTER = 8; internal const int TLS = 9; internal const int LOADCONFIG = 10; internal const int BOUNDIMPORT = 11; internal const int IMPORTADDRESSTABLE = 12; internal const int DELAYLOADIMPORTADDRESSTABLE = 13; internal const int CLRHEADER = 14; // // State // internal int virtualAddress; internal int size; // // Constructor Methods // internal DirectoryEntry( ArrayReader reader ) { this.virtualAddress = reader.ReadInt32(); this.size = reader.ReadInt32(); } // Output Routines internal void DumpToStream( LogWriter outputStream , String suffix ) { outputStream.WriteLine( "// {0:X8} [{1:X8}] {2}", this.virtualAddress, this.size, suffix ); } } public class Section { // // State // public SectionHeader header; byte[] rawData; // // Constructor Methods // public Section( SectionHeader header ) { this.header = header; } public void LoadSection( PELoader peLoader , ArrayReader reader ) { reader.Position = peLoader.VaToOffset( header.virtualAddress ); this.rawData = reader.ReadUInt8Array( header.sizeOfRawData ); } } public class SectionHeader { // // State // public String name; public int virtualSize; public int virtualAddress; public int sizeOfRawData; public int pointerToRawData; public int pointerToRelocations; public int pointerToLinenumbers; public short numberOfRelocations; public short numberOfLinenumbers; public int characteristics; // // Constructor Methods // public SectionHeader( ArrayReader reader ) { char[] chars = new char[8]; for(int j = 0; j < 8; j++) { chars[j] = (char)reader.ReadUInt8(); } this.name = new String( chars ); this.virtualSize = reader.ReadInt32(); this.virtualAddress = reader.ReadInt32(); this.sizeOfRawData = reader.ReadInt32(); this.pointerToRawData = reader.ReadInt32(); this.pointerToRelocations = reader.ReadInt32(); this.pointerToLinenumbers = reader.ReadInt32(); this.numberOfRelocations = reader.ReadInt16(); this.numberOfLinenumbers = reader.ReadInt16(); this.characteristics = reader.ReadInt32(); } } internal class COMHeader { // // State // // Corresponds to the WinNT IMAGE_COR20_HEADER data structure // Header Versioning internal int cb; internal short majorRuntimeVersion; internal short minorRuntimeVersion; // Symbol table and startup information internal DirectoryEntry metaData; internal int flags; internal int entryPointToken; // Binding information internal DirectoryEntry resources; internal DirectoryEntry strongNameSignature; // Regular fixup and binding information internal DirectoryEntry codeManagerTable; internal DirectoryEntry vtableFixups; internal DirectoryEntry exportAddressTableJumps; // Managed Native Code internal DirectoryEntry managedNativeHeader; // // Constructor Methods // internal COMHeader( ArrayReader reader ) { this.cb = reader.ReadInt32(); this.majorRuntimeVersion = reader.ReadInt16(); this.minorRuntimeVersion = reader.ReadInt16(); this.metaData = new DirectoryEntry( reader ); this.flags = reader.ReadInt32(); this.entryPointToken = reader.ReadInt32(); this.resources = new DirectoryEntry( reader ); this.strongNameSignature = new DirectoryEntry( reader ); this.codeManagerTable = new DirectoryEntry( reader ); this.vtableFixups = new DirectoryEntry( reader ); this.exportAddressTableJumps = new DirectoryEntry( reader ); this.managedNativeHeader = new DirectoryEntry( reader ); // Verify that we have a valid header if(this.majorRuntimeVersion == 1 || this.majorRuntimeVersion > 2) { throw new IllegalPEFormatException( "COM header problems" ); } } internal void DumpHeader( LogWriter outputStream ) { outputStream.WriteLine( "// CLR Header:" ); outputStream.WriteLine( "// {0:X8} Header size" , this.cb ); outputStream.WriteLine( "// {0:X4} Major runtime version" , this.majorRuntimeVersion ); outputStream.WriteLine( "// {0:X4} Minor runtime version" , this.minorRuntimeVersion ); outputStream.WriteLine( "// {0:X8} Flags" , this.flags ); outputStream.WriteLine( "// {0:X8} Entrypoint token" , this.entryPointToken ); outputStream.WriteLine( "// {0:X8} [{1:X8}] address [size] of Metadata directory" , this.metaData .virtualAddress, this.metaData .size ); outputStream.WriteLine( "// {0:X8} [{1:X8}] address [size] of Resources directory" , this.resources .virtualAddress, this.resources .size ); outputStream.WriteLine( "// {0:X8} [{1:X8}] address [size] of Strong name signature" , this.strongNameSignature .virtualAddress, this.strongNameSignature .size ); outputStream.WriteLine( "// {0:X8} [{1:X8}] address [size] of CodeManager table" , this.codeManagerTable .virtualAddress, this.codeManagerTable .size ); outputStream.WriteLine( "// {0:X8} [{1:X8}] address [size] of VTableFixups directory", this.vtableFixups .virtualAddress, this.vtableFixups .size ); outputStream.WriteLine( "// {0:X8} [{1:X8}] address [size] of Export address table" , this.exportAddressTableJumps.virtualAddress, this.exportAddressTableJumps.size ); outputStream.WriteLine( "// {0:X8} [{1:X8}] address [size] of Precompile header" , this.managedNativeHeader .virtualAddress, this.managedNativeHeader .size ); } } internal class ImportDescriptor { // Size of this structure in stream internal const int SIZE = 20; // // State // internal int characteristics; internal int timeDateStamp; internal int forwarderChain; internal int name; internal int firstChunk; // // Constructor Methods // internal ImportDescriptor( ArrayReader reader ) { this.characteristics = reader.ReadInt32(); this.timeDateStamp = reader.ReadInt32(); this.forwarderChain = reader.ReadInt32(); this.name = reader.ReadInt32(); this.firstChunk = reader.ReadInt32(); } internal void DumpToStream( LogWriter outputStream ) { outputStream.WriteLine( "// {0:X8} Import Address Table" , this.firstChunk ); outputStream.WriteLine( "// {0:X8} Import Name Table" , this.name ); outputStream.WriteLine( "// {0:X8} time date stamp" , this.timeDateStamp ); outputStream.WriteLine( "// {0:X8} characteristics" , this.characteristics ); outputStream.WriteLine( "// {0:X8} index of first forwarder reference", this.forwarderChain ); } } public class IllegalPEFormatException : Exception { // // Constructor Methods // internal IllegalPEFormatException( String reason ) : base( reason ) { } } public class MissingCLRheaderException : Exception { // // Constructor Methods // internal MissingCLRheaderException( String reason ) : base( reason ) { } } public class NotYetImplemented : Exception { // // Constructor Methods // internal NotYetImplemented( String reason ) : base( reason ) { } } } }
using Umbraco.Core.Configuration; using System; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Persistence.Caching; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.UnitOfWork; namespace Umbraco.Core.Persistence { /// <summary> /// Used to instantiate each repository type /// </summary> public class RepositoryFactory { private readonly bool _disableAllCache; private readonly CacheHelper _cacheHelper; private readonly IUmbracoSettingsSection _settings; #region Ctors public RepositoryFactory() : this(false, UmbracoConfig.For.UmbracoSettings()) { } public RepositoryFactory(CacheHelper cacheHelper) : this(false, UmbracoConfig.For.UmbracoSettings()) { if (cacheHelper == null) throw new ArgumentNullException("cacheHelper"); _disableAllCache = false; _cacheHelper = cacheHelper; } public RepositoryFactory(bool disableAllCache, CacheHelper cacheHelper) : this(disableAllCache, UmbracoConfig.For.UmbracoSettings()) { if (cacheHelper == null) throw new ArgumentNullException("cacheHelper"); _cacheHelper = cacheHelper; } public RepositoryFactory(bool disableAllCache) : this(disableAllCache, UmbracoConfig.For.UmbracoSettings()) { } internal RepositoryFactory(bool disableAllCache, IUmbracoSettingsSection settings) { _disableAllCache = disableAllCache; _settings = settings; _cacheHelper = _disableAllCache ? CacheHelper.CreateDisabledCacheHelper() : ApplicationContext.Current.ApplicationCache; } internal RepositoryFactory(bool disableAllCache, IUmbracoSettingsSection settings, CacheHelper cacheHelper) { _disableAllCache = disableAllCache; _settings = settings; _cacheHelper = cacheHelper; } #endregion public virtual ITagRepository CreateTagRepository(IDatabaseUnitOfWork uow) { return new TagRepository( uow, _disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current); } public virtual IContentRepository CreateContentRepository(IDatabaseUnitOfWork uow) { return new ContentRepository( uow, _disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current, CreateContentTypeRepository(uow), CreateTemplateRepository(uow), CreateTagRepository(uow), _cacheHelper) { EnsureUniqueNaming = _settings.Content.EnsureUniqueNaming }; } public virtual IContentTypeRepository CreateContentTypeRepository(IDatabaseUnitOfWork uow) { return new ContentTypeRepository( uow, _disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current, CreateTemplateRepository(uow)); } public virtual IDataTypeDefinitionRepository CreateDataTypeDefinitionRepository(IDatabaseUnitOfWork uow) { return new DataTypeDefinitionRepository( uow, _disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current, _cacheHelper, CreateContentTypeRepository(uow)); } public virtual IDictionaryRepository CreateDictionaryRepository(IDatabaseUnitOfWork uow) { return new DictionaryRepository( uow, _disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current, CreateLanguageRepository(uow)); } public virtual ILanguageRepository CreateLanguageRepository(IDatabaseUnitOfWork uow) { return new LanguageRepository( uow, _disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current); } public virtual IMediaRepository CreateMediaRepository(IDatabaseUnitOfWork uow) { return new MediaRepository( uow, _disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current, CreateMediaTypeRepository(uow), CreateTagRepository(uow)) { EnsureUniqueNaming = _settings.Content.EnsureUniqueNaming }; } public virtual IMediaTypeRepository CreateMediaTypeRepository(IDatabaseUnitOfWork uow) { return new MediaTypeRepository( uow, _disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current); } public virtual IRelationRepository CreateRelationRepository(IDatabaseUnitOfWork uow) { return new RelationRepository( uow, NullCacheProvider.Current, CreateRelationTypeRepository(uow)); } public virtual IRelationTypeRepository CreateRelationTypeRepository(IDatabaseUnitOfWork uow) { return new RelationTypeRepository( uow, NullCacheProvider.Current); } public virtual IScriptRepository CreateScriptRepository(IUnitOfWork uow) { return new ScriptRepository(uow); } internal virtual IPartialViewRepository CreatePartialViewRepository(IUnitOfWork uow) { return new PartialViewRepository(uow); } internal virtual IPartialViewRepository CreatePartialViewMacroRepository(IUnitOfWork uow) { return new PartialViewMacroRepository(uow); } public virtual IStylesheetRepository CreateStylesheetRepository(IUnitOfWork uow, IDatabaseUnitOfWork db) { return new StylesheetRepository(uow, db); } public virtual ITemplateRepository CreateTemplateRepository(IDatabaseUnitOfWork uow) { return new TemplateRepository(uow, _disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current); } internal virtual ServerRegistrationRepository CreateServerRegistrationRepository(IDatabaseUnitOfWork uow) { return new ServerRegistrationRepository( uow, NullCacheProvider.Current); } public virtual IUserTypeRepository CreateUserTypeRepository(IDatabaseUnitOfWork uow) { return new UserTypeRepository( uow, //There's not many user types but we query on users all the time so the result needs to be cached _disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current); } public virtual IUserRepository CreateUserRepository(IDatabaseUnitOfWork uow) { return new UserRepository( uow, //Need to cache users - we look up user information more than anything in the back office! _disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current, CreateUserTypeRepository(uow), _cacheHelper); } internal virtual IMacroRepository CreateMacroRepository(IDatabaseUnitOfWork uow) { return new MacroRepository(uow, _disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current); } public virtual IMemberRepository CreateMemberRepository(IDatabaseUnitOfWork uow) { return new MemberRepository( uow, _disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current, CreateMemberTypeRepository(uow), CreateMemberGroupRepository(uow), CreateTagRepository(uow)); } public virtual IMemberTypeRepository CreateMemberTypeRepository(IDatabaseUnitOfWork uow) { return new MemberTypeRepository(uow, _disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current); } public virtual IMemberGroupRepository CreateMemberGroupRepository(IDatabaseUnitOfWork uow) { return new MemberGroupRepository(uow, _disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current, _cacheHelper); } public virtual IEntityRepository CreateEntityRepository(IDatabaseUnitOfWork uow) { return new EntityRepository(uow); } } }
// // SingleFormatterTest.cs - NUnit Test Cases for System.SingleFormatter // // Author: // Patrick Kalkman kalkman@cistron.nl // // (C) 2003 Patrick Kalkman // using NUnit.Framework; using System; using System.Threading; using System.Globalization; namespace MonoTests.System { [TestFixture] public class SingleFormatterTest { [SetUp] public void GetReady() { CultureInfo EnUs = new CultureInfo ("en-us", false); EnUs.NumberFormat.CurrencyNegativePattern = 0; // -1 = (1) EnUs.NumberFormat.CurrencyDecimalSeparator = "."; EnUs.NumberFormat.NumberGroupSeparator = ","; EnUs.NumberFormat.NumberNegativePattern = 1; // -1 = -1 EnUs.NumberFormat.NumberDecimalDigits = 2; //Set this culture for the current thread. Thread.CurrentThread.CurrentCulture = EnUs; } [TearDown] public void Clean() {} [Test] [ExpectedException(typeof(FormatException))] public void TestToDecimal() { Single x = 1.0000001F; string Result = x.ToString ("D2"); //To Decimal is for integral types only. } [Test] [ExpectedException(typeof(FormatException))] public void TestToHex() { Single x = 1.212121F; string Result = x.ToString ("X2"); //To Hex is for integral types only. } [Test] [ExpectedException(typeof(FormatException))] public void TestToUnknown() { Single x = 1.212121F; string Result = x.ToString ("L2"); //Invalid format. } private void FormatStringTest(int TestNumber, float Number, string Format, string ExpectedResult) { Assertion.AssertEquals ("SngF #" + TestNumber, ExpectedResult, Number.ToString(Format)); } string GetPercent (string s) { switch (NumberFormatInfo.CurrentInfo.PercentPositivePattern) { case 0: return s + " %"; case 1: return s + "%"; default: return "%" + s; } } [Test] public void TestFormatStrings() { FormatStringTest (0, 121212F, "C", "$121,212.00"); FormatStringTest (1, 121212F, "C0", "$121,212"); FormatStringTest (2, 121212F, "C1", "$121,212.0"); FormatStringTest (3, 121212F, "C2", "$121,212.00"); FormatStringTest (4, 121212F, "C3", "$121,212.000"); FormatStringTest (5, 121212F, "C4", "$121,212.0000"); FormatStringTest (6, 121212F, "C5", "$121,212.00000"); FormatStringTest (7, 121212F, "C6", "$121,212.000000"); FormatStringTest (8, 121212F, "C7", "$121,212.0000000"); FormatStringTest (9, 121212F, "C8", "$121,212.00000000"); FormatStringTest (10, 121212F, "C9", "$121,212.000000000"); FormatStringTest (11, 121212F, "C67", "$121,212.0000000000000000000000000000000000000000000000000000000000000000000"); FormatStringTest (12, 121212F, "E", "1.212120E+005"); FormatStringTest (13, 121212F, "E0", "1E+005"); FormatStringTest (14, 121212F, "E1", "1.2E+005"); FormatStringTest (15, 121212F, "E2", "1.21E+005"); FormatStringTest (16, 121212F, "E3", "1.212E+005"); FormatStringTest (17, 121212F, "E4", "1.2121E+005"); FormatStringTest (18, 121212F, "E5", "1.21212E+005"); FormatStringTest (19, 121212F, "E6", "1.212120E+005"); FormatStringTest (20, 121212F, "E7", "1.2121200E+005"); FormatStringTest (21, 121212F, "E8", "1.21212000E+005"); FormatStringTest (22, 121212F, "E9", "1.212120000E+005"); FormatStringTest (23, 121212F, "E67", "1.2121200000000000000000000000000000000000000000000000000000000000000E+005"); FormatStringTest (24, 121212F, "F", "121212.00"); FormatStringTest (25, 121212F, "F0", "121212"); FormatStringTest (26, 121212F, "F1", "121212.0"); FormatStringTest (27, 121212F, "F2", "121212.00"); FormatStringTest (28, 121212F, "F3", "121212.000"); FormatStringTest (29, 121212F, "F4", "121212.0000"); FormatStringTest (30, 121212F, "F5", "121212.00000"); FormatStringTest (31, 121212F, "F6", "121212.000000"); FormatStringTest (32, 121212F, "F7", "121212.0000000"); FormatStringTest (33, 121212F, "F8", "121212.00000000"); FormatStringTest (34, 121212F, "F9", "121212.000000000"); FormatStringTest (35, 121212F, "F67", "121212.0000000000000000000000000000000000000000000000000000000000000000000"); FormatStringTest (36, 121212F, "G", "121212"); FormatStringTest (37, 121212F, "G0", "121212"); FormatStringTest (38, 121212F, "G1", "1E+05"); FormatStringTest (39, 121212F, "G2", "1.2E+05"); FormatStringTest (40, 121212F, "G3", "1.21E+05"); FormatStringTest (41, 121212F, "G4", "1.212E+05"); FormatStringTest (42, 121212F, "G5", "1.2121E+05"); FormatStringTest (43, 121212F, "G6", "121212"); FormatStringTest (44, 121212F, "G7", "121212"); FormatStringTest (45, 121212F, "G8", "121212"); FormatStringTest (46, 121212F, "G9", "121212"); FormatStringTest (47, 121212F, "G67", "121212"); FormatStringTest (48, 121212F, "N", "121,212.00"); FormatStringTest (49, 121212F, "N0", "121,212"); FormatStringTest (50, 121212F, "N1", "121,212.0"); FormatStringTest (51, 121212F, "N2", "121,212.00"); FormatStringTest (52, 121212F, "N3", "121,212.000"); FormatStringTest (53, 121212F, "N4", "121,212.0000"); FormatStringTest (54, 121212F, "N5", "121,212.00000"); FormatStringTest (55, 121212F, "N6", "121,212.000000"); FormatStringTest (56, 121212F, "N7", "121,212.0000000"); FormatStringTest (57, 121212F, "N8", "121,212.00000000"); FormatStringTest (58, 121212F, "N9", "121,212.000000000"); FormatStringTest (59, 121212F, "N67", "121,212.0000000000000000000000000000000000000000000000000000000000000000000"); FormatStringTest (60, 121212F, "P", GetPercent ("12,121,200.00")); FormatStringTest (61, 121212F, "P0", GetPercent ("12,121,200")); FormatStringTest (62, 121212F, "P1", GetPercent ("12,121,200.0")); FormatStringTest (63, 121212F, "P2", GetPercent ("12,121,200.00")); FormatStringTest (64, 121212F, "P3", GetPercent ("12,121,200.000")); FormatStringTest (65, 121212F, "P4", GetPercent ("12,121,200.0000")); FormatStringTest (66, 121212F, "P5", GetPercent ("12,121,200.00000")); FormatStringTest (67, 121212F, "P6", GetPercent ("12,121,200.000000")); FormatStringTest (68, 121212F, "P7", GetPercent ("12,121,200.0000000")); FormatStringTest (69, 121212F, "P8", GetPercent ("12,121,200.00000000")); FormatStringTest (70, 121212F, "P9", GetPercent ("12,121,200.000000000")); FormatStringTest (71, 121212F, "P67", GetPercent ("12,121,200.0000000000000000000000000000000000000000000000000000000000000000000")); FormatStringTest (72, 3.402823E+38F, "C", "$340,282,300,000,000,000,000,000,000,000,000,000,000.00"); FormatStringTest (73, 3.402823E+38F, "C0", "$340,282,300,000,000,000,000,000,000,000,000,000,000"); FormatStringTest (74, 3.402823E+38F, "C1", "$340,282,300,000,000,000,000,000,000,000,000,000,000.0"); FormatStringTest (75, 3.402823E+38F, "C2", "$340,282,300,000,000,000,000,000,000,000,000,000,000.00"); FormatStringTest (76, 3.402823E+38F, "C3", "$340,282,300,000,000,000,000,000,000,000,000,000,000.000"); FormatStringTest (77, 3.402823E+38F, "C4", "$340,282,300,000,000,000,000,000,000,000,000,000,000.0000"); FormatStringTest (78, 3.402823E+38F, "C5", "$340,282,300,000,000,000,000,000,000,000,000,000,000.00000"); FormatStringTest (79, 3.402823E+38F, "C6", "$340,282,300,000,000,000,000,000,000,000,000,000,000.000000"); FormatStringTest (80, 3.402823E+38F, "C7", "$340,282,300,000,000,000,000,000,000,000,000,000,000.0000000"); FormatStringTest (81, 3.402823E+38F, "C8", "$340,282,300,000,000,000,000,000,000,000,000,000,000.00000000"); FormatStringTest (82, 3.402823E+38F, "C9", "$340,282,300,000,000,000,000,000,000,000,000,000,000.000000000"); FormatStringTest (83, 3.402823E+38F, "C67", "$340,282,300,000,000,000,000,000,000,000,000,000,000.0000000000000000000000000000000000000000000000000000000000000000000"); FormatStringTest (84, 3.402823E+38F, "E", "3.402823E+038"); FormatStringTest (85, 3.402823E+38F, "E0", "3E+038"); FormatStringTest (86, 3.402823E+38F, "E1", "3.4E+038"); FormatStringTest (87, 3.402823E+38F, "E2", "3.40E+038"); FormatStringTest (88, 3.402823E+38F, "E3", "3.403E+038"); FormatStringTest (89, 3.402823E+38F, "E4", "3.4028E+038"); FormatStringTest (90, 3.402823E+38F, "E5", "3.40282E+038"); FormatStringTest (91, 3.402823E+38F, "E6", "3.402823E+038"); FormatStringTest (92, 3.402823E+38F, "E7", "3.4028231E+038"); FormatStringTest (93, 3.402823E+38F, "E8", "3.40282306E+038"); FormatStringTest (94, 3.402823E+38F, "E9", "3.402823060E+038"); FormatStringTest (95, 3.402823E+38F, "E67", "3.4028230600000000000000000000000000000000000000000000000000000000000E+038"); FormatStringTest (96, 3.402823E+38F, "F", "340282300000000000000000000000000000000.00"); FormatStringTest (97, 3.402823E+38F, "F0", "340282300000000000000000000000000000000"); FormatStringTest (98, 3.402823E+38F, "F1", "340282300000000000000000000000000000000.0"); FormatStringTest (99, 3.402823E+38F, "F2", "340282300000000000000000000000000000000.00"); FormatStringTest (100, 3.402823E+38F, "F3", "340282300000000000000000000000000000000.000"); FormatStringTest (101, 3.402823E+38F, "F4", "340282300000000000000000000000000000000.0000"); FormatStringTest (102, 3.402823E+38F, "F5", "340282300000000000000000000000000000000.00000"); FormatStringTest (103, 3.402823E+38F, "F6", "340282300000000000000000000000000000000.000000"); FormatStringTest (104, 3.402823E+38F, "F7", "340282300000000000000000000000000000000.0000000"); FormatStringTest (105, 3.402823E+38F, "F8", "340282300000000000000000000000000000000.00000000"); FormatStringTest (106, 3.402823E+38F, "F9", "340282300000000000000000000000000000000.000000000"); FormatStringTest (107, 3.402823E+38F, "F67", "340282300000000000000000000000000000000.0000000000000000000000000000000000000000000000000000000000000000000"); FormatStringTest (108, 3.402823E+38F, "G", "3.402823E+38"); FormatStringTest (109, 3.402823E+38F, "G0", "3.402823E+38"); FormatStringTest (110, 3.402823E+38F, "G1", "3E+38"); FormatStringTest (111, 3.402823E+38F, "G2", "3.4E+38"); FormatStringTest (112, 3.402823E+38F, "G3", "3.4E+38"); FormatStringTest (113, 3.402823E+38F, "G4", "3.403E+38"); FormatStringTest (114, 3.402823E+38F, "G5", "3.4028E+38"); FormatStringTest (115, 3.402823E+38F, "G6", "3.40282E+38"); FormatStringTest (116, 3.402823E+38F, "G7", "3.402823E+38"); FormatStringTest (117, 3.402823E+38F, "G8", "3.4028231E+38"); FormatStringTest (118, 3.402823E+38F, "G9", "3.40282306E+38"); FormatStringTest (119, 3.402823E+38F, "G67", "340282306000000000000000000000000000000"); FormatStringTest (120, 3.402823E+38F, "N", "340,282,300,000,000,000,000,000,000,000,000,000,000.00"); FormatStringTest (121, 3.402823E+38F, "N0", "340,282,300,000,000,000,000,000,000,000,000,000,000"); FormatStringTest (122, 3.402823E+38F, "N1", "340,282,300,000,000,000,000,000,000,000,000,000,000.0"); FormatStringTest (123, 3.402823E+38F, "N2", "340,282,300,000,000,000,000,000,000,000,000,000,000.00"); FormatStringTest (124, 3.402823E+38F, "N3", "340,282,300,000,000,000,000,000,000,000,000,000,000.000"); FormatStringTest (125, 3.402823E+38F, "N4", "340,282,300,000,000,000,000,000,000,000,000,000,000.0000"); FormatStringTest (126, 3.402823E+38F, "N5", "340,282,300,000,000,000,000,000,000,000,000,000,000.00000"); FormatStringTest (127, 3.402823E+38F, "N6", "340,282,300,000,000,000,000,000,000,000,000,000,000.000000"); FormatStringTest (128, 3.402823E+38F, "N7", "340,282,300,000,000,000,000,000,000,000,000,000,000.0000000"); FormatStringTest (129, 3.402823E+38F, "N8", "340,282,300,000,000,000,000,000,000,000,000,000,000.00000000"); FormatStringTest (130, 3.402823E+38F, "N9", "340,282,300,000,000,000,000,000,000,000,000,000,000.000000000"); FormatStringTest (131, 3.402823E+38F, "N67", "340,282,300,000,000,000,000,000,000,000,000,000,000.0000000000000000000000000000000000000000000000000000000000000000000"); FormatStringTest (132, 3.402823E+38F, "P", GetPercent ("34,028,230,000,000,000,000,000,000,000,000,000,000,000.00")); FormatStringTest (133, 3.402823E+38F, "P0", GetPercent ("34,028,230,000,000,000,000,000,000,000,000,000,000,000")); FormatStringTest (134, 3.402823E+38F, "P1", GetPercent ("34,028,230,000,000,000,000,000,000,000,000,000,000,000.0")); FormatStringTest (135, 3.402823E+38F, "P2", GetPercent ("34,028,230,000,000,000,000,000,000,000,000,000,000,000.00")); FormatStringTest (136, 3.402823E+38F, "P3", GetPercent ("34,028,230,000,000,000,000,000,000,000,000,000,000,000.000")); FormatStringTest (137, 3.402823E+38F, "P4", GetPercent ("34,028,230,000,000,000,000,000,000,000,000,000,000,000.0000")); FormatStringTest (138, 3.402823E+38F, "P5", GetPercent ("34,028,230,000,000,000,000,000,000,000,000,000,000,000.00000")); FormatStringTest (139, 3.402823E+38F, "P6", GetPercent ("34,028,230,000,000,000,000,000,000,000,000,000,000,000.000000")); FormatStringTest (140, 3.402823E+38F, "P7", GetPercent ("34,028,230,000,000,000,000,000,000,000,000,000,000,000.0000000")); FormatStringTest (141, 3.402823E+38F, "P8", GetPercent ("34,028,230,000,000,000,000,000,000,000,000,000,000,000.00000000")); FormatStringTest (142, 3.402823E+38F, "P9", GetPercent ("34,028,230,000,000,000,000,000,000,000,000,000,000,000.000000000")); FormatStringTest (143, 3.402823E+38F, "P67", GetPercent ("34,028,230,000,000,000,000,000,000,000,000,000,000,000.0000000000000000000000000000000000000000000000000000000000000000000")); FormatStringTest (144, -3.402823E+38F, "C", "($340,282,300,000,000,000,000,000,000,000,000,000,000.00)"); FormatStringTest (145, -3.402823E+38F, "C0", "($340,282,300,000,000,000,000,000,000,000,000,000,000)"); FormatStringTest (146, -3.402823E+38F, "C1", "($340,282,300,000,000,000,000,000,000,000,000,000,000.0)"); FormatStringTest (147, -3.402823E+38F, "C2", "($340,282,300,000,000,000,000,000,000,000,000,000,000.00)"); FormatStringTest (148, -3.402823E+38F, "C3", "($340,282,300,000,000,000,000,000,000,000,000,000,000.000)"); FormatStringTest (149, -3.402823E+38F, "C4", "($340,282,300,000,000,000,000,000,000,000,000,000,000.0000)"); FormatStringTest (150, -3.402823E+38F, "C5", "($340,282,300,000,000,000,000,000,000,000,000,000,000.00000)"); FormatStringTest (151, -3.402823E+38F, "C6", "($340,282,300,000,000,000,000,000,000,000,000,000,000.000000)"); FormatStringTest (152, -3.402823E+38F, "C7", "($340,282,300,000,000,000,000,000,000,000,000,000,000.0000000)"); FormatStringTest (153, -3.402823E+38F, "C8", "($340,282,300,000,000,000,000,000,000,000,000,000,000.00000000)"); FormatStringTest (154, -3.402823E+38F, "C9", "($340,282,300,000,000,000,000,000,000,000,000,000,000.000000000)"); FormatStringTest (155, -3.402823E+38F, "C67", "($340,282,300,000,000,000,000,000,000,000,000,000,000.0000000000000000000000000000000000000000000000000000000000000000000)"); FormatStringTest (156, -3.402823E+38F, "E", "-3.402823E+038"); FormatStringTest (157, -3.402823E+38F, "E0", "-3E+038"); FormatStringTest (158, -3.402823E+38F, "E1", "-3.4E+038"); FormatStringTest (159, -3.402823E+38F, "E2", "-3.40E+038"); FormatStringTest (160, -3.402823E+38F, "E3", "-3.403E+038"); FormatStringTest (161, -3.402823E+38F, "E4", "-3.4028E+038"); FormatStringTest (162, -3.402823E+38F, "E5", "-3.40282E+038"); FormatStringTest (163, -3.402823E+38F, "E6", "-3.402823E+038"); FormatStringTest (164, -3.402823E+38F, "E7", "-3.4028231E+038"); FormatStringTest (165, -3.402823E+38F, "E8", "-3.40282306E+038"); FormatStringTest (166, -3.402823E+38F, "E9", "-3.402823060E+038"); FormatStringTest (167, -3.402823E+38F, "E67", "-3.4028230600000000000000000000000000000000000000000000000000000000000E+038"); FormatStringTest (168, -3.402823E+38F, "F", "-340282300000000000000000000000000000000.00"); FormatStringTest (169, -3.402823E+38F, "F0", "-340282300000000000000000000000000000000"); FormatStringTest (170, -3.402823E+38F, "F1", "-340282300000000000000000000000000000000.0"); FormatStringTest (171, -3.402823E+38F, "F2", "-340282300000000000000000000000000000000.00"); FormatStringTest (172, -3.402823E+38F, "F3", "-340282300000000000000000000000000000000.000"); FormatStringTest (173, -3.402823E+38F, "F4", "-340282300000000000000000000000000000000.0000"); FormatStringTest (174, -3.402823E+38F, "F5", "-340282300000000000000000000000000000000.00000"); FormatStringTest (175, -3.402823E+38F, "F6", "-340282300000000000000000000000000000000.000000"); FormatStringTest (176, -3.402823E+38F, "F7", "-340282300000000000000000000000000000000.0000000"); FormatStringTest (177, -3.402823E+38F, "F8", "-340282300000000000000000000000000000000.00000000"); FormatStringTest (178, -3.402823E+38F, "F9", "-340282300000000000000000000000000000000.000000000"); FormatStringTest (179, -3.402823E+38F, "F67", "-340282300000000000000000000000000000000.0000000000000000000000000000000000000000000000000000000000000000000"); FormatStringTest (180, -3.402823E+38F, "G", "-3.402823E+38"); FormatStringTest (181, -3.402823E+38F, "G0", "-3.402823E+38"); FormatStringTest (182, -3.402823E+38F, "G1", "-3E+38"); FormatStringTest (183, -3.402823E+38F, "G2", "-3.4E+38"); FormatStringTest (184, -3.402823E+38F, "G3", "-3.4E+38"); FormatStringTest (185, -3.402823E+38F, "G4", "-3.403E+38"); FormatStringTest (186, -3.402823E+38F, "G5", "-3.4028E+38"); FormatStringTest (187, -3.402823E+38F, "G6", "-3.40282E+38"); FormatStringTest (188, -3.402823E+38F, "G7", "-3.402823E+38"); FormatStringTest (189, -3.402823E+38F, "G8", "-3.4028231E+38"); FormatStringTest (190, -3.402823E+38F, "G9", "-3.40282306E+38"); FormatStringTest (191, -3.402823E+38F, "G67", "-340282306000000000000000000000000000000"); FormatStringTest (192, -3.402823E+38F, "N", "-340,282,300,000,000,000,000,000,000,000,000,000,000.00"); FormatStringTest (193, -3.402823E+38F, "N0", "-340,282,300,000,000,000,000,000,000,000,000,000,000"); FormatStringTest (194, -3.402823E+38F, "N1", "-340,282,300,000,000,000,000,000,000,000,000,000,000.0"); FormatStringTest (195, -3.402823E+38F, "N2", "-340,282,300,000,000,000,000,000,000,000,000,000,000.00"); FormatStringTest (196, -3.402823E+38F, "N3", "-340,282,300,000,000,000,000,000,000,000,000,000,000.000"); FormatStringTest (197, -3.402823E+38F, "N4", "-340,282,300,000,000,000,000,000,000,000,000,000,000.0000"); FormatStringTest (198, -3.402823E+38F, "N5", "-340,282,300,000,000,000,000,000,000,000,000,000,000.00000"); FormatStringTest (199, -3.402823E+38F, "N6", "-340,282,300,000,000,000,000,000,000,000,000,000,000.000000"); FormatStringTest (200, -3.402823E+38F, "N7", "-340,282,300,000,000,000,000,000,000,000,000,000,000.0000000"); FormatStringTest (201, -3.402823E+38F, "N8", "-340,282,300,000,000,000,000,000,000,000,000,000,000.00000000"); FormatStringTest (202, -3.402823E+38F, "N9", "-340,282,300,000,000,000,000,000,000,000,000,000,000.000000000"); FormatStringTest (203, -3.402823E+38F, "N67", "-340,282,300,000,000,000,000,000,000,000,000,000,000.0000000000000000000000000000000000000000000000000000000000000000000"); FormatStringTest (204, -3.402823E+38F, "P", GetPercent ("-34,028,230,000,000,000,000,000,000,000,000,000,000,000.00")); FormatStringTest (205, -3.402823E+38F, "P0", GetPercent ("-34,028,230,000,000,000,000,000,000,000,000,000,000,000")); FormatStringTest (206, -3.402823E+38F, "P1", GetPercent ("-34,028,230,000,000,000,000,000,000,000,000,000,000,000.0")); FormatStringTest (207, -3.402823E+38F, "P2", GetPercent ("-34,028,230,000,000,000,000,000,000,000,000,000,000,000.00")); FormatStringTest (208, -3.402823E+38F, "P3", GetPercent ("-34,028,230,000,000,000,000,000,000,000,000,000,000,000.000")); FormatStringTest (209, -3.402823E+38F, "P4", GetPercent ("-34,028,230,000,000,000,000,000,000,000,000,000,000,000.0000")); FormatStringTest (210, -3.402823E+38F, "P5", GetPercent ("-34,028,230,000,000,000,000,000,000,000,000,000,000,000.00000")); FormatStringTest (211, -3.402823E+38F, "P6", GetPercent ("-34,028,230,000,000,000,000,000,000,000,000,000,000,000.000000")); FormatStringTest (212, -3.402823E+38F, "P7", GetPercent ("-34,028,230,000,000,000,000,000,000,000,000,000,000,000.0000000")); FormatStringTest (213, -3.402823E+38F, "P8", GetPercent ("-34,028,230,000,000,000,000,000,000,000,000,000,000,000.00000000")); FormatStringTest (214, -3.402823E+38F, "P9", GetPercent ("-34,028,230,000,000,000,000,000,000,000,000,000,000,000.000000000")); FormatStringTest (215, -3.402823E+38F, "P67", GetPercent ("-34,028,230,000,000,000,000,000,000,000,000,000,000,000.0000000000000000000000000000000000000000000000000000000000000000000")); FormatStringTest (216, 1E-10F, "C", "$0.00"); FormatStringTest (217, 1E-10F, "C0", "$0"); FormatStringTest (218, 1E-10F, "C1", "$0.0"); FormatStringTest (219, 1E-10F, "C2", "$0.00"); FormatStringTest (220, 1E-10F, "C3", "$0.000"); FormatStringTest (221, 1E-10F, "C4", "$0.0000"); FormatStringTest (222, 1E-10F, "C5", "$0.00000"); FormatStringTest (223, 1E-10F, "C6", "$0.000000"); FormatStringTest (224, 1E-10F, "C7", "$0.0000000"); FormatStringTest (225, 1E-10F, "C8", "$0.00000000"); FormatStringTest (226, 1E-10F, "C9", "$0.000000000"); FormatStringTest (227, 1E-10F, "C67", "$0.0000000001000000000000000000000000000000000000000000000000000000000"); FormatStringTest (228, 1E-10F, "E", "1.000000E-010"); FormatStringTest (229, 1E-10F, "E0", "1E-010"); FormatStringTest (230, 1E-10F, "E1", "1.0E-010"); FormatStringTest (231, 1E-10F, "E2", "1.00E-010"); FormatStringTest (232, 1E-10F, "E3", "1.000E-010"); FormatStringTest (233, 1E-10F, "E4", "1.0000E-010"); FormatStringTest (234, 1E-10F, "E5", "1.00000E-010"); FormatStringTest (235, 1E-10F, "E6", "1.000000E-010"); FormatStringTest (236, 1E-10F, "E7", "1.0000000E-010"); FormatStringTest (237, 1E-10F, "E8", "1.00000001E-010"); FormatStringTest (238, 1E-10F, "E9", "1.000000010E-010"); FormatStringTest (239, 1E-10F, "E67", "1.0000000100000000000000000000000000000000000000000000000000000000000E-010"); FormatStringTest (240, 1E-10F, "F", "0.00"); FormatStringTest (241, 1E-10F, "F0", "0"); FormatStringTest (242, 1E-10F, "F1", "0.0"); FormatStringTest (243, 1E-10F, "F2", "0.00"); FormatStringTest (244, 1E-10F, "F3", "0.000"); FormatStringTest (245, 1E-10F, "F4", "0.0000"); FormatStringTest (246, 1E-10F, "F5", "0.00000"); FormatStringTest (247, 1E-10F, "F6", "0.000000"); FormatStringTest (248, 1E-10F, "F7", "0.0000000"); FormatStringTest (249, 1E-10F, "F8", "0.00000000"); FormatStringTest (250, 1E-10F, "F9", "0.000000000"); FormatStringTest (251, 1E-10F, "F67", "0.0000000001000000000000000000000000000000000000000000000000000000000"); FormatStringTest (252, 1E-10F, "G", "1E-10"); FormatStringTest (253, 1E-10F, "G0", "1E-10"); FormatStringTest (254, 1E-10F, "G1", "1E-10"); FormatStringTest (255, 1E-10F, "G2", "1E-10"); FormatStringTest (256, 1E-10F, "G3", "1E-10"); FormatStringTest (257, 1E-10F, "G4", "1E-10"); FormatStringTest (258, 1E-10F, "G5", "1E-10"); FormatStringTest (259, 1E-10F, "G6", "1E-10"); FormatStringTest (260, 1E-10F, "G7", "1E-10"); FormatStringTest (261, 1E-10F, "G8", "1E-10"); FormatStringTest (262, 1E-10F, "G9", "1.00000001E-10"); FormatStringTest (263, 1E-10F, "G67", "1.00000001E-10"); FormatStringTest (264, 1E-10F, "N", "0.00"); FormatStringTest (265, 1E-10F, "N0", "0"); FormatStringTest (266, 1E-10F, "N1", "0.0"); FormatStringTest (267, 1E-10F, "N2", "0.00"); FormatStringTest (268, 1E-10F, "N3", "0.000"); FormatStringTest (269, 1E-10F, "N4", "0.0000"); FormatStringTest (270, 1E-10F, "N5", "0.00000"); FormatStringTest (271, 1E-10F, "N6", "0.000000"); FormatStringTest (272, 1E-10F, "N7", "0.0000000"); FormatStringTest (273, 1E-10F, "N8", "0.00000000"); FormatStringTest (274, 1E-10F, "N9", "0.000000000"); FormatStringTest (275, 1E-10F, "N67", "0.0000000001000000000000000000000000000000000000000000000000000000000"); FormatStringTest (276, 1E-10F, "P", GetPercent ("0.00")); FormatStringTest (277, 1E-10F, "P0", GetPercent ("0")); FormatStringTest (278, 1E-10F, "P1", GetPercent ("0.0")); FormatStringTest (279, 1E-10F, "P2", GetPercent ("0.00")); FormatStringTest (280, 1E-10F, "P3", GetPercent ("0.000")); FormatStringTest (281, 1E-10F, "P4", GetPercent ("0.0000")); FormatStringTest (282, 1E-10F, "P5", GetPercent ("0.00000")); FormatStringTest (283, 1E-10F, "P6", GetPercent ("0.000000")); FormatStringTest (284, 1E-10F, "P7", GetPercent ("0.0000000")); FormatStringTest (285, 1E-10F, "P8", GetPercent ("0.00000001")); FormatStringTest (286, 1E-10F, "P9", GetPercent ("0.000000010")); FormatStringTest (287, 1E-10F, "P67", GetPercent ("0.0000000100000000000000000000000000000000000000000000000000000000000")); } } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Authentication Configuration ///<para>SObject Name: AuthConfig</para> ///<para>Custom Object: False</para> ///</summary> public class SfAuthConfig : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "AuthConfig"; } } ///<summary> /// Authentication Configuration ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// Name /// <para>Name: DeveloperName</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "developerName")] [Updateable(false), Createable(false)] public string DeveloperName { get; set; } ///<summary> /// Master Language /// <para>Name: Language</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "language")] [Updateable(false), Createable(false)] public string Language { get; set; } ///<summary> /// Label /// <para>Name: MasterLabel</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "masterLabel")] [Updateable(false), Createable(false)] public string MasterLabel { get; set; } ///<summary> /// Namespace Prefix /// <para>Name: NamespacePrefix</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "namespacePrefix")] [Updateable(false), Createable(false)] public string NamespacePrefix { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// Last Modified By ID /// <para>Name: LastModifiedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedById")] [Updateable(false), Createable(false)] public string LastModifiedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastModifiedBy</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedBy")] [Updateable(false), Createable(false)] public SfUser LastModifiedBy { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// URL /// <para>Name: Url</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "url")] [Updateable(false), Createable(false)] public string Url { get; set; } ///<summary> /// UsernamePassword /// <para>Name: AuthOptionsUsernamePassword</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "authOptionsUsernamePassword")] [Updateable(false), Createable(false)] public bool? AuthOptionsUsernamePassword { get; set; } ///<summary> /// Saml /// <para>Name: AuthOptionsSaml</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "authOptionsSaml")] [Updateable(false), Createable(false)] public bool? AuthOptionsSaml { get; set; } ///<summary> /// AuthProvider /// <para>Name: AuthOptionsAuthProvider</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "authOptionsAuthProvider")] [Updateable(false), Createable(false)] public bool? AuthOptionsAuthProvider { get; set; } ///<summary> /// Certificate /// <para>Name: AuthOptionsCertificate</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "authOptionsCertificate")] [Updateable(false), Createable(false)] public bool? AuthOptionsCertificate { get; set; } ///<summary> /// Is Active /// <para>Name: IsActive</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isActive")] [Updateable(false), Createable(false)] public bool? IsActive { get; set; } ///<summary> /// Authentication Configuration Type /// <para>Name: Type</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "type")] [Updateable(false), Createable(false)] public string Type { get; set; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Azure.Management.Network; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.Storage; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System.Collections.Generic; using Xunit; namespace Compute.Tests { public class VMScaleSetUpdateTests : VMScaleSetTestsBase { /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VMScaleSet /// ScaleOut VMScaleSet /// ScaleIn VMScaleSet /// Delete VMScaleSet /// Delete RG /// </summary> [Fact] public void TestVMScaleSetScalingOperations() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group var rgName = TestUtilities.GenerateName(TestPrefix); var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist"); var vmScaleSet = CreateVMScaleSet_NoAsyncTracking(rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet); var getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmScaleSet.Name); ValidateVMScaleSet(inputVMScaleSet, getResponse); // Scale Out VMScaleSet inputVMScaleSet.Sku.Capacity = 3; UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet); getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmScaleSet.Name); ValidateVMScaleSet(inputVMScaleSet, getResponse); // Scale In VMScaleSet inputVMScaleSet.Sku.Capacity = 1; UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet); getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmScaleSet.Name); ValidateVMScaleSet(inputVMScaleSet, getResponse); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, vmScaleSet.Name); } finally { //Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose //of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rgName); } } } /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VMScaleSet /// Update VMScaleSet /// Delete VMScaleSet /// Delete RG /// </summary> [Fact] public void TestVMScaleSetUpdateOperations() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group var rgName = TestUtilities.GenerateName(TestPrefix); var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist"); var vmScaleSet = CreateVMScaleSet_NoAsyncTracking(rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet); var getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmScaleSet.Name); ValidateVMScaleSet(inputVMScaleSet, getResponse); inputVMScaleSet.Sku.Name = VirtualMachineSizeTypes.StandardA1; VirtualMachineScaleSetExtensionProfile extensionProfile = new VirtualMachineScaleSetExtensionProfile() { Extensions = new List<VirtualMachineScaleSetExtension>() { GetTestVMSSVMExtension(autoUpdateMinorVersion:false), } }; inputVMScaleSet.VirtualMachineProfile.ExtensionProfile = extensionProfile; UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet); getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmScaleSet.Name); ValidateVMScaleSet(inputVMScaleSet, getResponse); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, vmScaleSet.Name); } finally { //Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose //of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rgName); } } } /// <summary> /// This is same as TestVMScaleSetUpdateOperations except that this test calls PATCH API instead of PUT /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VMScaleSet /// Update VMScaleSet /// Scale VMScaleSet /// Delete VMScaleSet /// Delete RG /// </summary> [Fact] public void TestVMScaleSetPatchOperations() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group var rgName = TestUtilities.GenerateName(TestPrefix); var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist"); var vmScaleSet = CreateVMScaleSet_NoAsyncTracking(rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet); var getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmScaleSet.Name); ValidateVMScaleSet(inputVMScaleSet, getResponse); // Adding an extension to the VMScaleSet. We will use Patch to update this. VirtualMachineScaleSetExtensionProfile extensionProfile = new VirtualMachineScaleSetExtensionProfile() { Extensions = new List<VirtualMachineScaleSetExtension>() { GetTestVMSSVMExtension(autoUpdateMinorVersion:false), } }; VirtualMachineScaleSetUpdate patchVMScaleSet = new VirtualMachineScaleSetUpdate() { VirtualMachineProfile = new VirtualMachineScaleSetUpdateVMProfile() { ExtensionProfile = extensionProfile, }, }; PatchVMScaleSet(rgName, vmssName, patchVMScaleSet); // Update the inputVMScaleSet and then compare it with response to verify the result. inputVMScaleSet.VirtualMachineProfile.ExtensionProfile = extensionProfile; getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmScaleSet.Name); ValidateVMScaleSet(inputVMScaleSet, getResponse); // Scaling the VMScaleSet now to 3 instances VirtualMachineScaleSetUpdate patchVMScaleSet2 = new VirtualMachineScaleSetUpdate() { Sku = new Sku() { Capacity = 3, }, }; PatchVMScaleSet(rgName, vmssName, patchVMScaleSet2); // Validate that ScaleSet Scaled to 3 instances inputVMScaleSet.Sku.Capacity = 3; getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmScaleSet.Name); ValidateVMScaleSet(inputVMScaleSet, getResponse); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, vmScaleSet.Name); } finally { //Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose //of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rgName); } } } } }
using UnityEngine; using UnityEditor; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.IO; public class CutsceneIO { #region Variables MachinimaSaveData m_SaveData = new MachinimaSaveData(); List<List<CutsceneTrackGroup>> TrackGroups = new List<List<CutsceneTrackGroup>>(); #endregion #region Functions #region Saving /// <summary> /// Used for saving the provided cutscenes while unity is playing /// </summary> /// <param name="cutscenes"></param> /// <param name="path"></param> //public void SaveMachinimaData(List<Cutscene> cutscenes, string path) public void SaveMachinimaData(List<TimelineObject> cutscenes, string path) { m_SaveData = new MachinimaSaveData(); TrackGroups.Clear(); //TrackGroups.ForEach(g => g.Clear()); for (int cutsceneIndex = 0; cutsceneIndex < cutscenes.Count; cutsceneIndex++) { Cutscene c = cutscenes[cutsceneIndex] as Cutscene; m_SaveData.CutsceneDatas.Add(c.m_CutsceneData); for (int eventIndex = 0; eventIndex < c.CutsceneEvents.Count; eventIndex++) { CutsceneEvent ce = c.CutsceneEvents[eventIndex]; CutsceneEvent savedCe = m_SaveData.CutsceneDatas[cutsceneIndex].Events[eventIndex]; // I have to save this information manually post unity 4.3 so that I can reload events savedCe.TargetComponentName = ce.TargetComponent.GetType().ToString(); // same thing here for (int paramIndex = 0; paramIndex < ce.m_Params.Count; paramIndex++) { CutsceneEventParam cep = ce.m_Params[paramIndex]; CutsceneEventParam savedCep = savedCe.m_Params[paramIndex]; savedCep.objDataName = cep.objDataName; savedCep.objDataIsComponent = cep.objDataIsComponent; savedCep.usesObjectData = cep.usesObjectData; savedCep.objDataInstanceId = cep.objDataInstanceId; } } //m_SaveData.CutsceneDatas[i].TrackGroups.AddRange(c.GroupManager.m_TrackGroups); TrackGroups.Add(new List<CutsceneTrackGroup>()); TrackGroups[cutsceneIndex].AddRange(c.GroupManager.m_TrackGroups); } VHFile.WriteXML<MachinimaSaveData>(path, m_SaveData); } /// <summary> /// Save a specific cutscene to the specified path. Writes out an XML file /// </summary> /// <param name="path"></param> /// <param name="cutscene"></param> public void SaveCutscene(string path, Cutscene cutscene) { Debug.Log(string.Format("Saving {0}", path)); VHFile.WriteXML<CutsceneData>(path, cutscene.m_CutsceneData); } /// <summary> /// Writes out each cutscene in this unity scene to a respectively named different xml file /// </summary> /// <param name="cutscenes"></param> /// <param name="path"></param> public void SaveAllCutscenes(string path, List<Cutscene> cutscenes) { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } // setup some save variables just in case for older cutscenes foreach (Cutscene c in cutscenes) { foreach (CutsceneEvent ce in c.CutsceneEvents) { ce.SetFunctionTargets(ce.TargetGameObject, ce.TargetComponent); foreach (CutsceneEventParam cep in ce.m_Params) { cep.SetObjData(cep.objData); if (cep.usesObjectData) cep.objDataAssetPath = AssetDatabase.GetAssetPath(cep.objData.GetInstanceID()); } } } cutscenes.ForEach(c => SaveCutscene(string.Format("{0}/{1}.xml", path, c.CutsceneName), c)); Debug.Log("Finished Saving all Cutscenes"); } #endregion #region Loading /// <summary> /// Used for saving between stopping and playing unity so that changes made while playing don't get wiped /// </summary> /// <param name="cutscenes"></param> public void LoadMachinimaData(List<TimelineObject> cutscenes) { if (m_SaveData.CutsceneDatas.Count != cutscenes.Count) { Debug.LogWarning("Data discrepances in the cutscene editor save data"); } // this will find every single gameobject loaded, both active and in-active. This also prunes the prefab assets so they don't conflict with the instances of the prefabs GameObject[] allGameObjects = Array.FindAll<GameObject>((GameObject[])Resources.FindObjectsOfTypeAll(typeof(GameObject)), go => PrefabUtility.GetPrefabType(go) != PrefabType.Prefab); //Debug.Log("allGameObjects. count: " + allGameObjects.Length); for (int i = 0; i < m_SaveData.CutsceneDatas.Count; i++) { Cutscene cutscene = cutscenes.Find(c => c.NameIdentifier == m_SaveData.CutsceneDatas[i].CutsceneName) as Cutscene; if (cutscene != null) { cutscene.m_CutsceneData = m_SaveData.CutsceneDatas[i]; cutscene.GroupManager.RemoveAllGroups(); cutscene.GroupManager.m_TrackGroups.AddRange(TrackGroups[i]); TrackGroups[i].Clear(); // we need to manually load gameobject and component data since we can't serialize it for (int j = 0; j < cutscene.m_CutsceneData.Events.Count; j++) { CutsceneEvent ce = cutscene.CutsceneEvents[j]; CutsceneEvent savedCe = m_SaveData.CutsceneDatas[i].Events[j]; // something broke in unity 4.3 where the component doesn't get saved, so I have to use the component name to try and find it ce.SetFunctionTargets(savedCe.TargetGameObject, savedCe.TargetGameObject.GetComponent(savedCe.TargetComponentName)); // this was added as well post 4.3 for (int k = 0; k < ce.m_Params.Count; k++) { CutsceneEventParam cep = ce.m_Params[k]; CutsceneEventParam savedCep = savedCe.m_Params[k]; if (savedCep.objDataIsComponent && savedCep.objDataInstanceId != 0) { GameObject[] goData = Array.FindAll<GameObject>(allGameObjects, go => (go.GetInstanceID() == cep.objDataInstanceId)); string shortenedType = Path.GetExtension(cep.DataType); shortenedType = string.IsNullOrEmpty(shortenedType) ? cep.DataType : shortenedType.Remove(0, 1); if (goData != null && goData.Length > 0) { Component objData = goData[0].GetComponent(shortenedType); if (objData != null) { cep.SetObjData(objData); } } } } } } else { Debug.Log("Error finding cutscene: " + m_SaveData.CutsceneDatas[i].CutsceneName); } } Resources.UnloadUnusedAssets(); m_SaveData.Clear(); m_SaveData = null; } /// <summary> /// Loads a specific cutscene from the xml path but only if a cutscene with the name name exists in the list provided /// </summary> /// <param name="cutscenes"></param> /// <param name="path"></param> /// <returns></returns> public Cutscene LoadCutscene(List<Cutscene> cutscenes, string path, GameObject[] allGameObjects) { CutsceneData csData = VHFile.ReadXML<CutsceneData>(path); Cutscene cutscene = cutscenes.Find(c => c.CutsceneName == csData.CutsceneName); if (cutscene == null) { return null; } cutscene.m_CutsceneData = csData; cutscene.CutsceneEvents.ForEach(ce => SetupEventObjects(cutscene, ce, allGameObjects)); if (csData.Version == MachinimaSaveData.MachinimaVersionNumber) { UpgradeCutsceneVersion(cutscene); } return cutscene; } /// <summary> /// Loads all the specified cutscenes from xml files based on cutscene names /// </summary> /// <param name="cutscenes"></param> /// <param name="path"></param> public void LoadAllCutscenes(List<Cutscene> cutscenes, string path) { // this will find every single gameobject loaded, both active and in-active. This also prunes the prefab assets so they don't conflict with the instances of the prefabs GameObject[] allGameObjects = Array.FindAll<GameObject>((GameObject[])Resources.FindObjectsOfTypeAll(typeof(GameObject)), go => PrefabUtility.GetPrefabType(go) != PrefabType.Prefab); cutscenes.ForEach(c => LoadCutscene(cutscenes, string.Format("{0}/{1}.xml", path, c.CutsceneName), allGameObjects)); Debug.Log("Finished Loading all Cutscenes"); } #endregion void SetupEventObjects(Cutscene cutscene, CutsceneEvent ce, GameObject[] allGameObjects) { if (!GenericEventNames.IsCustomEvent(ce.EventType)) { // locate the generic events child gameobject of the cutscene // and use it to correctly hook up the component reference Transform child = cutscene.transform.Find(ce.TargetGameObjectName); GenericEvents genericEventsComp = null; if (child == null) { Debug.LogError(string.Format("No child named {0} under gameobject {1}", ce.TargetGameObjectName, cutscene.name)); return; } genericEventsComp = child.GetComponent<GenericEvents>(); ce.TargetComponent = genericEventsComp.GetGenericEventsByEventType(ce.EventType); if (ce.TargetComponent == null) { Debug.LogError("Couldn't find the GenericEvent component associated with event type: " + ce.EventType); return; } ce.TargetComponent = genericEventsComp.GetGenericEventsByEventType(ce.EventType); ce.SetFunctionTargets(ce.TargetComponent.gameObject, ce.TargetComponent); } else { // custom events GameObject target = Array.Find<GameObject>(allGameObjects, go => (go.GetInstanceID() == ce.TargetGameObjectInstanceId && go.name == ce.TargetGameObjectName) || go.name == ce.TargetGameObjectName); if (target == null) { Debug.LogError(string.Format("Can't setup custom event {0} because no gameobject with name {1} exists with component name {2} attached", ce.Name, ce.TargetGameObjectName, ce.TargetComponentName)); return; } ce.SetFunctionTargets(target, target.GetComponent(ce.TargetComponentName)); } ce.m_Params.ForEach(cep => SetupParamData(ce.Name, cep, allGameObjects)); } /// <summary> /// Sets up cutscene parameter data that cannot be serialized to an xml file. For example, /// game object and component references as well as unity asset types, like audio clips and textures /// </summary> /// <param name="cutsceneEventName"></param> /// <param name="cep"></param> void SetupParamData(string cutsceneEventName, CutsceneEventParam cep, GameObject[] allGameObjects) { if (!cep.usesObjectData) { // this parameter isn't using object data, so we don't // have to do anything because it's data was properly serialized return; } if (cep.objDataIsComponent) { GameObject[] goData = Array.FindAll<GameObject>(allGameObjects, go => (go.GetInstanceID() == cep.objDataInstanceId && go.name == cep.objDataName) || go.name == cep.objDataName); if (goData == null || goData.Length == 0) { Debug.LogError(string.Format("Couldn't find gameobject {0} for cutscene event {1}", cep.objDataName, cutsceneEventName)); return; } else if (goData.Length > 1) { Debug.LogError(string.Format("There are {0} game objects in the scene with the name {1}. Picking the first one found to be used in event {2}. You should give each unique names.", goData.Length, cep.objDataName, cutsceneEventName)); } string shortenedType = Path.GetExtension(cep.DataType); shortenedType = string.IsNullOrEmpty(shortenedType) ? cep.DataType : shortenedType.Remove(0, 1); Component objData = goData[0].GetComponent(shortenedType); if (objData == null) { Debug.LogError(string.Format("Couldn't find component {0} on gameobject {1} for cutscene event {2}", shortenedType, cep.objDataName, cutsceneEventName)); } cep.SetObjData(objData); } else { if (cep.DataType.IndexOf("GameObject") != -1) { GameObject[] goData = Array.FindAll<GameObject>(allGameObjects, go => (go.GetInstanceID() == cep.objDataInstanceId && go.name == cep.objDataName) || go.name == cep.objDataName); if (goData == null || goData.Length == 0) { Debug.LogError(string.Format("Couldn't find gameobject {0} for cutscene event {1}", cep.objDataName, cutsceneEventName)); return; } else if (goData.Length > 1) { Debug.LogError(string.Format("There are {0} game objects in the scene with the name {1}. Picking the first one found to be used in event {2}. You should give each unique names.", goData.Length, cep.objDataName, cutsceneEventName)); } cep.SetObjData(goData[0]); } else if (cep.DataType.IndexOf("AudioClip") != -1) { cep.SetObjData(LoadAsset(cep.objDataAssetPath, typeof(AudioClip))); } else if (cep.DataType.IndexOf("AnimationClip") != -1) { cep.SetObjData(LoadAsset(cep.objDataAssetPath, typeof(AnimationClip))); } else if (cep.DataType.IndexOf("TextAsset") != -1) { cep.SetObjData(LoadAsset(cep.objDataAssetPath, typeof(TextAsset))); } else if (cep.DataType.IndexOf("Material") != -1) { cep.SetObjData(LoadAsset(cep.objDataAssetPath, typeof(Material))); } else if (cep.DataType.IndexOf("Texture") != -1) { cep.SetObjData(LoadAsset(cep.objDataAssetPath, typeof(Texture))); } else if (cep.DataType.IndexOf("Mesh") != -1) { cep.SetObjData(LoadAsset(cep.objDataAssetPath, typeof(Mesh))); } else { cep.SetObjData(LoadAsset(cep.objDataAssetPath, typeof(UnityEngine.Object))); //Debug.LogError(string.Format("Couldn't figure out how to load parameter type {0}", cep.DataType)); } } } UnityEngine.Object LoadAsset(string path, Type assetType) { UnityEngine.Object retVal = AssetDatabase.LoadAssetAtPath(path, assetType); if (retVal == null) { Debug.LogError(string.Format("Couldn't load asset type {0} with path {1}", assetType.ToString(), path)); } return retVal; } /// <summary> /// Used to handle any data irregularities between machinima maker versions /// </summary> /// <param name="cutscene"></param> void UpgradeCutsceneVersion(Cutscene cutscene) { } #endregion }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion namespace NotLogging { using System; using System.Collections; using log4net; using log4net.Appender; using log4net.Layout; using log4net.Repository; using log4net.Repository.Hierarchy; public class NotLogging { #region Init Code private static int WARM_UP_CYCLES = 10000; static readonly ILog SHORT_LOG = LogManager.GetLogger("A0123456789"); static readonly ILog MEDIUM_LOG= LogManager.GetLogger("A0123456789.B0123456789"); static readonly ILog LONG_LOG = LogManager.GetLogger("A0123456789.B0123456789.C0123456789"); static readonly ILog INEXISTENT_SHORT_LOG = LogManager.GetLogger("I0123456789"); static readonly ILog INEXISTENT_MEDIUM_LOG= LogManager.GetLogger("I0123456789.B0123456789"); static readonly ILog INEXISTENT_LONG_LOG = LogManager.GetLogger("I0123456789.B0123456789.C0123456789"); static readonly ILog[] LOG_ARRAY = new ILog[] { SHORT_LOG, MEDIUM_LOG, LONG_LOG, INEXISTENT_SHORT_LOG, INEXISTENT_MEDIUM_LOG, INEXISTENT_LONG_LOG}; static readonly TimedTest[] TIMED_TESTS = new TimedTest[] { new SimpleMessage_Bare(), new SimpleMessage_Array(), new SimpleMessage_MethodGuard_Bare(), new SimpleMessage_LocalGuard_Bare(), new ComplexMessage_Bare(), new ComplexMessage_Array(), new ComplexMessage_MethodGuard_Bare(), new ComplexMessage_MethodGuard_Array(), new ComplexMessage_MemberGuard_Bare(), new ComplexMessage_LocalGuard_Bare()}; private static void Usage() { System.Console.WriteLine( "Usage: NotLogging <true|false> <runLength>" + Environment.NewLine + "\t true indicates shipped code" + Environment.NewLine + "\t false indicates code in development" + Environment.NewLine + "\t runLength is an int representing the run length of loops" + Environment.NewLine + "\t We suggest that runLength be at least 1000000 (1 million)."); Environment.Exit(1); } /// <summary> /// Program wide initialization method /// </summary> /// <param name="args"></param> private static int ProgramInit(String[] args) { int runLength = 0; try { runLength = int.Parse(args[1]); } catch(Exception e) { System.Console.Error.WriteLine(e); Usage(); } ConsoleAppender appender = new ConsoleAppender(new SimpleLayout()); if("false" == args[0]) { // nothing to do } else if ("true" == args[0]) { System.Console.WriteLine("Flagging as shipped code."); ((Hierarchy)LogManager.GetRepository()).Threshold = log4net.Core.Level.Warn; } else { Usage(); } ((Logger)SHORT_LOG.Logger).Level = log4net.Core.Level.Info; ((Hierarchy)LogManager.GetRepository()).Root.Level = log4net.Core.Level.Info; ((Hierarchy)LogManager.GetRepository()).Root.AddAppender(appender); return runLength; } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] argv) { if (System.Diagnostics.Debugger.IsAttached) { WARM_UP_CYCLES = 0; argv = new string[] { "false", "2" }; } if(argv.Length != 2) { Usage(); } int runLength = ProgramInit(argv); System.Console.WriteLine(); System.Console.Write("Warming Up..."); if (WARM_UP_CYCLES > 0) { foreach(ILog logger in LOG_ARRAY) { foreach(TimedTest timedTest in TIMED_TESTS) { timedTest.Run(logger, WARM_UP_CYCLES); } } } System.Console.WriteLine("Done"); System.Console.WriteLine(); // Calculate maximum description length int maxDescLen = 0; foreach(TimedTest timedTest in TIMED_TESTS) { maxDescLen = Math.Max(maxDescLen, timedTest.Description.Length); } string formatString = "{0,-"+(maxDescLen+1)+"} {1,9:G} ticks. Log: {2}"; double delta; ArrayList averageData = new ArrayList(); foreach(TimedTest timedTest in TIMED_TESTS) { double total = 0; foreach(ILog logger in LOG_ARRAY) { delta = timedTest.Run(logger, runLength); System.Console.WriteLine(string.Format(formatString, timedTest.Description, delta, ((Logger)logger.Logger).Name)); total += delta; } System.Console.WriteLine(); averageData.Add(new object[] { timedTest, total/((double)LOG_ARRAY.Length) }); } System.Console.WriteLine(); System.Console.WriteLine("Averages:"); System.Console.WriteLine(); foreach(object[] pair in averageData) { string avgFormatString = "{0,-"+(maxDescLen+1)+"} {1,9:G} ticks."; System.Console.WriteLine(string.Format(avgFormatString, ((TimedTest)pair[0]).Description, ((double)pair[1]))); } } } abstract class TimedTest { abstract public double Run(ILog log, long runLength); abstract public string Description {get;} } #region Tests calling Debug(string) class SimpleMessage_Bare : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { log.Debug("msg"); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "log.Debug(\"msg\");"; } } } class ComplexMessage_MethodGuard_Bare : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { if(log.IsDebugEnabled) { log.Debug("msg" + i + "msg"); } } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "if(log.IsDebugEnabled) log.Debug(\"msg\" + i + \"msg\");"; } } } class ComplexMessage_Bare : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { log.Debug("msg" + i + "msg"); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "log.Debug(\"msg\" + i + \"msg\");"; } } } #endregion #region Tests calling Debug(new object[] { ... }) class SimpleMessage_Array : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { log.Debug(new object[] { "msg" }); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "log.Debug(new object[] { \"msg\" });"; } } } class ComplexMessage_MethodGuard_Array : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { if(log.IsDebugEnabled) { log.Debug(new object[] { "msg" , i , "msg" }); } } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "if(log.IsDebugEnabled) log.Debug(new object[] { \"msg\" , i , \"msg\" });"; } } } class ComplexMessage_Array : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { log.Debug(new object[] { "msg" , i , "msg" }); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "log.Debug(new object[] { \"msg\" , i , \"msg\" });"; } } } #endregion #region Tests calling Debug(string) (using class members) class ComplexMessage_MemberGuard_Bare : TimedTest { override public double Run(ILog log, long runLength) { return (new Impl(log)).Run(runLength); } override public string Description { get { return "if(m_isEnabled) m_log.Debug(\"msg\" + i + \"msg\");"; } } class Impl { private readonly ILog m_log; private readonly bool m_isEnabled; public Impl(ILog log) { m_log = log; m_isEnabled = m_log.IsDebugEnabled; } public double Run(long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { if(m_isEnabled) { m_log.Debug("msg" + i + "msg"); } } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } } } class SimpleMessage_LocalGuard_Bare : TimedTest { override public double Run(ILog log, long runLength) { bool isEnabled = log.IsDebugEnabled; DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { if (isEnabled) log.Debug("msg"); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "if (isEnabled) log.Debug(\"msg\");"; } } } class SimpleMessage_MethodGuard_Bare : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { if (log.IsDebugEnabled) log.Debug("msg"); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "if (log.IsDebugEnabled) log.Debug(\"msg\");"; } } } class ComplexMessage_LocalGuard_Bare : TimedTest { override public double Run(ILog log, long runLength) { bool isEnabled = log.IsDebugEnabled; DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { if(isEnabled) log.Debug("msg" + i + "msg"); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "if (isEnabled) log.Debug(\"msg\" + i + \"msg\");"; } } } #endregion }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcvsv = Google.Cloud.Video.Stitcher.V1; using sys = System; namespace Google.Cloud.Video.Stitcher.V1 { /// <summary>Resource name for the <c>VodStitchDetail</c> resource.</summary> public sealed partial class VodStitchDetailName : gax::IResourceName, sys::IEquatable<VodStitchDetailName> { /// <summary>The possible contents of <see cref="VodStitchDetailName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c> /// projects/{project}/locations/{location}/vodSessions/{vod_session}/vodStitchDetails/{vod_stitch_detail}</c> /// . /// </summary> ProjectLocationVodSessionVodStitchDetail = 1, } private static gax::PathTemplate s_projectLocationVodSessionVodStitchDetail = new gax::PathTemplate("projects/{project}/locations/{location}/vodSessions/{vod_session}/vodStitchDetails/{vod_stitch_detail}"); /// <summary>Creates a <see cref="VodStitchDetailName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="VodStitchDetailName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static VodStitchDetailName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new VodStitchDetailName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="VodStitchDetailName"/> with the pattern /// <c>projects/{project}/locations/{location}/vodSessions/{vod_session}/vodStitchDetails/{vod_stitch_detail}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="vodSessionId">The <c>VodSession</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="vodStitchDetailId">The <c>VodStitchDetail</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="VodStitchDetailName"/> constructed from the provided ids.</returns> public static VodStitchDetailName FromProjectLocationVodSessionVodStitchDetail(string projectId, string locationId, string vodSessionId, string vodStitchDetailId) => new VodStitchDetailName(ResourceNameType.ProjectLocationVodSessionVodStitchDetail, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), vodSessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(vodSessionId, nameof(vodSessionId)), vodStitchDetailId: gax::GaxPreconditions.CheckNotNullOrEmpty(vodStitchDetailId, nameof(vodStitchDetailId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="VodStitchDetailName"/> with pattern /// <c>projects/{project}/locations/{location}/vodSessions/{vod_session}/vodStitchDetails/{vod_stitch_detail}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="vodSessionId">The <c>VodSession</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="vodStitchDetailId">The <c>VodStitchDetail</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="VodStitchDetailName"/> with pattern /// <c>projects/{project}/locations/{location}/vodSessions/{vod_session}/vodStitchDetails/{vod_stitch_detail}</c> /// . /// </returns> public static string Format(string projectId, string locationId, string vodSessionId, string vodStitchDetailId) => FormatProjectLocationVodSessionVodStitchDetail(projectId, locationId, vodSessionId, vodStitchDetailId); /// <summary> /// Formats the IDs into the string representation of this <see cref="VodStitchDetailName"/> with pattern /// <c>projects/{project}/locations/{location}/vodSessions/{vod_session}/vodStitchDetails/{vod_stitch_detail}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="vodSessionId">The <c>VodSession</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="vodStitchDetailId">The <c>VodStitchDetail</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="VodStitchDetailName"/> with pattern /// <c>projects/{project}/locations/{location}/vodSessions/{vod_session}/vodStitchDetails/{vod_stitch_detail}</c> /// . /// </returns> public static string FormatProjectLocationVodSessionVodStitchDetail(string projectId, string locationId, string vodSessionId, string vodStitchDetailId) => s_projectLocationVodSessionVodStitchDetail.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(vodSessionId, nameof(vodSessionId)), gax::GaxPreconditions.CheckNotNullOrEmpty(vodStitchDetailId, nameof(vodStitchDetailId))); /// <summary> /// Parses the given resource name string into a new <see cref="VodStitchDetailName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/vodSessions/{vod_session}/vodStitchDetails/{vod_stitch_detail}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="vodStitchDetailName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="VodStitchDetailName"/> if successful.</returns> public static VodStitchDetailName Parse(string vodStitchDetailName) => Parse(vodStitchDetailName, false); /// <summary> /// Parses the given resource name string into a new <see cref="VodStitchDetailName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/vodSessions/{vod_session}/vodStitchDetails/{vod_stitch_detail}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="vodStitchDetailName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="VodStitchDetailName"/> if successful.</returns> public static VodStitchDetailName Parse(string vodStitchDetailName, bool allowUnparsed) => TryParse(vodStitchDetailName, allowUnparsed, out VodStitchDetailName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="VodStitchDetailName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/vodSessions/{vod_session}/vodStitchDetails/{vod_stitch_detail}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="vodStitchDetailName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="VodStitchDetailName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string vodStitchDetailName, out VodStitchDetailName result) => TryParse(vodStitchDetailName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="VodStitchDetailName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/vodSessions/{vod_session}/vodStitchDetails/{vod_stitch_detail}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="vodStitchDetailName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="VodStitchDetailName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string vodStitchDetailName, bool allowUnparsed, out VodStitchDetailName result) { gax::GaxPreconditions.CheckNotNull(vodStitchDetailName, nameof(vodStitchDetailName)); gax::TemplatedResourceName resourceName; if (s_projectLocationVodSessionVodStitchDetail.TryParseName(vodStitchDetailName, out resourceName)) { result = FromProjectLocationVodSessionVodStitchDetail(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(vodStitchDetailName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private VodStitchDetailName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string vodSessionId = null, string vodStitchDetailId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; ProjectId = projectId; VodSessionId = vodSessionId; VodStitchDetailId = vodStitchDetailId; } /// <summary> /// Constructs a new instance of a <see cref="VodStitchDetailName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/vodSessions/{vod_session}/vodStitchDetails/{vod_stitch_detail}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="vodSessionId">The <c>VodSession</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="vodStitchDetailId">The <c>VodStitchDetail</c> ID. Must not be <c>null</c> or empty.</param> public VodStitchDetailName(string projectId, string locationId, string vodSessionId, string vodStitchDetailId) : this(ResourceNameType.ProjectLocationVodSessionVodStitchDetail, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), vodSessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(vodSessionId, nameof(vodSessionId)), vodStitchDetailId: gax::GaxPreconditions.CheckNotNullOrEmpty(vodStitchDetailId, nameof(vodStitchDetailId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>VodSession</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string VodSessionId { get; } /// <summary> /// The <c>VodStitchDetail</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string VodStitchDetailId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationVodSessionVodStitchDetail: return s_projectLocationVodSessionVodStitchDetail.Expand(ProjectId, LocationId, VodSessionId, VodStitchDetailId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as VodStitchDetailName); /// <inheritdoc/> public bool Equals(VodStitchDetailName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(VodStitchDetailName a, VodStitchDetailName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(VodStitchDetailName a, VodStitchDetailName b) => !(a == b); } public partial class VodStitchDetail { /// <summary> /// <see cref="gcvsv::VodStitchDetailName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcvsv::VodStitchDetailName VodStitchDetailName { get => string.IsNullOrEmpty(Name) ? null : gcvsv::VodStitchDetailName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
//----------------------------------------------------------------------------- // <copyright file="ExpressionComparer.cs" company="http://rulesengine.codeplex.com"> // Copyright (c) athoma13. See RulesEngine_License.txt. This file is // subject to the Microsoft Public License. All other rights reserved. // </copyright> // <summary> // Created by: athoma13 // Date : Fri Sep 30 2011 // Purpose : Rule Engine // </summary> // <history> // Sat Jan 28 2012 by Fastalanasa - Added to WheelMUD.Rules // </history> //----------------------------------------------------------------------------- namespace WheelMUD.Rules { using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; public class ExpressionComparer : IEqualityComparer<Expression> { public bool Compare(Expression node1, Expression node2) { object state = CreateCompareState(node1, node2); return Compare(node1, node2, state); } public bool Equals(Expression x, Expression y) { return Compare(x, y); } public int GetHashCode(Expression obj) { object state = CreateHashState(obj); return GetHashCode(obj, state); } protected bool CompareMany<T>(IEnumerable<T> nodes1, IEnumerable<T> nodes2, object state, Func<T, T, object, bool> compareDelegate) where T : class { if (AreBothNull(nodes1, nodes2)) return true; if (AreEitherNull(nodes1, nodes2)) return false; var en1 = nodes1.GetEnumerator(); var en2 = nodes2.GetEnumerator(); try { while (true) { var moved = false; var exp1 = (moved |= en1.MoveNext()) ? en1.Current : null; var exp2 = (moved |= en2.MoveNext()) ? en2.Current : null; if (!moved) return true; if (!compareDelegate(exp1, exp2, state)) return false; } } finally { en1.Dispose(); en2.Dispose(); } } protected bool AreBothNull<T>(T arg1, T arg2) where T : class { return arg1 == null && arg2 == null; } protected bool AreEitherNull<T>(T arg1, T arg2) where T : class { return arg1 == null || arg2 == null; } protected virtual bool CompareType(Type node1, Type node2, object state) { return node1 == node2; } protected virtual bool CompareMemberInfo(MemberInfo node1, MemberInfo node2, object state) { return node1 == node2; } protected virtual bool CompareObject(object node1, object node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return node1.Equals(node2); } protected virtual bool CompareBinary(BinaryExpression node1, BinaryExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareMemberInfo(node1.Method, node2.Method, state) && Compare(node1.Left, node2.Left, state) && CompareLambda(node1.Conversion, node2.Conversion, state) && Compare(node1.Right, node2.Right, state); } protected virtual bool CompareBlock(BlockExpression node1, BlockExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareType(node1.Type, node2.Type, state) && CompareMany(node1.Variables, node2.Variables, state, CompareParameter) && CompareMany(node1.Expressions, node2.Expressions, state, Compare); } protected virtual bool CompareCatchBlock(CatchBlock node1, CatchBlock node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareType(node1.Test, node2.Test, state) && Compare(node1.Body, node2.Body, state) && CompareParameter(node1.Variable, node2.Variable, state) && Compare(node1.Filter, node2.Filter, state); } protected virtual bool CompareConditional(ConditionalExpression node1, ConditionalExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return Compare(node1.Test, node2.Test, state) && Compare(node1.IfTrue, node2.IfTrue, state) && Compare(node1.IfFalse, node2.IfFalse, state); } protected virtual bool CompareConstant(ConstantExpression node1, ConstantExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareType(node1.Type, node2.Type, state) && CompareObject(node1.Value, node2.Value, state); } protected virtual bool CompareDebugInfo(DebugInfoExpression node1, DebugInfoExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return node1.Document.FileName == node2.Document.FileName && node1.EndColumn == node2.EndColumn && node1.EndLine == node2.EndLine && node1.StartColumn == node2.StartColumn && node1.StartLine == node2.StartLine; } protected virtual bool CompareDefault(DefaultExpression node1, DefaultExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareType(node1.Type, node2.Type, state); } protected virtual bool CompareDynamic(DynamicExpression node1, DynamicExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareType(node1.Type, node2.Type, state) && CompareType(node1.DelegateType, node2.DelegateType, state) && CompareMany(node1.Arguments, node2.Arguments, state, Compare); } protected virtual bool CompareElementInit(ElementInit node1, ElementInit node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareMemberInfo(node1.AddMethod, node2.AddMethod, state) && CompareMany(node1.Arguments, node2.Arguments, state, Compare); } protected virtual bool CompareGoto(GotoExpression node1, GotoExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return node1.Kind == node2.Kind && CompareType(node1.Type, node2.Type, state) && CompareLabelTarget(node1.Target, node2.Target, state) && Compare(node1.Value, node2.Value, state); } protected virtual bool CompareIndex(IndexExpression node1, IndexExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareType(node1.Type, node2.Type, state) && CompareMemberInfo(node1.Indexer, node2.Indexer, state) && Compare(node1.Object, node2.Object, state) && CompareMany(node1.Arguments, node2.Arguments, state, Compare); } protected virtual bool CompareInvocation(InvocationExpression node1, InvocationExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareType(node1.Type, node2.Type, state) && Compare(node1.Expression, node2.Expression, state) && CompareMany(node1.Arguments, node2.Arguments, state, Compare); } protected virtual bool CompareLabel(LabelExpression node1, LabelExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareType(node1.Type, node2.Type, state) && CompareLabelTarget(node1.Target, node2.Target, state) && Compare(node1.DefaultValue, node2.DefaultValue, state); } protected virtual bool CompareLabelTarget(LabelTarget node1, LabelTarget node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return node1.Name == node2.Name && CompareType(node1.Type, node2.Type, state); } protected virtual bool CompareLambda(LambdaExpression node1, LambdaExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareType(node1.Type, node2.Type, state) && CompareType(node1.ReturnType, node2.ReturnType, state) && CompareMany(node1.Parameters, node2.Parameters, state, CompareParameter) && Compare(node1.Body, node2.Body, state); } protected virtual bool CompareListInit(ListInitExpression node1, ListInitExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareType(node1.Type, node2.Type, state) && CompareNew(node1.NewExpression, node2.NewExpression, state) && CompareMany(node1.Initializers, node2.Initializers, state, CompareElementInit); } protected virtual bool CompareLoop(LoopExpression node1, LoopExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareType(node1.Type, node2.Type, state) && CompareLabelTarget(node1.BreakLabel, node2.BreakLabel, state) && CompareLabelTarget(node1.ContinueLabel, node2.ContinueLabel, state) && Compare(node1.Body, node2.Body, state); } protected virtual bool CompareMember(MemberExpression node1, MemberExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareType(node1.Type, node2.Type, state) && CompareMemberInfo(node1.Member, node2.Member, state) && Compare(node1.Expression, node2.Expression, state); } protected virtual bool CompareMemberAssignment(MemberAssignment node1, MemberAssignment node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareMemberInfo(node1.Member, node2.Member, state) && Compare(node1.Expression, node2.Expression, state); } protected virtual bool CompareMemberBinding(MemberBinding node1, MemberBinding node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareMemberInfo(node1.Member, node2.Member, state); } protected virtual bool CompareMemberInit(MemberInitExpression node1, MemberInitExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareType(node1.Type, node2.Type, state) && CompareNew(node1.NewExpression, node2.NewExpression, state); } protected virtual bool CompareMemberListBinding(MemberListBinding node1, MemberListBinding node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareMemberInfo(node1.Member, node2.Member, state) && CompareMany(node1.Initializers, node2.Initializers, state, CompareElementInit); } protected virtual bool CompareMemberMemberBinding(MemberMemberBinding node1, MemberMemberBinding node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareMemberInfo(node1.Member, node2.Member, state) && CompareMany(node1.Bindings, node2.Bindings, state, CompareMemberBinding); } protected virtual bool CompareMethodCall(MethodCallExpression node1, MethodCallExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareType(node1.Type, node2.Type, state) && CompareMemberInfo(node1.Method, node2.Method, state) && Compare(node1.Object, node2.Object, state) && CompareMany(node1.Arguments, node2.Arguments, state, Compare); } protected virtual bool CompareNew(NewExpression node1, NewExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareMemberInfo(node1.Constructor, node2.Constructor, state) && CompareMany(node1.Arguments, node2.Arguments, state, Compare); } protected virtual bool CompareNewArray(NewArrayExpression node1, NewArrayExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareType(node1.Type, node2.Type, state) && CompareMany(node1.Expressions, node2.Expressions, state, Compare); } protected virtual bool CompareParameter(ParameterExpression node1, ParameterExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareType(node1.Type, node2.Type, state) && node1.IsByRef == node2.IsByRef && node1.Name == node2.Name; } protected virtual bool CompareRuntimeVariables(RuntimeVariablesExpression node1, RuntimeVariablesExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareType(node1.Type, node2.Type, state) && CompareMany(node1.Variables, node2.Variables, state, CompareParameter); } protected virtual bool CompareSwitch(SwitchExpression node1, SwitchExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return Compare(node1.SwitchValue, node2.SwitchValue, state) && CompareMany(node1.Cases, node2.Cases, state, CompareSwitchCase) && CompareMemberInfo(node1.Comparison, node2.Comparison, state) && Compare(node1.DefaultBody, node2.DefaultBody, state); } protected virtual bool CompareSwitchCase(SwitchCase node1, SwitchCase node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return Compare(node1.Body, node2.Body, state) && CompareMany(node1.TestValues, node2.TestValues, state, Compare); } protected virtual bool CompareTry(TryExpression node1, TryExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return Compare(node1.Body, node2.Body, state) && Compare(node1.Fault, node2.Fault, state) && Compare(node1.Finally, node2.Finally, state) && CompareMany(node1.Handlers, node2.Handlers, state, CompareCatchBlock); } protected virtual bool CompareTypeBinary(TypeBinaryExpression node1, TypeBinaryExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return Compare(node1.Expression, node2.Expression, state) && CompareType(node1.TypeOperand, node2.TypeOperand, state); } protected virtual bool CompareUnary(UnaryExpression node1, UnaryExpression node2, object state) { if (AreBothNull(node1, node2)) return true; if (AreEitherNull(node1, node2)) return false; return CompareMemberInfo(node1.Method, node2.Method, state) && Compare(node1.Operand, node2.Operand, state); } protected virtual bool Compare(Expression node1, Expression node2, object state) { if (AreBothNull(node1, node2)) return true; // Let specific method decide if (AreEitherNull(node1, node2)) return false; if (node1 is BinaryExpression && node2 is BinaryExpression) return CompareBinary((BinaryExpression)node1, (BinaryExpression)node2, state); if (node1 is BlockExpression && node2 is BlockExpression) return CompareBlock((BlockExpression)node1, (BlockExpression)node2, state); if (node1 is ConditionalExpression && node2 is ConditionalExpression) return CompareConditional((ConditionalExpression)node1, (ConditionalExpression)node2, state); if (node1 is ConstantExpression && node2 is ConstantExpression) return CompareConstant((ConstantExpression)node1, (ConstantExpression)node2, state); if (node1 is DebugInfoExpression && node2 is DebugInfoExpression) return CompareDebugInfo((DebugInfoExpression)node1, (DebugInfoExpression)node2, state); if (node1 is DefaultExpression && node2 is DefaultExpression) return CompareDefault((DefaultExpression)node1, (DefaultExpression)node2, state); if (node1 is DynamicExpression && node2 is DynamicExpression) return CompareDynamic((DynamicExpression)node1, (DynamicExpression)node2, state); if (node1 is GotoExpression && node2 is GotoExpression) return CompareGoto((GotoExpression)node1, (GotoExpression)node2, state); if (node1 is IndexExpression && node2 is IndexExpression) return CompareIndex((IndexExpression)node1, (IndexExpression)node2, state); if (node1 is InvocationExpression && node2 is InvocationExpression) return CompareInvocation((InvocationExpression)node1, (InvocationExpression)node2, state); if (node1 is LabelExpression && node2 is LabelExpression) return CompareLabel((LabelExpression)node1, (LabelExpression)node2, state); if (node1 is LambdaExpression && node2 is LambdaExpression) return CompareLambda((LambdaExpression)node1, (LambdaExpression)node2, state); if (node1 is ListInitExpression && node2 is ListInitExpression) return CompareListInit((ListInitExpression)node1, (ListInitExpression)node2, state); if (node1 is LoopExpression && node2 is LoopExpression) return CompareLoop((LoopExpression)node1, (LoopExpression)node2, state); if (node1 is MemberExpression && node2 is MemberExpression) return CompareMember((MemberExpression)node1, (MemberExpression)node2, state); if (node1 is MemberInitExpression && node2 is MemberInitExpression) return CompareMemberInit((MemberInitExpression)node1, (MemberInitExpression)node2, state); if (node1 is MethodCallExpression && node2 is MethodCallExpression) return CompareMethodCall((MethodCallExpression)node1, (MethodCallExpression)node2, state); if (node1 is NewExpression && node2 is NewExpression) return CompareNew((NewExpression)node1, (NewExpression)node2, state); if (node1 is NewArrayExpression && node2 is NewArrayExpression) return CompareNewArray((NewArrayExpression)node1, (NewArrayExpression)node2, state); if (node1 is ParameterExpression && node2 is ParameterExpression) return CompareParameter((ParameterExpression)node1, (ParameterExpression)node2, state); if (node1 is RuntimeVariablesExpression && node2 is RuntimeVariablesExpression) return CompareRuntimeVariables((RuntimeVariablesExpression)node1, (RuntimeVariablesExpression)node2, state); if (node1 is SwitchExpression && node2 is SwitchExpression) return CompareSwitch((SwitchExpression)node1, (SwitchExpression)node2, state); if (node1 is TryExpression && node2 is TryExpression) return CompareTry((TryExpression)node1, (TryExpression)node2, state); if (node1 is TypeBinaryExpression && node2 is TypeBinaryExpression) return CompareTypeBinary((TypeBinaryExpression)node1, (TypeBinaryExpression)node2, state); if (node1 is UnaryExpression && node2 is UnaryExpression) return CompareUnary((UnaryExpression)node1, (UnaryExpression)node2, state); return false; } protected int CombineHash(int hashcode, params int[] otherHashes) { return Utilities.CombineHash(hashcode, otherHashes); } protected int GetHashCode<T>(IEnumerable<T> nodes, object state, Func<T, object, int> getHashCodeDelegate) where T : class { if (nodes == null) return 0; int result = 0; foreach (T node in nodes) { result = CombineHash(result, getHashCodeDelegate(node, state)); } return result; } protected virtual int GetHashCode(Type node, object state) { if (node == null) return 0; return node.GetHashCode(); } protected virtual int GetHashCode(MemberInfo node, object state) { if (node == null) return 0; return node.GetHashCode(); } protected virtual int GetHashCode(object node, object state) { if (node == null) return 0; return node.GetHashCode(); } protected virtual int GetHashCode(BinaryExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Method, state), GetHashCode(node.Left, state), GetHashCode(node.Conversion, state), GetHashCode(node.Right, state)); } protected virtual int GetHashCode(BlockExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Type, state), GetHashCode(node.Variables, state, GetHashCode), GetHashCode(node.Expressions, state, GetHashCode)); } protected virtual int GetHashCode(CatchBlock node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Test, state), GetHashCode(node.Body, state), GetHashCode(node.Variable, state), GetHashCode(node.Filter, state)); } protected virtual int GetHashCode(ConditionalExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Test, state), GetHashCode(node.IfTrue, state), GetHashCode(node.IfFalse, state)); } protected virtual int GetHashCode(ConstantExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Type, state), GetHashCode(node.Value, state)); } protected virtual int GetHashCode(DebugInfoExpression node, object state) { if (node == null) return 0; var hash = node.Document != null ? (node.Document.FileName ?? string.Empty).GetHashCode() : 0; return CombineHash(hash, node.EndColumn, node.EndLine, node.StartColumn, node.StartLine); } protected virtual int GetHashCode(DefaultExpression node, object state) { if (node == null) return 0; return GetHashCode(node.Type, state); } protected virtual int GetHashCode(DynamicExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Type, state), GetHashCode(node.DelegateType, state), GetHashCode(node.Arguments, state, GetHashCode)); } protected virtual int GetHashCode(ElementInit node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.AddMethod, state), GetHashCode(node.Arguments, state, GetHashCode)); } protected virtual int GetHashCode(GotoExpression node, object state) { if (node == null) return 0; return CombineHash(node.Kind.GetHashCode(), GetHashCode(node.Type, state), GetHashCode(node.Target, state), GetHashCode(node.Value, state)); } protected virtual int GetHashCode(IndexExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Type, state), GetHashCode(node.Indexer, state), GetHashCode(node.Object, state), GetHashCode(node.Arguments, state, GetHashCode)); } protected virtual int GetHashCode(InvocationExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Type, state), GetHashCode(node.Expression, state), GetHashCode(node.Arguments, state, GetHashCode)); } protected virtual int GetHashCode(LabelExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Type, state), GetHashCode(node.Target, state), GetHashCode(node.DefaultValue, state)); } protected virtual int GetHashCode(LabelTarget node, object state) { if (node == null) return 0; return CombineHash((node.Name ?? string.Empty).GetHashCode(), GetHashCode(node.Type, state)); } protected virtual int GetHashCode(LambdaExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Type, state), GetHashCode(node.ReturnType, state), GetHashCode(node.Parameters, state, GetHashCode), GetHashCode(node.Body, state)); } protected virtual int GetHashCode(ListInitExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Type, state), GetHashCode(node.NewExpression, state), GetHashCode(node.Initializers, state, GetHashCode)); } protected virtual int GetHashCode(LoopExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Type, state), GetHashCode(node.BreakLabel, state), GetHashCode(node.ContinueLabel, state), GetHashCode(node.Body, state)); } protected virtual int GetHashCode(MemberExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Type, state), GetHashCode(node.Member, state), GetHashCode(node.Expression, state)); } protected virtual int GetHashCode(MemberAssignment node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Member, state), GetHashCode(node.Expression, state)); } protected virtual int GetHashCode(MemberBinding node, object state) { if (node == null) return 0; return GetHashCode(node.Member, state); } protected virtual int GetHashCode(MemberInitExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Type, state), GetHashCode(node.NewExpression, state)); } protected virtual int GetHashCode(MemberListBinding node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Member, state), GetHashCode(node.Initializers, state, GetHashCode)); } protected virtual int GetHashCode(MemberMemberBinding node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Member, state), GetHashCode(node.Bindings, state, GetHashCode)); } protected virtual int GetHashCode(MethodCallExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Type, state), GetHashCode(node.Method, state), GetHashCode(node.Object, state), GetHashCode(node.Arguments, state, GetHashCode)); } protected virtual int GetHashCode(NewExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Constructor, state), GetHashCode(node.Arguments, state, GetHashCode)); } protected virtual int GetHashCode(NewArrayExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Type, state), GetHashCode(node.Expressions, state, GetHashCode)); } protected virtual int GetHashCode(ParameterExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Type, state), node.IsByRef.GetHashCode(), (node.Name ?? string.Empty).GetHashCode()); } protected virtual int GetHashCode(RuntimeVariablesExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Type, state), GetHashCode(node.Variables, state, GetHashCode)); } protected virtual int GetHashCode(SwitchExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.SwitchValue, state), GetHashCode(node.Cases, state, GetHashCode), GetHashCode(node.Comparison, state), GetHashCode(node.DefaultBody, state)); } protected virtual int GetHashCode(SwitchCase node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Body, state), GetHashCode(node.TestValues, state, GetHashCode)); } protected virtual int GetHashCode(TryExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Body, state), GetHashCode(node.Fault, state), GetHashCode(node.Finally, state), GetHashCode(node.Handlers, state, GetHashCode)); } protected virtual int GetHashCode(TypeBinaryExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Expression, state), GetHashCode(node.TypeOperand, state)); } protected virtual int GetHashCode(UnaryExpression node, object state) { if (node == null) return 0; return CombineHash(GetHashCode(node.Method, state), GetHashCode(node.Operand, state)); } protected virtual int GetHashCode(Expression node, object state) { if (node == null) return 0; if (node is BinaryExpression) return GetHashCode((BinaryExpression)node, state); if (node is BlockExpression) return GetHashCode((BlockExpression)node, state); if (node is ConditionalExpression) return GetHashCode((ConditionalExpression)node, state); if (node is ConstantExpression) return GetHashCode((ConstantExpression)node, state); if (node is DebugInfoExpression) return GetHashCode((DebugInfoExpression)node, state); if (node is DefaultExpression) return GetHashCode((DefaultExpression)node, state); if (node is DynamicExpression) return GetHashCode((DynamicExpression)node, state); if (node is GotoExpression) return GetHashCode((GotoExpression)node, state); if (node is IndexExpression) return GetHashCode((IndexExpression)node, state); if (node is InvocationExpression) return GetHashCode((InvocationExpression)node, state); if (node is LabelExpression) return GetHashCode((LabelExpression)node, state); if (node is LambdaExpression) return GetHashCode((LambdaExpression)node, state); if (node is ListInitExpression) return GetHashCode((ListInitExpression)node, state); if (node is LoopExpression) return GetHashCode((LoopExpression)node, state); if (node is MemberExpression) return GetHashCode((MemberExpression)node, state); if (node is MemberInitExpression) return GetHashCode((MemberInitExpression)node, state); if (node is MethodCallExpression) return GetHashCode((MethodCallExpression)node, state); if (node is NewExpression) return GetHashCode((NewExpression)node, state); if (node is NewArrayExpression) return GetHashCode((NewArrayExpression)node, state); if (node is ParameterExpression) return GetHashCode((ParameterExpression)node, state); if (node is RuntimeVariablesExpression) return GetHashCode((RuntimeVariablesExpression)node, state); if (node is SwitchExpression) return GetHashCode((SwitchExpression)node, state); if (node is TryExpression) return GetHashCode((TryExpression)node, state); if (node is TypeBinaryExpression) return GetHashCode((TypeBinaryExpression)node, state); if (node is UnaryExpression) return GetHashCode((UnaryExpression)node, state); return 0; } protected virtual object CreateCompareState(Expression node1, Expression node2) { return null; } protected virtual object CreateHashState(Expression node) { return null; } } }
// <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/> // <version>$Revision: 3630 $</version> // </file> using System; using System.Collections.Generic; namespace ICSharpCode.SharpDevelop.Dom { /// <summary> /// Base class for return types that wrap around other return types. /// </summary> public abstract class ProxyReturnType : IReturnType { public abstract IReturnType BaseType { get; } public sealed override bool Equals(object obj) { return Equals(obj as IReturnType); } public virtual bool Equals(IReturnType other) { // this check is necessary because the underlying Equals implementation // expects to be able to retrieve the base type of "other" - which fails when // this==other and therefore other.busy. if (other == this) return true; IReturnType baseType = BaseType; bool tmp = (baseType != null && TryEnter()) ? baseType.Equals(other) : false; Leave(); return tmp; } public override int GetHashCode() { IReturnType baseType = BaseType; int tmp = (baseType != null && TryEnter()) ? baseType.GetHashCode() : 0; Leave(); return tmp; } protected int GetObjectHashCode() { return base.GetHashCode(); } // Required to prevent stack overflow on inferrence cycles bool busy; // keep this method as small as possible, it should be inlined! bool TryEnter() { if (busy) { PrintTryEnterWarning(); return false; } else { busy = true; return true; } } void Leave() { busy = false; } void PrintTryEnterWarning() { LoggingService.Info("TryEnter failed on " + ToString()); } public virtual string FullyQualifiedName { get { IReturnType baseType = BaseType; string tmp = (baseType != null && TryEnter()) ? baseType.FullyQualifiedName : "?"; Leave(); return tmp; } } public virtual string Name { get { IReturnType baseType = BaseType; string tmp = (baseType != null && TryEnter()) ? baseType.Name : "?"; Leave(); return tmp; } } public virtual string Namespace { get { IReturnType baseType = BaseType; string tmp = (baseType != null && TryEnter()) ? baseType.Namespace : "?"; Leave(); return tmp; } } public virtual string DotNetName { get { IReturnType baseType = BaseType; string tmp = (baseType != null && TryEnter()) ? baseType.DotNetName : "?"; Leave(); return tmp; } } public virtual int TypeArgumentCount { get { IReturnType baseType = BaseType; int tmp = (baseType != null && TryEnter()) ? baseType.TypeArgumentCount : 0; Leave(); return tmp; } } public virtual IClass GetUnderlyingClass() { IReturnType baseType = BaseType; IClass tmp = (baseType != null && TryEnter()) ? baseType.GetUnderlyingClass() : null; Leave(); return tmp; } public virtual List<IMethod> GetMethods() { IReturnType baseType = BaseType; List<IMethod> tmp = (baseType != null && TryEnter()) ? baseType.GetMethods() : new List<IMethod>(); Leave(); return tmp; } public virtual List<IProperty> GetProperties() { IReturnType baseType = BaseType; List<IProperty> tmp = (baseType != null && TryEnter()) ? baseType.GetProperties() : new List<IProperty>(); Leave(); return tmp; } public virtual List<IField> GetFields() { IReturnType baseType = BaseType; List<IField> tmp = (baseType != null && TryEnter()) ? baseType.GetFields() : new List<IField>(); Leave(); return tmp; } public virtual List<IEvent> GetEvents() { IReturnType baseType = BaseType; List<IEvent> tmp = (baseType != null && TryEnter()) ? baseType.GetEvents() : new List<IEvent>(); Leave(); return tmp; } public virtual bool IsDefaultReturnType { get { IReturnType baseType = BaseType; bool tmp = (baseType != null && TryEnter()) ? baseType.IsDefaultReturnType : false; Leave(); return tmp; } } public bool IsDecoratingReturnType<T>() where T : DecoratingReturnType { return CastToDecoratingReturnType<T>() != null; } public virtual T CastToDecoratingReturnType<T>() where T : DecoratingReturnType { IReturnType baseType = BaseType; T temp; if (baseType != null && TryEnter()) temp = baseType.CastToDecoratingReturnType<T>(); else temp = null; Leave(); return temp; } public bool IsArrayReturnType { get { return IsDecoratingReturnType<ArrayReturnType>(); } } public ArrayReturnType CastToArrayReturnType() { return CastToDecoratingReturnType<ArrayReturnType>(); } public bool IsGenericReturnType { get { return IsDecoratingReturnType<GenericReturnType>(); } } public GenericReturnType CastToGenericReturnType() { return CastToDecoratingReturnType<GenericReturnType>(); } public bool IsConstructedReturnType { get { return IsDecoratingReturnType<ConstructedReturnType>(); } } public ConstructedReturnType CastToConstructedReturnType() { return CastToDecoratingReturnType<ConstructedReturnType>(); } public virtual bool? IsReferenceType { get { IReturnType baseType = BaseType; bool? tmp = (baseType != null && TryEnter()) ? baseType.IsReferenceType : null; Leave(); return tmp; } } public virtual IReturnType GetDirectReturnType() { IReturnType baseType = BaseType; IReturnType tmp = (baseType != null && TryEnter()) ? baseType.GetDirectReturnType() : UnknownReturnType.Instance; Leave(); return tmp; } } }
/* ==================================================================== 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 TestCases.SS.Formula.Atp { using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NUnit.Framework; using NPOI.HSSF.Model; using System; using TestCases.HSSF; using NPOI.SS.Util; using NPOI.SS.Formula.Eval; /** * Testcase for 'Analysis Toolpak' function RANDBETWEEN() * * @author Brendan Nolan */ [TestFixture] public class TestRandBetween { private HSSFWorkbook wb; private IFormulaEvaluator Evaluator; private ICell bottomValueCell; private ICell topValueCell; private ICell formulaCell; [SetUp] public void SetUp() { wb = HSSFTestDataSamples.OpenSampleWorkbook("TestRandBetween.xls"); Evaluator = wb.GetCreationHelper().CreateFormulaEvaluator(); ISheet sheet = wb.CreateSheet("RandBetweenSheet"); IRow row = sheet.CreateRow(0); bottomValueCell = row.CreateCell(0); topValueCell = row.CreateCell(1); formulaCell = row.CreateCell(2, CellType.Formula); } protected void tearDown() { // TODO Auto-generated method stub } /** * Check where values are the same */ [Test] public void TestRandBetweenSameValues() { Evaluator.ClearAllCachedResultValues(); formulaCell.CellFormula = ("RANDBETWEEN(1,1)"); Evaluator.EvaluateFormulaCell(formulaCell); Assert.AreEqual(1, formulaCell.NumericCellValue, 0); Evaluator.ClearAllCachedResultValues(); formulaCell.CellFormula = ("RANDBETWEEN(-1,-1)"); Evaluator.EvaluateFormulaCell(formulaCell); Assert.AreEqual(-1, formulaCell.NumericCellValue, 0); } /** * Check special case where rounded up bottom value is greater than * top value. */ [Test] public void TestRandBetweenSpecialCase() { bottomValueCell.SetCellValue(0.05); topValueCell.SetCellValue(0.1); formulaCell.CellFormula = ("RANDBETWEEN($A$1,$B$1)"); Evaluator.ClearAllCachedResultValues(); Evaluator.EvaluateFormulaCell(formulaCell); Assert.AreEqual(1, formulaCell.NumericCellValue, 0); bottomValueCell.SetCellValue(-0.1); topValueCell.SetCellValue(-0.05); formulaCell.CellFormula = ("RANDBETWEEN($A$1,$B$1)"); Evaluator.ClearAllCachedResultValues(); Evaluator.EvaluateFormulaCell(formulaCell); Assert.AreEqual(0, formulaCell.NumericCellValue, 0); bottomValueCell.SetCellValue(-1.1); topValueCell.SetCellValue(-1.05); formulaCell.CellFormula = ("RANDBETWEEN($A$1,$B$1)"); Evaluator.ClearAllCachedResultValues(); Evaluator.EvaluateFormulaCell(formulaCell); Assert.AreEqual(-1, formulaCell.NumericCellValue, 0); bottomValueCell.SetCellValue(-1.1); topValueCell.SetCellValue(-1.1); formulaCell.CellFormula = ("RANDBETWEEN($A$1,$B$1)"); Evaluator.ClearAllCachedResultValues(); Evaluator.EvaluateFormulaCell(formulaCell); Assert.AreEqual(-1, formulaCell.NumericCellValue, 0); } /** * Check top value of BLANK which Excel will Evaluate as 0 */ [Test] public void TestRandBetweenTopBlank() { bottomValueCell.SetCellValue(-1); topValueCell.SetCellType(CellType.Blank); formulaCell.CellFormula = ("RANDBETWEEN($A$1,$B$1)"); Evaluator.ClearAllCachedResultValues(); Evaluator.EvaluateFormulaCell(formulaCell); Assert.IsTrue(formulaCell.NumericCellValue == 0 || formulaCell.NumericCellValue == -1); } /** * Check where input values are of wrong type */ [Test] public void TestRandBetweenWrongInputTypes() { // Check case where bottom input is of the wrong type bottomValueCell.SetCellValue("STRING"); topValueCell.SetCellValue(1); formulaCell.CellFormula = ("RANDBETWEEN($A$1,$B$1)"); Evaluator.ClearAllCachedResultValues(); Evaluator.EvaluateFormulaCell(formulaCell); Assert.AreEqual(CellType.Error, formulaCell.CachedFormulaResultType); Assert.AreEqual(ErrorEval.VALUE_INVALID.ErrorCode, formulaCell.ErrorCellValue); // Check case where top input is of the wrong type bottomValueCell.SetCellValue(1); topValueCell.SetCellValue("STRING"); formulaCell.CellFormula = ("RANDBETWEEN($A$1,$B$1)"); Evaluator.ClearAllCachedResultValues(); Evaluator.EvaluateFormulaCell(formulaCell); Assert.AreEqual(CellType.Error, formulaCell.CachedFormulaResultType); Assert.AreEqual(ErrorEval.VALUE_INVALID.ErrorCode, formulaCell.ErrorCellValue); // Check case where both inputs are of wrong type bottomValueCell.SetCellValue("STRING"); topValueCell.SetCellValue("STRING"); formulaCell.CellFormula = ("RANDBETWEEN($A$1,$B$1)"); Evaluator.ClearAllCachedResultValues(); Evaluator.EvaluateFormulaCell(formulaCell); Assert.AreEqual(CellType.Error, formulaCell.CachedFormulaResultType); Assert.AreEqual(ErrorEval.VALUE_INVALID.ErrorCode, formulaCell.ErrorCellValue); } /** * Check case where bottom is greater than top */ [Test] public void TestRandBetweenBottomGreaterThanTop() { // Check case where bottom is greater than top bottomValueCell.SetCellValue(1); topValueCell.SetCellValue(0); formulaCell.CellFormula = ("RANDBETWEEN($A$1,$B$1)"); Evaluator.ClearAllCachedResultValues(); Evaluator.EvaluateFormulaCell(formulaCell); Assert.AreEqual(CellType.Error, formulaCell.CachedFormulaResultType); Assert.AreEqual(ErrorEval.NUM_ERROR.ErrorCode, formulaCell.ErrorCellValue); bottomValueCell.SetCellValue(1); topValueCell.SetCellType(CellType.Blank); formulaCell.CellFormula = ("RANDBETWEEN($A$1,$B$1)"); Evaluator.ClearAllCachedResultValues(); Evaluator.EvaluateFormulaCell(formulaCell); Assert.AreEqual(CellType.Error, formulaCell.CachedFormulaResultType); Assert.AreEqual(ErrorEval.NUM_ERROR.ErrorCode, formulaCell.ErrorCellValue); } /** * Boundary check of Double MIN and MAX values */ [Test] public void TestRandBetweenBoundaryCheck() { bottomValueCell.SetCellValue(Double.MinValue); topValueCell.SetCellValue(Double.MaxValue); formulaCell.CellFormula = ("RANDBETWEEN($A$1,$B$1)"); Evaluator.ClearAllCachedResultValues(); Evaluator.EvaluateFormulaCell(formulaCell); Assert.IsTrue(formulaCell.NumericCellValue >= Double.MinValue && formulaCell.NumericCellValue <= Double.MaxValue); } } }
/* /* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ using System; using Antlr4.Runtime.Dfa; using Antlr4.Runtime.Misc; namespace Antlr4.Runtime.Atn { /// <summary>"dup" of ParserInterpreter</summary> public class LexerATNSimulator : ATNSimulator { #if !PORTABLE public readonly bool debug = false; public readonly bool dfa_debug = false; #endif public static readonly int MIN_DFA_EDGE = 0; public static readonly int MAX_DFA_EDGE = 127; // forces unicode to stay in ATN protected readonly Lexer recog; /** The current token's starting index into the character stream. * Shared across DFA to ATN simulation in case the ATN fails and the * DFA did not have a previous accept state. In this case, we use the * ATN-generated exception object. */ protected int startIndex = -1; /** line number 1..n within the input */ protected int thisLine = 1; /** The index of the character relative to the beginning of the line 0..n-1 */ protected int charPositionInLine = 0; public readonly DFA[] decisionToDFA; protected int mode = Lexer.DEFAULT_MODE; /** Used during DFA/ATN exec to record the most recent accept configuration info */ readonly SimState prevAccept = new SimState(); public static int match_calls = 0; public LexerATNSimulator(ATN atn, DFA[] decisionToDFA, PredictionContextCache sharedContextCache) : this(null, atn, decisionToDFA, sharedContextCache) { } public LexerATNSimulator(Lexer recog, ATN atn, DFA[] decisionToDFA, PredictionContextCache sharedContextCache) : base(atn, sharedContextCache) { this.decisionToDFA = decisionToDFA; this.recog = recog; } public void CopyState(LexerATNSimulator simulator) { this.charPositionInLine = simulator.charPositionInLine; this.thisLine = simulator.thisLine; this.mode = simulator.mode; this.startIndex = simulator.startIndex; } public int Match(ICharStream input, int mode) { match_calls++; this.mode = mode; int mark = input.Mark(); try { this.startIndex = input.Index; this.prevAccept.Reset(); DFA dfa = decisionToDFA[mode]; if (dfa.s0 == null) { return MatchATN(input); } else { return ExecATN(input, dfa.s0); } } finally { input.Release(mark); } } public override void Reset() { prevAccept.Reset(); startIndex = -1; thisLine = 1; charPositionInLine = 0; mode = Lexer.DEFAULT_MODE; } public override void ClearDFA() { for (int d = 0; d < decisionToDFA.Length; d++) { decisionToDFA[d] = new DFA(atn.GetDecisionState(d), d); } } protected int MatchATN(ICharStream input) { ATNState startState = atn.modeToStartState[mode]; if (debug) { Console.WriteLine("matchATN mode " + mode + " start: " + startState); } int old_mode = mode; ATNConfigSet s0_closure = ComputeStartState(input, startState); bool suppressEdge = s0_closure.hasSemanticContext; s0_closure.hasSemanticContext = false; DFAState next = AddDFAState(s0_closure); if (!suppressEdge) { decisionToDFA[mode].s0 = next; } int predict = ExecATN(input, next); if (debug) { Console.WriteLine("DFA after matchATN: " + decisionToDFA[old_mode].ToString()); } return predict; } protected int ExecATN(ICharStream input, DFAState ds0) { //System.out.println("enter exec index "+input.index()+" from "+ds0.configs); if (debug) { Console.WriteLine("start state closure=" + ds0.configSet); } if (ds0.isAcceptState) { // allow zero-length tokens CaptureSimState(prevAccept, input, ds0); } int t = input.LA(1); DFAState s = ds0; // s is current/from DFA state while (true) { // while more work if (debug) { Console.WriteLine("execATN loop starting closure: " + s.configSet); } // As we move src->trg, src->trg, we keep track of the previous trg to // avoid looking up the DFA state again, which is expensive. // If the previous target was already part of the DFA, we might // be able to avoid doing a reach operation upon t. If s!=null, // it means that semantic predicates didn't prevent us from // creating a DFA state. Once we know s!=null, we check to see if // the DFA state has an edge already for t. If so, we can just reuse // it's configuration set; there's no point in re-computing it. // This is kind of like doing DFA simulation within the ATN // simulation because DFA simulation is really just a way to avoid // computing reach/closure sets. Technically, once we know that // we have a previously added DFA state, we could jump over to // the DFA simulator. But, that would mean popping back and forth // a lot and making things more complicated algorithmically. // This optimization makes a lot of sense for loops within DFA. // A character will take us back to an existing DFA state // that already has lots of edges out of it. e.g., .* in comments. DFAState target = GetExistingTargetState(s, t); if (target == null) { target = ComputeTargetState(input, s, t); } if (target == ERROR) { break; } // If this is a consumable input element, make sure to consume before // capturing the accept state so the input index, line, and char // position accurately reflect the state of the interpreter at the // end of the token. if (t != IntStreamConstants.EOF) { Consume(input); } if (target.isAcceptState) { CaptureSimState(prevAccept, input, target); if (t == IntStreamConstants.EOF) { break; } } t = input.LA(1); s = target; // flip; current DFA target becomes new src/from state } return FailOrAccept(prevAccept, input, s.configSet, t); } /** * Get an existing target state for an edge in the DFA. If the target state * for the edge has not yet been computed or is otherwise not available, * this method returns {@code null}. * * @param s The current DFA state * @param t The next input symbol * @return The existing target DFA state for the given input symbol * {@code t}, or {@code null} if the target state for this edge is not * already cached */ protected DFAState GetExistingTargetState(DFAState s, int t) { if (s.edges == null || t < MIN_DFA_EDGE || t > MAX_DFA_EDGE) { return null; } DFAState target = s.edges[t - MIN_DFA_EDGE]; if (debug && target != null) { Console.WriteLine("reuse state " + s.stateNumber + " edge to " + target.stateNumber); } return target; } /** * Compute a target state for an edge in the DFA, and attempt to add the * computed state and corresponding edge to the DFA. * * @param input The input stream * @param s The current DFA state * @param t The next input symbol * * @return The computed target DFA state for the given input symbol * {@code t}. If {@code t} does not lead to a valid DFA state, this method * returns {@link #ERROR}. */ protected DFAState ComputeTargetState(ICharStream input, DFAState s, int t) { ATNConfigSet reach = new OrderedATNConfigSet(); // if we don't find an existing DFA state // Fill reach starting from closure, following t transitions GetReachableConfigSet(input, s.configSet, reach, t); if (reach.Empty) { // we got nowhere on t from s if (!reach.hasSemanticContext) { // we got nowhere on t, don't throw out this knowledge; it'd // cause a failover from DFA later. AddDFAEdge(s, t, ERROR); } // stop when we can't match any more char return ERROR; } // Add an edge from s to target DFA found/created for reach return AddDFAEdge(s, t, reach); } protected int FailOrAccept(SimState prevAccept, ICharStream input, ATNConfigSet reach, int t) { if (prevAccept.dfaState != null) { LexerActionExecutor lexerActionExecutor = prevAccept.dfaState.lexerActionExecutor; Accept(input, lexerActionExecutor, startIndex, prevAccept.index, prevAccept.line, prevAccept.charPos); return prevAccept.dfaState.prediction; } else { // if no accept and EOF is first char, return EOF if (t == IntStreamConstants.EOF && input.Index == startIndex) { return TokenConstants.EOF; } throw new LexerNoViableAltException(recog, input, startIndex, reach); } } /** Given a starting configuration set, figure out all ATN configurations * we can reach upon input {@code t}. Parameter {@code reach} is a return * parameter. */ protected void GetReachableConfigSet(ICharStream input, ATNConfigSet closure, ATNConfigSet reach, int t) { // this is used to skip processing for configs which have a lower priority // than a config that already reached an accept state for the same rule int skipAlt = ATN.INVALID_ALT_NUMBER; foreach (ATNConfig c in closure.configs) { bool currentAltReachedAcceptState = c.alt == skipAlt; if (currentAltReachedAcceptState && ((LexerATNConfig)c).hasPassedThroughNonGreedyDecision()) { continue; } if (debug) { Console.WriteLine("testing " + GetTokenName(t) + " at " + c.ToString(recog, true)); } int n = c.state.NumberOfTransitions; for (int ti = 0; ti < n; ti++) { // for each transition Transition trans = c.state.Transition(ti); ATNState target = GetReachableTarget(trans, t); if (target != null) { LexerActionExecutor lexerActionExecutor = ((LexerATNConfig)c).getLexerActionExecutor(); if (lexerActionExecutor != null) { lexerActionExecutor = lexerActionExecutor.FixOffsetBeforeMatch(input.Index - startIndex); } bool treatEofAsEpsilon = t == IntStreamConstants.EOF; if (Closure(input, new LexerATNConfig((LexerATNConfig)c, target, lexerActionExecutor), reach, currentAltReachedAcceptState, true, treatEofAsEpsilon)) { // any remaining configs for this alt have a lower priority than // the one that just reached an accept state. skipAlt = c.alt; break; } } } } } protected void Accept(ICharStream input, LexerActionExecutor lexerActionExecutor, int startIndex, int index, int line, int charPos) { if (debug) { Console.WriteLine("ACTION " + lexerActionExecutor); } // seek to after last char in token input.Seek(index); this.thisLine = line; this.charPositionInLine = charPos; if (lexerActionExecutor != null && recog != null) { lexerActionExecutor.Execute(recog, input, startIndex); } } protected ATNState GetReachableTarget(Transition trans, int t) { if (trans.Matches(t, char.MinValue, char.MaxValue)) { return trans.target; } return null; } protected ATNConfigSet ComputeStartState(ICharStream input, ATNState p) { PredictionContext initialContext = PredictionContext.EMPTY; ATNConfigSet configs = new OrderedATNConfigSet(); for (int i = 0; i < p.NumberOfTransitions; i++) { ATNState target = p.Transition(i).target; LexerATNConfig c = new LexerATNConfig(target, i + 1, initialContext); Closure(input, c, configs, false, false, false); } return configs; } /** * Since the alternatives within any lexer decision are ordered by * preference, this method stops pursuing the closure as soon as an accept * state is reached. After the first accept state is reached by depth-first * search from {@code config}, all other (potentially reachable) states for * this rule would have a lower priority. * * @return {@code true} if an accept state is reached, otherwise * {@code false}. */ protected bool Closure(ICharStream input, LexerATNConfig config, ATNConfigSet configs, bool currentAltReachedAcceptState, bool speculative, bool treatEofAsEpsilon) { if (debug) { Console.WriteLine("closure(" + config.ToString(recog, true) + ")"); } if (config.state is RuleStopState) { if (debug) { if (recog != null) { Console.WriteLine("closure at " + recog.RuleNames[config.state.ruleIndex] + " rule stop " + config); } else { Console.WriteLine("closure at rule stop " + config); } } if (config.context == null || config.context.HasEmptyPath) { if (config.context == null || config.context.IsEmpty) { configs.Add(config); return true; } else { configs.Add(new LexerATNConfig(config, config.state, PredictionContext.EMPTY)); currentAltReachedAcceptState = true; } } if (config.context != null && !config.context.IsEmpty) { for (int i = 0; i < config.context.Size; i++) { if (config.context.GetReturnState(i) != PredictionContext.EMPTY_RETURN_STATE) { PredictionContext newContext = config.context.GetParent(i); // "pop" return state ATNState returnState = atn.states[config.context.GetReturnState(i)]; LexerATNConfig c = new LexerATNConfig(config, returnState, newContext); currentAltReachedAcceptState = Closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon); } } } return currentAltReachedAcceptState; } // optimization if (!config.state.OnlyHasEpsilonTransitions) { if (!currentAltReachedAcceptState || !config.hasPassedThroughNonGreedyDecision()) { configs.Add(config); } } ATNState p = config.state; for (int i = 0; i < p.NumberOfTransitions; i++) { Transition t = p.Transition(i); LexerATNConfig c = GetEpsilonTarget(input, config, t, configs, speculative, treatEofAsEpsilon); if (c != null) { currentAltReachedAcceptState = Closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon); } } return currentAltReachedAcceptState; } // side-effect: can alter configs.hasSemanticContext protected LexerATNConfig GetEpsilonTarget(ICharStream input, LexerATNConfig config, Transition t, ATNConfigSet configs, bool speculative, bool treatEofAsEpsilon) { LexerATNConfig c = null; switch (t.TransitionType) { case TransitionType.RULE: RuleTransition ruleTransition = (RuleTransition)t; PredictionContext newContext = new SingletonPredictionContext(config.context, ruleTransition.followState.stateNumber); c = new LexerATNConfig(config, t.target, newContext); break; case TransitionType.PRECEDENCE: throw new Exception("Precedence predicates are not supported in lexers."); case TransitionType.PREDICATE: /* Track traversing semantic predicates. If we traverse, we cannot add a DFA state for this "reach" computation because the DFA would not test the predicate again in the future. Rather than creating collections of semantic predicates like v3 and testing them on prediction, v4 will test them on the fly all the time using the ATN not the DFA. This is slower but semantically it's not used that often. One of the key elements to this predicate mechanism is not adding DFA states that see predicates immediately afterwards in the ATN. For example, a : ID {p1}? | ID {p2}? ; should create the start state for rule 'a' (to save start state competition), but should not create target of ID state. The collection of ATN states the following ID references includes states reached by traversing predicates. Since this is when we test them, we cannot cash the DFA state target of ID. */ PredicateTransition pt = (PredicateTransition)t; if (debug) { Console.WriteLine("EVAL rule " + pt.ruleIndex + ":" + pt.predIndex); } configs.hasSemanticContext = true; if (EvaluatePredicate(input, pt.ruleIndex, pt.predIndex, speculative)) { c = new LexerATNConfig(config, t.target); } break; case TransitionType.ACTION: if (config.context == null || config.context.HasEmptyPath) { // execute actions anywhere in the start rule for a token. // // TODO: if the entry rule is invoked recursively, some // actions may be executed during the recursive call. The // problem can appear when hasEmptyPath() is true but // isEmpty() is false. In this case, the config needs to be // split into two contexts - one with just the empty path // and another with everything but the empty path. // Unfortunately, the current algorithm does not allow // getEpsilonTarget to return two configurations, so // additional modifications are needed before we can support // the split operation. LexerActionExecutor lexerActionExecutor = LexerActionExecutor.Append(config.getLexerActionExecutor(), atn.lexerActions[((ActionTransition)t).actionIndex]); c = new LexerATNConfig(config, t.target, lexerActionExecutor); break; } else { // ignore actions in referenced rules c = new LexerATNConfig(config, t.target); break; } case TransitionType.EPSILON: c = new LexerATNConfig(config, t.target); break; case TransitionType.ATOM: case TransitionType.RANGE: case TransitionType.SET: if (treatEofAsEpsilon) { if (t.Matches(IntStreamConstants.EOF, char.MinValue, char.MaxValue)) { c = new LexerATNConfig(config, t.target); break; } } break; } return c; } /** * Evaluate a predicate specified in the lexer. * * <p>If {@code speculative} is {@code true}, this method was called before * {@link #consume} for the matched character. This method should call * {@link #consume} before evaluating the predicate to ensure position * sensitive values, including {@link Lexer#getText}, {@link Lexer#getLine}, * and {@link Lexer#getCharPositionInLine}, properly reflect the current * lexer state. This method should restore {@code input} and the simulator * to the original state before returning (i.e. undo the actions made by the * call to {@link #consume}.</p> * * @param input The input stream. * @param ruleIndex The rule containing the predicate. * @param predIndex The index of the predicate within the rule. * @param speculative {@code true} if the current index in {@code input} is * one character before the predicate's location. * * @return {@code true} if the specified predicate evaluates to * {@code true}. */ protected bool EvaluatePredicate(ICharStream input, int ruleIndex, int predIndex, bool speculative) { // assume true if no recognizer was provided if (recog == null) { return true; } if (!speculative) { return recog.Sempred(null, ruleIndex, predIndex); } int savedCharPositionInLine = charPositionInLine; int savedLine = thisLine; int index = input.Index; int marker = input.Mark(); try { Consume(input); return recog.Sempred(null, ruleIndex, predIndex); } finally { charPositionInLine = savedCharPositionInLine; thisLine = savedLine; input.Seek(index); input.Release(marker); } } protected void CaptureSimState(SimState settings, ICharStream input, DFAState dfaState) { settings.index = input.Index; settings.line = thisLine; settings.charPos = charPositionInLine; settings.dfaState = dfaState; } protected DFAState AddDFAEdge(DFAState from, int t, ATNConfigSet q) { /* leading to this call, ATNConfigSet.hasSemanticContext is used as a * marker indicating dynamic predicate evaluation makes this edge * dependent on the specific input sequence, so the static edge in the * DFA should be omitted. The target DFAState is still created since * execATN has the ability to resynchronize with the DFA state cache * following the predicate evaluation step. * * TJP notes: next time through the DFA, we see a pred again and eval. * If that gets us to a previously created (but dangling) DFA * state, we can continue in pure DFA mode from there. */ bool suppressEdge = q.hasSemanticContext; q.hasSemanticContext = false; DFAState to = AddDFAState(q); if (suppressEdge) { return to; } AddDFAEdge(from, t, to); return to; } protected void AddDFAEdge(DFAState p, int t, DFAState q) { if (t < MIN_DFA_EDGE || t > MAX_DFA_EDGE) { // Only track edges within the DFA bounds return; } if (debug) { Console.WriteLine("EDGE " + p + " -> " + q + " upon " + ((char)t)); } lock (p) { if (p.edges == null) { // make room for tokens 1..n and -1 masquerading as index 0 p.edges = new DFAState[MAX_DFA_EDGE - MIN_DFA_EDGE + 1]; } p.edges[t - MIN_DFA_EDGE] = q; // connect } } /** Add a new DFA state if there isn't one with this set of configurations already. This method also detects the first configuration containing an ATN rule stop state. Later, when traversing the DFA, we will know which rule to accept. */ protected DFAState AddDFAState(ATNConfigSet configSet) { /* the lexer evaluates predicates on-the-fly; by this point configs * should not contain any configurations with unevaluated predicates. */ DFAState proposed = new DFAState(configSet); ATNConfig firstConfigWithRuleStopState = null; foreach (ATNConfig c in configSet.configs) { if (c.state is RuleStopState) { firstConfigWithRuleStopState = c; break; } } if (firstConfigWithRuleStopState != null) { proposed.isAcceptState = true; proposed.lexerActionExecutor = ((LexerATNConfig)firstConfigWithRuleStopState).getLexerActionExecutor(); proposed.prediction = atn.ruleToTokenType[firstConfigWithRuleStopState.state.ruleIndex]; } DFA dfa = decisionToDFA[mode]; lock (dfa.states) { DFAState existing; if(dfa.states.TryGetValue(proposed, out existing)) return existing; DFAState newState = proposed; newState.stateNumber = dfa.states.Count; configSet.IsReadOnly = true; newState.configSet = configSet; dfa.states[newState] = newState; return newState; } } public DFA GetDFA(int mode) { return decisionToDFA[mode]; } /** Get the text matched so far for the current token. */ public String GetText(ICharStream input) { // index is first lookahead char, don't include. return input.GetText(Interval.Of(startIndex, input.Index - 1)); } public int Line { get { return thisLine; } set { this.thisLine = value; } } public int Column { get { return charPositionInLine; } set { this.charPositionInLine = value; } } public void Consume(ICharStream input) { int curChar = input.LA(1); if (curChar == '\n') { thisLine++; charPositionInLine = 0; } else { charPositionInLine++; } input.Consume(); } public String GetTokenName(int t) { if (t == -1) return "EOF"; //if ( atn.g!=null ) return atn.g.getTokenDisplayName(t); return "'" + (char)t + "'"; } } /** When we hit an accept state in either the DFA or the ATN, we * have to notify the character stream to start buffering characters * via {@link IntStream#mark} and record the current state. The current sim state * includes the current index into the input, the current line, * and current character position in that line. Note that the Lexer is * tracking the starting line and characterization of the token. These * variables track the "state" of the simulator when it hits an accept state. * * <p>We track these variables separately for the DFA and ATN simulation * because the DFA simulation often has to fail over to the ATN * simulation. If the ATN simulation fails, we need the DFA to fall * back to its previously accepted state, if any. If the ATN succeeds, * then the ATN does the accept and the DFA simulator that invoked it * can simply return the predicted token type.</p> */ public class SimState { public int index = -1; public int line = 0; public int charPos = -1; public DFAState dfaState; public void Reset() { index = -1; line = 0; charPos = -1; dfaState = null; } } }
// 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.Threading; namespace System.Net { // This is used by ContextAwareResult to cache callback closures between similar calls. Create one of these and // pass it in to FinishPostingAsyncOp() to prevent the context from being captured in every iteration of a looped async call. // // It was decided not to make the delegate and state into weak references because: // - The delegate is very likely to be abandoned by the user right after calling BeginXxx, making caching it useless. There's // no easy way to weakly reference just the target. // - We want to support identifying state via object.Equals() (especially value types), which means we need to keep a // reference to the original. Plus, if we're holding the target, might as well hold the state too. // The user will need to disable caching if they want their target/state to be instantly collected. // // For now the state is not included as part of the closure. It is too common a pattern (for example with socket receive) // to have several pending IOs differentiated by their state object. We don't want that pattern to break the cache. internal class CallbackClosure { private AsyncCallback _savedCallback; private ExecutionContext _savedContext; internal CallbackClosure(ExecutionContext context, AsyncCallback callback) { if (callback != null) { _savedCallback = callback; _savedContext = context; } } internal bool IsCompatible(AsyncCallback callback) { if (callback == null || _savedCallback == null) { return false; } // Delegates handle this ok. AsyncCallback is sealed and immutable, so if this succeeds, we are safe to use // the passed-in instance. if (!object.Equals(_savedCallback, callback)) { return false; } return true; } internal AsyncCallback AsyncCallback { get { return _savedCallback; } } internal ExecutionContext Context { get { return _savedContext; } } } // This class will ensure that the correct context is restored on the thread before invoking // a user callback. internal partial class ContextAwareResult : LazyAsyncResult { [Flags] private enum StateFlags : byte { None = 0x00, CaptureIdentity = 0x01, CaptureContext = 0x02, ThreadSafeContextCopy = 0x04, PostBlockStarted = 0x08, PostBlockFinished = 0x10, } // This needs to be volatile so it's sure to make it over to the completion thread in time. private volatile ExecutionContext _context; private object _lock; private StateFlags _flags; internal ContextAwareResult(object myObject, object myState, AsyncCallback myCallBack) : this(false, false, myObject, myState, myCallBack) { } // Setting captureIdentity enables the Identity property. This will be available even if ContextCopy isn't, either because // flow is suppressed or it wasn't needed. (If ContextCopy isn't available, Identity may or may not be. But if it is, it // should be used instead of ContextCopy for impersonation - ContextCopy might not include the identity.) // // Setting forceCaptureContext enables the ContextCopy property even when a null callback is specified. (The context is // always captured if a callback is given.) internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, object myObject, object myState, AsyncCallback myCallBack) : this(captureIdentity, forceCaptureContext, false, myObject, myState, myCallBack) { } internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, bool threadSafeContextCopy, object myObject, object myState, AsyncCallback myCallBack) : base(myObject, myState, myCallBack) { if (forceCaptureContext) { _flags = StateFlags.CaptureContext; } if (captureIdentity) { _flags |= StateFlags.CaptureIdentity; } if (threadSafeContextCopy) { _flags |= StateFlags.ThreadSafeContextCopy; } } // This can be used to establish a context during an async op for something like calling a delegate or demanding a permission. // May block briefly if the context is still being produced. // // Returns null if called from the posting thread. internal ExecutionContext ContextCopy { get { if (InternalPeekCompleted) { if ((_flags & StateFlags.ThreadSafeContextCopy) == 0) { NetEventSource.Fail(this, "Called on completed result."); } throw new InvalidOperationException(SR.net_completed_result); } ExecutionContext context = _context; if (context != null) { return context; // No need to copy on CoreCLR; ExecutionContext is immutable } // Make sure the context was requested. if (AsyncCallback == null && (_flags & StateFlags.CaptureContext) == 0) { NetEventSource.Fail(this, "No context captured - specify a callback or forceCaptureContext."); } // Just use the lock to block. We might be on the thread that owns the lock which is great, it means we // don't need a context anyway. if ((_flags & StateFlags.PostBlockFinished) == 0) { if (_lock == null) { NetEventSource.Fail(this, "Must lock (StartPostingAsyncOp()) { ... FinishPostingAsyncOp(); } when calling ContextCopy (unless it's only called after FinishPostingAsyncOp)."); } lock (_lock) { } } if (InternalPeekCompleted) { if ((_flags & StateFlags.ThreadSafeContextCopy) == 0) { NetEventSource.Fail(this, "Result became completed during call."); } throw new InvalidOperationException(SR.net_completed_result); } return _context; // No need to copy on CoreCLR; ExecutionContext is immutable } } #if DEBUG // Want to be able to verify that the Identity was requested. If it was requested but isn't available // on the Identity property, it's either available via ContextCopy or wasn't needed (synchronous). internal bool IdentityRequested { get { return (_flags & StateFlags.CaptureIdentity) != 0; } } #endif internal object StartPostingAsyncOp() { return StartPostingAsyncOp(true); } // If ContextCopy or Identity will be used, the return value should be locked until FinishPostingAsyncOp() is called // or the operation has been aborted (e.g. by BeginXxx throwing). Otherwise, this can be called with false to prevent the lock // object from being created. internal object StartPostingAsyncOp(bool lockCapture) { if (InternalPeekCompleted) { NetEventSource.Fail(this, "Called on completed result."); } DebugProtectState(true); _lock = lockCapture ? new object() : null; _flags |= StateFlags.PostBlockStarted; return _lock; } // Call this when returning control to the user. internal bool FinishPostingAsyncOp() { // Ignore this call if StartPostingAsyncOp() failed or wasn't called, or this has already been called. if ((_flags & (StateFlags.PostBlockStarted | StateFlags.PostBlockFinished)) != StateFlags.PostBlockStarted) { return false; } _flags |= StateFlags.PostBlockFinished; ExecutionContext cachedContext = null; return CaptureOrComplete(ref cachedContext, false); } // Call this when returning control to the user. Allows a cached Callback Closure to be supplied and used // as appropriate, and replaced with a new one. internal bool FinishPostingAsyncOp(ref CallbackClosure closure) { // Ignore this call if StartPostingAsyncOp() failed or wasn't called, or this has already been called. if ((_flags & (StateFlags.PostBlockStarted | StateFlags.PostBlockFinished)) != StateFlags.PostBlockStarted) { return false; } _flags |= StateFlags.PostBlockFinished; // Need a copy of this ref argument since it can be used in many of these calls simultaneously. CallbackClosure closureCopy = closure; ExecutionContext cachedContext; if (closureCopy == null) { cachedContext = null; } else { if (!closureCopy.IsCompatible(AsyncCallback)) { // Clear the cache as soon as a method is called with incompatible parameters. closure = null; cachedContext = null; } else { // If it succeeded, we want to replace our context/callback with the one from the closure. // Using the closure's instance of the callback is probably overkill, but safer. AsyncCallback = closureCopy.AsyncCallback; cachedContext = closureCopy.Context; } } bool calledCallback = CaptureOrComplete(ref cachedContext, true); // Set up new cached context if we didn't use the previous one. if (closure == null && AsyncCallback != null && cachedContext != null) { closure = new CallbackClosure(cachedContext, AsyncCallback); } return calledCallback; } protected override void Cleanup() { base.Cleanup(); if (NetEventSource.IsEnabled) NetEventSource.Info(this); CleanupInternal(); } // This must be called right before returning the result to the user. It might call the callback itself, // to avoid flowing context. Even if the operation completes before this call, the callback won't have been // called. // // Returns whether the operation completed sync or not. private bool CaptureOrComplete(ref ExecutionContext cachedContext, bool returnContext) { if ((_flags & StateFlags.PostBlockStarted) == 0) { NetEventSource.Fail(this, "Called without calling StartPostingAsyncOp."); } // See if we're going to need to capture the context. bool capturingContext = AsyncCallback != null || (_flags & StateFlags.CaptureContext) != 0; // Peek if we've already completed, but don't fix CompletedSynchronously yet // Capture the identity if requested, unless we're going to capture the context anyway, unless // capturing the context won't be sufficient. if ((_flags & StateFlags.CaptureIdentity) != 0 && !InternalPeekCompleted && (!capturingContext)) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "starting identity capture"); SafeCaptureIdentity(); } // No need to flow if there's no callback, unless it's been specifically requested. // Note that Capture() can return null, for example if SuppressFlow() is in effect. if (capturingContext && !InternalPeekCompleted) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "starting capture"); if (cachedContext == null) { cachedContext = ExecutionContext.Capture(); } if (cachedContext != null) { if (!returnContext) { _context = cachedContext; cachedContext = null; } else { _context = cachedContext; } } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_context:{_context}"); } else { // Otherwise we have to have completed synchronously, or not needed the context. if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Skipping capture"); cachedContext = null; if (AsyncCallback != null && !CompletedSynchronously) { NetEventSource.Fail(this, "Didn't capture context, but didn't complete synchronously!"); } } // Now we want to see for sure what to do. We might have just captured the context for no reason. // This has to be the first time the state has been queried "for real" (apart from InvokeCallback) // to guarantee synchronization with Complete() (otherwise, Complete() could try to call the // callback without the context having been gotten). DebugProtectState(false); if (CompletedSynchronously) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Completing synchronously"); base.Complete(IntPtr.Zero); return true; } return false; } // This method is guaranteed to be called only once. If called with a non-zero userToken, the context is not flowed. protected override void Complete(IntPtr userToken) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_context(set):{_context != null} userToken:{userToken}"); // If no flowing, just complete regularly. if ((_flags & StateFlags.PostBlockStarted) == 0) { base.Complete(userToken); return; } // At this point, IsCompleted is set and CompletedSynchronously is fixed. If it's synchronous, then we want to hold // the completion for the CaptureOrComplete() call to avoid the context flow. If not, we know CaptureOrComplete() has completed. if (CompletedSynchronously) { return; } ExecutionContext context = _context; // If the context is being abandoned or wasn't captured (SuppressFlow, null AsyncCallback), just // complete regularly, as long as CaptureOrComplete() has finished. // if (userToken != IntPtr.Zero || context == null) { base.Complete(userToken); return; } ExecutionContext.Run(context, s => ((ContextAwareResult)s).CompleteCallback(), this); } private void CompleteCallback() { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Context set, calling callback."); base.Complete(IntPtr.Zero); } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ // -------------------------------------------------------------------------------------------------------------------- // <copyright file="ChatAuthController.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Site.Areas.Chat.Controllers { using System; using System.Collections.Generic; using System.IdentityModel.Tokens; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Security.Claims; using System.Security.Cryptography; using System.Text; using System.Web.Mvc; using Adxstudio.Xrm; using Adxstudio.Xrm.Configuration; using Microsoft.Xrm.Portal.Configuration; using Microsoft.Xrm.Sdk; using Models; using Models.LivePerson; using Newtonsoft.Json; using Org.BouncyCastle.OpenSsl; /// <summary> /// The chat auth controller. /// </summary> public class ChatAuthController : Controller { /// <summary> /// Retrieve Portal Public Key /// </summary> /// <returns>Encoded public key</returns> [HttpGet] [AllowAnonymous] public ActionResult PublicKey() { using (var cryptoServiceProvider = ChatAuthController.GetCryptoProvider(false)) { var stringWriter = new StringWriter(); ChatAuthController.ExportPublicKey(cryptoServiceProvider, stringWriter); return this.Content(stringWriter.ToString(), "text/plain"); } } /// <summary> /// Return JWT Auth token for current user to provide authenticated data to Chat /// </summary> /// <returns>JWT Auth token for current user</returns> [HttpGet] public ActionResult Token() { IList<Claim> claims; if (this.HttpContext.User.Identity.IsAuthenticated) { claims = this.GetUserClaims(); } else { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "User not logged in"); return new HttpStatusCodeResult(HttpStatusCode.Unauthorized); } var tokenString = GetTokenString(claims); return this.Content(tokenString, "application/jwt"); } /// <summary> /// Endpoint for 3rd-party chat provider to use to get JWT auth token. May require user to login. /// </summary> /// <param name="response_type">sresponse type</param> /// <param name="client_id">client id</param> /// <param name="redirect_uri">redirect uri</param> /// <param name="scope">OAuth scope</param> /// <param name="state">OAuth state</param> /// <param name="nonce">nonce value</param> /// <returns>redirect with JWT</returns> [AllowAnonymous] public ActionResult Authorize(string response_type, string client_id, string redirect_uri, string scope, string state, string nonce) { if (string.IsNullOrEmpty(response_type) || response_type.Split(' ') .All(s => string.Compare("token", s, StringComparison.InvariantCultureIgnoreCase) != 0)) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } if (this.HttpContext.User.Identity.IsAuthenticated) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Authenticated User, returning token"); var claims = this.GetUserClaims(); if (!string.IsNullOrEmpty(nonce)) { claims.Add(new Claim("nonce", nonce)); } var token = GetTokenString(claims); var url = new UriBuilder(redirect_uri); var qs = !string.IsNullOrEmpty(url.Query) && url.Query.Length > 1 ? url.Query.Substring(1) + "&" : string.Empty; qs += "token=" + token; // token is already encoded url.Query = qs; return this.Redirect(url.ToString()); } else { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Unauthenticated User, triggering authentication"); var urlState = EncodeState(Request.Url.AbsoluteUri); var url = Url.Action("AuthForce", new { state = urlState }); return this.Redirect(url); } } /// <summary> /// Force authentication and redirect based on compressed url in state /// </summary> /// <param name="state">compressed url</param> /// <returns>redirect to token generator</returns> public ActionResult AuthForce(string state) { if (this.HttpContext.User.Identity.IsAuthenticated) { if (!string.IsNullOrEmpty(state)) { var returnUrl = DecodeState(state); return this.Redirect(returnUrl); } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } else { return new HttpStatusCodeResult(HttpStatusCode.Unauthorized); } } /// <summary> /// Compress and encode string for url /// </summary> /// <param name="state">string to encode</param> /// <returns>encoded string</returns> private static string EncodeState(string state) { var bytes = Encoding.UTF8.GetBytes(state); using (var input = new MemoryStream(bytes)) using (var output = new MemoryStream()) { using (var zip = new GZipStream(output, CompressionMode.Compress)) { input.CopyTo(zip); } return Base64UrlEncoder.Encode(output.ToArray()); } } /// <summary> /// Decompress and decode string from url /// </summary> /// <param name="encodedState">encoded string</param> /// <returns>decoded string</returns> private static string DecodeState(string encodedState) { var bytes = Base64UrlEncoder.DecodeBytes(encodedState); using (var input = new MemoryStream(bytes)) using (var output = new MemoryStream()) { using (var zip = new GZipStream(input, CompressionMode.Decompress)) { zip.CopyTo(output); } return Encoding.UTF8.GetString(output.ToArray()); } } /// <summary> /// Export a public key in PEM format /// </summary> /// <param name="csp">Crypto Service Provider with key to export</param> /// <param name="outputStream">output stream to write key to</param> private static void ExportPublicKey(RSACryptoServiceProvider csp, TextWriter outputStream) { var keyParams = csp.ExportParameters(false); var publicKey = Org.BouncyCastle.Security.DotNetUtilities.GetRsaPublicKey(keyParams); PemWriter pemWriter = new PemWriter(outputStream); pemWriter.WriteObject(publicKey); } /// <summary> /// Get a crypto service provider for portal keys /// </summary> /// <param name="includePrivateKey">flag indicating whether to include private key in provider</param> /// <returns>RSACryptoServiceProvider initialized with appropriate keys</returns> private static RSACryptoServiceProvider GetCryptoProvider(bool includePrivateKey) { var cert = PortalSettings.Instance.Certificate.FindCertificates().FirstOrDefault(); if (cert == null) { ADXTrace.Instance.TraceError(TraceCategory.Application, "Unable to find a valid certificate"); throw new CertificateNotFoundException(); } var csp = includePrivateKey ? (RSACryptoServiceProvider)cert.PrivateKey : (RSACryptoServiceProvider)cert.PublicKey.Key; if (includePrivateKey) { // need to move key into enhanced crypto provider without exporting key var rsa256Csp = new RSACryptoServiceProvider().CspKeyContainerInfo; var cspParams = new CspParameters(rsa256Csp.ProviderType, rsa256Csp.ProviderName, csp.CspKeyContainerInfo.KeyContainerName); return new RSACryptoServiceProvider(2048, cspParams) { PersistKeyInCsp = true }; } else { return csp; } } /// <summary> /// Get encoded JWT token for given claims /// </summary> /// <param name="claims">list of claims to include in token</param> /// <returns>string representation of JWT token</returns> private static string GetTokenString(IList<Claim> claims) { string tokenString = null; using (var cryptoServiceProvider = GetCryptoProvider(true)) { string issuer = PortalSettings.Instance.DomainName; string audience = string.Empty; DateTime notBefore = DateTime.Now; DateTime expires = notBefore.AddHours(1); var tokenHandler = new JwtSecurityTokenHandler(); var signingCredentials = new SigningCredentials(new RsaSecurityKey(cryptoServiceProvider), SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); // need to explicitly add "iat" claim DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var iat = Convert.ToInt64((TimeZoneInfo.ConvertTimeToUtc(notBefore) - unixEpoch).TotalSeconds - 1); claims.Add(new Claim("iat", iat.ToString(), ClaimValueTypes.Integer)); var header = new JwtHeader(signingCredentials); var payload = new JwtPayload(issuer, audience, claims, notBefore, expires); // Need to adjust this because Claim class ignores value type payload["iat"] = Convert.ToInt64(payload["iat"]); var jwtToken = new JwtSecurityToken(header, payload); tokenString = tokenHandler.WriteToken(jwtToken); } return tokenString; } /// <summary> /// The details of the customer. /// </summary> /// <returns> /// The <see cref="ChatUserModel"/>. /// </returns> private ChatUserModel GetChatUserData() { var portalContext = PortalCrmConfigurationManager.CreatePortalContext(); if (portalContext.User == null) { ADXTrace.Instance.TraceWarning(TraceCategory.Application, "portalContext.User is null"); return null; } var result = new ChatUserModel { Username = portalContext.User.GetAttributeValue<string>("adx_identity_username"), Id = portalContext.User.GetAttributeValue<Guid>("contactid"), FirstName = portalContext.User.GetAttributeValue<string>("firstname"), LastName = portalContext.User.GetAttributeValue<string>("lastname"), Email = portalContext.User.GetAttributeValue<string>("emailaddress1"), Phone = portalContext.User.GetAttributeValue<string>("telephone1") }; var customerType = portalContext.User.GetAttributeValue<OptionSetValue>("customertypecode"); if (customerType != null) { result.CustomerType = customerType.Value; } else { ADXTrace.Instance.TraceError(TraceCategory.Application, "customertypecode not set"); throw new NullReferenceException("customertypecode"); } return result; } /// <summary> /// Get list of claims /// </summary> /// <returns>list of claims for user</returns> private IList<Claim> GetUserClaims() { var userData = this.GetChatUserData(); IList<Claim> claims = new List<Claim> { new Claim("sub", userData.Id.ToString()), new Claim("preferred_username", userData.Username ?? string.Empty), new Claim("phone_number", userData.Phone ?? string.Empty), new Claim("given_name", userData.FirstName ?? string.Empty), new Claim("family_name", userData.LastName ?? string.Empty), new Claim("email", userData.Email ?? string.Empty) }; var lpSdes = new LivePersonSdesCustomerInfo() { CustomerInfo = new LivePersonCustomerInfo() { Type = "contact", Id = userData.Id.ToString(), Imei = userData.Phone ?? string.Empty, UserName = userData.Username ?? string.Empty } }; var custInfo = JsonConvert.SerializeObject(new object[] { lpSdes }); claims.Add(new Claim("lp_sdes", custInfo, "JSON_ARRAY")); return claims; } } }
// // CollectionIndexer.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Xml; using System.Threading; using System.Collections.Generic; using Hyena; using Banshee.Base; using Banshee.Sources; using Banshee.Library; using Banshee.ServiceStack; using Banshee.Collection; using Banshee.Collection.Database; namespace Banshee.Collection.Indexer { public class CollectionIndexer : ICollectionIndexer, IService, IDBusExportable, IDisposable { private static int instance_count = 0; private CollectionIndexerService service; private List<CachedList<DatabaseTrackInfo>> model_caches = new List<CachedList<DatabaseTrackInfo>> (); private string [] export_fields; private event ActionHandler indexing_finished; event ActionHandler ICollectionIndexer.IndexingFinished { add { indexing_finished += value; } remove { indexing_finished -= value; } } private event SaveToXmlFinishedHandler save_to_xml_finished; event SaveToXmlFinishedHandler ICollectionIndexer.SaveToXmlFinished { add { save_to_xml_finished += value; } remove { save_to_xml_finished -= value; } } public event EventHandler IndexingFinished; internal CollectionIndexer (CollectionIndexerService service) { this.service = service; } public void Dispose () { lock (this) { DisposeModels (); if (service != null) { service.DisposeIndexer (this); } } } private void DisposeModels () { foreach (CachedList<DatabaseTrackInfo> model in model_caches) { model.Dispose (); } model_caches.Clear (); } public void SetExportFields (string [] fields) { lock (this) { export_fields = fields; } } public void Index () { lock (this) { DisposeModels (); foreach (Source source in ServiceManager.SourceManager.Sources) { LibrarySource library = source as LibrarySource; if (library != null && library.Indexable) { model_caches.Add (CachedList<DatabaseTrackInfo>.CreateFromSourceModel ( (DatabaseTrackListModel)library.TrackModel)); } } } OnIndexingFinished (); } void ICollectionIndexer.Index () { ThreadPool.QueueUserWorkItem (delegate { Index (); }); } public void SaveToXml (string path) { lock (this) { uint timer_id = Hyena.Log.DebugTimerStart (); bool success = false; try { XmlTextWriter writer = new XmlTextWriter (path, System.Text.Encoding.UTF8); writer.Formatting = Formatting.Indented; writer.Indentation = 2; writer.IndentChar = ' '; writer.WriteStartDocument (true); writer.WriteStartElement ("banshee-collection"); writer.WriteStartAttribute ("version"); writer.WriteString (TrackInfo.ExportVersion); writer.WriteEndAttribute (); for (int i = 0; i < model_caches.Count; i++) { CachedList<DatabaseTrackInfo> model = model_caches[i]; if (model.Count <= 0) { continue; } writer.WriteStartElement ("model"); for (int j = 0; j < model.Count; j++) { writer.WriteStartElement ("item"); foreach (KeyValuePair<string, object> item in model[j].GenerateExportable (export_fields)) { string type = "string"; if (item.Value is Boolean) type = "bool"; else if (item.Value is Byte) type = "byte"; else if (item.Value is SByte) type = "sbyte"; else if (item.Value is Int16) type = "short"; else if (item.Value is UInt16) type = "ushort"; else if (item.Value is Int32) type = "int"; else if (item.Value is UInt32) type = "uint"; else if (item.Value is Int64) type = "long"; else if (item.Value is UInt64) type = "ulong"; else if (item.Value is Char) type = "char"; else if (item.Value is Double) type = "double"; else if (item.Value is Single) type = "float"; writer.WriteStartElement (item.Key); writer.WriteStartAttribute ("type"); writer.WriteString (type); writer.WriteEndAttribute (); writer.WriteString (item.Value.ToString ()); writer.WriteEndElement (); } writer.WriteEndElement (); } writer.WriteEndElement (); } writer.WriteEndElement (); writer.WriteEndDocument (); writer.Close (); success = true; } catch (Exception e) { Log.Error (e); } Hyena.Log.DebugTimerPrint (timer_id, "CollectionIndexer.SaveToXml: {0}"); SaveToXmlFinishedHandler handler = save_to_xml_finished; if (handler != null) { handler (success, path); } } } void ICollectionIndexer.SaveToXml (string path) { ThreadPool.QueueUserWorkItem (delegate { SaveToXml (path); }); } public IDictionary<string, object> GetResult (int modelIndex, int itemIndex) { lock (this) { if (modelIndex < 0 || modelIndex >= model_caches.Count) { throw new IndexOutOfRangeException ("modelIndex"); } CachedList<DatabaseTrackInfo> model = model_caches[modelIndex]; if (itemIndex < 0 || itemIndex >= model.Count) { throw new IndexOutOfRangeException ("itemIndex"); } return model[itemIndex].GenerateExportable (export_fields); } } public int GetModelCounts () { lock (this) { return model_caches.Count; } } public int GetModelResultsCount (int modelIndex) { lock (this) { if (modelIndex < 0 || modelIndex >= model_caches.Count) { return -1; } return model_caches[modelIndex].Count; } } protected virtual void OnIndexingFinished () { EventHandler handler = IndexingFinished; if (handler != null) { handler (this, EventArgs.Empty); } ActionHandler dbus_handler = indexing_finished; if (dbus_handler != null) { dbus_handler (); } } private string service_name = String.Format ("CollectionIndexer_{0}", instance_count++); string IService.ServiceName { get { return service_name; } } IDBusExportable IDBusExportable.Parent { get { return service; } } } }
// InflaterInputStream.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; using System.Security.Cryptography; using System.IO; using ICSharpCode.SharpZipLib.Zip.Compression; using ICSharpCode.SharpZipLib.Checksums; namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams.Interactive { /// <summary> /// An input buffer customised for use by <see cref="InflaterInputStream"/> /// </summary> /// <remarks> /// The buffer supports decryption of incoming data. /// </remarks> public class InteractiveInflaterInputBuffer { /// <summary> /// Initialise a new instance of <see cref="InflaterInputBuffer"/> /// </summary> /// <param name="stream">The stream to buffer.</param> public InteractiveInflaterInputBuffer(Stream stream, int bufferSize) { inputStream = stream; //rawData = new byte[4096]; rawData = new byte[bufferSize]; clearText = rawData; } /// <summary> /// Get the length of bytes bytes in the <see cref="RawData"/> /// </summary> public int RawLength { get { return rawLength; } } /// <summary> /// Get the contents of the raw data buffer. /// </summary> /// <remarks>This may contain encrypted data.</remarks> public byte[] RawData { get { return rawData; } } /// <summary> /// Get the number of useable bytes in <see cref="ClearText"/> /// </summary> public int ClearTextLength { get { return clearTextLength; } } /// <summary> /// Get the contents of the clear text buffer. /// </summary> public byte[] ClearText { get { return clearText; } } /// <summary> /// Get/set the number of bytes available /// </summary> public int Available { get { return available; } set { available = value; } } /// <summary> /// Call <see cref="Inflater.SetInput"/> passing the current clear text buffer contents. /// </summary> /// <param name="inflater">The inflater to set input for.</param> public void SetInflaterInput(Inflater inflater) { if (available > 0) { inflater.SetInput(clearText, clearTextLength - available, available); available = 0; } } /// <summary> /// Fill the buffer from the underlying input stream. /// </summary> public void Fill() { rawLength = 0; int toRead = rawData.Length; //while (toRead > 0) { int count = inputStream.Read(rawData, rawLength, toRead); if (count <= 0) { if (rawLength == 0) { throw new SharpZipBaseException("Unexpected EOF"); } //break; } rawLength += count; // toRead -= count; } if (cryptoTransform != null) { clearTextLength = cryptoTransform.TransformBlock(rawData, 0, rawLength, clearText, 0); } else { clearTextLength = rawLength; } available = clearTextLength; } /// <summary> /// Read a buffer directly from the input stream /// </summary> /// <param name="buffer">The buffer to fill</param> /// <returns>Returns the number of bytes read.</returns> public int ReadRawBuffer(byte[] buffer) { return ReadRawBuffer(buffer, 0, buffer.Length); } /// <summary> /// Read a buffer directly from the input stream /// </summary> /// <param name="outBuffer">The buffer to read into</param> /// <param name="offset">The offset to start reading data into.</param> /// <param name="length">The number of bytes to read.</param> /// <returns>Returns the number of bytes read.</returns> public int ReadRawBuffer(byte[] outBuffer, int offset, int length) { if (length <= 0) { throw new ArgumentOutOfRangeException("length"); } int currentOffset = offset; int currentLength = length; while (currentLength > 0) { if (available <= 0) { Fill(); if (available <= 0) { return 0; } } int toCopy = Math.Min(currentLength, available); System.Array.Copy(rawData, rawLength - (int)available, outBuffer, currentOffset, toCopy); currentOffset += toCopy; currentLength -= toCopy; available -= toCopy; } return length; } /// <summary> /// Read clear text data from the input stream. /// </summary> /// <param name="outBuffer">The buffer to add data to.</param> /// <param name="offset">The offset to start adding data at.</param> /// <param name="length">The number of bytes to read.</param> /// <returns>Returns the number of bytes actually read.</returns> public int ReadClearTextBuffer(byte[] outBuffer, int offset, int length) { if (length <= 0) { throw new ArgumentOutOfRangeException("length"); } int currentOffset = offset; int currentLength = length; while (currentLength > 0) { if (available <= 0) { Fill(); if (available <= 0) { return 0; } } int toCopy = Math.Min(currentLength, available); System.Array.Copy(clearText, clearTextLength - (int)available, outBuffer, currentOffset, toCopy); currentOffset += toCopy; currentLength -= toCopy; available -= toCopy; } return length; } /// <summary> /// Read a byte from the input stream. /// </summary> /// <returns>Returns the byte read.</returns> public int ReadLeByte() { if (available <= 0) { Fill(); if (available <= 0) { throw new ZipException("EOF in header"); } } byte result = (byte)(rawData[rawLength - available] & 0xff); available -= 1; return result; } /// <summary> /// Read an unsigned short in little endian byte order. /// </summary> public int ReadLeShort() { return ReadLeByte() | (ReadLeByte() << 8); } /// <summary> /// Read an int in little endian byte order. /// </summary> public int ReadLeInt() { return ReadLeShort() | (ReadLeShort() << 16); } /// <summary> /// Read an int baseInputStream little endian byte order. /// </summary> public long ReadLeLong() { return ReadLeInt() | (ReadLeInt() << 32); } /// <summary> /// Get/set the <see cref="ICryptoTransform"/> to apply to any data. /// </summary> /// <remarks>Set this value to null to have no transform applied.</remarks> public ICryptoTransform CryptoTransform { set { cryptoTransform = value; if (cryptoTransform != null) { if (rawData == clearText) { if (internalClearText == null) { internalClearText = new byte[4096]; } clearText = internalClearText; } clearTextLength = rawLength; if (available > 0) { cryptoTransform.TransformBlock(rawData, rawLength - available, available, clearText, rawLength - available); } } else { clearText = rawData; clearTextLength = rawLength; } } } #region Instance Fields int rawLength; byte[] rawData; int clearTextLength; byte[] clearText; byte[] internalClearText; int available; ICryptoTransform cryptoTransform; Stream inputStream; #endregion } /// <summary> /// This filter stream is used to decompress data compressed using the "deflate" /// format. The "deflate" format is described in RFC 1951. /// /// This stream may form the basis for other decompression filters, such /// as the <see cref="ICSharpCode.SharpZipLib.GZip.GZipInputStream">GZipInputStream</see>. /// /// Author of the original java version : John Leuner. /// </summary> public class InteractiveInflaterInputStream : Stream { /// <summary> /// Decompressor for this stream /// </summary> protected Inflater inf; /// <summary> /// <see cref="InflaterInputBuffer">Input buffer</see> for this stream. /// </summary> protected InteractiveInflaterInputBuffer inputBuffer; /// <summary> /// Base stream the inflater reads from. /// </summary> protected Stream baseInputStream; /// <summary> /// The compressed size /// </summary> protected long csize; bool isClosed = false; bool isStreamOwner = true; /// <summary> /// Get/set flag indicating ownership of underlying stream. /// When the flag is true <see cref="Close"/> will close the underlying stream also. /// </summary> /// <remarks> /// The default value is true. /// </remarks> public bool IsStreamOwner { get { return isStreamOwner; } set { isStreamOwner = value; } } /// <summary> /// Gets a value indicating whether the current stream supports reading /// </summary> public override bool CanRead { get { return baseInputStream.CanRead; } } /// <summary> /// Gets a value of false indicating seeking is not supported for this stream. /// </summary> public override bool CanSeek { get { return false; } } /// <summary> /// Gets a value of false indicating that this stream is not writeable. /// </summary> public override bool CanWrite { get { return false; } } /// <summary> /// A value representing the length of the stream in bytes. /// </summary> public override long Length { get { return inputBuffer.RawLength; } } /// <summary> /// The current position within the stream. /// Throws a NotSupportedException when attempting to set the position /// </summary> /// <exception cref="NotSupportedException">Attempting to set the position</exception> public override long Position { get { return baseInputStream.Position; } set { throw new NotSupportedException("InflaterInputStream Position not supported"); } } /// <summary> /// Flushes the baseInputStream /// </summary> public override void Flush() { baseInputStream.Flush(); } /// <summary> /// Sets the position within the current stream /// Always throws a NotSupportedException /// </summary> /// <exception cref="NotSupportedException">Any access</exception> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException("Seek not supported"); } /// <summary> /// Set the length of the current stream /// Always throws a NotSupportedException /// </summary> /// <exception cref="NotSupportedException">Any access</exception> public override void SetLength(long val) { throw new NotSupportedException("InflaterInputStream SetLength not supported"); } /// <summary> /// Writes a sequence of bytes to stream and advances the current position /// This method always throws a NotSupportedException /// </summary> /// <exception cref="NotSupportedException">Any access</exception> public override void Write(byte[] array, int offset, int count) { throw new NotSupportedException("InflaterInputStream Write not supported"); } /// <summary> /// Writes one byte to the current stream and advances the current position /// Always throws a NotSupportedException /// </summary> /// <exception cref="NotSupportedException">Any access</exception> public override void WriteByte(byte val) { throw new NotSupportedException("InflaterInputStream WriteByte not supported"); } /// <summary> /// Entry point to begin an asynchronous write. Always throws a NotSupportedException. /// </summary> /// <param name="buffer">The buffer to write data from</param> /// <param name="offset">Offset of first byte to write</param> /// <param name="count">The maximum number of bytes to write</param> /// <param name="callback">The method to be called when the asynchronous write operation is completed</param> /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests</param> /// <returns>An <see cref="System.IAsyncResult">IAsyncResult</see> that references the asynchronous write</returns> /// <exception cref="NotSupportedException">Any access</exception> public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException("InflaterInputStream BeginWrite not supported"); } /// <summary> /// Create an InflaterInputStream with the default decompressor /// and a default buffer size of 4KB. /// </summary> /// <param name = "baseInputStream"> /// The InputStream to read bytes from /// </param> public InteractiveInflaterInputStream(Stream baseInputStream) : this(baseInputStream, new Inflater(), 4096) { } /// <summary> /// Create an InflaterInputStream with the specified decompressor /// and a default buffer size of 4KB. /// </summary> /// <param name = "baseInputStream"> /// The source of input data /// </param> /// <param name = "inf"> /// The decompressor used to decompress data read from baseInputStream /// </param> public InteractiveInflaterInputStream(Stream baseInputStream, Inflater inf) : this(baseInputStream, inf, 4096) { } /// <summary> /// Create an InflaterInputStream with the specified decompressor /// and the specified buffer size. /// </summary> /// <param name = "baseInputStream"> /// The InputStream to read bytes from /// </param> /// <param name = "inflater"> /// The decompressor to use /// </param> /// <param name = "bufferSize"> /// Size of the buffer to use /// </param> public InteractiveInflaterInputStream(Stream baseInputStream, Inflater inflater, int bufferSize) { if (baseInputStream == null) { throw new ArgumentNullException("InflaterInputStream baseInputStream is null"); } if (inflater == null) { throw new ArgumentNullException("InflaterInputStream Inflater is null"); } if (bufferSize <= 0) { throw new ArgumentOutOfRangeException("bufferSize"); } this.baseInputStream = baseInputStream; this.inf = inflater; //inputBuffer = new InteractiveInflaterInputBuffer(baseInputStream); inputBuffer = new InteractiveInflaterInputBuffer(baseInputStream, bufferSize); } /// <summary> /// Returns 0 once the end of the stream (EOF) has been reached. /// Otherwise returns 1. /// </summary> public virtual int Available { get { return inf.IsFinished ? 0 : 1; } } /// <summary> /// Closes the input stream. When <see cref="IsStreamOwner"></see> /// is true the underlying stream is also closed. /// </summary> public override void Close() { if (!isClosed) { isClosed = true; if (isStreamOwner) { baseInputStream.Close(); } } } /// <summary> /// Fills the buffer with more data to decompress. /// </summary> /// <exception cref="SharpZipBaseException"> /// Stream ends early /// </exception> protected void Fill() { inputBuffer.Fill(); inputBuffer.SetInflaterInput(inf); } /// <summary> /// Decompresses data into the byte array /// </summary> /// <param name ="b"> /// The array to read and decompress data into /// </param> /// <param name ="off"> /// The offset indicating where the data should be placed /// </param> /// <param name ="len"> /// The number of bytes to decompress /// </param> /// <returns>The number of bytes read. Zero signals the end of stream</returns> /// <exception cref="SharpZipBaseException"> /// Inflater needs a dictionary /// </exception> public override int Read(byte[] b, int off, int len) { for (; ; ) { int count; try { count = inf.Inflate(b, off, len); } catch (Exception e) { throw new SharpZipBaseException(e.ToString()); } if (count > 0) { return count; } if (inf.IsNeedingDictionary) { throw new SharpZipBaseException("Need a dictionary"); } else if (inf.IsFinished) { return 0; } else if (inf.IsNeedingInput) { Fill(); } else { throw new InvalidOperationException("Don't know what to do"); } } } /// <summary> /// Skip specified number of bytes of uncompressed data /// </summary> /// <param name ="n"> /// Number of bytes to skip /// </param> /// <returns> /// The number of bytes skipped, zero if the end of /// stream has been reached /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// Number of bytes to skip is zero or less /// </exception> public long Skip(long n) { if (n <= 0) { throw new ArgumentOutOfRangeException("n"); } // v0.80 Skip by seeking if underlying stream supports it... if (baseInputStream.CanSeek) { baseInputStream.Seek(n, SeekOrigin.Current); return n; } else { int len = 2048; if (n < len) { len = (int)n; } byte[] tmp = new byte[len]; return (long)baseInputStream.Read(tmp, 0, tmp.Length); } } /// <summary> /// Clear any cryptographic state. /// </summary> protected void StopDecrypting() { inputBuffer.CryptoTransform = null; } } }
using UnityEngine; using System.Collections; namespace UINamespace { public enum UIAnchorLocation { LEFT_TOP, LEFT_MID, LEFT_BOT, MID_TOP, CENTER, MID_BOT, RIGHT_TOP, RIGHT_MID, RIGHT_BOT }; public class UIAnchor { public float m_xStart; public float m_yStart; public float m_xWidth; public float m_yHeight; private UIAnchorLocation m_anchorLocation; private delegate int pixelDelegate(); private delegate float relativeDelegate(); private pixelDelegate pixelXLeft; private pixelDelegate pixelXRight; private pixelDelegate pixelYBottom; private pixelDelegate pixelYTop; private relativeDelegate relativeXLeft; private relativeDelegate relativeXRight; private relativeDelegate relativeYBottom; private relativeDelegate relativeYTop; public UIAnchor(UIAnchorLocation anchorLocation, float xStart, float yStart, float xWidth, float yHeight) { switch (anchorLocation) { case UIAnchorLocation.LEFT_TOP: relativeXLeft = XLeft_AnchorLeft; relativeXRight = XRight_AnchorLeft; relativeYBottom = YBottom_AnchorTop; relativeYTop = YTop_AnchorTop; break; case UIAnchorLocation.LEFT_MID: relativeXLeft = XLeft_AnchorLeft; relativeXRight = XRight_AnchorLeft; relativeYBottom = YBottom_AnchorMid; relativeYTop = YTop_AnchorMid; break; case UIAnchorLocation.LEFT_BOT: relativeXLeft = XLeft_AnchorLeft; relativeXRight = XRight_AnchorLeft; relativeYBottom = YBottom_AnchorBottom; relativeYTop = YTop_AnchorBottom; break; case UIAnchorLocation.MID_TOP: relativeXLeft = XLeft_AnchorMid; relativeXRight = XRight_AnchorMid; relativeYBottom = YBottom_AnchorTop; relativeYTop = YTop_AnchorTop; break; case UIAnchorLocation.CENTER: relativeXLeft = XLeft_AnchorMid; relativeXRight = XRight_AnchorMid; relativeYBottom = YBottom_AnchorMid; relativeYTop = YTop_AnchorMid; break; case UIAnchorLocation.MID_BOT: relativeXLeft = XLeft_AnchorMid; relativeXRight = XRight_AnchorMid; relativeYBottom = YBottom_AnchorBottom; relativeYTop = YTop_AnchorBottom; break; case UIAnchorLocation.RIGHT_TOP: relativeXLeft = XLeft_AnchorRight; relativeXRight = XRight_AnchorRight; relativeYBottom = YBottom_AnchorTop; relativeYTop = YTop_AnchorTop; break; case UIAnchorLocation.RIGHT_MID: relativeXLeft = XLeft_AnchorRight; relativeXRight = XRight_AnchorRight; relativeYBottom = YBottom_AnchorMid; relativeYTop = YTop_AnchorMid; break; case UIAnchorLocation.RIGHT_BOT: relativeXLeft = XLeft_AnchorRight; relativeXRight = XRight_AnchorRight; relativeYBottom = YBottom_AnchorBottom; relativeYTop = YTop_AnchorBottom; break; } m_xStart = xStart; m_yStart = yStart; m_xWidth = xWidth; m_yHeight = yHeight; } public float GetRelativeXLeft() { return relativeXLeft(); } public float GetRelativeXRight() { return relativeXRight(); } public float GetRelativeYTop() { return relativeYTop(); } public float GetRelativeYBottom() { return relativeYBottom(); } public float GetPixelXLeft() { throw new System.NotImplementedException(); return pixelXLeft(); } public float GetPixelXRight() { throw new System.NotImplementedException(); return pixelXRight(); } public float GetPixelYTop() { throw new System.NotImplementedException(); return pixelYTop(); } public float GetPixelYBottom() { throw new System.NotImplementedException(); return pixelYBottom(); } private float XLeft_AnchorLeft() { return m_xStart; } private float XLeft_AnchorMid() { return m_xStart - 0.5f * m_xWidth; } private float XLeft_AnchorRight() { return m_xStart - m_xWidth; } private float XRight_AnchorLeft() { return m_xStart + m_xWidth; } private float XRight_AnchorMid() { return m_xStart + 0.5f * m_xWidth; } private float XRight_AnchorRight() { return m_xStart; } private float YBottom_AnchorBottom() { return m_yStart; } private float YBottom_AnchorMid() { return m_yStart - 0.5f * m_yHeight; } private float YBottom_AnchorTop() { return m_yStart - m_yHeight; } private float YTop_AnchorBottom() { return m_yStart + m_yHeight; } private float YTop_AnchorMid() { return m_yStart + 0.5f * m_yHeight; } private float YTop_AnchorTop() { return m_yStart; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics.CodeAnalysis; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http.Json; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.Http { /// <summary> /// Provides extension methods for writing a JSON serialized value to the HTTP response. /// </summary> public static partial class HttpResponseJsonExtensions { /// <summary> /// Write the specified value as JSON to the response body. The response content-type will be set to /// <c>application/json; charset=utf-8</c>. /// </summary> /// <typeparam name="TValue">The type of object to write.</typeparam> /// <param name="response">The response to write JSON to.</param> /// <param name="value">The value to write as JSON.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> used to cancel the operation.</param> /// <returns>The task object representing the asynchronous operation.</returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task WriteAsJsonAsync<TValue>( this HttpResponse response, TValue value, CancellationToken cancellationToken = default) { return response.WriteAsJsonAsync<TValue>(value, options: null, contentType: null, cancellationToken); } /// <summary> /// Write the specified value as JSON to the response body. The response content-type will be set to /// <c>application/json; charset=utf-8</c>. /// </summary> /// <typeparam name="TValue">The type of object to write.</typeparam> /// <param name="response">The response to write JSON to.</param> /// <param name="value">The value to write as JSON.</param> /// <param name="options">The serializer options use when serializing the value.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> used to cancel the operation.</param> /// <returns>The task object representing the asynchronous operation.</returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task WriteAsJsonAsync<TValue>( this HttpResponse response, TValue value, JsonSerializerOptions? options, CancellationToken cancellationToken = default) { return response.WriteAsJsonAsync<TValue>(value, options, contentType: null, cancellationToken); } /// <summary> /// Write the specified value as JSON to the response body. The response content-type will be set to /// the specified content-type. /// </summary> /// <typeparam name="TValue">The type of object to write.</typeparam> /// <param name="response">The response to write JSON to.</param> /// <param name="value">The value to write as JSON.</param> /// <param name="options">The serializer options use when serializing the value.</param> /// <param name="contentType">The content-type to set on the response.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> used to cancel the operation.</param> /// <returns>The task object representing the asynchronous operation.</returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task WriteAsJsonAsync<TValue>( this HttpResponse response, TValue value, JsonSerializerOptions? options, string? contentType, CancellationToken cancellationToken = default) { if (response == null) { throw new ArgumentNullException(nameof(response)); } options ??= ResolveSerializerOptions(response.HttpContext); response.ContentType = contentType ?? JsonConstants.JsonContentTypeWithCharset; // if no user provided token, pass the RequestAborted token and ignore OperationCanceledException if (!cancellationToken.CanBeCanceled) { return WriteAsJsonAsyncSlow<TValue>(response.Body, value, options, response.HttpContext.RequestAborted); } return JsonSerializer.SerializeAsync<TValue>(response.Body, value, options, cancellationToken); } private static async Task WriteAsJsonAsyncSlow<TValue>( Stream body, TValue value, JsonSerializerOptions? options, CancellationToken cancellationToken) { try { await JsonSerializer.SerializeAsync<TValue>(body, value, options, cancellationToken); } catch (OperationCanceledException) { } } /// <summary> /// Write the specified value as JSON to the response body. The response content-type will be set to /// <c>application/json; charset=utf-8</c>. /// </summary> /// <param name="response">The response to write JSON to.</param> /// <param name="value">The value to write as JSON.</param> /// <param name="type">The type of object to write.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> used to cancel the operation.</param> /// <returns>The task object representing the asynchronous operation.</returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task WriteAsJsonAsync( this HttpResponse response, object? value, Type type, CancellationToken cancellationToken = default) { return response.WriteAsJsonAsync(value, type, options: null, contentType: null, cancellationToken); } /// <summary> /// Write the specified value as JSON to the response body. The response content-type will be set to /// <c>application/json; charset=utf-8</c>. /// </summary> /// <param name="response">The response to write JSON to.</param> /// <param name="value">The value to write as JSON.</param> /// <param name="type">The type of object to write.</param> /// <param name="options">The serializer options use when serializing the value.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> used to cancel the operation.</param> /// <returns>The task object representing the asynchronous operation.</returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task WriteAsJsonAsync( this HttpResponse response, object? value, Type type, JsonSerializerOptions? options, CancellationToken cancellationToken = default) { return response.WriteAsJsonAsync(value, type, options, contentType: null, cancellationToken); } /// <summary> /// Write the specified value as JSON to the response body. The response content-type will be set to /// the specified content-type. /// </summary> /// <param name="response">The response to write JSON to.</param> /// <param name="value">The value to write as JSON.</param> /// <param name="type">The type of object to write.</param> /// <param name="options">The serializer options use when serializing the value.</param> /// <param name="contentType">The content-type to set on the response.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> used to cancel the operation.</param> /// <returns>The task object representing the asynchronous operation.</returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task WriteAsJsonAsync( this HttpResponse response, object? value, Type type, JsonSerializerOptions? options, string? contentType, CancellationToken cancellationToken = default) { if (response == null) { throw new ArgumentNullException(nameof(response)); } if (type == null) { throw new ArgumentNullException(nameof(type)); } options ??= ResolveSerializerOptions(response.HttpContext); response.ContentType = contentType ?? JsonConstants.JsonContentTypeWithCharset; // if no user provided token, pass the RequestAborted token and ignore OperationCanceledException if (!cancellationToken.CanBeCanceled) { return WriteAsJsonAsyncSlow(response.Body, value, type, options, response.HttpContext.RequestAborted); } return JsonSerializer.SerializeAsync(response.Body, value, type, options, cancellationToken); } private static async Task WriteAsJsonAsyncSlow( Stream body, object? value, Type type, JsonSerializerOptions? options, CancellationToken cancellationToken) { try { await JsonSerializer.SerializeAsync(body, value, type, options, cancellationToken); } catch (OperationCanceledException) { } } private static JsonSerializerOptions ResolveSerializerOptions(HttpContext httpContext) { // Attempt to resolve options from DI then fallback to default options return httpContext.RequestServices?.GetService<IOptions<JsonOptions>>()?.Value?.SerializerOptions ?? JsonOptions.DefaultSerializerOptions; } } }
// // Copyright 2012-2016, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Text; using System.Linq; #if ! PORTABLE && ! NETFX_CORE using System.Security.Cryptography; #endif using System.Net; using System.Globalization; using Xamarin.Utilities; #if ! AZURE_MOBILE_SERVICES namespace Xamarin.Auth #else namespace Xamarin.Auth._MobileServices #endif { /// <summary> /// A collection of utility functions for signing OAuth 1.0 requests. /// </summary> #if XAMARIN_AUTH_INTERNAL internal static class OAuth1 #else public static class OAuth1 #endif { /// <summary> /// Encodes a string according to: http://tools.ietf.org/html/rfc5849#section-3.6 /// </summary> /// <returns> /// The encoded string. /// </returns> /// <param name='unencoded'> /// The string to encode. /// </param> public static string EncodeString(string unencoded) { var utf8 = Encoding.UTF8.GetBytes(unencoded); var sb = new StringBuilder(); for (var i = 0; i < utf8.Length; i++) { var v = utf8[i]; if ((0x41 <= v && v <= 0x5A) || (0x61 <= v && v <= 0x7A) || (0x30 <= v && v <= 0x39) || v == 0x2D || v == 0x2E || v == 0x5F || v == 0x7E) { sb.Append((char)v); } else { sb.AppendFormat(CultureInfo.InvariantCulture, "%{0:X2}", v); } } return sb.ToString(); } /// <summary> /// Gets the signature base string according to: http://tools.ietf.org/html/rfc5849#section-3.4.1 /// </summary> /// <returns> /// The signature base string. /// </returns> /// <param name='method'> /// HTTP request method. /// </param> /// <param name='uri'> /// The request resource URI. /// </param> /// <param name='parameters'> /// Parameters covered by: http://tools.ietf.org/html/rfc5849#section-3.4.1.3 /// </param> public static string GetBaseString(string method, Uri uri, IDictionary<string, string> parameters) { var baseBuilder = new StringBuilder(); baseBuilder.Append(method); baseBuilder.Append("&"); baseBuilder.Append(EncodeString(uri.AbsoluteUri)); baseBuilder.Append("&"); var head = ""; foreach (var key in parameters.Keys.OrderBy(x => x)) { var p = head + EncodeString(key) + "=" + EncodeString(parameters[key]); baseBuilder.Append(EncodeString(p)); head = "&"; } return baseBuilder.ToString(); } /// <summary> /// Gets the signature of a request according to: http://tools.ietf.org/html/rfc5849#section-3.4 /// </summary> /// <returns> /// The signature. /// </returns> /// <param name='method'> /// HTTP request method. /// </param> /// <param name='uri'> /// The request resource URI. /// </param> /// <param name='parameters'> /// Parameters covered by: http://tools.ietf.org/html/rfc5849#section-3.4.1.3 /// </param> /// <param name='consumerSecret'> /// Consumer secret. /// </param> /// <param name='tokenSecret'> /// Token secret. /// </param> public static string GetSignature(string method, Uri uri, IDictionary<string, string> parameters, string consumerSecret, string tokenSecret) { #if !PORTABLE && !NETFX_CORE var baseString = GetBaseString(method, uri, parameters); var key = EncodeString(consumerSecret) + "&" + EncodeString(tokenSecret); var hashAlgo = new HMACSHA1(Encoding.UTF8.GetBytes(key)); var hash = hashAlgo.ComputeHash(Encoding.UTF8.GetBytes(baseString)); #else var hash = new byte[] { }; string msg = @" TODO: Get-Project Xamarin.Auth.Portable | Install-Package System.Security.Cryptography.Hashing -Pre Get-Project Xamarin.Auth.Portable | Install-Package System.Security.Cryptography.Hashing.Algorithms -Pre "; System.Diagnostics.Debug.WriteLine("Xamarin.Auth: " + msg); #endif var sig = Convert.ToBase64String(hash); return sig; } static Dictionary<string, string> MixInOAuthParameters(string method, Uri url, IDictionary<string, string> parameters, string consumerKey, string consumerSecret, string tokenSecret) { var ps = new Dictionary<string, string>(parameters); var nonce = new Random().Next().ToString(); var timestamp = ((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString(); ps["oauth_nonce"] = nonce; ps["oauth_timestamp"] = timestamp; ps["oauth_version"] = "1.0"; ps["oauth_consumer_key"] = consumerKey; ps["oauth_signature_method"] = "HMAC-SHA1"; var sig = GetSignature(method, url, ps, consumerSecret, tokenSecret); ps["oauth_signature"] = sig; return ps; } /// <summary> /// Creates an OAuth 1.0 signed request. /// </summary> /// <returns> /// The request. /// </returns> /// <param name='method'> /// HTTP request method. /// </param> /// <param name='uri'> /// The request resource URI. /// </param> /// <param name='parameters'> /// Parameters covered by: http://tools.ietf.org/html/rfc5849#section-3.4.1.3 /// </param> /// <param name='consumerKey'> /// Consumer key. /// </param> /// <param name='consumerSecret'> /// Consumer secret. /// </param> /// <param name='tokenSecret'> /// Token secret. /// </param> public static HttpWebRequest CreateRequest(string method, Uri uri, IDictionary<string, string> parameters, string consumerKey, string consumerSecret, string tokenSecret) { Dictionary<string, string> ps = MixInOAuthParameters(method, uri, parameters, consumerKey, consumerSecret, tokenSecret); string realUrl = uri.AbsoluteUri + "?" + ps.FormEncode(); HttpWebRequest req = // (HttpWebRequest)WebRequest.Create(realUrl) // WebRequest - no go for .NetStandard 1.6 HttpWebRequest.CreateHttp(realUrl) ; req.Method = method; return req; } /// <summary> /// Gets the authorization header for a signed request. /// </summary> /// <returns> /// The authorization header. /// </returns> /// <param name='method'> /// HTTP request method. /// </param> /// <param name='uri'> /// The request resource URI. /// </param> /// <param name='parameters'> /// Parameters covered by: http://tools.ietf.org/html/rfc5849#section-3.4.1.3 /// </param> /// <param name='consumerKey'> /// Consumer key. /// </param> /// <param name='consumerSecret'> /// Consumer secret. /// </param> /// <param name='token'> /// Token. /// </param> /// <param name='tokenSecret'> /// Token secret. /// </param> public static string GetAuthorizationHeader(string method, Uri uri, IDictionary<string, string> parameters, string consumerKey, string consumerSecret, string token, string tokenSecret) { var ps = new Dictionary<string, string>(parameters); ps["oauth_token"] = token; ps = MixInOAuthParameters(method, uri, ps, consumerKey, consumerSecret, tokenSecret); var sb = new StringBuilder(); var head = ""; foreach (var p in ps) { if (p.Key.StartsWith("oauth_")) { sb.Append(head); sb.AppendFormat("{0}=\"{1}\"", EncodeString(p.Key), EncodeString(p.Value)); head = ","; } } return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Xml.Linq; using System.Xml.XPath; using Microsoft.Extensions.Logging; namespace Umbraco.Cms.Core.Services.Implement { /// <inheritdoc /> public class LocalizedTextService : ILocalizedTextService { private readonly ILogger<LocalizedTextService> _logger; private readonly Lazy<LocalizedTextServiceFileSources> _fileSources; private IDictionary<CultureInfo, Lazy<IDictionary<string, IDictionary<string, string>>>> _dictionarySource => _dictionarySourceLazy.Value; private IDictionary<CultureInfo, Lazy<IDictionary<string, string>>> _noAreaDictionarySource => _noAreaDictionarySourceLazy.Value; private readonly Lazy<IDictionary<CultureInfo, Lazy<IDictionary<string, IDictionary<string, string>>>>> _dictionarySourceLazy; private readonly Lazy<IDictionary<CultureInfo, Lazy<IDictionary<string, string>>>> _noAreaDictionarySourceLazy; /// <summary> /// Initializes with a file sources instance /// </summary> /// <param name="fileSources"></param> /// <param name="logger"></param> public LocalizedTextService(Lazy<LocalizedTextServiceFileSources> fileSources, ILogger<LocalizedTextService> logger) { if (logger == null) throw new ArgumentNullException(nameof(logger)); _logger = logger; if (fileSources == null) throw new ArgumentNullException(nameof(fileSources)); _dictionarySourceLazy = new Lazy<IDictionary<CultureInfo, Lazy<IDictionary<string, IDictionary<string, string>>>>>(() => FileSourcesToAreaDictionarySources(fileSources.Value)); _noAreaDictionarySourceLazy = new Lazy<IDictionary<CultureInfo, Lazy<IDictionary<string, string>>>>(() => FileSourcesToNoAreaDictionarySources(fileSources.Value)); _fileSources = fileSources; } private IDictionary<CultureInfo, Lazy<IDictionary<string, string>>> FileSourcesToNoAreaDictionarySources( LocalizedTextServiceFileSources fileSources) { var xmlSources = fileSources.GetXmlSources(); return XmlSourceToNoAreaDictionary(xmlSources); } private IDictionary<CultureInfo, Lazy<IDictionary<string, string>>> XmlSourceToNoAreaDictionary( IDictionary<CultureInfo, Lazy<XDocument>> xmlSources) { var cultureNoAreaDictionary = new Dictionary<CultureInfo, Lazy<IDictionary<string, string>>>(); foreach (var xmlSource in xmlSources) { var noAreaAliasValue = new Lazy<IDictionary<string, string>>(() => GetNoAreaStoredTranslations(xmlSources, xmlSource.Key)); cultureNoAreaDictionary.Add(xmlSource.Key, noAreaAliasValue); } return cultureNoAreaDictionary; } private IDictionary<CultureInfo, Lazy<IDictionary<string, IDictionary<string, string>>>> FileSourcesToAreaDictionarySources(LocalizedTextServiceFileSources fileSources) { var xmlSources = fileSources.GetXmlSources(); return XmlSourcesToAreaDictionary(xmlSources); } private IDictionary<CultureInfo, Lazy<IDictionary<string, IDictionary<string, string>>>> XmlSourcesToAreaDictionary(IDictionary<CultureInfo, Lazy<XDocument>> xmlSources) { var cultureDictionary = new Dictionary<CultureInfo, Lazy<IDictionary<string, IDictionary<string, string>>>>(); foreach (var xmlSource in xmlSources) { var areaAliaValue = new Lazy<IDictionary<string, IDictionary<string, string>>>(() => GetAreaStoredTranslations(xmlSources, xmlSource.Key)); cultureDictionary.Add(xmlSource.Key, areaAliaValue); } return cultureDictionary; } /// <summary> /// Initializes with an XML source /// </summary> /// <param name="source"></param> /// <param name="logger"></param> public LocalizedTextService(IDictionary<CultureInfo, Lazy<XDocument>> source, ILogger<LocalizedTextService> logger) { if (source == null) throw new ArgumentNullException(nameof(source)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _dictionarySourceLazy = new Lazy<IDictionary<CultureInfo, Lazy<IDictionary<string, IDictionary<string, string>>>>>(() => XmlSourcesToAreaDictionary(source)); _noAreaDictionarySourceLazy = new Lazy<IDictionary<CultureInfo, Lazy<IDictionary<string, string>>>>(() => XmlSourceToNoAreaDictionary(source)); } [Obsolete("Use other ctor with IDictionary<CultureInfo, Lazy<IDictionary<string, IDictionary<string, string>>>> as input parameter.")] public LocalizedTextService(IDictionary<CultureInfo, IDictionary<string, IDictionary<string, string>>> source, ILogger<LocalizedTextService> logger) : this(source.ToDictionary(x=>x.Key, x=> new Lazy<IDictionary<string, IDictionary<string, string>>>(() => x.Value)), logger) { } /// <summary> /// Initializes with a source of a dictionary of culture -> areas -> sub dictionary of keys/values /// </summary> /// <param name="source"></param> /// <param name="logger"></param> public LocalizedTextService( IDictionary<CultureInfo, Lazy<IDictionary<string, IDictionary<string, string>>>> source, ILogger<LocalizedTextService> logger) { var dictionarySource = source ?? throw new ArgumentNullException(nameof(source)); _dictionarySourceLazy = new Lazy<IDictionary<CultureInfo, Lazy<IDictionary<string, IDictionary<string, string>>>>>(() => dictionarySource); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); var cultureNoAreaDictionary = new Dictionary<CultureInfo, Lazy<IDictionary<string, string>>>(); foreach (var cultureDictionary in dictionarySource) { var areaAliaValue = GetAreaStoredTranslations(source, cultureDictionary.Key); cultureNoAreaDictionary.Add(cultureDictionary.Key, new Lazy<IDictionary<string, string>>(() => GetAliasValues(areaAliaValue))); } _noAreaDictionarySourceLazy = new Lazy<IDictionary<CultureInfo, Lazy<IDictionary<string, string>>>>(() => cultureNoAreaDictionary); } private static Dictionary<string, string> GetAliasValues( Dictionary<string, IDictionary<string, string>> areaAliaValue) { var aliasValue = new Dictionary<string, string>(); foreach (var area in areaAliaValue) { foreach (var alias in area.Value) { if (!aliasValue.ContainsKey(alias.Key)) { aliasValue.Add(alias.Key, alias.Value); } } } return aliasValue; } public string Localize(string key, CultureInfo culture, IDictionary<string, string> tokens = null) { if (culture == null) throw new ArgumentNullException(nameof(culture)); //This is what the legacy ui service did if (string.IsNullOrEmpty(key)) return string.Empty; var keyParts = key.Split(Constants.CharArrays.ForwardSlash, StringSplitOptions.RemoveEmptyEntries); var area = keyParts.Length > 1 ? keyParts[0] : null; var alias = keyParts.Length > 1 ? keyParts[1] : keyParts[0]; return Localize(area, alias, culture, tokens); } public string Localize(string area, string alias, CultureInfo culture, IDictionary<string, string> tokens = null) { if (culture == null) throw new ArgumentNullException(nameof(culture)); //This is what the legacy ui service did if (string.IsNullOrEmpty(alias)) return string.Empty; // TODO: Hack, see notes on ConvertToSupportedCultureWithRegionCode culture = ConvertToSupportedCultureWithRegionCode(culture); return GetFromDictionarySource(culture, area, alias, tokens); } /// <summary> /// Returns all key/values in storage for the given culture /// </summary> public IDictionary<string, string> GetAllStoredValues(CultureInfo culture) { if (culture == null) throw new ArgumentNullException(nameof(culture)); // TODO: Hack, see notes on ConvertToSupportedCultureWithRegionCode culture = ConvertToSupportedCultureWithRegionCode(culture); if (_dictionarySource.ContainsKey(culture) == false) { _logger.LogWarning( "The culture specified {Culture} was not found in any configured sources for this service", culture); return new Dictionary<string, string>(0); } IDictionary<string, string> result = new Dictionary<string, string>(); //convert all areas + keys to a single key with a '/' foreach (var area in _dictionarySource[culture].Value) { foreach (var key in area.Value) { var dictionaryKey = string.Format("{0}/{1}", area.Key, key.Key); //i don't think it's possible to have duplicates because we're dealing with a dictionary in the first place, but we'll double check here just in case. if (result.ContainsKey(dictionaryKey) == false) { result.Add(dictionaryKey, key.Value); } } } return result; } private IDictionary<string, IDictionary<string, string>> GetAreaStoredTranslations( IDictionary<CultureInfo, Lazy<XDocument>> xmlSource, CultureInfo cult) { var overallResult = new Dictionary<string, IDictionary<string, string>>(StringComparer.InvariantCulture); var areas = xmlSource[cult].Value.XPathSelectElements("//area"); foreach (var area in areas) { var result = new Dictionary<string, string>(StringComparer.InvariantCulture); var keys = area.XPathSelectElements("./key"); foreach (var key in keys) { var dictionaryKey = (string)key.Attribute("alias"); //there could be duplicates if the language file isn't formatted nicely - which is probably the case for quite a few lang files if (result.ContainsKey(dictionaryKey) == false) result.Add(dictionaryKey, key.Value); } overallResult.Add(area.Attribute("alias").Value, result); } //Merge English Dictionary var englishCulture = new CultureInfo("en-US"); if (!cult.Equals(englishCulture)) { var enUS = xmlSource[englishCulture].Value.XPathSelectElements("//area"); foreach (var area in enUS) { IDictionary<string, string> result = new Dictionary<string, string>(StringComparer.InvariantCulture); if (overallResult.ContainsKey(area.Attribute("alias").Value)) { result = overallResult[area.Attribute("alias").Value]; } var keys = area.XPathSelectElements("./key"); foreach (var key in keys) { var dictionaryKey = (string)key.Attribute("alias"); //there could be duplicates if the language file isn't formatted nicely - which is probably the case for quite a few lang files if (result.ContainsKey(dictionaryKey) == false) result.Add(dictionaryKey, key.Value); } if (!overallResult.ContainsKey(area.Attribute("alias").Value)) { overallResult.Add(area.Attribute("alias").Value, result); } } } return overallResult; } private Dictionary<string, string> GetNoAreaStoredTranslations( IDictionary<CultureInfo, Lazy<XDocument>> xmlSource, CultureInfo cult) { var result = new Dictionary<string, string>(StringComparer.InvariantCulture); var keys = xmlSource[cult].Value.XPathSelectElements("//key"); foreach (var key in keys) { var dictionaryKey = (string)key.Attribute("alias"); //there could be duplicates if the language file isn't formatted nicely - which is probably the case for quite a few lang files if (result.ContainsKey(dictionaryKey) == false) result.Add(dictionaryKey, key.Value); } //Merge English Dictionary var englishCulture = new CultureInfo("en-US"); if (!cult.Equals(englishCulture)) { var keysEn = xmlSource[englishCulture].Value.XPathSelectElements("//key"); foreach (var key in keys) { var dictionaryKey = (string)key.Attribute("alias"); //there could be duplicates if the language file isn't formatted nicely - which is probably the case for quite a few lang files if (result.ContainsKey(dictionaryKey) == false) result.Add(dictionaryKey, key.Value); } } return result; } private Dictionary<string, IDictionary<string, string>> GetAreaStoredTranslations( IDictionary<CultureInfo, Lazy<IDictionary<string, IDictionary<string, string>>>> dictionarySource, CultureInfo cult) { var overallResult = new Dictionary<string, IDictionary<string, string>>(StringComparer.InvariantCulture); var areaDict = dictionarySource[cult]; foreach (var area in areaDict.Value) { var result = new Dictionary<string, string>(StringComparer.InvariantCulture); var keys = area.Value.Keys; foreach (var key in keys) { //there could be duplicates if the language file isn't formatted nicely - which is probably the case for quite a few lang files if (result.ContainsKey(key) == false) result.Add(key, area.Value[key]); } overallResult.Add(area.Key, result); } return overallResult; } /// <summary> /// Returns a list of all currently supported cultures /// </summary> /// <returns></returns> public IEnumerable<CultureInfo> GetSupportedCultures() { return _dictionarySource.Keys; } /// <summary> /// Tries to resolve a full 4 letter culture from a 2 letter culture name /// </summary> /// <param name="currentCulture"> /// The culture to determine if it is only a 2 letter culture, if so we'll try to convert it, otherwise it will just be returned /// </param> /// <returns></returns> /// <remarks> /// TODO: This is just a hack due to the way we store the language files, they should be stored with 4 letters since that /// is what they reference but they are stored with 2, further more our user's languages are stored with 2. So this attempts /// to resolve the full culture if possible. /// /// This only works when this service is constructed with the LocalizedTextServiceFileSources /// </remarks> public CultureInfo ConvertToSupportedCultureWithRegionCode(CultureInfo currentCulture) { if (currentCulture == null) throw new ArgumentNullException("currentCulture"); if (_fileSources == null) return currentCulture; if (currentCulture.Name.Length > 2) return currentCulture; var attempt = _fileSources.Value.TryConvert2LetterCultureTo4Letter(currentCulture.TwoLetterISOLanguageName); return attempt ? attempt.Result : currentCulture; } private string GetFromDictionarySource(CultureInfo culture, string area, string key, IDictionary<string, string> tokens) { if (_dictionarySource.ContainsKey(culture) == false) { _logger.LogWarning( "The culture specified {Culture} was not found in any configured sources for this service", culture); return "[" + key + "]"; } string found = null; if (string.IsNullOrWhiteSpace(area)) { _noAreaDictionarySource[culture].Value.TryGetValue(key, out found); } else { if (_dictionarySource[culture].Value.TryGetValue(area, out var areaDictionary)) { areaDictionary.TryGetValue(key, out found); } if (found == null) { _noAreaDictionarySource[culture].Value.TryGetValue(key, out found); } } if (found != null) { return ParseTokens(found, tokens); } //NOTE: Based on how legacy works, the default text does not contain the area, just the key return "[" + key + "]"; } /// <summary> /// Parses the tokens in the value /// </summary> /// <param name="value"></param> /// <param name="tokens"></param> /// <returns></returns> /// <remarks> /// This is based on how the legacy ui localized text worked, each token was just a sequential value delimited with a % symbol. /// For example: hello %0%, you are %1% ! /// /// Since we're going to continue using the same language files for now, the token system needs to remain the same. With our new service /// we support a dictionary which means in the future we can really have any sort of token system. /// Currently though, the token key's will need to be an integer and sequential - though we aren't going to throw exceptions if that is not the case. /// </remarks> internal static string ParseTokens(string value, IDictionary<string, string> tokens) { if (tokens == null || tokens.Any() == false) { return value; } foreach (var token in tokens) { value = value.Replace(string.Concat("%", token.Key, "%"), token.Value); } return value; } /// <summary> /// Returns all key/values in storage for the given culture /// </summary> /// <returns></returns> public IDictionary<string, IDictionary<string, string>> GetAllStoredValuesByAreaAndAlias(CultureInfo culture) { if (culture == null) { throw new ArgumentNullException("culture"); } // TODO: Hack, see notes on ConvertToSupportedCultureWithRegionCode culture = ConvertToSupportedCultureWithRegionCode(culture); if (_dictionarySource.ContainsKey(culture) == false) { _logger.LogWarning( "The culture specified {Culture} was not found in any configured sources for this service", culture); return new Dictionary<string, IDictionary<string, string>>(0); } return _dictionarySource[culture].Value; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.MachineLearning.WebServices { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.MachineLearning; 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> /// These APIs allow end users to operate on Azure Machine Learning Web /// Services resources. They support the following /// operations:&lt;ul&gt;&lt;li&gt;Create or update a web /// service&lt;/li&gt;&lt;li&gt;Get a web service&lt;/li&gt;&lt;li&gt;Patch /// a web service&lt;/li&gt;&lt;li&gt;Delete a web /// service&lt;/li&gt;&lt;li&gt;Get All Web Services in a Resource Group /// &lt;/li&gt;&lt;li&gt;Get All Web Services in a /// Subscription&lt;/li&gt;&lt;li&gt;Get Web Services /// Keys&lt;/li&gt;&lt;/ul&gt; /// </summary> public partial class AzureMLWebServicesManagementClient : ServiceClient<AzureMLWebServicesManagementClient>, IAzureMLWebServicesManagementClient, 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> /// The Azure subscription ID. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// The version of the Microsoft.MachineLearning resource provider API to use. /// </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 IWebServicesOperations. /// </summary> public virtual IWebServicesOperations WebServices { get; private set; } /// <summary> /// Initializes a new instance of the AzureMLWebServicesManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AzureMLWebServicesManagementClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AzureMLWebServicesManagementClient 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 AzureMLWebServicesManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AzureMLWebServicesManagementClient 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 AzureMLWebServicesManagementClient(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 AzureMLWebServicesManagementClient 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 AzureMLWebServicesManagementClient(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 AzureMLWebServicesManagementClient 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 AzureMLWebServicesManagementClient(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 AzureMLWebServicesManagementClient 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 AzureMLWebServicesManagementClient(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 AzureMLWebServicesManagementClient 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 AzureMLWebServicesManagementClient(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 AzureMLWebServicesManagementClient 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 AzureMLWebServicesManagementClient(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() { WebServices = new WebServicesOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2017-01-01"; 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() } }; 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() } }; SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<WebServiceProperties>("packageType")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<WebServiceProperties>("packageType")); CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
using System; /// <summary> /// System.Array.LastIndexOf<>(T[],T) /// </summary> public class ArrayIndexOf2 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Find out the last value which is equal to 3"); try { int length = TestLibrary.Generator.GetInt16(-55); int[] i1 = new int[length]; for (int i = 0; i < length; i++) { if (i % 3 == 0) { i1[i] = 3; } else { i1[i] = i; } } for (int a = length - 1; a > length - 4; a--) { if (a % 3 == 0) { int i2 = Array.LastIndexOf<int>(i1, 3); if (i2 != a) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected "); retVal = false; } } } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest2: Find the last string value in an array "); try { string[] s1 = new string[5]{"Jack", "Mary", "Mike", "Peter", "Jack"}; if (Array.LastIndexOf<string>(s1, "Jack") != 4) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest3: Find out the null element in an array of string "); try { string[] s1 = new string[7]{"Jack", "Mary", "Mike", null, "Peter", null, "Jack"}; if (Array.LastIndexOf<string>(s1, null) != 5) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest4: Find out no expected value in an array of string "); try { string[] s1 = new string[5]{"Jack", "Mary", "Mike", "Peter", "Jack"}; if (Array.LastIndexOf<string>(s1, "Tom") != -1) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest5: Find out the last empty string "); try { string[] s1 = new string[5]{"", "", "", "", "Tom"}; if (Array.LastIndexOf<string>(s1, "") != 3) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The array is a null reference"); try { string[] s1 = null; int i1 = Array.LastIndexOf<string>(s1, ""); TestLibrary.TestFramework.LogError("101", "The ArgumentNullException is not thrown as expected "); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ArrayIndexOf2 test = new ArrayIndexOf2(); TestLibrary.TestFramework.BeginTestCase("ArrayIndexOf2"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using System.Collections; using System.IO; using System.Threading; using System.Diagnostics; using NeuralNetwork; using NeuralNetwork.ActivationFunctions; using NeuralNetwork.Learning; using JustGestures.Properties; using JustGestures.GestureParts; using JustGestures.Languages; namespace JustGestures.ControlItems { public partial class UC_gesture : BaseActionControl { UC_TP_baseActivator m_activator; MyNeuralNetwork m_networkBackup; public MyNeuralNetwork MyNNetwork { get { if (tabControl_invokeAction.SelectedTab == tP_classicCurves) return m_tpClassicCurve.MyNNetwork; else return m_networkBackup; } set { m_networkBackup = new MyNeuralNetwork(value); m_tpClassicCurve.MyNNetwork = value; } } public MyNeuralNetwork MyNNetworkOriginal { set { m_tpClassicCurve.MyNNetworkOriginal = value; } } public UC_gesture() { InitializeComponent(); m_identifier = Page.Gesture; m_previous = Page.Action; //default m_next = Page.Name; tP_classicCurves.Text = Translation.GetText("C_Gestures_tP_curveG"); tP_rockerGesture.Text = Translation.GetText("C_Gestures_tP_rockerG"); tP_wheelGesture.Text = Translation.GetText("C_Gestures_tP_wheelG"); } private void UserControl_gesture_Load(object sender, EventArgs e) { List<UC_TP_baseActivator> activatorItems = new List<UC_TP_baseActivator>(); activatorItems.Add(m_tpClassicCurve); activatorItems.Add(m_tPdoubleBtn); activatorItems.Add(m_tpWheelButton); tabControl_invokeAction.TabPages.Clear(); foreach (UC_TP_baseActivator activator in activatorItems) { activator.CanContinue += new DlgCanContinue(CanContinue); if (ChangeAboutText != null) activator.ChangeAboutText += new DlgChangeAboutText(ChangeAboutText); activator.ChangeInfoText += new DlgChangeInfoText(ChangeInfoText); activator.PB_Display = pb_Display; activator.Gestures = m_gesturesCollection; activator.TempGesture = m_tempGesture; activator.Initialize(); } SetTabPages(); if (m_tempGesture.Activator != null) { if (m_tempGesture.Activator.Type == MouseActivator.Types.ClassicCurve) { m_activator = m_tpClassicCurve; tabControl_invokeAction.SelectedTab = tP_classicCurves; } else if (m_tempGesture.Activator.Type == MouseActivator.Types.DoubleButton) { m_activator = m_tPdoubleBtn; tabControl_invokeAction.SelectedTab = tP_rockerGesture; } else if (m_tempGesture.Activator.Type == BaseActivator.Types.WheelButton) { m_activator = m_tpWheelButton; tabControl_invokeAction.SelectedTab = tP_wheelGesture; } } else { if (!m_tempGesture.Action.IsExtras())//.Category != TypeOfAction.ExtrasControl.NAME) { m_activator = m_tpClassicCurve; tabControl_invokeAction.SelectedTab = tP_classicCurves; } else { m_activator = m_tpWheelButton; tabControl_invokeAction.SelectedTab = tP_wheelGesture; } } OnCanContinue(false); } private void panel_recognizedGesture_MouseDown(object sender, MouseEventArgs e) { if (pb_Display.Image == null) { ((UC_TP_baseActivator)m_tpClassicCurve).InitializePictureBox(); ((UC_TP_baseActivator)m_tPdoubleBtn).InitializePictureBox(); ((UC_TP_baseActivator)m_tpWheelButton).InitializePictureBox(); } m_activator.Display_MouseDown(sender, e); } private void panel_recognizedGesture_MouseMove(object sender, MouseEventArgs e) { m_activator.Display_MouseMove(sender, e); } private void panel_recognizedGesture_MouseUp(object sender, MouseEventArgs e) { m_activator.Display_MouseUp(sender, e); } private void panel_recognizedGesture_MouseClick(object sender, MouseEventArgs e) { m_activator.Display_MouseClick(sender, e); } private void SetTabPages() { if (!m_tempGesture.Action.IsExtras()) //.Category != TypeOfAction.ExtrasControl.NAME) { if (!tabControl_invokeAction.TabPages.Contains(tP_classicCurves)) tabControl_invokeAction.TabPages.Add(tP_classicCurves); if (!tabControl_invokeAction.TabPages.Contains(tP_rockerGesture)) tabControl_invokeAction.TabPages.Add(tP_rockerGesture); if (tabControl_invokeAction.TabPages.Contains(tP_wheelGesture)) tabControl_invokeAction.TabPages.Remove(tP_wheelGesture); } else { if (!tabControl_invokeAction.TabPages.Contains(tP_wheelGesture)) tabControl_invokeAction.TabPages.Add(tP_wheelGesture); if (tabControl_invokeAction.TabPages.Contains(tP_classicCurves)) tabControl_invokeAction.TabPages.Remove(tP_classicCurves); if (tabControl_invokeAction.TabPages.Contains(tP_rockerGesture)) tabControl_invokeAction.TabPages.Remove(tP_rockerGesture); } } private void UC_gesture_VisibleChanged(object sender, EventArgs e) { if (m_tempGesture != null && m_tempGesture.Activator != null) m_tempGesture.Activator.AbortAnimating(); if (((UC_gesture)sender).Visible) { SetTabPages(); m_activator.SetValues(); } } public void OnClosingForm(DialogResult result) { if (m_tempGesture != null && m_tempGesture.Activator != null) m_tempGesture.Activator.AbortAnimating(); if (result != DialogResult.OK && m_tpClassicCurve.MyNNetwork != null) m_tpClassicCurve.MyNNetwork.StopLearning(); } private void tabControl_invokeAction_SelectedIndexChanged(object sender, EventArgs e) { if (m_tempGesture != null && m_tempGesture.Activator != null) m_tempGesture.Activator.AbortAnimating(); if (tabControl_invokeAction.SelectedTab == tP_classicCurves) m_activator = m_tpClassicCurve; else if (tabControl_invokeAction.SelectedTab == tP_rockerGesture) m_activator = m_tPdoubleBtn; else if (tabControl_invokeAction.SelectedTab == tP_wheelGesture) m_activator = m_tpWheelButton; if (m_activator != null) m_activator.SetValues(); } private void pb_Display_SizeChanged(object sender, EventArgs e) { if (m_activator != null) m_activator.RedrawDisplay(); } private void tabControl_invokeAction_DrawItem(object sender, DrawItemEventArgs e) { int i = 0; } } }
#region License /* * Copyright 2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion #region Imports using System; using System.Diagnostics; using System.Runtime.Remoting; using System.Runtime.Remoting.Lifetime; using NUnit.Framework; using Spring.Aop.Framework; using Spring.Context; using Spring.Context.Support; using Spring.Objects; using Spring.Objects.Factory.Config; using Spring.Objects.Factory.Xml; #endregion namespace Spring.Remoting { /// <summary> /// Unit tests for the SaoFactoryObject class. /// </summary> /// <author>Mark Pollack</author> /// <author>Bruno Baia</author> [TestFixture] public class SaoFactoryObjectTests : BaseRemotingTestFixture { [Test] [ExpectedException(typeof(ArgumentException))] public void BailsWhenNotConfigured () { SaoFactoryObject sfo = new SaoFactoryObject(); sfo.AfterPropertiesSet(); } /// <summary> /// Make sure that transparent proxies are recognized /// correctly by the core object factory. /// </summary> /// <remarks> /// This is a test for SPRNET-200 /// </remarks> [Test] public void WiringWithTransparentProxy() { IApplicationContext ctx = new XmlApplicationContext("assembly://Spring.Services.Tests/Spring.Data.Spring.Remoting/autowire.xml"); ContextRegistry.RegisterContext(ctx); TestObject to = (TestObject) ctx.GetObject("kerry3"); Assert.IsNotNull(to, "Object is null even though a object has been configured."); Assert.IsTrue(RemotingServices.IsTransparentProxy(to.Sibling), "IsTransparentProxy"); Assert.AreEqual("Kerry3", to.Name, "Name"); to = (TestObject) ctx.GetObject("objectWithCtorArgRefShortcuts"); Assert.IsTrue(RemotingServices.IsTransparentProxy(to.Spouse), "IsTransparentProxy"); ConstructorDependenciesObject cdo = (ConstructorDependenciesObject) ctx.GetObject("rod2"); Assert.IsTrue(RemotingServices.IsTransparentProxy(cdo.Spouse1), "IsTransparentProxy"); Assert.IsTrue(RemotingServices.IsTransparentProxy(cdo.Spouse2), "IsTransparentProxy"); } [Test] public void GetSaoWithSingletonMode() { IApplicationContext ctx = new XmlApplicationContext("assembly://Spring.Services.Tests/Spring.Data.Spring.Remoting/saoSingleton.xml"); ContextRegistry.RegisterContext(ctx); object obj = ctx.GetObject("remoteSaoSingletonCounter"); Assert.IsNotNull(obj, "Object is null even though a object has been exported."); Assert.IsTrue((obj is ISimpleCounter), "Object should implement 'ISimpleCounter' interface."); ISimpleCounter sc = (ISimpleCounter) obj; Assert.AreEqual(1, sc.Counter, "Remote object hasn't been activated by the server."); sc.Count(); Assert.AreEqual(2, sc.Counter, "Remote object doesn't work in a 'Singleton' mode."); } public class SPRNET967_SimpleCounterWrapper : MarshalByRefObject, ISimpleCounter { private ISimpleCounter service; public SPRNET967_SimpleCounterWrapper() {} public SPRNET967_SimpleCounterWrapper(ISimpleCounter service) { this.service = service; } public ISimpleCounter Service { get { return service; } set { service = value; } } public int Counter { get { return service.Counter; } set { service.Counter = value; } } public void Count() { service.Count(); } } public class SPRNET967_SimpleCounterClient { private ISimpleCounter service; public SPRNET967_SimpleCounterClient() {} public SPRNET967_SimpleCounterClient(ISimpleCounter service) { this.service = service; } public ISimpleCounter Service { get { return service; } set { service = value; } } public int Counter { get { return service.Counter; } set { service.Counter = value; } } public void Count() { service.Count(); } } [Test] public void GetSaoWithSingletonModeAutowired_SPRNET967() { // register server by hand to avoid duplicate interfaces SPRNET967_SimpleCounterWrapper svr = new SPRNET967_SimpleCounterWrapper( new SimpleCounter(1) ); RemotingServices.Marshal(svr, "RemotedSaoSingletonCounter"); // object svc = Activator.GetObject(typeof(ISimpleCounter), "tcp://localhost:8005/RemotedSaoSingletonCounter"); // Assert.IsTrue( svc is IObjectDefinition ); // Assert.IsTrue( svc is ISimpleCounter ); IApplicationContext ctx = new XmlApplicationContext("assembly://Spring.Services.Tests/Spring.Data.Spring.Remoting/saoSingleton-autowired.xml"); ContextRegistry.RegisterContext(ctx); SPRNET967_SimpleCounterClient client = (SPRNET967_SimpleCounterClient) ctx.GetObject("counterClient"); client.Count(); Assert.AreEqual(2, client.Counter); } [Test] public void GetSaoWithSingletonModeAndAop() { IApplicationContext ctx = new XmlApplicationContext("assembly://Spring.Services.Tests/Spring.Data.Spring.Remoting/saoSingleton-aop.xml"); ContextRegistry.RegisterContext(ctx); //object saoFactory = ctx.GetObject("&remoteCounter"); //Assert.IsNotNull(saoFactory); object obj = ctx.GetObject("remoteCounter"); Assert.IsNotNull(obj, "Object is null even though a object has been exported."); Assert.IsTrue(AopUtils.IsAopProxy(obj)); Assert.IsTrue((obj is ISimpleCounter), "Object should implement 'ISimpleCounter' interface."); MethodCounter aopCounter = ctx.GetObject("countingBeforeAdvice") as MethodCounter; Assert.IsNotNull(aopCounter); int aopCount = aopCounter.GetCalls("Count"); Assert.AreEqual(0, aopCount); ISimpleCounter sc = (ISimpleCounter)obj; Assert.AreEqual(1, sc.Counter, "Remote object hasn't been activated by the server."); sc.Count(); Assert.AreEqual(2, sc.Counter, "Remote object doesn't work in a 'Singleton' mode."); Assert.AreEqual(1, aopCounter.GetCalls("Count")); } [Test] public void GetSaoWithSingleCallMode() { IApplicationContext ctx = new XmlApplicationContext("assembly://Spring.Services.Tests/Spring.Data.Spring.Remoting/saoSingleCall.xml"); ContextRegistry.RegisterContext(ctx); object obj = ctx.GetObject("remoteSaoSingleCallCounter"); Assert.IsNotNull(obj, "Object is null even though a object has been exported."); Assert.IsTrue((obj is ISimpleCounter), "Object should implement 'ISimpleCounter' interface."); ISimpleCounter sc = (ISimpleCounter) obj; Assert.IsNotNull(sc, "Object is null even though a object has been exported."); Assert.AreEqual(1, sc.Counter, "Remote object hasn't been activated by the server."); sc.Count(); Assert.AreEqual(1, sc.Counter, "Remote object don't works in a 'SingleCall' mode."); } [Test] public void GetSaoWithLifetimeService() { IApplicationContext ctx = new XmlApplicationContext("assembly://Spring.Services.Tests/Spring.Data.Spring.Remoting/saoLifetimeService.xml"); ContextRegistry.RegisterContext(ctx); MarshalByRefObject obj = (MarshalByRefObject) ctx.GetObject("remoteSaoCounter"); ILease lease = (ILease) obj.GetLifetimeService(); Assert.AreEqual(TimeSpan.FromMilliseconds(10000), lease.InitialLeaseTime, "InitialLeaseTime"); Assert.AreEqual(TimeSpan.FromMilliseconds(1000), lease.RenewOnCallTime, "RenewOnCallTime"); Assert.AreEqual(TimeSpan.FromMilliseconds(100), lease.SponsorshipTimeout, "SponsorshipTimeout"); } } }
// // Mono.System.Xml.XmlNodeReader2.cs - splitted XmlNodeReader that manages entities. // // Author: // Duncan Mak (duncan@ximian.com) // Atsushi Enomoto (ginga@kit.hi-ho.ne.jp) // // (C) Ximian, Inc. // (C) Atsushi Enomoto // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; #if NET_2_0 using System.Collections.Generic; #endif using Mono.System.Xml; using Mono.System.Xml.Schema; using System.Text; using Mono.Xml; namespace Mono.System.Xml { #if NET_2_0 public class XmlNodeReader : XmlReader, IHasXmlParserContext, IXmlNamespaceResolver #else public class XmlNodeReader : XmlReader, IHasXmlParserContext #endif { XmlReader entity; XmlNodeReaderImpl source; bool entityInsideAttribute; bool insideAttribute; #region Constructor public XmlNodeReader (XmlNode node) { source = new XmlNodeReaderImpl (node); } private XmlNodeReader (XmlNodeReaderImpl entityContainer, bool insideAttribute) { source = new XmlNodeReaderImpl (entityContainer); this.entityInsideAttribute = insideAttribute; } #endregion #region Properties private XmlReader Current { get { return entity != null && entity.ReadState != ReadState.Initial ? entity : source; } } public override int AttributeCount { get { return Current.AttributeCount; } } public override string BaseURI { get { return Current.BaseURI; } } #if NET_2_0 public override bool CanReadBinaryContent { get { return true; } } /* public override bool CanReadValueChunk { get { return true; } } */ #else internal override bool CanReadBinaryContent { get { return true; } } /* internal override bool CanReadValueChunk { get { return true; } } */ #endif public override bool CanResolveEntity { get { return true; } } public override int Depth { get { // On EndEntity, depth is the same as that // of EntityReference. if (entity != null && entity.ReadState == ReadState.Interactive) return source.Depth + entity.Depth + 1; else return source.Depth; } } public override bool EOF { get { return source.EOF; } } public override bool HasAttributes { get { return Current.HasAttributes; } } public override bool HasValue { get { return Current.HasValue; } } public override bool IsDefault { get { return Current.IsDefault; } } public override bool IsEmptyElement { get { return Current.IsEmptyElement; } } #if NET_2_0 #else public override string this [int i] { get { return GetAttribute (i); } } public override string this [string name] { get { return GetAttribute (name); } } public override string this [string name, string namespaceURI] { get { return GetAttribute (name, namespaceURI); } } #endif public override string LocalName { get { return Current.LocalName; } } public override string Name { get { return Current.Name; } } public override string NamespaceURI { get { return Current.NamespaceURI; } } public override XmlNameTable NameTable { get { return Current.NameTable; } } public override XmlNodeType NodeType { get { if (entity != null) return entity.ReadState == ReadState.Initial ? source.NodeType : entity.EOF ? XmlNodeType.EndEntity : entity.NodeType; else return source.NodeType; } } XmlParserContext IHasXmlParserContext.ParserContext { get { return ((IHasXmlParserContext) Current).ParserContext; } } public override string Prefix { get { return Current.Prefix; } } #if NET_2_0 #else public override char QuoteChar { get { return '"'; } } #endif public override ReadState ReadState { get { return entity != null ? ReadState.Interactive : source.ReadState; } } #if NET_2_0 public override IXmlSchemaInfo SchemaInfo { get { return entity != null ? entity.SchemaInfo : source.SchemaInfo; } } #endif public override string Value { get { return Current.Value; } } public override string XmlLang { get { return Current.XmlLang; } } public override XmlSpace XmlSpace { get { return Current.XmlSpace; } } #endregion #region Methods // If current entityReference is a child of an attribute, // then MoveToAttribute simply means that we no more need this entity Current. // Otherwise, this invokation means that // it is expected to move to resolved (maybe) element's attribute. // // This rule applies to many methods like MoveTo*Attribute(). public override void Close () { if (entity != null) entity.Close (); source.Close (); } public override string GetAttribute (int attributeIndex) { return Current.GetAttribute (attributeIndex); } public override string GetAttribute (string name) { return Current.GetAttribute (name); } public override string GetAttribute (string name, string namespaceURI) { return Current.GetAttribute (name, namespaceURI); } #if NET_2_0 IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope (XmlNamespaceScope scope) { return ((IXmlNamespaceResolver) Current).GetNamespacesInScope (scope); } #endif public override string LookupNamespace (string prefix) { return Current.LookupNamespace (prefix); } #if NET_2_0 string IXmlNamespaceResolver.LookupPrefix (string ns) { return ((IXmlNamespaceResolver) Current).LookupPrefix (ns); } #endif public override void MoveToAttribute (int attributeIndex) { if (entity != null && entityInsideAttribute) { entity.Close (); entity = null; } Current.MoveToAttribute (attributeIndex); insideAttribute = true; } public override bool MoveToAttribute (string name) { if (entity != null && !entityInsideAttribute) return entity.MoveToAttribute (name); if (!source.MoveToAttribute (name)) return false; if (entity != null && entityInsideAttribute) { entity.Close (); entity = null; } insideAttribute = true; return true; } public override bool MoveToAttribute (string name, string namespaceURI) { if (entity != null && !entityInsideAttribute) return entity.MoveToAttribute (name, namespaceURI); if (!source.MoveToAttribute (name, namespaceURI)) return false; if (entity != null && entityInsideAttribute) { entity.Close (); entity = null; } insideAttribute = true; return true; } public override bool MoveToElement () { if (entity != null && entityInsideAttribute) entity = null; if (!Current.MoveToElement ()) return false; insideAttribute = false; return true; } public override bool MoveToFirstAttribute () { if (entity != null && !entityInsideAttribute) return entity.MoveToFirstAttribute (); if (!source.MoveToFirstAttribute ()) return false; if (entity != null && entityInsideAttribute) { entity.Close (); entity = null; } insideAttribute = true; return true; } public override bool MoveToNextAttribute () { if (entity != null && !entityInsideAttribute) return entity.MoveToNextAttribute (); if (!source.MoveToNextAttribute ()) return false; if (entity != null && entityInsideAttribute) { entity.Close (); entity = null; } insideAttribute = true; return true; } public override bool Read () { insideAttribute = false; if (entity != null && (entityInsideAttribute || entity.EOF)) entity = null; if (entity != null) { entity.Read (); return true; // either success or EndEntity } else return source.Read (); } public override bool ReadAttributeValue () { if (entity != null && entityInsideAttribute) { if (entity.EOF) entity = null; else { entity.Read (); return true; // either success or EndEntity } } return Current.ReadAttributeValue (); } #if NET_2_0 public override int ReadContentAsBase64 (byte [] buffer, int index, int count) { // return base.ReadContentAsBase64 ( // buffer, offset, length); // FIXME: This is problematic wrt end of entity. if (entity != null) return entity.ReadContentAsBase64 ( buffer, index, count); else return source.ReadContentAsBase64 ( buffer, index, count); } public override int ReadContentAsBinHex (byte [] buffer, int index, int count) { // return base.ReadContentAsBinHex ( // buffer, offset, length); // FIXME: This is problematic wrt end of entity. if (entity != null) return entity.ReadContentAsBinHex ( buffer, index, count); else return source.ReadContentAsBinHex ( buffer, index, count); } public override int ReadElementContentAsBase64 (byte [] buffer, int index, int count) { // return base.ReadElementContentAsBase64 ( // buffer, index, count); // FIXME: This is problematic wrt end of entity. if (entity != null) return entity.ReadElementContentAsBase64 ( buffer, index, count); else return source.ReadElementContentAsBase64 ( buffer, index, count); } public override int ReadElementContentAsBinHex ( byte [] buffer, int index, int count) { // return base.ReadElementContentAsBinHex ( // buffer, index, count); // FIXME: This is problematic wrt end of entity. if (entity != null) return entity.ReadElementContentAsBinHex ( buffer, index, count); else return source.ReadElementContentAsBinHex ( buffer, index, count); } #endif public override string ReadString () { return base.ReadString (); } public override void ResolveEntity () { if (entity != null) entity.ResolveEntity (); else { if (source.NodeType != XmlNodeType.EntityReference) throw new InvalidOperationException ("The current node is not an Entity Reference"); entity = new XmlNodeReader (source, insideAttribute); } } public override void Skip () { if (entity != null && entityInsideAttribute) entity = null; Current.Skip (); } #endregion } }
namespace Economy.scripts.Messages { using System; using System.Collections.Generic; using System.Linq; using EconConfig; using Economy.scripts; using Economy.scripts.EconStructures; using ProtoBuf; using Sandbox.Definitions; using Sandbox.Game.Entities; using Sandbox.ModAPI; using VRage; using VRage.Game; using VRage.Game.Entity; using VRage.Game.ModAPI; using VRage.Game.ObjectBuilders.Definitions; using VRage.ModAPI; using VRage.ObjectBuilders; /// <summary> /// this is to do the actual work of checking and moving the goods when a player is selling to something/someone. /// </summary> [ProtoContract] public class MessageSell : MessageBase { #region properties [ProtoMember(1)] public SellAction SellAction; /// <summary> /// person, NPC, offer or faction to sell to /// </summary> [ProtoMember(2)] public string ToUserName; /// <summary> /// qty of item /// </summary> [ProtoMember(3)] public decimal ItemQuantity; /// <summary> /// item id we are selling /// </summary> [ProtoMember(4)] public string ItemTypeId; /// <summary> /// item subid we are selling /// </summary> [ProtoMember(5)] public string ItemSubTypeName; /// <summary> /// unit price of item /// </summary> [ProtoMember(6)] public decimal ItemPrice; /// <summary> /// Use the Current Buy price to sell it at. The Player /// will not have access to this information without fetching it first. This saves us the trouble. /// </summary> [ProtoMember(7)] public bool UseBankBuyPrice; /// <summary> /// We are trading with a (Player/NPC) Merchant market?. /// </summary> [ProtoMember(8)] public bool SellToMerchant; /// <summary> /// The Item is been put onto the market. /// </summary> [ProtoMember(9)] public bool OfferToMarket; //[ProtoMember(10)] //public string zone; //used to identify market we are selling to ?? #endregion #region send message methods public static void SendAcceptMessage() { ConnectionHelper.SendMessageToServer(new MessageSell { SellAction = SellAction.Accept }); } public static void SendCancelMessage() { ConnectionHelper.SendMessageToServer(new MessageSell { SellAction = SellAction.Cancel }); } public static void SendCollectMessage() { ConnectionHelper.SendMessageToServer(new MessageSell { SellAction = SellAction.Collect }); } public static void SendDenyMessage() { ConnectionHelper.SendMessageToServer(new MessageSell { SellAction = SellAction.Deny }); } public static void SendSellMessage(string toUserName, decimal itemQuantity, string itemTypeId, string itemSubTypeName, decimal itemPrice, bool useBankBuyPrice, bool sellToMerchant, bool offerToMarket) { ConnectionHelper.SendMessageToServer(new MessageSell { SellAction = SellAction.Create, ToUserName = toUserName, ItemQuantity = itemQuantity, ItemTypeId = itemTypeId, ItemSubTypeName = itemSubTypeName, ItemPrice = itemPrice, UseBankBuyPrice = useBankBuyPrice, SellToMerchant = sellToMerchant, OfferToMarket = offerToMarket }); } #endregion public override void ProcessClient() { // never processed on client } public override void ProcessServer() { if (!EconomyScript.Instance.ServerConfig.EnableNpcTradezones && !EconomyScript.Instance.ServerConfig.EnablePlayerTradezones) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "All Trade zones are disabled."); return; } switch (SellAction) { #region create case SellAction.Create: { EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create started by Steam Id '{0}'.", SenderSteamId); //* Logic: //* Get player steam ID var sellingPlayer = MyAPIGateway.Players.FindPlayerBySteamId(SenderSteamId); MyDefinitionBase definition = null; MyObjectBuilderType result; if (MyObjectBuilderType.TryParse(ItemTypeId, out result)) { var id = new MyDefinitionId(result, ItemSubTypeName); MyDefinitionManager.Static.TryGetDefinition(id, out definition); } if (definition == null) { // Someone hacking, and passing bad data? MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, the item you specified doesn't exist!"); EconomyScript.Instance.ServerLogger.WriteVerbose("Definition could not be found for item during '/sell'; '{0}' '{1}'.", ItemTypeId, ItemSubTypeName); return; } // Do a floating point check on the item item. Tools and components cannot have decimals. They must be whole numbers. if (definition.Id.TypeId != typeof(MyObjectBuilder_Ore) && definition.Id.TypeId != typeof(MyObjectBuilder_Ingot)) { if (ItemQuantity != Math.Truncate(ItemQuantity)) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You must provide a whole number for the quantity of that item."); return; } //ItemQuantity = Math.Round(ItemQuantity, 0); // Or do we just round the number? } if (ItemQuantity <= 0) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Invalid quantity, or you dont have any to trade!"); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- Invalid quantity.", SenderSteamId); return; } // Who are we selling to? BankAccountStruct accountToBuy; if (SellToMerchant) accountToBuy = AccountManager.FindAccount(EconomyConsts.NpcMerchantId); else accountToBuy = AccountManager.FindAccount(ToUserName); if (accountToBuy == null) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, player does not exist or have an account!"); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- account not found.", SenderSteamId); return; } if (MarketManager.IsItemBlacklistedOnServer(ItemTypeId, ItemSubTypeName)) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, the item you tried to sell is blacklisted on this server."); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- Item is blacklisted.", SenderSteamId); return; } // Verify that the items are in the player inventory. // TODO: later check trade block, cockpit inventory, cockpit ship inventory, inventory of targeted cube. // Get the player's inventory, regardless of if they are in a ship, or a remote control cube. var character = sellingPlayer.GetCharacter(); // TODO: do players in Cryochambers count as a valid trading partner? They should be alive, but the connected player may be offline. // I think we'll have to do lower level checks to see if a physical player is Online. if (character == null) { // Player has no body. Could mean they are dead. // Either way, there is no inventory. MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You are dead. You cannot trade while dead."); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- player is dead.", SenderSteamId); return; } // TODO: is a null check adaqaute?, or do we need to check for IsDead? // I don't think the chat console is accessible during respawn, only immediately after death. // Is it valid to be able to trade when freshly dead? //var identity = payingPlayer.Identity(); //MyAPIGateway.Utilities.ShowMessage("CHECK", "Is Dead: {0}", identity.IsDead); //if (identity.IsDead) //{ // MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You are dead. You cannot trade while dead."); // return; //} EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell finalizing by Steam Id '{0}' -- cataloging cargo cubes.", SenderSteamId); // Build list of all cargo blocks that player is attached to as pilot or passenger. var cargoBlocks = new List<MyCubeBlock>(); var tankBlocks = new List<MyCubeBlock>(); var controllingCube = sellingPlayer.Controller.ControlledEntity as IMyCubeBlock; if (controllingCube != null) { var terminalsys = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(controllingCube.CubeGrid); var blocks = new List<IMyTerminalBlock>(); terminalsys.GetBlocksOfType<IMyCargoContainer>(blocks); cargoBlocks.AddRange(blocks.Cast<MyCubeBlock>()); terminalsys.GetBlocksOfType<IMyGasTank>(blocks); tankBlocks.AddRange(blocks.Cast<MyCubeBlock>()); } EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell finalizing by Steam Id '{0}' -- checking inventory.", SenderSteamId); var position = ((IMyEntity)character).WorldMatrix.Translation; var playerInventory = character.GetPlayerInventory(); MyFixedPoint amount = (MyFixedPoint)ItemQuantity; var storedAmount = playerInventory.GetItemAmount(definition.Id); if (definition.Id.TypeId == typeof(MyObjectBuilder_GasProperties)) { foreach (MyCubeBlock cubeBlock in tankBlocks) { MyGasTankDefinition gasTankDefintion = cubeBlock.BlockDefinition as MyGasTankDefinition; if (gasTankDefintion == null || gasTankDefintion.StoredGasId != definition.Id) continue; var tankLevel = ((IMyGasTank)cubeBlock).FilledRatio; storedAmount += (MyFixedPoint)((decimal)tankLevel * (decimal)gasTankDefintion.Capacity); } } else { foreach (MyCubeBlock cubeBlock in cargoBlocks) { var cubeInventory = cubeBlock.GetInventory(); storedAmount += cubeInventory.GetItemAmount(definition.Id); } } if (amount > storedAmount) { // Insufficient items in inventory. // TODO: use of definition.GetDisplayName() isn't localized here. if ((definition.Id.TypeId != typeof(MyObjectBuilder_GasProperties) && cargoBlocks.Count == 0) && (definition.Id.TypeId == typeof(MyObjectBuilder_GasProperties) && tankBlocks.Count == 0)) MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You don't have {0} of '{1}' to sell. You have {2} in your inventory.", ItemQuantity, definition.GetDisplayName(), storedAmount); else MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You don't have {0} of '{1}' to sell. You have {2} in your player and cargo inventory.", ItemQuantity, definition.GetDisplayName(), storedAmount); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- inventory doesn't exist.", SenderSteamId); return; } MarketItemStruct marketItem = null; if (SellToMerchant || UseBankBuyPrice) { var markets = MarketManager.FindMarketsFromLocation(position); if (markets.Count == 0) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, your are not in range of any markets!"); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- no market in range.", SenderSteamId); return; } // TODO: find market with best Buy price that isn't blacklisted. var market = markets.FirstOrDefault(); if (market == null) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, the market you are accessing does not exist!"); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- no market found.", SenderSteamId); return; } accountToBuy = AccountManager.FindAccount(market.MarketId); marketItem = market.MarketItems.FirstOrDefault(e => e.TypeId == ItemTypeId && e.SubtypeName == ItemSubTypeName); if (marketItem == null) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, the items you are trying to sell doesn't have a market entry!"); // In reality, this shouldn't happen as all markets have their items synced up on start up of the mod. return; } if (marketItem.IsBlacklisted) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, the item you tried to sell is blacklisted in this market."); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- item is blacklisted.", SenderSteamId); return; } if (UseBankBuyPrice) // The player is selling, but the *Market* will *buy* it from the player at this price. // if we are not using price scaling OR the market we are trading with isn't owned by the NPC ID, dont change price. Otherwise scale. if (!EconomyScript.Instance.ServerConfig.PriceScaling || accountToBuy.SteamId != EconomyConsts.NpcMerchantId) ItemPrice = marketItem.BuyPrice; else ItemPrice = EconDataManager.PriceAdjust(marketItem.BuyPrice, marketItem.Quantity, PricingBias.Buy); // if we are using price scaling adjust the price before our NPC trade (or check player for subsidy pricing) } var accountToSell = AccountManager.FindOrCreateAccount(SenderSteamId, SenderDisplayName, SenderLanguage); // need fix negative amounts before checking if the player can afford it. if (!sellingPlayer.IsAdmin()) ItemPrice = Math.Abs(ItemPrice); var transactionAmount = ItemPrice * ItemQuantity; if (!sellingPlayer.IsAdmin()) transactionAmount = Math.Abs(transactionAmount); if (SellToMerchant) // && (merchant has enough money || !EconomyScript.Instance.ServerConfig.LimitedSupply) //this is also a quick fix ideally npc should buy what it can afford and the rest is posted as a sell offer { if (accountToBuy.SteamId != accountToSell.SteamId) { decimal limit = EconomyScript.Instance.ServerConfig.LimitedSupply ? marketItem.StockLimit - marketItem.Quantity : ItemQuantity; if (limit == 0) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, you cannot sell any more {0} into this market.", definition.GetDisplayName()); return; } if (ItemQuantity > limit) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, you cannot sell any more than {0} of {1} into this market.", limit, definition.GetDisplayName()); return; } } if (accountToBuy.BankBalance >= transactionAmount // || !EconomyScript.Instance.ServerConfig.LimitedSupply // I'm not sure why we check limited supply when selling. || accountToBuy.SteamId == accountToSell.SteamId) { // here we look up item price and transfer items and money as appropriate EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell finalizing by Steam Id '{0}' -- removing inventory.", SenderSteamId); RemoveInventory(playerInventory, cargoBlocks, tankBlocks, amount, definition.Id); marketItem.Quantity += ItemQuantity; // increment Market content. if (accountToBuy.SteamId != accountToSell.SteamId) { accountToBuy.BankBalance -= transactionAmount; accountToBuy.Date = DateTime.Now; accountToSell.BankBalance += transactionAmount; accountToSell.Date = DateTime.Now; MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You just sold {0} {3} worth of {2} ({1} units)", transactionAmount, ItemQuantity, definition.GetDisplayName(), EconomyScript.Instance.ServerConfig.CurrencyName); MessageUpdateClient.SendAccountMessage(accountToBuy); MessageUpdateClient.SendAccountMessage(accountToSell); } else { accountToSell.Date = DateTime.Now; MessageClientTextMessage.SendMessage(SenderSteamId, "BUY", "You just arranged transfer of {0} '{1}' into your market.", ItemQuantity, definition.GetDisplayName()); } } else { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "NPC can't afford {0} {4} worth of {2} ({1} units) NPC only has {3} funds!", transactionAmount, ItemQuantity, definition.GetDisplayName(), accountToBuy.BankBalance, EconomyScript.Instance.ServerConfig.CurrencyName); } EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create completed by Steam Id '{0}' -- to NPC market.", SenderSteamId); return; } if (OfferToMarket) { // TODO: Here we post offer to appropriate zone market MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Offset to market at price is not yet available!"); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- Offer to market at price is not yet available.", SenderSteamId); return; } // is it a player then? if (accountToBuy.SteamId == sellingPlayer.SteamUserId) { // commented out for testing with myself. MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, you cannot sell to yourself!"); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- can't sell to self.", SenderSteamId); return; } // check if buying player is online and in range? var buyingPlayer = MyAPIGateway.Players.FindPlayerBySteamId(accountToBuy.SteamId); if (EconomyScript.Instance.ServerConfig.LimitedRange && !Support.RangeCheck(buyingPlayer, sellingPlayer)) { MessageClientTextMessage.SendMessage(SenderSteamId, "BUY", "Sorry, you are not in range of that player!"); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- target player not in range.", SenderSteamId); return; } // if other player online, send message. if (buyingPlayer == null) { // TODO: other player offline. MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You cannot sell to offline players at this time."); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- cannot sell to offline player.", SenderSteamId); return; // TODO: we need a way to queue up messages. // While you were gone.... // You missed an offer for 4000Kg of Gold for 20,000. } else { // The other player is online. // write to Trade offer table. MarketManager.CreateTradeOffer(SenderSteamId, ItemTypeId, ItemSubTypeName, ItemQuantity, ItemPrice, accountToBuy.SteamId); // remove items from inventory. EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell finalizing by Steam Id '{0}' -- removing inventory.", SenderSteamId); RemoveInventory(playerInventory, cargoBlocks, tankBlocks, amount, definition.Id); // Only send message to targeted player if this is the only offer pending for them. // Otherwise it will be sent when the have with previous orders in their order Queue. if (EconomyScript.Instance.Data.OrderBook.Count(e => (e.OptionalId == accountToBuy.SteamId.ToString() && e.TradeState == TradeState.SellDirectPlayer)) == 1) { MessageClientTextMessage.SendMessage(accountToBuy.SteamId, "SELL", "You have received an offer from {0} to buy {1} {2} at price {3} {4} each - type '/sell accept' to accept offer (or '/sell deny' to reject and return item to seller)", SenderDisplayName, ItemQuantity, definition.GetDisplayName(), ItemPrice, EconomyScript.Instance.ServerConfig.CurrencyName); } // TODO: Improve the message here, to say who were are trading to, and that the item is gone from inventory. // send message to seller to confirm action, "Your Trade offer has been submitted, and the goods removed from you inventory." MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Your offer of {0} {1} for {2} {4} each has been sent to {3}.", ItemQuantity, definition.GetDisplayName(), ItemPrice, accountToBuy.NickName, EconomyScript.Instance.ServerConfig.CurrencyName); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create completed by Steam Id '{0}' -- to another player.", SenderSteamId); return; } } #endregion #region accept case SellAction.Accept: { EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Accept started by Steam Id '{0}'.", SenderSteamId); var order = EconomyScript.Instance.Data.OrderBook.FirstOrDefault(e => e.OptionalId == SenderSteamId.ToString() && e.TradeState == TradeState.SellDirectPlayer); if (order == null) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "There are no outstanding orders to be accepted."); return; } var payingPlayer = MyAPIGateway.Players.FindPlayerBySteamId(SenderSteamId); // get the accounts and check finance. var accountToBuy = AccountManager.FindAccount(ulong.Parse(order.OptionalId)); var transactionAmount = order.Price * order.Quantity; // need fix negative amounts before checking if the player can afford it. if (!payingPlayer.IsAdmin()) transactionAmount = Math.Abs(transactionAmount); if (accountToBuy.BankBalance < transactionAmount) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You cannot afford {0} {1} at this time.", transactionAmount, EconomyScript.Instance.ServerConfig.CurrencyName); return; } var accountToSell = AccountManager.FindAccount(order.TraderId); // rebalance accounts. accountToBuy.BankBalance -= transactionAmount; accountToBuy.Date = DateTime.Now; accountToSell.BankBalance += transactionAmount; accountToSell.Date = DateTime.Now; MessageUpdateClient.SendAccountMessage(accountToBuy); MessageUpdateClient.SendAccountMessage(accountToSell); order.TradeState = TradeState.SellAccepted; var definition = MyDefinitionManager.Static.GetDefinition(order.TypeId, order.SubtypeName); if (definition == null) { // Someone hacking, and passing bad data? MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, the item in your order doesn't exist!"); // trade has been finalized, so we can exit safely. EconomyScript.Instance.ServerLogger.WriteVerbose("Definition could not be found for item during '/sell accept'; '{0}' '{1}'.", order.TypeId, order.SubtypeName); return; } // TODO: Improve the messages. // message back "Your Trade offer of xxx to yyy has been accepted. You have recieved zzzz" MessageClientTextMessage.SendMessage(accountToSell.SteamId, "SELL", "You just sold {0} {3} worth of {2} ({1} units)", transactionAmount, order.Quantity, definition.GetDisplayName(), EconomyScript.Instance.ServerConfig.CurrencyName); var collectingPlayer = MyAPIGateway.Players.FindPlayerBySteamId(SenderSteamId); var playerInventory = collectingPlayer.GetPlayerInventory(); bool hasAddedToInventory = true; if (playerInventory != null) { MyFixedPoint amount = (MyFixedPoint)order.Quantity; hasAddedToInventory = Support.InventoryAdd(playerInventory, amount, definition.Id); } if (hasAddedToInventory) { EconomyScript.Instance.Data.OrderBook.Remove(order); // item has been collected, so the order is finalized. MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You just purchased {0} {3} worth of {2} ({1} units) which are now in your player inventory.", transactionAmount, order.Quantity, definition.GetDisplayName(), EconomyScript.Instance.ServerConfig.CurrencyName); } else MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You just purchased {0} {3} worth of {2} ({1} units). Enter '/collect' when you are ready to receive them.", transactionAmount, order.Quantity, definition.GetDisplayName(), EconomyScript.Instance.ServerConfig.CurrencyName); // Send message to player if additional offers are pending their attention. DisplayNextOrderToAccept(SenderSteamId); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Accept completed by Steam Id '{0}'.", SenderSteamId); return; } #endregion #region collect case SellAction.Collect: { EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Collect or /collect started by Steam Id '{0}'.", SenderSteamId); var collectableOrders = EconomyScript.Instance.Data.OrderBook.Where(e => (e.TraderId == SenderSteamId && e.TradeState == TradeState.SellTimedout) || (e.TraderId == SenderSteamId && e.TradeState == TradeState.Holding) || (e.TraderId == SenderSteamId && e.TradeState == TradeState.SellRejected) || (e.OptionalId == SenderSteamId.ToString() && e.TradeState == TradeState.SellAccepted)).ToArray(); if (collectableOrders.Length == 0) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "There is nothing to collect currently."); return; } var collectingPlayer = MyAPIGateway.Players.FindPlayerBySteamId(SenderSteamId); // TODO: this is just for debugging until the message below are completed.... //MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You are collecting items from {0} order/s.", collectableOrders.Length); foreach (var order in collectableOrders) { MyDefinitionBase definition = null; MyObjectBuilderType result; if (MyObjectBuilderType.TryParse(order.TypeId, out result)) { var id = new MyDefinitionId(result, order.SubtypeName); MyDefinitionManager.Static.TryGetDefinition(id, out definition); } if (definition == null) { // Someone hacking, and passing bad data? MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, the item in your order doesn't exist!"); // TODO: more detail on the item. EconomyScript.Instance.ServerLogger.WriteVerbose("Definition could not be found for item during '/sell collect or /collect'; '{0}' '{1}'.", order.TypeId, order.SubtypeName); continue; } EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell finalizing by Steam Id '{0}' -- adding to inventories.", SenderSteamId); var remainingToCollect = MessageSell.AddToInventories(collectingPlayer, order.Quantity, definition.Id); var collected = order.Quantity - remainingToCollect; if (remainingToCollect == 0) { EconomyScript.Instance.Data.OrderBook.Remove(order); MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You just collected {0} worth of {2} ({1} units)", order.Price * collected, collected, definition.GetDisplayName()); } else { order.Quantity = remainingToCollect; MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You just collected {0} worth of {2} ({1} units). There are {3} remaining.", order.Price * collected, collected, definition.GetDisplayName(), remainingToCollect); } } EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Collect completed by Steam Id '{0}'.", SenderSteamId); return; } #endregion #region cancel case SellAction.Cancel: { EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Cancel started by Steam Id '{0}'.", SenderSteamId); var cancellableOrders = EconomyScript.Instance.Data.OrderBook.Where(e => (e.TraderId == SenderSteamId && e.TradeState == TradeState.SellDirectPlayer)).OrderByDescending(e => e.Created).ToArray(); if (cancellableOrders.Length == 0) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "There is nothing to cancel currently."); } // Sellers should be presented with the newest order first, as they will be the most recently created. // use of OrderByDescending above assures us that [0] is the most recent order added. var order = cancellableOrders[0]; order.TradeState = TradeState.SellRejected; var definition = MyDefinitionManager.Static.GetDefinition(order.TypeId, order.SubtypeName); if (definition == null) { // Someone hacking, and passing bad data? MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, the item in your order doesn't exist!"); // trade has been finalized, so we can exit safely. EconomyScript.Instance.ServerLogger.WriteVerbose("Definition could not be found for item during '/sell cancel'; '{0}' '{1}'.", order.TypeId, order.SubtypeName); return; } var transactionAmount = order.Price * order.Quantity; var collectingPlayer = MyAPIGateway.Players.FindPlayerBySteamId(SenderSteamId); var inventory = collectingPlayer.GetPlayerInventory(); bool hasAddedToInventory = true; if (inventory != null) { MyFixedPoint amount = (MyFixedPoint)order.Quantity; hasAddedToInventory = Support.InventoryAdd(inventory, amount, definition.Id); } if (hasAddedToInventory) { EconomyScript.Instance.Data.OrderBook.Remove(order); // item has been collected, so the order is finalized. MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You just cancelled the sale of {2} ({1} units) for a total of {0} {3} which are now in your inventory.", transactionAmount, order.Quantity, definition.GetDisplayName(), EconomyScript.Instance.ServerConfig.CurrencyName); } else MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You just cancelled the sale of {2} ({1} units) for a total of {0} {3}. Enter '/sell collect' when you are ready to receive them.", transactionAmount, order.Quantity, definition.GetDisplayName(), EconomyScript.Instance.ServerConfig.CurrencyName); cancellableOrders = EconomyScript.Instance.Data.OrderBook.Where(e => (e.TraderId == SenderSteamId && e.TradeState == TradeState.SellDirectPlayer)).OrderByDescending(e => e.Created).ToArray(); if (cancellableOrders.Length > 0) { // TODO: Inform the player of the next order in the queue that can be cancelled. } EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Cancel completed by Steam Id '{0}'.", SenderSteamId); return; } #endregion #region deny case SellAction.Deny: { EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Deny started by Steam Id '{0}'.", SenderSteamId); var buyOrdersForMe = EconomyScript.Instance.Data.OrderBook.Where(e => (e.OptionalId == SenderSteamId.ToString() && e.TradeState == TradeState.SellDirectPlayer)).OrderBy(e => e.Created).ToArray(); if (buyOrdersForMe.Length == 0) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "There is nothing to deny currently."); } // Buyers should be presented with the oldest order first, as they will timout first. // use of OrderBy above assures us that [0] is the most oldest order added. var order = buyOrdersForMe[0]; order.TradeState = TradeState.SellRejected; var definition = MyDefinitionManager.Static.GetDefinition(order.TypeId, order.SubtypeName); if (definition == null) { // Someone hacking, and passing bad data? MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, the item in your order doesn't exist!"); // trade has been finalized, so we can exit safely. EconomyScript.Instance.ServerLogger.WriteVerbose("Definition could not be found for item during '/sell deny'; '{0}' '{1}'.", order.TypeId, order.SubtypeName); return; } var transactionAmount = order.Price * order.Quantity; var buyerId = ulong.Parse(order.OptionalId); MessageClientTextMessage.SendMessage(buyerId, "SELL", "You just rejected the purchase of {2} ({1} units) for a total of {0} {3}.", transactionAmount, order.Quantity, definition.GetDisplayName(), EconomyScript.Instance.ServerConfig.CurrencyName); // TODO: return items to inventory automatically to Trader inventory if there is space. MessageClientTextMessage.SendMessage(order.TraderId, "SELL", "{3} has just rejected your offer of {2} ({1} units) for a total of {0} {4}. Enter '/sell collect' when you are ready to receive them.", transactionAmount, order.Quantity, definition.GetDisplayName(), SenderDisplayName, EconomyScript.Instance.ServerConfig.CurrencyName); // Send message to player if additional offers are pending their attention. DisplayNextOrderToAccept(SenderSteamId); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Deny completed by Steam Id '{0}'.", SenderSteamId); return; } #endregion } // this is a fall through from the above conditions not yet complete. MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Not yet complete."); } /// <summary> /// Send a message to targeted player if have additional offers pending for them. /// </summary> /// <param name="steamdId"></param> private void DisplayNextOrderToAccept(ulong steamdId) { // Buyers should be presented with the oldest order first, as they will timout first. // use of OrderBy assures us that [0] is the most oldest order added. var remaingingUnacceptedOrders = EconomyScript.Instance.Data.OrderBook.Where(e => (e.OptionalId == steamdId.ToString() && e.TradeState == TradeState.SellDirectPlayer)).OrderBy(e => e.Created).ToList(); if (remaingingUnacceptedOrders.Count <= 0) return; var order = remaingingUnacceptedOrders[0]; var accountToSell = AccountManager.FindAccount(order.TraderId); var transactionAmount = order.Price * order.Quantity; var payingPlayer = MyAPIGateway.Players.FindPlayerBySteamId(steamdId); // need fix negative amounts before checking if the player can afford it. if (!payingPlayer.IsAdmin()) transactionAmount = Math.Abs(transactionAmount); var definition = MyDefinitionManager.Static.GetDefinition(order.TypeId, order.SubtypeName); if (definition == null) { // Someone hacking, and passing bad data? MessageClientTextMessage.SendMessage(steamdId, "SELL", "Sorry, the item in your order doesn't exist!"); EconomyScript.Instance.ServerLogger.WriteVerbose("Definition could not be found for item during 'DisplayNextOrderToAccept'; '{0}' '{1}'.", order.TypeId, order.SubtypeName); return; } MessageClientTextMessage.SendMessage(steamdId, "SELL", "You have received an offer from {0} to buy {1} {2} at total price {3} {4} - type '/sell accept' to accept offer (or '/sell deny' to reject and return item to seller)", accountToSell.NickName, order.Quantity, definition.GetDisplayName(), transactionAmount, EconomyScript.Instance.ServerConfig.CurrencyName); } private void RemoveInventory(IMyInventory playerInventory, List<MyCubeBlock> cargoBlocks, List<MyCubeBlock> tankBlocks, MyFixedPoint amount, MyDefinitionId definitionId) { if (definitionId.TypeId == typeof(MyObjectBuilder_GasProperties)) { foreach (MyCubeBlock cubeBlock in tankBlocks) { MyGasTankDefinition gasTankDefintion = cubeBlock.BlockDefinition as MyGasTankDefinition; if (gasTankDefintion == null || gasTankDefintion.StoredGasId != definitionId) continue; var tank = ((IMyGasTank)cubeBlock); // TODO: Cannot set oxygen level of tank yet. //tank.le //var tankLevel = ((IMyGasTank)cubeBlock).FilledRatio; //storedAmount += (MyFixedPoint)((decimal)tankLevel * (decimal)gasTankDefintion.Capacity); } } else { var available = playerInventory.GetItemAmount(definitionId); if (amount <= available) { playerInventory.RemoveItemsOfType(amount, definitionId); amount = 0; } else { playerInventory.RemoveItemsOfType(available, definitionId); amount -= available; } foreach (var cubeBlock in cargoBlocks) { if (amount > 0) { var cubeInventory = cubeBlock.GetInventory(); available = cubeInventory.GetItemAmount(definitionId); if (amount <= available) { cubeInventory.RemoveItemsOfType(amount, definitionId); amount = 0; } else { cubeInventory.RemoveItemsOfType(available, definitionId); amount -= available; } } } } } internal static decimal AddToInventories(IMyPlayer collectingPlayer, decimal quantity, MyDefinitionId definitionId) { MyFixedPoint amount = (MyFixedPoint)quantity; var cargoBlocks = new List<MyEntity>(); var controllingCube = collectingPlayer.Controller.ControlledEntity as IMyCubeBlock; if (controllingCube != null) { var terminalsys = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(controllingCube.CubeGrid); var blocks = new List<IMyTerminalBlock>(); terminalsys.GetBlocksOfType<IMyCargoContainer>(blocks); foreach (var block in blocks) cargoBlocks.Add((MyEntity)block); } foreach (var cubeBlock in cargoBlocks) { if (amount > 0) { var cubeInventory = cubeBlock.GetInventory(); var space = cubeInventory.ComputeAmountThatFits(definitionId); if (amount <= space) { if (Support.InventoryAdd(cubeInventory, amount, definitionId)) amount = 0; } else { if (Support.InventoryAdd(cubeInventory, space, definitionId)) amount -= space; } } } if (amount > 0) { var playerInventory = collectingPlayer.GetPlayerInventory(); if (playerInventory != null) { var space = ((Sandbox.Game.MyInventory)playerInventory).ComputeAmountThatFits(definitionId); if (amount <= space) { if (Support.InventoryAdd(playerInventory, amount, definitionId)) amount = 0; } else { if (Support.InventoryAdd(playerInventory, space, definitionId)) amount -= space; } } } return (decimal)amount; } } }
// // UniqueFileIdentifierFrame.cs: // // Author: // Brian Nickel (brian.nickel@gmail.com) // // Original Source: // uniquefileidentifierframe.cpp from TagLib // // Copyright (C) 2005-2007 Brian Nickel // Copyright (C) 2004 Scott Wheeler (Original Implementation) // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License version // 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA // using System.Collections; using System; namespace TagLib.Id3v2 { /// <summary> /// This class extends <see cref="Frame" />, implementing support for /// ID3v2 Unique File Identifier (UFID) Frames. /// </summary> public class UniqueFileIdentifierFrame : Frame { #region Private Fields /// <summary> /// Contains the owner string. /// </summary> private string owner = null; /// <summary> /// Contains the identifier data. /// </summary> private ByteVector identifier = null; #endregion #region Constructors /// <summary> /// Constructs and initializes a new instance of <see /// cref="UniqueFileIdentifierFrame" /> with a specified /// owner and identifier data. /// </summary> /// <param name="owner"> /// A <see cref="string" /> containing the owner of the new /// frame. /// </param> /// <param name="identifier"> /// A <see cref="ByteVector" /> object containing the /// identifier for the new frame. /// </param> /// <remarks> /// When a frame is created, it is not automatically added to /// the tag. Consider using <see /// cref="Get(Tag,string,bool)" /> for more integrated frame /// creation. /// </remarks> /// <exception cref="ArgumentNullException"> /// <paramref name="owner" /> is <see langword="null" />. /// </exception> public UniqueFileIdentifierFrame (string owner, ByteVector identifier) : base (FrameType.UFID, 4) { if (owner == null) throw new ArgumentNullException ("owner"); this.owner = owner; this.identifier = identifier; } /// <summary> /// Constructs and initializes a new instance of <see /// cref="UniqueFileIdentifierFrame" /> with a specified /// owner. /// </summary> /// <param name="owner"> /// A <see cref="string" /> containing the owner of the new /// frame. /// </param> /// <remarks> /// When a frame is created, it is not automatically added to /// the tag. Consider using <see /// cref="Get(Tag,string,bool)" /> for more integrated frame /// creation. /// </remarks> /// <exception cref="ArgumentNullException"> /// <paramref name="owner" /> is <see langword="null" />. /// </exception> public UniqueFileIdentifierFrame (string owner) : this (owner, null) { } /// <summary> /// Constructs and initializes a new instance of <see /// cref="UniqueFileIdentifierFrame" /> by reading its raw /// data in a specified ID3v2 version. /// </summary> /// <param name="data"> /// A <see cref="ByteVector" /> object starting with the raw /// representation of the new frame. /// </param> /// <param name="version"> /// A <see cref="byte" /> indicating the ID3v2 version the /// raw frame is encoded in. /// </param> public UniqueFileIdentifierFrame (ByteVector data, byte version) : base (data, version) { SetData (data, 0, version, true); } /// <summary> /// Constructs and initializes a new instance of <see /// cref="UniqueFileIdentifierFrame" /> by reading its raw /// data in a specified ID3v2 version. /// </summary> /// <param name="data"> /// A <see cref="ByteVector" /> object containing the raw /// representation of the new frame. /// </param> /// <param name="offset"> /// A <see cref="int" /> indicating at what offset in /// <paramref name="data" /> the frame actually begins. /// </param> /// <param name="header"> /// A <see cref="FrameHeader" /> containing the header of the /// frame found at <paramref name="offset" /> in the data. /// </param> /// <param name="version"> /// A <see cref="byte" /> indicating the ID3v2 version the /// raw frame is encoded in. /// </param> protected internal UniqueFileIdentifierFrame (ByteVector data, int offset, FrameHeader header, byte version) : base(header) { SetData (data, offset, version, false); } #endregion #region Public Properties /// <summary> /// Gets and sets the owner of the current instance. /// </summary> /// <value> /// A <see cref="string" /> containing the owner of the /// current instance. /// </value> /// <remarks> /// There should only be one frame with a matching owner per /// tag. /// </remarks> public string Owner { get {return owner;} } /// <summary> /// Gets and sets the identifier data stored in the current /// instance. /// </summary> /// <value> /// A <see cref="ByteVector" /> object containiner the unique /// file identifier frame. /// </value> public ByteVector Identifier { get {return identifier;} set {identifier = value;} } #endregion #region Public Static Methods /// <summary> /// Gets a specified unique file identifer frame from the /// specified tag, optionally creating it if it does not /// exist. /// </summary> /// <param name="tag"> /// A <see cref="Tag" /> object to search in. /// </param> /// <param name="owner"> /// A <see cref="string" /> specifying the owner to match. /// </param> /// <param name="create"> /// A <see cref="bool" /> specifying whether or not to create /// and add a new frame to the tag if a match is not found. /// </param> /// <returns> /// A <see cref="UserTextInformationFrame" /> object /// containing the matching frame, or <see langword="null" /> /// if a match wasn't found and <paramref name="create" /> is /// <see langword="false" />. /// </returns> public static UniqueFileIdentifierFrame Get (Tag tag, string owner, bool create) { UniqueFileIdentifierFrame ufid; foreach (Frame frame in tag.GetFrames (FrameType.UFID)) { ufid = frame as UniqueFileIdentifierFrame; if (ufid == null) continue; if (ufid.Owner == owner) return ufid; } if (!create) return null; ufid = new UniqueFileIdentifierFrame (owner, null); tag.AddFrame (ufid); return ufid; } #endregion #region Protected Methods /// <summary> /// Populates the values in the current instance by parsing /// its field data in a specified version. /// </summary> /// <param name="data"> /// A <see cref="ByteVector" /> object containing the /// extracted field data. /// </param> /// <param name="version"> /// A <see cref="byte" /> indicating the ID3v2 version the /// field data is encoded in. /// </param> protected override void ParseFields (ByteVector data, byte version) { ByteVectorCollection fields = ByteVectorCollection.Split (data, (byte) 0); if (fields.Count != 2) return; owner = fields [0].ToString (StringType.Latin1); identifier = fields [1]; } /// <summary> /// Renders the values in the current instance into field /// data for a specified version. /// </summary> /// <param name="version"> /// A <see cref="byte" /> indicating the ID3v2 version the /// field data is to be encoded in. /// </param> /// <returns> /// A <see cref="ByteVector" /> object containing the /// rendered field data. /// </returns> protected override ByteVector RenderFields (byte version) { ByteVector data = new ByteVector (); data.Add (ByteVector.FromString (owner, StringType.Latin1)); data.Add (ByteVector.TextDelimiter (StringType.Latin1)); data.Add (identifier); return data; } #endregion #region ICloneable /// <summary> /// Creates a deep copy of the current instance. /// </summary> /// <returns> /// A new <see cref="Frame" /> object identical to the /// current instance. /// </returns> public override Frame Clone () { UniqueFileIdentifierFrame frame = new UniqueFileIdentifierFrame (owner); if (identifier != null) frame.identifier = new ByteVector (identifier); return frame; } #endregion } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Screens; using osu.Framework.Threading; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Online; using osu.Game.Online.Multiplayer; using osu.Game.Online.Rooms; using osu.Game.Overlays; using osu.Game.Overlays.Dialog; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Screens.OnlinePlay.Components; using osu.Game.Screens.OnlinePlay.Match; using osu.Game.Screens.OnlinePlay.Match.Components; using osu.Game.Screens.OnlinePlay.Multiplayer.Match; using osu.Game.Screens.OnlinePlay.Multiplayer.Participants; using osu.Game.Screens.OnlinePlay.Multiplayer.Spectate; using osu.Game.Screens.Play; using osu.Game.Screens.Play.HUD; using osu.Game.Users; using osuTK; using ParticipantsList = osu.Game.Screens.OnlinePlay.Multiplayer.Participants.ParticipantsList; namespace osu.Game.Screens.OnlinePlay.Multiplayer { [Cached] public class MultiplayerMatchSubScreen : RoomSubScreen, IHandlePresentBeatmap { public override string Title { get; } public override string ShortTitle => "room"; [Resolved] private MultiplayerClient client { get; set; } [Resolved] private OngoingOperationTracker ongoingOperationTracker { get; set; } private readonly IBindable<bool> isConnected = new Bindable<bool>(); [CanBeNull] private IDisposable readyClickOperation; public MultiplayerMatchSubScreen(Room room) : base(room) { Title = room.RoomID.Value == null ? "New room" : room.Name.Value; Activity.Value = new UserActivity.InLobby(room); } protected override void LoadComplete() { base.LoadComplete(); SelectedItem.BindTo(client.CurrentMatchPlayingItem); BeatmapAvailability.BindValueChanged(updateBeatmapAvailability, true); UserMods.BindValueChanged(onUserModsChanged); client.LoadRequested += onLoadRequested; client.RoomUpdated += onRoomUpdated; isConnected.BindTo(client.IsConnected); isConnected.BindValueChanged(connected => { if (!connected.NewValue) handleRoomLost(); }, true); } protected override Drawable CreateMainContent() => new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { new Drawable[] { new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Horizontal = 5, Vertical = 10 }, Child = new GridContainer { RelativeSizeAxes = Axes.Both, ColumnDimensions = new[] { new Dimension(GridSizeMode.Relative, size: 0.5f, maxSize: 400), new Dimension(), new Dimension(GridSizeMode.Relative, size: 0.5f, maxSize: 600), }, Content = new[] { new Drawable[] { // Main left column new GridContainer { RelativeSizeAxes = Axes.Both, RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize) }, Content = new[] { new Drawable[] { new ParticipantsListHeader() }, new Drawable[] { new ParticipantsList { RelativeSizeAxes = Axes.Both }, } } }, // Spacer null, // Main right column new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { new Drawable[] { new OverlinedHeader("Beatmap") }, new Drawable[] { new BeatmapSelectionControl { RelativeSizeAxes = Axes.X } }, new[] { UserModsSection = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Margin = new MarginPadding { Top = 10 }, Alpha = 0, Children = new Drawable[] { new OverlinedHeader("Extra mods"), new FillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(10, 0), Children = new Drawable[] { new UserModSelectButton { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Width = 90, Text = "Select", Action = ShowUserModSelect, }, new ModDisplay { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Current = UserMods, Scale = new Vector2(0.8f), }, } }, } }, }, new Drawable[] { new OverlinedHeader("Chat") { Margin = new MarginPadding { Vertical = 5 }, }, }, new Drawable[] { new MatchChatDisplay(Room) { RelativeSizeAxes = Axes.Both } } }, RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize), new Dimension(GridSizeMode.AutoSize), new Dimension(GridSizeMode.AutoSize), new Dimension(GridSizeMode.AutoSize), new Dimension(), } }, } } } } }, }, }; protected override Drawable CreateFooter() => new MultiplayerMatchFooter { OnReadyClick = onReadyClick, OnSpectateClick = onSpectateClick }; protected override RoomSettingsOverlay CreateRoomSettingsOverlay(Room room) => new MultiplayerMatchSettingsOverlay(room); protected override void UpdateMods() { if (SelectedItem.Value == null || client.LocalUser == null) return; // update local mods based on room's reported status for the local user (omitting the base call implementation). // this makes the server authoritative, and avoids the local user potentially setting mods that the server is not aware of (ie. if the match was started during the selection being changed). var ruleset = Ruleset.Value.CreateInstance(); Mods.Value = client.LocalUser.Mods.Select(m => m.ToMod(ruleset)).Concat(SelectedItem.Value.RequiredMods).ToList(); } [Resolved(canBeNull: true)] private DialogOverlay dialogOverlay { get; set; } private bool exitConfirmed; public override bool OnExiting(IScreen next) { // the room may not be left immediately after a disconnection due to async flow, // so checking the IsConnected status is also required. if (client.Room == null || !client.IsConnected.Value) { // room has not been created yet; exit immediately. return base.OnExiting(next); } if (!exitConfirmed && dialogOverlay != null) { if (dialogOverlay.CurrentDialog is ConfirmDialog confirmDialog) confirmDialog.PerformOkAction(); else { dialogOverlay.Push(new ConfirmDialog("Are you sure you want to leave this multiplayer match?", () => { exitConfirmed = true; this.Exit(); })); } return true; } return base.OnExiting(next); } private ModSettingChangeTracker modSettingChangeTracker; private ScheduledDelegate debouncedModSettingsUpdate; private void onUserModsChanged(ValueChangedEvent<IReadOnlyList<Mod>> mods) { modSettingChangeTracker?.Dispose(); if (client.Room == null) return; client.ChangeUserMods(mods.NewValue); modSettingChangeTracker = new ModSettingChangeTracker(mods.NewValue); modSettingChangeTracker.SettingChanged += onModSettingsChanged; } private void onModSettingsChanged(Mod mod) { // Debounce changes to mod settings so as to not thrash the network. debouncedModSettingsUpdate?.Cancel(); debouncedModSettingsUpdate = Scheduler.AddDelayed(() => { if (client.Room == null) return; client.ChangeUserMods(UserMods.Value); }, 500); } private void updateBeatmapAvailability(ValueChangedEvent<BeatmapAvailability> availability) { if (client.Room == null) return; client.ChangeBeatmapAvailability(availability.NewValue); if (availability.NewValue.State != DownloadState.LocallyAvailable) { // while this flow is handled server-side, this covers the edge case of the local user being in a ready state and then deleting the current beatmap. if (client.LocalUser?.State == MultiplayerUserState.Ready) client.ChangeState(MultiplayerUserState.Idle); } else { if (client.LocalUser?.State == MultiplayerUserState.Spectating && (client.Room?.State == MultiplayerRoomState.WaitingForLoad || client.Room?.State == MultiplayerRoomState.Playing)) onLoadRequested(); } } private void onReadyClick() { Debug.Assert(readyClickOperation == null); readyClickOperation = ongoingOperationTracker.BeginOperation(); if (client.IsHost && (client.LocalUser?.State == MultiplayerUserState.Ready || client.LocalUser?.State == MultiplayerUserState.Spectating)) { client.StartMatch() .ContinueWith(t => { // accessing Exception here silences any potential errors from the antecedent task if (t.Exception != null) { // gameplay was not started due to an exception; unblock button. endOperation(); } // gameplay is starting, the button will be unblocked on load requested. }); return; } client.ToggleReady() .ContinueWith(t => endOperation()); void endOperation() { readyClickOperation?.Dispose(); readyClickOperation = null; } } private void onSpectateClick() { Debug.Assert(readyClickOperation == null); readyClickOperation = ongoingOperationTracker.BeginOperation(); client.ToggleSpectate().ContinueWith(t => endOperation()); void endOperation() { readyClickOperation?.Dispose(); readyClickOperation = null; } } private void onRoomUpdated() { // may happen if the client is kicked or otherwise removed from the room. if (client.Room == null) { handleRoomLost(); return; } Scheduler.AddOnce(UpdateMods); } private void handleRoomLost() => Schedule(() => { if (this.IsCurrentScreen()) this.Exit(); else ValidForResume = false; }); private void onLoadRequested() { if (BeatmapAvailability.Value.State != DownloadState.LocallyAvailable) return; // In the case of spectating, IMultiplayerClient.LoadRequested can be fired while the game is still spectating a previous session. // For now, we want to game to switch to the new game so need to request exiting from the play screen. if (!ParentScreen.IsCurrentScreen()) { ParentScreen.MakeCurrent(); Schedule(onLoadRequested); return; } StartPlay(); readyClickOperation?.Dispose(); readyClickOperation = null; } protected override Screen CreateGameplayScreen() { Debug.Assert(client.LocalUser != null); Debug.Assert(client.Room != null); int[] userIds = client.CurrentMatchPlayingUserIds.ToArray(); MultiplayerRoomUser[] users = userIds.Select(id => client.Room.Users.First(u => u.UserID == id)).ToArray(); switch (client.LocalUser.State) { case MultiplayerUserState.Spectating: return new MultiSpectatorScreen(users.Take(PlayerGrid.MAX_PLAYERS).ToArray()); default: return new PlayerLoader(() => new MultiplayerPlayer(Room, SelectedItem.Value, users)); } } public void PresentBeatmap(WorkingBeatmap beatmap, RulesetInfo ruleset) { if (!this.IsCurrentScreen()) return; if (!client.IsHost) { // todo: should handle this when the request queue is implemented. // if we decide that the presentation should exit the user from the multiplayer game, the PresentBeatmap // flow may need to change to support an "unable to present" return value. return; } this.Push(new MultiplayerMatchSongSelect(Room, beatmap, ruleset)); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (client != null) { client.RoomUpdated -= onRoomUpdated; client.LoadRequested -= onLoadRequested; } modSettingChangeTracker?.Dispose(); } } }
// // XmlSerializationReaderInterpreter.cs: // // Author: // Lluis Sanchez Gual (lluis@ximian.com) // // (C) 2002, 2003 Ximian, Inc. http://www.ximian.com // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Reflection; using System.Collections; namespace System.Xml.Serialization { #if CONFIG_SERIALIZATION internal class XmlSerializationReaderInterpreter: XmlSerializationReader { XmlMapping _typeMap; SerializationFormat _format; static readonly XmlQualifiedName AnyType = new XmlQualifiedName("anyType", System.Xml.Schema.XmlSchema.Namespace); public XmlSerializationReaderInterpreter(XmlMapping typeMap) { _typeMap = typeMap; _format = typeMap.Format; } protected override void InitCallbacks () { ArrayList maps = _typeMap.RelatedMaps; if (maps != null) { foreach (XmlTypeMapping map in maps) { if (map.TypeData.SchemaType == SchemaTypes.Class || map.TypeData.SchemaType == SchemaTypes.Enum) { ReaderCallbackInfo info = new ReaderCallbackInfo (this, map); AddReadCallback (map.XmlType, map.Namespace, map.TypeData.Type, new XmlSerializationReadCallback (info.ReadObject)); } } } } protected override void InitIDs () { } protected XmlTypeMapping GetTypeMap (Type type) { ArrayList maps = _typeMap.RelatedMaps; if (maps != null) { foreach (XmlTypeMapping map in maps) if (map.TypeData.Type == type) return map; } throw new InvalidOperationException ("Type " + type + " not mapped"); } public object ReadRoot () { Reader.MoveToContent(); if (_typeMap is XmlTypeMapping) { if (_format == SerializationFormat.Literal) return ReadRoot ((XmlTypeMapping)_typeMap); else return ReadEncodedObject ((XmlTypeMapping)_typeMap); } else return ReadMessage ((XmlMembersMapping)_typeMap); } object ReadEncodedObject (XmlTypeMapping typeMap) { object ob = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == typeMap.ElementName && Reader.NamespaceURI == typeMap.Namespace) ob = ReadReferencedElement(); else throw CreateUnknownNodeException(); } else UnknownNode(null); ReadReferencedElements(); return ob; } protected virtual object ReadMessage (XmlMembersMapping typeMap) { object[] parameters = new object[typeMap.Count]; if (typeMap.HasWrapperElement) { if (_format == SerializationFormat.Encoded) { while (Reader.NodeType == System.Xml.XmlNodeType.Element) { string root = Reader.GetAttribute ("root", XmlSerializer.EncodingNamespace); if (root == null || System.Xml.XmlConvert.ToBoolean(root)) break; ReadReferencedElement (); Reader.MoveToContent (); } } while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.IsStartElement(typeMap.ElementName, typeMap.Namespace) || _format == SerializationFormat.Encoded) { if (Reader.IsEmptyElement) { Reader.Skip(); Reader.MoveToContent(); continue; } Reader.ReadStartElement(); ReadMembers ((ClassMap)typeMap.ObjectMap, parameters, true, false); ReadEndElement(); break; } else UnknownNode(null); Reader.MoveToContent(); } } else ReadMembers ((ClassMap)typeMap.ObjectMap, parameters, true, _format == SerializationFormat.Encoded); if (_format == SerializationFormat.Encoded) ReadReferencedElements(); return parameters; } object ReadRoot (XmlTypeMapping rootMap) { if (rootMap.TypeData.SchemaType == SchemaTypes.XmlNode) { return ReadXmlNodeElement (rootMap, true); } else { if (Reader.LocalName != rootMap.ElementName || Reader.NamespaceURI != rootMap.Namespace) throw CreateUnknownNodeException(); return ReadObject (rootMap, true, true); } } protected virtual object ReadObject (XmlTypeMapping typeMap, bool isNullable, bool checkType) { switch (typeMap.TypeData.SchemaType) { case SchemaTypes.Class: return ReadClassInstance (typeMap, isNullable, checkType); case SchemaTypes.Array: return ReadListElement (typeMap, isNullable, null, true); case SchemaTypes.XmlNode: return ReadXmlNodeElement (typeMap, isNullable); case SchemaTypes.Primitive: return ReadPrimitiveElement (typeMap, isNullable); case SchemaTypes.Enum: return ReadEnumElement (typeMap, isNullable); case SchemaTypes.XmlSerializable: return ReadXmlSerializableElement (typeMap, isNullable); default: throw new Exception ("Unsupported map type"); } } protected virtual object ReadClassInstance (XmlTypeMapping typeMap, bool isNullable, bool checkType) { if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t != null) { XmlTypeMapping realMap = typeMap.GetRealElementMap (t.Name, t.Namespace); if (realMap == null) { if (typeMap.TypeData.Type == typeof(object)) return ReadTypedPrimitive (t); else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)t); } if (realMap != typeMap) return ReadObject (realMap, false, false); } else if (typeMap.TypeData.Type == typeof(object)) return ReadTypedPrimitive (AnyType); } object ob = Activator.CreateInstance (typeMap.TypeData.Type); Reader.MoveToElement(); bool isEmpty = Reader.IsEmptyElement; ReadClassInstanceMembers (typeMap, ob); if (isEmpty) Reader.Skip(); else ReadEndElement(); return ob; } protected virtual void ReadClassInstanceMembers (XmlTypeMapping typeMap, object ob) { ReadMembers ((ClassMap) typeMap.ObjectMap, ob, false, false); } void ReadMembers (ClassMap map, object ob, bool isValueList, bool readByOrder) { // Set the default values of the members if (map.MembersWithDefault != null) { ArrayList members = map.MembersWithDefault; for (int n=0; n<members.Count; n++) { XmlTypeMapMember mem = (XmlTypeMapMember) members[n]; SetMemberValueFromAttr (mem, ob, mem.DefaultValue, isValueList); } } // Reads attributes XmlTypeMapMember anyAttrMember = map.DefaultAnyAttributeMember; int anyAttributeIndex = 0; object anyAttributeArray = null; while (Reader.MoveToNextAttribute()) { XmlTypeMapMemberAttribute member = map.GetAttribute (Reader.LocalName, Reader.NamespaceURI); if (member != null) { SetMemberValue (member, ob, GetValueFromXmlString (Reader.Value, member.TypeData, member.MappedType), isValueList); } else if (IsXmlnsAttribute(Reader.Name)) { // If the map has NamespaceDeclarations, // then store this xmlns to the given member. // If the instance doesn't exist, then create. if (map.NamespaceDeclarations != null) { XmlSerializerNamespaces nss = this.GetMemberValue (map.NamespaceDeclarations, ob, isValueList) as XmlSerializerNamespaces; if (nss == null) { nss = new XmlSerializerNamespaces (); SetMemberValue (map.NamespaceDeclarations, ob, nss, isValueList); } if (Reader.Prefix == "xmlns") nss.Add (Reader.LocalName, Reader.Value); else nss.Add ("", Reader.Value); } } else if (anyAttrMember != null) { XmlAttribute attr = (XmlAttribute) Document.ReadNode(Reader); ParseWsdlArrayType (attr); AddListValue (anyAttrMember.TypeData, ref anyAttributeArray, anyAttributeIndex++, attr, true); } else ProcessUnknownAttribute(ob); } if (anyAttrMember != null) { anyAttributeArray = ShrinkArray ((Array)anyAttributeArray, anyAttributeIndex, anyAttrMember.TypeData.Type.GetElementType(), true); SetMemberValue (anyAttrMember, ob, anyAttributeArray, isValueList); } if (!isValueList) { Reader.MoveToElement(); if (Reader.IsEmptyElement) return; Reader.ReadStartElement(); } // Reads elements bool[] readFlag = new bool[(map.ElementMembers != null) ? map.ElementMembers.Count : 0]; bool hasAnyReturnMember = (isValueList && _format == SerializationFormat.Encoded && map.ReturnMember != null && map.ReturnMember.TypeData.Type == typeof(object)); Reader.MoveToContent(); int[] indexes = null; object[] flatLists = null; Fixup fixup = null; int ind = 0; int maxInd; if (readByOrder) { if (map.ElementMembers != null) maxInd = map.ElementMembers.Count; else maxInd = 0; } else maxInd = int.MaxValue; if (map.FlatLists != null) { indexes = new int[map.FlatLists.Count]; flatLists = new object[map.FlatLists.Count]; foreach (XmlTypeMapMemberExpandable mem in map.FlatLists) if (IsReadOnly (mem, ob, isValueList)) flatLists[mem.FlatArrayIndex] = mem.GetValue (ob); } if (_format == SerializationFormat.Encoded && map.ElementMembers != null) { FixupCallbackInfo info = new FixupCallbackInfo (this, map, isValueList); fixup = new Fixup(ob, new XmlSerializationFixupCallback(info.FixupMembers), map.ElementMembers.Count); AddFixup (fixup); } while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && (ind < maxInd)) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { XmlTypeMapElementInfo info; if (readByOrder) { info = map.GetElement (ind++); } else if (hasAnyReturnMember) { info = (XmlTypeMapElementInfo) ((XmlTypeMapMemberElement)map.ReturnMember).ElementInfo[0]; hasAnyReturnMember = false; } else info = map.GetElement (Reader.LocalName, Reader.NamespaceURI); if (info != null && !readFlag[info.Member.Index] ) { if (info.Member.GetType() == typeof (XmlTypeMapMemberList)) { if (_format == SerializationFormat.Encoded && info.MultiReferenceType) { object list = ReadReferencingElement (out fixup.Ids[info.Member.Index]); if (fixup.Ids[info.Member.Index] == null) // Already read { if (IsReadOnly (info.Member, ob, isValueList)) throw CreateReadOnlyCollectionException (info.TypeData.FullTypeName); else SetMemberValue (info.Member, ob, list, isValueList); } else if (!info.MappedType.TypeData.Type.IsArray) { if (IsReadOnly (info.Member, ob, isValueList)) list = GetMemberValue (info.Member, ob, isValueList); else { list = CreateList (info.MappedType.TypeData.Type); SetMemberValue (info.Member, ob, list, isValueList); } AddFixup (new CollectionFixup (list, new XmlSerializationCollectionFixupCallback (FillList), fixup.Ids[info.Member.Index])); fixup.Ids[info.Member.Index] = null; // The member already has the value, no further fix needed. } } else { if (IsReadOnly (info.Member, ob, isValueList)) ReadListElement (info.MappedType, info.IsNullable, GetMemberValue (info.Member, ob, isValueList), false); else SetMemberValue (info.Member, ob, ReadListElement (info.MappedType, info.IsNullable, null, true), isValueList); } readFlag[info.Member.Index] = true; } else if (info.Member.GetType() == typeof (XmlTypeMapMemberFlatList)) { XmlTypeMapMemberFlatList mem = (XmlTypeMapMemberFlatList)info.Member; AddListValue (mem.TypeData, ref flatLists[mem.FlatArrayIndex], indexes[mem.FlatArrayIndex]++, ReadObjectElement (info), !IsReadOnly (info.Member, ob, isValueList)); } else if (info.Member.GetType() == typeof (XmlTypeMapMemberAnyElement)) { XmlTypeMapMemberAnyElement mem = (XmlTypeMapMemberAnyElement)info.Member; if (mem.TypeData.IsListType) AddListValue (mem.TypeData, ref flatLists[mem.FlatArrayIndex], indexes[mem.FlatArrayIndex]++, ReadXmlNode (mem.TypeData.ListItemTypeData, false), true); else SetMemberValue (mem, ob, ReadXmlNode (mem.TypeData, false), isValueList); } else if (info.Member.GetType() == typeof(XmlTypeMapMemberElement)) { object val; readFlag[info.Member.Index] = true; if (_format == SerializationFormat.Encoded) { val = ReadReferencingElement (out fixup.Ids[info.Member.Index]); if (info.MultiReferenceType) { if (fixup.Ids[info.Member.Index] == null) // already read SetMemberValue (info.Member, ob, val, isValueList); } else if (val != null) SetMemberValue (info.Member, ob, val, isValueList); } else SetMemberValue (info.Member, ob, ReadObjectElement (info), isValueList); } else throw new InvalidOperationException ("Unknown member type"); } else if (map.DefaultAnyElementMember != null) { XmlTypeMapMemberAnyElement mem = map.DefaultAnyElementMember; if (mem.TypeData.IsListType) AddListValue (mem.TypeData, ref flatLists[mem.FlatArrayIndex], indexes[mem.FlatArrayIndex]++, ReadXmlNode (mem.TypeData.ListItemTypeData, false), true); else SetMemberValue (mem, ob, ReadXmlNode (mem.TypeData, false), isValueList); } else ProcessUnknownElement(ob); } else if (Reader.NodeType == System.Xml.XmlNodeType.Text && map.XmlTextCollector != null) { if (map.XmlTextCollector is XmlTypeMapMemberExpandable) { XmlTypeMapMemberExpandable mem = (XmlTypeMapMemberExpandable)map.XmlTextCollector; XmlTypeMapMemberFlatList flatl = mem as XmlTypeMapMemberFlatList; TypeData itype = (flatl == null) ? mem.TypeData.ListItemTypeData : flatl.ListMap.FindTextElement().TypeData; object val = (itype.Type == typeof (string)) ? (object) Reader.ReadString() : (object) ReadXmlNode (itype, false); AddListValue (mem.TypeData, ref flatLists[mem.FlatArrayIndex], indexes[mem.FlatArrayIndex]++, val, true); } else { XmlTypeMapMemberElement mem = (XmlTypeMapMemberElement) map.XmlTextCollector; XmlTypeMapElementInfo info = (XmlTypeMapElementInfo) mem.ElementInfo [0]; if (info.TypeData.Type == typeof (string)) SetMemberValue (mem, ob, ReadString ((string) GetMemberValue (mem, ob, isValueList)), isValueList); else SetMemberValue (mem, ob, GetValueFromXmlString (Reader.ReadString(), info.TypeData, info.MappedType), isValueList); } } else UnknownNode(ob); Reader.Read(); Reader.MoveToContent(); } if (flatLists != null) { foreach (XmlTypeMapMemberExpandable mem in map.FlatLists) { Object list = flatLists[mem.FlatArrayIndex]; if (mem.TypeData.Type.IsArray) list = ShrinkArray ((Array)list, indexes[mem.FlatArrayIndex], mem.TypeData.Type.GetElementType(), true); if (!IsReadOnly (mem, ob, isValueList)) SetMemberValue (mem, ob, list, isValueList); } } } internal void FixupMembers (ClassMap map, object obfixup, bool isValueList) { Fixup fixup = (Fixup)obfixup; ICollection members = map.ElementMembers; string[] ids = fixup.Ids; foreach (XmlTypeMapMember member in members) { if (ids[member.Index] != null) SetMemberValue (member, fixup.Source, GetTarget(ids[member.Index]), isValueList); } } protected virtual void ProcessUnknownAttribute (object target) { UnknownNode (target); } protected virtual void ProcessUnknownElement (object target) { UnknownNode (target); } bool IsReadOnly (XmlTypeMapMember member, object ob, bool isValueList) { if (isValueList) return false; else return member.IsReadOnly (ob.GetType()); } void SetMemberValue (XmlTypeMapMember member, object ob, object value, bool isValueList) { if (isValueList) ((object[])ob)[member.Index] = value; else { member.SetValue (ob, value); if (member.IsOptionalValueType) member.SetValueSpecified (ob, true); } } void SetMemberValueFromAttr (XmlTypeMapMember member, object ob, object value, bool isValueList) { // Enumeration values specified in custom attributes are stored as integer // values if the custom attribute property is of type object. So, it is // necessary to convert to the enum type before asigning the value to the field. if (member.TypeData.Type.IsEnum) value = Enum.ToObject (member.TypeData.Type, value); SetMemberValue (member, ob, value, isValueList); } object GetMemberValue (XmlTypeMapMember member, object ob, bool isValueList) { if (isValueList) return ((object[])ob)[member.Index]; else return member.GetValue (ob); } object ReadObjectElement (XmlTypeMapElementInfo elem) { switch (elem.TypeData.SchemaType) { case SchemaTypes.XmlNode: return ReadXmlNode (elem.TypeData, true); case SchemaTypes.Primitive: case SchemaTypes.Enum: return ReadPrimitiveValue (elem); case SchemaTypes.Array: return ReadListElement (elem.MappedType, elem.IsNullable, null, true); case SchemaTypes.Class: return ReadObject (elem.MappedType, elem.IsNullable, true); case SchemaTypes.XmlSerializable: object ob = Activator.CreateInstance (elem.TypeData.Type); return ReadSerializable ((IXmlSerializable)ob); default: throw new NotSupportedException ("Invalid value type"); } } object ReadPrimitiveValue (XmlTypeMapElementInfo elem) { if (elem.TypeData.Type == typeof (XmlQualifiedName)) { if (elem.IsNullable) return ReadNullableQualifiedName (); else return ReadElementQualifiedName (); } else if (elem.IsNullable) return GetValueFromXmlString (ReadNullableString (), elem.TypeData, elem.MappedType); else return GetValueFromXmlString (Reader.ReadElementString (), elem.TypeData, elem.MappedType); } object GetValueFromXmlString (string value, TypeData typeData, XmlTypeMapping typeMap) { if (typeData.SchemaType == SchemaTypes.Array) return ReadListString (typeMap, value); else if (typeData.SchemaType == SchemaTypes.Enum) return GetEnumValue (typeMap, value); else if (typeData.Type == typeof (XmlQualifiedName)) return ToXmlQualifiedName (value); else return XmlCustomFormatter.FromXmlString (typeData, value); } object ReadListElement (XmlTypeMapping typeMap, bool isNullable, object list, bool canCreateInstance) { Type listType = typeMap.TypeData.Type; ListMap listMap = (ListMap)typeMap.ObjectMap; if (ReadNull()) return null; if (list == null) { if (canCreateInstance) list = CreateList (listType); else throw CreateReadOnlyCollectionException (typeMap.TypeFullName); } if (Reader.IsEmptyElement) { Reader.Skip(); if (listType.IsArray) list = ShrinkArray ((Array)list, 0, listType.GetElementType(), isNullable); return list; } int index = 0; Reader.ReadStartElement(); Reader.MoveToContent(); while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { XmlTypeMapElementInfo elemInfo = listMap.FindElement (Reader.LocalName, Reader.NamespaceURI); if (elemInfo != null) AddListValue (typeMap.TypeData, ref list, index++, ReadObjectElement (elemInfo), false); else UnknownNode(null); } else UnknownNode(null); Reader.MoveToContent(); } ReadEndElement(); if (listType.IsArray) list = ShrinkArray ((Array)list, index, listType.GetElementType(), isNullable); return list; } object ReadListString (XmlTypeMapping typeMap, string values) { Type listType = typeMap.TypeData.Type; ListMap listMap = (ListMap)typeMap.ObjectMap; values = values.Trim (); if (values == string.Empty) { return Array.CreateInstance (listType.GetElementType(), 0); } string[] valueArray = values.Split (' '); Array list = Array.CreateInstance (listType.GetElementType(), valueArray.Length); XmlTypeMapElementInfo info = (XmlTypeMapElementInfo)listMap.ItemInfo[0]; for (int index = 0; index < valueArray.Length; index++) list.SetValue (GetValueFromXmlString (valueArray[index], info.TypeData, info.MappedType), index); return list; } void AddListValue (TypeData listType, ref object list, int index, object value, bool canCreateInstance) { Type type = listType.Type; if (type.IsArray) { list = EnsureArrayIndex ((Array)list, index, type.GetElementType()); ((Array)list).SetValue (value, index); } else // Must be IEnumerable { if (list == null) { if (canCreateInstance) list = Activator.CreateInstance (type); else throw CreateReadOnlyCollectionException (type.FullName); } MethodInfo mi = type.GetMethod ("Add", new Type[] {listType.ListItemType} ); mi.Invoke (list, new object[] { value }); } } object CreateList (Type listType) { if (listType.IsArray) return EnsureArrayIndex (null, 0, listType.GetElementType()); else return Activator.CreateInstance (listType); } void FillList (object list, object items) { CopyEnumerableList (items, list); } void CopyEnumerableList (object source, object dest) { if (dest == null) throw CreateReadOnlyCollectionException (source.GetType().FullName); object[] param = new object[1]; MethodInfo mi = dest.GetType().GetMethod ("Add"); foreach (object ob in (IEnumerable)source) { param[0] = ob; mi.Invoke (dest, param); } } int GetListCount (TypeData listType, object ob) { if (listType.Type.IsArray) return ((Array)ob).Length; else return (int) listType.Type.GetProperty ("Count").GetValue(ob,null); } object ReadXmlNodeElement (XmlTypeMapping typeMap, bool isNullable) { return ReadXmlNode (typeMap.TypeData, false); } object ReadXmlNode (TypeData type, bool wrapped) { if (type.Type == typeof (XmlDocument)) return ReadXmlDocument (wrapped); else return ReadXmlNode (wrapped); } object ReadPrimitiveElement (XmlTypeMapping typeMap, bool isNullable) { XmlQualifiedName t = GetXsiType(); if (t == null) t = new XmlQualifiedName (typeMap.XmlType, typeMap.Namespace); return ReadTypedPrimitive (t); } object ReadEnumElement (XmlTypeMapping typeMap, bool isNullable) { Reader.ReadStartElement (); object o = GetEnumValue (typeMap, Reader.ReadString()); Reader.ReadEndElement (); return o; } object GetEnumValue (XmlTypeMapping typeMap, string val) { EnumMap map = (EnumMap) typeMap.ObjectMap; string ev = map.GetEnumName (val); if (ev == null) throw CreateUnknownConstantException (val, typeMap.TypeData.Type); return Enum.Parse (typeMap.TypeData.Type, ev); } object ReadXmlSerializableElement (XmlTypeMapping typeMap, bool isNullable) { Reader.MoveToContent (); if (Reader.NodeType == XmlNodeType.Element) { if (Reader.LocalName == typeMap.ElementName && Reader.NamespaceURI == typeMap.Namespace) { object ob = Activator.CreateInstance (typeMap.TypeData.Type); return ReadSerializable ((IXmlSerializable)ob); } else throw CreateUnknownNodeException (); } else { UnknownNode (null); return null; } } class FixupCallbackInfo { XmlSerializationReaderInterpreter _sri; ClassMap _map; bool _isValueList; public FixupCallbackInfo (XmlSerializationReaderInterpreter sri, ClassMap map, bool isValueList) { _sri = sri; _map = map; _isValueList = isValueList; } public void FixupMembers (object fixup) { _sri.FixupMembers (_map, fixup, _isValueList); } } class ReaderCallbackInfo { XmlSerializationReaderInterpreter _sri; XmlTypeMapping _typeMap; public ReaderCallbackInfo (XmlSerializationReaderInterpreter sri, XmlTypeMapping typeMap) { _sri = sri; _typeMap = typeMap; } internal object ReadObject () { return _sri.ReadObject (_typeMap, true, true); } } } #endif // CONFIG_SERIALIZATION }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class ChallengeDecoder { public const ushort BLOCK_LENGTH = 16; public const ushort TEMPLATE_ID = 7; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 7; private ChallengeDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public ChallengeDecoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public ChallengeDecoder Wrap( IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { this._buffer = buffer; this._offset = offset; this._actingBlockLength = actingBlockLength; this._actingVersion = actingVersion; Limit(offset + actingBlockLength); return this; } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int CorrelationIdId() { return 1; } public static int CorrelationIdSinceVersion() { return 0; } public static int CorrelationIdEncodingOffset() { return 0; } public static int CorrelationIdEncodingLength() { return 8; } public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public long CorrelationId() { return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian); } public static int ClusterSessionIdId() { return 2; } public static int ClusterSessionIdSinceVersion() { return 0; } public static int ClusterSessionIdEncodingOffset() { return 8; } public static int ClusterSessionIdEncodingLength() { return 8; } public static string ClusterSessionIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long ClusterSessionIdNullValue() { return -9223372036854775808L; } public static long ClusterSessionIdMinValue() { return -9223372036854775807L; } public static long ClusterSessionIdMaxValue() { return 9223372036854775807L; } public long ClusterSessionId() { return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian); } public static int EncodedChallengeId() { return 3; } public static int EncodedChallengeSinceVersion() { return 0; } public static string EncodedChallengeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int EncodedChallengeHeaderLength() { return 4; } public int EncodedChallengeLength() { int limit = _parentMessage.Limit(); return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); } public int GetEncodedChallenge(IMutableDirectBuffer dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public int GetEncodedChallenge(byte[] dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[Challenge](sbeTemplateId="); builder.Append(TEMPLATE_ID); builder.Append("|sbeSchemaId="); builder.Append(SCHEMA_ID); builder.Append("|sbeSchemaVersion="); if (_parentMessage._actingVersion != SCHEMA_VERSION) { builder.Append(_parentMessage._actingVersion); builder.Append('/'); } builder.Append(SCHEMA_VERSION); builder.Append("|sbeBlockLength="); if (_actingBlockLength != BLOCK_LENGTH) { builder.Append(_actingBlockLength); builder.Append('/'); } builder.Append(BLOCK_LENGTH); builder.Append("):"); //Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("CorrelationId="); builder.Append(CorrelationId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='clusterSessionId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("ClusterSessionId="); builder.Append(ClusterSessionId()); builder.Append('|'); //Token{signal=BEGIN_VAR_DATA, name='encodedChallenge', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("EncodedChallenge="); builder.Append(EncodedChallengeLength() + " raw bytes"); Limit(originalLimit); return builder; } } }
namespace AngleSharp.Html { using AngleSharp.Dom; using AngleSharp.Html.Forms; using AngleSharp.Html.Forms.Submitters; using AngleSharp.Io.Dom; using AngleSharp.Text; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; /// <summary> /// Bundles information stored in HTML forms. /// </summary> public sealed class FormDataSet : IEnumerable<String> { #region Fields private readonly List<FormDataSetEntry> _entries; private String _boundary; #endregion #region ctor /// <summary> /// Creates a new form data set with a randomly generated boundary. /// </summary> public FormDataSet() { _boundary = Guid.NewGuid().ToString(); _entries = new List<FormDataSetEntry>(); } #endregion #region Properties /// <summary> /// Gets the chosen boundary. /// </summary> public String Boundary => _boundary; #endregion #region Methods /// <summary> /// Applies the multipart/form-data algorithm. /// http://www.w3.org/html/wg/drafts/html/master/forms.html#multipart/form-data-encoding-algorithm /// </summary> /// <param name="htmlEncoder">HTML encoder.</param> /// <param name="encoding">(Optional) Explicit encoding.</param> /// <returns>A stream containing the body.</returns> public Stream AsMultipart(IHtmlEncoder htmlEncoder, Encoding? encoding = null) { return BuildRequestContent(encoding, stream => Connect(new MultipartFormDataSetVisitor(htmlEncoder, stream.Encoding, _boundary), stream)); } /// <summary> /// Applies the urlencoded algorithm. /// http://www.w3.org/html/wg/drafts/html/master/forms.html#application/x-www-form-urlencoded-encoding-algorithm /// </summary> /// <param name="encoding">(Optional) Explicit encoding.</param> /// <returns>A stream containing the body.</returns> public Stream AsUrlEncoded(Encoding? encoding = null) { return BuildRequestContent(encoding, stream => Connect(new UrlEncodedFormDataSetVisitor(stream.Encoding), stream)); } /// <summary> /// Applies the plain encoding algorithm. /// http://www.w3.org/html/wg/drafts/html/master/forms.html#text/plain-encoding-algorithm /// </summary> /// <param name="encoding">(Optional) Explicit encoding.</param> /// <returns>A stream containing the body.</returns> public Stream AsPlaintext(Encoding? encoding = null) { return BuildRequestContent(encoding, stream => Connect(new PlaintextFormDataSetVisitor(), stream)); } /// <summary> /// Applies the application json encoding algorithm. /// https://darobin.github.io/formic/specs/json/#the-application-json-encoding-algorithm /// </summary> /// <returns>A stream containing the body.</returns> public Stream AsJson() { return BuildRequestContent(TextEncoding.Utf8, stream => Connect(new JsonFormDataSetVisitor(), stream)); } /// <summary> /// Applies the given submitter to serialize the form data set. /// </summary> /// <param name="submitter">The algorithm to use.</param> /// <param name="encoding">(Optional) Explicit encoding.</param> /// <returns>A stream containing the body.</returns> public Stream As(IFormSubmitter submitter, Encoding? encoding = null) { return BuildRequestContent(encoding, stream => Connect(submitter, stream)); } /// <summary> /// Appends a text entry to the form data set. /// </summary> /// <param name="name">The name of the entry.</param> /// <param name="value">The value of the entry.</param> /// <param name="type">The type of the entry.</param> public void Append(String name, String value, String type) { if (type.Isi(InputTypeNames.Radio)) { // If same name radio entry already exist, drop it. var earlierEntry = _entries.FirstOrDefault(s => s.Name.Is(name) && s.Type.Isi(InputTypeNames.Radio)); if (earlierEntry != null) { _entries.Remove(earlierEntry); } } if (type.Isi(TagNames.Textarea)) { name = name.NormalizeLineEndings(); value = value.NormalizeLineEndings(); } _entries.Add(new TextDataSetEntry(name, value, type)); } /// <summary> /// Appends a file entry to the form data set. /// </summary> /// <param name="name">The name of the entry.</param> /// <param name="value">The value of the entry.</param> /// <param name="type">The type of the entry.</param> public void Append(String name, IFile value, String type) { if (type.Isi(InputTypeNames.File)) { name = name.NormalizeLineEndings(); } _entries.Add(new FileDataSetEntry(name, value, type)); } #endregion #region Helpers private Stream BuildRequestContent(Encoding? encoding, Action<StreamWriter> process) { encoding ??= TextEncoding.Utf8; var ms = new MemoryStream(); FixPotentialBoundaryCollisions(encoding); ReplaceCharset(encoding); var tw = new StreamWriter(ms, encoding); process(tw); tw.Flush(); ms.Position = 0; return ms; } private void Connect(IFormSubmitter submitter, StreamWriter stream) { foreach (var entry in _entries) { entry.Accept(submitter); } submitter.Serialize(stream); } private void ReplaceCharset(Encoding encoding) { for (var i = 0; i < _entries.Count; i++ ) { var entry = _entries[i]; if (!String.IsNullOrEmpty(entry.Name) && entry.Name is "_charset_" && entry.Type.Isi(InputTypeNames.Hidden)) { _entries[i] = new TextDataSetEntry(entry.Name, encoding.WebName, entry.Type); } } } private void FixPotentialBoundaryCollisions(Encoding encoding) { var found = false; do { for (var i = 0; i < _entries.Count; i++) { if (found = _entries[i].Contains(_boundary, encoding)) { _boundary = Guid.NewGuid().ToString(); break; } } } while (found); } #endregion #region IEnumerable Implementation /// <summary> /// Gets an enumerator over all entry names. /// </summary> /// <returns>The enumerator.</returns> public IEnumerator<String> GetEnumerator() { return _entries.Select(m => m.Name).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }
'From Squeak3.7alpha of 11 September 2003 [latest update: #5764] on 4 March 2004 at 3:17:54 pm'! "Change Set: q13-resizeBook-sw Date: 7 June 2003 Author: Scott Wallace Derived from Squeakland updates: 0166fullScreenBookFix (4 March 2003) 0176pageSize-sw (7 June 2003) 0177storyBdFix-sw (25 July 2003) Makes the resize handle on a BookMorph or StackMorph or TabbedPalette behave the way any reasonable person would expect. Finally, after all these years. Also adds an option for any BookMorph or StackMorph to have all its pages be maintained at the same dimensions. Also, a bug fix: In a bookMorph's full-screen mode, going to a different page was resulting in the disappearance and non-recoverability of the floating page controls"! !BooklikeMorph methodsFor: 'page controls' stamp: 'sw 6/6/2003 14:10'! addPageControlMorph: aMorph "Add the morph provided as a page control, at the appropriate place" aMorph setProperty: #pageControl toValue: true. self addMorph: aMorph asElementNumber: self indexForPageControls! ! !BooklikeMorph methodsFor: 'page controls' stamp: 'sw 6/6/2003 17:00'! indexForPageControls "Answer which submorph should hold the page controls" ^ (submorphs size > 0 and: [submorphs first hasProperty: #header]) ifTrue: [2] ifFalse: [1]! ! !BooklikeMorph methodsFor: 'page controls' stamp: 'sw 6/6/2003 22:44'! setEventHandlerForPageControls: controls "Set the controls' event handler if appropriate. Default is to let the tool be dragged by the controls" controls eventHandler: (EventHandler new on: #mouseDown send: #move to: self)! ! !BooklikeMorph methodsFor: 'page controls' stamp: 'sw 6/6/2003 13:58'! showPageControls: controlSpecs "Remove any existing page controls, and add fresh controls at the top of the receiver (or in position 2 if the receiver's first submorph is one with property #header). Add a single column of controls." | pageControls column | self hidePageControls. column _ AlignmentMorph newColumn beTransparent. pageControls _ self makePageControlsFrom: controlSpecs. pageControls borderWidth: 0; layoutInset: 4. pageControls beSticky. pageControls setNameTo: 'Page Controls'. self setEventHandlerForPageControls: pageControls. column addMorphBack: pageControls. self addPageControlMorph: column! ! !BookMorph methodsFor: 'menu' stamp: 'sw 3/3/2004 18:40'! invokeBookMenu "Invoke the book's control panel menu." | aMenu | aMenu _ MenuMorph new defaultTarget: self. aMenu addTitle: 'Book' translated. aMenu addStayUpItem. aMenu add: 'find...' translated action: #textSearch. aMenu add: 'go to page...' translated action: #goToPage. aMenu addLine. aMenu addList: { {'sort pages' translated. #sortPages}. {'uncache page sorter' translated. #uncachePageSorter}}. (self hasProperty: #dontWrapAtEnd) ifTrue: [aMenu add: 'wrap after last page' translated selector: #setWrapPages: argument: true] ifFalse: [aMenu add: 'stop at last page' translated selector: #setWrapPages: argument: false]. aMenu addList: { {'make bookmark' translated. #bookmarkForThisPage}. {'make thumbnail' translated. #thumbnailForThisPage}}. aMenu addUpdating: #showingPageControlsString action: #toggleShowingOfPageControls. aMenu addUpdating: #showingFullScreenString action: #toggleFullScreen. aMenu addLine. aMenu add: 'sound effect for all pages' translated action: #menuPageSoundForAll:. aMenu add: 'sound effect this page only' translated action: #menuPageSoundForThisPage:. aMenu add: 'visual effect for all pages' translated action: #menuPageVisualForAll:. aMenu add: 'visual effect this page only' translated action: #menuPageVisualForThisPage:. aMenu addLine. (self primaryHand pasteBuffer class isKindOf: PasteUpMorph class) ifTrue: [aMenu add: 'paste book page' translated action: #pasteBookPage]. aMenu add: 'save as new-page prototype' translated action: #setNewPagePrototype. newPagePrototype ifNotNil: [ aMenu add: 'clear new-page prototype' translated action: #clearNewPagePrototype]. aMenu add: (self dragNDropEnabled ifTrue: ['close dragNdrop'] ifFalse: ['open dragNdrop']) translated action: #toggleDragNDrop. aMenu add: 'make all pages this size' translated action: #makeUniformPageSize. aMenu addUpdating: #keepingUniformPageSizeString target: self action: #toggleMaintainUniformPageSize. aMenu addLine. aMenu add: 'send all pages to server' translated action: #savePagesOnURL. aMenu add: 'send this page to server' translated action: #saveOneOnURL. aMenu add: 'reload all from server' translated action: #reload. aMenu add: 'copy page url to clipboard' translated action: #copyUrl. aMenu add: 'keep in one file' translated action: #keepTogether. aMenu addLine. aMenu add: 'load PPT images from slide #1' translated action: #loadImagesIntoBook. aMenu add: 'background color for all pages...' translated action: #setPageColor. aMenu add: 'make a thread of projects in this book' translated action: #buildThreadOfProjects. aMenu popUpEvent: self world activeHand lastEvent in: self world ! ! !BookMorph methodsFor: 'other' stamp: 'sw 6/6/2003 13:55'! adjustCurrentPageForFullScreen "Adjust current page to conform to whether or not I am in full-screen mode. Also, enforce uniform page size constraint if appropriate" self isInFullScreenMode ifTrue: [(currentPage hasProperty: #sizeWhenNotFullScreen) ifFalse: [currentPage setProperty: #sizeWhenNotFullScreen toValue: currentPage extent]. currentPage extent: Display extent] ifFalse: [(currentPage hasProperty: #sizeWhenNotFullScreen) ifTrue: [currentPage extent: (currentPage valueOfProperty: #sizeWhenNotFullScreen). currentPage removeProperty: #sizeWhenNotFullScreen]. self uniformPageSize ifNotNilDo: [:anExtent | currentPage extent: anExtent]]. (self valueOfProperty: #floatingPageControls) ifNotNilDo: [:pc | pc isInWorld ifFalse: [pc openInWorld]]! ! !BookMorph methodsFor: 'other' stamp: 'sw 6/6/2003 17:21'! setExtentFromHalo: anExtent "The user has dragged the grow box such that the receiver's extent would be anExtent. Do what's needed. For a BookMorph, we assume any resizing attempt is a request that the book-page currently being viewed be resized accoringly; this will typically not affect unseen book pages, though there is a command that can be issued to harmonize all book-page sizes, and also an option to set that will maintain all pages at the same size no matter what." currentPage isInWorld ifFalse: "doubtful case mostly" [super setExtentFromHalo: anExtent] ifTrue: [currentPage width: anExtent x. currentPage height: (anExtent y - (self innerBounds height - currentPage height)). self maintainsUniformPageSize ifTrue: [self setProperty: #uniformPageSize toValue: currentPage extent]]! ! !BookMorph methodsFor: 'uniform page size' stamp: 'sw 3/3/2004 18:39'! keepingUniformPageSizeString "Answer a string characterizing whether I am currently maintaining uniform page size" ^ (self maintainsUniformPageSize ifTrue: ['<yes>'] ifFalse: ['<no>']), 'keep all pages the same size' translated! ! !BookMorph methodsFor: 'uniform page size' stamp: 'sw 6/6/2003 13:56'! maintainsUniformPageSize "Answer whether I am currently set up to maintain uniform page size" ^ self uniformPageSize notNil! ! !BookMorph methodsFor: 'uniform page size' stamp: 'sw 6/6/2003 13:56'! maintainsUniformPageSize: aBoolean "Set the property governing whether I maintain uniform page size" aBoolean ifFalse: [self removeProperty: #uniformPageSize] ifTrue: [self setProperty: #uniformPageSize toValue: currentPage extent]! ! !BookMorph methodsFor: 'uniform page size' stamp: 'sw 6/6/2003 13:57'! toggleMaintainUniformPageSize "Toggle whether or not the receiver should maintain uniform page size" self maintainsUniformPageSize: self maintainsUniformPageSize not! ! !BookMorph methodsFor: 'uniform page size' stamp: 'sw 6/6/2003 13:57'! uniformPageSize "Answer the uniform page size to maintain, or nil if the option is not set" ^ self valueOfProperty: #uniformPageSize ifAbsent: [nil]! ! !StackMorph methodsFor: 'initialization' stamp: 'sw 6/5/2003 04:04'! addPane: aPane paneType: aType | anIndex | anIndex _ self insertionIndexForPaneOfType: aType. self privateAddMorph: aPane atIndex: anIndex! ! !StackMorph methodsFor: 'menu' stamp: 'sw 6/6/2003 13:53'! offerBookishMenu "Offer a menu with book-related items in it" | aMenu | aMenu _ MenuMorph new defaultTarget: self. aMenu addTitle: 'Stack / Book'. aMenu addStayUpItem. aMenu addList: #(('sort pages' sortPages) ('uncache page sorter' uncachePageSorter)). (self hasProperty: #dontWrapAtEnd) ifTrue: [aMenu add: 'wrap after last page' selector: #setWrapPages: argument: true] ifFalse: [aMenu add: 'stop at last page' selector: #setWrapPages: argument: false]. aMenu addList: #(('make bookmark' bookmarkForThisPage) ('make thumbnail' thumbnailForThisPage)). aMenu addLine. aMenu add: 'sound effect for all pages' action: #menuPageSoundForAll:. aMenu add: 'sound effect this page only' action: #menuPageSoundForThisPage:. aMenu add: 'visual effect for all pages' action: #menuPageVisualForAll:. aMenu add: 'visual effect this page only' action: #menuPageVisualForThisPage:. aMenu addLine. (self primaryHand pasteBuffer class isKindOf: PasteUpMorph class) ifTrue: [aMenu add: 'paste book page' action: #pasteBookPage]. aMenu add: 'save as new-page prototype' action: #setNewPagePrototype. newPagePrototype ifNotNil: [ aMenu add: 'clear new-page prototype' action: #clearNewPagePrototype]. aMenu add: (self dragNDropEnabled ifTrue: ['close'] ifFalse: ['open']) , ' dragNdrop' action: #toggleDragNDrop. aMenu addLine. aMenu add: 'make all pages this size' action: #makeUniformPageSize. aMenu addUpdating: #keepingUniformPageSizeString target: self action: #toggleMaintainUniformPageSize. aMenu addLine. aMenu add: 'send all pages to server' action: #savePagesOnURL. aMenu add: 'send this page to server' action: #saveOneOnURL. aMenu add: 'reload all from server' action: #reload. aMenu add: 'copy page url to clipboard' action: #copyUrl. aMenu add: 'keep in one file' action: #keepTogether. aMenu addLine. aMenu add: 'load PPT images from slide #1' action: #loadImagesIntoBook. aMenu add: 'background color for all pages...' action: #setPageColor. aMenu popUpEvent: self world activeHand lastEvent in: self world ! ! !StackMorph methodsFor: 'page controls' stamp: 'sw 6/6/2003 13:59'! addPageControlMorph: aMorph "Add the given morph as a page-control, at the appropriate place" aMorph setProperty: #pageControl toValue: true. self addPane: aMorph paneType: #pageControl! ! !StackMorph methodsFor: 'submorphs-accessing' stamp: 'sw 6/5/2003 04:01'! insertionIndexForPaneOfType: aType | naturalIndex insertionIndex | naturalIndex _ self naturalPaneOrder indexOf: aType. insertionIndex _ 1. (self naturalPaneOrder copyFrom: 1 to: (naturalIndex - 1)) do: "guys that would precede" [:sym | (self hasSubmorphWithProperty: sym) ifTrue: [insertionIndex _ insertionIndex + 1]]. ^ insertionIndex! ! !StackMorph methodsFor: 'submorphs-accessing' stamp: 'sw 6/5/2003 04:02'! naturalPaneOrder ^ #(header pageControl retrieve search index content)! ! !StoryboardBookMorph methodsFor: 'navigation' stamp: 'sw 7/25/2003 16:47'! insertPageMorphInCorrectSpot: aPageMorph "Insert the page morph at the correct spot" | place | place _ submorphs size > 1 ifTrue: [submorphs second] ifFalse: [submorphs first]. "Old architecture had a tiny spacer morph as the second morph; now architecture does not" self addMorph: (currentPage _ aPageMorph) behind: place. self changeTiltFactor: self getTiltFactor. self changeZoomFactor: self getZoomFactor. zoomController target: currentPage. ! ! !TabbedPalette methodsFor: 'other' stamp: 'sw 6/6/2003 17:38'! setExtentFromHalo: anExtent "The user has dragged the grow box such that the receiver's extent would be anExtent. Do what's needed. For a BookMorph, we assume any resizing attempt is a request that the book-page currently being viewed be resized accoringly; this will typically not affect unseen book pages, though there is a command that can be issued to harmonize all book-page sizes, and also an option to set that will maintain all pages at the same size no matter what." currentPage isInWorld ifFalse: "doubtful case mostly" [super setExtentFromHalo: anExtent] ifTrue: [currentPage setExtentFromHalo: ((anExtent x @ (anExtent y - (self innerBounds height - currentPage height))) - (2 * (self borderWidth @ self borderWidth))). self maintainsUniformPageSize ifTrue: [self setProperty: #uniformPageSize toValue: currentPage extent]]! !
// 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 Internal.TypeSystem; namespace Internal.IL { public static class ILStackHelper { /// <summary> /// Validates that the CIL evaluation stack is properly balanced. /// </summary> [Conditional("DEBUG")] public static void CheckStackBalance(this MethodIL methodIL) { methodIL.ComputeMaxStack(); } /// <summary> /// Computes the maximum number of items that can be pushed onto the CIL evaluation stack. /// </summary> public static int ComputeMaxStack(this MethodIL methodIL) { const int StackHeightNotSet = Int32.MinValue; byte[] ilbytes = methodIL.GetILBytes(); int currentOffset = 0; int stackHeight = 0; int maxStack = 0; // TODO: Use Span<T> for this and stackalloc the array if reasonably sized int[] stackHeights = new int[ilbytes.Length]; for (int i = 0; i < stackHeights.Length; i++) stackHeights[i] = StackHeightNotSet; // Catch and filter clauses have a known non-zero stack height. foreach (ILExceptionRegion region in methodIL.GetExceptionRegions()) { if (region.Kind == ILExceptionRegionKind.Catch) { stackHeights[region.HandlerOffset] = 1; } else if (region.Kind == ILExceptionRegionKind.Filter) { stackHeights[region.FilterOffset] = 1; stackHeights[region.HandlerOffset] = 1; } } while (currentOffset < ilbytes.Length) { ILOpcode opcode = (ILOpcode)ilbytes[currentOffset]; if (opcode == ILOpcode.prefix1) opcode = 0x100 + (ILOpcode)ilbytes[currentOffset + 1]; // The stack height could be unknown if the previous instruction // was an unconditional control transfer. // In that case we check if we have a known stack height due to // this instruction being a target of a previous branch or an EH block. if (stackHeight == StackHeightNotSet) stackHeight = stackHeights[currentOffset]; // If we still don't know the stack height, ECMA-335 III.1.7.5 // "Backward branch constraint" demands the evaluation stack be empty. if (stackHeight == StackHeightNotSet) stackHeight = 0; // Remeber the stack height at this offset. Debug.Assert(stackHeights[currentOffset] == StackHeightNotSet || stackHeights[currentOffset] == stackHeight); stackHeights[currentOffset] = stackHeight; bool isVariableSize = false; switch (opcode) { case ILOpcode.arglist: case ILOpcode.dup: case ILOpcode.ldc_i4: case ILOpcode.ldc_i4_0: case ILOpcode.ldc_i4_1: case ILOpcode.ldc_i4_2: case ILOpcode.ldc_i4_3: case ILOpcode.ldc_i4_4: case ILOpcode.ldc_i4_5: case ILOpcode.ldc_i4_6: case ILOpcode.ldc_i4_7: case ILOpcode.ldc_i4_8: case ILOpcode.ldc_i4_m1: case ILOpcode.ldc_i4_s: case ILOpcode.ldc_i8: case ILOpcode.ldc_r4: case ILOpcode.ldc_r8: case ILOpcode.ldftn: case ILOpcode.ldnull: case ILOpcode.ldsfld: case ILOpcode.ldsflda: case ILOpcode.ldstr: case ILOpcode.ldtoken: case ILOpcode.ldarg: case ILOpcode.ldarg_0: case ILOpcode.ldarg_1: case ILOpcode.ldarg_2: case ILOpcode.ldarg_3: case ILOpcode.ldarg_s: case ILOpcode.ldarga: case ILOpcode.ldarga_s: case ILOpcode.ldloc: case ILOpcode.ldloc_0: case ILOpcode.ldloc_1: case ILOpcode.ldloc_2: case ILOpcode.ldloc_3: case ILOpcode.ldloc_s: case ILOpcode.ldloca: case ILOpcode.ldloca_s: case ILOpcode.sizeof_: stackHeight += 1; break; case ILOpcode.add: case ILOpcode.add_ovf: case ILOpcode.add_ovf_un: case ILOpcode.and: case ILOpcode.ceq: case ILOpcode.cgt: case ILOpcode.cgt_un: case ILOpcode.clt: case ILOpcode.clt_un: case ILOpcode.div: case ILOpcode.div_un: case ILOpcode.initobj: case ILOpcode.ldelem: case ILOpcode.ldelem_i: case ILOpcode.ldelem_i1: case ILOpcode.ldelem_i2: case ILOpcode.ldelem_i4: case ILOpcode.ldelem_i8: case ILOpcode.ldelem_r4: case ILOpcode.ldelem_r8: case ILOpcode.ldelem_ref: case ILOpcode.ldelem_u1: case ILOpcode.ldelem_u2: case ILOpcode.ldelem_u4: case ILOpcode.ldelema: case ILOpcode.mkrefany: case ILOpcode.mul: case ILOpcode.mul_ovf: case ILOpcode.mul_ovf_un: case ILOpcode.or: case ILOpcode.pop: case ILOpcode.rem: case ILOpcode.rem_un: case ILOpcode.shl: case ILOpcode.shr: case ILOpcode.shr_un: case ILOpcode.stsfld: case ILOpcode.sub: case ILOpcode.sub_ovf: case ILOpcode.sub_ovf_un: case ILOpcode.xor: case ILOpcode.starg: case ILOpcode.starg_s: case ILOpcode.stloc: case ILOpcode.stloc_0: case ILOpcode.stloc_1: case ILOpcode.stloc_2: case ILOpcode.stloc_3: case ILOpcode.stloc_s: Debug.Assert(stackHeight > 0); stackHeight -= 1; break; case ILOpcode.throw_: Debug.Assert(stackHeight > 0); stackHeight = StackHeightNotSet; break; case ILOpcode.br: case ILOpcode.leave: case ILOpcode.brfalse: case ILOpcode.brtrue: case ILOpcode.beq: case ILOpcode.bge: case ILOpcode.bge_un: case ILOpcode.bgt: case ILOpcode.bgt_un: case ILOpcode.ble: case ILOpcode.ble_un: case ILOpcode.blt: case ILOpcode.blt_un: case ILOpcode.bne_un: { int target = currentOffset + ReadInt32(ilbytes, currentOffset + 1) + 5; int adjustment; bool isConditional; if (opcode == ILOpcode.br || opcode == ILOpcode.leave) { isConditional = false; adjustment = 0; } else if (opcode == ILOpcode.brfalse || opcode == ILOpcode.brtrue) { isConditional = true; adjustment = 1; } else { isConditional = true; adjustment = 2; } Debug.Assert(stackHeight >= adjustment); stackHeight -= adjustment; Debug.Assert(stackHeights[target] == StackHeightNotSet || stackHeights[target] == stackHeight); // Forward branch carries information about stack height at a future // offset. We need to remember it. if (target > currentOffset) stackHeights[target] = stackHeight; if (!isConditional) stackHeight = StackHeightNotSet; } break; case ILOpcode.br_s: case ILOpcode.leave_s: case ILOpcode.brfalse_s: case ILOpcode.brtrue_s: case ILOpcode.beq_s: case ILOpcode.bge_s: case ILOpcode.bge_un_s: case ILOpcode.bgt_s: case ILOpcode.bgt_un_s: case ILOpcode.ble_s: case ILOpcode.ble_un_s: case ILOpcode.blt_s: case ILOpcode.blt_un_s: case ILOpcode.bne_un_s: { int target = currentOffset + (sbyte)ilbytes[currentOffset + 1] + 2; int adjustment; bool isConditional; if (opcode == ILOpcode.br_s || opcode == ILOpcode.leave_s) { isConditional = false; adjustment = 0; } else if (opcode == ILOpcode.brfalse_s || opcode == ILOpcode.brtrue_s) { isConditional = true; adjustment = 1; } else { isConditional = true; adjustment = 2; } Debug.Assert(stackHeight >= adjustment); stackHeight -= adjustment; Debug.Assert(stackHeights[target] == StackHeightNotSet || stackHeights[target] == stackHeight); // Forward branch carries information about stack height at a future // offset. We need to remember it. if (target > currentOffset) stackHeights[target] = stackHeight; if (!isConditional) stackHeight = StackHeightNotSet; } break; case ILOpcode.call: case ILOpcode.calli: case ILOpcode.callvirt: case ILOpcode.newobj: { int token = ReadILToken(ilbytes, currentOffset + 1); object obj = methodIL.GetObject(token); MethodSignature sig = obj is MethodSignature ? (MethodSignature)obj : ((MethodDesc)obj).Signature; int adjustment = sig.Length; if (opcode == ILOpcode.newobj) { adjustment--; } else { if (opcode == ILOpcode.calli) adjustment++; if (!sig.IsStatic) adjustment++; if (!sig.ReturnType.IsVoid) adjustment--; } Debug.Assert(stackHeight >= adjustment); stackHeight -= adjustment; } break; case ILOpcode.ret: { bool hasReturnValue = !methodIL.OwningMethod.Signature.ReturnType.IsVoid; if (hasReturnValue) stackHeight -= 1; Debug.Assert(stackHeight == 0); stackHeight = StackHeightNotSet; } break; case ILOpcode.cpobj: case ILOpcode.stfld: case ILOpcode.stind_i: case ILOpcode.stind_i1: case ILOpcode.stind_i2: case ILOpcode.stind_i4: case ILOpcode.stind_i8: case ILOpcode.stind_r4: case ILOpcode.stind_r8: case ILOpcode.stind_ref: case ILOpcode.stobj: Debug.Assert(stackHeight > 1); stackHeight -= 2; break; case ILOpcode.cpblk: case ILOpcode.initblk: case ILOpcode.stelem: case ILOpcode.stelem_i: case ILOpcode.stelem_i1: case ILOpcode.stelem_i2: case ILOpcode.stelem_i4: case ILOpcode.stelem_i8: case ILOpcode.stelem_r4: case ILOpcode.stelem_r8: case ILOpcode.stelem_ref: Debug.Assert(stackHeight > 2); stackHeight -= 3; break; case ILOpcode.break_: case ILOpcode.constrained: case ILOpcode.no: case ILOpcode.nop: case ILOpcode.readonly_: case ILOpcode.tail: case ILOpcode.unaligned: case ILOpcode.volatile_: break; case ILOpcode.endfilter: Debug.Assert(stackHeight > 0); stackHeight = StackHeightNotSet; break; case ILOpcode.jmp: case ILOpcode.rethrow: case ILOpcode.endfinally: stackHeight = StackHeightNotSet; break; case ILOpcode.box: case ILOpcode.castclass: case ILOpcode.ckfinite: case ILOpcode.conv_i: case ILOpcode.conv_i1: case ILOpcode.conv_i2: case ILOpcode.conv_i4: case ILOpcode.conv_i8: case ILOpcode.conv_ovf_i: case ILOpcode.conv_ovf_i_un: case ILOpcode.conv_ovf_i1: case ILOpcode.conv_ovf_i1_un: case ILOpcode.conv_ovf_i2: case ILOpcode.conv_ovf_i2_un: case ILOpcode.conv_ovf_i4: case ILOpcode.conv_ovf_i4_un: case ILOpcode.conv_ovf_i8: case ILOpcode.conv_ovf_i8_un: case ILOpcode.conv_ovf_u: case ILOpcode.conv_ovf_u_un: case ILOpcode.conv_ovf_u1: case ILOpcode.conv_ovf_u1_un: case ILOpcode.conv_ovf_u2: case ILOpcode.conv_ovf_u2_un: case ILOpcode.conv_ovf_u4: case ILOpcode.conv_ovf_u4_un: case ILOpcode.conv_ovf_u8: case ILOpcode.conv_ovf_u8_un: case ILOpcode.conv_r_un: case ILOpcode.conv_r4: case ILOpcode.conv_r8: case ILOpcode.conv_u: case ILOpcode.conv_u1: case ILOpcode.conv_u2: case ILOpcode.conv_u4: case ILOpcode.conv_u8: case ILOpcode.isinst: case ILOpcode.ldfld: case ILOpcode.ldflda: case ILOpcode.ldind_i: case ILOpcode.ldind_i1: case ILOpcode.ldind_i2: case ILOpcode.ldind_i4: case ILOpcode.ldind_i8: case ILOpcode.ldind_r4: case ILOpcode.ldind_r8: case ILOpcode.ldind_ref: case ILOpcode.ldind_u1: case ILOpcode.ldind_u2: case ILOpcode.ldind_u4: case ILOpcode.ldlen: case ILOpcode.ldobj: case ILOpcode.ldvirtftn: case ILOpcode.localloc: case ILOpcode.neg: case ILOpcode.newarr: case ILOpcode.not: case ILOpcode.refanytype: case ILOpcode.refanyval: case ILOpcode.unbox: case ILOpcode.unbox_any: Debug.Assert(stackHeight > 0); break; case ILOpcode.switch_: Debug.Assert(stackHeight > 0); isVariableSize = true; stackHeight -= 1; currentOffset += 1 + (ReadInt32(ilbytes, currentOffset + 1) * 4) + 4; break; default: Debug.Fail("Unknown instruction"); break; } if (!isVariableSize) currentOffset += opcode.GetSize(); maxStack = Math.Max(maxStack, stackHeight); } return maxStack; } private static int ReadInt32(byte[] ilBytes, int offset) { return ilBytes[offset] + (ilBytes[offset + 1] << 8) + (ilBytes[offset + 2] << 16) + (ilBytes[offset + 3] << 24); } private static int ReadILToken(byte[] ilBytes, int offset) { return ReadInt32(ilBytes, offset); } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.LdapSearchResults.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using System.Collections; using Novell.Directory.Ldap.Utilclass; namespace Novell.Directory.Ldap { /// <summary> /// An LdapSearchResults object is returned from a synchronous search /// operation. It provides access to all results received during the /// operation (entries and exceptions). /// </summary> /// <seealso cref="LdapConnection.Search"> /// </seealso> public class LdapSearchResults { /// <summary> /// Returns a count of the items in the search result. /// Returns a count of the entries and exceptions remaining in the object. /// If the search was submitted with a batch size greater than zero, /// getCount reports the number of results received so far but not enumerated /// with next(). If batch size equals zero, getCount reports the number of /// items received, since the application thread blocks until all results are /// received. /// </summary> /// <returns> /// The number of items received but not retrieved by the application /// </returns> public virtual int Count { get { var qCount = queue.MessageAgent.Count; return entryCount - entryIndex + referenceCount - referenceIndex + qCount; } } /// <summary> /// Returns the latest server controls returned by the server /// in the context of this search request, or null /// if no server controls were returned. /// </summary> /// <returns> /// The server controls returned with the search request, or null /// if none were returned. /// </returns> public virtual LdapControl[] ResponseControls { get { return controls; } } /// <summary> /// Collects batchSize elements from an LdapSearchQueue message /// queue and places them in a Vector. /// If the last message from the server, /// the result message, contains an error, it will be stored in the Vector /// for nextElement to process. (although it does not increment the search /// result count) All search result entries will be placed in the Vector. /// If a null is returned from getResponse(), it is likely that the search /// was abandoned. /// </summary> /// <returns> /// true if all search results have been placed in the vector. /// </returns> private bool BatchOfResults { get { LdapMessage msg; // <=batchSize so that we can pick up the result-done message for (var i = 0; i < batchSize;) { try { if ((msg = queue.getResponse()) != null) { // Only save controls if there are some var ctls = msg.Controls; if (ctls != null) { controls = ctls; } if (msg is LdapSearchResult) { // Search Entry object entry = ((LdapSearchResult) msg).Entry; entries.Add(entry); i++; entryCount++; } else if (msg is LdapSearchResultReference) { // Search Ref var refs = ((LdapSearchResultReference) msg).Referrals; if (cons.ReferralFollowing) { // referralConn = conn.chaseReferral(queue, cons, msg, refs, 0, true, referralConn); } else { references.Add(refs); referenceCount++; } } else { // LdapResponse var resp = (LdapResponse) msg; var resultCode = resp.ResultCode; // Check for an embedded exception if (resp.hasException()) { // Fake it, results in an exception when msg read resultCode = LdapException.CONNECT_ERROR; } if (resultCode == LdapException.REFERRAL && cons.ReferralFollowing) { // Following referrals // referralConn = conn.chaseReferral(queue, cons, resp, resp.Referrals, 0, false, referralConn); } else if (resultCode != LdapException.SUCCESS) { // Results in an exception when message read entries.Add(resp); entryCount++; } // We are done only when we have read all messages // including those received from following referrals var msgIDs = queue.MessageIDs; if (msgIDs.Length == 0) { // Release referral exceptions // conn.releaseReferralConnections(referralConn); return true; // search completed } } } else { // We get here if the connection timed out // we have no responses, no message IDs and no exceptions var e = new LdapException(null, LdapException.Ldap_TIMEOUT, null); entries.Add(e); break; } } catch (LdapException e) { // Hand exception off to user entries.Add(e); } } return false; // search not completed } } private readonly ArrayList entries; // Search entries private int entryCount; // # Search entries in vector private int entryIndex; // Current position in vector private readonly ArrayList references; // Search Result References private int referenceCount; // # Search Result Reference in vector private int referenceIndex; // Current position in vector private readonly int batchSize; // Application specified batch size private bool completed; // All entries received private LdapControl[] controls; // Last set of controls private readonly LdapSearchQueue queue; private static object nameLock; // protect resultsNum private static int resultsNum = 0; // used for debug private string name; // used for debug private LdapConnection conn; // LdapConnection which started search private readonly LdapSearchConstraints cons; // LdapSearchConstraints for search private ArrayList referralConn = null; // Referral Connections /// <summary> /// Constructs a queue object for search results. /// </summary> /// <param name="conn"> /// The LdapConnection which initiated the search /// </param> /// <param name="queue"> /// The queue for the search results. /// </param> /// <param name="cons"> /// The LdapSearchConstraints associated with this search /// </param> internal LdapSearchResults(LdapConnection conn, LdapSearchQueue queue, LdapSearchConstraints cons) { // setup entry Vector this.conn = conn; this.cons = cons; var batchSize = cons.BatchSize; var vectorIncr = batchSize == 0 ? 64 : 0; entries = new ArrayList(batchSize == 0 ? 64 : batchSize); entryCount = 0; entryIndex = 0; // setup search reference Vector references = new ArrayList(5); referenceCount = 0; referenceIndex = 0; this.queue = queue; this.batchSize = batchSize == 0 ? int.MaxValue : batchSize; } /// <summary> /// Reports if there are more search results. /// </summary> /// <returns> /// true if there are more search results. /// </returns> public virtual bool hasMore() { var ret = false; if (entryIndex < entryCount || referenceIndex < referenceCount) { // we have data ret = true; } else if (completed == false) { // reload the Vector by getting more results resetVectors(); ret = entryIndex < entryCount || referenceIndex < referenceCount; } return ret; } /* * If both of the vectors are empty, get more data for them. */ private void resetVectors() { // If we're done, no further checking needed if (completed) { return; } // Checks if we have run out of references if (referenceIndex != 0 && referenceIndex >= referenceCount) { SupportClass.SetSize(references, 0); referenceCount = 0; referenceIndex = 0; } // Checks if we have run out of entries if (entryIndex != 0 && entryIndex >= entryCount) { SupportClass.SetSize(entries, 0); entryCount = 0; entryIndex = 0; } // If no data at all, must reload enumeration if (referenceIndex == 0 && referenceCount == 0 && entryIndex == 0 && entryCount == 0) { completed = BatchOfResults; } } /// <summary> /// Returns the next result as an LdapEntry. /// If automatic referral following is disabled or if a referral /// was not followed, next() will throw an LdapReferralException /// when the referral is received. /// </summary> /// <returns> /// The next search result as an LdapEntry. /// </returns> /// <exception> /// LdapException A general exception which includes an error /// message and an Ldap error code. /// </exception> /// <exception> /// LdapReferralException A referral was received and not /// followed. /// </exception> public virtual LdapEntry next() { if (completed && entryIndex >= entryCount && referenceIndex >= referenceCount) { throw new ArgumentOutOfRangeException("LdapSearchResults.next() no more results"); } // Check if the enumeration is empty and must be reloaded resetVectors(); object element = null; // Check for Search References & deliver to app as they come in // We only get here if not following referrals/references if (referenceIndex < referenceCount) { var refs = (string[]) references[referenceIndex++]; var rex = new LdapReferralException(ExceptionMessages.REFERENCE_NOFOLLOW); rex.setReferrals(refs); throw rex; } if (entryIndex < entryCount) { // Check for Search Entries and the Search Result element = entries[entryIndex++]; if (element is LdapResponse) { // Search done w/bad status if (((LdapResponse) element).hasException()) { var lr = (LdapResponse) element; var ri = lr.ActiveReferral; if (ri != null) { // Error attempting to follow a search continuation reference var rex = new LdapReferralException(ExceptionMessages.REFERENCE_ERROR, lr.Exception); rex.setReferrals(ri.ReferralList); rex.FailedReferral = ri.ReferralUrl.ToString(); throw rex; } } // Throw an exception if not success ((LdapResponse) element).chkResultCode(); } else if (element is LdapException) { throw (LdapException) element; } } else { // If not a Search Entry, Search Result, or search continuation // we are very confused. // LdapSearchResults.next(): No entry found & request is not complete throw new LdapException(ExceptionMessages.REFERRAL_LOCAL, new object[] {"next"}, LdapException.LOCAL_ERROR, null); } return (LdapEntry) element; } /// <summary> Cancels the search request and clears the message and enumeration.</summary> /*package*/ internal virtual void Abandon() { // first, remove message ID and timer and any responses in the queue queue.MessageAgent.AbandonAll(); // next, clear out enumeration resetVectors(); completed = true; } static LdapSearchResults() { nameLock = new object(); } } }
namespace Nancy { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; public abstract class NamedPipelineBase<TDelegate> { /// <summary> /// Pipeline items to execute /// </summary> protected readonly List<PipelineItem<TDelegate>> pipelineItems; protected NamedPipelineBase() { this.pipelineItems = new List<PipelineItem<TDelegate>>(); } protected NamedPipelineBase(int capacity) { this.pipelineItems = new List<PipelineItem<TDelegate>>(capacity); } /// <summary> /// Gets the current pipeline items /// </summary> public IEnumerable<PipelineItem<TDelegate>> PipelineItems { get { return this.pipelineItems.AsReadOnly(); } } /// <summary> /// Gets the current pipeline item delegates /// </summary> public IEnumerable<TDelegate> PipelineDelegates { get { return this.pipelineItems.Select(pipelineItem => pipelineItem.Delegate); } } /// <summary> /// Add an item to the start of the pipeline /// </summary> /// <param name="item">Item to add</param> public virtual void AddItemToStartOfPipeline(TDelegate item) { this.AddItemToStartOfPipeline((PipelineItem<TDelegate>)item); } /// <summary> /// Add an item to the start of the pipeline /// </summary> /// <param name="item">Item to add</param> /// <param name="replaceInPlace"> /// Whether to replace an existing item with the same name in its current place, /// rather than at the position requested. Defaults to false. /// </param> public virtual void AddItemToStartOfPipeline(PipelineItem<TDelegate> item, bool replaceInPlace = false) { this.InsertItemAtPipelineIndex(0, item, replaceInPlace); } /// <summary> /// Add an item to the end of the pipeline /// </summary> /// <param name="item">Item to add</param> public virtual void AddItemToEndOfPipeline(TDelegate item) { this.AddItemToEndOfPipeline((PipelineItem<TDelegate>)item); } /// <summary> /// Add an item to the end of the pipeline /// </summary> /// <param name="item">Item to add</param> /// <param name="replaceInPlace"> /// Whether to replace an existing item with the same name in its current place, /// rather than at the position requested. Defaults to false. /// </param> public virtual void AddItemToEndOfPipeline(PipelineItem<TDelegate> item, bool replaceInPlace = false) { var existingIndex = this.RemoveByName(item.Name); if (replaceInPlace && existingIndex != -1) { this.InsertItemAtPipelineIndex(existingIndex, item); } else { this.pipelineItems.Add(item); } } /// <summary> /// Add an item to a specific place in the pipeline. /// </summary> /// <param name="index">Index to add at</param> /// <param name="item">Item to add</param> public virtual void InsertItemAtPipelineIndex(int index, TDelegate item) { this.InsertItemAtPipelineIndex(index, (PipelineItem<TDelegate>)item); } /// <summary> /// Add an item to a specific place in the pipeline. /// </summary> /// <param name="index">Index to add at</param> /// <param name="item">Item to add</param> /// <param name="replaceInPlace"> /// Whether to replace an existing item with the same name in its current place, /// rather than at the position requested. Defaults to false. /// </param> public virtual void InsertItemAtPipelineIndex(int index, PipelineItem<TDelegate> item, bool replaceInPlace = false) { var existingIndex = this.RemoveByName(item.Name); var newIndex = (replaceInPlace && existingIndex != -1) ? existingIndex : index; this.pipelineItems.Insert(newIndex, item); } /// <summary> /// Insert an item before a named item. /// If the named item does not exist the item is inserted at the start of the pipeline. /// </summary> /// <param name="name">Name of the item to insert before</param> /// <param name="item">Item to insert</param> public virtual void InsertBefore(string name, TDelegate item) { this.InsertBefore(name, (PipelineItem<TDelegate>)item); } /// <summary> /// Insert an item before a named item. /// If the named item does not exist the item is inserted at the start of the pipeline. /// </summary> /// <param name="name">Name of the item to insert before</param> /// <param name="item">Item to insert</param> public virtual void InsertBefore(string name, PipelineItem<TDelegate> item) { var existingIndex = this.pipelineItems.FindIndex(i => String.Equals(name, i.Name, StringComparison.Ordinal)); if (existingIndex == -1) { existingIndex = 0; } this.InsertItemAtPipelineIndex(existingIndex, item); } /// <summary> /// Insert an item after a named item. /// If the named item does not exist the item is inserted at the end of the pipeline. /// </summary> /// <param name="name">Name of the item to insert after</param> /// <param name="item">Item to insert</param> public virtual void InsertAfter(string name, TDelegate item) { this.InsertAfter(name, (PipelineItem<TDelegate>)item); } /// <summary> /// Insert an item after a named item. /// If the named item does not exist the item is inserted at the end of the pipeline. /// </summary> /// <param name="name">Name of the item to insert after</param> /// <param name="item">Item to insert</param> public virtual void InsertAfter(string name, PipelineItem<TDelegate> item) { var existingIndex = this.pipelineItems.FindIndex(i => String.Equals(name, i.Name, StringComparison.Ordinal)); if (existingIndex == -1) { existingIndex = this.pipelineItems.Count; } existingIndex++; if (existingIndex > this.pipelineItems.Count) { this.AddItemToEndOfPipeline(item); } else { this.InsertItemAtPipelineIndex(existingIndex, item); } } /// <summary> /// Remove a named pipeline item /// </summary> /// <param name="name">Name</param> /// <returns>Index of item that was removed or -1 if nothing removed</returns> public virtual int RemoveByName(string name) { if (string.IsNullOrEmpty(name)) { return -1; } var existingIndex = this.pipelineItems.FindIndex(i => String.Equals(name, i.Name, StringComparison.Ordinal)); if (existingIndex != -1) { this.pipelineItems.RemoveAt(existingIndex); } return existingIndex; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Data; using System.Globalization; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Interop.Windows; using OpenLiveWriter.Localization.Bidi; using OpenLiveWriter.Localization; namespace OpenLiveWriter.Controls { public partial class AutoCompleteTextbox : TextBox { private readonly AutoCompleteForm tagSuggestForm; private AutoCompleteSource tagSource; private BitmapButton button; private Font normalFont; private Font cueFont; public AutoCompleteTextbox() { tagSuggestForm = new AutoCompleteForm(); tagSuggestForm.CreateControl(); tagSuggestForm.TagSelected += TagSelected; CreateButton(); GotFocus += new EventHandler(AutoCompleteTextbox_Enter); LostFocus += new EventHandler(AutoCompleteTextbox_Leave); normalFont = Res.DefaultFont; cueFont = Res.DefaultFont; } private bool rtlFixedUp = false; protected override void OnCreateControl() { base.OnCreateControl(); if (!BidiHelper.IsRightToLeft || RightToLeft == RightToLeft.No) User32.SendMessage(Handle, WM.EM_SETMARGINS, (UIntPtr)EC.RIGHTMARGIN, new IntPtr((BUTTON_WIDTH + BUTTON_RIGHT_OFFSET) << 16)); else { if (!rtlFixedUp) { rtlFixedUp = true; int leftMargin = Margin.Left; int rightMargin = Margin.Right; BidiHelper.RtlLayoutFixup(this); Margin = new Padding(leftMargin, Padding.Top, rightMargin, Padding.Bottom); } } } void AutoCompleteTextbox_Leave(object sender, EventArgs e) { if (Text == String.Empty) { _isDirty = false; SetDefaultText(); } tagSuggestForm.Dismissed = false; } void AutoCompleteTextbox_Enter(object sender, EventArgs e) { if (!_isDirty) { _isDirty = true; Text = String.Empty; ForeColor = SystemColors.WindowText; Font = normalFont; } } public bool ShowButton { get { return button.Visible; } set { button.Visible = value; } } private const int BUTTON_WIDTH = 16; private const int BUTTON_RIGHT_OFFSET = 8; private void CreateButton() { button = new BitmapButton(); button.BitmapEnabled = ResourceHelper.LoadAssemblyResourceBitmap("Images.refresh.png"); button.BitmapPushed = ResourceHelper.LoadAssemblyResourceBitmap("Images.refreshPushed.png"); button.BitmapSelected = ResourceHelper.LoadAssemblyResourceBitmap("Images.refreshSelected.png"); button.Anchor = AnchorStyles.Right; button.Height = 16; button.Width = BUTTON_WIDTH; button.Cursor = Cursors.Hand; button.Left = Width - button.Width - BUTTON_RIGHT_OFFSET; button.AccessibleName = Res.Get(StringId.CategoryRefreshList); button.ToolTip = Res.Get(StringId.CategoryRefreshList); Controls.Add(button); } private bool _isDirty = false; public string _defaultText; public string DefaultText { get { return _defaultText; } set { _defaultText = value; AccessibleName = _defaultText; if (!_isDirty) { SetDefaultText(); } } } private void SetDefaultText() { base.Text = _defaultText; ForeColor = SystemColors.GrayText; Font = cueFont; } public string TextValue { get { return _isDirty ? Text : ""; } } public override string Text { get { return base.Text; } set { if (string.IsNullOrEmpty(value) && !Focused && !button.Focused) { ClearTextbox(); return; } _isDirty = true; ForeColor = SystemColors.WindowText; Font = normalFont; base.Text = value; } } public void ClearTextbox() { _isDirty = false; SetDefaultText(); } public override Size GetPreferredSize(Size proposedSize) { Size preferredSize = base.GetPreferredSize(proposedSize); // WinLive 118369: Windows Forms doesn't take into account that the refresh button may be drawn over // text, so we add extra padding to leave enough room to fit the text and the button. if (ShowButton) preferredSize.Width += BUTTON_WIDTH + BUTTON_RIGHT_OFFSET * 2; return preferredSize; } public event EventHandler ButtonClicked { add { button.Click += value; } remove { button.Click -= value; } } public event EventHandler DirtyChanged; public void FireDirtyChanged() { if (DirtyChanged != null) DirtyChanged(this, EventArgs.Empty); } public AutoCompleteSource TagSource { set { tagSource = value; } } private void TagSelected(object sender, EventArgs e) { int pos; int len; string prefix = tagSource.GetPrefix(this, out pos, out len); Trace.Assert(!string.IsNullOrEmpty(prefix)); Select(pos, len); SelectedText = tagSuggestForm.SelectedTag; Select(SelectionStart + SelectionLength, 0); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) tagSuggestForm.Dispose(); } protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); tagSuggestForm.Owner = FindForm(); tagSuggestForm.Font = normalFont; } protected override void OnFontChanged(EventArgs e) { base.OnFontChanged(e); if (tagSuggestForm != null) tagSuggestForm.Font = normalFont; } protected override void OnTextChanged(EventArgs e) { if (!_isDirty) return; FireDirtyChanged(); ShowSuggestionForm(); base.OnTextChanged(e); } private void ShowSuggestionForm() { int pos; int segmentLength; if (tagSource == null) { tagSuggestForm.Hide(); return; } string prefix = tagSource.GetPrefix(this, out pos, out segmentLength); if (string.IsNullOrEmpty(prefix)) { tagSuggestForm.Hide(); } else { prefix = prefix.ToLower(CultureInfo.CurrentUICulture); List<string> listChoices = new List<string>(); tagSource.PopulateTags(prefix, listChoices); IntPtr p = User32.SendMessage(Handle, WM.EM_POSFROMCHAR, new IntPtr(pos), IntPtr.Zero); int x = p.ToInt32() & 0xFFFF; tagSuggestForm.Origin = PointToScreen(new Point(x, ClientSize.Height - 2)); tagSuggestForm.SetSuggestions(FindForm(), listChoices); } } protected override void OnLostFocus(EventArgs e) { base.OnLostFocus(e); if (!tagSuggestForm.ContainsFocus) tagSuggestForm.Visible = false; } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { switch (keyData) { case Keys.Up: tagSuggestForm.MoveSelectionUp(); return true; case Keys.Down: tagSuggestForm.MoveSelectionDown(); return true; case Keys.Escape: if (!tagSuggestForm.Visible) break; tagSuggestForm.Dismissed = true; return true; case Keys.Enter: case Keys.Tab: if (tagSuggestForm.CanAcceptSelection) { tagSuggestForm.AcceptSelection(); return true; } break; case Keys.Control | Keys.Space: tagSuggestForm.Dismissed = false; ShowSuggestionForm(); return true; case Keys.Control | Keys.A: SelectAll(); return true; } return base.ProcessCmdKey(ref msg, keyData); } protected override void OnKeyPress(KeyPressEventArgs e) { base.OnKeyPress(e); if (e.KeyChar == ',') { // if (tagSuggestForm.CanAcceptSelection) // { // tagSuggestForm.AcceptSelection(); // SelectedText = ", "; // e.Handled = true; // } tagSuggestForm.Dismissed = false; } } } public abstract class AutoCompleteSource { public virtual string GetPrefix(AutoCompleteTextbox tstb, out int pos, out int segmentLength) { if (tstb.SelectionLength == 0) { string s = tstb.Text; int selPos = tstb.SelectionStart; Match m = Regex.Match(s, @"[^,\s][^,]*"); while (m.Success) { if (m.Index <= selPos && m.Index + m.Length >= selPos) { pos = m.Index; segmentLength = m.Length; return s.Substring(m.Index, selPos - m.Index); } m = m.NextMatch(); } } pos = -1; segmentLength = -1; return null; } public abstract void PopulateTags(string prefix, List<string> tagList); } public class SimpleTagSource : AutoCompleteSource { private readonly List<string> tags; public SimpleTagSource(IEnumerable<string> tags) { this.tags = new List<string>(tags); } public override void PopulateTags(string prefix, List<string> tagList) { foreach (string str in tags) { if (str.ToLower(CultureInfo.CurrentUICulture).StartsWith(prefix, StringComparison.CurrentCulture)) tagList.Add(str); } } } public class AutoCompleteForm : Form { /// <summary> /// The position of this form relative to the owner form. /// </summary> private Point relativeLocation = Point.Empty; /// <summary> /// The desired position of the lower-left (or lower-right, in RTL) corner of the form. /// </summary> private Point origin; private bool dismissed; public AutoCompleteForm() { InitializeComponent(); VisibleChanged += TagSuggestForm_VisibleChanged; lstSuggest.Resize += new EventHandler(lstSuggest_Resize); RightToLeft = BidiHelper.IsRightToLeft ? RightToLeft.Yes : RightToLeft.No; } void lstSuggest_Resize(object sender, EventArgs e) { Size = lstSuggest.Size; } protected override bool ShowWithoutActivation { get { return true; } } public event EventHandler TagSelected; public bool CanAcceptSelection { get { return Visible && lstSuggest.SelectedIndex >= 0; } } public string SelectedTag { get { return lstSuggest.SelectedItem.ToString(); } } public void SetSuggestions(Form owner, IEnumerable<string> suggestions) { if (dismissed) { return; } lstSuggest.BeginUpdate(); try { lstSuggest.Items.Clear(); foreach (string sugg in suggestions) { lstSuggest.Items.Add(sugg); } if (lstSuggest.Items.Count == 0) { Visible = false; } else { AdjustListSize(); if (!Visible) Show(owner); lstSuggest.SelectedIndex = 0; } } finally { lstSuggest.EndUpdate(); } } protected override void OnShown(EventArgs e) { AdjustListSize(); base.OnShown(e); } private void AdjustListSize() { int width = 0; using (Graphics g = CreateGraphics()) { foreach (string s in lstSuggest.Items) width = Math.Max(width, TextRenderer.MeasureText(g, s, Font, Size.Empty, TextFormatFlags.NoPrefix).Width); } width += 3; int preferredHeight = lstSuggest.PreferredHeight; int height = Math.Min(preferredHeight, lstSuggest.ItemHeight * 11); if (height < preferredHeight) width += SystemInformation.VerticalScrollBarWidth; lstSuggest.Size = new Size(width, height); } public void MoveSelectionUp() { MoveSelection(true); } public void MoveSelectionDown() { MoveSelection(false); } private void MoveSelection(bool up) { int c = lstSuggest.Items.Count; if (c <= 1) return; int offset = up ? -1 : 1; lstSuggest.SelectedIndex = (lstSuggest.SelectedIndex + c + offset) % c; } private void lstSuggest_Click(object sender, EventArgs e) { AcceptSelection(); } public void AcceptSelection() { if (TagSelected != null) TagSelected(this, EventArgs.Empty); Visible = false; } public bool Dismissed { set { if (value) Visible = false; dismissed = value; Debug.WriteLine("dismissed: " + dismissed); } } public Point Origin { get { return origin; } set { if (origin != value) { origin = value; RepositionForm(); } } } protected override void OnResize(EventArgs e) { base.OnResize(e); RepositionForm(); } private void RepositionForm() { if (!BidiHelper.IsRightToLeft) Location = new Point(origin.X, origin.Y); else Location = new Point(origin.X - Width, origin.Y); } private void TagSuggestForm_VisibleChanged(object sender, EventArgs e) { if (Visible) { VisibleChanged -= TagSuggestForm_VisibleChanged; if (Owner != null) Owner.LocationChanged += ParentForm_LocationChanged; } } protected override void OnLocationChanged(EventArgs e) { base.OnLocationChanged(e); if (Owner != null) { Point p = Owner.Location; relativeLocation = Point.Subtract(Location, new Size(p.X, p.Y)); } } private void ParentForm_LocationChanged(object sender, EventArgs e) { Point p = Owner.Location; p.Offset(relativeLocation); Location = p; } private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.lstSuggest = new System.Windows.Forms.ListBox(); this.SuspendLayout(); // // lstSuggest // this.lstSuggest.Location = new System.Drawing.Point(0, 0); this.lstSuggest.Name = "lstSuggest"; this.lstSuggest.Size = new System.Drawing.Size(148, 108); this.lstSuggest.TabIndex = 0; this.lstSuggest.Click += new System.EventHandler(this.lstSuggest_Click); // // TagSuggestForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.BackColor = System.Drawing.SystemColors.Window; this.ClientSize = new System.Drawing.Size(148, 108); this.Controls.Add(this.lstSuggest); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Name = "TagSuggestForm"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "TagSuggestForm"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.ListBox lstSuggest; } }
/* * Copyright 2008 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 ErrorCorrectionLevel = ZXing.QrCode.Internal.ErrorCorrectionLevel; using Mode = ZXing.MicroQrCode.Internal.Mode; namespace ZXing.MicroQrCode.Internal { /// <author> satorux@google.com (Satoru Takabayashi) - creator /// </author> /// <author> dswitkin@google.com (Daniel Switkin) - ported from C++ /// </author> /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source /// </author> public sealed class MicroQRCode { public Mode Mode { // Mode of the Micro QR Code. get { return mode; } set { mode = value; } } public ErrorCorrectionLevel ECLevel { // Error correction level of the QR Code. get { return ecLevel; } set { ecLevel = value; } } public int Version { // Version of the QR Code. The bigger size, the bigger version. get { return version; } set { version = value; } } public int MatrixWidth { // ByteMatrix width of the QR Code. get { return matrixWidth; } set { matrixWidth = value; } } public int MaskPattern { // Mask pattern of the QR Code. get { return maskPattern; } set { maskPattern = value; } } public int NumTotalBytes { // Number of total bytes in the QR Code. get { return numTotalBytes; } set { numTotalBytes = value; } } public int NumDataBytes { // Number of data bytes in the QR Code. get { return numDataBytes; } set { numDataBytes = value; } } public int NumECBytes { // Number of error correction bytes in the QR Code. get { return numECBytes; } set { numECBytes = value; } } public int NumRSBlocks { // Number of Reedsolomon blocks in the QR Code. get { return numRSBlocks; } set { numRSBlocks = value; } } public ByteMatrix Matrix { get; set; } public bool Valid { // Checks all the member variables are set properly. Returns true on success. Otherwise, returns // false. get { return mode != null && ecLevel != null && version != - 1 && matrixWidth != - 1 && maskPattern != - 1 && numTotalBytes != - 1 && numDataBytes != - 1 && numECBytes != - 1 && numRSBlocks != - 1 && isValidMaskPattern(maskPattern) && numTotalBytes == numDataBytes + numECBytes && Matrix != null && matrixWidth == Matrix.Width && Matrix.Width == Matrix.Height; // Must be square. } } public const int NUM_MASK_PATTERNS = 4; private Mode mode; private ErrorCorrectionLevel ecLevel; private int version; private int matrixWidth; private int maskPattern; private int numTotalBytes; private int numDataBytes; private int numECBytes; private int numRSBlocks; //private ByteMatrix matrix; public MicroQRCode() { mode = null; ecLevel = null; version = - 1; matrixWidth = - 1; maskPattern = - 1; numTotalBytes = - 1; numDataBytes = - 1; numECBytes = - 1; numRSBlocks = - 1; Matrix = null; } // Return the value of the module (cell) pointed by "x" and "y" in the matrix of the QR Code. They // call cells in the matrix "modules". 1 represents a black cell, and 0 represents a white cell. /* public int at(int x, int y) { // The value must be zero or one. int value_Renamed = Matrix.get_Renamed(x, y); if (!(value_Renamed == 0 || value_Renamed == 1)) { // this is really like an assert... not sure what better exception to use? throw new System.SystemException("Bad value"); } return value_Renamed; } */ // Return debug String. public override System.String ToString() { System.Text.StringBuilder result = new System.Text.StringBuilder(200); result.Append("<<\n"); result.Append(" mode: "); result.Append(mode); result.Append("\n ecLevel: "); result.Append(ecLevel); result.Append("\n version: "); result.Append(version); result.Append("\n matrixWidth: "); result.Append(matrixWidth); result.Append("\n maskPattern: "); result.Append(maskPattern); result.Append("\n numTotalBytes: "); result.Append(numTotalBytes); result.Append("\n numDataBytes: "); result.Append(numDataBytes); result.Append("\n numECBytes: "); result.Append(numECBytes); result.Append("\n numRSBlocks: "); result.Append(numRSBlocks); if (Matrix == null) { result.Append("\n Matrix: null\n"); } else { result.Append("\n matrix:\n"); result.Append(Matrix.ToString()); } result.Append(">>\n"); return result.ToString(); } // Check if "mask_pattern" is valid. public static bool isValidMaskPattern(int maskPattern) { return maskPattern >= 0 && maskPattern < NUM_MASK_PATTERNS; } // Return true if the all values in the matrix are binary numbers. // // JAVAPORT: This is going to be super expensive and unnecessary, we should not call this in // production. I'm leaving it because it may be useful for testing. It should be removed entirely // if ByteMatrix is changed never to contain a -1. /* private static boolean EverythingIsBinary(final ByteMatrix matrix) { for (int y = 0; y < matrix.height(); ++y) { for (int x = 0; x < matrix.width(); ++x) { int value = matrix.get(y, x); if (!(value == 0 || value == 1)) { // Found non zero/one value. return false; } } } return true; } */ } }
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 Backend.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using NUnit.Framework; using StructureMap.Configuration; using StructureMap.Graph; using StructureMap.Pipeline; using StructureMap.Testing.Configuration; using StructureMap.Testing.Widget2; using StructureMap.Testing.Widget3; namespace StructureMap.Testing { [TestFixture] public class InstanceMementoInstanceCreationTester { #region Setup/Teardown [SetUp] public void SetUp() { _graph = new PluginGraph(); } #endregion private PluginGraph _graph; public class Rule { } public class ComplexRule : Rule { private readonly bool _Bool; private readonly byte _Byte; private readonly BreedEnum _color; private readonly double _Double; private readonly int _Int; private readonly long _Long; private readonly string _String; [DefaultConstructor] public ComplexRule(string String, BreedEnum Breed, int Int, long Long, byte Byte, double Double, bool Bool, IAutomobile car, IAutomobile[] cars) { _String = String; _color = Breed; _Int = Int; _Long = Long; _Byte = Byte; _Double = Double; _Bool = Bool; } /// <summary> /// Plugin should find the constructor above, not the "greedy" one below. /// </summary> /// <param name="String"></param> /// <param name="String2"></param> /// <param name="Int"></param> /// <param name="Long"></param> /// <param name="Byte"></param> /// <param name="Double"></param> /// <param name="Bool"></param> /// <param name="extra"></param> public ComplexRule(string String, string String2, int Int, long Long, byte Byte, double Double, bool Bool, string extra) { } public string String { get { return _String; } } public int Int { get { return _Int; } } public byte Byte { get { return _Byte; } } public long Long { get { return _Long; } } public double Double { get { return _Double; } } public bool Bool { get { return _Bool; } } public static MemoryInstanceMemento GetMemento() { var memento = new MemoryInstanceMemento("", "Sample"); memento.SetProperty("String", "Red"); memento.SetProperty("Breed", "Longhorn"); memento.SetProperty("Int", "1"); memento.SetProperty("Long", "2"); memento.SetProperty("Byte", "3"); memento.SetProperty("Double", "4"); memento.SetProperty("Bool", "True"); return memento; } } public interface IAutomobile { } public class GrandPrix : IAutomobile { private readonly string _color; private readonly int _horsePower; public GrandPrix(int horsePower, string color) { _horsePower = horsePower; _color = color; } } public class Mustang : IAutomobile { } private void assertIsReference(Instance instance, string referenceKey) { var referencedInstance = (ReferencedInstance) instance; Assert.AreEqual(referenceKey, referencedInstance.ReferenceKey); } [Test] public void Create_a_default_instance() { MemoryInstanceMemento memento = MemoryInstanceMemento.CreateDefaultInstanceMemento(); Instance instance = memento.ReadInstance(null, GetType()); instance.ShouldBeOfType<DefaultInstance>(); } [Test] public void Create_a_referenced_instance() { MemoryInstanceMemento memento = MemoryInstanceMemento.CreateReferencedInstanceMemento("blue"); var instance = (ReferencedInstance) memento.ReadInstance(null, GetType()); Assert.AreEqual("blue", instance.ReferenceKey); } [Test] public void Get_the_instance_name() { var memento = new MemoryInstanceMemento("Color", "Red"); memento.SetPluggedType<ColorService>(); memento.SetProperty("Color", "Red"); memento.InstanceKey = "Red"; Assert.AreEqual("Red", memento.ReadInstance(new SimplePluginFactory(), typeof(IService)).Name); } [Test] public void ReadChildArrayProperty() { MemoryInstanceMemento memento = ComplexRule.GetMemento(); memento.SetPluggedType<ComplexRule>(); memento.AddChildArray("cars", new InstanceMemento[] { MemoryInstanceMemento.CreateReferencedInstanceMemento("Ford"), MemoryInstanceMemento.CreateReferencedInstanceMemento("Chevy"), MemoryInstanceMemento.CreateReferencedInstanceMemento("Dodge"), }); var instance = (IStructuredInstance)memento.ReadInstance(new SimplePluginFactory(), typeof(Rule)); Instance[] instances = instance.GetChildArray("cars"); Assert.AreEqual(3, instances.Length); assertIsReference(instances[0], "Ford"); assertIsReference(instances[1], "Chevy"); assertIsReference(instances[2], "Dodge"); } [Test] public void ReadChildProperty_child_property_is_defined_build_child() { var memento = ComplexRule.GetMemento(); memento.SetPluggedType<ComplexRule>(); MemoryInstanceMemento carMemento = MemoryInstanceMemento.CreateReferencedInstanceMemento("GrandPrix"); memento.AddChild("car", carMemento); var instance = (IStructuredInstance)memento.ReadInstance(new SimplePluginFactory(), typeof(Rule)); var child = (ReferencedInstance) instance.GetChild("car"); Assert.AreEqual("GrandPrix", child.ReferenceKey); } [Test] public void ReadPrimitivePropertiesHappyPath() { var memento = ComplexRule.GetMemento(); memento.SetPluggedType<ComplexRule>(); var instance = (IConfiguredInstance)memento.ReadInstance(new SimplePluginFactory(), typeof(Rule)); Assert.AreEqual(memento.GetProperty("String"), instance.GetProperty("String")); Assert.AreEqual(memento.GetProperty("Breed"), instance.GetProperty("Breed")); Assert.AreEqual(memento.GetProperty("Int"), instance.GetProperty("Int")); Assert.AreEqual(memento.GetProperty("Long"), instance.GetProperty("Long")); Assert.AreEqual(memento.GetProperty("Byte"), instance.GetProperty("Byte")); Assert.AreEqual(memento.GetProperty("Double"), instance.GetProperty("Double")); Assert.AreEqual(memento.GetProperty("Bool"), instance.GetProperty("Bool")); } } }
using System; using Csla; using ParentLoadSoftDelete.DataAccess; using ParentLoadSoftDelete.DataAccess.ERCLevel; namespace ParentLoadSoftDelete.Business.ERCLevel { /// <summary> /// F09_Region_Child (editable child object).<br/> /// This is a generated base class of <see cref="F09_Region_Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="F08_Region"/> collection. /// </remarks> [Serializable] public partial class F09_Region_Child : BusinessBase<F09_Region_Child> { #region State Fields [NotUndoable] [NonSerialized] internal int region_ID1 = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Region_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Region_Child_NameProperty = RegisterProperty<string>(p => p.Region_Child_Name, "Cities Child Name"); /// <summary> /// Gets or sets the Cities Child Name. /// </summary> /// <value>The Cities Child Name.</value> public string Region_Child_Name { get { return GetProperty(Region_Child_NameProperty); } set { SetProperty(Region_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="F09_Region_Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="F09_Region_Child"/> object.</returns> internal static F09_Region_Child NewF09_Region_Child() { return DataPortal.CreateChild<F09_Region_Child>(); } /// <summary> /// Factory method. Loads a <see cref="F09_Region_Child"/> object from the given F09_Region_ChildDto. /// </summary> /// <param name="data">The <see cref="F09_Region_ChildDto"/>.</param> /// <returns>A reference to the fetched <see cref="F09_Region_Child"/> object.</returns> internal static F09_Region_Child GetF09_Region_Child(F09_Region_ChildDto data) { F09_Region_Child obj = new F09_Region_Child(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(data); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="F09_Region_Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public F09_Region_Child() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="F09_Region_Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="F09_Region_Child"/> object from the given <see cref="F09_Region_ChildDto"/>. /// </summary> /// <param name="data">The F09_Region_ChildDto to use.</param> private void Fetch(F09_Region_ChildDto data) { // Value properties LoadProperty(Region_Child_NameProperty, data.Region_Child_Name); // parent properties region_ID1 = data.Parent_Region_ID; var args = new DataPortalHookArgs(data); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="F09_Region_Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(F08_Region parent) { var dto = new F09_Region_ChildDto(); dto.Parent_Region_ID = parent.Region_ID; dto.Region_Child_Name = Region_Child_Name; using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnInsertPre(args); var dal = dalManager.GetProvider<IF09_Region_ChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Insert(dto); args = new DataPortalHookArgs(resultDto); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="F09_Region_Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(F08_Region parent) { if (!IsDirty) return; var dto = new F09_Region_ChildDto(); dto.Parent_Region_ID = parent.Region_ID; dto.Region_Child_Name = Region_Child_Name; using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnUpdatePre(args); var dal = dalManager.GetProvider<IF09_Region_ChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Update(dto); args = new DataPortalHookArgs(resultDto); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="F09_Region_Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(F08_Region parent) { using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IF09_Region_ChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.Region_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void OrUInt64() { var test = new SimpleBinaryOpTest__OrUInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__OrUInt64 { private const int VectorSize = 16; private const int ElementCount = VectorSize / sizeof(UInt64); private static UInt64[] _data1 = new UInt64[ElementCount]; private static UInt64[] _data2 = new UInt64[ElementCount]; private static Vector128<UInt64> _clsVar1; private static Vector128<UInt64> _clsVar2; private Vector128<UInt64> _fld1; private Vector128<UInt64> _fld2; private SimpleBinaryOpTest__DataTable<UInt64> _dataTable; static SimpleBinaryOpTest__OrUInt64() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); _data2[i] = (ulong)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__OrUInt64() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); _data2[i] = (ulong)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); _data2[i] = (ulong)(random.Next(0, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt64>(_data1, _data2, new UInt64[ElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.Or( Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.Or( Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.Or( Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.Or( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr); var result = Sse2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)); var result = Sse2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)); var result = Sse2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__OrUInt64(); var result = Sse2.Or(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.Or(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<UInt64> left, Vector128<UInt64> right, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[ElementCount]; UInt64[] inArray2 = new UInt64[ElementCount]; UInt64[] outArray = new UInt64[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[ElementCount]; UInt64[] inArray2 = new UInt64[ElementCount]; UInt64[] outArray = new UInt64[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "") { if ((ulong)(left[0] | right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if ((ulong)(left[i] | right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Or)}<UInt64>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.ServiceModel.Discovery { using System; using System.Collections.Generic; using System.Runtime; using System.Text; using SR2 = System.ServiceModel.Discovery.SR; static class ScopeCompiler { public static string[] Compile(ICollection<Uri> scopes) { if (scopes == null || scopes.Count == 0) { return null; } List<string> compiledScopes = new List<string>(); foreach (Uri scope in scopes) { Compile(scope, compiledScopes); } return compiledScopes.ToArray(); } public static CompiledScopeCriteria[] CompileMatchCriteria(ICollection<Uri> scopes, Uri matchBy) { Fx.Assert(matchBy != null, "The matchBy must be non null."); if (scopes == null || scopes.Count == 0) { return null; } List<CompiledScopeCriteria> compiledCriterias = new List<CompiledScopeCriteria>(); foreach (Uri scope in scopes) { compiledCriterias.Add(CompileCriteria(scope, matchBy)); } return compiledCriterias.ToArray(); } public static bool IsSupportedMatchingRule(Uri matchBy) { Fx.Assert(matchBy != null, "The matchBy must be non null."); return (matchBy.Equals(FindCriteria.ScopeMatchByPrefix) || matchBy.Equals(FindCriteria.ScopeMatchByUuid) || matchBy.Equals(FindCriteria.ScopeMatchByLdap) || matchBy.Equals(FindCriteria.ScopeMatchByExact) || matchBy.Equals(FindCriteria.ScopeMatchByNone)); } public static bool IsMatch(CompiledScopeCriteria compiledScopeMatchCriteria, string[] compiledScopes) { Fx.Assert(compiledScopeMatchCriteria != null, "The compiledScopeMatchCriteria must be non null."); Fx.Assert(compiledScopes != null, "The compiledScopes must be non null."); if (compiledScopeMatchCriteria.MatchBy == CompiledScopeCriteriaMatchBy.Exact) { for (int i = 0; i < compiledScopes.Length; i++) { if (string.CompareOrdinal(compiledScopes[i], compiledScopeMatchCriteria.CompiledScope) == 0) { return true; } } } else if (compiledScopeMatchCriteria.MatchBy == CompiledScopeCriteriaMatchBy.StartsWith) { for (int i = 0; i < compiledScopes.Length; i++) { if (compiledScopes[i].StartsWith(compiledScopeMatchCriteria.CompiledScope, StringComparison.Ordinal)) { return true; } } } return false; } static void Compile(Uri scope, List<string> compiledScopes) { // MatchByRfc2396 can be applied to any URI compiledScopes.Add(CompileForMatchByRfc2396(scope)); // MatchByUuid can be applied to only UUIDs we treat urn:uuid:GUID same as uuid:GUID Guid guid; if (TryGetUuidGuid(scope, out guid)) { compiledScopes.Add(CompileForMatchByUuid(guid)); } // MatchByStrcmp0 can be applied to any URI compiledScopes.Add(CompileForMatchByStrcmp0(scope)); // MatchByLdap can be applied to only LDAP URI if (string.Compare(scope.Scheme, "ldap", StringComparison.OrdinalIgnoreCase) == 0) { compiledScopes.Add(CompileForMatchByLdap(scope)); } } static CompiledScopeCriteria CompileCriteria(Uri scope, Uri matchBy) { string compiledScope; CompiledScopeCriteriaMatchBy compiledMatchBy; if (matchBy.Equals(FindCriteria.ScopeMatchByPrefix)) { compiledScope = CompileForMatchByRfc2396(scope); compiledMatchBy = CompiledScopeCriteriaMatchBy.StartsWith; } else if (matchBy.Equals(FindCriteria.ScopeMatchByUuid)) { Guid guid; if (!TryGetUuidGuid(scope, out guid)) { throw FxTrace.Exception.AsError(new FormatException(SR2.DiscoveryFormatInvalidScopeUuidUri(scope.ToString()))); } compiledScope = CompileForMatchByUuid(guid); compiledMatchBy = CompiledScopeCriteriaMatchBy.Exact; } else if (matchBy.Equals(FindCriteria.ScopeMatchByLdap)) { if (string.Compare(scope.Scheme, "ldap", StringComparison.OrdinalIgnoreCase) != 0) { throw FxTrace.Exception.AsError(new FormatException(SR2.DiscoveryFormatInvalidScopeLdapUri(scope.ToString()))); } compiledScope = CompileForMatchByLdap(scope); compiledMatchBy = CompiledScopeCriteriaMatchBy.StartsWith; } else if (matchBy.Equals(FindCriteria.ScopeMatchByExact)) { compiledScope = CompileForMatchByStrcmp0(scope); compiledMatchBy = CompiledScopeCriteriaMatchBy.Exact; } else { throw FxTrace.Exception.ArgumentOutOfRange("matchBy", matchBy, SR2.DiscoveryMatchingRuleNotSupported( FindCriteria.ScopeMatchByExact, FindCriteria.ScopeMatchByPrefix, FindCriteria.ScopeMatchByUuid, FindCriteria.ScopeMatchByLdap)); } return new CompiledScopeCriteria(compiledScope, compiledMatchBy); } static string CompileForMatchByRfc2396(Uri scope) { StringBuilder compiledScopeBuilder = new StringBuilder(); // Append the matching rule name, so this compiled scope can only be // matched for that particular matching rule. compiledScopeBuilder.Append("rfc2396match::"); // // Rule: Using a case-insensitive comparison, The scheme [RFC 2396] // of S1 and S2 is the same and // string scheme = scope.GetComponents(UriComponents.Scheme, UriFormat.UriEscaped); if (scheme != null) { scheme = scheme.ToUpperInvariant(); } else { scheme = string.Empty; } compiledScopeBuilder.Append(scheme); compiledScopeBuilder.Append(":"); // // Rule: Using a case-insensitive comparison, The authority of S1 // and S2 is the same and // string authority = scope.GetComponents(UriComponents.StrongAuthority, UriFormat.UriEscaped); if (authority != null) { authority = authority.ToUpperInvariant(); } else { authority = string.Empty; } compiledScopeBuilder.Append(authority); compiledScopeBuilder.Append(":"); // // Rule: The path_segments of S1 is a segment-wise (not string) // prefix of the path_segments of S2 and Neither S1 nor S2 // contain the "." segment or the ".." segment. All other // components (e.g., query and fragment) are explicitly // excluded from comparison. S1 and S2 MUST be canonicalized // (e.g., unescaping escaped characters) before using this // matching rule. foreach (string segment in scope.Segments) { compiledScopeBuilder.Append(ProcessUriSegment(segment)); } return compiledScopeBuilder.ToString(); } static string ProcessUriSegment(string segment) { // ignore the segment parameters, if any int index = segment.IndexOf(';'); if (index != -1) { segment = segment.Substring(0, index); } // prevent the comparision of partial segments // Note: this matching rule does NOT test whether the string // representation of S1 is a prefix of the string representation // of S2. For example, "http://example.com/abc" matches // "http://example.com/abc/def" using this rule but // "http://example.com/a" does not. if (!segment.EndsWith("/", StringComparison.Ordinal)) { segment = segment + "/"; } return segment; } static bool TryGetUuidGuid(Uri scope, out Guid guid) { string guidString = null; if (string.Compare(scope.Scheme, "uuid", StringComparison.OrdinalIgnoreCase) == 0) { guidString = scope.GetComponents(UriComponents.Path, UriFormat.UriEscaped); } else if (string.Compare(scope.Scheme, "urn", StringComparison.OrdinalIgnoreCase) == 0) { string scopeString = scope.ToString(); if (string.Compare(scopeString, 4, "uuid:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0) { guidString = scopeString.Substring(9); } } return Fx.TryCreateGuid(guidString, out guid); } static string CompileForMatchByUuid(Guid guid) { // Append the matching rule name, so this compiled scope can only be // matched for that particular matching rule. // // Rule: Using a case-insensitive comparison, the scheme of S1 and // S2 is "uuid" and each of the unsigned integer fields [UUID] // in S1 is equal to the corresponding field in S2, or // equivalently, the 128 bits of the in-memory representation // of S1 and S2 are the same 128 bit unsigned integer. return "uuidmatch::" + guid.ToString(); } static string CompileForMatchByStrcmp0(Uri scope) { // // Rule: Using a case-sensitive comparison, the string // representation of S1 and S2 is the same. // return "strcmp0match::" + scope.ToString(); } static string CompileForMatchByLdap(Uri scope) { StringBuilder compiledScopeBuilder = new StringBuilder(); // Append the matching rule name, so this compiled scope can only be // matched for that particular matching rule. compiledScopeBuilder.Append("ldapmatch::"); // // Rule: Using a case-insensitive comparison, the scheme of S1 // and S2 is "ldap" and compiledScopeBuilder.Append("ldap:"); // // Rule: and the hostport [RFC 2255] of S1 and S2 is the // same and // string hostport = scope.GetComponents(UriComponents.HostAndPort, UriFormat.UriEscaped); if (hostport != null) { hostport = hostport.ToUpperInvariant(); } else { hostport = string.Empty; } compiledScopeBuilder.Append(hostport); compiledScopeBuilder.Append(":"); // // Rule: and the RDNSequence [RFC 2253] of the dn of S1 is a // prefix of the RDNSequence of the dn of S2, where comparison // does not support the variants in an RDNSequence described // in Section 4 of RFC 2253 [RFC 2253]. // // get the ldap DN string. string dn = scope.GetComponents(UriComponents.Path, UriFormat.Unescaped); // parse the RDNs in order from DN compiledScopeBuilder.Append(ParseLdapRDNSequence(dn)); return compiledScopeBuilder.ToString(); } static string ParseLdapRDNSequence(string dn) { // Assuming the conversion of DN to string as per Section 2 RFC2253 // ignoring the variations described in section 4. StringBuilder rdnSequenceBuilder = new StringBuilder(); string[] tokens = dn.Split(','); StringBuilder rdnBuilder = new StringBuilder(); foreach (string token in tokens) { if (string.IsNullOrEmpty(token.Trim())) { continue; } if (token.EndsWith("\\", StringComparison.Ordinal)) { // it is part of the RDN rdnBuilder.Append(token.Substring(0, token.Length - 1)); rdnBuilder.Append(','); } else { // RDN ends here. rdnBuilder.Append(token); rdnSequenceBuilder.Insert(0, "/"); rdnSequenceBuilder.Insert(0, ParseAndSortRDNAttributes(rdnBuilder.ToString())); rdnBuilder = new StringBuilder(); } } return rdnSequenceBuilder.ToString(); } static string ParseAndSortRDNAttributes(string rdn) { // // Rule: RFC2253 Section 2: // When converting from an ASN.1 RelativeDistinguishedName // to a string, the output consists of the string encodings // of each AttributeTypeAndValue (according to 2.3), in any // order. Where there is a multi-valued RDN, the outputs // from adjoining AttributeTypeAndValues are separated by // a plus ('+' ASCII 43) character. // // since the RDN attributes can be converted to string in any order // we must make sure that the compiled form of the scope and match // criteria have the same order so that simple string prefix // comparision produces the same result of comparing the RDN // attribute values individually, we sort the attributes or RDN // based on their name. // optimize the case where there is only one attrvalue for RDN if (rdn.IndexOf('+') == -1) { return rdn; } string[] tokens = rdn.Split('+'); StringBuilder attrTypeAndValueBuilder = new StringBuilder(); Dictionary<string, string> attrTypeValueTable = new Dictionary<string, string>(); List<string> attrTypeList = new List<string>(); foreach (string token in tokens) { if (string.IsNullOrEmpty(token.Trim())) { continue; } if (token.EndsWith("\\", StringComparison.Ordinal)) { // it is part of the attribute value attrTypeAndValueBuilder.Append(token.Substring(0, token.Length - 1)); attrTypeAndValueBuilder.Append('+'); } else { // attribute value ends here. attrTypeAndValueBuilder.Append(token); // get attribute and value. string attrTypeAndValue = attrTypeAndValueBuilder.ToString(); string attrType = attrTypeAndValue; string attrValue = null; int equalIndex = attrTypeAndValue.IndexOf('='); if (equalIndex != -1) { attrType = attrTypeAndValue.Substring(0, equalIndex); attrValue = attrTypeAndValue.Substring(equalIndex + 1); } attrTypeList.Add(attrType); attrTypeValueTable.Add(attrType, attrValue); attrTypeAndValueBuilder = new StringBuilder(); } } // sort the list based on the attribute type attrTypeList.Sort(); // created the RDN from the sorted attribute values. StringBuilder rdnBuilder = new StringBuilder(); for (int i = 0; i < attrTypeList.Count - 1; i++) { rdnBuilder.Append(attrTypeList[i]); if (attrTypeValueTable[attrTypeList[i]] != null) { rdnBuilder.Append("="); rdnBuilder.Append(attrTypeValueTable[attrTypeList[i]]); } rdnBuilder.Append("+"); } if (attrTypeList.Count > 1) { rdnBuilder.Append(attrTypeList[attrTypeList.Count - 1]); if (attrTypeValueTable[attrTypeList[attrTypeList.Count - 1]] != null) { rdnBuilder.Append("="); rdnBuilder.Append(attrTypeValueTable[attrTypeList[attrTypeList.Count - 1]]); } rdnBuilder.Append("+"); } return rdnBuilder.ToString(); } } }
// LzBinTree.cs using System; namespace SevenZip.Compression.LZ { public class BinTree : InWindow, IMatchFinder { private UInt32 _cyclicBufferPos; private UInt32 _cyclicBufferSize = 0; private UInt32 _matchMaxLen; private UInt32[] _son; private UInt32[] _hash; private UInt32 _cutValue = 0xFF; private UInt32 _hashMask; private UInt32 _hashSizeSum = 0; private bool HASH_ARRAY = true; private const UInt32 kHash2Size = 1 << 10; private const UInt32 kHash3Size = 1 << 16; private const UInt32 kBT2HashSize = 1 << 16; private const UInt32 kStartMaxLen = 1; private const UInt32 kHash3Offset = kHash2Size; private const UInt32 kEmptyHashValue = 0; private const UInt32 kMaxValForNormalize = ((UInt32)1 << 31) - 1; private UInt32 kNumHashDirectBytes = 0; private UInt32 kMinMatchCheck = 4; private UInt32 kFixHashSize = kHash2Size + kHash3Size; public void SetType(int numHashBytes) { HASH_ARRAY = (numHashBytes > 2); if (HASH_ARRAY) { kNumHashDirectBytes = 0; kMinMatchCheck = 4; kFixHashSize = kHash2Size + kHash3Size; } else { kNumHashDirectBytes = 2; kMinMatchCheck = 2 + 1; kFixHashSize = 0; } } public new void SetStream(System.IO.Stream stream) { base.SetStream(stream); } public new void ReleaseStream() { base.ReleaseStream(); } public new void Init() { base.Init(); for (UInt32 i = 0; i < _hashSizeSum; i++) _hash[i] = kEmptyHashValue; _cyclicBufferPos = 0; ReduceOffsets(-1); } public new void MovePos() { if (++_cyclicBufferPos >= _cyclicBufferSize) _cyclicBufferPos = 0; base.MovePos(); if (_pos == kMaxValForNormalize) Normalize(); } public new Byte GetIndexByte(Int32 index) { return base.GetIndexByte(index); } public new UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit) { return base.GetMatchLen(index, distance, limit); } public new UInt32 GetNumAvailableBytes() { return base.GetNumAvailableBytes(); } public void Create(UInt32 historySize, UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter) { if (historySize > kMaxValForNormalize - 256) throw new Exception(); _cutValue = 16 + (matchMaxLen >> 1); UInt32 windowReservSize = (historySize + keepAddBufferBefore + matchMaxLen + keepAddBufferAfter) / 2 + 256; base.Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, windowReservSize); _matchMaxLen = matchMaxLen; UInt32 cyclicBufferSize = historySize + 1; if (_cyclicBufferSize != cyclicBufferSize) _son = new UInt32[(_cyclicBufferSize = cyclicBufferSize) * 2]; UInt32 hs = kBT2HashSize; if (HASH_ARRAY) { hs = historySize - 1; hs |= (hs >> 1); hs |= (hs >> 2); hs |= (hs >> 4); hs |= (hs >> 8); hs >>= 1; hs |= 0xFFFF; if (hs > (1 << 24)) hs >>= 1; _hashMask = hs; hs++; hs += kFixHashSize; } if (hs != _hashSizeSum) _hash = new UInt32[_hashSizeSum = hs]; } public UInt32 GetMatches(UInt32[] distances) { UInt32 lenLimit; if (_pos + _matchMaxLen <= _streamPos) lenLimit = _matchMaxLen; else { lenLimit = _streamPos - _pos; if (lenLimit < kMinMatchCheck) { MovePos(); return 0; } } UInt32 offset = 0; UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; UInt32 cur = _bufferOffset + _pos; UInt32 maxLen = kStartMaxLen; // to avoid items for len < hashSize; UInt32 hashValue, hash2Value = 0, hash3Value = 0; if (HASH_ARRAY) { UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1]; hash2Value = temp & (kHash2Size - 1); temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8); hash3Value = temp & (kHash3Size - 1); hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask; } else hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8); UInt32 curMatch = _hash[kFixHashSize + hashValue]; if (HASH_ARRAY) { UInt32 curMatch2 = _hash[hash2Value]; UInt32 curMatch3 = _hash[kHash3Offset + hash3Value]; _hash[hash2Value] = _pos; _hash[kHash3Offset + hash3Value] = _pos; if (curMatch2 > matchMinPos) if (_bufferBase[_bufferOffset + curMatch2] == _bufferBase[cur]) { distances[offset++] = maxLen = 2; distances[offset++] = _pos - curMatch2 - 1; } if (curMatch3 > matchMinPos) if (_bufferBase[_bufferOffset + curMatch3] == _bufferBase[cur]) { if (curMatch3 == curMatch2) offset -= 2; distances[offset++] = maxLen = 3; distances[offset++] = _pos - curMatch3 - 1; curMatch2 = curMatch3; } if (offset != 0 && curMatch2 == curMatch) { offset -= 2; maxLen = kStartMaxLen; } } _hash[kFixHashSize + hashValue] = _pos; UInt32 ptr0 = (_cyclicBufferPos << 1) + 1; UInt32 ptr1 = (_cyclicBufferPos << 1); UInt32 len0, len1; len0 = len1 = kNumHashDirectBytes; if (kNumHashDirectBytes != 0) { if (curMatch > matchMinPos) { if (_bufferBase[_bufferOffset + curMatch + kNumHashDirectBytes] != _bufferBase[cur + kNumHashDirectBytes]) { distances[offset++] = maxLen = kNumHashDirectBytes; distances[offset++] = _pos - curMatch - 1; } } } UInt32 count = _cutValue; while (true) { if (curMatch <= matchMinPos || count-- == 0) { _son[ptr0] = _son[ptr1] = kEmptyHashValue; break; } UInt32 delta = _pos - curMatch; UInt32 cyclicPos = ((delta <= _cyclicBufferPos) ? (_cyclicBufferPos - delta) : (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; UInt32 pby1 = _bufferOffset + curMatch; UInt32 len = Math.Min(len0, len1); if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) { while (++len != lenLimit) if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) break; if (maxLen < len) { distances[offset++] = maxLen = len; distances[offset++] = delta - 1; if (len == lenLimit) { _son[ptr1] = _son[cyclicPos]; _son[ptr0] = _son[cyclicPos + 1]; break; } } } if (_bufferBase[pby1 + len] < _bufferBase[cur + len]) { _son[ptr1] = curMatch; ptr1 = cyclicPos + 1; curMatch = _son[ptr1]; len1 = len; } else { _son[ptr0] = curMatch; ptr0 = cyclicPos; curMatch = _son[ptr0]; len0 = len; } } MovePos(); return offset; } public void Skip(UInt32 num) { do { UInt32 lenLimit; if (_pos + _matchMaxLen <= _streamPos) lenLimit = _matchMaxLen; else { lenLimit = _streamPos - _pos; if (lenLimit < kMinMatchCheck) { MovePos(); continue; } } UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; UInt32 cur = _bufferOffset + _pos; UInt32 hashValue; if (HASH_ARRAY) { UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1]; UInt32 hash2Value = temp & (kHash2Size - 1); _hash[hash2Value] = _pos; temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8); UInt32 hash3Value = temp & (kHash3Size - 1); _hash[kHash3Offset + hash3Value] = _pos; hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask; } else hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8); UInt32 curMatch = _hash[kFixHashSize + hashValue]; _hash[kFixHashSize + hashValue] = _pos; UInt32 ptr0 = (_cyclicBufferPos << 1) + 1; UInt32 ptr1 = (_cyclicBufferPos << 1); UInt32 len0, len1; len0 = len1 = kNumHashDirectBytes; UInt32 count = _cutValue; while (true) { if (curMatch <= matchMinPos || count-- == 0) { _son[ptr0] = _son[ptr1] = kEmptyHashValue; break; } UInt32 delta = _pos - curMatch; UInt32 cyclicPos = ((delta <= _cyclicBufferPos) ? (_cyclicBufferPos - delta) : (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; UInt32 pby1 = _bufferOffset + curMatch; UInt32 len = Math.Min(len0, len1); if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) { while (++len != lenLimit) if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) break; if (len == lenLimit) { _son[ptr1] = _son[cyclicPos]; _son[ptr0] = _son[cyclicPos + 1]; break; } } if (_bufferBase[pby1 + len] < _bufferBase[cur + len]) { _son[ptr1] = curMatch; ptr1 = cyclicPos + 1; curMatch = _son[ptr1]; len1 = len; } else { _son[ptr0] = curMatch; ptr0 = cyclicPos; curMatch = _son[ptr0]; len0 = len; } } MovePos(); } while (--num != 0); } private void NormalizeLinks(UInt32[] items, UInt32 numItems, UInt32 subValue) { for (UInt32 i = 0; i < numItems; i++) { UInt32 value = items[i]; if (value <= subValue) value = kEmptyHashValue; else value -= subValue; items[i] = value; } } private void Normalize() { UInt32 subValue = _pos - _cyclicBufferSize; NormalizeLinks(_son, _cyclicBufferSize * 2, subValue); NormalizeLinks(_hash, _hashSizeSum, subValue); ReduceOffsets((Int32)subValue); } public void SetCutValue(UInt32 cutValue) { _cutValue = cutValue; } } }
#region Using Statements using System; using WaveEngine.Common; using WaveEngine.Common.Graphics; using WaveEngine.Common.Math; using WaveEngine.Common.Media; using WaveEngine.Components.Cameras; using WaveEngine.Components.Graphics2D; using WaveEngine.Components.Graphics3D; using WaveEngine.Components.UI; using WaveEngine.Framework; using WaveEngine.Framework.Graphics; using WaveEngine.Framework.Resources; using WaveEngine.Framework.Services; using WaveEngine.Materials; #endregion namespace CameraCaptureProject { public class MyScene : Scene { private bool isRecording = false; private bool isVideoPlaying = false; private string finalVideoPath; Entity TvRoomEntity; Button RecBtn; Button PlayRecordedBtn; protected override void CreateScene() { FreeCamera camera = new FreeCamera("camera", new Vector3(-1.3f, 1.6f, 2.5f), new Vector3(-0.25f, 1.375f, 1.275f)) { Speed = 5, NearPlane = 0.1f }; EntityManager.Add(camera); this.TvRoomEntity = new Entity("tvRoom") .AddComponent(new Transform3D()) .AddComponent(new Model("Content/TvRoom.wpk")) .AddComponent(new ModelRenderer()) .AddComponent(new MaterialsMap(new System.Collections.Generic.Dictionary<string, Material> { {"floor", new DualTextureMaterial("Content/parketFloor_Difuse.wpk", "Content/TvRoomLightingMap.wpk", DefaultLayers.Opaque)}, {"tv", new DualTextureMaterial("Content/Tv_Difuse.wpk", "Content/TvRoomLightingMap.wpk", DefaultLayers.Opaque)}, {"table", new DualTextureMaterial("Content/table_Difuse.wpk", "Content/TvRoomLightingMap.wpk", DefaultLayers.Opaque)}, {"chair", new DualTextureMaterial("Content/Chair_Difuse.wpk", "Content/TvRoomLightingMap.wpk", DefaultLayers.Opaque)}, // Camera preview texture used in a basic material {"tv_screen", new BasicMaterial(Color.Black)} } )); EntityManager.Add(this.TvRoomEntity); if (WaveServices.CameraCapture.IsConnected) { StackPanel controlPanel = new StackPanel() { VerticalAlignment = WaveEngine.Framework.UI.VerticalAlignment.Bottom, HorizontalAlignment = WaveEngine.Framework.UI.HorizontalAlignment.Right, Margin = new WaveEngine.Framework.UI.Thickness(0, 0, 30, 30), BorderColor = Color.White, IsBorder = true, }; this.RecBtn = new Button("RecBtn") { Text = "Start Rec", Margin = new WaveEngine.Framework.UI.Thickness(5, 5, 5, 0), Width = 170 }; controlPanel.Add(this.RecBtn); this.PlayRecordedBtn = new Button("PlayRecordedBtn") { Text = "Play", Width = 170, Margin = new WaveEngine.Framework.UI.Thickness(5, 0, 5, 5), Opacity = 0.5f }; controlPanel.Add(this.PlayRecordedBtn); this.RecBtn.Click += (e, s) => { if (!this.isRecording) { this.StartRecording(); } else { this.StopRecording(); } }; this.PlayRecordedBtn.Click += (e, s) => { if (!this.isVideoPlaying) { this.PlayVideo(); } else { this.StopVideo(); } }; EntityManager.Add(controlPanel); } else { TextBlock text = new TextBlock() { Text = "There is no connected camera", Width = 300, VerticalAlignment = WaveEngine.Framework.UI.VerticalAlignment.Bottom, HorizontalAlignment = WaveEngine.Framework.UI.HorizontalAlignment.Right, Margin = new WaveEngine.Framework.UI.Thickness(0, 0, 30, 30) }; EntityManager.Add(text); } } protected override void Start() { base.Start(); if (WaveServices.CameraCapture.IsConnected) { WaveServices.VideoPlayer.OnComplete += (s, e) => { this.StopVideo(); }; WaveServices.CameraCapture.Start(CameraCaptureType.Front); this.TvRoomEntity.FindComponent<MaterialsMap>().Materials["tv_screen"] = new BasicMaterial(WaveServices.CameraCapture.PreviewTexture); this.TvRoomEntity.RefreshDependencies(); } } protected override void End() { if (WaveServices.CameraCapture.IsConnected) { WaveServices.CameraCapture.Stop(); } base.End(); } private void StartRecording() { if (WaveServices.CameraCapture.IsConnected) { this.isRecording = true; this.RecBtn.Text = "Stop Rec"; WaveServices.CameraCapture.StartRecording("MyVideo.mp4"); } } private void StopRecording() { if (WaveServices.CameraCapture.IsConnected) { if (WaveServices.CameraCapture.State != CameraCaptureState.Recording) { return; } this.isRecording = false; this.RecBtn.Text = "Start Rec"; this.finalVideoPath = WaveServices.CameraCapture.StopRecording(); if (this.finalVideoPath != null) { this.PlayRecordedBtn.Opacity = 1f; } } } private void PlayVideo() { this.StopRecording(); if (this.finalVideoPath != null) { VideoInfo videoInfo = WaveServices.VideoPlayer.VideoInfoFromPath(this.finalVideoPath); WaveServices.VideoPlayer.Play(videoInfo); this.TvRoomEntity.FindComponent<MaterialsMap>().Materials["tv_screen"] = new BasicMaterial(WaveServices.VideoPlayer.VideoTexture); this.TvRoomEntity.RefreshDependencies(); this.PlayRecordedBtn.Text = "Stop"; this.isVideoPlaying = true; } } private void StopVideo() { if (WaveServices.VideoPlayer.State == VideoState.Playing) { WaveServices.VideoPlayer.Stop(); } this.TvRoomEntity.FindComponent<MaterialsMap>().Materials["tv_screen"] = new BasicMaterial(WaveServices.CameraCapture.PreviewTexture); this.TvRoomEntity.RefreshDependencies(); this.PlayRecordedBtn.Text = "Play"; this.isVideoPlaying = false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.AspNetCore.DataProtection.Abstractions; using Microsoft.Extensions.Internal; namespace Microsoft.AspNetCore.DataProtection { /// <summary> /// Helpful extension methods for data protection APIs. /// </summary> public static class DataProtectionCommonExtensions { /// <summary> /// Creates an <see cref="IDataProtector"/> given a list of purposes. /// </summary> /// <param name="provider">The <see cref="IDataProtectionProvider"/> from which to generate the purpose chain.</param> /// <param name="purposes">The list of purposes which contribute to the purpose chain. This list must /// contain at least one element, and it may not contain null elements.</param> /// <returns>An <see cref="IDataProtector"/> tied to the provided purpose chain.</returns> /// <remarks> /// This is a convenience method which chains together several calls to /// <see cref="IDataProtectionProvider.CreateProtector(string)"/>. See that method's /// documentation for more information. /// </remarks> public static IDataProtector CreateProtector(this IDataProtectionProvider provider, IEnumerable<string> purposes) { if (provider == null) { throw new ArgumentNullException(nameof(provider)); } if (purposes == null) { throw new ArgumentNullException(nameof(purposes)); } bool collectionIsEmpty = true; IDataProtectionProvider retVal = provider; foreach (string purpose in purposes) { if (purpose == null) { throw new ArgumentException(Resources.DataProtectionExtensions_NullPurposesCollection, nameof(purposes)); } retVal = retVal.CreateProtector(purpose) ?? CryptoUtil.Fail<IDataProtector>("CreateProtector returned null."); collectionIsEmpty = false; } if (collectionIsEmpty) { throw new ArgumentException(Resources.DataProtectionExtensions_NullPurposesCollection, nameof(purposes)); } Debug.Assert(retVal is IDataProtector); // CreateProtector is supposed to return an instance of this interface return (IDataProtector)retVal; } /// <summary> /// Creates an <see cref="IDataProtector"/> given a list of purposes. /// </summary> /// <param name="provider">The <see cref="IDataProtectionProvider"/> from which to generate the purpose chain.</param> /// <param name="purpose">The primary purpose used to create the <see cref="IDataProtector"/>.</param> /// <param name="subPurposes">An optional list of secondary purposes which contribute to the purpose chain. /// If this list is provided it cannot contain null elements.</param> /// <returns>An <see cref="IDataProtector"/> tied to the provided purpose chain.</returns> /// <remarks> /// This is a convenience method which chains together several calls to /// <see cref="IDataProtectionProvider.CreateProtector(string)"/>. See that method's /// documentation for more information. /// </remarks> public static IDataProtector CreateProtector(this IDataProtectionProvider provider, string purpose, params string[] subPurposes) { if (provider == null) { throw new ArgumentNullException(nameof(provider)); } if (purpose == null) { throw new ArgumentNullException(nameof(purpose)); } // The method signature isn't simply CreateProtector(this IDataProtectionProvider, params string[] purposes) // because we don't want the code provider.CreateProtector() [parameterless] to inadvertently compile. // The actual signature for this method forces at least one purpose to be provided at the call site. IDataProtector? protector = provider.CreateProtector(purpose); if (subPurposes != null && subPurposes.Length > 0) { protector = protector?.CreateProtector((IEnumerable<string>)subPurposes); } return protector ?? CryptoUtil.Fail<IDataProtector>("CreateProtector returned null."); } /// <summary> /// Retrieves an <see cref="IDataProtectionProvider"/> from an <see cref="IServiceProvider"/>. /// </summary> /// <param name="services">The service provider from which to retrieve the <see cref="IDataProtectionProvider"/>.</param> /// <returns>An <see cref="IDataProtectionProvider"/>. This method is guaranteed never to return null.</returns> /// <exception cref="InvalidOperationException">If no <see cref="IDataProtectionProvider"/> service exists in <paramref name="services"/>.</exception> public static IDataProtectionProvider GetDataProtectionProvider(this IServiceProvider services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } // We have our own implementation of GetRequiredService<T> since we don't want to // take a dependency on DependencyInjection.Interfaces. var provider = (IDataProtectionProvider?)services.GetService(typeof(IDataProtectionProvider)); if (provider == null) { throw new InvalidOperationException(Resources.FormatDataProtectionExtensions_NoService(typeof(IDataProtectionProvider).FullName)); } return provider; } /// <summary> /// Retrieves an <see cref="IDataProtector"/> from an <see cref="IServiceProvider"/> given a list of purposes. /// </summary> /// <param name="services">An <see cref="IServiceProvider"/> which contains the <see cref="IDataProtectionProvider"/> /// from which to generate the purpose chain.</param> /// <param name="purposes">The list of purposes which contribute to the purpose chain. This list must /// contain at least one element, and it may not contain null elements.</param> /// <returns>An <see cref="IDataProtector"/> tied to the provided purpose chain.</returns> /// <remarks> /// This is a convenience method which calls <see cref="GetDataProtectionProvider(IServiceProvider)"/> /// then <see cref="CreateProtector(IDataProtectionProvider, IEnumerable{string})"/>. See those methods' /// documentation for more information. /// </remarks> public static IDataProtector GetDataProtector(this IServiceProvider services, IEnumerable<string> purposes) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (purposes == null) { throw new ArgumentNullException(nameof(purposes)); } return services.GetDataProtectionProvider().CreateProtector(purposes); } /// <summary> /// Retrieves an <see cref="IDataProtector"/> from an <see cref="IServiceProvider"/> given a list of purposes. /// </summary> /// <param name="services">An <see cref="IServiceProvider"/> which contains the <see cref="IDataProtectionProvider"/> /// from which to generate the purpose chain.</param> /// <param name="purpose">The primary purpose used to create the <see cref="IDataProtector"/>.</param> /// <param name="subPurposes">An optional list of secondary purposes which contribute to the purpose chain. /// If this list is provided it cannot contain null elements.</param> /// <returns>An <see cref="IDataProtector"/> tied to the provided purpose chain.</returns> /// <remarks> /// This is a convenience method which calls <see cref="GetDataProtectionProvider(IServiceProvider)"/> /// then <see cref="CreateProtector(IDataProtectionProvider, string, string[])"/>. See those methods' /// documentation for more information. /// </remarks> public static IDataProtector GetDataProtector(this IServiceProvider services, string purpose, params string[] subPurposes) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (purpose == null) { throw new ArgumentNullException(nameof(purpose)); } return services.GetDataProtectionProvider().CreateProtector(purpose, subPurposes); } /// <summary> /// Cryptographically protects a piece of plaintext data. /// </summary> /// <param name="protector">The data protector to use for this operation.</param> /// <param name="plaintext">The plaintext data to protect.</param> /// <returns>The protected form of the plaintext data.</returns> public static string Protect(this IDataProtector protector, string plaintext) { if (protector == null) { throw new ArgumentNullException(nameof(protector)); } if (plaintext == null) { throw new ArgumentNullException(nameof(plaintext)); } try { byte[] plaintextAsBytes = EncodingUtil.SecureUtf8Encoding.GetBytes(plaintext); byte[] protectedDataAsBytes = protector.Protect(plaintextAsBytes); return WebEncoders.Base64UrlEncode(protectedDataAsBytes); } catch (Exception ex) when (ex.RequiresHomogenization()) { // Homogenize exceptions to CryptographicException throw Error.CryptCommon_GenericError(ex); } } /// <summary> /// Cryptographically unprotects a piece of protected data. /// </summary> /// <param name="protector">The data protector to use for this operation.</param> /// <param name="protectedData">The protected data to unprotect.</param> /// <returns>The plaintext form of the protected data.</returns> /// <exception cref="System.Security.Cryptography.CryptographicException"> /// Thrown if <paramref name="protectedData"/> is invalid or malformed. /// </exception> public static string Unprotect(this IDataProtector protector, string protectedData) { if (protector == null) { throw new ArgumentNullException(nameof(protector)); } if (protectedData == null) { throw new ArgumentNullException(nameof(protectedData)); } try { byte[] protectedDataAsBytes = WebEncoders.Base64UrlDecode(protectedData); byte[] plaintextAsBytes = protector.Unprotect(protectedDataAsBytes); return EncodingUtil.SecureUtf8Encoding.GetString(plaintextAsBytes); } catch (Exception ex) when (ex.RequiresHomogenization()) { // Homogenize exceptions to CryptographicException throw Error.CryptCommon_GenericError(ex); } } } }
namespace Benchmark.Flattening { using System; using MicroMapper; public class CtorMapper : IObjectToObjectMapper { private Model11 _model; public string Name => nameof(CtorMapper); public void Initialize() { Mapper.Initialize(cfg => cfg.CreateMap<Model11, Dto11>()); _model = new Model11 {Value = 5}; } public void Map() { Mapper.Map<Model11, Dto11>(_model); } } public class ManualCtorMapper : IObjectToObjectMapper { private Model11 _model; public string Name => nameof(ManualCtorMapper); public void Initialize() { _model = new Model11 {Value = 5}; } public void Map() { var dto = new Dto11(_model.Value); } } public class FlatteningMapper : IObjectToObjectMapper { private ModelObject _source; public string Name => nameof(FlatteningMapper); public void Initialize() { Mapper.Initialize(cfg => { cfg.CreateMap<Model1, Dto1>(); cfg.CreateMap<Model2, Dto2>(); cfg.CreateMap<Model3, Dto3>(); cfg.CreateMap<Model4, Dto4>(); cfg.CreateMap<Model5, Dto5>(); cfg.CreateMap<Model6, Dto6>(); cfg.CreateMap<Model7, Dto7>(); cfg.CreateMap<Model8, Dto8>(); cfg.CreateMap<Model9, Dto9>(); cfg.CreateMap<Model10, Dto10>(); cfg.CreateMap<ModelObject, ModelDto>(); }); Mapper.AssertConfigurationIsValid(); _source = new ModelObject { BaseDate = new DateTime(2007, 4, 5), Sub = new ModelSubObject { ProperName = "Some name", SubSub = new ModelSubSubObject {IAmACoolProperty = "Cool daddy-o"} }, Sub2 = new ModelSubObject {ProperName = "Sub 2 name"}, SubWithExtraName = new ModelSubObject {ProperName = "Some other name"} }; } public void Map() { Mapper.Map<ModelObject, ModelDto>(_source); } } public class ManualMapper : IObjectToObjectMapper { private ModelObject _source; public string Name => nameof(ManualMapper); public void Initialize() { _source = new ModelObject { BaseDate = new DateTime(2007, 4, 5), Sub = new ModelSubObject { ProperName = "Some name", SubSub = new ModelSubSubObject {IAmACoolProperty = "Cool daddy-o"} }, Sub2 = new ModelSubObject {ProperName = "Sub 2 name"}, SubWithExtraName = new ModelSubObject {ProperName = "Some other name"} }; } public void Map() { var destination = new ModelDto { BaseDate = _source.BaseDate, Sub2ProperName = _source.Sub2.ProperName, SubProperName = _source.Sub.ProperName, SubSubSubIAmACoolProperty = _source.Sub.SubSub.IAmACoolProperty, SubWithExtraNameProperName = _source.SubWithExtraName.ProperName }; } } public class Model1 { public int Value { get; set; } } public class Model2 { public int Value { get; set; } } public class Model3 { public int Value { get; set; } } public class Model4 { public int Value { get; set; } } public class Model5 { public int Value { get; set; } } public class Model6 { public int Value { get; set; } } public class Model7 { public int Value { get; set; } } public class Model8 { public int Value { get; set; } } public class Model9 { public int Value { get; set; } } public class Model10 { public int Value { get; set; } } public class Model11 { public int Value { get; set; } } public class Dto1 { public int Value { get; set; } } public class Dto2 { public int Value { get; set; } } public class Dto3 { public int Value { get; set; } } public class Dto4 { public int Value { get; set; } } public class Dto5 { public int Value { get; set; } } public class Dto6 { public int Value { get; set; } } public class Dto7 { public int Value { get; set; } } public class Dto8 { public int Value { get; set; } } public class Dto9 { public int Value { get; set; } } public class Dto10 { public int Value { get; set; } } public class Dto11 { public Dto11(int value) { Value = value; } public int Value { get; } } public class ModelObject { public DateTime BaseDate { get; set; } public ModelSubObject Sub { get; set; } public ModelSubObject Sub2 { get; set; } public ModelSubObject SubWithExtraName { get; set; } } public class ModelSubObject { public string ProperName { get; set; } public ModelSubSubObject SubSub { get; set; } } public class ModelSubSubObject { public string IAmACoolProperty { get; set; } } public class ModelDto { public DateTime BaseDate { get; set; } public string SubProperName { get; set; } public string Sub2ProperName { get; set; } public string SubWithExtraNameProperName { get; set; } public string SubSubSubIAmACoolProperty { get; set; } } }
using System; using System.Globalization; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Abp.Application.Features; using Abp.Authorization; using Abp.Configuration; using Abp.Dependency; using Abp.Domain.Uow; using Abp.Events.Bus; using Abp.Events.Bus.Exceptions; using Abp.Localization; using Abp.Localization.Sources; using Abp.Logging; using Abp.Reflection; using Abp.Runtime.Session; using Abp.Web.Models; using Abp.Web.Mvc.Configuration; using Abp.Web.Mvc.Controllers.Results; using Abp.Web.Mvc.Extensions; using Abp.Web.Mvc.Models; using Castle.Core.Logging; namespace Abp.Web.Mvc.Controllers { /// <summary> /// Base class for all MVC Controllers in Abp system. /// </summary> public abstract class AbpController : Controller { /// <summary> /// Gets current session information. /// </summary> public IAbpSession AbpSession { get; set; } /// <summary> /// Gets the event bus. /// </summary> public IEventBus EventBus { get; set; } /// <summary> /// Reference to the permission manager. /// </summary> public IPermissionManager PermissionManager { get; set; } /// <summary> /// Reference to the setting manager. /// </summary> public ISettingManager SettingManager { get; set; } /// <summary> /// Reference to the permission checker. /// </summary> public IPermissionChecker PermissionChecker { protected get; set; } /// <summary> /// Reference to the feature manager. /// </summary> public IFeatureManager FeatureManager { protected get; set; } /// <summary> /// Reference to the permission checker. /// </summary> public IFeatureChecker FeatureChecker { protected get; set; } /// <summary> /// Reference to the localization manager. /// </summary> public ILocalizationManager LocalizationManager { protected get; set; } /// <summary> /// Reference to the error info builder. /// </summary> public IErrorInfoBuilder ErrorInfoBuilder { protected get; set; } /// <summary> /// Gets/sets name of the localization source that is used in this application service. /// It must be set in order to use <see cref="L(string)"/> and <see cref="L(string,CultureInfo)"/> methods. /// </summary> protected string LocalizationSourceName { get; set; } /// <summary> /// Gets localization source. /// It's valid if <see cref="LocalizationSourceName"/> is set. /// </summary> protected ILocalizationSource LocalizationSource { get { if (LocalizationSourceName == null) { throw new AbpException("Must set LocalizationSourceName before, in order to get LocalizationSource"); } if (_localizationSource == null || _localizationSource.Name != LocalizationSourceName) { _localizationSource = LocalizationManager.GetSource(LocalizationSourceName); } return _localizationSource; } } private ILocalizationSource _localizationSource; /// <summary> /// Reference to the logger to write logs. /// </summary> public ILogger Logger { get; set; } /// <summary> /// Gets current session information. /// </summary> [Obsolete("Use AbpSession property instead. CurrentSession will be removed in future releases.")] protected IAbpSession CurrentSession { get { return AbpSession; } } /// <summary> /// Reference to <see cref="IUnitOfWorkManager"/>. /// </summary> public IUnitOfWorkManager UnitOfWorkManager { get { if (_unitOfWorkManager == null) { throw new AbpException("Must set UnitOfWorkManager before use it."); } return _unitOfWorkManager; } set { _unitOfWorkManager = value; } } private IUnitOfWorkManager _unitOfWorkManager; /// <summary> /// Gets current unit of work. /// </summary> protected IActiveUnitOfWork CurrentUnitOfWork { get { return UnitOfWorkManager.Current; } } public IIocResolver IocResolver { get; set; } public IAbpMvcConfiguration AbpMvcConfiguration { get; set; } /// <summary> /// MethodInfo for currently executing action. /// </summary> private MethodInfo _currentMethodInfo; /// <summary> /// WrapResultAttribute for currently executing action. /// </summary> private WrapResultAttribute _wrapResultAttribute; /// <summary> /// Constructor. /// </summary> protected AbpController() { AbpSession = NullAbpSession.Instance; Logger = NullLogger.Instance; LocalizationManager = NullLocalizationManager.Instance; PermissionChecker = NullPermissionChecker.Instance; EventBus = NullEventBus.Instance; IocResolver = IocManager.Instance; } /// <summary> /// Gets localized string for given key name and current language. /// </summary> /// <param name="name">Key name</param> /// <returns>Localized string</returns> protected virtual string L(string name) { return LocalizationSource.GetString(name); } /// <summary> /// Gets localized string for given key name and current language with formatting strings. /// </summary> /// <param name="name">Key name</param> /// <param name="args">Format arguments</param> /// <returns>Localized string</returns> protected string L(string name, params object[] args) { return LocalizationSource.GetString(name, args); } /// <summary> /// Gets localized string for given key name and specified culture information. /// </summary> /// <param name="name">Key name</param> /// <param name="culture">culture information</param> /// <returns>Localized string</returns> protected virtual string L(string name, CultureInfo culture) { return LocalizationSource.GetString(name, culture); } /// <summary> /// Gets localized string for given key name and current language with formatting strings. /// </summary> /// <param name="name">Key name</param> /// <param name="culture">culture information</param> /// <param name="args">Format arguments</param> /// <returns>Localized string</returns> protected string L(string name, CultureInfo culture, params object[] args) { return LocalizationSource.GetString(name, culture, args); } /// <summary> /// Checks if current user is granted for a permission. /// </summary> /// <param name="permissionName">Name of the permission</param> protected Task<bool> IsGrantedAsync(string permissionName) { return PermissionChecker.IsGrantedAsync(permissionName); } /// <summary> /// Checks if current user is granted for a permission. /// </summary> /// <param name="permissionName">Name of the permission</param> protected bool IsGranted(string permissionName) { return PermissionChecker.IsGranted(permissionName); } /// <summary> /// Checks if given feature is enabled for current tenant. /// </summary> /// <param name="featureName">Name of the feature</param> /// <returns></returns> protected virtual Task<bool> IsEnabledAsync(string featureName) { return FeatureChecker.IsEnabledAsync(featureName); } /// <summary> /// Checks if given feature is enabled for current tenant. /// </summary> /// <param name="featureName">Name of the feature</param> /// <returns></returns> protected virtual bool IsEnabled(string featureName) { return FeatureChecker.IsEnabled(featureName); } /// <summary> /// Json the specified data, contentType, contentEncoding and behavior. /// </summary> /// <param name="data">Data.</param> /// <param name="contentType">Content type.</param> /// <param name="contentEncoding">Content encoding.</param> /// <param name="behavior">Behavior.</param> protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior) { if (_wrapResultAttribute != null && !_wrapResultAttribute.WrapOnSuccess) { return base.Json(data, contentType, contentEncoding, behavior); } if (data == null) { data = new AjaxResponse(); } else if (!ReflectionHelper.IsAssignableToGenericType(data.GetType(), typeof(AjaxResponse<>))) { data = new AjaxResponse(data); } return new AbpJsonResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior }; } #region OnActionExecuting / OnActionExecuted protected override void OnActionExecuting(ActionExecutingContext filterContext) { SetCurrentMethodInfoAndWrapResultAttribute(filterContext); base.OnActionExecuting(filterContext); } private void SetCurrentMethodInfoAndWrapResultAttribute(ActionExecutingContext filterContext) { //Prevent overriding for child actions if (_currentMethodInfo != null) { return; } _currentMethodInfo = filterContext.ActionDescriptor.GetMethodInfoOrNull(); _wrapResultAttribute = ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrDefault( _currentMethodInfo, AbpMvcConfiguration.DefaultWrapResultAttribute ); } #endregion #region Exception handling protected override void OnException(ExceptionContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } //If exception handled before, do nothing. //If this is child action, exception should be handled by main action. if (context.ExceptionHandled || context.IsChildAction) { base.OnException(context); return; } //Log exception if (_wrapResultAttribute == null || _wrapResultAttribute.LogError) { LogHelper.LogException(Logger, context.Exception); } // If custom errors are disabled, we need to let the normal ASP.NET exception handler // execute so that the user can see useful debugging information. if (!context.HttpContext.IsCustomErrorEnabled) { base.OnException(context); return; } // If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method), // ignore it. if (new HttpException(null, context.Exception).GetHttpCode() != 500) { base.OnException(context); return; } //Check WrapResultAttribute if (_wrapResultAttribute == null || !_wrapResultAttribute.WrapOnError) { base.OnException(context); return; } //We handled the exception! context.ExceptionHandled = true; //Return an error response to the client. context.HttpContext.Response.Clear(); context.HttpContext.Response.StatusCode = GetStatusCodeForException(context); context.Result = IsJsonResult() ? GenerateJsonExceptionResult(context) : GenerateNonJsonExceptionResult(context); // Certain versions of IIS will sometimes use their own error page when // they detect a server error. Setting this property indicates that we // want it to try to render ASP.NET MVC's error page instead. context.HttpContext.Response.TrySkipIisCustomErrors = true; //Trigger an event, so we can register it. EventBus.Trigger(this, new AbpHandledExceptionData(context.Exception)); } protected virtual int GetStatusCodeForException(ExceptionContext context) { if (context.Exception is AbpAuthorizationException) { return context.HttpContext.User.Identity.IsAuthenticated ? 403 : 401; } return 500; } protected virtual bool IsJsonResult() { return typeof(JsonResult).IsAssignableFrom(_currentMethodInfo.ReturnType) || typeof(Task<JsonResult>).IsAssignableFrom(_currentMethodInfo.ReturnType); } protected virtual ActionResult GenerateJsonExceptionResult(ExceptionContext context) { context.HttpContext.Items.Add("IgnoreJsonRequestBehaviorDenyGet", "true"); return new AbpJsonResult( new MvcAjaxResponse( ErrorInfoBuilder.BuildForException(context.Exception), context.Exception is AbpAuthorizationException ) ); } protected virtual ActionResult GenerateNonJsonExceptionResult(ExceptionContext context) { return new ViewResult { ViewName = "Error", MasterName = string.Empty, ViewData = new ViewDataDictionary<ErrorViewModel>(new ErrorViewModel(ErrorInfoBuilder.BuildForException(context.Exception), context.Exception)), TempData = context.Controller.TempData }; } #endregion } }
using Lucene.Net.Support; using System; namespace Lucene.Net.Util { /* * 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 FilteredTermsEnum = Lucene.Net.Index.FilteredTermsEnum; using TermsEnum = Lucene.Net.Index.TermsEnum; /// <summary> /// This is a helper class to generate prefix-encoded representations for numerical values /// and supplies converters to represent float/double values as sortable integers/longs. /// /// <para/>To quickly execute range queries in Apache Lucene, a range is divided recursively /// into multiple intervals for searching: The center of the range is searched only with /// the lowest possible precision in the trie, while the boundaries are matched /// more exactly. this reduces the number of terms dramatically. /// /// <para/>This class generates terms to achieve this: First the numerical integer values need to /// be converted to bytes. For that integer values (32 bit or 64 bit) are made unsigned /// and the bits are converted to ASCII chars with each 7 bit. The resulting byte[] is /// sortable like the original integer value (even using UTF-8 sort order). Each value is also /// prefixed (in the first char) by the <c>shift</c> value (number of bits removed) used /// during encoding. /// /// <para/>To also index floating point numbers, this class supplies two methods to convert them /// to integer values by changing their bit layout: <see cref="DoubleToSortableInt64(double)"/>, /// <see cref="SingleToSortableInt32(float)"/>. You will have no precision loss by /// converting floating point numbers to integers and back (only that the integer form /// is not usable). Other data types like dates can easily converted to <see cref="long"/>s or <see cref="int"/>s (e.g. /// date to long: <see cref="DateTime.Ticks"/>). /// /// <para/>For easy usage, the trie algorithm is implemented for indexing inside /// <see cref="Analysis.NumericTokenStream"/> that can index <see cref="int"/>, <see cref="long"/>, /// <see cref="float"/>, and <see cref="double"/>. For querying, /// <see cref="Search.NumericRangeQuery"/> and <see cref="Search.NumericRangeFilter"/> implement the query part /// for the same data types. /// /// <para/>This class can also be used, to generate lexicographically sortable (according to /// <see cref="BytesRef.UTF8SortedAsUTF16Comparer"/>) representations of numeric data /// types for other usages (e.g. sorting). /// /// <para/> /// @lucene.internal /// @since 2.9, API changed non backwards-compliant in 4.0 /// </summary> public sealed class NumericUtils { private NumericUtils() // no instance! { } /// <summary> /// The default precision step used by <see cref="Documents.Int32Field"/>, /// <see cref="Documents.SingleField"/>, <see cref="Documents.Int64Field"/>, /// <see cref="Documents.DoubleField"/>, <see cref="Analysis.NumericTokenStream"/>, /// <see cref="Search.NumericRangeQuery"/>, and <see cref="Search.NumericRangeFilter"/>. /// </summary> public const int PRECISION_STEP_DEFAULT = 4; /// <summary> /// Longs are stored at lower precision by shifting off lower bits. The shift count is /// stored as <c>SHIFT_START_INT64+shift</c> in the first byte /// <para/> /// NOTE: This was SHIFT_START_LONG in Lucene /// </summary> public const char SHIFT_START_INT64 = (char)0x20; /// <summary> /// The maximum term length (used for <see cref="T:byte[]"/> buffer size) /// for encoding <see cref="long"/> values. /// <para/> /// NOTE: This was BUF_SIZE_LONG in Lucene /// </summary> /// <seealso cref="Int64ToPrefixCodedBytes(long, int, BytesRef)"/> public const int BUF_SIZE_INT64 = 63 / 7 + 2; /// <summary> /// Integers are stored at lower precision by shifting off lower bits. The shift count is /// stored as <c>SHIFT_START_INT32+shift</c> in the first byte /// <para/> /// NOTE: This was SHIFT_START_INT in Lucene /// </summary> public const byte SHIFT_START_INT32 = 0x60; /// <summary> /// The maximum term length (used for <see cref="T:byte[]"/> buffer size) /// for encoding <see cref="int"/> values. /// <para/> /// NOTE: This was BUF_SIZE_INT in Lucene /// </summary> /// <seealso cref="Int32ToPrefixCodedBytes(int, int, BytesRef)"/> public const int BUF_SIZE_INT32 = 31 / 7 + 2; /// <summary> /// Returns prefix coded bits after reducing the precision by <paramref name="shift"/> bits. /// This is method is used by <see cref="Analysis.NumericTokenStream"/>. /// After encoding, <c>bytes.Offset</c> will always be 0. /// <para/> /// NOTE: This was longToPrefixCoded() in Lucene /// </summary> /// <param name="val"> The numeric value </param> /// <param name="shift"> How many bits to strip from the right </param> /// <param name="bytes"> Will contain the encoded value </param> public static void Int64ToPrefixCoded(long val, int shift, BytesRef bytes) { Int64ToPrefixCodedBytes(val, shift, bytes); } /// <summary> /// Returns prefix coded bits after reducing the precision by <paramref name="shift"/> bits. /// This is method is used by <see cref="Analysis.NumericTokenStream"/>. /// After encoding, <c>bytes.Offset</c> will always be 0. /// <para/> /// NOTE: This was intToPrefixCoded() in Lucene /// </summary> /// <param name="val"> The numeric value </param> /// <param name="shift"> How many bits to strip from the right </param> /// <param name="bytes"> Will contain the encoded value </param> public static void Int32ToPrefixCoded(int val, int shift, BytesRef bytes) { Int32ToPrefixCodedBytes(val, shift, bytes); } /// <summary> /// Returns prefix coded bits after reducing the precision by <paramref name="shift"/> bits. /// This is method is used by <see cref="Analysis.NumericTokenStream"/>. /// After encoding, <c>bytes.Offset</c> will always be 0. /// <para/> /// NOTE: This was longToPrefixCodedBytes() in Lucene /// </summary> /// <param name="val"> The numeric value </param> /// <param name="shift"> How many bits to strip from the right </param> /// <param name="bytes"> Will contain the encoded value </param> public static void Int64ToPrefixCodedBytes(long val, int shift, BytesRef bytes) { if ((shift & ~0x3f) != 0) // ensure shift is 0..63 { throw new System.ArgumentException("Illegal shift value, must be 0..63"); } int nChars = (((63 - shift) * 37) >> 8) + 1; // i/7 is the same as (i*37)>>8 for i in 0..63 bytes.Offset = 0; bytes.Length = nChars + 1; // one extra for the byte that contains the shift info if (bytes.Bytes.Length < bytes.Length) { bytes.Bytes = new byte[NumericUtils.BUF_SIZE_INT64]; // use the max } bytes.Bytes[0] = (byte)(SHIFT_START_INT64 + shift); ulong sortableBits = BitConverter.ToUInt64(BitConverter.GetBytes(val), 0) ^ 0x8000000000000000L; sortableBits = sortableBits >> shift; while (nChars > 0) { // Store 7 bits per byte for compatibility // with UTF-8 encoding of terms bytes.Bytes[nChars--] = (byte)(sortableBits & 0x7f); sortableBits = sortableBits >> 7; } } /// <summary> /// Returns prefix coded bits after reducing the precision by <paramref name="shift"/> bits. /// This is method is used by <see cref="Analysis.NumericTokenStream"/>. /// After encoding, <c>bytes.Offset</c> will always be 0. /// <para/> /// NOTE: This was intToPrefixCodedBytes() in Lucene /// </summary> /// <param name="val"> The numeric value </param> /// <param name="shift"> How many bits to strip from the right </param> /// <param name="bytes"> Will contain the encoded value </param> public static void Int32ToPrefixCodedBytes(int val, int shift, BytesRef bytes) { if ((shift & ~0x1f) != 0) // ensure shift is 0..31 { throw new System.ArgumentException("Illegal shift value, must be 0..31"); } int nChars = (((31 - shift) * 37) >> 8) + 1; // i/7 is the same as (i*37)>>8 for i in 0..63 bytes.Offset = 0; bytes.Length = nChars + 1; // one extra for the byte that contains the shift info if (bytes.Bytes.Length < bytes.Length) { bytes.Bytes = new byte[NumericUtils.BUF_SIZE_INT64]; // use the max } bytes.Bytes[0] = (byte)(SHIFT_START_INT32 + shift); int sortableBits = val ^ unchecked((int)0x80000000); sortableBits = Number.URShift(sortableBits, shift); while (nChars > 0) { // Store 7 bits per byte for compatibility // with UTF-8 encoding of terms bytes.Bytes[nChars--] = (byte)(sortableBits & 0x7f); sortableBits = (int)((uint)sortableBits >> 7); } } /// <summary> /// Returns the shift value from a prefix encoded <see cref="long"/>. /// <para/> /// NOTE: This was getPrefixCodedLongShift() in Lucene /// </summary> /// <exception cref="FormatException"> if the supplied <see cref="BytesRef"/> is /// not correctly prefix encoded. </exception> public static int GetPrefixCodedInt64Shift(BytesRef val) { int shift = val.Bytes[val.Offset] - SHIFT_START_INT64; if (shift > 63 || shift < 0) { throw new System.FormatException("Invalid shift value (" + shift + ") in prefixCoded bytes (is encoded value really an INT?)"); } return shift; } /// <summary> /// Returns the shift value from a prefix encoded <see cref="int"/>. /// <para/> /// NOTE: This was getPrefixCodedIntShift() in Lucene /// </summary> /// <exception cref="FormatException"> if the supplied <see cref="BytesRef"/> is /// not correctly prefix encoded. </exception> public static int GetPrefixCodedInt32Shift(BytesRef val) { int shift = val.Bytes[val.Offset] - SHIFT_START_INT32; if (shift > 31 || shift < 0) { throw new System.FormatException("Invalid shift value in prefixCoded bytes (is encoded value really an INT?)"); } return shift; } /// <summary> /// Returns a <see cref="long"/> from prefixCoded bytes. /// Rightmost bits will be zero for lower precision codes. /// This method can be used to decode a term's value. /// <para/> /// NOTE: This was prefixCodedToLong() in Lucene /// </summary> /// <exception cref="FormatException"> if the supplied <see cref="BytesRef"/> is /// not correctly prefix encoded. </exception> /// <seealso cref="Int64ToPrefixCodedBytes(long, int, BytesRef)"/> public static long PrefixCodedToInt64(BytesRef val) { long sortableBits = 0L; for (int i = val.Offset + 1, limit = val.Offset + val.Length; i < limit; i++) { sortableBits <<= 7; var b = val.Bytes[i]; if (b < 0) { throw new System.FormatException("Invalid prefixCoded numerical value representation (byte " + (b & 0xff).ToString("x") + " at position " + (i - val.Offset) + " is invalid)"); } sortableBits |= (byte)b; } return (long)((ulong)(sortableBits << GetPrefixCodedInt64Shift(val)) ^ 0x8000000000000000L); } /// <summary> /// Returns an <see cref="int"/> from prefixCoded bytes. /// Rightmost bits will be zero for lower precision codes. /// This method can be used to decode a term's value. /// <para/> /// NOTE: This was prefixCodedToInt() in Lucene /// </summary> /// <exception cref="FormatException"> if the supplied <see cref="BytesRef"/> is /// not correctly prefix encoded. </exception> /// <seealso cref="Int32ToPrefixCodedBytes(int, int, BytesRef)"/> public static int PrefixCodedToInt32(BytesRef val) { long sortableBits = 0; for (int i = val.Offset, limit = val.Offset + val.Length; i < limit; i++) { sortableBits <<= 7; var b = val.Bytes[i]; if (b < 0) { throw new System.FormatException("Invalid prefixCoded numerical value representation (byte " + (b & 0xff).ToString("x") + " at position " + (i - val.Offset) + " is invalid)"); } sortableBits |= b; } return (int)((sortableBits << GetPrefixCodedInt32Shift(val)) ^ 0x80000000); } /// <summary> /// Converts a <see cref="double"/> value to a sortable signed <see cref="long"/>. /// The value is converted by getting their IEEE 754 floating-point &quot;double format&quot; /// bit layout and then some bits are swapped, to be able to compare the result as <see cref="long"/>. /// By this the precision is not reduced, but the value can easily used as a <see cref="long"/>. /// The sort order (including <see cref="double.NaN"/>) is defined by /// <see cref="double.CompareTo(double)"/>; <c>NaN</c> is greater than positive infinity. /// <para/> /// NOTE: This was doubleToSortableLong() in Lucene /// </summary> /// <seealso cref="SortableInt64ToDouble(long)"/> public static long DoubleToSortableInt64(double val) { long f = Number.DoubleToInt64Bits(val); if (f < 0) { f ^= 0x7fffffffffffffffL; } return f; } /// <summary> /// Converts a sortable <see cref="long"/> back to a <see cref="double"/>. /// <para/> /// NOTE: This was sortableLongToDouble() in Lucene /// </summary> /// <seealso cref="DoubleToSortableInt64(double)"/> public static double SortableInt64ToDouble(long val) { if (val < 0) { val ^= 0x7fffffffffffffffL; } return BitConverter.Int64BitsToDouble(val); } /// <summary> /// Converts a <see cref="float"/> value to a sortable signed <see cref="int"/>. /// The value is converted by getting their IEEE 754 floating-point &quot;float format&quot; /// bit layout and then some bits are swapped, to be able to compare the result as <see cref="int"/>. /// By this the precision is not reduced, but the value can easily used as an <see cref="int"/>. /// The sort order (including <see cref="float.NaN"/>) is defined by /// <seealso cref="float.CompareTo(float)"/>; <c>NaN</c> is greater than positive infinity. /// <para/> /// NOTE: This was floatToSortableInt() in Lucene /// </summary> /// <seealso cref="SortableInt32ToSingle(int)"/> public static int SingleToSortableInt32(float val) { int f = Number.SingleToInt32Bits(val); if (f < 0) { f ^= 0x7fffffff; } return f; } /// <summary> /// Converts a sortable <see cref="int"/> back to a <see cref="float"/>. /// <para/> /// NOTE: This was sortableIntToFloat() in Lucene /// </summary> /// <seealso cref="SingleToSortableInt32"/> public static float SortableInt32ToSingle(int val) { if (val < 0) { val ^= 0x7fffffff; } return Number.Int32BitsToSingle(val); } /// <summary> /// Splits a long range recursively. /// You may implement a builder that adds clauses to a /// <see cref="Lucene.Net.Search.BooleanQuery"/> for each call to its /// <see cref="Int64RangeBuilder.AddRange(BytesRef, BytesRef)"/> /// method. /// <para/> /// This method is used by <see cref="Search.NumericRangeQuery"/>. /// <para/> /// NOTE: This was splitLongRange() in Lucene /// </summary> public static void SplitInt64Range(Int64RangeBuilder builder, int precisionStep, long minBound, long maxBound) { SplitRange(builder, 64, precisionStep, minBound, maxBound); } /// <summary> /// Splits an <see cref="int"/> range recursively. /// You may implement a builder that adds clauses to a /// <see cref="Lucene.Net.Search.BooleanQuery"/> for each call to its /// <see cref="Int32RangeBuilder.AddRange(BytesRef, BytesRef)"/> /// method. /// <para/> /// This method is used by <see cref="Search.NumericRangeQuery"/>. /// <para/> /// NOTE: This was splitIntRange() in Lucene /// </summary> public static void SplitInt32Range(Int32RangeBuilder builder, int precisionStep, int minBound, int maxBound) { SplitRange(builder, 32, precisionStep, minBound, maxBound); } /// <summary> /// This helper does the splitting for both 32 and 64 bit. </summary> private static void SplitRange(object builder, int valSize, int precisionStep, long minBound, long maxBound) { if (precisionStep < 1) { throw new System.ArgumentException("precisionStep must be >=1"); } if (minBound > maxBound) { return; } for (int shift = 0; ; shift += precisionStep) { // calculate new bounds for inner precision long diff = 1L << (shift + precisionStep), mask = ((1L << precisionStep) - 1L) << shift; bool hasLower = (minBound & mask) != 0L, hasUpper = (maxBound & mask) != mask; long nextMinBound = (hasLower ? (minBound + diff) : minBound) & ~mask, nextMaxBound = (hasUpper ? (maxBound - diff) : maxBound) & ~mask; bool lowerWrapped = nextMinBound < minBound, upperWrapped = nextMaxBound > maxBound; if (shift + precisionStep >= valSize || nextMinBound > nextMaxBound || lowerWrapped || upperWrapped) { // We are in the lowest precision or the next precision is not available. AddRange(builder, valSize, minBound, maxBound, shift); // exit the split recursion loop break; } if (hasLower) { AddRange(builder, valSize, minBound, minBound | mask, shift); } if (hasUpper) { AddRange(builder, valSize, maxBound & ~mask, maxBound, shift); } // recurse to next precision minBound = nextMinBound; maxBound = nextMaxBound; } } /// <summary> /// Helper that delegates to correct range builder. </summary> private static void AddRange(object builder, int valSize, long minBound, long maxBound, int shift) { // for the max bound set all lower bits (that were shifted away): // this is important for testing or other usages of the splitted range // (e.g. to reconstruct the full range). The prefixEncoding will remove // the bits anyway, so they do not hurt! maxBound |= (1L << shift) - 1L; // delegate to correct range builder switch (valSize) { case 64: ((Int64RangeBuilder)builder).AddRange(minBound, maxBound, shift); break; case 32: ((Int32RangeBuilder)builder).AddRange((int)minBound, (int)maxBound, shift); break; default: // Should not happen! throw new System.ArgumentException("valSize must be 32 or 64."); } } /// <summary> /// Callback for <see cref="SplitInt64Range(Int64RangeBuilder, int, long, long)"/>. /// You need to override only one of the methods. /// <para/> /// NOTE: This was LongRangeBuilder in Lucene /// <para/> /// @lucene.internal /// @since 2.9, API changed non backwards-compliant in 4.0 /// </summary> public abstract class Int64RangeBuilder { /// <summary> /// Override this method, if you like to receive the already prefix encoded range bounds. /// You can directly build classical (inclusive) range queries from them. /// </summary> public virtual void AddRange(BytesRef minPrefixCoded, BytesRef maxPrefixCoded) { throw new System.NotSupportedException(); } /// <summary> /// Override this method, if you like to receive the raw long range bounds. /// You can use this for e.g. debugging purposes (print out range bounds). /// </summary> public virtual void AddRange(long min, long max, int shift) { BytesRef minBytes = new BytesRef(BUF_SIZE_INT64), maxBytes = new BytesRef(BUF_SIZE_INT64); Int64ToPrefixCodedBytes(min, shift, minBytes); Int64ToPrefixCodedBytes(max, shift, maxBytes); AddRange(minBytes, maxBytes); } } /// <summary> /// Callback for <see cref="SplitInt32Range(Int32RangeBuilder, int, int, int)"/>. /// You need to override only one of the methods. /// <para/> /// NOTE: This was IntRangeBuilder in Lucene /// /// @lucene.internal /// @since 2.9, API changed non backwards-compliant in 4.0 /// </summary> public abstract class Int32RangeBuilder { /// <summary> /// Override this method, if you like to receive the already prefix encoded range bounds. /// You can directly build classical range (inclusive) queries from them. /// </summary> public virtual void AddRange(BytesRef minPrefixCoded, BytesRef maxPrefixCoded) { throw new System.NotSupportedException(); } /// <summary> /// Override this method, if you like to receive the raw int range bounds. /// You can use this for e.g. debugging purposes (print out range bounds). /// </summary> public virtual void AddRange(int min, int max, int shift) { BytesRef minBytes = new BytesRef(BUF_SIZE_INT32), maxBytes = new BytesRef(BUF_SIZE_INT32); Int32ToPrefixCodedBytes(min, shift, minBytes); Int32ToPrefixCodedBytes(max, shift, maxBytes); AddRange(minBytes, maxBytes); } } /// <summary> /// Filters the given <see cref="TermsEnum"/> by accepting only prefix coded 64 bit /// terms with a shift value of <c>0</c>. /// <para/> /// NOTE: This was filterPrefixCodedLongs() in Lucene /// </summary> /// <param name="termsEnum"> /// The terms enum to filter </param> /// <returns> A filtered <see cref="TermsEnum"/> that only returns prefix coded 64 bit /// terms with a shift value of <c>0</c>. </returns> public static TermsEnum FilterPrefixCodedInt64s(TermsEnum termsEnum) { return new FilteredTermsEnumAnonymousInnerClassHelper(termsEnum); } private class FilteredTermsEnumAnonymousInnerClassHelper : FilteredTermsEnum { public FilteredTermsEnumAnonymousInnerClassHelper(TermsEnum termsEnum) : base(termsEnum, false) { } protected override AcceptStatus Accept(BytesRef term) { return NumericUtils.GetPrefixCodedInt64Shift(term) == 0 ? AcceptStatus.YES : AcceptStatus.END; } } /// <summary> /// Filters the given <see cref="TermsEnum"/> by accepting only prefix coded 32 bit /// terms with a shift value of <c>0</c>. /// <para/> /// NOTE: This was filterPrefixCodedInts() in Lucene /// </summary> /// <param name="termsEnum"> /// The terms enum to filter </param> /// <returns> A filtered <see cref="TermsEnum"/> that only returns prefix coded 32 bit /// terms with a shift value of <c>0</c>. </returns> public static TermsEnum FilterPrefixCodedInt32s(TermsEnum termsEnum) { return new FilteredTermsEnumAnonymousInnerClassHelper2(termsEnum); } private class FilteredTermsEnumAnonymousInnerClassHelper2 : FilteredTermsEnum { public FilteredTermsEnumAnonymousInnerClassHelper2(TermsEnum termsEnum) : base(termsEnum, false) { } protected override AcceptStatus Accept(BytesRef term) { return NumericUtils.GetPrefixCodedInt32Shift(term) == 0 ? AcceptStatus.YES : AcceptStatus.END; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace RebbauReichenbach.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); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace STEM_Db.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); } } } }
using Pid = System.UInt32; using IPage = Core.PgHdr; using System; using System.Diagnostics; using Core.IO; namespace Core { public partial class Btree { static ushort MX_CELL_SIZE(BtShared bt) { return (ushort)(bt.PageSize - 8); } static ushort MX_CELL(BtShared bt) { return (ushort)((bt.PageSize - 8) / 6); } const string FILE_HEADER = "SQLite format 3\0"; const int DEFAULT_CACHE_SIZE = 2000; const int MASTER_ROOT = 1; // The root-page of the master database table. const byte PTF_INTKEY = 0x01; const byte PTF_ZERODATA = 0x02; const byte PTF_LEAFDATA = 0x04; const byte PTF_LEAF = 0x08; public struct OverflowCell // Cells that will not fit on aData[] { internal byte[] Cell; // Pointers to the body of the overflow cell internal OverflowCell Copy() { var cp = new OverflowCell(); if (Cell != null) { cp.Cell = C._alloc(Cell.Length); Buffer.BlockCopy(Cell, 0, cp.Cell, 0, Cell.Length); } return cp; } }; public class MemPage { internal bool IsInit; // True if previously initialized. MUST BE FIRST! internal byte Overflows; // Number of overflow cell bodies in aCell[] internal bool IntKey; // True if intkey flag is set internal bool Leaf; // True if leaf flag is set internal bool HasData; // True if this page stores data internal byte HdrOffset; // 100 for page 1. 0 otherwise internal byte ChildPtrSize; // 0 if leaf. 4 if !leaf internal byte Max1bytePayload; // min(maxLocal,127) internal ushort MaxLocal; // Copy of BtShared.maxLocal or BtShared.maxLeaf internal ushort MinLocal; // Copy of BtShared.minLocal or BtShared.minLeaf internal ushort CellOffset; // Index in aData of first cell pou16er internal ushort Frees; // Number of free bytes on the page internal ushort Cells; // Number of cells on this page, local and ovfl internal ushort MaskPage; // Mask for page offset internal ushort[] OvflIdxs = new ushort[5]; internal OverflowCell[] Ovfls = new OverflowCell[5]; internal BtShared Bt; // Pointer to BtShared that this page is part of internal byte[] Data; // Pointer to disk image of the page data //object byte[] DataEnd; // One byte past the end of usable data //object byte[] CellIdx; // The cell index area internal IPage DBPage; // Pager page handle internal Pid ID; // Page number for this page internal MemPage memcopy() { var cp = (MemPage)MemberwiseClone(); //if (Overflows != null) //{ // cp.Overflows = new OverflowCell[Overflows.Length]; // for (int i = 0; i < Overflows.Length; i++) // cp.Overflows[i] = Overflows[i].Copy(); //} //if (Data != null) //{ // cp.Data = C._alloc(Data.Length); // Buffer.BlockCopy(Data, 0, cp.Data, 0, Data.Length); //} return cp; } }; const int EXTRA_SIZE = 0; // No used in C#, since we use create a class; was MemPage.Length; public enum BTS : ushort { READ_ONLY = 0x0001, // Underlying file is readonly PAGESIZE_FIXED = 0x0002,// Page size can no longer be changed SECURE_DELETE = 0x0004, // PRAGMA secure_delete is enabled INITIALLY_EMPTY = 0x0008, // Database was empty at trans start NO_WAL = 0x0010, // Do not open write-ahead-log files EXCLUSIVE = 0x0020, // pWriter has an exclusive lock PENDING = 0x0040, // Waiting for read-locks to clear } public class BtShared { static int _autoID; // For C# internal int AutoID; // For C# public BtShared() { AutoID = _autoID++; } // For C# internal Pager Pager; // The page cache internal BContext Ctx; // Database connection currently using this Btree internal BtCursor Cursor; // A list of all open cursors internal MemPage Page1; // First page of the database internal Btree.OPEN OpenFlags; // Flags to sqlite3BtreeOpen() #if !OMIT_AUTOVACUUM internal bool AutoVacuum; // True if auto-vacuum is enabled internal bool IncrVacuum; // True if incr-vacuum is enabled internal bool DoTruncate; // True to truncate db on commit #endif internal TRANS InTransaction; // Transaction state internal byte Max1bytePayload; // Maximum first byte of cell for a 1-byte payload internal BTS BtsFlags; // Boolean parameters. See BTS_* macros below internal ushort MaxLocal; // Maximum local payload in non-LEAFDATA tables internal ushort MinLocal; // Minimum local payload in non-LEAFDATA tables internal ushort MaxLeaf; // Maximum local payload in a LEAFDATA table internal ushort MinLeaf; // Minimum local payload in a LEAFDATA table internal uint PageSize; // Total number of bytes on a page internal uint UsableSize; // Number of usable bytes on each page internal int Transactions; // Number of open transactions (read + write) internal Pid Pages; // Number of pages in the database internal Schema Schema; // Pointer to space allocated by sqlite3BtreeSchema() internal Action<Schema> FreeSchema; // Destructor for BtShared.pSchema internal MutexEx Mutex; // Non-recursive mutex required to access this object internal Bitvec HasContent; // Set of pages moved to free-list this transaction #if !OMIT_SHARED_CACHE internal int Refs; // Number of references to this structure internal BtShared Next; // Next on a list of sharable BtShared structs internal BtLock Lock; // List of locks held on this shared-btree struct internal Btree Writer; // Btree with currently open write transaction #endif internal byte[] TmpSpace; // BtShared.pageSize bytes of space for tmp use } public struct CellInfo { internal uint Cell_; // Offset to start of cell content -- Needed for C# internal long Key; // The key for INTKEY tables, or number of bytes in key internal byte[] Cell; // Pointer to the start of cell content internal uint Data; // Number of bytes of data internal uint Payload; // Total amount of payload internal ushort Header; // Size of the cell content header in bytes internal ushort Local; // Amount of payload held locally internal ushort Overflow; // Offset to overflow page number. Zero if no overflow internal ushort Size; // Size of the cell content on the main b-tree page internal bool Equals(CellInfo ci) { if (ci.Cell_ >= ci.Cell.Length || Cell_ >= this.Cell.Length) return false; if (ci.Cell[ci.Cell_] != this.Cell[Cell_]) return false; if (ci.Key != this.Key || ci.Data != this.Data || ci.Payload != this.Payload) return false; if (ci.Header != this.Header || ci.Local != this.Local) return false; if (ci.Overflow != this.Overflow || ci.Size != this.Size) return false; return true; } } const int BTCURSOR_MAX_DEPTH = 20; public enum CURSOR : byte { INVALID = 0, VALID = 1, REQUIRESEEK = 2, FAULT = 3, } public class BtCursor { internal Btree Btree; // The Btree to which this cursor belongs internal BtShared Bt; // The BtShared this cursor points to internal BtCursor Next, Prev; // Forms a linked list of all cursors internal KeyInfo KeyInfo; // Argument passed to comparison function #if !OMIT_INCRBLOB internal Pid[] Overflows; // Cache of overflow page locations #endif internal Pid RootID; // The root page of this tree internal long CachedRowID; // Next rowid cache. 0 means not valid internal CellInfo Info = new CellInfo(); // A parse of the cell we are pointing at internal long KeyLength; // Size of pKey, or last integer key internal byte[] Key; // Saved key that was cursor's last known position internal int SkipNext; // Prev() is noop if negative. Next() is noop if positive internal bool WrFlag; // True if writable internal byte AtLast; // VdbeCursor pointing to the last entry internal bool ValidNKey; // True if info.nKey is valid internal CURSOR State; // One of the CURSOR_XXX constants (see below) #if !OMIT_INCRBLOB internal bool IsIncrblobHandle; // True if this cursor is an incr. io handle #endif internal byte Hints; // As configured by CursorSetHints() internal short ID; // Index of current page in apPage internal ushort[] Idxs = new ushort[BTCURSOR_MAX_DEPTH]; // Current index in apPage[i] internal MemPage[] Pages = new MemPage[BTCURSOR_MAX_DEPTH]; // Pages from root to current page internal void memset() { Next = Prev = null; KeyInfo = null; RootID = 0; CachedRowID = 0; Info = new CellInfo(); WrFlag = false; AtLast = 0; ValidNKey = false; State = 0; KeyLength = 0; Key = null; SkipNext = 0; #if !OMIT_INCRBLOB IsIncrblobHandle = false; Overflows = null; #endif ID = 0; } public BtCursor Copy() { var cp = (BtCursor)MemberwiseClone(); return cp; } #if !OMIT_INCRBLOB public void EnterCursor() { Btree.Enter(); } public void LeaveCursor() { Btree.Leave(); } #endif } public static Pid PENDING_BYTE_PAGE(BtShared bt) { return Pager.MJ_PID(bt.Pager); } static Pid PTRMAP_PAGENO(BtShared bt, Pid id) { return ptrmapPageno(bt, id); } static Pid PTRMAP_PTROFFSET(Pid ptrmapID, Pid id) { return (5 * (id - ptrmapID - 1)); } static bool PTRMAP_ISPAGE(BtShared bt, Pid id) { return (PTRMAP_PAGENO((bt), (id)) == (id)); } internal enum PTRMAP : byte { ROOTPAGE = 1, FREEPAGE = 2, OVERFLOW1 = 3, OVERFLOW2 = 4, BTREE = 5, } #if DEBUG static void btreeIntegrity(Btree p) { Debug.Assert(p.Bt.InTransaction != TRANS.NONE || p.Bt.Transactions == 0); Debug.Assert(p.Bt.InTransaction >= p.InTrans); } #else static void btreeIntegrity(Btree p) { } #endif internal class IntegrityCk { public BtShared Bt; // The tree being checked out public Pager Pager; // The associated pager. Also accessible by pBt.pPager public byte[] PgRefs; // 1 bit per page in the db (see above) public Pid Pages; // Number of pages in the database public int MaxErrors; // Stop accumulating errors when this reaches zero public int Errors; // Number of messages written to zErrMsg so far public bool MallocFailed; // A memory allocation error has occurred public Text.StringBuilder ErrMsg = new Text.StringBuilder(); // Accumulate the error message text here }; } }
/******************************************************************************* * Copyright 2009-2013 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. *******************************************************************************/ using System; using System.Collections.Generic; using System.Threading; using Amazon; using Amazon.EC2; using Amazon.EC2.Model; using Amazon.EC2.Util; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; using Amazon.Auth.AccessControlPolicy; using Amazon.Auth.AccessControlPolicy.ActionIdentifiers; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Util; using System.IO; using System.Net; namespace AwsEC2Sample1 { /// <summary> /// This sample shows how to launch an Amazon EC2 instance with a PowerShell script that is executed when the /// instance becomes available and access Amazon S3. /// </summary> class Program { static readonly string RESOURCDE_POSTFIX = DateTime.Now.Ticks.ToString(); static readonly string SAMPLE_PREFIX = AWSConfigSettings.AWSSamplePrefix; static readonly string SAMPLE_NAME = SAMPLE_PREFIX + DateTime.Now.ToShortDateString() + "_" + DateTime.Now.ToShortTimeString().Replace(":", "."); static readonly string SAMPLE_LONG_UNIQUE_NAME = SAMPLE_PREFIX + RESOURCDE_POSTFIX; const bool CREATE_AND_SAVE_KEY_PAIR = true; public static void Main(string[] args) { string awsProfileName = AWSConfigSettings.AWSProfileName; AmazonEC2Config config = new AmazonEC2Config(); config.ServiceURL = AWSConfigSettings.AWSServiceUrl; Amazon.Runtime.AWSCredentials credentials = new Amazon.Runtime.StoredProfileAWSCredentials(awsProfileName); // AmazonEC2Client ec2Client = new AmazonEC2Client(credentials, config); AmazonEC2Client ec2Client = new AmazonEC2Client(); var bucketName = SAMPLE_LONG_UNIQUE_NAME; // Get latest 2012 Base AMI var imageId = ImageUtilities.FindImage(ec2Client, ImageUtilities.WINDOWS_2012_BASE).ImageId; Console.WriteLine("Using Image ID: {0}", imageId); // Create an IAM role var instanceProfileArn = CreateInstanceProfile(); Console.WriteLine("Created Instance Profile: {0}", instanceProfileArn); Thread.Sleep(15000); // Check existing keypairs string keyPairName = SAMPLE_LONG_UNIQUE_NAME; var dkpRequest = new DescribeKeyPairsRequest(); var dkpResponse = ec2Client.DescribeKeyPairs(dkpRequest); List<KeyPairInfo> myKeyPairs = dkpResponse.KeyPairs; foreach (KeyPairInfo item in myKeyPairs) { Console.WriteLine("Existing key pair: " + item.KeyName); } // Create new KeyPair KeyPair newKeyPair = null; CreateKeyPairRequest newKeyRequest = new CreateKeyPairRequest() { KeyName = keyPairName }; CreateKeyPairResponse ckpResponse = ec2Client.CreateKeyPair(newKeyRequest); // store the received new Key newKeyPair = ckpResponse.KeyPair; Console.WriteLine(); Console.WriteLine("New key: " + keyPairName); Console.WriteLine("fingerprint: " + newKeyPair.KeyFingerprint); Console.WriteLine(); // Save the private key in a .pem file using (FileStream s = new FileStream(keyPairName + ".pem", FileMode.Create)) { using (StreamWriter writer = new StreamWriter(s)) { writer.WriteLine(newKeyPair.KeyMaterial); Console.WriteLine(newKeyPair.KeyMaterial); } } string secGroupId = string.Empty; // Create new security Group try { System.Net.HttpStatusCode createSecGrCode = CreateSecurityGroup(ec2Client, ref secGroupId); } catch (AmazonEC2Exception ae) { if (string.Equals(ae.ErrorCode, "InvalidGroup.Duplicate", StringComparison.InvariantCulture)) Console.WriteLine(ae.Message); else throw; } // add ip ranges String ipSource = "0.0.0.0/0"; List<String> ipRanges = new List<String>(); ipRanges.Add(ipSource); List<IpPermission> ipPermissions = new List<IpPermission>(); IpPermission tcpSSH = new IpPermission() { IpProtocol = "tcp", FromPort = 22, ToPort = 22, IpRanges = ipRanges }; ipPermissions.Add(tcpSSH); IpPermission tcpHTTP = new IpPermission() { IpProtocol = "tcp", FromPort = 80, ToPort = 80, IpRanges = ipRanges }; ipPermissions.Add(tcpHTTP); IpPermission tcpHTTPS = new IpPermission() { IpProtocol = "tcp", FromPort = 443, ToPort = 443, IpRanges = ipRanges }; ipPermissions.Add(tcpHTTPS); IpPermission tcpMYSQL = new IpPermission() { IpProtocol = "tcp", FromPort = 3306, ToPort = 3306, IpRanges = ipRanges }; ipPermissions.Add(tcpMYSQL); IpPermission tcpRDP = new IpPermission() { IpProtocol = "tcp", FromPort = 3389, ToPort = 3389, IpRanges = ipRanges }; ipPermissions.Add(tcpRDP); try { // Authorize the ports to be used. AuthorizeSecurityGroupIngressRequest ipPermissionsRequest = new AuthorizeSecurityGroupIngressRequest(); ipPermissionsRequest.IpPermissions = ipPermissions; ipPermissionsRequest.GroupName = SAMPLE_NAME; if (!string.IsNullOrEmpty(secGroupId)) { ipPermissionsRequest.GroupId = secGroupId; } AuthorizeSecurityGroupIngressResponse authResp = ec2Client.AuthorizeSecurityGroupIngress(ipPermissionsRequest); Console.WriteLine("Auth SecurityGroup Request HttpStatusCode " + authResp.HttpStatusCode + " "); Console.WriteLine(authResp.ResponseMetadata); } catch (AmazonEC2Exception ae) { if (String.Equals(ae.ErrorCode, "InvalidPermission.Duplicate", StringComparison.InvariantCulture)) Console.WriteLine(ae.Message); else throw; } // run ec2 instance request with existing or new generated keypair var runRequest = new RunInstancesRequest { ImageId = imageId, MinCount = 1, MaxCount = 1, KeyName = newKeyPair.KeyName, //keyPair.KeyName, IamInstanceProfile = new IamInstanceProfileSpecification { Arn = instanceProfileArn }, // Add the region for the S3 bucket and the name of the bucket to create UserData = EncodeToBase64( string.Format( AWSConfigSettings.POWERSHELL_S3_BUCKET_SCRIPT, AWSConfigSettings.AWSRegionEndpoint.SystemName, bucketName) ) }; // add secGroupId if (!string.IsNullOrEmpty(secGroupId)) { runRequest.SecurityGroupIds.Add(secGroupId); } var instanceId = ec2Client.RunInstances(runRequest).Reservation.Instances[0].InstanceId; Console.WriteLine("Launch Instance {0}", instanceId); // Create the name tag ec2Client.CreateTags(new CreateTagsRequest { Resources = new List<string> { instanceId }, Tags = new List<Amazon.EC2.Model.Tag> { new Amazon.EC2.Model.Tag { Key = "Name", Value = "Processor" } } }); Console.WriteLine("Adding Name Tag to instance"); // Amazon.CloudWatch. // create ElastiCache Cluster try { Amazon.ElastiCache.AmazonElastiCacheConfig eCacheConfig = new Amazon.ElastiCache.AmazonElastiCacheConfig(); eCacheConfig.ServiceURL = AWSConfigSettings.AWSServiceUrl; Amazon.ElastiCache.AmazonElastiCacheClient eCacheClient = new Amazon.ElastiCache.AmazonElastiCacheClient(); // List<string> x = new List<string>(); // x.Add(secGroupId); // Amazon.ElastiCache.Model.CreateCacheClusterRequest eCacheReq = new Amazon.ElastiCache.Model.CreateCacheClusterRequest( // "cache-cluster" + SAMPLE_NAME, 2, "cache.t2.medium", "memcached", x); Amazon.ElastiCache.Model.CreateCacheClusterRequest eCacheReq = new Amazon.ElastiCache.Model.CreateCacheClusterRequest( "Christian", 2, "cache.t2.medium", "memcached", new List<string>()); Amazon.ElastiCache.Model.CreateCacheClusterResponse eCacheResp = eCacheClient.CreateCacheCluster(eCacheReq); Console.WriteLine("Cache Cluster Created" + eCacheResp.HttpStatusCode.ToString()); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(); } // rds client Amazon.RDS.AmazonRDSConfig rdsConf = new Amazon.RDS.AmazonRDSConfig(); rdsConf.ServiceURL = AWSConfigSettings.AWSServiceUrl; Amazon.RDS.AmazonRDSClient rdsClient = new Amazon.RDS.AmazonRDSClient(); // create Database Cluster with aurora DB string dbClusterIdentifier = string.Empty; try { Amazon.RDS.Model.DBCluster createdCluster = CreateDBClusterRDS(rdsClient, SAMPLE_NAME, "aurora", "root", SAMPLE_LONG_UNIQUE_NAME, secGroupId, ref dbClusterIdentifier); Console.WriteLine("Created DBCluster with Id " + createdCluster.DBClusterIdentifier); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(); } Console.WriteLine("Waiting for EC2 Instance to stop"); // The script put in the user data will shutdown the instance when it is complete. Wait // till the instance has stopped which signals the script is done so the instance can be terminated. Instance instance = null; var instanceDescribeRequest = new DescribeInstancesRequest { InstanceIds = new List<string> { instanceId } }; do { Thread.Sleep(10000); instance = ec2Client.DescribeInstances(instanceDescribeRequest).Reservations[0].Instances[0]; if (instance.State.Name == "stopped") { // Demonstrate how to get the Administrator password using the keypair. var passwordResponse = ec2Client.GetPasswordData(new GetPasswordDataRequest { InstanceId = instanceId }); // Make sure we actually got a password if (passwordResponse.PasswordData != null) { var password = passwordResponse.GetDecryptedPassword(newKeyPair.KeyMaterial); Console.WriteLine("The Windows Administrator password is: {0}", password); } } } while (instance.State.Name == "pending" || instance.State.Name == "running"); // Terminate instance Console.WriteLine("Terminate Instances " + instanceId.ToString()); ec2Client.TerminateInstances(new TerminateInstancesRequest { InstanceIds = new List<string>() { instanceId } }); // Delete key pair created for sample. Console.WriteLine("Delete KeyPair " + newKeyPair.KeyName); ec2Client.DeleteKeyPair(new DeleteKeyPairRequest { KeyName = newKeyPair.KeyName }); try { var s3Client = new AmazonS3Client(); var listResponse = s3Client.ListObjects(new ListObjectsRequest { BucketName = bucketName }); if (listResponse.S3Objects.Count > 0) { Console.WriteLine("Found results file {0} in S3 bucket {1}", listResponse.S3Objects[0].Key, bucketName); } // Delete bucket created for sample. AmazonS3Util.DeleteS3BucketWithObjects(s3Client, bucketName); Console.WriteLine("Deleted S3 bucket created for sample."); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(); } // delete DB Cluster try { System.Net.HttpStatusCode delClusterStatus = DeleteDBClusterRDS(rdsClient, dbClusterIdentifier); Console.WriteLine("Delete Cluster Request with Id " + dbClusterIdentifier + " returned " + delClusterStatus.ToString()); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(); } Thread.Sleep(1000); Console.WriteLine("Delete Instance Profile created for sample."); DeleteInstanceProfile(); // delete Security Group try { System.Net.HttpStatusCode delSecGroupStatus = DeleteSecurityGroup(ec2Client, secGroupId); Console.WriteLine("Delete SecurityGroup " + secGroupId + " returned " + delSecGroupStatus.ToString()); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(); } Console.WriteLine("Instance terminated, push enter to exit the program"); Console.Read(); } /// <summary> /// CreateSecurityGroup /// </summary> /// <param name="ref ec2Client"></param> /// <param name="secGroupId"></param> /// <returns>HttpStatusCode</returns> static HttpStatusCode CreateSecurityGroup(AmazonEC2Client ec2Client, ref string secGroupId) { CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest(); securityGroupRequest.GroupName = SAMPLE_NAME; securityGroupRequest.Description = SAMPLE_LONG_UNIQUE_NAME; CreateSecurityGroupResponse secRes = ec2Client.CreateSecurityGroup(securityGroupRequest); Console.WriteLine("Created security Group with GroupId " + secRes.GroupId); secGroupId = secRes.GroupId; Console.WriteLine(secRes.ResponseMetadata); return secRes.HttpStatusCode; } /// <summary> /// CreateDBClusterRDS /// </summary> /// <param name="rdsClient"></param> /// <param name="databaseName"></param> /// <param name="databaseEngine"></param> /// <param name="MasterUsername"></param> /// <param name="MasterUserPassword"></param> /// <param name="secGroupId"></param> /// <param name="ref dbClusterIdentifier"></param> /// <returns></returns> static Amazon.RDS.Model.DBCluster CreateDBClusterRDS(Amazon.RDS.AmazonRDSClient rdsClient, string databaseName, string databaseEngine, string MasterUsername, string MasterUserPassword, string secGroupId, ref string dbClusterIdentifier) { Amazon.RDS.Model.CreateDBClusterRequest createClusterReq = new Amazon.RDS.Model.CreateDBClusterRequest(); createClusterReq.DatabaseName = databaseName; createClusterReq.DBClusterIdentifier = dbClusterIdentifier; createClusterReq.Engine = databaseEngine; if (!string.IsNullOrEmpty(secGroupId)) { createClusterReq.VpcSecurityGroupIds.Add(secGroupId); } createClusterReq.MasterUserPassword = MasterUserPassword; createClusterReq.MasterUsername = MasterUsername; Amazon.RDS.Model.CreateDBClusterResponse createClusterResp = rdsClient.CreateDBCluster(createClusterReq); Amazon.RDS.Model.DBCluster createdCluster = createClusterResp.DBCluster; dbClusterIdentifier = createdCluster.DBClusterIdentifier; return createdCluster; } /// <summary> /// DeleteDBClusterRDS /// </summary> /// <param name="rdsClient">Amazon.RDS.AmazonRDSClient</param> /// <param name="dbClusterIdentifier">Identifier of RDS DatabaseCluster 2 delete</param> /// <returns>HttpStatusCode</returns> static HttpStatusCode DeleteDBClusterRDS(Amazon.RDS.AmazonRDSClient rdsClient, string dbClusterIdentifier) { if (!string.IsNullOrEmpty(dbClusterIdentifier)) { throw new ArgumentException("Null or Empty DBClusterIdentifier which is needed for Amazon.RDS.Model.DeleteDBClusterRequest", "string dbClusterIdentifier"); } Console.WriteLine("Deleting DeleteDBClusterRDS with identifier " + dbClusterIdentifier); Amazon.RDS.Model.DeleteDBClusterRequest delClusterReq = new Amazon.RDS.Model.DeleteDBClusterRequest(); delClusterReq.DBClusterIdentifier = dbClusterIdentifier; Amazon.RDS.Model.DeleteDBClusterResponse delClusterResp = rdsClient.DeleteDBCluster(delClusterReq); return delClusterResp.HttpStatusCode; } /// <summary> /// DeleteSecurityGroup /// </summary> /// <param name="ec2Client">EC2Client</param> /// <param name="securityGroupId">Identifier of SecurityGroup 2 delete</param> /// <returns>HttpStatusCode</returns> static HttpStatusCode DeleteSecurityGroup(AmazonEC2Client ec2Client, string securityGroupId) { if (!string.IsNullOrEmpty(securityGroupId)) { throw new ArgumentException("Null or Empty securityGroupId which is needed for Amazon.EC2.Model.DeleteSecurityGroupRequest", "string securityGroupId"); } Console.WriteLine("Deleting SecurityGroup " + securityGroupId); DeleteSecurityGroupRequest delSecGroupReq = new DeleteSecurityGroupRequest(); delSecGroupReq.GroupId = securityGroupId; DeleteSecurityGroupResponse delSecGroupResp = ec2Client.DeleteSecurityGroup(delSecGroupReq); return delSecGroupResp.HttpStatusCode; } /// <summary> /// Create instance profile & grant EC2 instance requesting S3 bucket /// </summary> /// <returns></returns> static string CreateInstanceProfile() { var roleName = SAMPLE_NAME; var client = new AmazonIdentityManagementServiceClient(); client.CreateRole(new CreateRoleRequest { RoleName = roleName, AssumeRolePolicyDocument = @"{""Statement"":[{""Principal"":{""Service"":[""ec2.amazonaws.com""]},""Effect"":""Allow"",""Action"":[""sts:AssumeRole""]}]}" }); var statement = new Amazon.Auth.AccessControlPolicy.Statement( Amazon.Auth.AccessControlPolicy.Statement.StatementEffect.Allow); statement.Actions.Add(S3ActionIdentifiers.AllS3Actions); statement.Resources.Add(new Resource("*")); var policy = new Policy(); policy.Statements.Add(statement); client.PutRolePolicy(new PutRolePolicyRequest { RoleName = roleName, PolicyName = "S3Access", PolicyDocument = policy.ToJson() }); var response = client.CreateInstanceProfile(new CreateInstanceProfileRequest { InstanceProfileName = roleName }); client.AddRoleToInstanceProfile(new AddRoleToInstanceProfileRequest { InstanceProfileName = roleName, RoleName = roleName }); return response.InstanceProfile.Arn; } /// <summary> /// Delete the instance profile created for the sample. /// </summary> static void DeleteInstanceProfile() { var roleName = SAMPLE_NAME; var client = new AmazonIdentityManagementServiceClient(); client.DeleteRolePolicy(new DeleteRolePolicyRequest { RoleName = roleName, PolicyName = "S3Access" }); client.RemoveRoleFromInstanceProfile(new RemoveRoleFromInstanceProfileRequest { InstanceProfileName = roleName, RoleName = roleName }); client.DeleteRole(new DeleteRoleRequest { RoleName = roleName }); client.DeleteInstanceProfile(new DeleteInstanceProfileRequest { InstanceProfileName = roleName }); } static string EncodeToBase64(string str) { byte[] toEncodeAsBytes = System.Text.Encoding.UTF8.GetBytes(str); string returnValue = System.Convert.ToBase64String(toEncodeAsBytes); return returnValue; } } }
// <copyright file="UserGramSchmidtTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Single.Factorization; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Single.Factorization { /// <summary> /// GramSchmidt factorization tests for a user matrix. /// </summary> [TestFixture, Category("LAFactorization")] public class UserGramSchmidtTests { /// <summary> /// Constructor with wide matrix throws <c>ArgumentException</c>. /// </summary> [Test] public void ConstructorWideMatrixThrowsInvalidMatrixOperationException() { Assert.That(() => UserGramSchmidt.Create(new UserDefinedMatrix(3, 4)), Throws.ArgumentException); } /// <summary> /// Can factorize identity matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void CanFactorizeIdentity(int order) { var matrixI = UserDefinedMatrix.Identity(order); var factorGramSchmidt = matrixI.GramSchmidt(); var q = factorGramSchmidt.Q; var r = factorGramSchmidt.R; Assert.AreEqual(matrixI.RowCount, q.RowCount); Assert.AreEqual(matrixI.ColumnCount, q.ColumnCount); for (var i = 0; i < r.RowCount; i++) { for (var j = 0; j < r.ColumnCount; j++) { Assert.AreEqual(i == j ? 1.0 : 0.0, r[i, j]); } } for (var i = 0; i < q.RowCount; i++) { for (var j = 0; j < q.ColumnCount; j++) { Assert.AreEqual(i == j ? 1.0 : 0.0, q[i, j]); } } } /// <summary> /// Identity determinant is one. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void IdentityDeterminantIsOne(int order) { var matrixI = UserDefinedMatrix.Identity(order); var factorGramSchmidt = matrixI.GramSchmidt(); Assert.AreEqual(1.0, factorGramSchmidt.Determinant); } /// <summary> /// Can factorize a random matrix. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(2, 2)] [TestCase(5, 5)] [TestCase(10, 6)] [TestCase(50, 48)] [TestCase(100, 98)] public void CanFactorizeRandomMatrix(int row, int column) { var matrixA = new UserDefinedMatrix(Matrix<float>.Build.Random(row, column, 1).ToArray()); var factorGramSchmidt = matrixA.GramSchmidt(); var q = factorGramSchmidt.Q; var r = factorGramSchmidt.R; // Make sure the Q has the right dimensions. Assert.AreEqual(row, q.RowCount); Assert.AreEqual(column, q.ColumnCount); // Make sure the R has the right dimensions. Assert.AreEqual(column, r.RowCount); Assert.AreEqual(column, r.ColumnCount); // Make sure the R factor is upper triangular. for (var i = 0; i < r.RowCount; i++) { for (var j = 0; j < r.ColumnCount; j++) { if (i > j) { Assert.AreEqual(0.0, r[i, j]); } } } // Make sure the Q*R is the original matrix. var matrixQfromR = q * r; for (var i = 0; i < matrixQfromR.RowCount; i++) { for (var j = 0; j < matrixQfromR.ColumnCount; j++) { Assert.AreEqual(matrixA[i, j], matrixQfromR[i, j], 1e-4); } } } /// <summary> /// Can solve a system of linear equations for a random vector (Ax=b). /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVector(int order) { var matrixA = new UserDefinedMatrix(Matrix<float>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorGramSchmidt = matrixA.GramSchmidt(); var vectorb = new UserDefinedVector(Vector<float>.Build.Random(order, 1).ToArray()); var resultx = factorGramSchmidt.Solve(vectorb); Assert.AreEqual(matrixA.ColumnCount, resultx.Count); var matrixBReconstruct = matrixA * resultx; // Check the reconstruction. for (var i = 0; i < order; i++) { Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1e-3); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B). /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomMatrix(int order) { var matrixA = new UserDefinedMatrix(Matrix<float>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorGramSchmidt = matrixA.GramSchmidt(); var matrixB = new UserDefinedMatrix(Matrix<float>.Build.Random(order, order, 1).ToArray()); var matrixX = factorGramSchmidt.Solve(matrixB); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA * matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1e-3); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve for a random vector into a result vector. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVectorWhenResultVectorGiven(int order) { var matrixA = new UserDefinedMatrix(Matrix<float>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorGramSchmidt = matrixA.GramSchmidt(); var vectorb = new UserDefinedVector(Vector<float>.Build.Random(order, 1).ToArray()); var vectorbCopy = vectorb.Clone(); var resultx = new UserDefinedVector(order); factorGramSchmidt.Solve(vectorb, resultx); Assert.AreEqual(vectorb.Count, resultx.Count); var matrixBReconstruct = matrixA * resultx; // Check the reconstruction. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1e-3); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure b didn't change. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorbCopy[i], vectorb[i]); } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomMatrixWhenResultMatrixGiven(int order) { var matrixA = new UserDefinedMatrix(Matrix<float>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorGramSchmidt = matrixA.GramSchmidt(); var matrixB = new UserDefinedMatrix(Matrix<float>.Build.Random(order, order, 1).ToArray()); var matrixBCopy = matrixB.Clone(); var matrixX = new UserDefinedMatrix(order, order); factorGramSchmidt.Solve(matrixB, matrixX); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA * matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1e-3); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure B didn't change. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]); } } } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System.Net.Sockets; using System.Collections; using System.Threading; ////using Microsoft.SPOT.Net.Security; /// <summary> /// Provides a simple, programmatically controlled HTTP protocol listener. /// This class cannot be inherited. /// </summary> /// <remarks> /// This class enables using a socket to receive data that uses the HTTP /// protocol. /// </remarks> public class HttpListener { /// <summary> /// Indicates whether the listener is waiting on an http or https /// connection. /// </summary> bool m_isHttpsConnection; /// <summary> /// The certificate to send during https authentication. /// </summary> //////X509Certificate m_httpsCert; /// <summary> /// This value is the number of connections that can be ready but are /// not retrieved through the Accept call. /// </summary> /// <remarks> /// This value is passed to the <b>Listen</b> method of the socket. /// </remarks> private const int MaxCountOfPendingConnections = 10; /// <summary> /// The time we keep connection idle with HTTP 1.1 /// This is one minute. /// </summary> internal const int DefaultKeepAliveMilliseconds = 60000; /// <summary> /// Server socket for incoming connections. /// </summary> private Socket m_listener; /// <summary> /// The MAXIMUM length, in kilobytes (1024 bytes), of the request /// headers. /// </summary> internal int m_maxResponseHeadersLen; /// <summary> /// Event that indicates arrival of new event from client. /// </summary> private AutoResetEvent m_requestArrived; /// <summary> /// The queue of connected networks streams with pending client data. /// </summary> Queue m_inputStreamsQueue; /// <summary> /// Port number for the server socket. /// </summary> private int m_port; /// <summary> /// Indicates whether the listener is started and is currently accepting /// connections. /// </summary> private bool m_serviceRunning; /// <summary> /// Indicates whether the listener has been closed /// </summary> private bool m_closed; /// <summary> /// Array of connected client sockets. /// </summary> private ArrayList m_clientStreams; /// <summary> /// Http Thread for accepting new connections. /// </summary> private Thread m_thAccept; /// <summary> /// Creates an HTTP or HTTPS listener on the standard ports. /// </summary> /// <param name="prefix">Prefix ( http or https ) to start listen</param> /// <remarks>In the desktop version of .NET, the constructor for this /// class has no arguments.</remarks> public HttpListener(string prefix) { InitListener(prefix, -1); } /// <summary> /// Creates an HTTP or HTTPS listener on the specified port. /// </summary> /// <param name="prefix">The prefix for the service, either "http" or /// "https".</param> /// <param name="port">The port to start listening on. If -1, the /// default port is used (port 80 for http, or port 443 for https). /// </param> /// <remarks>In the desktop version of .NET, the constructor for this /// class has no arguments.</remarks> public HttpListener(string prefix, int port) { InitListener(prefix, port); } /// <summary> /// Initializes the listener. /// </summary> /// <param name="prefix">The prefix for the service, either "http" or /// "https".</param> /// <param name="port">The port to start listening on. If -1, the /// default port is used (port 80 for http, or port 443 for https). /// </param> private void InitListener(string prefix, int port) { switch (prefix.ToLower()) { case "http": { m_isHttpsConnection = false; m_port = Uri.HttpDefaultPort; break; } case "https": { m_isHttpsConnection = true; m_port = Uri.HttpsDefaultPort; break; } default: throw new ArgumentException("Prefix should be http or https"); } if (port != -1) { m_port = port; } // Default members initialization m_maxResponseHeadersLen = 4; m_requestArrived = new AutoResetEvent(false); m_inputStreamsQueue = new Queue(); m_clientStreams = new ArrayList(); } /// <summary> /// Adds a new output stream to the list of connected streams. /// </summary> /// <remarks>This is an internal function, not visible to the user. /// </remarks> /// <param name="clientStream">The stream to add.</param> internal void AddClientStream(OutputNetworkStreamWrapper clientStream) { lock(m_clientStreams) { m_clientStreams.Add(clientStream); } } /// <summary> /// Removes the specified output stream from the list of connected /// streams. /// </summary> /// <param name="clientStream">The stream to remove.</param> internal void RemoveClientStream(OutputNetworkStreamWrapper clientStream) { lock(m_clientStreams) { for (int i = 0; i < m_clientStreams.Count; i++) { if (clientStream == m_clientStreams[i]) { m_clientStreams.RemoveAt(i); break; } } } } /// <summary> /// Packages together an HttpListener and a socket. /// </summary> /// <remarks>This class is used to package together an HttpListener and a socket. /// We need to start new thread and pass 2 parameters - instance of listener and socket. /// For that purpose we create class that keeps references to both listerner and socket and /// start thread using member function of this class as delegate. /// Internal class not visible to user.</remarks> private class HttpListernerAndStream { internal HttpListernerAndStream(HttpListener listener, OutputNetworkStreamWrapper outputStream) { m_listener = listener; m_outStream = outputStream; } internal HttpListener m_listener; internal OutputNetworkStreamWrapper m_outStream; // Forwards to waiting function of the listener. internal void AddToWaitingConnections() { m_listener.WaitingConnectionThreadFunc(m_outStream); } } internal void AddToWaitingConnections(OutputNetworkStreamWrapper outputStream) { // Create a thread that blocks onsocket.Poll - basically waits for new data from client. HttpListernerAndStream listAndSock = new HttpListernerAndStream(this, outputStream); // Creates new thread to wait on data Thread thWaitData = new Thread(listAndSock.AddToWaitingConnections); thWaitData.Start(); } /// <summary> /// Waits for new data from the client. /// </summary> private void WaitingConnectionThreadFunc(OutputNetworkStreamWrapper outputStream) { try { // This is a blocking call waiting for more data. outputStream.m_socket.Poll(DefaultKeepAliveMilliseconds * 1000, SelectMode.SelectRead); if (outputStream.m_socket.Available > 0) { // Add this connected stream to the list. lock (m_inputStreamsQueue) { m_inputStreamsQueue.Enqueue(outputStream); } // Set event that client stream or exception is added to the queue. m_requestArrived.Set(); } else // If no data available - means connection was close on other side or timed out. { outputStream.Dispose(); } } catch { } } /// <summary> /// Shuts down the <itemref>HttpListener</itemref> object immediately, /// discarding all currently queued requests. /// </summary> /// <remarks>This method disposes of all resources held by this /// listener. Any pending requests are unable to complete. To shut /// down the <itemref>HttpListener</itemref> object after processing /// currently queued requests, use the /// <see cref='System.Net.HttpListener.Close'/> method. /// <para> /// After calling this method, you will receive an /// <see cref='ObjectDisposedException'/> if you attempt to use this /// <itemref>HttpListener</itemref>. /// </para> /// </remarks> public void Abort() { lock (this) { // First we shut down the service. Close(); // Now we need to go through list of all client sockets and close all of them. // This will cause exceptions on read/write operations on these sockets. foreach (OutputNetworkStreamWrapper netStream in m_clientStreams) { netStream.Close(); } m_clientStreams.Clear(); } if (m_thAccept != null) { m_thAccept.Join(); } } /// <summary> /// Waits for new connections from the client. /// </summary> /// <remarks>On new connections, this method enques the new input /// network stream and sets an event that a new connection is available. /// </remarks> private void AcceptThreadFunc() { Thread.CurrentThread.Priority = ThreadPriority.AboveNormal; // If there was no exception up to this point, means we succeded to start listening. m_serviceRunning = true; int retry = 0; // The Start function is waiting on this event. We set it to indicate that // thread that waits for connections is already started. m_requestArrived.Set(); // The value of m_serviceStarted normally is changed from other thread by calling Stop. while (m_serviceRunning) { Socket clientSock; // Need to create NetworkStream or SSL stream depending on protocol used. NetworkStream netStream = null; try { // It is important that multithread access to m_listener.Accept(); is not locked. // If it was locked - then Close or Stop would be blocked potnetially for ever while waiting for connection. // This is a blocking call waiting for connection. clientSock = m_listener.Accept(); retry = 0; try { // set NoDelay to increase HTTP(s) response times clientSock.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true); } catch { } } catch (SocketException) { if (retry > 5) { // If request to stop listener flag is set or locking call is interupted return // On exception we stop the service and record the exception. if (m_serviceRunning && !m_closed) { Stop(); } // Set event to unblock thread waiting for accept. m_requestArrived.Set(); break; } retry++; continue; } catch { // If request to stop listener flag is set or locking call is interupted return // On exception we stop the service and record the exception. if (m_serviceRunning && !m_closed) { Stop(); } // Set event to unblock thread waiting for accept. m_requestArrived.Set(); break; } try { if (!m_isHttpsConnection) { // This is case of normal HTTP. Create network stream. netStream = new NetworkStream(clientSock, true); } else { throw new NotImplementedException( ); //////// This is the case of https. //////// Once connection estiblished need to create secure stream and authenticate server. //////netStream = new SslStream(clientSock); //////SslProtocols[] sslProtocols = new SslProtocols[] { SslProtocols.Default }; //////// Throws exception if fails. //////((SslStream)netStream).AuthenticateAsServer(m_httpsCert, SslVerification.NoVerification, sslProtocols); //////netStream.ReadTimeout = 10000; } } catch(SocketException) { if (netStream != null) { netStream.Dispose(); } else { clientSock.Close(); } m_requestArrived.Set(); // try again continue; } // Add this connected stream to the list. lock (m_inputStreamsQueue) { m_inputStreamsQueue.Enqueue(new OutputNetworkStreamWrapper(clientSock, netStream)); } // Set event that client stream or exception is added to the queue. m_requestArrived.Set(); } } /// <summary> /// Allows this instance to receive incoming requests. /// </summary> /// <remarks>This method must be called before you call the /// <see cref="System.Net.HttpListener.GetContext"/> method. If /// the service was already started, the call has no effect. After you /// have started an <itemref>HttpListener</itemref> object, you can use /// the <see cref='System.Net.HttpListener.Stop'/> method to stop it. /// </remarks> public void Start() { lock (this) { if(m_closed) throw new ObjectDisposedException( "System.Net.HttpListener" ); // If service was already started, the call has no effect. if (m_serviceRunning) { return; } m_listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { // set NoDelay to increase HTTP(s) response times m_listener.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true); } catch {} try { // Start server socket to accept incoming connections. m_listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); } catch {} IPEndPoint endPoint = new IPEndPoint(IPAddress.GetDefaultLocalAddress(), m_port); m_listener.Bind(endPoint); // Starts to listen to maximum of 10 connections. m_listener.Listen(MaxCountOfPendingConnections); // Create a thread that blocks on m_listener.Accept() - basically waits for connection from client. m_thAccept = new Thread(AcceptThreadFunc); m_thAccept.Start(); // Waits for thread that calls Accept to start. m_requestArrived.WaitOne(); } } /// <summary> /// Shuts down the <itemref>HttpListener</itemref> after processing all /// currently queued requests. /// </summary> /// <remarks>After calling this method, you can no longer use the /// <itemref>HttpListener</itemref> object. To temporarily pause an /// <itemref>HttpListener</itemref> object, use the /// <see cref='System.Net.HttpListener.Stop'/> method.</remarks> public void Close() { lock(this) { // close does not throw try { Stop(); } catch { } m_closed = true; } } /// <summary> /// Causes this instance to stop receiving incoming requests. /// </summary> /// <remarks>If this instance is already stopped, calling this method /// has no effect. /// <para> /// After you have stopped an <itemref>HttpListener</itemref> object, /// you can use the <see cref='System.Net.HttpListener.Start'/> method /// to restart it. /// </para> /// </remarks> public void Stop() { // Need to lock access to object, because Stop can be called from a // different thread. lock (this) { if (m_closed) throw new ObjectDisposedException( "System.Net.HttpListener" ); m_serviceRunning = false; // We close the server socket that listen for incoming connection. // Connections that already accepted are processed. // Connections that has been in queue for server socket, but not accepted, are lost. if(m_listener != null) { m_listener.Close(); m_listener = null; m_requestArrived.Set(); } } } /// <summary> /// Waits for an incoming request and returns when one is received. /// </summary> /// <returns> /// An <see cref="System.Net.HttpListenerContext"/> object that /// represents a client request. /// </returns> /// <exception cref="SocketException">A socket call failed. Check the /// exception's ErrorCode property to determine the cause of the exception.</exception> /// <exception cref="InvalidOperationException">This object has not been started or is /// currently stopped or The HttpListener does not have any Uniform Resource Identifier /// (URI) prefixes to respond to.</exception> /// <exception cref="ObjectDisposedException">This object is closed.</exception> /// <example>This example shows how to call the /// <itemref>GetContext</itemref> method. /// <code> /// HttpListener myListener = new HttpListener("http", -1); /// myListener.Start(); /// while (true) /// { /// HttpListenerResponse response = null; /// try /// { /// Debug.Print("Waiting for requests"); /// HttpListenerContext context = myListener.GetContext(); /// </code> /// </example> public HttpListenerContext GetContext() { // Protects access for simulteneous call for GetContext and Close or Stop. lock (this) { if (m_closed) throw new ObjectDisposedException( "System.Net.HttpListener" ); if (!m_serviceRunning) throw new InvalidOperationException(); } // Try to get context until service is running. while (m_serviceRunning) { // Before waiting for event we need to look for pending connections. lock (m_inputStreamsQueue) { if (m_inputStreamsQueue.Count > 0) { OutputNetworkStreamWrapper outputStreamWrap = m_inputStreamsQueue.Dequeue() as OutputNetworkStreamWrapper; if (outputStreamWrap != null) { return new HttpListenerContext(outputStreamWrap, this); } } } // Waits for new connection to arrive on new or existing socket. m_requestArrived.WaitOne(); } return null; } /// <summary> /// Gets whether the <itemref>HttpListener</itemref> service was started /// and is waiting for client connections. /// </summary> /// <value><itemref>true</itemref> if the /// <itemref>HttpListener</itemref> was started; otherwise, /// <itemref>false</itemref>.</value> public bool IsListening { get { return m_serviceRunning; } } /// <summary> /// Gets or sets the maximum allowed length of the response headers, in /// KB. /// </summary> /// <value>The length, in kilobytes (1024 bytes), of the response /// headers.</value> /// <remarks> /// The length of the response header includes the response status line /// and any extra control characters that are received as part of the /// HTTP protocol. A value of -1 means no limit is imposed on the /// response headers; a value of 0 means that all requests fail. If /// this property is not explicitly set, it defaults to 4 (KB). /// </remarks> public int MaximumResponseHeadersLength { get { return m_maxResponseHeadersLen; } set { if (value <= 0 && value != -1) { throw new ArgumentOutOfRangeException(); } m_maxResponseHeadersLen = value; } } ///////// <summary> ///////// The certificate used if <b>HttpListener</b> implements an https ///////// server. ///////// </summary> //////public X509Certificate HttpsCert //////{ ////// get { return m_httpsCert; } ////// set { m_httpsCert = 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace Microsoft.Win32.SafeHandles { public sealed partial class SafeProcessHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid { public SafeProcessHandle(System.IntPtr existingHandle, bool ownsHandle) : base(default(bool)) { } public override bool IsInvalid { [System.Security.SecurityCritical] get { throw null; } } protected override bool ReleaseHandle() { throw null; } } } namespace System.Diagnostics { public partial class DataReceivedEventArgs : System.EventArgs { internal DataReceivedEventArgs() { } public string Data { get { throw null; } } } public delegate void DataReceivedEventHandler(object sender, System.Diagnostics.DataReceivedEventArgs e); public partial class Process : System.ComponentModel.Component { public IntPtr Handle { get { throw null; } } public int HandleCount { get { throw null; } } public IntPtr MainWindowHandle { get { throw null; } } public string MainWindowTitle { get { throw null; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.NonpagedSystemMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int NonpagedSystemMemorySize { get { throw null; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PagedMemorySize { get { throw null; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedSystemMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PagedSystemMemorySize { get { throw null; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakPagedMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PeakPagedMemorySize { get { throw null; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakVirtualMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PeakVirtualMemorySize { get { throw null; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakWorkingSet64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PeakWorkingSet { get { throw null; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PrivateMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PrivateMemorySize { get { throw null; } } public bool Responding { get { throw null; } } public System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get { throw null; } set { } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.VirtualMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int VirtualMemorySize { get { throw null; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.WorkingSet64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int WorkingSet { get { throw null; } } public void Close() { } public bool CloseMainWindow() { throw null; } protected override void Dispose(bool disposing) { } public bool WaitForInputIdle() { throw null; } public bool WaitForInputIdle(int milliseconds) { throw null; } public override string ToString() { throw null; } public Process() { } public int BasePriority { get { throw null; } } [System.ComponentModel.DefaultValueAttribute(false)] public bool EnableRaisingEvents { get { throw null; } set { } } public int ExitCode { get { throw null; } } public System.DateTime ExitTime { get { throw null; } } public bool HasExited { get { throw null; } } public int Id { get { throw null; } } public string MachineName { get { throw null; } } public System.Diagnostics.ProcessModule MainModule { get { throw null; } } public System.IntPtr MaxWorkingSet { get { throw null; } set { } } public System.IntPtr MinWorkingSet { get { throw null; } set { } } public System.Diagnostics.ProcessModuleCollection Modules { get { throw null; } } public long NonpagedSystemMemorySize64 { get { throw null; } } public long PagedMemorySize64 { get { throw null; } } public long PagedSystemMemorySize64 { get { throw null; } } public long PeakPagedMemorySize64 { get { throw null; } } public long PeakVirtualMemorySize64 { get { throw null; } } public long PeakWorkingSet64 { get { throw null; } } public bool PriorityBoostEnabled { get { throw null; } set { } } public System.Diagnostics.ProcessPriorityClass PriorityClass { get { throw null; } set { } } public long PrivateMemorySize64 { get { throw null; } } public System.TimeSpan PrivilegedProcessorTime { get { throw null; } } public string ProcessName { get { throw null; } } public System.IntPtr ProcessorAffinity { get { throw null; } set { } } public Microsoft.Win32.SafeHandles.SafeProcessHandle SafeHandle { get { throw null; } } public int SessionId { get { throw null; } } public System.IO.StreamReader StandardError { get { throw null; } } public System.IO.StreamWriter StandardInput { get { throw null; } } public System.IO.StreamReader StandardOutput { get { throw null; } } public System.Diagnostics.ProcessStartInfo StartInfo { get { throw null; } set { } } public System.DateTime StartTime { get { throw null; } } public System.Diagnostics.ProcessThreadCollection Threads { get { throw null; } } public System.TimeSpan TotalProcessorTime { get { throw null; } } public System.TimeSpan UserProcessorTime { get { throw null; } } public long VirtualMemorySize64 { get { throw null; } } public long WorkingSet64 { get { throw null; } } public event System.Diagnostics.DataReceivedEventHandler ErrorDataReceived { add { } remove { } } public event System.EventHandler Exited { add { } remove { } } public event System.Diagnostics.DataReceivedEventHandler OutputDataReceived { add { } remove { } } public void BeginErrorReadLine() { } public void BeginOutputReadLine() { } public void CancelErrorRead() { } public void CancelOutputRead() { } public static void EnterDebugMode() { } public static System.Diagnostics.Process GetCurrentProcess() { throw null; } public static System.Diagnostics.Process GetProcessById(int processId) { throw null; } public static System.Diagnostics.Process GetProcessById(int processId, string machineName) { throw null; } public static System.Diagnostics.Process[] GetProcesses() { throw null; } public static System.Diagnostics.Process[] GetProcesses(string machineName) { throw null; } public static System.Diagnostics.Process[] GetProcessesByName(string processName) { throw null; } public static System.Diagnostics.Process[] GetProcessesByName(string processName, string machineName) { throw null; } public void Kill() { } public static void LeaveDebugMode() { } protected void OnExited() { } public void Refresh() { } public bool Start() { throw null; } public static System.Diagnostics.Process Start(System.Diagnostics.ProcessStartInfo startInfo) { throw null; } public static System.Diagnostics.Process Start(string fileName) { throw null; } public static System.Diagnostics.Process Start(string fileName, string arguments) { throw null; } [System.CLSCompliant(false)] public static System.Diagnostics.Process Start(string fileName, string userName, System.Security.SecureString password, string domain) { throw null; } [System.CLSCompliant(false)] public static System.Diagnostics.Process Start(string fileName, string arguments, string userName, System.Security.SecureString password, string domain) { throw null; } public void WaitForExit() { } public bool WaitForExit(int milliseconds) { throw null; } } public partial class ProcessModule : System.ComponentModel.Component { internal ProcessModule() { } public System.IntPtr BaseAddress { get { throw null; } } public System.IntPtr EntryPointAddress { get { throw null; } } public string FileName { get { throw null; } } public int ModuleMemorySize { get { throw null; } } public string ModuleName { get { throw null; } } public FileVersionInfo FileVersionInfo { get { throw null; } } public override string ToString() { throw null; } } public partial class ProcessModuleCollection : System.Collections.ReadOnlyCollectionBase { protected ProcessModuleCollection() { } public ProcessModuleCollection(System.Diagnostics.ProcessModule[] processModules) { } public System.Diagnostics.ProcessModule this[int index] { get { throw null; } } public bool Contains(System.Diagnostics.ProcessModule module) { throw null; } public void CopyTo(System.Diagnostics.ProcessModule[] array, int index) { } public int IndexOf(System.Diagnostics.ProcessModule module) { throw null; } } public enum ProcessPriorityClass { AboveNormal = 32768, BelowNormal = 16384, High = 128, Idle = 64, Normal = 32, RealTime = 256, } public sealed partial class ProcessStartInfo { public ProcessStartInfo() { } public ProcessStartInfo(string fileName) { } public ProcessStartInfo(string fileName, string arguments) { } public string Arguments { get { throw null; } set { } } public bool CreateNoWindow { get { throw null; } set { } } public string Domain { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(null)] public System.Collections.Generic.IDictionary<string, string> Environment { get { throw null; } } public string FileName { get { throw null; } set { } } public bool LoadUserProfile { get { throw null; } set { } } [System.CLSCompliant(false)] public System.Security.SecureString Password { get { throw null; } set { } } public bool RedirectStandardError { get { throw null; } set { } } public bool RedirectStandardInput { get { throw null; } set { } } public bool RedirectStandardOutput { get { throw null; } set { } } public System.Text.Encoding StandardErrorEncoding { get { throw null; } set { } } public System.Text.Encoding StandardOutputEncoding { get { throw null; } set { } } public string UserName { get { throw null; } set { } } public bool UseShellExecute { get { throw null; } set { } } public string WorkingDirectory { get { throw null; } set { } } public bool ErrorDialog { get { throw null; } set { } } public System.IntPtr ErrorDialogParentHandle { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(null)] public string Verb { get { throw null; } set { } } public string[] Verbs { get { throw null; } } [System.ComponentModel.DefaultValueAttribute(null)] public System.Diagnostics.ProcessWindowStyle WindowStyle { get { throw null ; } set { } } public System.Collections.Specialized.StringDictionary EnvironmentVariables { get { throw null; } } } public partial class ProcessThread : System.ComponentModel.Component { internal ProcessThread() { } public int BasePriority { get { throw null; } } public int CurrentPriority { get { throw null; } } public int Id { get { throw null; } } public int IdealProcessor { set { } } public bool PriorityBoostEnabled { get { throw null; } set { } } public System.Diagnostics.ThreadPriorityLevel PriorityLevel { get { throw null; } set { } } public System.TimeSpan PrivilegedProcessorTime { get { throw null; } } public System.IntPtr ProcessorAffinity { set { } } public System.IntPtr StartAddress { get { throw null; } } public System.DateTime StartTime { get { throw null; } } public System.Diagnostics.ThreadState ThreadState { get { throw null; } } public System.TimeSpan TotalProcessorTime { get { throw null; } } public System.TimeSpan UserProcessorTime { get { throw null; } } public System.Diagnostics.ThreadWaitReason WaitReason { get { throw null; } } public void ResetIdealProcessor() { } } public partial class ProcessThreadCollection : System.Collections.ReadOnlyCollectionBase { protected ProcessThreadCollection() { } public ProcessThreadCollection(System.Diagnostics.ProcessThread[] processThreads) { } public System.Diagnostics.ProcessThread this[int index] { get { throw null; } } public int Add(System.Diagnostics.ProcessThread thread) { throw null; } public bool Contains(System.Diagnostics.ProcessThread thread) { throw null; } public void CopyTo(System.Diagnostics.ProcessThread[] array, int index) { } public int IndexOf(System.Diagnostics.ProcessThread thread) { throw null; } public void Insert(int index, System.Diagnostics.ProcessThread thread) { } public void Remove(System.Diagnostics.ProcessThread thread) { } } public enum ThreadPriorityLevel { AboveNormal = 1, BelowNormal = -1, Highest = 2, Idle = -15, Lowest = -2, Normal = 0, TimeCritical = 15, } public enum ThreadState { Initialized = 0, Ready = 1, Running = 2, Standby = 3, Terminated = 4, Transition = 6, Unknown = 7, Wait = 5, } public enum ThreadWaitReason { EventPairHigh = 7, EventPairLow = 8, ExecutionDelay = 4, Executive = 0, FreePage = 1, LpcReceive = 9, LpcReply = 10, PageIn = 2, PageOut = 12, Suspended = 5, SystemAllocation = 3, Unknown = 13, UserRequest = 6, VirtualMemory = 11, } public enum ProcessWindowStyle { Hidden = 1, Maximized = 3, Minimized = 2, Normal = 0, } public class MonitoringDescriptionAttribute : System.ComponentModel.DescriptionAttribute { public MonitoringDescriptionAttribute(string description) { throw null; } public override string Description { get { throw null; } } } }
/* * REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application * * The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists. * * OpenAPI spec version: v1 * * */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using HETSAPI.Models; namespace HETSAPI.Models { /// <summary> /// Additional attributes about a piece of equipment designated as a Dump Truck. Historically, there was a perceived need to track a lot of informatiion about a dump truck, but in practice, few fields are being completed by users. Places for the attributes are being maintained, but the UI is prompting only for a couple of the fields, and only those fields are likely to be populated. Additional basic information about the attributes can be found on Wikipedia, BC-specific details on MOTI&amp;#39;s CVSE website and www.bclaws.ca&amp;#x2F;EPLibraries&amp;#x2F;bclaws_new&amp;#x2F;document&amp;#x2F;ID&amp;#x2F;freeside&amp;#x2F;30_78#AppendicesAtoK, Appendix A and B. Any metrics information provided here is from the Equipment Owner. /// </summary> [MetaDataExtension (Description = "Additional attributes about a piece of equipment designated as a Dump Truck. Historically, there was a perceived need to track a lot of informatiion about a dump truck, but in practice, few fields are being completed by users. Places for the attributes are being maintained, but the UI is prompting only for a couple of the fields, and only those fields are likely to be populated. Additional basic information about the attributes can be found on Wikipedia, BC-specific details on MOTI&amp;#39;s CVSE website and www.bclaws.ca&amp;#x2F;EPLibraries&amp;#x2F;bclaws_new&amp;#x2F;document&amp;#x2F;ID&amp;#x2F;freeside&amp;#x2F;30_78#AppendicesAtoK, Appendix A and B. Any metrics information provided here is from the Equipment Owner.")] public partial class DumpTruck : AuditableEntity, IEquatable<DumpTruck> { /// <summary> /// Default constructor, required by entity framework /// </summary> public DumpTruck() { this.Id = 0; } /// <summary> /// Initializes a new instance of the <see cref="DumpTruck" /> class. /// </summary> /// <param name="Id">A system-generated unique identifier for a DumpTruck (required).</param> /// <param name="IsSingleAxle">True if the vehicle has a single axle. Can be false or null..</param> /// <param name="IsTandemAxle">True if the vehicle has a tandem axle. Can be false or null..</param> /// <param name="IsTridem">True if the Dump Truck is a tridem - a three axle dump truck. Can be false or null..</param> /// <param name="HasPUP">True if the Dump Truck has a PUP trailer - a trailer with it&amp;#39;s own hydraulic unloading system. Can be false or null..</param> /// <param name="HasBellyDump">True if the Dump Truck has a belly dump capability. Can be false or null..</param> /// <param name="HasRockBox">True if the Dump Truck has a rock box. Can be false or null..</param> /// <param name="HasHiliftGate">True if the Dump Truck has a high lift gate vs. a traditional gate. Can be false or null..</param> /// <param name="IsWaterTruck">True if the Dump Truck is a Water Truck. Can be false or null..</param> /// <param name="HasSealcoatHitch">True if the Dump Truck has a hitch for using sealcoat trailers. Can be false or null..</param> /// <param name="RearAxleSpacing">The spacing of the rear axles, if applicable. Usually in metres..</param> /// <param name="FrontTireSize">The size of of the Front Tires of the Dump Truck..</param> /// <param name="FrontTireUOM">The Unit of Measure of the Front Tire Size..</param> /// <param name="FrontAxleCapacity">The rated capacity of the Front Axle..</param> /// <param name="RearAxleCapacity">The rated capacity of the Rear Axle..</param> /// <param name="LegalLoad">The legal load of the vehicle in kg..</param> /// <param name="LegalCapacity">The legal capacity of the dump truck..</param> /// <param name="LegalPUPTareWeight">The legal Tare Weight (weight when unloaded) of the PUP trailer..</param> /// <param name="LicencedGVW">The Gross Vehicle Weight for which the vehicle is licensed. GVW includes the vehicle&amp;#39;s chassis, body, engine, engine fluids, fuel, accessories, driver, passengers and cargo but excluding that of any trailers..</param> /// <param name="LicencedGVWUOM">The Unit of Measure (UOM) of the licenced GVW..</param> /// <param name="LicencedTareWeight">The licenced Tare Weight (weight when unloaded) of the vehicle..</param> /// <param name="LicencedPUPTareWeight">The licenced Tare Weight (weight when unloaded) of the PUP trailer..</param> /// <param name="LicencedLoad">The licenced maximum load of the vehicle in kg..</param> /// <param name="LicencedCapacity">The licenced maximum capacity of the vehicle..</param> /// <param name="BoxLength">The length of the box, in metres. See - http-&amp;#x2F;&amp;#x2F;www.bclaws.ca&amp;#x2F;EPLibraries&amp;#x2F;bclaws_new&amp;#x2F;document&amp;#x2F;ID&amp;#x2F;freeside&amp;#x2F;30_7, appendix B.</param> /// <param name="BoxWidth">The width of the box, in metres. See - http-&amp;#x2F;&amp;#x2F;www.bclaws.ca&amp;#x2F;EPLibraries&amp;#x2F;bclaws_new&amp;#x2F;document&amp;#x2F;ID&amp;#x2F;freeside&amp;#x2F;30_7, appendix B.</param> /// <param name="BoxHeight">The height of the box, in metres. See- http-&amp;#x2F;&amp;#x2F;www.bclaws.ca&amp;#x2F;EPLibraries&amp;#x2F;bclaws_new&amp;#x2F;document&amp;#x2F;ID&amp;#x2F;freeside&amp;#x2F;30_7, appendix B.</param> /// <param name="BoxCapacity">The capacity of the box..</param> /// <param name="TrailerBoxLength">The length of the trailer box, in metres. See www.bclaws.ca&amp;#x2F;EPLibraries&amp;#x2F;bclaws_new&amp;#x2F;document&amp;#x2F;ID&amp;#x2F;freeside&amp;#x2F;30_7, appendix B.</param> /// <param name="TrailerBoxWidth">The width of the trailer box, in metres. See www.bclaws.ca&amp;#x2F;EPLibraries&amp;#x2F;bclaws_new&amp;#x2F;document&amp;#x2F;ID&amp;#x2F;freeside&amp;#x2F;30_7, appendix B.</param> /// <param name="TrailerBoxHeight">The height of the trailer box, in metres. See www.bclaws.ca&amp;#x2F;EPLibraries&amp;#x2F;bclaws_new&amp;#x2F;document&amp;#x2F;ID&amp;#x2F;freeside&amp;#x2F;30_7, appendix B.</param> /// <param name="TrailerBoxCapacity">The capacity of the trailer box..</param> public DumpTruck(int Id, bool? IsSingleAxle = null, bool? IsTandemAxle = null, bool? IsTridem = null, bool? HasPUP = null, bool? HasBellyDump = null, bool? HasRockBox = null, bool? HasHiliftGate = null, bool? IsWaterTruck = null, bool? HasSealcoatHitch = null, string RearAxleSpacing = null, string FrontTireSize = null, string FrontTireUOM = null, string FrontAxleCapacity = null, string RearAxleCapacity = null, string LegalLoad = null, string LegalCapacity = null, string LegalPUPTareWeight = null, string LicencedGVW = null, string LicencedGVWUOM = null, string LicencedTareWeight = null, string LicencedPUPTareWeight = null, string LicencedLoad = null, string LicencedCapacity = null, string BoxLength = null, string BoxWidth = null, string BoxHeight = null, string BoxCapacity = null, string TrailerBoxLength = null, string TrailerBoxWidth = null, string TrailerBoxHeight = null, string TrailerBoxCapacity = null) { this.Id = Id; this.IsSingleAxle = IsSingleAxle; this.IsTandemAxle = IsTandemAxle; this.IsTridem = IsTridem; this.HasPUP = HasPUP; this.HasBellyDump = HasBellyDump; this.HasRockBox = HasRockBox; this.HasHiliftGate = HasHiliftGate; this.IsWaterTruck = IsWaterTruck; this.HasSealcoatHitch = HasSealcoatHitch; this.RearAxleSpacing = RearAxleSpacing; this.FrontTireSize = FrontTireSize; this.FrontTireUOM = FrontTireUOM; this.FrontAxleCapacity = FrontAxleCapacity; this.RearAxleCapacity = RearAxleCapacity; this.LegalLoad = LegalLoad; this.LegalCapacity = LegalCapacity; this.LegalPUPTareWeight = LegalPUPTareWeight; this.LicencedGVW = LicencedGVW; this.LicencedGVWUOM = LicencedGVWUOM; this.LicencedTareWeight = LicencedTareWeight; this.LicencedPUPTareWeight = LicencedPUPTareWeight; this.LicencedLoad = LicencedLoad; this.LicencedCapacity = LicencedCapacity; this.BoxLength = BoxLength; this.BoxWidth = BoxWidth; this.BoxHeight = BoxHeight; this.BoxCapacity = BoxCapacity; this.TrailerBoxLength = TrailerBoxLength; this.TrailerBoxWidth = TrailerBoxWidth; this.TrailerBoxHeight = TrailerBoxHeight; this.TrailerBoxCapacity = TrailerBoxCapacity; } /// <summary> /// A system-generated unique identifier for a DumpTruck /// </summary> /// <value>A system-generated unique identifier for a DumpTruck</value> [MetaDataExtension (Description = "A system-generated unique identifier for a DumpTruck")] public int Id { get; set; } /// <summary> /// True if the vehicle has a single axle. Can be false or null. /// </summary> /// <value>True if the vehicle has a single axle. Can be false or null.</value> [MetaDataExtension (Description = "True if the vehicle has a single axle. Can be false or null.")] public bool? IsSingleAxle { get; set; } /// <summary> /// True if the vehicle has a tandem axle. Can be false or null. /// </summary> /// <value>True if the vehicle has a tandem axle. Can be false or null.</value> [MetaDataExtension (Description = "True if the vehicle has a tandem axle. Can be false or null.")] public bool? IsTandemAxle { get; set; } /// <summary> /// True if the Dump Truck is a tridem - a three axle dump truck. Can be false or null. /// </summary> /// <value>True if the Dump Truck is a tridem - a three axle dump truck. Can be false or null.</value> [MetaDataExtension (Description = "True if the Dump Truck is a tridem - a three axle dump truck. Can be false or null.")] public bool? IsTridem { get; set; } /// <summary> /// True if the Dump Truck has a PUP trailer - a trailer with it&#39;s own hydraulic unloading system. Can be false or null. /// </summary> /// <value>True if the Dump Truck has a PUP trailer - a trailer with it&#39;s own hydraulic unloading system. Can be false or null.</value> [MetaDataExtension (Description = "True if the Dump Truck has a PUP trailer - a trailer with it&#39;s own hydraulic unloading system. Can be false or null.")] public bool? HasPUP { get; set; } /// <summary> /// True if the Dump Truck has a belly dump capability. Can be false or null. /// </summary> /// <value>True if the Dump Truck has a belly dump capability. Can be false or null.</value> [MetaDataExtension (Description = "True if the Dump Truck has a belly dump capability. Can be false or null.")] public bool? HasBellyDump { get; set; } /// <summary> /// True if the Dump Truck has a rock box. Can be false or null. /// </summary> /// <value>True if the Dump Truck has a rock box. Can be false or null.</value> [MetaDataExtension (Description = "True if the Dump Truck has a rock box. Can be false or null.")] public bool? HasRockBox { get; set; } /// <summary> /// True if the Dump Truck has a high lift gate vs. a traditional gate. Can be false or null. /// </summary> /// <value>True if the Dump Truck has a high lift gate vs. a traditional gate. Can be false or null.</value> [MetaDataExtension (Description = "True if the Dump Truck has a high lift gate vs. a traditional gate. Can be false or null.")] public bool? HasHiliftGate { get; set; } /// <summary> /// True if the Dump Truck is a Water Truck. Can be false or null. /// </summary> /// <value>True if the Dump Truck is a Water Truck. Can be false or null.</value> [MetaDataExtension (Description = "True if the Dump Truck is a Water Truck. Can be false or null.")] public bool? IsWaterTruck { get; set; } /// <summary> /// True if the Dump Truck has a hitch for using sealcoat trailers. Can be false or null. /// </summary> /// <value>True if the Dump Truck has a hitch for using sealcoat trailers. Can be false or null.</value> [MetaDataExtension (Description = "True if the Dump Truck has a hitch for using sealcoat trailers. Can be false or null.")] public bool? HasSealcoatHitch { get; set; } /// <summary> /// The spacing of the rear axles, if applicable. Usually in metres. /// </summary> /// <value>The spacing of the rear axles, if applicable. Usually in metres.</value> [MetaDataExtension (Description = "The spacing of the rear axles, if applicable. Usually in metres.")] [MaxLength(150)] public string RearAxleSpacing { get; set; } /// <summary> /// The size of of the Front Tires of the Dump Truck. /// </summary> /// <value>The size of of the Front Tires of the Dump Truck.</value> [MetaDataExtension (Description = "The size of of the Front Tires of the Dump Truck.")] [MaxLength(150)] public string FrontTireSize { get; set; } /// <summary> /// The Unit of Measure of the Front Tire Size. /// </summary> /// <value>The Unit of Measure of the Front Tire Size.</value> [MetaDataExtension (Description = "The Unit of Measure of the Front Tire Size.")] [MaxLength(150)] public string FrontTireUOM { get; set; } /// <summary> /// The rated capacity of the Front Axle. /// </summary> /// <value>The rated capacity of the Front Axle.</value> [MetaDataExtension (Description = "The rated capacity of the Front Axle.")] [MaxLength(150)] public string FrontAxleCapacity { get; set; } /// <summary> /// The rated capacity of the Rear Axle. /// </summary> /// <value>The rated capacity of the Rear Axle.</value> [MetaDataExtension (Description = "The rated capacity of the Rear Axle.")] [MaxLength(150)] public string RearAxleCapacity { get; set; } /// <summary> /// The legal load of the vehicle in kg. /// </summary> /// <value>The legal load of the vehicle in kg.</value> [MetaDataExtension (Description = "The legal load of the vehicle in kg.")] [MaxLength(150)] public string LegalLoad { get; set; } /// <summary> /// The legal capacity of the dump truck. /// </summary> /// <value>The legal capacity of the dump truck.</value> [MetaDataExtension (Description = "The legal capacity of the dump truck.")] [MaxLength(150)] public string LegalCapacity { get; set; } /// <summary> /// The legal Tare Weight (weight when unloaded) of the PUP trailer. /// </summary> /// <value>The legal Tare Weight (weight when unloaded) of the PUP trailer.</value> [MetaDataExtension (Description = "The legal Tare Weight (weight when unloaded) of the PUP trailer.")] [MaxLength(150)] public string LegalPUPTareWeight { get; set; } /// <summary> /// The Gross Vehicle Weight for which the vehicle is licensed. GVW includes the vehicle&#39;s chassis, body, engine, engine fluids, fuel, accessories, driver, passengers and cargo but excluding that of any trailers. /// </summary> /// <value>The Gross Vehicle Weight for which the vehicle is licensed. GVW includes the vehicle&#39;s chassis, body, engine, engine fluids, fuel, accessories, driver, passengers and cargo but excluding that of any trailers.</value> [MetaDataExtension (Description = "The Gross Vehicle Weight for which the vehicle is licensed. GVW includes the vehicle&#39;s chassis, body, engine, engine fluids, fuel, accessories, driver, passengers and cargo but excluding that of any trailers.")] [MaxLength(150)] public string LicencedGVW { get; set; } /// <summary> /// The Unit of Measure (UOM) of the licenced GVW. /// </summary> /// <value>The Unit of Measure (UOM) of the licenced GVW.</value> [MetaDataExtension (Description = "The Unit of Measure (UOM) of the licenced GVW.")] [MaxLength(150)] public string LicencedGVWUOM { get; set; } /// <summary> /// The licenced Tare Weight (weight when unloaded) of the vehicle. /// </summary> /// <value>The licenced Tare Weight (weight when unloaded) of the vehicle.</value> [MetaDataExtension (Description = "The licenced Tare Weight (weight when unloaded) of the vehicle.")] [MaxLength(150)] public string LicencedTareWeight { get; set; } /// <summary> /// The licenced Tare Weight (weight when unloaded) of the PUP trailer. /// </summary> /// <value>The licenced Tare Weight (weight when unloaded) of the PUP trailer.</value> [MetaDataExtension (Description = "The licenced Tare Weight (weight when unloaded) of the PUP trailer.")] [MaxLength(150)] public string LicencedPUPTareWeight { get; set; } /// <summary> /// The licenced maximum load of the vehicle in kg. /// </summary> /// <value>The licenced maximum load of the vehicle in kg.</value> [MetaDataExtension (Description = "The licenced maximum load of the vehicle in kg.")] [MaxLength(150)] public string LicencedLoad { get; set; } /// <summary> /// The licenced maximum capacity of the vehicle. /// </summary> /// <value>The licenced maximum capacity of the vehicle.</value> [MetaDataExtension (Description = "The licenced maximum capacity of the vehicle.")] [MaxLength(150)] public string LicencedCapacity { get; set; } /// <summary> /// The length of the box, in metres. See - http-&#x2F;&#x2F;www.bclaws.ca&#x2F;EPLibraries&#x2F;bclaws_new&#x2F;document&#x2F;ID&#x2F;freeside&#x2F;30_7, appendix B /// </summary> /// <value>The length of the box, in metres. See - http-&#x2F;&#x2F;www.bclaws.ca&#x2F;EPLibraries&#x2F;bclaws_new&#x2F;document&#x2F;ID&#x2F;freeside&#x2F;30_7, appendix B</value> [MetaDataExtension (Description = "The length of the box, in metres. See - http-&#x2F;&#x2F;www.bclaws.ca&#x2F;EPLibraries&#x2F;bclaws_new&#x2F;document&#x2F;ID&#x2F;freeside&#x2F;30_7, appendix B")] [MaxLength(150)] public string BoxLength { get; set; } /// <summary> /// The width of the box, in metres. See - http-&#x2F;&#x2F;www.bclaws.ca&#x2F;EPLibraries&#x2F;bclaws_new&#x2F;document&#x2F;ID&#x2F;freeside&#x2F;30_7, appendix B /// </summary> /// <value>The width of the box, in metres. See - http-&#x2F;&#x2F;www.bclaws.ca&#x2F;EPLibraries&#x2F;bclaws_new&#x2F;document&#x2F;ID&#x2F;freeside&#x2F;30_7, appendix B</value> [MetaDataExtension (Description = "The width of the box, in metres. See - http-&#x2F;&#x2F;www.bclaws.ca&#x2F;EPLibraries&#x2F;bclaws_new&#x2F;document&#x2F;ID&#x2F;freeside&#x2F;30_7, appendix B")] [MaxLength(150)] public string BoxWidth { get; set; } /// <summary> /// The height of the box, in metres. See- http-&#x2F;&#x2F;www.bclaws.ca&#x2F;EPLibraries&#x2F;bclaws_new&#x2F;document&#x2F;ID&#x2F;freeside&#x2F;30_7, appendix B /// </summary> /// <value>The height of the box, in metres. See- http-&#x2F;&#x2F;www.bclaws.ca&#x2F;EPLibraries&#x2F;bclaws_new&#x2F;document&#x2F;ID&#x2F;freeside&#x2F;30_7, appendix B</value> [MetaDataExtension (Description = "The height of the box, in metres. See- http-&#x2F;&#x2F;www.bclaws.ca&#x2F;EPLibraries&#x2F;bclaws_new&#x2F;document&#x2F;ID&#x2F;freeside&#x2F;30_7, appendix B")] [MaxLength(150)] public string BoxHeight { get; set; } /// <summary> /// The capacity of the box. /// </summary> /// <value>The capacity of the box.</value> [MetaDataExtension (Description = "The capacity of the box.")] [MaxLength(150)] public string BoxCapacity { get; set; } /// <summary> /// The length of the trailer box, in metres. See www.bclaws.ca&#x2F;EPLibraries&#x2F;bclaws_new&#x2F;document&#x2F;ID&#x2F;freeside&#x2F;30_7, appendix B /// </summary> /// <value>The length of the trailer box, in metres. See www.bclaws.ca&#x2F;EPLibraries&#x2F;bclaws_new&#x2F;document&#x2F;ID&#x2F;freeside&#x2F;30_7, appendix B</value> [MetaDataExtension (Description = "The length of the trailer box, in metres. See www.bclaws.ca&#x2F;EPLibraries&#x2F;bclaws_new&#x2F;document&#x2F;ID&#x2F;freeside&#x2F;30_7, appendix B")] [MaxLength(150)] public string TrailerBoxLength { get; set; } /// <summary> /// The width of the trailer box, in metres. See www.bclaws.ca&#x2F;EPLibraries&#x2F;bclaws_new&#x2F;document&#x2F;ID&#x2F;freeside&#x2F;30_7, appendix B /// </summary> /// <value>The width of the trailer box, in metres. See www.bclaws.ca&#x2F;EPLibraries&#x2F;bclaws_new&#x2F;document&#x2F;ID&#x2F;freeside&#x2F;30_7, appendix B</value> [MetaDataExtension (Description = "The width of the trailer box, in metres. See www.bclaws.ca&#x2F;EPLibraries&#x2F;bclaws_new&#x2F;document&#x2F;ID&#x2F;freeside&#x2F;30_7, appendix B")] [MaxLength(150)] public string TrailerBoxWidth { get; set; } /// <summary> /// The height of the trailer box, in metres. See www.bclaws.ca&#x2F;EPLibraries&#x2F;bclaws_new&#x2F;document&#x2F;ID&#x2F;freeside&#x2F;30_7, appendix B /// </summary> /// <value>The height of the trailer box, in metres. See www.bclaws.ca&#x2F;EPLibraries&#x2F;bclaws_new&#x2F;document&#x2F;ID&#x2F;freeside&#x2F;30_7, appendix B</value> [MetaDataExtension (Description = "The height of the trailer box, in metres. See www.bclaws.ca&#x2F;EPLibraries&#x2F;bclaws_new&#x2F;document&#x2F;ID&#x2F;freeside&#x2F;30_7, appendix B")] [MaxLength(150)] public string TrailerBoxHeight { get; set; } /// <summary> /// The capacity of the trailer box. /// </summary> /// <value>The capacity of the trailer box.</value> [MetaDataExtension (Description = "The capacity of the trailer box.")] [MaxLength(150)] public string TrailerBoxCapacity { 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 DumpTruck {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" IsSingleAxle: ").Append(IsSingleAxle).Append("\n"); sb.Append(" IsTandemAxle: ").Append(IsTandemAxle).Append("\n"); sb.Append(" IsTridem: ").Append(IsTridem).Append("\n"); sb.Append(" HasPUP: ").Append(HasPUP).Append("\n"); sb.Append(" HasBellyDump: ").Append(HasBellyDump).Append("\n"); sb.Append(" HasRockBox: ").Append(HasRockBox).Append("\n"); sb.Append(" HasHiliftGate: ").Append(HasHiliftGate).Append("\n"); sb.Append(" IsWaterTruck: ").Append(IsWaterTruck).Append("\n"); sb.Append(" HasSealcoatHitch: ").Append(HasSealcoatHitch).Append("\n"); sb.Append(" RearAxleSpacing: ").Append(RearAxleSpacing).Append("\n"); sb.Append(" FrontTireSize: ").Append(FrontTireSize).Append("\n"); sb.Append(" FrontTireUOM: ").Append(FrontTireUOM).Append("\n"); sb.Append(" FrontAxleCapacity: ").Append(FrontAxleCapacity).Append("\n"); sb.Append(" RearAxleCapacity: ").Append(RearAxleCapacity).Append("\n"); sb.Append(" LegalLoad: ").Append(LegalLoad).Append("\n"); sb.Append(" LegalCapacity: ").Append(LegalCapacity).Append("\n"); sb.Append(" LegalPUPTareWeight: ").Append(LegalPUPTareWeight).Append("\n"); sb.Append(" LicencedGVW: ").Append(LicencedGVW).Append("\n"); sb.Append(" LicencedGVWUOM: ").Append(LicencedGVWUOM).Append("\n"); sb.Append(" LicencedTareWeight: ").Append(LicencedTareWeight).Append("\n"); sb.Append(" LicencedPUPTareWeight: ").Append(LicencedPUPTareWeight).Append("\n"); sb.Append(" LicencedLoad: ").Append(LicencedLoad).Append("\n"); sb.Append(" LicencedCapacity: ").Append(LicencedCapacity).Append("\n"); sb.Append(" BoxLength: ").Append(BoxLength).Append("\n"); sb.Append(" BoxWidth: ").Append(BoxWidth).Append("\n"); sb.Append(" BoxHeight: ").Append(BoxHeight).Append("\n"); sb.Append(" BoxCapacity: ").Append(BoxCapacity).Append("\n"); sb.Append(" TrailerBoxLength: ").Append(TrailerBoxLength).Append("\n"); sb.Append(" TrailerBoxWidth: ").Append(TrailerBoxWidth).Append("\n"); sb.Append(" TrailerBoxHeight: ").Append(TrailerBoxHeight).Append("\n"); sb.Append(" TrailerBoxCapacity: ").Append(TrailerBoxCapacity).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) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((DumpTruck)obj); } /// <summary> /// Returns true if DumpTruck instances are equal /// </summary> /// <param name="other">Instance of DumpTruck to be compared</param> /// <returns>Boolean</returns> public bool Equals(DumpTruck other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( this.Id == other.Id || this.Id.Equals(other.Id) ) && ( this.IsSingleAxle == other.IsSingleAxle || this.IsSingleAxle != null && this.IsSingleAxle.Equals(other.IsSingleAxle) ) && ( this.IsTandemAxle == other.IsTandemAxle || this.IsTandemAxle != null && this.IsTandemAxle.Equals(other.IsTandemAxle) ) && ( this.IsTridem == other.IsTridem || this.IsTridem != null && this.IsTridem.Equals(other.IsTridem) ) && ( this.HasPUP == other.HasPUP || this.HasPUP != null && this.HasPUP.Equals(other.HasPUP) ) && ( this.HasBellyDump == other.HasBellyDump || this.HasBellyDump != null && this.HasBellyDump.Equals(other.HasBellyDump) ) && ( this.HasRockBox == other.HasRockBox || this.HasRockBox != null && this.HasRockBox.Equals(other.HasRockBox) ) && ( this.HasHiliftGate == other.HasHiliftGate || this.HasHiliftGate != null && this.HasHiliftGate.Equals(other.HasHiliftGate) ) && ( this.IsWaterTruck == other.IsWaterTruck || this.IsWaterTruck != null && this.IsWaterTruck.Equals(other.IsWaterTruck) ) && ( this.HasSealcoatHitch == other.HasSealcoatHitch || this.HasSealcoatHitch != null && this.HasSealcoatHitch.Equals(other.HasSealcoatHitch) ) && ( this.RearAxleSpacing == other.RearAxleSpacing || this.RearAxleSpacing != null && this.RearAxleSpacing.Equals(other.RearAxleSpacing) ) && ( this.FrontTireSize == other.FrontTireSize || this.FrontTireSize != null && this.FrontTireSize.Equals(other.FrontTireSize) ) && ( this.FrontTireUOM == other.FrontTireUOM || this.FrontTireUOM != null && this.FrontTireUOM.Equals(other.FrontTireUOM) ) && ( this.FrontAxleCapacity == other.FrontAxleCapacity || this.FrontAxleCapacity != null && this.FrontAxleCapacity.Equals(other.FrontAxleCapacity) ) && ( this.RearAxleCapacity == other.RearAxleCapacity || this.RearAxleCapacity != null && this.RearAxleCapacity.Equals(other.RearAxleCapacity) ) && ( this.LegalLoad == other.LegalLoad || this.LegalLoad != null && this.LegalLoad.Equals(other.LegalLoad) ) && ( this.LegalCapacity == other.LegalCapacity || this.LegalCapacity != null && this.LegalCapacity.Equals(other.LegalCapacity) ) && ( this.LegalPUPTareWeight == other.LegalPUPTareWeight || this.LegalPUPTareWeight != null && this.LegalPUPTareWeight.Equals(other.LegalPUPTareWeight) ) && ( this.LicencedGVW == other.LicencedGVW || this.LicencedGVW != null && this.LicencedGVW.Equals(other.LicencedGVW) ) && ( this.LicencedGVWUOM == other.LicencedGVWUOM || this.LicencedGVWUOM != null && this.LicencedGVWUOM.Equals(other.LicencedGVWUOM) ) && ( this.LicencedTareWeight == other.LicencedTareWeight || this.LicencedTareWeight != null && this.LicencedTareWeight.Equals(other.LicencedTareWeight) ) && ( this.LicencedPUPTareWeight == other.LicencedPUPTareWeight || this.LicencedPUPTareWeight != null && this.LicencedPUPTareWeight.Equals(other.LicencedPUPTareWeight) ) && ( this.LicencedLoad == other.LicencedLoad || this.LicencedLoad != null && this.LicencedLoad.Equals(other.LicencedLoad) ) && ( this.LicencedCapacity == other.LicencedCapacity || this.LicencedCapacity != null && this.LicencedCapacity.Equals(other.LicencedCapacity) ) && ( this.BoxLength == other.BoxLength || this.BoxLength != null && this.BoxLength.Equals(other.BoxLength) ) && ( this.BoxWidth == other.BoxWidth || this.BoxWidth != null && this.BoxWidth.Equals(other.BoxWidth) ) && ( this.BoxHeight == other.BoxHeight || this.BoxHeight != null && this.BoxHeight.Equals(other.BoxHeight) ) && ( this.BoxCapacity == other.BoxCapacity || this.BoxCapacity != null && this.BoxCapacity.Equals(other.BoxCapacity) ) && ( this.TrailerBoxLength == other.TrailerBoxLength || this.TrailerBoxLength != null && this.TrailerBoxLength.Equals(other.TrailerBoxLength) ) && ( this.TrailerBoxWidth == other.TrailerBoxWidth || this.TrailerBoxWidth != null && this.TrailerBoxWidth.Equals(other.TrailerBoxWidth) ) && ( this.TrailerBoxHeight == other.TrailerBoxHeight || this.TrailerBoxHeight != null && this.TrailerBoxHeight.Equals(other.TrailerBoxHeight) ) && ( this.TrailerBoxCapacity == other.TrailerBoxCapacity || this.TrailerBoxCapacity != null && this.TrailerBoxCapacity.Equals(other.TrailerBoxCapacity) ); } /// <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 hash = hash * 59 + this.Id.GetHashCode(); if (this.IsSingleAxle != null) { hash = hash * 59 + this.IsSingleAxle.GetHashCode(); } if (this.IsTandemAxle != null) { hash = hash * 59 + this.IsTandemAxle.GetHashCode(); } if (this.IsTridem != null) { hash = hash * 59 + this.IsTridem.GetHashCode(); } if (this.HasPUP != null) { hash = hash * 59 + this.HasPUP.GetHashCode(); } if (this.HasBellyDump != null) { hash = hash * 59 + this.HasBellyDump.GetHashCode(); } if (this.HasRockBox != null) { hash = hash * 59 + this.HasRockBox.GetHashCode(); } if (this.HasHiliftGate != null) { hash = hash * 59 + this.HasHiliftGate.GetHashCode(); } if (this.IsWaterTruck != null) { hash = hash * 59 + this.IsWaterTruck.GetHashCode(); } if (this.HasSealcoatHitch != null) { hash = hash * 59 + this.HasSealcoatHitch.GetHashCode(); } if (this.RearAxleSpacing != null) { hash = hash * 59 + this.RearAxleSpacing.GetHashCode(); } if (this.FrontTireSize != null) { hash = hash * 59 + this.FrontTireSize.GetHashCode(); } if (this.FrontTireUOM != null) { hash = hash * 59 + this.FrontTireUOM.GetHashCode(); } if (this.FrontAxleCapacity != null) { hash = hash * 59 + this.FrontAxleCapacity.GetHashCode(); } if (this.RearAxleCapacity != null) { hash = hash * 59 + this.RearAxleCapacity.GetHashCode(); } if (this.LegalLoad != null) { hash = hash * 59 + this.LegalLoad.GetHashCode(); } if (this.LegalCapacity != null) { hash = hash * 59 + this.LegalCapacity.GetHashCode(); } if (this.LegalPUPTareWeight != null) { hash = hash * 59 + this.LegalPUPTareWeight.GetHashCode(); } if (this.LicencedGVW != null) { hash = hash * 59 + this.LicencedGVW.GetHashCode(); } if (this.LicencedGVWUOM != null) { hash = hash * 59 + this.LicencedGVWUOM.GetHashCode(); } if (this.LicencedTareWeight != null) { hash = hash * 59 + this.LicencedTareWeight.GetHashCode(); } if (this.LicencedPUPTareWeight != null) { hash = hash * 59 + this.LicencedPUPTareWeight.GetHashCode(); } if (this.LicencedLoad != null) { hash = hash * 59 + this.LicencedLoad.GetHashCode(); } if (this.LicencedCapacity != null) { hash = hash * 59 + this.LicencedCapacity.GetHashCode(); } if (this.BoxLength != null) { hash = hash * 59 + this.BoxLength.GetHashCode(); } if (this.BoxWidth != null) { hash = hash * 59 + this.BoxWidth.GetHashCode(); } if (this.BoxHeight != null) { hash = hash * 59 + this.BoxHeight.GetHashCode(); } if (this.BoxCapacity != null) { hash = hash * 59 + this.BoxCapacity.GetHashCode(); } if (this.TrailerBoxLength != null) { hash = hash * 59 + this.TrailerBoxLength.GetHashCode(); } if (this.TrailerBoxWidth != null) { hash = hash * 59 + this.TrailerBoxWidth.GetHashCode(); } if (this.TrailerBoxHeight != null) { hash = hash * 59 + this.TrailerBoxHeight.GetHashCode(); } if (this.TrailerBoxCapacity != null) { hash = hash * 59 + this.TrailerBoxCapacity.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(DumpTruck left, DumpTruck right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(DumpTruck left, DumpTruck right) { return !Equals(left, right); } #endregion Operators } }
// // AppleDeviceTrackInfo.cs // // Author: // Alan McGovern <amcgovern@novell.com> // // Copyright (c) 2010 Moonlight Team // // 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 Banshee.Base; using Banshee.Streaming; using Banshee.Collection; using Banshee.Collection.Database; using Hyena; namespace Banshee.Dap.AppleDevice { public class AppleDeviceTrackInfo : DatabaseTrackInfo { internal GPod.Track IpodTrack { get; set; } // Used for podcasts only //private string description; public AppleDeviceTrackInfo (GPod.Track track) { IpodTrack = track; LoadFromIpodTrack (); CanSaveToDatabase = true; } public AppleDeviceTrackInfo (TrackInfo track) { if (track is AppleDeviceTrackInfo) { IpodTrack = ((AppleDeviceTrackInfo)track).IpodTrack; LoadFromIpodTrack (); } else { IsCompilation = track.IsCompilation ; AlbumArtist = track.AlbumArtist; AlbumTitle = track.AlbumTitle; ArtistName = track.ArtistName; BitRate = track.BitRate; SampleRate = track.SampleRate; Bpm = track.Bpm; Comment = track.Comment; Composer = track.Composer; Conductor = track.Conductor; Copyright = track.Copyright; DateAdded = track.DateAdded; DiscCount = track.DiscCount; DiscNumber = track.DiscNumber; Duration = track.Duration; FileSize = track.FileSize; Genre = track.Genre; Grouping = track.Grouping; LastPlayed = track.LastPlayed; LastSkipped = track.LastSkipped; PlayCount = track.PlayCount; Rating = track.Rating; ReleaseDate = track.ReleaseDate; SkipCount = track.SkipCount; TrackCount = track.TrackCount; TrackNumber = track.TrackNumber; TrackTitle = track.TrackTitle; Year = track.Year; MediaAttributes = track.MediaAttributes; var podcast_info = track.ExternalObject as IPodcastInfo; if (podcast_info != null) { //description = podcast_info.Description; ReleaseDate = podcast_info.ReleaseDate; } } CanSaveToDatabase = true; } private void LoadFromIpodTrack () { var track = IpodTrack; try { Uri = new SafeUri (System.IO.Path.Combine (track.ITDB.Mountpoint, track.IpodPath.Replace (":", System.IO.Path.DirectorySeparatorChar.ToString ()).Substring (1))); } catch (Exception ex) { Log.Exception (ex); Uri = null; } ExternalId = (long) track.DBID; IsCompilation = track.Compilation; AlbumArtist = track.AlbumArtist; AlbumTitle = String.IsNullOrEmpty (track.Album) ? null : track.Album; ArtistName = String.IsNullOrEmpty (track.Artist) ? null : track.Artist; BitRate = track.Bitrate; SampleRate = track.Samplerate; Bpm = (int)track.BPM; Comment = track.Comment; Composer = track.Composer; DateAdded = track.TimeAdded; DiscCount = track.CDs; DiscNumber = track.CDNumber; Duration = TimeSpan.FromMilliseconds (track.TrackLength); FileSize = track.Size; Genre = String.IsNullOrEmpty (track.Genre) ? null : track.Genre; Grouping = track.Grouping; LastPlayed = track.TimePlayed; PlayCount = (int) track.PlayCount; TrackCount = track.Tracks; TrackNumber = track.TrackNumber; TrackTitle = String.IsNullOrEmpty (track.Title) ? null : track.Title; Year = track.Year; //description = track.Description; ReleaseDate = track.TimeReleased; rating = track.Rating > 5 ? 0 : (int) track.Rating; if (track.DRMUserID > 0) { PlaybackError = StreamPlaybackError.Drm; } MediaAttributes = TrackMediaAttributes.AudioStream | TrackMediaAttributes.Music; // switch (track.Type) { // case IPod.MediaType.Audio: // MediaAttributes |= TrackMediaAttributes.Music; // break; // case IPod.MediaType.AudioVideo: // case IPod.MediaType.Video: // MediaAttributes |= TrackMediaAttributes.VideoStream; // break; // case IPod.MediaType.MusicVideo: // MediaAttributes |= TrackMediaAttributes.Music | TrackMediaAttributes.VideoStream; // break; // case IPod.MediaType.Movie: // MediaAttributes |= TrackMediaAttributes.VideoStream | TrackMediaAttributes.Movie; // break; // case IPod.MediaType.TVShow: // MediaAttributes |= TrackMediaAttributes.VideoStream | TrackMediaAttributes.TvShow; // break; // case IPod.MediaType.VideoPodcast: // MediaAttributes |= TrackMediaAttributes.VideoStream | TrackMediaAttributes.Podcast; // break; // case IPod.MediaType.Podcast: // MediaAttributes |= TrackMediaAttributes.Podcast; // // FIXME: persist URL on the track (track.PodcastUrl) // break; // case IPod.MediaType.Audiobook: // MediaAttributes |= TrackMediaAttributes.AudioBook; // break; // } } public void CommitToIpod (GPod.ITDB database) { bool addTrack = IpodTrack == null; if (IpodTrack == null) { IpodTrack = new GPod.Track (); } var track = IpodTrack; track.Compilation = IsCompilation; track.AlbumArtist = AlbumArtist; track.Bitrate = BitRate; track.Samplerate= (ushort)SampleRate; track.BPM = (short)Bpm; track.Comment = Comment; track.Composer = Composer; track.TimeAdded = DateAdded; track.CDs = DiscCount; track.CDNumber = DiscNumber; track.TrackLength = (int) Duration.TotalMilliseconds; track.Size = (int)FileSize; track.Grouping = Grouping; track.TimePlayed = LastPlayed; track.PlayCount = (uint) PlayCount; track.Tracks = TrackCount; track.TrackNumber = TrackNumber; track.Year = Year; track.TimeReleased = ReleaseDate; track.Album = AlbumTitle; track.Artist = ArtistName; track.Title = TrackTitle; track.Genre = Genre; switch (Rating) { case 1: case 2: case 3: case 4: case 5: track.Rating = (uint) rating; break; default: track.Rating = 0; break; } // if (HasAttribute (TrackMediaAttributes.Podcast)) { // track.DateReleased = ReleaseDate; // track.Description = description; // track.RememberPosition = true; // track.NotPlayedMark = track.PlayCount == 0; // } // // if (HasAttribute (TrackMediaAttributes.VideoStream)) { // if (HasAttribute (TrackMediaAttributes.Podcast)) { // track.Type = IPod.MediaType.VideoPodcast; // } else if (HasAttribute (TrackMediaAttributes.Music)) { // track.Type = IPod.MediaType.MusicVideo; // } else if (HasAttribute (TrackMediaAttributes.Movie)) { // track.Type = IPod.MediaType.Movie; // } else if (HasAttribute (TrackMediaAttributes.TvShow)) { // track.Type = IPod.MediaType.TVShow; // } else { // track.Type = IPod.MediaType.Video; // } // } else { // if (HasAttribute (TrackMediaAttributes.Podcast)) { // track.Type = IPod.MediaType.Podcast; // } else if (HasAttribute (TrackMediaAttributes.AudioBook)) { // track.Type = IPod.MediaType.Audiobook; // } else if (HasAttribute (TrackMediaAttributes.Music)) { // track.Type = IPod.MediaType.Audio; // } else { // track.Type = IPod.MediaType.Audio; // } // } track.MediaType = GPod.MediaType.Audio; if (addTrack) { track.Filetype = "MP3-file"; database.Tracks.Add (IpodTrack); database.MasterPlaylist.Tracks.Add (IpodTrack); database.CopyTrackToIPod (track, Uri.LocalPath); ExternalId = (long) IpodTrack.DBID; } // if (CoverArtSpec.CoverExists (ArtworkId)) { // SetIpodCoverArt (device, track, CoverArtSpec.GetPath (ArtworkId)); // } } // FIXME: No reason for this to use GdkPixbuf - the file is on disk already in // the artwork cache as a JPEG, so just shove the bytes from disk into the track public static void SetIpodCoverArt (GPod.Device device, GPod.Track track, string path) { // try { // Gdk.Pixbuf pixbuf = null; // foreach (IPod.ArtworkFormat format in device.LookupArtworkFormats (IPod.ArtworkUsage.Cover)) { // if (!track.HasCoverArt (format)) { // // Lazily load the pixbuf // if (pixbuf == null) { // pixbuf = new Gdk.Pixbuf (path); // } // // track.SetCoverArt (format, IPod.ArtworkHelpers.ToBytes (format, pixbuf)); // } // } // // if (pixbuf != null) { // pixbuf.Dispose (); // } // } catch (Exception e) { // Log.Exception (String.Format ("Failed to set cover art on iPod from {0}", path), e); // } } } }
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange // // Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using PdfSharp.Internal; #if GDI using System.Drawing; #endif #if WPF using System.Windows.Media; #endif #pragma warning disable 1591 #if !EDF_CORE namespace PdfSharp.Drawing #else namespace Edf.Drawing #endif { /// <summary> /// Represents a two-dimensional vector specified by x- and y-coordinates. /// </summary> [DebuggerDisplay("{DebuggerDisplay}")] [Serializable] [StructLayout(LayoutKind.Sequential)] public struct XVector : IFormattable { public XVector(double x, double y) { _x = x; _y = y; } public static bool operator ==(XVector vector1, XVector vector2) { // ReSharper disable CompareOfFloatsByEqualityOperator return vector1._x == vector2._x && vector1._y == vector2._y; // ReSharper restore CompareOfFloatsByEqualityOperator } public static bool operator !=(XVector vector1, XVector vector2) { // ReSharper disable CompareOfFloatsByEqualityOperator return vector1._x != vector2._x || vector1._y != vector2._y; // ReSharper restore CompareOfFloatsByEqualityOperator } public static bool Equals(XVector vector1, XVector vector2) { if (vector1.X.Equals(vector2.X)) return vector1.Y.Equals(vector2.Y); return false; } public override bool Equals(object o) { if (!(o is XVector)) return false; return Equals(this, (XVector)o); } public bool Equals(XVector value) { return Equals(this, value); } public override int GetHashCode() { // ReSharper disable NonReadonlyFieldInGetHashCode return _x.GetHashCode() ^ _y.GetHashCode(); // ReSharper restore NonReadonlyFieldInGetHashCode } public static XVector Parse(string source) { TokenizerHelper helper = new TokenizerHelper(source, CultureInfo.InvariantCulture); string str = helper.NextTokenRequired(); XVector vector = new XVector(Convert.ToDouble(str, CultureInfo.InvariantCulture), Convert.ToDouble(helper.NextTokenRequired(), CultureInfo.InvariantCulture)); helper.LastTokenRequired(); return vector; } public double X { get { return _x; } set { _x = value; } } double _x; public double Y { get { return _y; } set { _y = value; } } double _y; public override string ToString() { return ConvertToString(null, null); } public string ToString(IFormatProvider provider) { return ConvertToString(null, provider); } string IFormattable.ToString(string format, IFormatProvider provider) { return ConvertToString(format, provider); } internal string ConvertToString(string format, IFormatProvider provider) { const char numericListSeparator = ','; provider = provider ?? CultureInfo.InvariantCulture; // ReSharper disable once FormatStringProblem return string.Format(provider, "{1:" + format + "}{0}{2:" + format + "}", numericListSeparator, _x, _y); } public double Length { get { return Math.Sqrt(_x * _x + _y * _y); } } public double LengthSquared { get { return _x * _x + _y * _y; } } public void Normalize() { this = this / Math.Max(Math.Abs(_x), Math.Abs(_y)); this = this / Length; } public static double CrossProduct(XVector vector1, XVector vector2) { return vector1._x * vector2._y - vector1._y * vector2._x; } public static double AngleBetween(XVector vector1, XVector vector2) { double y = vector1._x * vector2._y - vector2._x * vector1._y; double x = vector1._x * vector2._x + vector1._y * vector2._y; return (Math.Atan2(y, x) * 57.295779513082323); } public static XVector operator -(XVector vector) { return new XVector(-vector._x, -vector._y); } public void Negate() { _x = -_x; _y = -_y; } public static XVector operator +(XVector vector1, XVector vector2) { return new XVector(vector1._x + vector2._x, vector1._y + vector2._y); } public static XVector Add(XVector vector1, XVector vector2) { return new XVector(vector1._x + vector2._x, vector1._y + vector2._y); } public static XVector operator -(XVector vector1, XVector vector2) { return new XVector(vector1._x - vector2._x, vector1._y - vector2._y); } public static XVector Subtract(XVector vector1, XVector vector2) { return new XVector(vector1._x - vector2._x, vector1._y - vector2._y); } public static XPoint operator +(XVector vector, XPoint point) { return new XPoint(point.X + vector._x, point.Y + vector._y); } public static XPoint Add(XVector vector, XPoint point) { return new XPoint(point.X + vector._x, point.Y + vector._y); } public static XVector operator *(XVector vector, double scalar) { return new XVector(vector._x * scalar, vector._y * scalar); } public static XVector Multiply(XVector vector, double scalar) { return new XVector(vector._x * scalar, vector._y * scalar); } public static XVector operator *(double scalar, XVector vector) { return new XVector(vector._x * scalar, vector._y * scalar); } public static XVector Multiply(double scalar, XVector vector) { return new XVector(vector._x * scalar, vector._y * scalar); } public static XVector operator /(XVector vector, double scalar) { return vector * (1.0 / scalar); } public static XVector Divide(XVector vector, double scalar) { return vector * (1.0 / scalar); } public static XVector operator *(XVector vector, XMatrix matrix) { return matrix.Transform(vector); } public static XVector Multiply(XVector vector, XMatrix matrix) { return matrix.Transform(vector); } public static double operator *(XVector vector1, XVector vector2) { return vector1._x * vector2._x + vector1._y * vector2._y; } public static double Multiply(XVector vector1, XVector vector2) { return vector1._x * vector2._x + vector1._y * vector2._y; } public static double Determinant(XVector vector1, XVector vector2) { return vector1._x * vector2._y - vector1._y * vector2._x; } public static explicit operator XSize(XVector vector) { return new XSize(Math.Abs(vector._x), Math.Abs(vector._y)); } public static explicit operator XPoint(XVector vector) { return new XPoint(vector._x, vector._y); } /// <summary> /// Gets the DebuggerDisplayAttribute text. /// </summary> /// <value>The debugger display.</value> // ReSharper disable UnusedMember.Local string DebuggerDisplay // ReSharper restore UnusedMember.Local { get { const string format = Config.SignificantFigures10; return string.Format(CultureInfo.InvariantCulture, "vector=({0:" + format + "}, {1:" + format + "})", _x, _y); } } } }
/*! Achordeon - MIT License Copyright (c) 2017 tiamatix / Wolf Robben 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.Globalization; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; namespace Achordeon.Common.Helpers { [Serializable] public class XmlFile : ICloneable, IComparable<XmlFile>, IComparable, ISerializable, IDisposable { public const string DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; private static CultureInfo _Culture = CultureInfo.InvariantCulture; private XElement m_CursorElement; public XDocument Document { get; private set; } public static void OverrideCultureSettings(CultureInfo ANewCulture) { _Culture = ANewCulture; } public static XmlFile CreateFromString(string AXmlString) { return new XmlFile(AXmlString, true); } public static XmlFile CreateFromFile(string AXmlFileName) { return new XmlFile(AXmlFileName); } public static XmlFile CreateFromXmlFile(XmlFile AOther) { return CreateFromString(AOther.GetXmlString(false)); } public static XmlFile CreateFromXmlDocument(XDocument ADoc) { return new XmlFile(ADoc); } public static XmlFile CreateFromXmlNode(XNode ANode) { return new XmlFile(ANode); } public static XmlFile CreateFromStream(Stream AStream) { using (var r = new StreamReader(AStream)) return new XmlFile(r.ReadToEnd(), true); } public static XmlFile CreateEmpty(string ADocumentElementName) { return new XmlFile(ADocumentElementName, "1.0"); //MLHIDE } private XmlFile(string ADocumenElementName, string ADocumentVersion = "1.0") { Document = new XDocument(); Document.Declaration = new XDeclaration(ADocumentVersion, "utf-8", "yes"); Document.Add(new XElement(ADocumenElementName)); } private XmlFile(XDocument ADoc) { Document = ADoc; } private XmlFile(XNode ANode) { Document = new XDocument(); using (var rdr = ANode.CreateReader()) Document.Add(XElement.Load(rdr)); } private XmlFile(XDocument ADoc, XElement ANewCursorElement) { Document = ADoc; m_CursorElement = ANewCursorElement; } private XmlFile(string AFileName) { Document = new XDocument(); Document.Add(XElement.Load(AFileName)); } private XmlFile(string AXmlString, bool ALoadFromXmlString) { Document = new XDocument(); if (ALoadFromXmlString) Document.Add(XElement.Parse(AXmlString, LoadOptions.PreserveWhitespace)); else throw new Exception("XmlString(string XmlString, bool LoadFromXmlString == false)"); } public XElement Root => Document.Root; public XElement CursorElement { get { if (m_CursorElement == null) ResetCursorToRoot(); return m_CursorElement; } } public string CursorElementName { get { var e = CursorElement; return e == null ? string.Empty : e.Name.LocalName; } } public string this[string ATagName] { get { return Get(ATagName); } set { Set(ATagName, value); } } public string this[string ATagName, string ADefaultValue] => Get(ATagName, ADefaultValue); public void ResetCursorToRoot() { m_CursorElement = Document.Root; } public void SetCursor(XElement AElement) { if (AElement.Document != Document) throw new XmlException("Cursor has to be set to a child element of the current file"); m_CursorElement = AElement; } public object Clone() { return CreateFromXmlFile(this); } public XmlFile CloneAtCursor() { if (CursorElement == null) throw new XmlException("Cursor node is null"); return CreateFromXmlNode(CursorElement); } public void Save(string AFileName) { Document.Save(AFileName); } public void Save(string AFileName, bool AIndend) { Save(AFileName, AIndend, null); } public void Save(string AFileName, bool AIndend, Encoding AEncoding) { if (!AIndend && AEncoding == null) Save(AFileName); else { using (var writer = new XmlTextWriter(AFileName, AEncoding)) { writer.Formatting = AIndend ? Formatting.Indented : Formatting.None; Document.Save(writer); } } } public XDocument GetDocument() { return Document; } public string GetXmlString() { return Document.ToString(SaveOptions.DisableFormatting); } public MemoryStream GetStream(bool AIndend) { return GetStream(AIndend, true); } public MemoryStream GetStream(bool AIndend, bool AIncludeDeclaration) { return GetStream(AIndend, Encoding.Default, AIncludeDeclaration); } public MemoryStream GetStream(bool AIndend, Encoding AEncoding, bool AIncludeDeclaration) { if (!AIndend) return new StringStream(GetXmlString()); var result = new MemoryStream(); var sets = new XmlWriterSettings(); sets.CloseOutput = false; sets.IndentChars = " "; sets.Indent = true; sets.OmitXmlDeclaration = !AIncludeDeclaration; sets.Encoding = AEncoding; using (var writer = XmlWriter.Create(result, sets)) Document.Save(writer); result.Seek(0, SeekOrigin.Begin); return result; } public string GetXmlString(bool AIndend) { return GetXmlString(AIndend, true); } public string GetXmlString(bool AIndend, bool AIncludeDeclaration) { return GetXmlString(AIndend, Encoding.Default, AIncludeDeclaration); } public string GetXmlString(bool AIndend, Encoding AEncoding, bool AIncludeDeclaration) { if (!AIndend && AIncludeDeclaration) return GetXmlString(); if (AIndend && !AIncludeDeclaration) return Document.ToString(SaveOptions.None); using (var ms = GetStream(true, AIncludeDeclaration)) return AEncoding.GetString(ms.ToArray()); } public int CompareTo(XmlFile AOther) { return String.Compare(GetXmlString(), AOther.GetXmlString(), StringComparison.Ordinal); } public int CompareTo(object AOther) { if (AOther is XmlFile) return CompareTo((XmlFile)AOther); if (AOther == null) return 1; throw new Exception("Can only compare XmlFile2 to XmlFile2"); } void ISerializable.GetObjectData(SerializationInfo AInfo, StreamingContext AContext) { AInfo.AddValue("xml", GetXmlString(false)); //MLHIDE } public XmlFile(SerializationInfo AInfo, StreamingContext AContext) { Document = new XDocument(); Document.Add(XElement.Parse((string) AInfo.GetValue("xml", typeof (string)), LoadOptions.PreserveWhitespace)); } public override string ToString() { return GetXmlString(true); } public void Dispose() { m_CursorElement = null; Document?.RemoveNodes(); Document = null; } public XmlFile SelectSingle(string ANodeName) { if (CursorElement == null) throw new XmlException("Cursor node is null"); if (string.IsNullOrEmpty(ANodeName)) return this; var NewCursor = CursorElement.XPathSelectElement(ANodeName); return NewCursor == null ? null : new XmlFile(Document, NewCursor); } public IEnumerable<XmlFile> SelectAll(string ANodeName = null) { if (CursorElement == null) throw new XmlException("Cursor node is null"); if (string.IsNullOrEmpty(ANodeName)) { foreach (var Element in CursorElement.Elements()) yield return new XmlFile(Document, Element); yield break; } foreach (var Element in CursorElement.XPathSelectElements(ANodeName)) yield return new XmlFile(Document, Element); } public bool HasValue(string ATag = null) { var Tag = SelectSingle(ATag); return !string.IsNullOrEmpty(Tag?.CursorElement.Value); } public string Get(string ATag = null, string ADefaultValue = "") { var Tag = SelectSingle(ATag); if (Tag != null) return Tag.CursorElement.InnerText(); return ADefaultValue; } public int GetI(string ATag = null, int ADefaultValue = 0) { var Tag = SelectSingle(ATag); if (Tag != null) return Convert.ToInt32(Tag.CursorElement.InnerText(), _Culture); return ADefaultValue; } public double GetF(string ATag = null, double ADefaultValue = 0.0) { var ele = SelectSingle(ATag); if (ele != null) return Convert.ToDouble(ele.CursorElement.InnerText(), _Culture); return ADefaultValue; } public float GetFs(string ATag = null, float ADefaultValue = 0.0f) { var Tag = SelectSingle(ATag); if (Tag != null) return Convert.ToSingle(Tag.CursorElement.InnerText(), _Culture); return ADefaultValue; } public DateTime GetDt(string ATag = null) { var Tag = SelectSingle(ATag); if (Tag != null) return DateTime.ParseExact(Tag.CursorElement.InnerText(), DATE_TIME_FORMAT, _Culture); return DateTime.MinValue; } public bool GetB(string ATag = null, bool ADefaultValue = false) { var Tag = SelectSingle(ATag); var Value = Tag?.CursorElement.InnerText(); if (!string.IsNullOrEmpty(Value)) { int i; if (char.IsNumber(Value, 0) && int.TryParse(Value, NumberStyles.Integer, _Culture, out i)) return i != 0; return Convert.ToBoolean(Tag.CursorElement.InnerText(), _Culture); } return ADefaultValue; } public T GetEnum<T>(string ATag = null, T ADefaultValue = default(T)) where T : struct, IConvertible { if (!typeof(T).IsEnum) throw new ArgumentException("GetEnum is only allowed for enum types"); var Value = Get(ATag); if (string.IsNullOrEmpty(Value)) return ADefaultValue; int i; if (int.TryParse(Value, NumberStyles.Integer, _Culture, out i)) { try { var Result = Convert.ChangeType(i, typeof(T)); if (Result != null) return (T)Result; } catch (Exception) { } } return (T)Enum.Parse(typeof(T), Value, true); } public Guid GetG(string ATag = null) { var ele = SelectSingle(ATag); if (ele != null) return new Guid(ele.CursorElement.InnerText()); return Guid.Empty; } public byte[] GetBytes(string ATag = null) { var s = Get(ATag); if (string.IsNullOrEmpty(s)) return null; return Convert.FromBase64String(s); } public XmlFile Add(string ATag) { if (CursorElement == null) throw new XmlException("Cursor node is null"); var NewCursor = new XElement(ATag); CursorElement.Add(NewCursor); return new XmlFile(Document, NewCursor); } public XComment AddComment(string AComment) { if (CursorElement == null) throw new XmlException("Cursor node is null"); var res = new XComment(AComment); CursorElement.Add(res); return res; } public void Delete(string ATag = null) { if (CursorElement == null) throw new XmlException("Cursor node is null"); var Element = !string.IsNullOrEmpty(ATag) ? CursorElement.XPathSelectElement(ATag) : CursorElement; if (Element != null) { if (Element == CursorElement) throw new XmlException("Cursor-Element must not be removed"); bool ContainesCursor = false; try { var XPath = Element.GetXPath(); var CursorXpath = CursorElement.GetXPath(); ContainesCursor = XPath.Contains(CursorXpath); } catch { } if (ContainesCursor) throw new XmlException("Cursor-Element must not be removed"); Element.Remove(); } } public void Set(string ATag, string AValue) { if (CursorElement == null) throw new XmlException("Cursor node is null"); CursorElement.SetElementValue(ATag, AValue); } public void Set(string ATag, int AValue) { Set(ATag, AValue.ToString(_Culture)); } public void Set(string ATag, bool AValue) { Set(ATag, AValue.ToString(_Culture)); } public void Set(string ATag, double AValue) { Set(ATag, AValue.ToString(_Culture)); } public void Set(string ATag, byte[] ABytes) { Set(ATag, Convert.ToBase64String(ABytes)); } public void Set(string ATag, Guid AValue) { Set(ATag, AValue.ToString()); } public void Set(string ATag, DateTime AValue) { Set(ATag, AValue.ToString(DATE_TIME_FORMAT, _Culture)); //MLHIDE } public void SetEnum<T>(string ATag, T AValue) where T : struct, IConvertible { if (!typeof(T).IsEnum) throw new ArgumentException("AddEnum can only handle enum types"); Set(ATag, AValue.ToString(_Culture)); } public void Set(string AValue) { if (CursorElement == null) throw new XmlException("Cursor node is null"); CursorElement.Value = AValue; } public void Set(int AValue) { Set(AValue.ToString(_Culture)); } public void Set(bool AValue) { Set(AValue.ToString(_Culture)); } public void Set(double AValue) { Set(AValue.ToString(_Culture)); } public void Set(byte[] ABytes) { Set(Convert.ToBase64String(ABytes)); } public void Set(Guid AValue) { Set(AValue.ToString()); } public void Set(DateTime AValue) { Set(AValue.ToString(DATE_TIME_FORMAT, _Culture)); //MLHIDE } public void SetEnum<T>(T AValue) where T : struct, IConvertible { if (!typeof(T).IsEnum) throw new ArgumentException("AddEnum can only handle enum types"); Set(AValue.ToString(_Culture)); } } }
/* * ****************************************************************************** * Copyright 2014-2016 Spectra Logic Corporation. 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://www.apache.org/licenses/LICENSE-2.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. * **************************************************************************** */ // This code is auto-generated, do not modify using Ds3.Models; using System; using System.Net; namespace Ds3.Calls { public class PutDataPolicySpectraS3Request : Ds3Request { public string Name { get; private set; } private bool? _alwaysForcePutJobCreation; public bool? AlwaysForcePutJobCreation { get { return _alwaysForcePutJobCreation; } set { WithAlwaysForcePutJobCreation(value); } } private bool? _alwaysMinimizeSpanningAcrossMedia; public bool? AlwaysMinimizeSpanningAcrossMedia { get { return _alwaysMinimizeSpanningAcrossMedia; } set { WithAlwaysMinimizeSpanningAcrossMedia(value); } } private bool? _alwaysReplicateDeletes; public bool? AlwaysReplicateDeletes { get { return _alwaysReplicateDeletes; } set { WithAlwaysReplicateDeletes(value); } } private bool? _blobbingEnabled; public bool? BlobbingEnabled { get { return _blobbingEnabled; } set { WithBlobbingEnabled(value); } } private ChecksumType.Type? _checksumType; public ChecksumType.Type? ChecksumType { get { return _checksumType; } set { WithChecksumType(value); } } private long? _defaultBlobSize; public long? DefaultBlobSize { get { return _defaultBlobSize; } set { WithDefaultBlobSize(value); } } private Priority? _defaultGetJobPriority; public Priority? DefaultGetJobPriority { get { return _defaultGetJobPriority; } set { WithDefaultGetJobPriority(value); } } private Priority? _defaultPutJobPriority; public Priority? DefaultPutJobPriority { get { return _defaultPutJobPriority; } set { WithDefaultPutJobPriority(value); } } private Priority? _defaultVerifyJobPriority; public Priority? DefaultVerifyJobPriority { get { return _defaultVerifyJobPriority; } set { WithDefaultVerifyJobPriority(value); } } private bool? _endToEndCrcRequired; public bool? EndToEndCrcRequired { get { return _endToEndCrcRequired; } set { WithEndToEndCrcRequired(value); } } private Priority? _rebuildPriority; public Priority? RebuildPriority { get { return _rebuildPriority; } set { WithRebuildPriority(value); } } private VersioningLevel? _versioning; public VersioningLevel? Versioning { get { return _versioning; } set { WithVersioning(value); } } public PutDataPolicySpectraS3Request WithAlwaysForcePutJobCreation(bool? alwaysForcePutJobCreation) { this._alwaysForcePutJobCreation = alwaysForcePutJobCreation; if (alwaysForcePutJobCreation != null) { this.QueryParams.Add("always_force_put_job_creation", alwaysForcePutJobCreation.ToString()); } else { this.QueryParams.Remove("always_force_put_job_creation"); } return this; } public PutDataPolicySpectraS3Request WithAlwaysMinimizeSpanningAcrossMedia(bool? alwaysMinimizeSpanningAcrossMedia) { this._alwaysMinimizeSpanningAcrossMedia = alwaysMinimizeSpanningAcrossMedia; if (alwaysMinimizeSpanningAcrossMedia != null) { this.QueryParams.Add("always_minimize_spanning_across_media", alwaysMinimizeSpanningAcrossMedia.ToString()); } else { this.QueryParams.Remove("always_minimize_spanning_across_media"); } return this; } public PutDataPolicySpectraS3Request WithAlwaysReplicateDeletes(bool? alwaysReplicateDeletes) { this._alwaysReplicateDeletes = alwaysReplicateDeletes; if (alwaysReplicateDeletes != null) { this.QueryParams.Add("always_replicate_deletes", alwaysReplicateDeletes.ToString()); } else { this.QueryParams.Remove("always_replicate_deletes"); } return this; } public PutDataPolicySpectraS3Request WithBlobbingEnabled(bool? blobbingEnabled) { this._blobbingEnabled = blobbingEnabled; if (blobbingEnabled != null) { this.QueryParams.Add("blobbing_enabled", blobbingEnabled.ToString()); } else { this.QueryParams.Remove("blobbing_enabled"); } return this; } public PutDataPolicySpectraS3Request WithChecksumType(ChecksumType.Type? checksumType) { this._checksumType = checksumType; if (checksumType != null) { this.QueryParams.Add("checksum_type", checksumType.ToString()); } else { this.QueryParams.Remove("checksum_type"); } return this; } public PutDataPolicySpectraS3Request WithDefaultBlobSize(long? defaultBlobSize) { this._defaultBlobSize = defaultBlobSize; if (defaultBlobSize != null) { this.QueryParams.Add("default_blob_size", defaultBlobSize.ToString()); } else { this.QueryParams.Remove("default_blob_size"); } return this; } public PutDataPolicySpectraS3Request WithDefaultGetJobPriority(Priority? defaultGetJobPriority) { this._defaultGetJobPriority = defaultGetJobPriority; if (defaultGetJobPriority != null) { this.QueryParams.Add("default_get_job_priority", defaultGetJobPriority.ToString()); } else { this.QueryParams.Remove("default_get_job_priority"); } return this; } public PutDataPolicySpectraS3Request WithDefaultPutJobPriority(Priority? defaultPutJobPriority) { this._defaultPutJobPriority = defaultPutJobPriority; if (defaultPutJobPriority != null) { this.QueryParams.Add("default_put_job_priority", defaultPutJobPriority.ToString()); } else { this.QueryParams.Remove("default_put_job_priority"); } return this; } public PutDataPolicySpectraS3Request WithDefaultVerifyJobPriority(Priority? defaultVerifyJobPriority) { this._defaultVerifyJobPriority = defaultVerifyJobPriority; if (defaultVerifyJobPriority != null) { this.QueryParams.Add("default_verify_job_priority", defaultVerifyJobPriority.ToString()); } else { this.QueryParams.Remove("default_verify_job_priority"); } return this; } public PutDataPolicySpectraS3Request WithEndToEndCrcRequired(bool? endToEndCrcRequired) { this._endToEndCrcRequired = endToEndCrcRequired; if (endToEndCrcRequired != null) { this.QueryParams.Add("end_to_end_crc_required", endToEndCrcRequired.ToString()); } else { this.QueryParams.Remove("end_to_end_crc_required"); } return this; } public PutDataPolicySpectraS3Request WithRebuildPriority(Priority? rebuildPriority) { this._rebuildPriority = rebuildPriority; if (rebuildPriority != null) { this.QueryParams.Add("rebuild_priority", rebuildPriority.ToString()); } else { this.QueryParams.Remove("rebuild_priority"); } return this; } public PutDataPolicySpectraS3Request WithVersioning(VersioningLevel? versioning) { this._versioning = versioning; if (versioning != null) { this.QueryParams.Add("versioning", versioning.ToString()); } else { this.QueryParams.Remove("versioning"); } return this; } public PutDataPolicySpectraS3Request(string name) { this.Name = name; this.QueryParams.Add("name", name); } internal override HttpVerb Verb { get { return HttpVerb.POST; } } internal override string Path { get { return "/_rest_/data_policy"; } } } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.27.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Google Flight Availability API Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://devsite.googleplex.com/flightavailability'>Google Flight Availability API</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>20170713 (924) * <tr><th>API Docs * <td><a href='https://devsite.googleplex.com/flightavailability'> * https://devsite.googleplex.com/flightavailability</a> * <tr><th>Discovery Name<td>flightavailability * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Google Flight Availability API can be found at * <a href='https://devsite.googleplex.com/flightavailability'>https://devsite.googleplex.com/flightavailability</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.FlightAvailability.v1 { /// <summary>The FlightAvailability Service.</summary> public class FlightAvailabilityService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public FlightAvailabilityService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public FlightAvailabilityService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { v1 = new V1Resource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "flightavailability"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://flightavailability.googleapis.com/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return ""; } } #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri { get { return "https://flightavailability.googleapis.com/batch"; } } /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath { get { return "batch"; } } #endif private readonly V1Resource v1; /// <summary>Gets the V1 resource.</summary> public virtual V1Resource V1 { get { return v1; } } } ///<summary>A base abstract class for FlightAvailability requests.</summary> public abstract class FlightAvailabilityBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new FlightAvailabilityBaseServiceRequest instance.</summary> protected FlightAvailabilityBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto, } /// <summary>OAuth bearer token.</summary> [Google.Apis.Util.RequestParameterAttribute("bearer_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string BearerToken { get; set; } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Pretty-print response.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("pp", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> Pp { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes FlightAvailability parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "bearer_token", new Google.Apis.Discovery.Parameter { Name = "bearer_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pp", new Google.Apis.Discovery.Parameter { Name = "pp", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "v1" collection of methods.</summary> public class V1Resource { private const string Resource = "v1"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public V1Resource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Called by a partner: receives questions, each of which consists of one or more segments, and /// returns answers with availability data.</summary> /// <param name="body">The body of the request.</param> public virtual QueryRequest Query(Google.Apis.FlightAvailability.v1.Data.FlightavailabilityPartnerAvailQuestions body) { return new QueryRequest(service, body); } /// <summary>Called by a partner: receives questions, each of which consists of one or more segments, and /// returns answers with availability data.</summary> public class QueryRequest : FlightAvailabilityBaseServiceRequest<Google.Apis.FlightAvailability.v1.Data.FlightavailabilityPartnerAvailAnswers> { /// <summary>Constructs a new Query request.</summary> public QueryRequest(Google.Apis.Services.IClientService service, Google.Apis.FlightAvailability.v1.Data.FlightavailabilityPartnerAvailQuestions body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.FlightAvailability.v1.Data.FlightavailabilityPartnerAvailQuestions Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "query"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1:query"; } } /// <summary>Initializes Query parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } } } namespace Google.Apis.FlightAvailability.v1.Data { /// <summary>Represents a whole calendar date, e.g. date of birth. The time of day and time zone are either /// specified elsewhere or are not significant. The date is relative to the Proleptic Gregorian Calendar. The day /// may be 0 to represent a year and month where the day is not significant, e.g. credit card expiration date. The /// year may be 0 to represent a month and day independent of year, e.g. anniversary date. Related types are /// google.type.TimeOfDay and `google.protobuf.Timestamp`.</summary> public class FlightavailabilityDate : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Day of month. Must be from 1 to 31 and valid for the year and month, or 0 if specifying a /// year/month where the day is not significant.</summary> [Newtonsoft.Json.JsonPropertyAttribute("day")] public virtual System.Nullable<int> Day { get; set; } /// <summary>Month of year. Must be from 1 to 12.</summary> [Newtonsoft.Json.JsonPropertyAttribute("month")] public virtual System.Nullable<int> Month { get; set; } /// <summary>Year of date. Must be from 1 to 9999, or 0 if specifying a date without a year.</summary> [Newtonsoft.Json.JsonPropertyAttribute("year")] public virtual System.Nullable<int> Year { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>External (public) availability answer.</summary> public class FlightavailabilityPartnerAvailAnswers : Google.Apis.Requests.IDirectResponseSchema { /// <summary>One-to-one mapping of answers to questions.</summary> [Newtonsoft.Json.JsonPropertyAttribute("answers")] public virtual System.Collections.Generic.IList<FlightavailabilityPartnerAvailAnswersAnswer> Answers { get; set; } /// <summary>Consists of the sequence of calculations done to produce the questions.</summary> [Newtonsoft.Json.JsonPropertyAttribute("narrative")] public virtual string Narrative { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>One answer to an availability question.</summary> public class FlightavailabilityPartnerAvailAnswersAnswer : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Set to true if no solution is found for the corresponding question. Note: We return no solution if /// AVS returns an empty solution or reports an error for that question.</summary> [Newtonsoft.Json.JsonPropertyAttribute("foundNoSolution")] public virtual System.Nullable<bool> FoundNoSolution { get; set; } /// <summary>Consists of the sequence of calculations done to produce the answer.</summary> [Newtonsoft.Json.JsonPropertyAttribute("narrative")] public virtual string Narrative { get; set; } /// <summary>The answer. It consists of multiple solutions.</summary> [Newtonsoft.Json.JsonPropertyAttribute("solutions")] public virtual System.Collections.Generic.IList<FlightavailabilityPartnerAvailAnswersSolution> Solutions { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Conditions or constraints that apply to a solution.</summary> public class FlightavailabilityPartnerAvailAnswersConstraint : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Zero-based non-negative index into the list of segments in the original question.</summary> [Newtonsoft.Json.JsonPropertyAttribute("segmentIndices")] public virtual System.Collections.Generic.IList<System.Nullable<int>> SegmentIndices { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Condition or constraint that applies to a set of segments and has sets of equivalent booking /// codes.</summary> public class FlightavailabilityPartnerAvailAnswersConstraintWithEquivalence : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Multiple groups if booking codes are to be treated as equivalent.</summary> [Newtonsoft.Json.JsonPropertyAttribute("equivalentBookingCodes")] public virtual System.Collections.Generic.IList<FlightavailabilityPartnerAvailAnswersEquivalentBookingCodes> EquivalentBookingCodes { get; set; } /// <summary>Zero-based non-negative index into the list of segments in the original question.</summary> [Newtonsoft.Json.JsonPropertyAttribute("segmentIndices")] public virtual System.Collections.Generic.IList<System.Nullable<int>> SegmentIndices { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Conditions or constraints that apply to a solution.</summary> public class FlightavailabilityPartnerAvailAnswersConstraints : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Counts that are valid only when booking in different BCs.</summary> [Newtonsoft.Json.JsonPropertyAttribute("diffBookingCodes")] public virtual System.Collections.Generic.IList<FlightavailabilityPartnerAvailAnswersConstraintWithEquivalence> DiffBookingCodes { get; set; } /// <summary>Segments that must be married.</summary> [Newtonsoft.Json.JsonPropertyAttribute("marriedSegments")] public virtual System.Collections.Generic.IList<FlightavailabilityPartnerAvailAnswersConstraint> MarriedSegments { get; set; } /// <summary>Counts that are valid only when booking in the same BCs.</summary> [Newtonsoft.Json.JsonPropertyAttribute("sameBookingCodes")] public virtual System.Collections.Generic.IList<FlightavailabilityPartnerAvailAnswersConstraintWithEquivalence> SameBookingCodes { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A set of booking codes considered equivalent.</summary> public class FlightavailabilityPartnerAvailAnswersEquivalentBookingCodes : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Booking code, one or two letters.</summary> [Newtonsoft.Json.JsonPropertyAttribute("bookingCodes")] public virtual System.Collections.Generic.IList<string> BookingCodes { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Availability count from the seat.</summary> public class FlightavailabilityPartnerAvailAnswersSeatCount : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Booking code, one or two letters.</summary> [Newtonsoft.Json.JsonPropertyAttribute("bookingCode")] public virtual string BookingCode { get; set; } /// <summary>Available seat counts.</summary> [Newtonsoft.Json.JsonPropertyAttribute("count")] public virtual System.Nullable<int> Count { get; set; } /// <summary>Seats flag.</summary> [Newtonsoft.Json.JsonPropertyAttribute("seatsFlag")] public virtual FlightavailabilityPartnerAvailAnswersSeatCountSeatsFlag SeatsFlag { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Seats flag parameters.</summary> public class FlightavailabilityPartnerAvailAnswersSeatCountSeatsFlag : Google.Apis.Requests.IDirectResponseSchema { /// <summary>More seats may be available.</summary> [Newtonsoft.Json.JsonPropertyAttribute("infinityFlag")] public virtual System.Nullable<bool> InfinityFlag { get; set; } /// <summary>Non-operating.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nonOperating")] public virtual System.Nullable<bool> NonOperating { get; set; } /// <summary>Available on request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("onRequest")] public virtual System.Nullable<bool> OnRequest { get; set; } /// <summary>Wait list closed.</summary> [Newtonsoft.Json.JsonPropertyAttribute("waitlistClosed")] public virtual System.Nullable<bool> WaitlistClosed { get; set; } /// <summary>Wait list open.</summary> [Newtonsoft.Json.JsonPropertyAttribute("waitlistOpen")] public virtual System.Nullable<bool> WaitlistOpen { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A list of seat counts for a segment.</summary> public class FlightavailabilityPartnerAvailAnswersSegmentCounts : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Consists of the sequence of calculations done to produce the segment.</summary> [Newtonsoft.Json.JsonPropertyAttribute("narrative")] public virtual string Narrative { get; set; } /// <summary>A list of seat counts for a segment.</summary> [Newtonsoft.Json.JsonPropertyAttribute("seatCounts")] public virtual System.Collections.Generic.IList<FlightavailabilityPartnerAvailAnswersSeatCount> SeatCounts { get; set; } /// <summary>Segment index in the original question.</summary> [Newtonsoft.Json.JsonPropertyAttribute("segmentIndex")] public virtual System.Nullable<int> SegmentIndex { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>One solution within an availability answer.</summary> public class FlightavailabilityPartnerAvailAnswersSolution : Google.Apis.Requests.IDirectResponseSchema { /// <summary>All constraints that apply to a solution.</summary> [Newtonsoft.Json.JsonPropertyAttribute("constraints")] public virtual FlightavailabilityPartnerAvailAnswersConstraints Constraints { get; set; } /// <summary>Consists of the sequence of calculations done to produce the solution.</summary> [Newtonsoft.Json.JsonPropertyAttribute("narrative")] public virtual string Narrative { get; set; } /// <summary>A list of seat counts for one or more segments.</summary> [Newtonsoft.Json.JsonPropertyAttribute("segmentCounts")] public virtual System.Collections.Generic.IList<FlightavailabilityPartnerAvailAnswersSegmentCounts> SegmentCounts { get; set; } /// <summary>UTC timestamp that indicates when the solution was computed.</summary> [Newtonsoft.Json.JsonPropertyAttribute("timestampTime")] public virtual object TimestampTime { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>External (public) availability questions.</summary> public class FlightavailabilityPartnerAvailQuestions : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Parameters that apply to all questions.</summary> [Newtonsoft.Json.JsonPropertyAttribute("parameters")] public virtual FlightavailabilityPartnerAvailQuestionsParameters Parameters { get; set; } /// <summary>Availability questions.</summary> [Newtonsoft.Json.JsonPropertyAttribute("questions")] public virtual System.Collections.Generic.IList<FlightavailabilityPartnerAvailQuestionsQuestion> Questions { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Parameters upon which the questions should be answered.</summary> public class FlightavailabilityPartnerAvailQuestionsParameters : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Indicates that answer should follow carrier preferred rules.</summary> [Newtonsoft.Json.JsonPropertyAttribute("carrierPreferredAnswer")] public virtual System.Nullable<bool> CarrierPreferredAnswer { get; set; } /// <summary>List of segments provided as journey data.</summary> [Newtonsoft.Json.JsonPropertyAttribute("journeyDataSegments")] public virtual System.Collections.Generic.IList<FlightavailabilityPartnerAvailQuestionsSegment> JourneyDataSegments { get; set; } /// <summary>Location where tickets are purchased.</summary> [Newtonsoft.Json.JsonPropertyAttribute("pointOfSale")] public virtual FlightavailabilityPartnerAvailQuestionsPointOfSale PointOfSale { get; set; } /// <summary>Whether a PAORES-adjusted answer has been requested.</summary> [Newtonsoft.Json.JsonPropertyAttribute("seamlessAdjustment")] public virtual System.Nullable<bool> SeamlessAdjustment { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Location where the ticket is purchased.</summary> public class FlightavailabilityPartnerAvailQuestionsPointOfSale : Google.Apis.Requests.IDirectResponseSchema { /// <summary>3 to 5 letters.</summary> [Newtonsoft.Json.JsonPropertyAttribute("salesAirport")] public virtual string SalesAirport { get; set; } /// <summary>Exactly 2 or 3 alphanumeric characters.</summary> [Newtonsoft.Json.JsonPropertyAttribute("salesCarriers")] public virtual System.Collections.Generic.IList<string> SalesCarriers { get; set; } /// <summary>3 to 5 letters.</summary> [Newtonsoft.Json.JsonPropertyAttribute("salesCity")] public virtual string SalesCity { get; set; } /// <summary>2 to 3 letters. Defaults to 'US'.</summary> [Newtonsoft.Json.JsonPropertyAttribute("salesCountry")] public virtual string SalesCountry { get; set; } /// <summary>Exactly 2 or 3 alphanumeric characters. CRS stands for Computer Reservation System.</summary> [Newtonsoft.Json.JsonPropertyAttribute("salesCrss")] public virtual System.Collections.Generic.IList<string> SalesCrss { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>One availability question.</summary> public class FlightavailabilityPartnerAvailQuestionsQuestion : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Three-letter abbreviation for the city where the journey originates.</summary> [Newtonsoft.Json.JsonPropertyAttribute("journeyOriginCity")] public virtual string JourneyOriginCity { get; set; } /// <summary>List of segments to be queried for availability. Note: No more than 10 segments per question is /// allowed.</summary> [Newtonsoft.Json.JsonPropertyAttribute("segments")] public virtual System.Collections.Generic.IList<FlightavailabilityPartnerAvailQuestionsSegment> Segments { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A flight segment, also known as leg.</summary> public class FlightavailabilityPartnerAvailQuestionsSegment : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Booking code, one or two letters.</summary> [Newtonsoft.Json.JsonPropertyAttribute("bookingCode")] public virtual string BookingCode { get; set; } /// <summary>Exactly 2 alphanumeric characters.</summary> [Newtonsoft.Json.JsonPropertyAttribute("carrier")] public virtual string Carrier { get; set; } /// <summary>Departure date for this segment, in the time zone of the origin airport.</summary> [Newtonsoft.Json.JsonPropertyAttribute("departureDate")] public virtual FlightavailabilityDate DepartureDate { get; set; } /// <summary>Three-letter code of the destination airport.</summary> [Newtonsoft.Json.JsonPropertyAttribute("destination")] public virtual string Destination { get; set; } /// <summary>A positive number from 1 to 9999.</summary> [Newtonsoft.Json.JsonPropertyAttribute("flightNumber")] public virtual System.Nullable<int> FlightNumber { get; set; } /// <summary>Three-letter code of the origin airport.</summary> [Newtonsoft.Json.JsonPropertyAttribute("origin")] public virtual string Origin { get; set; } /// <summary>If true, then don't include an availability answer for this segment. The default is false (=include /// information). Useful for multiple segments with married availability, when it would only be desirable to /// expose availability from a few selected segments. Note: Married availability refers to flight segments that /// are sold together based on origin and destination, but might not be available if you try to book them /// separately, segment by segment. For example, a routing from New York via Paris to Cairo might be available /// when you book a New York-Cairo flight, but an airline might restrict booking the two segments (New York to /// Paris, and Paris to Cairo) separately.</summary> [Newtonsoft.Json.JsonPropertyAttribute("passiveSegment")] public virtual System.Nullable<bool> PassiveSegment { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
// 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 Internal.Runtime.Augments; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace System { public static partial class Environment { public static int ExitCode { get { return EnvironmentAugments.ExitCode; } set { EnvironmentAugments.ExitCode = value; } } private static string ExpandEnvironmentVariablesCore(string name) { int currentSize = 100; StringBuilder result = StringBuilderCache.Acquire(currentSize); // A somewhat reasonable default size result.Length = 0; int size = Interop.Kernel32.ExpandEnvironmentStringsW(name, result, currentSize); if (size == 0) { StringBuilderCache.Release(result); Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } while (size > currentSize) { currentSize = size; result.Length = 0; result.Capacity = currentSize; size = Interop.Kernel32.ExpandEnvironmentStringsW(name, result, currentSize); if (size == 0) { StringBuilderCache.Release(result); Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } } return StringBuilderCache.GetStringAndRelease(result); } private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOption option) { // We're using SHGetKnownFolderPath instead of SHGetFolderPath as SHGetFolderPath is // capped at MAX_PATH. // // Because we validate both of the input enums we shouldn't have to care about CSIDL and flag // definitions we haven't mapped. If we remove or loosen the checks we'd have to account // for mapping here (this includes tweaking as SHGetFolderPath would do). // // The only SpecialFolderOption defines we have are equivalent to KnownFolderFlags. string folderGuid; switch (folder) { case SpecialFolder.ApplicationData: folderGuid = Interop.Shell32.KnownFolders.RoamingAppData; break; case SpecialFolder.CommonApplicationData: folderGuid = Interop.Shell32.KnownFolders.ProgramData; break; case SpecialFolder.LocalApplicationData: folderGuid = Interop.Shell32.KnownFolders.LocalAppData; break; case SpecialFolder.Cookies: folderGuid = Interop.Shell32.KnownFolders.Cookies; break; case SpecialFolder.Desktop: folderGuid = Interop.Shell32.KnownFolders.Desktop; break; case SpecialFolder.Favorites: folderGuid = Interop.Shell32.KnownFolders.Favorites; break; case SpecialFolder.History: folderGuid = Interop.Shell32.KnownFolders.History; break; case SpecialFolder.InternetCache: folderGuid = Interop.Shell32.KnownFolders.InternetCache; break; case SpecialFolder.Programs: folderGuid = Interop.Shell32.KnownFolders.Programs; break; case SpecialFolder.MyComputer: folderGuid = Interop.Shell32.KnownFolders.ComputerFolder; break; case SpecialFolder.MyMusic: folderGuid = Interop.Shell32.KnownFolders.Music; break; case SpecialFolder.MyPictures: folderGuid = Interop.Shell32.KnownFolders.Pictures; break; case SpecialFolder.MyVideos: folderGuid = Interop.Shell32.KnownFolders.Videos; break; case SpecialFolder.Recent: folderGuid = Interop.Shell32.KnownFolders.Recent; break; case SpecialFolder.SendTo: folderGuid = Interop.Shell32.KnownFolders.SendTo; break; case SpecialFolder.StartMenu: folderGuid = Interop.Shell32.KnownFolders.StartMenu; break; case SpecialFolder.Startup: folderGuid = Interop.Shell32.KnownFolders.Startup; break; case SpecialFolder.System: folderGuid = Interop.Shell32.KnownFolders.System; break; case SpecialFolder.Templates: folderGuid = Interop.Shell32.KnownFolders.Templates; break; case SpecialFolder.DesktopDirectory: folderGuid = Interop.Shell32.KnownFolders.Desktop; break; case SpecialFolder.Personal: // Same as Personal // case SpecialFolder.MyDocuments: folderGuid = Interop.Shell32.KnownFolders.Documents; break; case SpecialFolder.ProgramFiles: folderGuid = Interop.Shell32.KnownFolders.ProgramFiles; break; case SpecialFolder.CommonProgramFiles: folderGuid = Interop.Shell32.KnownFolders.ProgramFilesCommon; break; case SpecialFolder.AdminTools: folderGuid = Interop.Shell32.KnownFolders.AdminTools; break; case SpecialFolder.CDBurning: folderGuid = Interop.Shell32.KnownFolders.CDBurning; break; case SpecialFolder.CommonAdminTools: folderGuid = Interop.Shell32.KnownFolders.CommonAdminTools; break; case SpecialFolder.CommonDocuments: folderGuid = Interop.Shell32.KnownFolders.PublicDocuments; break; case SpecialFolder.CommonMusic: folderGuid = Interop.Shell32.KnownFolders.PublicMusic; break; case SpecialFolder.CommonOemLinks: folderGuid = Interop.Shell32.KnownFolders.CommonOEMLinks; break; case SpecialFolder.CommonPictures: folderGuid = Interop.Shell32.KnownFolders.PublicPictures; break; case SpecialFolder.CommonStartMenu: folderGuid = Interop.Shell32.KnownFolders.CommonStartMenu; break; case SpecialFolder.CommonPrograms: folderGuid = Interop.Shell32.KnownFolders.CommonPrograms; break; case SpecialFolder.CommonStartup: folderGuid = Interop.Shell32.KnownFolders.CommonStartup; break; case SpecialFolder.CommonDesktopDirectory: folderGuid = Interop.Shell32.KnownFolders.PublicDesktop; break; case SpecialFolder.CommonTemplates: folderGuid = Interop.Shell32.KnownFolders.CommonTemplates; break; case SpecialFolder.CommonVideos: folderGuid = Interop.Shell32.KnownFolders.PublicVideos; break; case SpecialFolder.Fonts: folderGuid = Interop.Shell32.KnownFolders.Fonts; break; case SpecialFolder.NetworkShortcuts: folderGuid = Interop.Shell32.KnownFolders.NetHood; break; case SpecialFolder.PrinterShortcuts: folderGuid = Interop.Shell32.KnownFolders.PrintersFolder; break; case SpecialFolder.UserProfile: folderGuid = Interop.Shell32.KnownFolders.Profile; break; case SpecialFolder.CommonProgramFilesX86: folderGuid = Interop.Shell32.KnownFolders.ProgramFilesCommonX86; break; case SpecialFolder.ProgramFilesX86: folderGuid = Interop.Shell32.KnownFolders.ProgramFilesX86; break; case SpecialFolder.Resources: folderGuid = Interop.Shell32.KnownFolders.ResourceDir; break; case SpecialFolder.LocalizedResources: folderGuid = Interop.Shell32.KnownFolders.LocalizedResourcesDir; break; case SpecialFolder.SystemX86: folderGuid = Interop.Shell32.KnownFolders.SystemX86; break; case SpecialFolder.Windows: folderGuid = Interop.Shell32.KnownFolders.Windows; break; default: return string.Empty; } return GetKnownFolderPath(folderGuid, option); } private static string GetKnownFolderPath(string folderGuid, SpecialFolderOption option) { Guid folderId = new Guid(folderGuid); string path; int hr = Interop.Shell32.SHGetKnownFolderPath(folderId, (uint)option, IntPtr.Zero, out path); if (hr != 0) // Not S_OK { return string.Empty; } return path; } private static bool Is64BitOperatingSystemWhen32BitProcess { get { bool isWow64; return Interop.Kernel32.IsWow64Process(Interop.Kernel32.GetCurrentProcess(), out isWow64) && isWow64; } } public static string MachineName { get { string name = Interop.Kernel32.GetComputerName(); if (name == null) { throw new InvalidOperationException(SR.InvalidOperation_ComputerName); } return name; } } private static unsafe Lazy<OperatingSystem> s_osVersion = new Lazy<OperatingSystem>(() => { var version = new Interop.Kernel32.OSVERSIONINFOEX { dwOSVersionInfoSize = sizeof(Interop.Kernel32.OSVERSIONINFOEX) }; if (!Interop.Kernel32.GetVersionExW(ref version)) { throw new InvalidOperationException(SR.InvalidOperation_GetVersion); } return new OperatingSystem( PlatformID.Win32NT, new Version(version.dwMajorVersion, version.dwMinorVersion, version.dwBuildNumber, (version.wServicePackMajor << 16) | version.wServicePackMinor), Marshal.PtrToStringUni((IntPtr)version.szCSDVersion)); }); public static int ProcessorCount { get { // First try GetLogicalProcessorInformationEx, caching the result as desktop/coreclr does. // If that fails for some reason, fall back to a non-cached result from GetSystemInfo. // (See SystemNative::GetProcessorCount in coreclr for a comparison.) int pc = s_processorCountFromGetLogicalProcessorInformationEx.Value; return pc != 0 ? pc : ProcessorCountFromSystemInfo; } } private static readonly unsafe Lazy<int> s_processorCountFromGetLogicalProcessorInformationEx = new Lazy<int>(() => { // Determine how much size we need for a call to GetLogicalProcessorInformationEx uint len = 0; if (!Interop.Kernel32.GetLogicalProcessorInformationEx(Interop.Kernel32.LOGICAL_PROCESSOR_RELATIONSHIP.RelationGroup, IntPtr.Zero, ref len) && Marshal.GetLastWin32Error() == Interop.Errors.ERROR_INSUFFICIENT_BUFFER) { // Allocate that much space Debug.Assert(len > 0); var buffer = new byte[len]; fixed (byte* bufferPtr = buffer) { // Call GetLogicalProcessorInformationEx with the allocated buffer if (Interop.Kernel32.GetLogicalProcessorInformationEx(Interop.Kernel32.LOGICAL_PROCESSOR_RELATIONSHIP.RelationGroup, (IntPtr)bufferPtr, ref len)) { // Walk each SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX in the buffer, where the Size of each dictates how // much space it's consuming. For each group relation, count the number of active processors in each of its group infos. int processorCount = 0; byte* ptr = bufferPtr, endPtr = bufferPtr + len; while (ptr < endPtr) { var current = (Interop.Kernel32.SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)ptr; if (current->Relationship == Interop.Kernel32.LOGICAL_PROCESSOR_RELATIONSHIP.RelationGroup) { Interop.Kernel32.PROCESSOR_GROUP_INFO* groupInfo = &current->Group.GroupInfo; int groupCount = current->Group.ActiveGroupCount; for (int i = 0; i < groupCount; i++) { processorCount += (groupInfo + i)->ActiveProcessorCount; } } ptr += current->Size; } return processorCount; } } } return 0; }); public static string SystemDirectory { get { StringBuilder sb = StringBuilderCache.Acquire(PathInternal.MaxShortPath); if (Interop.Kernel32.GetSystemDirectoryW(sb, PathInternal.MaxShortPath) == 0) { StringBuilderCache.Release(sb); throw Win32Marshal.GetExceptionForLastWin32Error(); } return StringBuilderCache.GetStringAndRelease(sb); } } public static string UserName { get { // Use GetUserNameExW, as GetUserNameW isn't available on all platforms, e.g. Win7 var domainName = new StringBuilder(1024); uint domainNameLen = (uint)domainName.Capacity; if (Interop.Secur32.GetUserNameExW(Interop.Secur32.NameSamCompatible, domainName, ref domainNameLen) == 1) { string samName = domainName.ToString(); int index = samName.IndexOf('\\'); if (index != -1) { return samName.Substring(index + 1); } } return string.Empty; } } public static string UserDomainName { get { var domainName = new StringBuilder(1024); uint domainNameLen = (uint)domainName.Capacity; if (Interop.Secur32.GetUserNameExW(Interop.Secur32.NameSamCompatible, domainName, ref domainNameLen) == 1) { string samName = domainName.ToString(); int index = samName.IndexOf('\\'); if (index != -1) { return samName.Substring(0, index); } } domainNameLen = (uint)domainName.Capacity; byte[] sid = new byte[1024]; int sidLen = sid.Length; int peUse; if (!Interop.Advapi32.LookupAccountNameW(null, UserName, sid, ref sidLen, domainName, ref domainNameLen, out peUse)) { throw new InvalidOperationException(Win32Marshal.GetExceptionForLastWin32Error().Message); } return domainName.ToString(); } } } }
using System; using System.Diagnostics; using System.Text; namespace Community.CsharpSqlite { using sqlite3_value = Sqlite3.Mem; public partial class Sqlite3 { /* ** 2003 January 11 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to implement the sqlite3_set_authorizer() ** API. This facility is an optional feature of the library. Embedded ** systems that do not need this facility may omit it by recompiling ** the library with -DSQLITE_OMIT_AUTHORIZATION=1 ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2009-12-07 16:39:13 1ed88e9d01e9eda5cbc622e7614277f29bcc551c ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* ** All of the code in this file may be omitted by defining a single ** macro. */ #if !SQLITE_OMIT_AUTHORIZATION /* ** Set or clear the access authorization function. ** ** The access authorization function is be called during the compilation ** phase to verify that the user has read and/or write access permission on ** various fields of the database. The first argument to the auth function ** is a copy of the 3rd argument to this routine. The second argument ** to the auth function is one of these constants: ** ** SQLITE_CREATE_INDEX ** SQLITE_CREATE_TABLE ** SQLITE_CREATE_TEMP_INDEX ** SQLITE_CREATE_TEMP_TABLE ** SQLITE_CREATE_TEMP_TRIGGER ** SQLITE_CREATE_TEMP_VIEW ** SQLITE_CREATE_TRIGGER ** SQLITE_CREATE_VIEW ** SQLITE_DELETE ** SQLITE_DROP_INDEX ** SQLITE_DROP_TABLE ** SQLITE_DROP_TEMP_INDEX ** SQLITE_DROP_TEMP_TABLE ** SQLITE_DROP_TEMP_TRIGGER ** SQLITE_DROP_TEMP_VIEW ** SQLITE_DROP_TRIGGER ** SQLITE_DROP_VIEW ** SQLITE_INSERT ** SQLITE_PRAGMA ** SQLITE_READ ** SQLITE_SELECT ** SQLITE_TRANSACTION ** SQLITE_UPDATE ** ** The third and fourth arguments to the auth function are the name of ** the table and the column that are being accessed. The auth function ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY ** means that the SQL statement will never-run - the sqlite3_exec() call ** will return with an error. SQLITE_IGNORE means that the SQL statement ** should run but attempts to read the specified column will return NULL ** and attempts to write the column will be ignored. ** ** Setting the auth function to NULL disables this hook. The default ** setting of the auth function is NULL. */ int sqlite3_set_authorizer( sqlite3 *db, int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), void *pArg ){ sqlite3_mutex_enter(db->mutex); db->xAuth = xAuth; db->pAuthArg = pArg; sqlite3ExpirePreparedStatements(db); sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } /* ** Write an error message into pParse->zErrMsg that explains that the ** user-supplied authorization function returned an illegal value. */ static void sqliteAuthBadReturnCode(Parse *pParse){ sqlite3ErrorMsg(pParse, "authorizer malfunction"); pParse->rc = SQLITE_ERROR; } /* ** Invoke the authorization callback for permission to read column zCol from ** table zTab in database zDb. This function assumes that an authorization ** callback has been registered (i.e. that sqlite3.xAuth is not NULL). ** ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE ** is treated as SQLITE_DENY. In this case an error is left in pParse. */ int sqlite3AuthReadCol( Parse *pParse, /* The parser context */ const char *zTab, /* Table name */ const char *zCol, /* Column name */ int iDb /* Index of containing database. */ ){ sqlite3 *db = pParse->db; /* Database handle */ char *zDb = db->aDb[iDb].zName; /* Name of attached database */ int rc; /* Auth callback return code */ rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext); if( rc==SQLITE_DENY ){ if( db->nDb>2 || iDb!=0 ){ sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol); }else{ sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol); } pParse->rc = SQLITE_AUTH; }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){ sqliteAuthBadReturnCode(pParse); } return rc; } /* ** The pExpr should be a TK_COLUMN expression. The table referred to ** is in pTabList or else it is the NEW or OLD table of a trigger. ** Check to see if it is OK to read this particular column. ** ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY, ** then generate an error. */ void sqlite3AuthRead( Parse *pParse, /* The parser context */ Expr *pExpr, /* The expression to check authorization on */ Schema *pSchema, /* The schema of the expression */ SrcList *pTabList /* All table that pExpr might refer to */ ){ sqlite3 *db = pParse->db; Table *pTab = 0; /* The table being read */ const char *zCol; /* Name of the column of the table */ int iSrc; /* Index in pTabList->a[] of table being read */ int iDb; /* The index of the database the expression refers to */ int iCol; /* Index of column in table */ if( db->xAuth==0 ) return; iDb = sqlite3SchemaToIndex(pParse->db, pSchema); if( iDb<0 ){ /* An attempt to read a column out of a subquery or other ** temporary table. */ return; } assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER ); if( pExpr->op==TK_TRIGGER ){ pTab = pParse->pTriggerTab; }else{ assert( pTabList ); for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){ if( pExpr->iTable==pTabList->a[iSrc].iCursor ){ pTab = pTabList->a[iSrc].pTab; break; } } } iCol = pExpr->iColumn; if( NEVER(pTab==0) ) return; if( iCol>=0 ){ assert( iCol<pTab->nCol ); zCol = pTab->aCol[iCol].zName; }else if( pTab->iPKey>=0 ){ assert( pTab->iPKey<pTab->nCol ); zCol = pTab->aCol[pTab->iPKey].zName; }else{ zCol = "ROWID"; } assert( iDb>=0 && iDb<db->nDb ); if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){ pExpr->op = TK_NULL; } } /* ** Do an authorization check using the code and arguments given. Return ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY ** is returned, then the error count and error message in pParse are ** modified appropriately. */ int sqlite3AuthCheck( Parse *pParse, int code, const char *zArg1, const char *zArg2, const char *zArg3 ){ sqlite3 *db = pParse->db; int rc; /* Don't do any authorization checks if the database is initialising ** or if the parser is being invoked from within sqlite3_declare_vtab. */ if( db->init.busy || IN_DECLARE_VTAB ){ return SQLITE_OK; } if( db->xAuth==0 ){ return SQLITE_OK; } rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext); if( rc==SQLITE_DENY ){ sqlite3ErrorMsg(pParse, "not authorized"); pParse->rc = SQLITE_AUTH; }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){ rc = SQLITE_DENY; sqliteAuthBadReturnCode(pParse); } return rc; } /* ** Push an authorization context. After this routine is called, the ** zArg3 argument to authorization callbacks will be zContext until ** popped. Or if pParse==0, this routine is a no-op. */ void sqlite3AuthContextPush( Parse *pParse, AuthContext *pContext, const char *zContext ){ assert( pParse ); pContext->pParse = pParse; pContext->zAuthContext = pParse->zAuthContext; pParse->zAuthContext = zContext; } /* ** Pop an authorization context that was previously pushed ** by sqlite3AuthContextPush */ void sqlite3AuthContextPop(AuthContext *pContext){ if( pContext->pParse ){ pContext->pParse->zAuthContext = pContext->zAuthContext; pContext->pParse = 0; } } #endif //* SQLITE_OMIT_AUTHORIZATION */ } }
// 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.Windows; using System.Windows.Interop; using ControlzEx.Native; using ControlzEx.Standard; using MahApps.Metro.Controls; using Microsoft.Xaml.Behaviors; namespace MahApps.Metro.Behaviors { public class WindowsSettingBehavior : Behavior<MetroWindow> { /// <inheritdoc /> protected override void OnAttached() { base.OnAttached(); this.AssociatedObject.SourceInitialized += this.AssociatedObject_SourceInitialized; } /// <inheritdoc /> protected override void OnDetaching() { this.CleanUp("from OnDetaching"); base.OnDetaching(); } private void AssociatedObject_SourceInitialized(object? sender, EventArgs e) { this.LoadWindowState(); var window = this.AssociatedObject; if (window is null) { // if the associated object is null at this point, then there is really something wrong! Trace.TraceError($"{this}: Can not attach to nested events, cause the AssociatedObject is null."); return; } window.StateChanged += this.AssociatedObject_StateChanged; window.Closing += this.AssociatedObject_Closing; window.Closed += this.AssociatedObject_Closed; // This operation must be thread safe. It is possible, that the window is running in a different Thread. Application.Current?.BeginInvoke(app => { if (app != null) { app.SessionEnding += this.CurrentApplicationSessionEnding; } }); } private void AssociatedObject_Closing(object? sender, System.ComponentModel.CancelEventArgs e) { this.SaveWindowState(); } private void AssociatedObject_Closed(object? sender, EventArgs e) { this.CleanUp("from AssociatedObject closed event"); } private void CurrentApplicationSessionEnding(object? sender, SessionEndingCancelEventArgs e) { this.SaveWindowState(); } private void AssociatedObject_StateChanged(object? sender, EventArgs e) { // save the settings on this state change, because hidden windows gets no window placements // all the saving stuff could be so much easier with ReactiveUI :-D if (this.AssociatedObject?.WindowState == WindowState.Minimized) { this.SaveWindowState(); } } private void CleanUp(string fromWhere) { var window = this.AssociatedObject; if (window is null) { // it's bad if the associated object is null, so trace this here Trace.TraceWarning($"{this}: Can not clean up {fromWhere}, cause the AssociatedObject is null. This can maybe happen if this Behavior was already detached."); return; } Debug.WriteLine($"{this}: Clean up {fromWhere}."); window.StateChanged -= this.AssociatedObject_StateChanged; window.Closing -= this.AssociatedObject_Closing; window.Closed -= this.AssociatedObject_Closed; window.SourceInitialized -= this.AssociatedObject_SourceInitialized; // This operation must be thread safe Application.Current?.BeginInvoke(app => { if (app != null) { app.SessionEnding -= this.CurrentApplicationSessionEnding; } }); } #pragma warning disable 618 private void LoadWindowState() { var window = this.AssociatedObject; if (window is null) { return; } var settings = window.GetWindowPlacementSettings(); if (settings is null || !window.SaveWindowPosition) { return; } try { settings.Reload(); } catch (Exception e) { Trace.TraceError($"{this}: The settings for {window} could not be reloaded! {e}"); return; } // check for existing placement and prevent empty bounds if (settings.Placement is null || settings.Placement.normalPosition.IsEmpty) { return; } try { var wp = settings.Placement; WinApiHelper.SetWindowPlacement(window, wp); } catch (Exception ex) { throw new MahAppsException($"Failed to set the window state for {window} from the settings.", ex); } } private void SaveWindowState() { var window = this.AssociatedObject; if (window is null) { return; } var settings = window.GetWindowPlacementSettings(); if (settings is null || !window.SaveWindowPosition) { return; } var windowHandle = new WindowInteropHelper(window).EnsureHandle(); var wp = NativeMethods.GetWindowPlacement(windowHandle); // check for saveable values if (wp.showCmd != SW.HIDE && wp.length > 0) { if (wp.showCmd == SW.NORMAL) { if (UnsafeNativeMethods.GetWindowRect(windowHandle, out var rect)) { var monitor = NativeMethods.MonitorFromWindow(windowHandle, MonitorOptions.MONITOR_DEFAULTTONEAREST); if (monitor != IntPtr.Zero) { var monitorInfo = NativeMethods.GetMonitorInfo(monitor); rect.Offset(monitorInfo.rcMonitor.Left - monitorInfo.rcWork.Left, monitorInfo.rcMonitor.Top - monitorInfo.rcWork.Top); } wp.normalPosition = rect; } } if (!wp.normalPosition.IsEmpty) { settings.Placement = wp; } } try { settings.Save(); } catch (Exception e) { Trace.TraceError($"{this}: The settings could not be saved! {e}"); } } #pragma warning restore 618 } }
// 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 Xunit; namespace System.Numerics.Tests { public class cast_toTest { public delegate void ExceptionGenerator(); private const int NumberOfRandomIterations = 10; private static Random s_random = new Random(100); [Fact] public static void RunByteImplicitCastToBigIntegerTests() { // Byte Implicit Cast to BigInteger: Byte.MinValue VerifyByteImplicitCastToBigInteger(Byte.MinValue); // Byte Implicit Cast to BigInteger: 0 VerifyByteImplicitCastToBigInteger(0); // Byte Implicit Cast to BigInteger: 1 VerifyByteImplicitCastToBigInteger(1); // Byte Implicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyByteImplicitCastToBigInteger((Byte)s_random.Next(1, Byte.MaxValue)); } // Byte Implicit Cast to BigInteger: Byte.MaxValue VerifyByteImplicitCastToBigInteger(Byte.MaxValue); } [Fact] public static void RunSByteImplicitCastToBigIntegerTests() { // SByte Implicit Cast to BigInteger: SByte.MinValue VerifySByteImplicitCastToBigInteger(SByte.MinValue); // SByte Implicit Cast to BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifySByteImplicitCastToBigInteger((SByte)s_random.Next(SByte.MinValue, 0)); } // SByte Implicit Cast to BigInteger: -1 VerifySByteImplicitCastToBigInteger(-1); // SByte Implicit Cast to BigInteger: 0 VerifySByteImplicitCastToBigInteger(0); // SByte Implicit Cast to BigInteger: 1 VerifySByteImplicitCastToBigInteger(1); // SByte Implicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifySByteImplicitCastToBigInteger((SByte)s_random.Next(1, SByte.MaxValue)); } // SByte Implicit Cast to BigInteger: SByte.MaxValue VerifySByteImplicitCastToBigInteger(SByte.MaxValue); } [Fact] public static void RunUInt16ImplicitCastToBigIntegerTests() { // UInt16 Implicit Cast to BigInteger: UInt16.MinValue VerifyUInt16ImplicitCastToBigInteger(UInt16.MinValue); // UInt16 Implicit Cast to BigInteger: 0 VerifyUInt16ImplicitCastToBigInteger(0); // UInt16 Implicit Cast to BigInteger: 1 VerifyUInt16ImplicitCastToBigInteger(1); // UInt16 Implicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyUInt16ImplicitCastToBigInteger((UInt16)s_random.Next(1, UInt16.MaxValue)); } // UInt16 Implicit Cast to BigInteger: UInt16.MaxValue VerifyUInt16ImplicitCastToBigInteger(UInt16.MaxValue); } [Fact] public static void RunInt16ImplicitCastToBigIntegerTests() { // Int16 Implicit Cast to BigInteger: Int16.MinValue VerifyInt16ImplicitCastToBigInteger(Int16.MinValue); // Int16 Implicit Cast to BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyInt16ImplicitCastToBigInteger((Int16)s_random.Next(Int16.MinValue, 0)); } // Int16 Implicit Cast to BigInteger: -1 VerifyInt16ImplicitCastToBigInteger(-1); // Int16 Implicit Cast to BigInteger: 0 VerifyInt16ImplicitCastToBigInteger(0); // Int16 Implicit Cast to BigInteger: 1 VerifyInt16ImplicitCastToBigInteger(1); // Int16 Implicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyInt16ImplicitCastToBigInteger((Int16)s_random.Next(1, Int16.MaxValue)); } // Int16 Implicit Cast to BigInteger: Int16.MaxValue VerifyInt16ImplicitCastToBigInteger(Int16.MaxValue); } [Fact] public static void RunUInt32ImplicitCastToBigIntegerTests() { // UInt32 Implicit Cast to BigInteger: UInt32.MinValue VerifyUInt32ImplicitCastToBigInteger(UInt32.MinValue); // UInt32 Implicit Cast to BigInteger: 0 VerifyUInt32ImplicitCastToBigInteger(0); // UInt32 Implicit Cast to BigInteger: 1 VerifyUInt32ImplicitCastToBigInteger(1); // UInt32 Implicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyUInt32ImplicitCastToBigInteger((UInt32)(UInt32.MaxValue * s_random.NextDouble())); } // UInt32 Implicit Cast to BigInteger: UInt32.MaxValue VerifyUInt32ImplicitCastToBigInteger(UInt32.MaxValue); } [Fact] public static void RunInt32ImplicitCastToBigIntegerTests() { // Int32 Implicit Cast to BigInteger: Int32.MinValue VerifyInt32ImplicitCastToBigInteger(Int32.MinValue); // Int32 Implicit Cast to BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyInt32ImplicitCastToBigInteger((Int32)s_random.Next(Int32.MinValue, 0)); } // Int32 Implicit Cast to BigInteger: -1 VerifyInt32ImplicitCastToBigInteger(-1); // Int32 Implicit Cast to BigInteger: 0 VerifyInt32ImplicitCastToBigInteger(0); // Int32 Implicit Cast to BigInteger: 1 VerifyInt32ImplicitCastToBigInteger(1); // Int32 Implicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyInt32ImplicitCastToBigInteger((Int32)s_random.Next(1, Int32.MaxValue)); } // Int32 Implicit Cast to BigInteger: Int32.MaxValue VerifyInt32ImplicitCastToBigInteger(Int32.MaxValue); } [Fact] public static void RunUInt64ImplicitCastToBigIntegerTests() { // UInt64 Implicit Cast to BigInteger: UInt64.MinValue VerifyUInt64ImplicitCastToBigInteger(UInt64.MinValue); // UInt64 Implicit Cast to BigInteger: 0 VerifyUInt64ImplicitCastToBigInteger(0); // UInt64 Implicit Cast to BigInteger: 1 VerifyUInt64ImplicitCastToBigInteger(1); // UInt64 Implicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyUInt64ImplicitCastToBigInteger((UInt64)(UInt64.MaxValue * s_random.NextDouble())); } // UInt64 Implicit Cast to BigInteger: UInt64.MaxValue VerifyUInt64ImplicitCastToBigInteger(UInt64.MaxValue); } [Fact] public static void RunInt64ImplicitCastToBigIntegerTests() { // Int64 Implicit Cast to BigInteger: Int64.MinValue VerifyInt64ImplicitCastToBigInteger(Int64.MinValue); // Int64 Implicit Cast to BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyInt64ImplicitCastToBigInteger(((Int64)(Int64.MaxValue * s_random.NextDouble())) - Int64.MaxValue); } // Int64 Implicit Cast to BigInteger: -1 VerifyInt64ImplicitCastToBigInteger(-1); // Int64 Implicit Cast to BigInteger: 0 VerifyInt64ImplicitCastToBigInteger(0); // Int64 Implicit Cast to BigInteger: 1 VerifyInt64ImplicitCastToBigInteger(1); // Int64 Implicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyInt64ImplicitCastToBigInteger((Int64)(Int64.MaxValue * s_random.NextDouble())); } // Int64 Implicit Cast to BigInteger: Int64.MaxValue VerifyInt64ImplicitCastToBigInteger(Int64.MaxValue); } [Fact] public static void RunSingleExplicitCastToBigIntegerTests() { Single value; // Single Explicit Cast to BigInteger: Single.NegativeInfinity Assert.Throws<OverflowException>(() => { BigInteger temp = (BigInteger)Single.NegativeInfinity; }); // Single Explicit Cast to BigInteger: Single.MinValue VerifySingleExplicitCastToBigInteger(Single.MinValue); // Single Explicit Cast to BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifySingleExplicitCastToBigInteger(((Single)(Single.MaxValue * s_random.NextDouble())) - Single.MaxValue); } // Single Explicit Cast to BigInteger: Random Non-Integral Negative > -100 for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifySingleExplicitCastToBigInteger((Single)(-100 * s_random.NextDouble())); } // Single Explicit Cast to BigInteger: -1 VerifySingleExplicitCastToBigInteger(-1); // Single Explicit Cast to BigInteger: 0 VerifySingleExplicitCastToBigInteger(0); // Single Explicit Cast to BigInteger: 1 VerifySingleExplicitCastToBigInteger(1); // Single Explicit Cast to BigInteger: Random Non-Integral Positive < 100 for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifySingleExplicitCastToBigInteger((Single)(100 * s_random.NextDouble())); } // Single Explicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifySingleExplicitCastToBigInteger((Single)(Single.MaxValue * s_random.NextDouble())); } // Single Explicit Cast to BigInteger: Single.MaxValue VerifySingleExplicitCastToBigInteger(Single.MaxValue); // Single Explicit Cast to BigInteger: Single.PositiveInfinity Assert.Throws<OverflowException>(() => { BigInteger temp = (BigInteger)Single.PositiveInfinity; }); // double.IsInfinity(float.MaxValue * 2.0f) == false, but we don't want this odd behavior here Assert.Throws<OverflowException>(() => { BigInteger temp = (BigInteger)(float.MaxValue * 2.0f); }); // Single Explicit Cast to BigInteger: Single.Epsilon VerifySingleExplicitCastToBigInteger(Single.Epsilon); // Single Explicit Cast to BigInteger: Single.NaN Assert.Throws<OverflowException>(() => { BigInteger temp = (BigInteger)Single.NaN; }); //There are multiple ways to represent a NaN just try another one // Single Explicit Cast to BigInteger: Single.NaN 2 Assert.Throws<OverflowException>(() => { BigInteger temp = (BigInteger)ConvertInt32ToSingle(0x7FC00000); }); // Single Explicit Cast to BigInteger: Smallest Exponent VerifySingleExplicitCastToBigInteger((Single)Math.Pow(2, -126)); // Single Explicit Cast to BigInteger: Largest Exponent VerifySingleExplicitCastToBigInteger((Single)Math.Pow(2, 127)); // Single Explicit Cast to BigInteger: Largest number less then 1 value = 0; for (int i = 1; i <= 24; ++i) { value += (Single)(Math.Pow(2, -i)); } VerifySingleExplicitCastToBigInteger(value); // Single Explicit Cast to BigInteger: Smallest number greater then 1 value = (Single)(1 + Math.Pow(2, -23)); VerifySingleExplicitCastToBigInteger(value); // Single Explicit Cast to BigInteger: Largest number less then 2 value = 0; for (int i = 1; i <= 23; ++i) { value += (Single)(Math.Pow(2, -i)); } value += 1; VerifySingleExplicitCastToBigInteger(value); } [Fact] public static void RunDoubleExplicitCastToBigIntegerTests() { Double value; // Double Explicit Cast to BigInteger: Double.NegativeInfinity Assert.Throws<OverflowException>(() => { BigInteger temp = (BigInteger)Double.NegativeInfinity; }); // Double Explicit Cast to BigInteger: Double.MinValue VerifyDoubleExplicitCastToBigInteger(Double.MinValue); // Double Explicit Cast to BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyDoubleExplicitCastToBigInteger(((Double)(Double.MaxValue * s_random.NextDouble())) - Double.MaxValue); } // Double Explicit Cast to BigInteger: Random Non-Integral Negative > -100 for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyDoubleExplicitCastToBigInteger((Double)(-100 * s_random.NextDouble())); } // Double Explicit Cast to BigInteger: -1 VerifyDoubleExplicitCastToBigInteger(-1); // Double Explicit Cast to BigInteger: 0 VerifyDoubleExplicitCastToBigInteger(0); // Double Explicit Cast to BigInteger: 1 VerifyDoubleExplicitCastToBigInteger(1); // Double Explicit Cast to BigInteger: Random Non-Integral Positive < 100 for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyDoubleExplicitCastToBigInteger((Double)(100 * s_random.NextDouble())); } // Double Explicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyDoubleExplicitCastToBigInteger((Double)(Double.MaxValue * s_random.NextDouble())); } // Double Explicit Cast to BigInteger: Double.MaxValue VerifyDoubleExplicitCastToBigInteger(Double.MaxValue); // Double Explicit Cast to BigInteger: Double.PositiveInfinity Assert.Throws<OverflowException>(() => { BigInteger temp = (BigInteger)Double.PositiveInfinity; }); // Double Explicit Cast to BigInteger: Double.Epsilon VerifyDoubleExplicitCastToBigInteger(Double.Epsilon); // Double Explicit Cast to BigInteger: Double.NaN Assert.Throws<OverflowException>(() => { BigInteger temp = (BigInteger)Double.NaN; }); //There are multiple ways to represent a NaN just try another one // Double Explicit Cast to BigInteger: Double.NaN 2 Assert.Throws<OverflowException>(() => { BigInteger temp = (BigInteger)ConvertInt64ToDouble(0x7FF8000000000000); }); // Double Explicit Cast to BigInteger: Smallest Exponent VerifyDoubleExplicitCastToBigInteger((Double)Math.Pow(2, -1022)); // Double Explicit Cast to BigInteger: Largest Exponent VerifyDoubleExplicitCastToBigInteger((Double)Math.Pow(2, 1023)); // Double Explicit Cast to BigInteger: Largest number less then 1 value = 0; for (int i = 1; i <= 53; ++i) { value += (Double)(Math.Pow(2, -i)); } VerifyDoubleExplicitCastToBigInteger(value); // Double Explicit Cast to BigInteger: Smallest number greater then 1 value = (Double)(1 + Math.Pow(2, -52)); VerifyDoubleExplicitCastToBigInteger(value); // Double Explicit Cast to BigInteger: Largest number less then 2 value = 0; for (int i = 1; i <= 52; ++i) { value += (Double)(Math.Pow(2, -i)); } value += 1; VerifyDoubleExplicitCastToBigInteger(value); } [Fact] public static void RunDecimalExplicitCastToBigIntegerTests() { Decimal value; // Decimal Explicit Cast to BigInteger: Decimal.MinValue VerifyDecimalExplicitCastToBigInteger(Decimal.MinValue); // Decimal Explicit Cast to BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { value = new Decimal( s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), true, (byte)s_random.Next(0, 29)); VerifyDecimalExplicitCastToBigInteger(value); } // Decimal Explicit Cast to BigInteger: -1 VerifyDecimalExplicitCastToBigInteger(-1); // Decimal Explicit Cast to BigInteger: 0 VerifyDecimalExplicitCastToBigInteger(0); // Decimal Explicit Cast to BigInteger: 1 VerifyDecimalExplicitCastToBigInteger(1); // Decimal Explicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { value = new Decimal( s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), false, (byte)s_random.Next(0, 29)); VerifyDecimalExplicitCastToBigInteger(value); } // Decimal Explicit Cast to BigInteger: Decimal.MaxValue VerifyDecimalExplicitCastToBigInteger(Decimal.MaxValue); // Decimal Explicit Cast to BigInteger: Smallest Exponent unchecked { value = new Decimal(1, 0, 0, false, 0); } VerifyDecimalExplicitCastToBigInteger(value); // Decimal Explicit Cast to BigInteger: Largest Exponent and zero integer unchecked { value = new Decimal(0, 0, 0, false, 28); } VerifyDecimalExplicitCastToBigInteger(value); // Decimal Explicit Cast to BigInteger: Largest Exponent and non zero integer unchecked { value = new Decimal(1, 0, 0, false, 28); } VerifyDecimalExplicitCastToBigInteger(value); // Decimal Explicit Cast to BigInteger: Largest number less then 1 value = 1 - new Decimal(1, 0, 0, false, 28); VerifyDecimalExplicitCastToBigInteger(value); // Decimal Explicit Cast to BigInteger: Smallest number greater then 1 value = 1 + new Decimal(1, 0, 0, false, 28); VerifyDecimalExplicitCastToBigInteger(value); // Decimal Explicit Cast to BigInteger: Largest number less then 2 value = 2 - new Decimal(1, 0, 0, false, 28); VerifyDecimalExplicitCastToBigInteger(value); } private static Single ConvertInt32ToSingle(Int32 value) { return BitConverter.ToSingle(BitConverter.GetBytes(value), 0); } private static Double ConvertInt64ToDouble(Int64 value) { return BitConverter.ToDouble(BitConverter.GetBytes(value), 0); } private static void VerifyByteImplicitCastToBigInteger(Byte value) { BigInteger bigInteger = value; Assert.Equal(value, bigInteger); Assert.Equal(value.ToString(), bigInteger.ToString()); Assert.Equal(value, (Byte)bigInteger); if (value != Byte.MaxValue) { Assert.Equal((Byte)(value + 1), (Byte)(bigInteger + 1)); } if (value != Byte.MinValue) { Assert.Equal((Byte)(value - 1), (Byte)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } private static void VerifySByteImplicitCastToBigInteger(SByte value) { BigInteger bigInteger = value; Assert.Equal(value, bigInteger); Assert.Equal(value.ToString(), bigInteger.ToString()); Assert.Equal(value, (SByte)bigInteger); if (value != SByte.MaxValue) { Assert.Equal((SByte)(value + 1), (SByte)(bigInteger + 1)); } if (value != SByte.MinValue) { Assert.Equal((SByte)(value - 1), (SByte)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } private static void VerifyUInt16ImplicitCastToBigInteger(UInt16 value) { BigInteger bigInteger = value; Assert.Equal(value, bigInteger); Assert.Equal(value.ToString(), bigInteger.ToString()); Assert.Equal(value, (UInt16)bigInteger); if (value != UInt16.MaxValue) { Assert.Equal((UInt16)(value + 1), (UInt16)(bigInteger + 1)); } if (value != UInt16.MinValue) { Assert.Equal((UInt16)(value - 1), (UInt16)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } private static void VerifyInt16ImplicitCastToBigInteger(Int16 value) { BigInteger bigInteger = value; Assert.Equal(value, bigInteger); Assert.Equal(value.ToString(), bigInteger.ToString()); Assert.Equal(value, (Int16)bigInteger); if (value != Int16.MaxValue) { Assert.Equal((Int16)(value + 1), (Int16)(bigInteger + 1)); } if (value != Int16.MinValue) { Assert.Equal((Int16)(value - 1), (Int16)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } private static void VerifyUInt32ImplicitCastToBigInteger(UInt32 value) { BigInteger bigInteger = value; Assert.Equal(value, bigInteger); Assert.Equal(value.ToString(), bigInteger.ToString()); Assert.Equal(value, (UInt32)bigInteger); if (value != UInt32.MaxValue) { Assert.Equal((UInt32)(value + 1), (UInt32)(bigInteger + 1)); } if (value != UInt32.MinValue) { Assert.Equal((UInt32)(value - 1), (UInt32)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } private static void VerifyInt32ImplicitCastToBigInteger(Int32 value) { BigInteger bigInteger = value; Assert.Equal(value, bigInteger); Assert.Equal(value.ToString(), bigInteger.ToString()); Assert.Equal(value, (Int32)bigInteger); if (value != Int32.MaxValue) { Assert.Equal((Int32)(value + 1), (Int32)(bigInteger + 1)); } if (value != Int32.MinValue) { Assert.Equal((Int32)(value - 1), (Int32)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } private static void VerifyUInt64ImplicitCastToBigInteger(UInt64 value) { BigInteger bigInteger = value; Assert.Equal(value, bigInteger); Assert.Equal(value.ToString(), bigInteger.ToString()); Assert.Equal(value, (UInt64)bigInteger); if (value != UInt64.MaxValue) { Assert.Equal((UInt64)(value + 1), (UInt64)(bigInteger + 1)); } if (value != UInt64.MinValue) { Assert.Equal((UInt64)(value - 1), (UInt64)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } private static void VerifyInt64ImplicitCastToBigInteger(Int64 value) { BigInteger bigInteger = value; Assert.Equal(value, bigInteger); Assert.Equal(value.ToString(), bigInteger.ToString()); Assert.Equal(value, (Int64)bigInteger); if (value != Int64.MaxValue) { Assert.Equal((Int64)(value + 1), (Int64)(bigInteger + 1)); } if (value != Int64.MinValue) { Assert.Equal((Int64)(value - 1), (Int64)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } private static void VerifySingleExplicitCastToBigInteger(Single value) { Single expectedValue; BigInteger bigInteger; if (value < 0) { expectedValue = (Single)Math.Ceiling(value); } else { expectedValue = (Single)Math.Floor(value); } bigInteger = (BigInteger)value; Assert.Equal(expectedValue, (Single)bigInteger); // Single can only accurately represent integers between -16777216 and 16777216 exclusive. // ToString starts to become inaccurate at this point. if (expectedValue < 16777216 && -16777216 < expectedValue) { Assert.Equal(expectedValue.ToString("G9"), bigInteger.ToString()); } if (expectedValue != Math.Floor(Single.MaxValue)) { Assert.Equal((Single)(expectedValue + 1), (Single)(bigInteger + 1)); } if (expectedValue != Math.Ceiling(Single.MinValue)) { Assert.Equal((Single)(expectedValue - 1), (Single)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == expectedValue); } private static void VerifyDoubleExplicitCastToBigInteger(Double value) { Double expectedValue; BigInteger bigInteger; if (value < 0) { expectedValue = Math.Ceiling(value); } else { expectedValue = Math.Floor(value); } bigInteger = (BigInteger)value; Assert.Equal(expectedValue, (Double)bigInteger); // Double can only accurately represent integers between -9007199254740992 and 9007199254740992 exclusive. // ToString starts to become inaccurate at this point. if (expectedValue < 9007199254740992 && -9007199254740992 < expectedValue) { Assert.Equal(expectedValue.ToString(), bigInteger.ToString()); } if (!Single.IsInfinity((Single)expectedValue)) { Assert.Equal((Double)(expectedValue + 1), (Double)(bigInteger + 1)); Assert.Equal((Double)(expectedValue - 1), (Double)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == expectedValue); } private static void VerifyDecimalExplicitCastToBigInteger(Decimal value) { Decimal expectedValue; BigInteger bigInteger; if (value < 0) { expectedValue = Math.Ceiling(value); } else { expectedValue = Math.Floor(value); } bigInteger = (BigInteger)value; Assert.Equal(expectedValue.ToString(), bigInteger.ToString()); Assert.Equal(expectedValue, (Decimal)bigInteger); VerifyBigIntegerUsingIdentities(bigInteger, 0 == expectedValue); if (expectedValue != Math.Floor(Decimal.MaxValue)) { Assert.Equal((Decimal)(expectedValue + 1), (Decimal)(bigInteger + 1)); } if (expectedValue != Math.Ceiling(Decimal.MinValue)) { Assert.Equal((Decimal)(expectedValue - 1), (Decimal)(bigInteger - 1)); } } private static void VerifyBigIntegerUsingIdentities(BigInteger bigInteger, bool isZero) { BigInteger tempBigInteger = new BigInteger(bigInteger.ToByteArray()); Assert.Equal(bigInteger, tempBigInteger); if (isZero) { Assert.Equal(BigInteger.Zero, bigInteger); } else { Assert.NotEqual(BigInteger.Zero, bigInteger); // x/x = 1 Assert.Equal(BigInteger.One, bigInteger / bigInteger); } // (x + 1) - 1 = x Assert.Equal(bigInteger, (bigInteger + BigInteger.One) - BigInteger.One); // (x + 1) - x = 1 Assert.Equal(BigInteger.One, (bigInteger + BigInteger.One) - bigInteger); // x - x = 0 Assert.Equal(BigInteger.Zero, bigInteger - bigInteger); // x + x = 2x Assert.Equal(2 * bigInteger, bigInteger + bigInteger); // x/1 = x Assert.Equal(bigInteger, bigInteger / BigInteger.One); // 1 * x = x Assert.Equal(bigInteger, BigInteger.One * bigInteger); } } }
// 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.Runtime.InteropServices; using System.Runtime.Versioning; using System.Runtime.ConstrainedExecution; using System.Runtime.CompilerServices; using System.Runtime; using System.Security; namespace System.Threading { // // Methods for accessing memory with volatile semantics. These are preferred over Thread.VolatileRead // and Thread.VolatileWrite, as these are implemented more efficiently. // // (We cannot change the implementations of Thread.VolatileRead/VolatileWrite without breaking code // that relies on their overly-strong ordering guarantees.) // // The actual implementations of these methods are typically supplied by the VM at JIT-time, because C# does // not allow us to express a volatile read/write from/to a byref arg. // See getILIntrinsicImplementationForVolatile() in jitinterface.cpp. // public static class Volatile { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static bool Read(ref bool location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] public static sbyte Read(ref sbyte location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static byte Read(ref byte location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static short Read(ref short location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] public static ushort Read(ref ushort location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static int Read(ref int location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] public static uint Read(ref uint location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } #if BIT64 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static long Read(ref long location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] public static ulong Read(ref ulong location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } #else [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static long Read(ref long location) { // // On 32-bit machines, we use this implementation, since an ordinary volatile read // would not be atomic. // // On 64-bit machines, the VM will replace this with a more efficient implementation. // return Interlocked.CompareExchange(ref location, 0, 0); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] public static ulong Read(ref ulong location) { unsafe { // // There is no overload of Interlocked.Exchange that accepts a ulong. So we have // to do some pointer tricks to pass our arguments to the overload that takes a long. // fixed (ulong* pLocation = &location) { return (ulong)Interlocked.CompareExchange(ref *(long*)pLocation, 0, 0); } } } #endif [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static IntPtr Read(ref IntPtr location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] public static UIntPtr Read(ref UIntPtr location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static float Read(ref float location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static double Read(ref double location) { // // On 32-bit machines, we use this implementation, since an ordinary volatile read // would not be atomic. // // On 64-bit machines, the VM will replace this with a more efficient implementation. // return Interlocked.CompareExchange(ref location, 0, 0); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static T Read<T>(ref T location) where T : class { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static void Write(ref bool location, bool value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] public static void Write(ref sbyte location, sbyte value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static void Write(ref byte location, byte value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static void Write(ref short location, short value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] public static void Write(ref ushort location, ushort value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static void Write(ref int location, int value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] public static void Write(ref uint location, uint value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } #if BIT64 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static void Write(ref long location, long value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] public static void Write(ref ulong location, ulong value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } #else [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static void Write(ref long location, long value) { // // On 32-bit machines, we use this implementation, since an ordinary volatile write // would not be atomic. // // On 64-bit machines, the VM will replace this with a more efficient implementation. // Interlocked.Exchange(ref location, value); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] public static void Write(ref ulong location, ulong value) { // // On 32-bit machines, we use this implementation, since an ordinary volatile write // would not be atomic. // // On 64-bit machines, the VM will replace this with a more efficient implementation. // unsafe { // // There is no overload of Interlocked.Exchange that accepts a ulong. So we have // to do some pointer tricks to pass our arguments to the overload that takes a long. // fixed (ulong* pLocation = &location) { Interlocked.Exchange(ref *(long*)pLocation, (long)value); } } } #endif [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static void Write(ref IntPtr location, IntPtr value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] public static void Write(ref UIntPtr location, UIntPtr value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static void Write(ref float location, float value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static void Write(ref double location, double value) { // // On 32-bit machines, we use this implementation, since an ordinary volatile write // would not be atomic. // // On 64-bit machines, the VM will replace this with a more efficient implementation. // Interlocked.Exchange(ref location, value); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static void Write<T>(ref T location, T value) where T : class { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Xml; using Palaso.WritingSystems.Collation; using Palaso.Xml; namespace Palaso.WritingSystems.Migration.WritingSystemsLdmlV0To1Migration { public class LdmlAdaptorV0 { private XmlNamespaceManager _nameSpaceManager; public LdmlAdaptorV0() { _nameSpaceManager = MakeNameSpaceManager(); } public void Read(string filePath, WritingSystemDefinitionV0 ws) { if (filePath == null) { throw new ArgumentNullException("filePath"); } if (ws == null) { throw new ArgumentNullException("ws"); } XmlReaderSettings settings = new XmlReaderSettings(); settings.NameTable = _nameSpaceManager.NameTable; settings.ValidationType = ValidationType.None; settings.XmlResolver = null; settings.ProhibitDtd = false; using (XmlReader reader = XmlReader.Create(filePath, settings)) { ReadLdml(reader, ws); } } public void Read(XmlReader xmlReader, WritingSystemDefinitionV0 ws) { if (xmlReader == null) { throw new ArgumentNullException("xmlReader"); } if (ws == null) { throw new ArgumentNullException("ws"); } XmlReaderSettings settings = new XmlReaderSettings(); settings.NameTable = _nameSpaceManager.NameTable; settings.ConformanceLevel = ConformanceLevel.Auto; settings.ValidationType = ValidationType.None; settings.XmlResolver = null; settings.ProhibitDtd = false; using (XmlReader reader = XmlReader.Create(xmlReader, settings)) { ReadLdml(reader, ws); } } private static bool FindElement(XmlReader reader, string name) { return XmlHelpersV0.FindNextElementInSequence(reader, name, LdmlNodeComparerV0.CompareElementNames); } private static bool FindElement(XmlReader reader, string name, string nameSpace) { return XmlHelpersV0.FindNextElementInSequence(reader, name, nameSpace, LdmlNodeComparerV0.CompareElementNames); } private static void WriteLdmlText(XmlWriter writer, string text) { // Not all Unicode characters are valid in an XML document, so we need to create // the <cp hex="X"> elements to replace the invalid characters. // Note: While 0xD (carriage return) is a valid XML character, it is automatically // either dropped or coverted to 0xA by any conforming XML parser, so we also make a <cp> // element for that one. StringBuilder sb = new StringBuilder(text.Length); for (int i=0; i < text.Length; i++) { int code = Char.ConvertToUtf32(text, i); if ((code == 0x9) || (code == 0xA) || (code >= 0x20 && code <= 0xD7FF) || (code >= 0xE000 && code <= 0xFFFD) || (code >= 0x10000 && code <= 0x10FFFF)) { sb.Append(Char.ConvertFromUtf32(code)); } else { writer.WriteString(sb.ToString()); writer.WriteStartElement("cp"); writer.WriteAttributeString("hex", String.Format("{0:X}", code)); writer.WriteEndElement(); sb = new StringBuilder(text.Length - i); } if (Char.IsSurrogatePair(text, i)) { i++; } } writer.WriteString(sb.ToString()); } private void ReadLdml(XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(reader != null); Debug.Assert(ws != null); if (reader.MoveToContent() != XmlNodeType.Element || reader.Name != "ldml") { throw new ApplicationException("Unable to load writing system definition: Missing <ldml> tag."); } reader.Read(); if (FindElement(reader, "identity")) { ReadIdentityElement(reader, ws); } if (FindElement(reader, "layout")) { ReadLayoutElement(reader, ws); } if (FindElement(reader, "collations")) { ReadCollationsElement(reader, ws); } while (FindElement(reader, "special")) { ReadTopLevelSpecialElement(reader, ws); } ws.StoreID = ""; } protected virtual void ReadTopLevelSpecialElement(XmlReader reader, WritingSystemDefinitionV0 ws) { if (reader.GetAttribute("xmlns:palaso") != null) { reader.ReadStartElement("special"); ws.Abbreviation = GetSpecialValue(reader, "palaso", "abbreviation"); ws.DefaultFontName = GetSpecialValue(reader, "palaso", "defaultFontFamily"); float fontSize; if (float.TryParse(GetSpecialValue(reader, "palaso", "defaultFontSize"), out fontSize)) { ws.DefaultFontSize = fontSize; } ws.Keyboard = GetSpecialValue(reader, "palaso", "defaultKeyboard"); string isLegacyEncoded = GetSpecialValue(reader, "palaso", "isLegacyEncoded"); if (!String.IsNullOrEmpty(isLegacyEncoded)) { ws.IsLegacyEncoded = Convert.ToBoolean(isLegacyEncoded); } ws.LanguageName = GetSpecialValue(reader, "palaso", "languageName"); ws.SpellCheckingId = GetSpecialValue(reader, "palaso", "spellCheckingId"); while (reader.NodeType != XmlNodeType.EndElement) { reader.Read(); } reader.ReadEndElement(); } else { reader.Skip(); } } private void ReadIdentityElement(XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(reader.NodeType == XmlNodeType.Element && reader.Name == "identity"); using (XmlReader identityReader = reader.ReadSubtree()) { identityReader.MoveToContent(); identityReader.ReadStartElement("identity"); if (FindElement(identityReader, "version")) { ws.VersionNumber = identityReader.GetAttribute("number") ?? string.Empty; if (!identityReader.IsEmptyElement) { ws.VersionDescription = identityReader.ReadString(); identityReader.ReadEndElement(); } } string dateTime = GetSubNodeAttributeValue(identityReader, "generation", "date"); DateTime modified = DateTime.UtcNow; if (!string.IsNullOrEmpty(dateTime.Trim()) && !DateTime.TryParse(dateTime, out modified)) { //CVS format: "$Date: 2008/06/18 22:52:35 $" modified = DateTime.ParseExact(dateTime, "'$Date: 'yyyy/MM/dd HH:mm:ss $", null, DateTimeStyles.AssumeUniversal); } ws.DateModified = modified; ws.ISO639 = GetSubNodeAttributeValue(identityReader, "language", "type"); ws.Script = GetSubNodeAttributeValue(identityReader, "script", "type"); ws.Region = GetSubNodeAttributeValue(identityReader, "territory", "type"); ws.Variant = GetSubNodeAttributeValue(identityReader, "variant", "type"); // move to end of identity node while (identityReader.Read()) ; } if (!reader.IsEmptyElement) { reader.ReadEndElement(); } } private void ReadLayoutElement(XmlReader reader, WritingSystemDefinitionV0 ws) { // The orientation node has two attributes, "lines" and "characters" which define direction of writing. // The valid values are: "top-to-bottom", "bottom-to-top", "left-to-right", and "right-to-left" // Currently we only handle horizontal character orders with top-to-bottom line order, so // any value other than characters right-to-left, we treat as our default left-to-right order. // This probably works for many scripts such as various East Asian scripts which traditionally // are top-to-bottom characters and right-to-left lines, but can also be written with // left-to-right characters and top-to-bottom lines. Debug.Assert(reader.NodeType == XmlNodeType.Element && reader.Name == "layout"); using (XmlReader layoutReader = reader.ReadSubtree()) { layoutReader.MoveToContent(); layoutReader.ReadStartElement("layout"); ws.RightToLeftScript = GetSubNodeAttributeValue(layoutReader, "orientation", "characters") == "right-to-left"; while (layoutReader.Read()); } if (!reader.IsEmptyElement) { reader.ReadEndElement(); } } private void ReadCollationsElement(XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(reader.NodeType == XmlNodeType.Element && reader.Name == "collations"); using (XmlReader collationsReader = reader.ReadSubtree()) { collationsReader.MoveToContent(); collationsReader.ReadStartElement("collations"); bool found = false; while (FindElement(collationsReader, "collation")) { // having no type is the same as type=standard, and is the only one we're interested in string typeValue = collationsReader.GetAttribute("type"); if (string.IsNullOrEmpty(typeValue) || typeValue == "standard") { found = true; break; } reader.Skip(); } if (found) { reader.MoveToElement(); string collationXml = reader.ReadInnerXml(); ReadCollationElement(collationXml, ws); } while (collationsReader.Read()); } if (!reader.IsEmptyElement) { reader.ReadEndElement(); } } private void ReadCollationElement(string collationXml, WritingSystemDefinitionV0 ws) { Debug.Assert(collationXml != null); Debug.Assert(ws != null); XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.CloseInput = true; readerSettings.ConformanceLevel = ConformanceLevel.Fragment; using (XmlReader collationReader = XmlReader.Create(new StringReader(collationXml), readerSettings)) { if (FindElement(collationReader, "special")) { collationReader.Read(); string rulesTypeAsString = GetSpecialValue(collationReader, "palaso", "sortRulesType"); if (!String.IsNullOrEmpty(rulesTypeAsString)) { ws.SortUsing = (WritingSystemDefinitionV0.SortRulesType)Enum.Parse(typeof(WritingSystemDefinitionV0.SortRulesType), rulesTypeAsString); } } } switch (ws.SortUsing) { case WritingSystemDefinitionV0.SortRulesType.OtherLanguage: ReadCollationRulesForOtherLanguage(collationXml, ws); break; case WritingSystemDefinitionV0.SortRulesType.CustomSimple: ReadCollationRulesForCustomSimple(collationXml, ws); break; case WritingSystemDefinitionV0.SortRulesType.CustomICU: ReadCollationRulesForCustomICU(collationXml, ws); break; case WritingSystemDefinitionV0.SortRulesType.DefaultOrdering: break; default: string message = string.Format("Unhandled SortRulesType '{0}' while writing LDML definition file.", ws.SortUsing); throw new ApplicationException(message); } } private void ReadCollationRulesForOtherLanguage(string collationXml, WritingSystemDefinitionV0 ws) { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.CloseInput = true; readerSettings.ConformanceLevel = ConformanceLevel.Fragment; using (XmlReader collationReader = XmlReader.Create(new StringReader(collationXml), readerSettings)) { bool foundValue = false; if (FindElement(collationReader, "base")) { if (!collationReader.IsEmptyElement && collationReader.ReadToDescendant("alias")) { string sortRules = collationReader.GetAttribute("source"); if (sortRules != null) { ws.SortRules = sortRules; foundValue = true; } } } if (!foundValue) { // missing base alias element, fall back to ICU rules ws.SortUsing = WritingSystemDefinitionV0.SortRulesType.CustomICU; ReadCollationRulesForCustomICU(collationXml, ws); } } } private void ReadCollationRulesForCustomICU(string collationXml, WritingSystemDefinitionV0 ws) { ws.SortRules = LdmlCollationParserV0.GetIcuRulesFromCollationNode(collationXml); } private void ReadCollationRulesForCustomSimple(string collationXml, WritingSystemDefinitionV0 ws) { string rules; if (LdmlCollationParserV0.TryGetSimpleRulesFromCollationNode(collationXml, out rules)) { ws.SortRules = rules; return; } // fall back to ICU rules if Simple rules don't work ws.SortUsing = WritingSystemDefinitionV0.SortRulesType.CustomICU; ReadCollationRulesForCustomICU(collationXml, ws); } public void Write(string filePath, WritingSystemDefinitionV0 ws, Stream oldFile) { if (filePath == null) { throw new ArgumentNullException("filePath"); } if (ws == null) { throw new ArgumentNullException("ws"); } XmlWriterSettings writerSettings = new XmlWriterSettings(); writerSettings.Indent = true; writerSettings.IndentChars = "\t"; writerSettings.NewLineHandling = NewLineHandling.None; XmlReader reader = null; try { if (oldFile != null) { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.NameTable = _nameSpaceManager.NameTable; readerSettings.ConformanceLevel = ConformanceLevel.Auto; readerSettings.ValidationType = ValidationType.None; readerSettings.XmlResolver = null; readerSettings.ProhibitDtd = false; readerSettings.IgnoreWhitespace = true; reader = XmlReader.Create(oldFile, readerSettings); } using (XmlWriter writer = XmlWriter.Create(filePath, CanonicalXmlSettings.CreateXmlWriterSettings())) { writer.WriteStartDocument(); WriteLdml(writer, reader, ws); writer.Close(); } } finally { if (reader != null) { reader.Close(); } } } public void Write(XmlWriter xmlWriter, WritingSystemDefinitionV0 ws, XmlReader xmlReader) { if (xmlWriter == null) { throw new ArgumentNullException("xmlWriter"); } if (ws == null) { throw new ArgumentNullException("ws"); } XmlReader reader = null; try { if (xmlReader != null) { XmlReaderSettings settings = new XmlReaderSettings(); settings.NameTable = _nameSpaceManager.NameTable; settings.ConformanceLevel = ConformanceLevel.Auto; settings.ValidationType = ValidationType.None; settings.XmlResolver = null; settings.ProhibitDtd = false; reader = XmlReader.Create(xmlReader, settings); } WriteLdml(xmlWriter, reader, ws); } finally { if (reader != null) { reader.Close(); } } } private void WriteLdml(XmlWriter writer, XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(writer != null); Debug.Assert(ws != null); writer.WriteStartElement("ldml"); if (reader != null) { reader.MoveToContent(); reader.ReadStartElement("ldml"); CopyUntilElement(writer, reader, "identity"); } WriteIdentityElement(writer, reader, ws); if (reader != null) { CopyUntilElement(writer, reader, "layout"); } WriteLayoutElement(writer, reader, ws); if (reader != null) { CopyUntilElement(writer, reader, "collations"); } WriteCollationsElement(writer, reader, ws); if (reader != null) { CopyUntilElement(writer, reader, "special"); } WriteTopLevelSpecialElements(writer, ws); if (reader != null) { CopyOtherSpecialElements(writer, reader); CopyToEndElement(writer, reader); } writer.WriteEndElement(); } private void CopyUntilElement(XmlWriter writer, XmlReader reader, string elementName) { Debug.Assert(writer != null); Debug.Assert(reader != null); Debug.Assert(!string.IsNullOrEmpty(elementName)); if (reader.NodeType == XmlNodeType.None) { reader.Read(); } while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement && (reader.NodeType != XmlNodeType.Element || LdmlNodeComparerV0.CompareElementNames(reader.Name, elementName) < 0)) { // XmlWriter.WriteNode doesn't do anything if the node type is Attribute if (reader.NodeType == XmlNodeType.Attribute) { writer.WriteAttributes(reader, false); } else { writer.WriteNode(reader, false); } } } private void CopyToEndElement(XmlWriter writer, XmlReader reader) { Debug.Assert(writer != null); Debug.Assert(reader != null); while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement) { // XmlWriter.WriteNode doesn't do anything if the node type is Attribute if (reader.NodeType == XmlNodeType.Attribute) { writer.WriteAttributes(reader, false); } else { writer.WriteNode(reader, false); } } // either read the end element or no-op if EOF reader.Read(); } private void CopyOtherSpecialElements(XmlWriter writer, XmlReader reader) { Debug.Assert(writer != null); Debug.Assert(reader != null); while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement && (reader.NodeType != XmlNodeType.Element || reader.Name == "special")) { if (reader.NodeType == XmlNodeType.Element) { bool knownNS = IsKnownSpecialElement(reader); reader.MoveToElement(); if (knownNS) { reader.Skip(); continue; } } writer.WriteNode(reader, false); } } private bool IsKnownSpecialElement(XmlReader reader) { while (reader.MoveToNextAttribute()) { if (reader.Name.StartsWith("xmlns:") && _nameSpaceManager.HasNamespace(reader.Name.Substring(6, reader.Name.Length - 6))) return true; } return false; } public void FillWithDefaults(string rfc4646, WritingSystemDefinitionV0 ws) { string id = rfc4646.ToLower(); switch (id) { case "en-latn": ws.ISO639 = "en"; ws.LanguageName = "English"; ws.Abbreviation = "eng"; ws.Script = "Latn"; break; default: ws.Script = "Latn"; break; } } protected string GetSpecialValue(XmlReader reader, string ns, string field) { if (!XmlHelpersV0.FindNextElementInSequence(reader, ns + ":" + field, _nameSpaceManager.LookupNamespace(ns), string.Compare)) { return string.Empty; } return reader.GetAttribute("value") ?? string.Empty; } private string GetSubNodeAttributeValue(XmlReader reader, string elementName, string attributeName) { return FindElement(reader, elementName) ? (reader.GetAttribute(attributeName) ?? string.Empty) : string.Empty; } private XmlNamespaceManager MakeNameSpaceManager() { XmlNamespaceManager m = new XmlNamespaceManager(new NameTable()); AddNamespaces(m); return m; } protected virtual void AddNamespaces(XmlNamespaceManager m) { m.AddNamespace("palaso", "urn://palaso.org/ldmlExtensions/v1"); } private void WriteElementWithAttribute(XmlWriter writer, string elementName, string attributeName, string value) { writer.WriteStartElement(elementName); writer.WriteAttributeString(attributeName, value); writer.WriteEndElement(); } protected void WriteSpecialValue(XmlWriter writer, string ns, string field, string value) { if (String.IsNullOrEmpty(value)) { return; } writer.WriteStartElement(field, _nameSpaceManager.LookupNamespace(ns)); writer.WriteAttributeString("value", value); writer.WriteEndElement(); } private void WriteIdentityElement(XmlWriter writer, XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(writer != null); Debug.Assert(ws != null); bool needToCopy = reader != null && reader.NodeType == XmlNodeType.Element && reader.Name == "identity"; writer.WriteStartElement("identity"); writer.WriteStartElement("version"); writer.WriteAttributeString("number", ws.VersionNumber); writer.WriteString(ws.VersionDescription); writer.WriteEndElement(); WriteElementWithAttribute(writer, "generation", "date", String.Format("{0:s}", ws.DateModified)); WriteElementWithAttribute(writer, "language", "type", ws.ISO639); if (!String.IsNullOrEmpty(ws.Script)) { WriteElementWithAttribute(writer, "script", "type", ws.Script); } if (!String.IsNullOrEmpty(ws.Region)) { WriteElementWithAttribute(writer, "territory", "type", ws.Region); } if (!String.IsNullOrEmpty(ws.Variant)) { WriteElementWithAttribute(writer, "variant", "type", ws.Variant); } if (needToCopy) { if (reader.IsEmptyElement) { reader.Skip(); } else { reader.Read(); // move past "identity" element} // <special> is the only node we possibly left out and need to copy FindElement(reader, "special"); CopyToEndElement(writer, reader); } } writer.WriteEndElement(); } private void WriteLayoutElement(XmlWriter writer, XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(writer != null); Debug.Assert(ws != null); bool needToCopy = reader != null && reader.NodeType == XmlNodeType.Element && reader.Name == "identity"; // if we're left-to-right, we don't need to write out default values bool needLayoutElement = ws.RightToLeftScript; if (needLayoutElement) { writer.WriteStartElement("layout"); writer.WriteStartElement("orientation"); // omit default value for "lines" attribute writer.WriteAttributeString("characters", "right-to-left"); writer.WriteEndElement(); } if (needToCopy) { if (reader.IsEmptyElement) { reader.Skip(); } else { reader.Read(); // skip any existing orientation and alias element, and copy the rest if (FindElement(reader, "orientation")) { reader.Skip(); } if (reader.NodeType != XmlNodeType.EndElement && !needLayoutElement) { needLayoutElement = true; writer.WriteStartElement("layout"); } CopyToEndElement(writer, reader); } } if (needLayoutElement) { writer.WriteEndElement(); } } protected void WriteBeginSpecialElement(XmlWriter writer, string ns) { writer.WriteStartElement("special"); writer.WriteAttributeString("xmlns", ns, null, _nameSpaceManager.LookupNamespace(ns)); } protected virtual void WriteTopLevelSpecialElements(XmlWriter writer, WritingSystemDefinitionV0 ws) { WriteBeginSpecialElement(writer, "palaso"); WriteSpecialValue(writer, "palaso", "abbreviation", ws.Abbreviation); WriteSpecialValue(writer, "palaso", "defaultFontFamily", ws.DefaultFontName); if (ws.DefaultFontSize != 0) { WriteSpecialValue(writer, "palaso", "defaultFontSize", ws.DefaultFontSize.ToString()); } WriteSpecialValue(writer, "palaso", "defaultKeyboard", ws.Keyboard); if (ws.IsLegacyEncoded) { WriteSpecialValue(writer, "palaso", "isLegacyEncoded", ws.IsLegacyEncoded.ToString()); } WriteSpecialValue(writer, "palaso", "languageName", ws.LanguageName); if (ws.SpellCheckingId != ws.ISO639) { WriteSpecialValue(writer, "palaso", "spellCheckingId", ws.SpellCheckingId); } writer.WriteEndElement(); } private void WriteCollationsElement(XmlWriter writer, XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(writer != null); Debug.Assert(ws != null); bool needToCopy = reader != null && reader.NodeType == XmlNodeType.Element && reader.Name == "collations"; writer.WriteStartElement("collations"); if (needToCopy) { if (reader.IsEmptyElement) { reader.Skip(); needToCopy = false; } else { reader.ReadStartElement("collations"); if (FindElement(reader, "alias")) { reader.Skip(); } CopyUntilElement(writer, reader, "collation"); } } WriteCollationElement(writer, reader, ws); if (needToCopy) { CopyToEndElement(writer, reader); } writer.WriteEndElement(); } private void WriteCollationElement(XmlWriter writer, XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(writer != null); Debug.Assert(ws != null); bool needToCopy = reader != null && reader.NodeType == XmlNodeType.Element && reader.Name == "collation"; if (needToCopy) { string collationType = reader.GetAttribute("type"); needToCopy = String.IsNullOrEmpty(collationType) || collationType == "standard"; } if (needToCopy && reader.IsEmptyElement) { reader.Skip(); needToCopy = false; } if (ws.SortUsing == WritingSystemDefinitionV0.SortRulesType.DefaultOrdering && !needToCopy) return; if (needToCopy && reader.IsEmptyElement) { reader.Skip(); needToCopy = false; } if (!needToCopy) { // set to null if we don't need to copy to make it easier to tell in the methods we call reader = null; } else { reader.ReadStartElement("collation"); while (reader.NodeType == XmlNodeType.Attribute) { reader.Read(); } } if (ws.SortUsing != WritingSystemDefinitionV0.SortRulesType.DefaultOrdering) { writer.WriteStartElement("collation"); switch (ws.SortUsing) { case WritingSystemDefinitionV0.SortRulesType.OtherLanguage: WriteCollationRulesFromOtherLanguage(writer, reader, ws); break; case WritingSystemDefinitionV0.SortRulesType.CustomSimple: WriteCollationRulesFromCustomSimple(writer, reader, ws); break; case WritingSystemDefinitionV0.SortRulesType.CustomICU: WriteCollationRulesFromCustomICU(writer, reader, ws); break; default: string message = string.Format("Unhandled SortRulesType '{0}' while writing LDML definition file.", ws.SortUsing); throw new ApplicationException(message); } WriteBeginSpecialElement(writer, "palaso"); WriteSpecialValue(writer, "palaso", "sortRulesType", ws.SortUsing.ToString()); writer.WriteEndElement(); if (needToCopy) { if (FindElement(reader, "special")) { CopyOtherSpecialElements(writer, reader); } CopyToEndElement(writer, reader); } writer.WriteEndElement(); } else if (needToCopy) { bool startElementWritten = false; if (FindElement(reader, "special")) { // write out any other special elements while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement && (reader.NodeType != XmlNodeType.Element || reader.Name == "special")) { if (reader.NodeType == XmlNodeType.Element) { bool knownNS = IsKnownSpecialElement(reader); reader.MoveToElement(); if (knownNS) { reader.Skip(); continue; } } if (!startElementWritten) { writer.WriteStartElement("collation"); startElementWritten = true; } writer.WriteNode(reader, false); } } if (!reader.EOF && reader.NodeType != XmlNodeType.EndElement) { // copy any other elements if (!startElementWritten) { writer.WriteStartElement("collation"); startElementWritten = true; } CopyToEndElement(writer, reader); } if (startElementWritten) writer.WriteEndElement(); } } private void WriteCollationRulesFromOtherLanguage(XmlWriter writer, XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(writer != null); Debug.Assert(ws != null); Debug.Assert(ws.SortUsing == WritingSystemDefinitionV0.SortRulesType.OtherLanguage); // Since the alias element gets all information from another source, // we should remove all other elements in this collation element. We // leave "special" elements as they are custom data from some other app. writer.WriteStartElement("base"); WriteElementWithAttribute(writer, "alias", "source", ws.SortRules); writer.WriteEndElement(); if (reader != null) { // don't copy anything, but skip to the 1st special node FindElement(reader, "special"); } } private void WriteCollationRulesFromCustomSimple(XmlWriter writer, XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(writer != null); Debug.Assert(ws != null); Debug.Assert(ws.SortUsing == WritingSystemDefinitionV0.SortRulesType.CustomSimple); string message; // avoid throwing exception, just don't save invalid data if (!SimpleRulesCollator.ValidateSimpleRules(ws.SortRules ?? string.Empty, out message)) { return; } string icu = SimpleRulesCollator.ConvertToIcuRules(ws.SortRules ?? string.Empty); WriteCollationRulesFromICUString(writer, reader, icu); } private void WriteCollationRulesFromCustomICU(XmlWriter writer, XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(writer != null); Debug.Assert(ws != null); Debug.Assert(ws.SortUsing == WritingSystemDefinitionV0.SortRulesType.CustomICU); WriteCollationRulesFromICUString(writer, reader, ws.SortRules); } private void WriteCollationRulesFromICUString(XmlWriter writer, XmlReader reader, string icu) { Debug.Assert(writer != null); icu = icu ?? string.Empty; if (reader != null) { // don't copy any alias that would override our rules if (FindElement(reader, "alias")) { reader.Skip(); } CopyUntilElement(writer, reader, "settings"); // for now we'll omit anything in the suppress_contractions and optimize nodes FindElement(reader, "special"); } IcuRulesParser parser = new IcuRulesParser(false); string message; // avoid throwing exception, just don't save invalid data if (!parser.ValidateIcuRules(icu, out message)) { return; } parser.WriteIcuRules(writer, icu); } //This class is used to load writing systems from ldml. It will allow the ldml adaptor to load //writing systems that are otherwise invalid and give the consumer a chance to fix them up before //loading them into a "real" writing system. private class WritingSystemV0DefinitionForValidationChecking:WritingSystemDefinitionV0 { } } }
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Kodestruct.Common.Entities; using Kodestruct.Common.Section.Interfaces; using Kodestruct.Steel.AISC.Interfaces; using Kodestruct.Common.CalculationLogger.Interfaces; using Kodestruct.Steel.AISC.Interfaces; using Kodestruct.Steel.AISC.Exceptions; using Kodestruct.Steel.AISC.SteelEntities; using Kodestruct.Steel.AISC.SteelEntities.Sections; using Kodestruct.Common.Mathematics; using Kodestruct.Steel.AISC.AISC360v10.K_HSS.TrussConnections; namespace Kodestruct.Steel.AISC.AISC360v10.HSS.TrussConnections { public abstract partial class ChsTrussBranchConnection: HssTrussConnection, IHssTrussBranchConnection { private double _theta; public double theta { get { _theta = thetaMain; return _theta; } set { _theta = value; } } private double _sin_theta; public double sin_theta { get { _sin_theta = Math.Sin(theta.ToRadians()); return _sin_theta; } set { _sin_theta = value; } } /// <summary> /// Width ratio B_b/B /// </summary> private double _beta; protected double beta { get { _beta = Get_beta(); return _beta; } set { _beta = value; } } private double Get_beta() { return D_b / D; } private double _D_b; public double D_b { get { double D_b = 0.0; if (IsMainBranch == true) { D_b = MainBranch.Section.D; } else { D_b = SecondBranch.Section.D; } return _D_b; } set { _D_b = value; } } private double _gamma; /// <summary> /// Chord slenderness ratio /// </summary> protected double gamma { get { _gamma = Get_gamma(); return _gamma; } set { _gamma = value; } } private double Get_gamma() { return D / (2.0 * t); } private double _t; protected double t { get { _t = Chord.Section.t_des; return _t; } set { _t = value; } } protected override double GetF_y() { return Chord.Material.YieldStress; } protected override double GetF_yb() { return MainBranch.Material.YieldStress; } private double _D; public double D { get { _D = Chord.Section.D; return _D; } set { _D = value; } } private double _D_bComp; public double D_bComp { get { _D_bComp = MainBranch.Section.D; return _D_bComp; } set { _D_bComp = value; } } //private double _t_b; //public double t_b //{ // get // { // SteelChsSection br = getBranch(); // _t_b = br.Section.t_des; // return _t_b; // } // set { _t_b = value; } //} private double _t_b; public double t_b { get { SteelChsSection br = getBranch(); _t_b = br.Section.t_des; return _t_b; } set { _t_b = value; } } private double _E; public double E { get { _E = SteelConstants.ModulusOfElasticity; return _E; } set { _E = value; } } protected abstract SteelChsSection getBranch(); } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Student Trips Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class STTRIPSDataSet : EduHubDataSet<STTRIPS> { /// <inheritdoc /> public override string Name { get { return "STTRIPS"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal STTRIPSDataSet(EduHubContext Context) : base(Context) { Index_AM_PICKUP_ADDRESS_ID = new Lazy<NullDictionary<int?, IReadOnlyList<STTRIPS>>>(() => this.ToGroupedNullDictionary(i => i.AM_PICKUP_ADDRESS_ID)); Index_AM_ROUTE_ID = new Lazy<NullDictionary<int?, IReadOnlyList<STTRIPS>>>(() => this.ToGroupedNullDictionary(i => i.AM_ROUTE_ID)); Index_AM_SETDOWN_CAMPUS = new Lazy<NullDictionary<int?, IReadOnlyList<STTRIPS>>>(() => this.ToGroupedNullDictionary(i => i.AM_SETDOWN_CAMPUS)); Index_AM_TRANSPORT_MODE = new Lazy<NullDictionary<int?, IReadOnlyList<STTRIPS>>>(() => this.ToGroupedNullDictionary(i => i.AM_TRANSPORT_MODE)); Index_PM_PICKUP_CAMPUS = new Lazy<NullDictionary<int?, IReadOnlyList<STTRIPS>>>(() => this.ToGroupedNullDictionary(i => i.PM_PICKUP_CAMPUS)); Index_PM_ROUTE_ID = new Lazy<NullDictionary<int?, IReadOnlyList<STTRIPS>>>(() => this.ToGroupedNullDictionary(i => i.PM_ROUTE_ID)); Index_PM_SETDOWN_ADDRESS_ID = new Lazy<NullDictionary<int?, IReadOnlyList<STTRIPS>>>(() => this.ToGroupedNullDictionary(i => i.PM_SETDOWN_ADDRESS_ID)); Index_PM_TRANSPORT_MODE = new Lazy<NullDictionary<int?, IReadOnlyList<STTRIPS>>>(() => this.ToGroupedNullDictionary(i => i.PM_TRANSPORT_MODE)); Index_STUDENT_ID = new Lazy<Dictionary<string, IReadOnlyList<STTRIPS>>>(() => this.ToGroupedDictionary(i => i.STUDENT_ID)); Index_STUDENT_ID_TRAVEL_DAY = new Lazy<Dictionary<Tuple<string, string>, STTRIPS>>(() => this.ToDictionary(i => Tuple.Create(i.STUDENT_ID, i.TRAVEL_DAY))); Index_TID = new Lazy<Dictionary<int, STTRIPS>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="STTRIPS" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="STTRIPS" /> fields for each CSV column header</returns> internal override Action<STTRIPS, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<STTRIPS, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "STUDENT_ID": mapper[i] = (e, v) => e.STUDENT_ID = v; break; case "TRANSPORT_START_DATE": mapper[i] = (e, v) => e.TRANSPORT_START_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "TRANSPORT_END_DATE": mapper[i] = (e, v) => e.TRANSPORT_END_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "TRAVEL_IN_WHEELCHAIR": mapper[i] = (e, v) => e.TRAVEL_IN_WHEELCHAIR = v; break; case "TRAVEL_DAY": mapper[i] = (e, v) => e.TRAVEL_DAY = v; break; case "TRAVEL_NOTES": mapper[i] = (e, v) => e.TRAVEL_NOTES = v; break; case "AM_ROUTE_ID": mapper[i] = (e, v) => e.AM_ROUTE_ID = v == null ? (int?)null : int.Parse(v); break; case "AM_TRANSPORT_MODE": mapper[i] = (e, v) => e.AM_TRANSPORT_MODE = v == null ? (int?)null : int.Parse(v); break; case "AM_ROUTE_EVERY_DAY": mapper[i] = (e, v) => e.AM_ROUTE_EVERY_DAY = v; break; case "AM_PICKUP_TIME": mapper[i] = (e, v) => e.AM_PICKUP_TIME = v == null ? (short?)null : short.Parse(v); break; case "AM_PICKUP_ADDRESS_ID": mapper[i] = (e, v) => e.AM_PICKUP_ADDRESS_ID = v == null ? (int?)null : int.Parse(v); break; case "AM_PICKUP_ADD_SAME_AS_HOME": mapper[i] = (e, v) => e.AM_PICKUP_ADD_SAME_AS_HOME = v; break; case "AM_PICKUP_DIRECTIONS": mapper[i] = (e, v) => e.AM_PICKUP_DIRECTIONS = v; break; case "AM_PICKUP_ADD_MAP_TYPE": mapper[i] = (e, v) => e.AM_PICKUP_ADD_MAP_TYPE = v; break; case "AM_PICKUP_ADD_MAP_NO": mapper[i] = (e, v) => e.AM_PICKUP_ADD_MAP_NO = v; break; case "AM_PICKUP_ADD_MAP_X_REF": mapper[i] = (e, v) => e.AM_PICKUP_ADD_MAP_X_REF = v; break; case "AM_PICKUP_ADD_DESCP": mapper[i] = (e, v) => e.AM_PICKUP_ADD_DESCP = v; break; case "AM_SETDOWN_TIME": mapper[i] = (e, v) => e.AM_SETDOWN_TIME = v == null ? (short?)null : short.Parse(v); break; case "AM_SETDOWN_CAMPUS": mapper[i] = (e, v) => e.AM_SETDOWN_CAMPUS = v == null ? (int?)null : int.Parse(v); break; case "PM_ROUTE_ID": mapper[i] = (e, v) => e.PM_ROUTE_ID = v == null ? (int?)null : int.Parse(v); break; case "PM_TRANSPORT_MODE": mapper[i] = (e, v) => e.PM_TRANSPORT_MODE = v == null ? (int?)null : int.Parse(v); break; case "PM_ROUTE_EVERY_DAY": mapper[i] = (e, v) => e.PM_ROUTE_EVERY_DAY = v; break; case "PM_PICKUP_TIME": mapper[i] = (e, v) => e.PM_PICKUP_TIME = v == null ? (short?)null : short.Parse(v); break; case "PM_PICKUP_CAMPUS": mapper[i] = (e, v) => e.PM_PICKUP_CAMPUS = v == null ? (int?)null : int.Parse(v); break; case "PM_SETDOWN_TIME": mapper[i] = (e, v) => e.PM_SETDOWN_TIME = v == null ? (short?)null : short.Parse(v); break; case "PM_SETDOWN_ADDRESS_ID": mapper[i] = (e, v) => e.PM_SETDOWN_ADDRESS_ID = v == null ? (int?)null : int.Parse(v); break; case "PM_STDWN_AM_PKUP_ADD_SAME": mapper[i] = (e, v) => e.PM_STDWN_AM_PKUP_ADD_SAME = v; break; case "PM_SETDOWN_DIRECTIONS": mapper[i] = (e, v) => e.PM_SETDOWN_DIRECTIONS = v; break; case "PM_SETDOWN_ADD_MAP_TYPE": mapper[i] = (e, v) => e.PM_SETDOWN_ADD_MAP_TYPE = v; break; case "PM_SETDOWN_ADD_MAP_NO": mapper[i] = (e, v) => e.PM_SETDOWN_ADD_MAP_NO = v; break; case "PM_SETDOWN_ADD_MAP_X_REF": mapper[i] = (e, v) => e.PM_SETDOWN_ADD_MAP_X_REF = v; break; case "PM_SETDOWN_ADD_DESCP": mapper[i] = (e, v) => e.PM_SETDOWN_ADD_DESCP = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="STTRIPS" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="STTRIPS" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="STTRIPS" /> entities</param> /// <returns>A merged <see cref="IEnumerable{STTRIPS}"/> of entities</returns> internal override IEnumerable<STTRIPS> ApplyDeltaEntities(IEnumerable<STTRIPS> Entities, List<STTRIPS> DeltaEntities) { HashSet<Tuple<string, string>> Index_STUDENT_ID_TRAVEL_DAY = new HashSet<Tuple<string, string>>(DeltaEntities.Select(i => Tuple.Create(i.STUDENT_ID, i.TRAVEL_DAY))); HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.STUDENT_ID; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = false; overwritten = overwritten || Index_STUDENT_ID_TRAVEL_DAY.Remove(Tuple.Create(entity.STUDENT_ID, entity.TRAVEL_DAY)); overwritten = overwritten || Index_TID.Remove(entity.TID); if (entity.STUDENT_ID.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<int?, IReadOnlyList<STTRIPS>>> Index_AM_PICKUP_ADDRESS_ID; private Lazy<NullDictionary<int?, IReadOnlyList<STTRIPS>>> Index_AM_ROUTE_ID; private Lazy<NullDictionary<int?, IReadOnlyList<STTRIPS>>> Index_AM_SETDOWN_CAMPUS; private Lazy<NullDictionary<int?, IReadOnlyList<STTRIPS>>> Index_AM_TRANSPORT_MODE; private Lazy<NullDictionary<int?, IReadOnlyList<STTRIPS>>> Index_PM_PICKUP_CAMPUS; private Lazy<NullDictionary<int?, IReadOnlyList<STTRIPS>>> Index_PM_ROUTE_ID; private Lazy<NullDictionary<int?, IReadOnlyList<STTRIPS>>> Index_PM_SETDOWN_ADDRESS_ID; private Lazy<NullDictionary<int?, IReadOnlyList<STTRIPS>>> Index_PM_TRANSPORT_MODE; private Lazy<Dictionary<string, IReadOnlyList<STTRIPS>>> Index_STUDENT_ID; private Lazy<Dictionary<Tuple<string, string>, STTRIPS>> Index_STUDENT_ID_TRAVEL_DAY; private Lazy<Dictionary<int, STTRIPS>> Index_TID; #endregion #region Index Methods /// <summary> /// Find STTRIPS by AM_PICKUP_ADDRESS_ID field /// </summary> /// <param name="AM_PICKUP_ADDRESS_ID">AM_PICKUP_ADDRESS_ID value used to find STTRIPS</param> /// <returns>List of related STTRIPS entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STTRIPS> FindByAM_PICKUP_ADDRESS_ID(int? AM_PICKUP_ADDRESS_ID) { return Index_AM_PICKUP_ADDRESS_ID.Value[AM_PICKUP_ADDRESS_ID]; } /// <summary> /// Attempt to find STTRIPS by AM_PICKUP_ADDRESS_ID field /// </summary> /// <param name="AM_PICKUP_ADDRESS_ID">AM_PICKUP_ADDRESS_ID value used to find STTRIPS</param> /// <param name="Value">List of related STTRIPS entities</param> /// <returns>True if the list of related STTRIPS entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByAM_PICKUP_ADDRESS_ID(int? AM_PICKUP_ADDRESS_ID, out IReadOnlyList<STTRIPS> Value) { return Index_AM_PICKUP_ADDRESS_ID.Value.TryGetValue(AM_PICKUP_ADDRESS_ID, out Value); } /// <summary> /// Attempt to find STTRIPS by AM_PICKUP_ADDRESS_ID field /// </summary> /// <param name="AM_PICKUP_ADDRESS_ID">AM_PICKUP_ADDRESS_ID value used to find STTRIPS</param> /// <returns>List of related STTRIPS entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STTRIPS> TryFindByAM_PICKUP_ADDRESS_ID(int? AM_PICKUP_ADDRESS_ID) { IReadOnlyList<STTRIPS> value; if (Index_AM_PICKUP_ADDRESS_ID.Value.TryGetValue(AM_PICKUP_ADDRESS_ID, out value)) { return value; } else { return null; } } /// <summary> /// Find STTRIPS by AM_ROUTE_ID field /// </summary> /// <param name="AM_ROUTE_ID">AM_ROUTE_ID value used to find STTRIPS</param> /// <returns>List of related STTRIPS entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STTRIPS> FindByAM_ROUTE_ID(int? AM_ROUTE_ID) { return Index_AM_ROUTE_ID.Value[AM_ROUTE_ID]; } /// <summary> /// Attempt to find STTRIPS by AM_ROUTE_ID field /// </summary> /// <param name="AM_ROUTE_ID">AM_ROUTE_ID value used to find STTRIPS</param> /// <param name="Value">List of related STTRIPS entities</param> /// <returns>True if the list of related STTRIPS entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByAM_ROUTE_ID(int? AM_ROUTE_ID, out IReadOnlyList<STTRIPS> Value) { return Index_AM_ROUTE_ID.Value.TryGetValue(AM_ROUTE_ID, out Value); } /// <summary> /// Attempt to find STTRIPS by AM_ROUTE_ID field /// </summary> /// <param name="AM_ROUTE_ID">AM_ROUTE_ID value used to find STTRIPS</param> /// <returns>List of related STTRIPS entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STTRIPS> TryFindByAM_ROUTE_ID(int? AM_ROUTE_ID) { IReadOnlyList<STTRIPS> value; if (Index_AM_ROUTE_ID.Value.TryGetValue(AM_ROUTE_ID, out value)) { return value; } else { return null; } } /// <summary> /// Find STTRIPS by AM_SETDOWN_CAMPUS field /// </summary> /// <param name="AM_SETDOWN_CAMPUS">AM_SETDOWN_CAMPUS value used to find STTRIPS</param> /// <returns>List of related STTRIPS entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STTRIPS> FindByAM_SETDOWN_CAMPUS(int? AM_SETDOWN_CAMPUS) { return Index_AM_SETDOWN_CAMPUS.Value[AM_SETDOWN_CAMPUS]; } /// <summary> /// Attempt to find STTRIPS by AM_SETDOWN_CAMPUS field /// </summary> /// <param name="AM_SETDOWN_CAMPUS">AM_SETDOWN_CAMPUS value used to find STTRIPS</param> /// <param name="Value">List of related STTRIPS entities</param> /// <returns>True if the list of related STTRIPS entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByAM_SETDOWN_CAMPUS(int? AM_SETDOWN_CAMPUS, out IReadOnlyList<STTRIPS> Value) { return Index_AM_SETDOWN_CAMPUS.Value.TryGetValue(AM_SETDOWN_CAMPUS, out Value); } /// <summary> /// Attempt to find STTRIPS by AM_SETDOWN_CAMPUS field /// </summary> /// <param name="AM_SETDOWN_CAMPUS">AM_SETDOWN_CAMPUS value used to find STTRIPS</param> /// <returns>List of related STTRIPS entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STTRIPS> TryFindByAM_SETDOWN_CAMPUS(int? AM_SETDOWN_CAMPUS) { IReadOnlyList<STTRIPS> value; if (Index_AM_SETDOWN_CAMPUS.Value.TryGetValue(AM_SETDOWN_CAMPUS, out value)) { return value; } else { return null; } } /// <summary> /// Find STTRIPS by AM_TRANSPORT_MODE field /// </summary> /// <param name="AM_TRANSPORT_MODE">AM_TRANSPORT_MODE value used to find STTRIPS</param> /// <returns>List of related STTRIPS entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STTRIPS> FindByAM_TRANSPORT_MODE(int? AM_TRANSPORT_MODE) { return Index_AM_TRANSPORT_MODE.Value[AM_TRANSPORT_MODE]; } /// <summary> /// Attempt to find STTRIPS by AM_TRANSPORT_MODE field /// </summary> /// <param name="AM_TRANSPORT_MODE">AM_TRANSPORT_MODE value used to find STTRIPS</param> /// <param name="Value">List of related STTRIPS entities</param> /// <returns>True if the list of related STTRIPS entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByAM_TRANSPORT_MODE(int? AM_TRANSPORT_MODE, out IReadOnlyList<STTRIPS> Value) { return Index_AM_TRANSPORT_MODE.Value.TryGetValue(AM_TRANSPORT_MODE, out Value); } /// <summary> /// Attempt to find STTRIPS by AM_TRANSPORT_MODE field /// </summary> /// <param name="AM_TRANSPORT_MODE">AM_TRANSPORT_MODE value used to find STTRIPS</param> /// <returns>List of related STTRIPS entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STTRIPS> TryFindByAM_TRANSPORT_MODE(int? AM_TRANSPORT_MODE) { IReadOnlyList<STTRIPS> value; if (Index_AM_TRANSPORT_MODE.Value.TryGetValue(AM_TRANSPORT_MODE, out value)) { return value; } else { return null; } } /// <summary> /// Find STTRIPS by PM_PICKUP_CAMPUS field /// </summary> /// <param name="PM_PICKUP_CAMPUS">PM_PICKUP_CAMPUS value used to find STTRIPS</param> /// <returns>List of related STTRIPS entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STTRIPS> FindByPM_PICKUP_CAMPUS(int? PM_PICKUP_CAMPUS) { return Index_PM_PICKUP_CAMPUS.Value[PM_PICKUP_CAMPUS]; } /// <summary> /// Attempt to find STTRIPS by PM_PICKUP_CAMPUS field /// </summary> /// <param name="PM_PICKUP_CAMPUS">PM_PICKUP_CAMPUS value used to find STTRIPS</param> /// <param name="Value">List of related STTRIPS entities</param> /// <returns>True if the list of related STTRIPS entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByPM_PICKUP_CAMPUS(int? PM_PICKUP_CAMPUS, out IReadOnlyList<STTRIPS> Value) { return Index_PM_PICKUP_CAMPUS.Value.TryGetValue(PM_PICKUP_CAMPUS, out Value); } /// <summary> /// Attempt to find STTRIPS by PM_PICKUP_CAMPUS field /// </summary> /// <param name="PM_PICKUP_CAMPUS">PM_PICKUP_CAMPUS value used to find STTRIPS</param> /// <returns>List of related STTRIPS entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STTRIPS> TryFindByPM_PICKUP_CAMPUS(int? PM_PICKUP_CAMPUS) { IReadOnlyList<STTRIPS> value; if (Index_PM_PICKUP_CAMPUS.Value.TryGetValue(PM_PICKUP_CAMPUS, out value)) { return value; } else { return null; } } /// <summary> /// Find STTRIPS by PM_ROUTE_ID field /// </summary> /// <param name="PM_ROUTE_ID">PM_ROUTE_ID value used to find STTRIPS</param> /// <returns>List of related STTRIPS entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STTRIPS> FindByPM_ROUTE_ID(int? PM_ROUTE_ID) { return Index_PM_ROUTE_ID.Value[PM_ROUTE_ID]; } /// <summary> /// Attempt to find STTRIPS by PM_ROUTE_ID field /// </summary> /// <param name="PM_ROUTE_ID">PM_ROUTE_ID value used to find STTRIPS</param> /// <param name="Value">List of related STTRIPS entities</param> /// <returns>True if the list of related STTRIPS entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByPM_ROUTE_ID(int? PM_ROUTE_ID, out IReadOnlyList<STTRIPS> Value) { return Index_PM_ROUTE_ID.Value.TryGetValue(PM_ROUTE_ID, out Value); } /// <summary> /// Attempt to find STTRIPS by PM_ROUTE_ID field /// </summary> /// <param name="PM_ROUTE_ID">PM_ROUTE_ID value used to find STTRIPS</param> /// <returns>List of related STTRIPS entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STTRIPS> TryFindByPM_ROUTE_ID(int? PM_ROUTE_ID) { IReadOnlyList<STTRIPS> value; if (Index_PM_ROUTE_ID.Value.TryGetValue(PM_ROUTE_ID, out value)) { return value; } else { return null; } } /// <summary> /// Find STTRIPS by PM_SETDOWN_ADDRESS_ID field /// </summary> /// <param name="PM_SETDOWN_ADDRESS_ID">PM_SETDOWN_ADDRESS_ID value used to find STTRIPS</param> /// <returns>List of related STTRIPS entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STTRIPS> FindByPM_SETDOWN_ADDRESS_ID(int? PM_SETDOWN_ADDRESS_ID) { return Index_PM_SETDOWN_ADDRESS_ID.Value[PM_SETDOWN_ADDRESS_ID]; } /// <summary> /// Attempt to find STTRIPS by PM_SETDOWN_ADDRESS_ID field /// </summary> /// <param name="PM_SETDOWN_ADDRESS_ID">PM_SETDOWN_ADDRESS_ID value used to find STTRIPS</param> /// <param name="Value">List of related STTRIPS entities</param> /// <returns>True if the list of related STTRIPS entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByPM_SETDOWN_ADDRESS_ID(int? PM_SETDOWN_ADDRESS_ID, out IReadOnlyList<STTRIPS> Value) { return Index_PM_SETDOWN_ADDRESS_ID.Value.TryGetValue(PM_SETDOWN_ADDRESS_ID, out Value); } /// <summary> /// Attempt to find STTRIPS by PM_SETDOWN_ADDRESS_ID field /// </summary> /// <param name="PM_SETDOWN_ADDRESS_ID">PM_SETDOWN_ADDRESS_ID value used to find STTRIPS</param> /// <returns>List of related STTRIPS entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STTRIPS> TryFindByPM_SETDOWN_ADDRESS_ID(int? PM_SETDOWN_ADDRESS_ID) { IReadOnlyList<STTRIPS> value; if (Index_PM_SETDOWN_ADDRESS_ID.Value.TryGetValue(PM_SETDOWN_ADDRESS_ID, out value)) { return value; } else { return null; } } /// <summary> /// Find STTRIPS by PM_TRANSPORT_MODE field /// </summary> /// <param name="PM_TRANSPORT_MODE">PM_TRANSPORT_MODE value used to find STTRIPS</param> /// <returns>List of related STTRIPS entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STTRIPS> FindByPM_TRANSPORT_MODE(int? PM_TRANSPORT_MODE) { return Index_PM_TRANSPORT_MODE.Value[PM_TRANSPORT_MODE]; } /// <summary> /// Attempt to find STTRIPS by PM_TRANSPORT_MODE field /// </summary> /// <param name="PM_TRANSPORT_MODE">PM_TRANSPORT_MODE value used to find STTRIPS</param> /// <param name="Value">List of related STTRIPS entities</param> /// <returns>True if the list of related STTRIPS entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByPM_TRANSPORT_MODE(int? PM_TRANSPORT_MODE, out IReadOnlyList<STTRIPS> Value) { return Index_PM_TRANSPORT_MODE.Value.TryGetValue(PM_TRANSPORT_MODE, out Value); } /// <summary> /// Attempt to find STTRIPS by PM_TRANSPORT_MODE field /// </summary> /// <param name="PM_TRANSPORT_MODE">PM_TRANSPORT_MODE value used to find STTRIPS</param> /// <returns>List of related STTRIPS entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STTRIPS> TryFindByPM_TRANSPORT_MODE(int? PM_TRANSPORT_MODE) { IReadOnlyList<STTRIPS> value; if (Index_PM_TRANSPORT_MODE.Value.TryGetValue(PM_TRANSPORT_MODE, out value)) { return value; } else { return null; } } /// <summary> /// Find STTRIPS by STUDENT_ID field /// </summary> /// <param name="STUDENT_ID">STUDENT_ID value used to find STTRIPS</param> /// <returns>List of related STTRIPS entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STTRIPS> FindBySTUDENT_ID(string STUDENT_ID) { return Index_STUDENT_ID.Value[STUDENT_ID]; } /// <summary> /// Attempt to find STTRIPS by STUDENT_ID field /// </summary> /// <param name="STUDENT_ID">STUDENT_ID value used to find STTRIPS</param> /// <param name="Value">List of related STTRIPS entities</param> /// <returns>True if the list of related STTRIPS entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySTUDENT_ID(string STUDENT_ID, out IReadOnlyList<STTRIPS> Value) { return Index_STUDENT_ID.Value.TryGetValue(STUDENT_ID, out Value); } /// <summary> /// Attempt to find STTRIPS by STUDENT_ID field /// </summary> /// <param name="STUDENT_ID">STUDENT_ID value used to find STTRIPS</param> /// <returns>List of related STTRIPS entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STTRIPS> TryFindBySTUDENT_ID(string STUDENT_ID) { IReadOnlyList<STTRIPS> value; if (Index_STUDENT_ID.Value.TryGetValue(STUDENT_ID, out value)) { return value; } else { return null; } } /// <summary> /// Find STTRIPS by STUDENT_ID and TRAVEL_DAY fields /// </summary> /// <param name="STUDENT_ID">STUDENT_ID value used to find STTRIPS</param> /// <param name="TRAVEL_DAY">TRAVEL_DAY value used to find STTRIPS</param> /// <returns>Related STTRIPS entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public STTRIPS FindBySTUDENT_ID_TRAVEL_DAY(string STUDENT_ID, string TRAVEL_DAY) { return Index_STUDENT_ID_TRAVEL_DAY.Value[Tuple.Create(STUDENT_ID, TRAVEL_DAY)]; } /// <summary> /// Attempt to find STTRIPS by STUDENT_ID and TRAVEL_DAY fields /// </summary> /// <param name="STUDENT_ID">STUDENT_ID value used to find STTRIPS</param> /// <param name="TRAVEL_DAY">TRAVEL_DAY value used to find STTRIPS</param> /// <param name="Value">Related STTRIPS entity</param> /// <returns>True if the related STTRIPS entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySTUDENT_ID_TRAVEL_DAY(string STUDENT_ID, string TRAVEL_DAY, out STTRIPS Value) { return Index_STUDENT_ID_TRAVEL_DAY.Value.TryGetValue(Tuple.Create(STUDENT_ID, TRAVEL_DAY), out Value); } /// <summary> /// Attempt to find STTRIPS by STUDENT_ID and TRAVEL_DAY fields /// </summary> /// <param name="STUDENT_ID">STUDENT_ID value used to find STTRIPS</param> /// <param name="TRAVEL_DAY">TRAVEL_DAY value used to find STTRIPS</param> /// <returns>Related STTRIPS entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public STTRIPS TryFindBySTUDENT_ID_TRAVEL_DAY(string STUDENT_ID, string TRAVEL_DAY) { STTRIPS value; if (Index_STUDENT_ID_TRAVEL_DAY.Value.TryGetValue(Tuple.Create(STUDENT_ID, TRAVEL_DAY), out value)) { return value; } else { return null; } } /// <summary> /// Find STTRIPS by TID field /// </summary> /// <param name="TID">TID value used to find STTRIPS</param> /// <returns>Related STTRIPS entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public STTRIPS FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find STTRIPS by TID field /// </summary> /// <param name="TID">TID value used to find STTRIPS</param> /// <param name="Value">Related STTRIPS entity</param> /// <returns>True if the related STTRIPS entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out STTRIPS Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find STTRIPS by TID field /// </summary> /// <param name="TID">TID value used to find STTRIPS</param> /// <returns>Related STTRIPS entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public STTRIPS TryFindByTID(int TID) { STTRIPS value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a STTRIPS table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[STTRIPS]( [TID] int IDENTITY NOT NULL, [STUDENT_ID] varchar(10) NOT NULL, [TRANSPORT_START_DATE] datetime NULL, [TRANSPORT_END_DATE] datetime NULL, [TRAVEL_IN_WHEELCHAIR] varchar(1) NULL, [TRAVEL_DAY] varchar(2) NULL, [TRAVEL_NOTES] varchar(MAX) NULL, [AM_ROUTE_ID] int NULL, [AM_TRANSPORT_MODE] int NULL, [AM_ROUTE_EVERY_DAY] varchar(1) NULL, [AM_PICKUP_TIME] smallint NULL, [AM_PICKUP_ADDRESS_ID] int NULL, [AM_PICKUP_ADD_SAME_AS_HOME] varchar(1) NULL, [AM_PICKUP_DIRECTIONS] varchar(2) NULL, [AM_PICKUP_ADD_MAP_TYPE] varchar(1) NULL, [AM_PICKUP_ADD_MAP_NO] varchar(4) NULL, [AM_PICKUP_ADD_MAP_X_REF] varchar(4) NULL, [AM_PICKUP_ADD_DESCP] varchar(MAX) NULL, [AM_SETDOWN_TIME] smallint NULL, [AM_SETDOWN_CAMPUS] int NULL, [PM_ROUTE_ID] int NULL, [PM_TRANSPORT_MODE] int NULL, [PM_ROUTE_EVERY_DAY] varchar(1) NULL, [PM_PICKUP_TIME] smallint NULL, [PM_PICKUP_CAMPUS] int NULL, [PM_SETDOWN_TIME] smallint NULL, [PM_SETDOWN_ADDRESS_ID] int NULL, [PM_STDWN_AM_PKUP_ADD_SAME] varchar(1) NULL, [PM_SETDOWN_DIRECTIONS] varchar(2) NULL, [PM_SETDOWN_ADD_MAP_TYPE] varchar(1) NULL, [PM_SETDOWN_ADD_MAP_NO] varchar(4) NULL, [PM_SETDOWN_ADD_MAP_X_REF] varchar(4) NULL, [PM_SETDOWN_ADD_DESCP] varchar(MAX) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [STTRIPS_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE NONCLUSTERED INDEX [STTRIPS_Index_AM_PICKUP_ADDRESS_ID] ON [dbo].[STTRIPS] ( [AM_PICKUP_ADDRESS_ID] ASC ); CREATE NONCLUSTERED INDEX [STTRIPS_Index_AM_ROUTE_ID] ON [dbo].[STTRIPS] ( [AM_ROUTE_ID] ASC ); CREATE NONCLUSTERED INDEX [STTRIPS_Index_AM_SETDOWN_CAMPUS] ON [dbo].[STTRIPS] ( [AM_SETDOWN_CAMPUS] ASC ); CREATE NONCLUSTERED INDEX [STTRIPS_Index_AM_TRANSPORT_MODE] ON [dbo].[STTRIPS] ( [AM_TRANSPORT_MODE] ASC ); CREATE NONCLUSTERED INDEX [STTRIPS_Index_PM_PICKUP_CAMPUS] ON [dbo].[STTRIPS] ( [PM_PICKUP_CAMPUS] ASC ); CREATE NONCLUSTERED INDEX [STTRIPS_Index_PM_ROUTE_ID] ON [dbo].[STTRIPS] ( [PM_ROUTE_ID] ASC ); CREATE NONCLUSTERED INDEX [STTRIPS_Index_PM_SETDOWN_ADDRESS_ID] ON [dbo].[STTRIPS] ( [PM_SETDOWN_ADDRESS_ID] ASC ); CREATE NONCLUSTERED INDEX [STTRIPS_Index_PM_TRANSPORT_MODE] ON [dbo].[STTRIPS] ( [PM_TRANSPORT_MODE] ASC ); CREATE CLUSTERED INDEX [STTRIPS_Index_STUDENT_ID] ON [dbo].[STTRIPS] ( [STUDENT_ID] ASC ); CREATE NONCLUSTERED INDEX [STTRIPS_Index_STUDENT_ID_TRAVEL_DAY] ON [dbo].[STTRIPS] ( [STUDENT_ID] ASC, [TRAVEL_DAY] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_AM_PICKUP_ADDRESS_ID') ALTER INDEX [STTRIPS_Index_AM_PICKUP_ADDRESS_ID] ON [dbo].[STTRIPS] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_AM_ROUTE_ID') ALTER INDEX [STTRIPS_Index_AM_ROUTE_ID] ON [dbo].[STTRIPS] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_AM_SETDOWN_CAMPUS') ALTER INDEX [STTRIPS_Index_AM_SETDOWN_CAMPUS] ON [dbo].[STTRIPS] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_AM_TRANSPORT_MODE') ALTER INDEX [STTRIPS_Index_AM_TRANSPORT_MODE] ON [dbo].[STTRIPS] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_PM_PICKUP_CAMPUS') ALTER INDEX [STTRIPS_Index_PM_PICKUP_CAMPUS] ON [dbo].[STTRIPS] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_PM_ROUTE_ID') ALTER INDEX [STTRIPS_Index_PM_ROUTE_ID] ON [dbo].[STTRIPS] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_PM_SETDOWN_ADDRESS_ID') ALTER INDEX [STTRIPS_Index_PM_SETDOWN_ADDRESS_ID] ON [dbo].[STTRIPS] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_PM_TRANSPORT_MODE') ALTER INDEX [STTRIPS_Index_PM_TRANSPORT_MODE] ON [dbo].[STTRIPS] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_STUDENT_ID_TRAVEL_DAY') ALTER INDEX [STTRIPS_Index_STUDENT_ID_TRAVEL_DAY] ON [dbo].[STTRIPS] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_TID') ALTER INDEX [STTRIPS_Index_TID] ON [dbo].[STTRIPS] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_AM_PICKUP_ADDRESS_ID') ALTER INDEX [STTRIPS_Index_AM_PICKUP_ADDRESS_ID] ON [dbo].[STTRIPS] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_AM_ROUTE_ID') ALTER INDEX [STTRIPS_Index_AM_ROUTE_ID] ON [dbo].[STTRIPS] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_AM_SETDOWN_CAMPUS') ALTER INDEX [STTRIPS_Index_AM_SETDOWN_CAMPUS] ON [dbo].[STTRIPS] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_AM_TRANSPORT_MODE') ALTER INDEX [STTRIPS_Index_AM_TRANSPORT_MODE] ON [dbo].[STTRIPS] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_PM_PICKUP_CAMPUS') ALTER INDEX [STTRIPS_Index_PM_PICKUP_CAMPUS] ON [dbo].[STTRIPS] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_PM_ROUTE_ID') ALTER INDEX [STTRIPS_Index_PM_ROUTE_ID] ON [dbo].[STTRIPS] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_PM_SETDOWN_ADDRESS_ID') ALTER INDEX [STTRIPS_Index_PM_SETDOWN_ADDRESS_ID] ON [dbo].[STTRIPS] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_PM_TRANSPORT_MODE') ALTER INDEX [STTRIPS_Index_PM_TRANSPORT_MODE] ON [dbo].[STTRIPS] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_STUDENT_ID_TRAVEL_DAY') ALTER INDEX [STTRIPS_Index_STUDENT_ID_TRAVEL_DAY] ON [dbo].[STTRIPS] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STTRIPS]') AND name = N'STTRIPS_Index_TID') ALTER INDEX [STTRIPS_Index_TID] ON [dbo].[STTRIPS] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="STTRIPS"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="STTRIPS"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<STTRIPS> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<Tuple<string, string>> Index_STUDENT_ID_TRAVEL_DAY = new List<Tuple<string, string>>(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_STUDENT_ID_TRAVEL_DAY.Add(Tuple.Create(entity.STUDENT_ID, entity.TRAVEL_DAY)); Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[STTRIPS] WHERE"); // Index_STUDENT_ID_TRAVEL_DAY builder.Append("("); for (int index = 0; index < Index_STUDENT_ID_TRAVEL_DAY.Count; index++) { if (index != 0) builder.Append(" OR "); // STUDENT_ID var parameterSTUDENT_ID = $"@p{parameterIndex++}"; builder.Append("([STUDENT_ID]=").Append(parameterSTUDENT_ID); command.Parameters.Add(parameterSTUDENT_ID, SqlDbType.VarChar, 10).Value = Index_STUDENT_ID_TRAVEL_DAY[index].Item1; // TRAVEL_DAY if (Index_STUDENT_ID_TRAVEL_DAY[index].Item2 == null) { builder.Append(" AND [TRAVEL_DAY] IS NULL)"); } else { var parameterTRAVEL_DAY = $"@p{parameterIndex++}"; builder.Append(" AND [TRAVEL_DAY]=").Append(parameterTRAVEL_DAY).Append(")"); command.Parameters.Add(parameterTRAVEL_DAY, SqlDbType.VarChar, 2).Value = Index_STUDENT_ID_TRAVEL_DAY[index].Item2; } } builder.AppendLine(") OR"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the STTRIPS data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the STTRIPS data set</returns> public override EduHubDataSetDataReader<STTRIPS> GetDataSetDataReader() { return new STTRIPSDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the STTRIPS data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the STTRIPS data set</returns> public override EduHubDataSetDataReader<STTRIPS> GetDataSetDataReader(List<STTRIPS> Entities) { return new STTRIPSDataReader(new EduHubDataSetLoadedReader<STTRIPS>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class STTRIPSDataReader : EduHubDataSetDataReader<STTRIPS> { public STTRIPSDataReader(IEduHubDataSetReader<STTRIPS> Reader) : base (Reader) { } public override int FieldCount { get { return 36; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // STUDENT_ID return Current.STUDENT_ID; case 2: // TRANSPORT_START_DATE return Current.TRANSPORT_START_DATE; case 3: // TRANSPORT_END_DATE return Current.TRANSPORT_END_DATE; case 4: // TRAVEL_IN_WHEELCHAIR return Current.TRAVEL_IN_WHEELCHAIR; case 5: // TRAVEL_DAY return Current.TRAVEL_DAY; case 6: // TRAVEL_NOTES return Current.TRAVEL_NOTES; case 7: // AM_ROUTE_ID return Current.AM_ROUTE_ID; case 8: // AM_TRANSPORT_MODE return Current.AM_TRANSPORT_MODE; case 9: // AM_ROUTE_EVERY_DAY return Current.AM_ROUTE_EVERY_DAY; case 10: // AM_PICKUP_TIME return Current.AM_PICKUP_TIME; case 11: // AM_PICKUP_ADDRESS_ID return Current.AM_PICKUP_ADDRESS_ID; case 12: // AM_PICKUP_ADD_SAME_AS_HOME return Current.AM_PICKUP_ADD_SAME_AS_HOME; case 13: // AM_PICKUP_DIRECTIONS return Current.AM_PICKUP_DIRECTIONS; case 14: // AM_PICKUP_ADD_MAP_TYPE return Current.AM_PICKUP_ADD_MAP_TYPE; case 15: // AM_PICKUP_ADD_MAP_NO return Current.AM_PICKUP_ADD_MAP_NO; case 16: // AM_PICKUP_ADD_MAP_X_REF return Current.AM_PICKUP_ADD_MAP_X_REF; case 17: // AM_PICKUP_ADD_DESCP return Current.AM_PICKUP_ADD_DESCP; case 18: // AM_SETDOWN_TIME return Current.AM_SETDOWN_TIME; case 19: // AM_SETDOWN_CAMPUS return Current.AM_SETDOWN_CAMPUS; case 20: // PM_ROUTE_ID return Current.PM_ROUTE_ID; case 21: // PM_TRANSPORT_MODE return Current.PM_TRANSPORT_MODE; case 22: // PM_ROUTE_EVERY_DAY return Current.PM_ROUTE_EVERY_DAY; case 23: // PM_PICKUP_TIME return Current.PM_PICKUP_TIME; case 24: // PM_PICKUP_CAMPUS return Current.PM_PICKUP_CAMPUS; case 25: // PM_SETDOWN_TIME return Current.PM_SETDOWN_TIME; case 26: // PM_SETDOWN_ADDRESS_ID return Current.PM_SETDOWN_ADDRESS_ID; case 27: // PM_STDWN_AM_PKUP_ADD_SAME return Current.PM_STDWN_AM_PKUP_ADD_SAME; case 28: // PM_SETDOWN_DIRECTIONS return Current.PM_SETDOWN_DIRECTIONS; case 29: // PM_SETDOWN_ADD_MAP_TYPE return Current.PM_SETDOWN_ADD_MAP_TYPE; case 30: // PM_SETDOWN_ADD_MAP_NO return Current.PM_SETDOWN_ADD_MAP_NO; case 31: // PM_SETDOWN_ADD_MAP_X_REF return Current.PM_SETDOWN_ADD_MAP_X_REF; case 32: // PM_SETDOWN_ADD_DESCP return Current.PM_SETDOWN_ADD_DESCP; case 33: // LW_DATE return Current.LW_DATE; case 34: // LW_TIME return Current.LW_TIME; case 35: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // TRANSPORT_START_DATE return Current.TRANSPORT_START_DATE == null; case 3: // TRANSPORT_END_DATE return Current.TRANSPORT_END_DATE == null; case 4: // TRAVEL_IN_WHEELCHAIR return Current.TRAVEL_IN_WHEELCHAIR == null; case 5: // TRAVEL_DAY return Current.TRAVEL_DAY == null; case 6: // TRAVEL_NOTES return Current.TRAVEL_NOTES == null; case 7: // AM_ROUTE_ID return Current.AM_ROUTE_ID == null; case 8: // AM_TRANSPORT_MODE return Current.AM_TRANSPORT_MODE == null; case 9: // AM_ROUTE_EVERY_DAY return Current.AM_ROUTE_EVERY_DAY == null; case 10: // AM_PICKUP_TIME return Current.AM_PICKUP_TIME == null; case 11: // AM_PICKUP_ADDRESS_ID return Current.AM_PICKUP_ADDRESS_ID == null; case 12: // AM_PICKUP_ADD_SAME_AS_HOME return Current.AM_PICKUP_ADD_SAME_AS_HOME == null; case 13: // AM_PICKUP_DIRECTIONS return Current.AM_PICKUP_DIRECTIONS == null; case 14: // AM_PICKUP_ADD_MAP_TYPE return Current.AM_PICKUP_ADD_MAP_TYPE == null; case 15: // AM_PICKUP_ADD_MAP_NO return Current.AM_PICKUP_ADD_MAP_NO == null; case 16: // AM_PICKUP_ADD_MAP_X_REF return Current.AM_PICKUP_ADD_MAP_X_REF == null; case 17: // AM_PICKUP_ADD_DESCP return Current.AM_PICKUP_ADD_DESCP == null; case 18: // AM_SETDOWN_TIME return Current.AM_SETDOWN_TIME == null; case 19: // AM_SETDOWN_CAMPUS return Current.AM_SETDOWN_CAMPUS == null; case 20: // PM_ROUTE_ID return Current.PM_ROUTE_ID == null; case 21: // PM_TRANSPORT_MODE return Current.PM_TRANSPORT_MODE == null; case 22: // PM_ROUTE_EVERY_DAY return Current.PM_ROUTE_EVERY_DAY == null; case 23: // PM_PICKUP_TIME return Current.PM_PICKUP_TIME == null; case 24: // PM_PICKUP_CAMPUS return Current.PM_PICKUP_CAMPUS == null; case 25: // PM_SETDOWN_TIME return Current.PM_SETDOWN_TIME == null; case 26: // PM_SETDOWN_ADDRESS_ID return Current.PM_SETDOWN_ADDRESS_ID == null; case 27: // PM_STDWN_AM_PKUP_ADD_SAME return Current.PM_STDWN_AM_PKUP_ADD_SAME == null; case 28: // PM_SETDOWN_DIRECTIONS return Current.PM_SETDOWN_DIRECTIONS == null; case 29: // PM_SETDOWN_ADD_MAP_TYPE return Current.PM_SETDOWN_ADD_MAP_TYPE == null; case 30: // PM_SETDOWN_ADD_MAP_NO return Current.PM_SETDOWN_ADD_MAP_NO == null; case 31: // PM_SETDOWN_ADD_MAP_X_REF return Current.PM_SETDOWN_ADD_MAP_X_REF == null; case 32: // PM_SETDOWN_ADD_DESCP return Current.PM_SETDOWN_ADD_DESCP == null; case 33: // LW_DATE return Current.LW_DATE == null; case 34: // LW_TIME return Current.LW_TIME == null; case 35: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // STUDENT_ID return "STUDENT_ID"; case 2: // TRANSPORT_START_DATE return "TRANSPORT_START_DATE"; case 3: // TRANSPORT_END_DATE return "TRANSPORT_END_DATE"; case 4: // TRAVEL_IN_WHEELCHAIR return "TRAVEL_IN_WHEELCHAIR"; case 5: // TRAVEL_DAY return "TRAVEL_DAY"; case 6: // TRAVEL_NOTES return "TRAVEL_NOTES"; case 7: // AM_ROUTE_ID return "AM_ROUTE_ID"; case 8: // AM_TRANSPORT_MODE return "AM_TRANSPORT_MODE"; case 9: // AM_ROUTE_EVERY_DAY return "AM_ROUTE_EVERY_DAY"; case 10: // AM_PICKUP_TIME return "AM_PICKUP_TIME"; case 11: // AM_PICKUP_ADDRESS_ID return "AM_PICKUP_ADDRESS_ID"; case 12: // AM_PICKUP_ADD_SAME_AS_HOME return "AM_PICKUP_ADD_SAME_AS_HOME"; case 13: // AM_PICKUP_DIRECTIONS return "AM_PICKUP_DIRECTIONS"; case 14: // AM_PICKUP_ADD_MAP_TYPE return "AM_PICKUP_ADD_MAP_TYPE"; case 15: // AM_PICKUP_ADD_MAP_NO return "AM_PICKUP_ADD_MAP_NO"; case 16: // AM_PICKUP_ADD_MAP_X_REF return "AM_PICKUP_ADD_MAP_X_REF"; case 17: // AM_PICKUP_ADD_DESCP return "AM_PICKUP_ADD_DESCP"; case 18: // AM_SETDOWN_TIME return "AM_SETDOWN_TIME"; case 19: // AM_SETDOWN_CAMPUS return "AM_SETDOWN_CAMPUS"; case 20: // PM_ROUTE_ID return "PM_ROUTE_ID"; case 21: // PM_TRANSPORT_MODE return "PM_TRANSPORT_MODE"; case 22: // PM_ROUTE_EVERY_DAY return "PM_ROUTE_EVERY_DAY"; case 23: // PM_PICKUP_TIME return "PM_PICKUP_TIME"; case 24: // PM_PICKUP_CAMPUS return "PM_PICKUP_CAMPUS"; case 25: // PM_SETDOWN_TIME return "PM_SETDOWN_TIME"; case 26: // PM_SETDOWN_ADDRESS_ID return "PM_SETDOWN_ADDRESS_ID"; case 27: // PM_STDWN_AM_PKUP_ADD_SAME return "PM_STDWN_AM_PKUP_ADD_SAME"; case 28: // PM_SETDOWN_DIRECTIONS return "PM_SETDOWN_DIRECTIONS"; case 29: // PM_SETDOWN_ADD_MAP_TYPE return "PM_SETDOWN_ADD_MAP_TYPE"; case 30: // PM_SETDOWN_ADD_MAP_NO return "PM_SETDOWN_ADD_MAP_NO"; case 31: // PM_SETDOWN_ADD_MAP_X_REF return "PM_SETDOWN_ADD_MAP_X_REF"; case 32: // PM_SETDOWN_ADD_DESCP return "PM_SETDOWN_ADD_DESCP"; case 33: // LW_DATE return "LW_DATE"; case 34: // LW_TIME return "LW_TIME"; case 35: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "STUDENT_ID": return 1; case "TRANSPORT_START_DATE": return 2; case "TRANSPORT_END_DATE": return 3; case "TRAVEL_IN_WHEELCHAIR": return 4; case "TRAVEL_DAY": return 5; case "TRAVEL_NOTES": return 6; case "AM_ROUTE_ID": return 7; case "AM_TRANSPORT_MODE": return 8; case "AM_ROUTE_EVERY_DAY": return 9; case "AM_PICKUP_TIME": return 10; case "AM_PICKUP_ADDRESS_ID": return 11; case "AM_PICKUP_ADD_SAME_AS_HOME": return 12; case "AM_PICKUP_DIRECTIONS": return 13; case "AM_PICKUP_ADD_MAP_TYPE": return 14; case "AM_PICKUP_ADD_MAP_NO": return 15; case "AM_PICKUP_ADD_MAP_X_REF": return 16; case "AM_PICKUP_ADD_DESCP": return 17; case "AM_SETDOWN_TIME": return 18; case "AM_SETDOWN_CAMPUS": return 19; case "PM_ROUTE_ID": return 20; case "PM_TRANSPORT_MODE": return 21; case "PM_ROUTE_EVERY_DAY": return 22; case "PM_PICKUP_TIME": return 23; case "PM_PICKUP_CAMPUS": return 24; case "PM_SETDOWN_TIME": return 25; case "PM_SETDOWN_ADDRESS_ID": return 26; case "PM_STDWN_AM_PKUP_ADD_SAME": return 27; case "PM_SETDOWN_DIRECTIONS": return 28; case "PM_SETDOWN_ADD_MAP_TYPE": return 29; case "PM_SETDOWN_ADD_MAP_NO": return 30; case "PM_SETDOWN_ADD_MAP_X_REF": return 31; case "PM_SETDOWN_ADD_DESCP": return 32; case "LW_DATE": return 33; case "LW_TIME": return 34; case "LW_USER": return 35; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.Reflection; namespace System.Net { internal enum CookieToken { // State types Nothing, NameValuePair, // X=Y Attribute, // X EndToken, // ';' EndCookie, // ',' End, // EOLN Equals, // Value types Comment, CommentUrl, CookieName, Discard, Domain, Expires, MaxAge, Path, Port, Secure, HttpOnly, Unknown, Version } // CookieTokenizer // // Used to split a single or multi-cookie (header) string into individual // tokens. internal class CookieTokenizer { private bool _eofCookie; private int _index; private int _length; private string _name; private bool _quoted; private int _start; private CookieToken _token; private int _tokenLength; private string _tokenStream; private string _value; private int _cookieStartIndex; private int _cookieLength; internal CookieTokenizer(string tokenStream) { _length = tokenStream.Length; _tokenStream = tokenStream; } internal bool EndOfCookie { get { return _eofCookie; } set { _eofCookie = value; } } internal bool Eof { get { return _index >= _length; } } internal string Name { get { return _name; } set { _name = value; } } internal bool Quoted { get { return _quoted; } set { _quoted = value; } } internal CookieToken Token { get { return _token; } set { _token = value; } } internal string Value { get { return _value; } set { _value = value; } } // GetCookieString // // Gets the full string of the cookie internal string GetCookieString() { return _tokenStream.SubstringTrim(_cookieStartIndex, _cookieLength); } // Extract // // Extracts the current token internal string Extract() { string tokenString = string.Empty; if (_tokenLength != 0) { tokenString = Quoted ? _tokenStream.Substring(_start, _tokenLength) : _tokenStream.SubstringTrim(_start, _tokenLength); } return tokenString; } // FindNext // // Find the start and length of the next token. The token is terminated // by one of: // - end-of-line // - end-of-cookie: unquoted comma separates multiple cookies // - end-of-token: unquoted semi-colon // - end-of-name: unquoted equals // // Inputs: // <argument> ignoreComma // true if parsing doesn't stop at a comma. This is only true when // we know we're parsing an original cookie that has an expires= // attribute, because the format of the time/date used in expires // is: // Wdy, dd-mmm-yyyy HH:MM:SS GMT // // <argument> ignoreEquals // true if parsing doesn't stop at an equals sign. The LHS of the // first equals sign is an attribute name. The next token may // include one or more equals signs. For example: // SESSIONID=ID=MSNx45&q=33 // // Outputs: // <member> _index // incremented to the last position in _tokenStream contained by // the current token // // <member> _start // incremented to the start of the current token // // <member> _tokenLength // set to the length of the current token // // Assumes: Nothing // // Returns: // type of CookieToken found: // // End - end of the cookie string // EndCookie - end of current cookie in (potentially) a // multi-cookie string // EndToken - end of name=value pair, or end of an attribute // Equals - end of name= // // Throws: Nothing internal CookieToken FindNext(bool ignoreComma, bool ignoreEquals) { _tokenLength = 0; _start = _index; while ((_index < _length) && Char.IsWhiteSpace(_tokenStream[_index])) { ++_index; ++_start; } CookieToken token = CookieToken.End; int increment = 1; if (!Eof) { if (_tokenStream[_index] == '"') { Quoted = true; ++_index; bool quoteOn = false; while (_index < _length) { char currChar = _tokenStream[_index]; if (!quoteOn && currChar == '"') { break; } if (quoteOn) { quoteOn = false; } else if (currChar == '\\') { quoteOn = true; } ++_index; } if (_index < _length) { ++_index; } _tokenLength = _index - _start; increment = 0; // If we are here, reset ignoreComma. // In effect, we ignore everything after quoted string until the next delimiter. ignoreComma = false; } while ((_index < _length) && (_tokenStream[_index] != ';') && (ignoreEquals || (_tokenStream[_index] != '=')) && (ignoreComma || (_tokenStream[_index] != ','))) { // Fixing 2 things: // 1) ignore day of week in cookie string // 2) revert ignoreComma once meet it, so won't miss the next cookie) if (_tokenStream[_index] == ',') { _start = _index + 1; _tokenLength = -1; ignoreComma = false; } ++_index; _tokenLength += increment; } if (!Eof) { switch (_tokenStream[_index]) { case ';': token = CookieToken.EndToken; break; case '=': token = CookieToken.Equals; break; default: _cookieLength = _index - _cookieStartIndex; token = CookieToken.EndCookie; break; } ++_index; } else { _cookieLength = _index - _cookieStartIndex; } } return token; } // Next // // Get the next cookie name/value or attribute // // Cookies come in the following formats: // // 1. Version0 // Set-Cookie: [<name>][=][<value>] // [; expires=<date>] // [; path=<path>] // [; domain=<domain>] // [; secure] // Cookie: <name>=<value> // // Notes: <name> and/or <value> may be blank // <date> is the RFC 822/1123 date format that // incorporates commas, e.g. // "Wednesday, 09-Nov-99 23:12:40 GMT" // // 2. RFC 2109 // Set-Cookie: 1#{ // <name>=<value> // [; comment=<comment>] // [; domain=<domain>] // [; max-age=<seconds>] // [; path=<path>] // [; secure] // ; Version=<version> // } // Cookie: $Version=<version> // 1#{ // ; <name>=<value> // [; path=<path>] // [; domain=<domain>] // } // // 3. RFC 2965 // Set-Cookie2: 1#{ // <name>=<value> // [; comment=<comment>] // [; commentURL=<comment>] // [; discard] // [; domain=<domain>] // [; max-age=<seconds>] // [; path=<path>] // [; ports=<portlist>] // [; secure] // ; Version=<version> // } // Cookie: $Version=<version> // 1#{ // ; <name>=<value> // [; path=<path>] // [; domain=<domain>] // [; port="<port>"] // } // [Cookie2: $Version=<version>] // // Inputs: // <argument> first // true if this is the first name/attribute that we have looked for // in the cookie stream // // Outputs: // // Assumes: // Nothing // // Returns: // type of CookieToken found: // // - Attribute // - token was single-value. May be empty. Caller should check // Eof or EndCookie to determine if any more action needs to // be taken // // - NameValuePair // - Name and Value are meaningful. Either may be empty // // Throws: // Nothing internal CookieToken Next(bool first, bool parseResponseCookies) { Reset(); if (first) { _cookieStartIndex = _index; _cookieLength = 0; } CookieToken terminator = FindNext(false, false); if (terminator == CookieToken.EndCookie) { EndOfCookie = true; } if ((terminator == CookieToken.End) || (terminator == CookieToken.EndCookie)) { if ((Name = Extract()).Length != 0) { Token = TokenFromName(parseResponseCookies); return CookieToken.Attribute; } return terminator; } Name = Extract(); if (first) { Token = CookieToken.CookieName; } else { Token = TokenFromName(parseResponseCookies); } if (terminator == CookieToken.Equals) { terminator = FindNext(!first && (Token == CookieToken.Expires), true); if (terminator == CookieToken.EndCookie) { EndOfCookie = true; } Value = Extract(); return CookieToken.NameValuePair; } else { return CookieToken.Attribute; } } // Reset // // Sets this tokenizer up for finding the next name/value pair, // attribute, or end-of-{token,cookie,line}. internal void Reset() { _eofCookie = false; _name = string.Empty; _quoted = false; _start = _index; _token = CookieToken.Nothing; _tokenLength = 0; _value = string.Empty; } private struct RecognizedAttribute { private string _name; private CookieToken _token; internal RecognizedAttribute(string name, CookieToken token) { _name = name; _token = token; } internal CookieToken Token { get { return _token; } } internal bool IsEqualTo(string value) { return string.Equals(_name, value, StringComparison.OrdinalIgnoreCase); } } // Recognized attributes in order of expected frequency. private static readonly RecognizedAttribute[] s_recognizedAttributes = { new RecognizedAttribute(CookieFields.PathAttributeName, CookieToken.Path), new RecognizedAttribute(CookieFields.MaxAgeAttributeName, CookieToken.MaxAge), new RecognizedAttribute(CookieFields.ExpiresAttributeName, CookieToken.Expires), new RecognizedAttribute(CookieFields.VersionAttributeName, CookieToken.Version), new RecognizedAttribute(CookieFields.DomainAttributeName, CookieToken.Domain), new RecognizedAttribute(CookieFields.SecureAttributeName, CookieToken.Secure), new RecognizedAttribute(CookieFields.DiscardAttributeName, CookieToken.Discard), new RecognizedAttribute(CookieFields.PortAttributeName, CookieToken.Port), new RecognizedAttribute(CookieFields.CommentAttributeName, CookieToken.Comment), new RecognizedAttribute(CookieFields.CommentUrlAttributeName, CookieToken.CommentUrl), new RecognizedAttribute(CookieFields.HttpOnlyAttributeName, CookieToken.HttpOnly), }; private static readonly RecognizedAttribute[] s_recognizedServerAttributes = { new RecognizedAttribute('$' + CookieFields.PathAttributeName, CookieToken.Path), new RecognizedAttribute('$' + CookieFields.VersionAttributeName, CookieToken.Version), new RecognizedAttribute('$' + CookieFields.DomainAttributeName, CookieToken.Domain), new RecognizedAttribute('$' + CookieFields.PortAttributeName, CookieToken.Port), new RecognizedAttribute('$' + CookieFields.HttpOnlyAttributeName, CookieToken.HttpOnly), }; internal CookieToken TokenFromName(bool parseResponseCookies) { if (!parseResponseCookies) { for (int i = 0; i < s_recognizedServerAttributes.Length; ++i) { if (s_recognizedServerAttributes[i].IsEqualTo(Name)) { return s_recognizedServerAttributes[i].Token; } } } else { for (int i = 0; i < s_recognizedAttributes.Length; ++i) { if (s_recognizedAttributes[i].IsEqualTo(Name)) { return s_recognizedAttributes[i].Token; } } } return CookieToken.Unknown; } } // CookieParser // // Takes a cookie header, makes cookies. internal class CookieParser { private CookieTokenizer _tokenizer; private Cookie _savedCookie; internal CookieParser(string cookieString) { _tokenizer = new CookieTokenizer(cookieString); } // GetString // // Gets the next cookie string internal string GetString() { bool first = true; if (_tokenizer.Eof) { return null; } do { _tokenizer.Next(first, true); first = false; } while (!_tokenizer.Eof && !_tokenizer.EndOfCookie); return _tokenizer.GetCookieString(); } #if SYSTEM_NET_PRIMITIVES_DLL private static bool InternalSetNameMethod(Cookie cookie, string value) { return cookie.InternalSetName(value); } #else private static Func<Cookie, string, bool> s_internalSetNameMethod; private static Func<Cookie, string, bool> InternalSetNameMethod { get { if (s_internalSetNameMethod == null) { // TODO: #13607 // We need to use Cookie.InternalSetName instead of the Cookie.set_Name wrapped in a try catch block, as // Cookie.set_Name keeps the original name if the string is empty or null. // Unfortunately this API is internal so we use reflection to access it. The method is cached for performance reasons. BindingFlags flags = BindingFlags.Instance; #if uap flags |= BindingFlags.Public; #else flags |= BindingFlags.NonPublic; #endif MethodInfo method = typeof(Cookie).GetMethod("InternalSetName", flags); Debug.Assert(method != null, "We need to use an internal method named InternalSetName that is declared on Cookie."); s_internalSetNameMethod = (Func<Cookie, string, bool>)Delegate.CreateDelegate(typeof(Func<Cookie, string, bool>), method); } return s_internalSetNameMethod; } } #endif private static FieldInfo s_isQuotedDomainField = null; private static FieldInfo IsQuotedDomainField { get { if (s_isQuotedDomainField == null) { // TODO: #13607 BindingFlags flags = BindingFlags.Instance; #if uap flags |= BindingFlags.Public; #else flags |= BindingFlags.NonPublic; #endif FieldInfo field = typeof(Cookie).GetField("IsQuotedDomain", flags); Debug.Assert(field != null, "We need to use an internal field named IsQuotedDomain that is declared on Cookie."); s_isQuotedDomainField = field; } return s_isQuotedDomainField; } } private static FieldInfo s_isQuotedVersionField = null; private static FieldInfo IsQuotedVersionField { get { if (s_isQuotedVersionField == null) { // TODO: #13607 BindingFlags flags = BindingFlags.Instance; #if uap flags |= BindingFlags.Public; #else flags |= BindingFlags.NonPublic; #endif FieldInfo field = typeof(Cookie).GetField("IsQuotedVersion", flags); Debug.Assert(field != null, "We need to use an internal field named IsQuotedVersion that is declared on Cookie."); s_isQuotedVersionField = field; } return s_isQuotedVersionField; } } // Get // // Gets the next cookie or null if there are no more cookies. internal Cookie Get() { Cookie cookie = null; // Only the first occurrence of an attribute value must be counted. bool commentSet = false; bool commentUriSet = false; bool domainSet = false; bool expiresSet = false; bool pathSet = false; bool portSet = false; // Special case: may have no value in header. bool versionSet = false; bool secureSet = false; bool discardSet = false; do { CookieToken token = _tokenizer.Next(cookie == null, true); if (cookie == null && (token == CookieToken.NameValuePair || token == CookieToken.Attribute)) { cookie = new Cookie(); InternalSetNameMethod(cookie, _tokenizer.Name); cookie.Value = _tokenizer.Value; } else { switch (token) { case CookieToken.NameValuePair: switch (_tokenizer.Token) { case CookieToken.Comment: if (!commentSet) { commentSet = true; cookie.Comment = _tokenizer.Value; } break; case CookieToken.CommentUrl: if (!commentUriSet) { commentUriSet = true; if (Uri.TryCreate(CheckQuoted(_tokenizer.Value), UriKind.Absolute, out Uri parsed)) { cookie.CommentUri = parsed; } } break; case CookieToken.Domain: if (!domainSet) { domainSet = true; cookie.Domain = CheckQuoted(_tokenizer.Value); IsQuotedDomainField.SetValue(cookie, _tokenizer.Quoted); } break; case CookieToken.Expires: if (!expiresSet) { expiresSet = true; if (DateTime.TryParse(CheckQuoted(_tokenizer.Value), CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out DateTime expires)) { cookie.Expires = expires; } else { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.MaxAge: if (!expiresSet) { expiresSet = true; if (int.TryParse(CheckQuoted(_tokenizer.Value), out int parsed)) { cookie.Expires = DateTime.Now.AddSeconds(parsed); } else { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.Path: if (!pathSet) { pathSet = true; cookie.Path = _tokenizer.Value; } break; case CookieToken.Port: if (!portSet) { portSet = true; try { cookie.Port = _tokenizer.Value; } catch { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.Version: if (!versionSet) { versionSet = true; int parsed; if (int.TryParse(CheckQuoted(_tokenizer.Value), out parsed)) { cookie.Version = parsed; IsQuotedVersionField.SetValue(cookie, _tokenizer.Quoted); } else { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; } break; case CookieToken.Attribute: switch (_tokenizer.Token) { case CookieToken.Discard: if (!discardSet) { discardSet = true; cookie.Discard = true; } break; case CookieToken.Secure: if (!secureSet) { secureSet = true; cookie.Secure = true; } break; case CookieToken.HttpOnly: cookie.HttpOnly = true; break; case CookieToken.Port: if (!portSet) { portSet = true; cookie.Port = string.Empty; } break; } break; } } } while (!_tokenizer.Eof && !_tokenizer.EndOfCookie); return cookie; } internal Cookie GetServer() { Cookie cookie = _savedCookie; _savedCookie = null; // Only the first occurrence of an attribute value must be counted. bool domainSet = false; bool pathSet = false; bool portSet = false; // Special case: may have no value in header. do { bool first = cookie == null || string.IsNullOrEmpty(cookie.Name); CookieToken token = _tokenizer.Next(first, false); if (first && (token == CookieToken.NameValuePair || token == CookieToken.Attribute)) { if (cookie == null) { cookie = new Cookie(); } InternalSetNameMethod(cookie, _tokenizer.Name); cookie.Value = _tokenizer.Value; } else { switch (token) { case CookieToken.NameValuePair: switch (_tokenizer.Token) { case CookieToken.Domain: if (!domainSet) { domainSet = true; cookie.Domain = CheckQuoted(_tokenizer.Value); IsQuotedDomainField.SetValue(cookie, _tokenizer.Quoted); } break; case CookieToken.Path: if (!pathSet) { pathSet = true; cookie.Path = _tokenizer.Value; } break; case CookieToken.Port: if (!portSet) { portSet = true; try { cookie.Port = _tokenizer.Value; } catch (CookieException) { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.Version: // this is a new cookie, this token is for the next cookie. _savedCookie = new Cookie(); if (int.TryParse(_tokenizer.Value, out int parsed)) { _savedCookie.Version = parsed; } return cookie; case CookieToken.Unknown: // this is a new cookie, the token is for the next cookie. _savedCookie = new Cookie(); InternalSetNameMethod(_savedCookie, _tokenizer.Name); _savedCookie.Value = _tokenizer.Value; return cookie; } break; case CookieToken.Attribute: if (_tokenizer.Token == CookieToken.Port && !portSet) { portSet = true; cookie.Port = string.Empty; } break; } } } while (!_tokenizer.Eof && !_tokenizer.EndOfCookie); return cookie; } internal static string CheckQuoted(string value) { if (value.Length < 2 || value[0] != '\"' || value[value.Length - 1] != '\"') return value; return value.Length == 2 ? string.Empty : value.Substring(1, value.Length - 2); } } }
using System.Collections.Generic; using System; using Ceen.Mvc; using Ceen.Database; using System.Threading.Tasks; using Ceen; using Newtonsoft.Json; using System.Data; using System.Linq; namespace Ceen.PaaS.API { public class UserHandler : ControllerBase, IAPIv1 { /// <summary> /// Layout for the quick response /// </summary> private class QuickResponse { /// <summary> /// A value indicating if the user is logged in /// </summary> [JsonProperty("loggedIn")] public bool LoggedIn; /// <summary> /// The user ID /// </summary> [JsonProperty("userID")] public string UserID; /// <summary> /// The display name of the user /// </summary> [JsonProperty("name")] public string Name; /// <summary> /// The display name of the user /// </summary> [JsonProperty("imageUrl")] public string AvatarImage; /// <summary> /// A value indicating if the user has admin rights /// </summary> [JsonProperty("isAdmin")] public bool IsAdmin; /// <summary> /// The number of unread notifications for the user /// </summary> [JsonProperty("unreadNotifications")] public long UnreadNotifications; } /// <summary> /// Information when updating the password /// </summary> public class UpdatePasswordInfo { /// <summary> /// The current password for the user /// </summary> public string Current; /// <summary> /// The new password for the user /// </summary> public string New; /// <summary> /// The repeated new password /// </summary> public string Repeated; } /// <summary> /// Gets a value indicating if the <paramref name="userid" /> is for the current user /// </summary> /// <param name="userid">The userID to test</param> /// <returns><c>true</c> if the user ID refers to the current logged in user; <c>false</c> otherwise</returns> protected bool IsSelfUser(string userid) => !string.IsNullOrWhiteSpace(Context.UserID) && (Context.UserID == userid || userid == "me"); /// <summary> /// Handles the quick info call /// </summary> /// <param name="userid">The user to query</param> /// <returns>A response item</returns> [HttpGet] [Route("{userid}/quick")] [Ceen.Mvc.Name("index")] public async Task<IResult> GetQuick(string userid) { // If the user is not logged in, send empty response if (string.IsNullOrWhiteSpace(Context.UserID)) return Json(new QuickResponse()); // Only allow queries to own data if (!IsSelfUser(userid)) return Forbidden; return Json(await DB.RunInTransactionAsync(db => LoadQuickInfo(db))); } /// <summary> /// Gets an object representing an anonymous user /// </summary> public static object AnonymousQuickInfo => new QuickResponse(); /// <summary> /// Returns the quick-info object for json serialization /// </summary> /// <param name="db">The connection to use</param> /// <returns>The user info object</returns> public static object LoadQuickInfo(IDbConnection db) { var uid = Context.UserID; // If the user is not logged in, send empty response if (string.IsNullOrWhiteSpace(uid)) return new QuickResponse(); // Build a response var res = new QuickResponse() { LoggedIn = true, UserID = uid }; // Add database information var user = db.SelectItemById<Database.User>(uid); res.Name = user.Name; res.AvatarImage = Services.Images.CreateLinkForId(user.AvatarImageID); res.UnreadNotifications = db.SelectCount<Database.Notification>(x => x.UserID == uid && x.Seen == false); res.IsAdmin = Services.AdminHelper.IsAdmin(db, uid); return res; } /// <summary> /// Class with display settings for a user /// </summary> public class UserSettings { /// <summary> /// The user ID /// </summary> public string ID; /// <summary> /// The users display name /// </summary> public string Handle; /// <summary> /// The users profile picture /// </summary> public string Avatar; } /// <summary> /// The settings for the current user /// </summary> public class OwnUserSettings : UserSettings { /// <summary> /// The users email /// </summary> public string Email; /// <summary> /// The users name /// </summary> public string Name; /// <summary> /// The users invoice address /// </summary> public string InvoiceAddress; /// <summary> /// The users delivery address /// </summary> public string DeliveryAddress; /// <summary> /// A flag indicating if the user is disabled /// </summary> public bool? Disabled; /// <summary> /// A flag indicating if the user is an admin /// </summary> public bool? Admin; /// <summary> /// A flag indicating if two-factor authentication is required /// </summary> public bool? Require2FA; } [HttpGet] [Route("{userid}")] [Ceen.Mvc.Name("index")] public async Task<IResult> Get(string userid) { // Only logged in users can query user information if (string.IsNullOrWhiteSpace(Context.UserID)) return Forbidden; var res = IsSelfUser(userid) ? new OwnUserSettings() : new UserSettings(); await DB.RunInTransactionAsync(db => { var user = db.SelectItemById<Database.User>(Context.UserID); res.ID = user.ID; res.Handle = user.Handle; res.Avatar = Services.Images.CreateLinkForId(user.AvatarImageID); if (res is OwnUserSettings ous) { ous.Email = user.Email; ous.Name = user.Name; ous.InvoiceAddress = user.InvoiceAddress; ous.DeliveryAddress = user.DeliveryAddress; } }); return Json(res); } [HttpPatch] [Ceen.Mvc.Name("index")] public Task<IResult> Patch(OwnUserSettings settings) { // The normal user can only update their own settings return UpdateUserAsync(Context.UserID, settings); } /// <summary> /// Updates the user settings /// </summary> /// <param name="userid">The user to update</param> /// <param name="settings">The settings to apply</param> /// <returns>The request result</returns> protected async Task<IResult> UpdateUserAsync(string userid, OwnUserSettings settings) { var requestuserid = Context.UserID; // Only allow calls by logged in users if (string.IsNullOrWhiteSpace(requestuserid)) return Forbidden; if (string.IsNullOrWhiteSpace(userid)) return BadRequest; var isself = IsSelfUser(userid); if (settings == null) return Status(BadRequest, "Missing update information"); try { Database.ChangeEmailRequest nx = null; Database.User user = null; string oldemail = null; var res = await DB.RunInTransactionAsync(db => { var isadmin = Services.AdminHelper.IsAdmin(db, requestuserid); if (!isself && !isadmin) return Forbidden; user = db.SelectItemById<Database.User>(userid); if (!string.IsNullOrWhiteSpace(settings.Handle)) user.Handle = settings.Handle; if (!string.IsNullOrWhiteSpace(settings.Name)) user.Name = settings.Name; if (settings.InvoiceAddress != null) user.InvoiceAddress = settings.InvoiceAddress; if (settings.DeliveryAddress != null) user.DeliveryAddress = settings.DeliveryAddress; if (isadmin && settings.Disabled != null) user.Disabled = settings.Disabled.Value; if (isadmin && settings.Require2FA != null) user.Require2FA = settings.Require2FA.Value; // Register a new activation request if (!string.IsNullOrWhiteSpace(settings.Email) && settings.Email != user.Email) { if (!Services.PasswordPolicy.IsValidEmail(settings.Email)) return Status(BadRequest, "The new email address is not valid"); oldemail = user.Email; if (isadmin) { user.Email = settings.Email; } else { db.InsertItem(nx = new Database.ChangeEmailRequest() { UserID = user.ID, NewEmail = settings.Email, Token = Services.PasswordPolicy.GenerateActivationCode() }); } } //TODO: The profile image? db.UpdateItem(user); // Toggle admin status if (isadmin && settings.Admin != null) { if (settings.Admin.Value) { db.InsertOrIgnoreItem(new Database.UserGroupIndex() { UserID = user.ID, GroupID = IDConstants.AdminGroupID }); } else { db.Delete<Database.UserGroupIndex>(x => x.UserID == user.ID && x.GroupID == IDConstants.AdminGroupID ); } } if (isadmin && !string.IsNullOrWhiteSpace(oldemail)) { //TODO: Implement the change email notification //Services.SendEmail.ChangeEmailNotification(oldemail, settings.Email); } return OK; }); if (user != null && nx != null) await Queues.SendEmailChangeConfirmationEmailAsync(user.Name, nx.NewEmail, nx.ID, Services.LocaleHelper.GetBestLocale(Context.Request)); return res; } catch (Exception ex) { var t = Ceen.Extras.CRUDExceptionHelper.WrapExceptionMessage(ex); if (t != null) return t; throw; } } protected async Task<IResult> UpdatePasswordAsync(string userid, UpdatePasswordInfo req) { var requestuserid = Context.UserID; // Only allow calls by logged in users if (string.IsNullOrWhiteSpace(requestuserid)) return Forbidden; if (new [] { req?.Current, req?.New, req?.Repeated }.Any(x => string.IsNullOrWhiteSpace(x))) return Status(BadRequest, "One or more fields are missing"); if (req.New != req.Repeated) return Status(BadRequest, "The new password does not match the repeated one"); Services.PasswordPolicy.ValidatePassword(req.New); var isself = IsSelfUser(userid); try { return await DB.RunInTransactionAsync(db => { var isadmin = Services.AdminHelper.IsAdmin(db, requestuserid); if (!isself && !isadmin) return Forbidden; var user = db.SelectItemById<Database.User>(userid); if (!isadmin && !Ceen.Security.PBKDF2.ComparePassword(req.Current, user.Password)) return Status(BadRequest, "The current password is not correct"); user.Password = Ceen.Security.PBKDF2.CreatePBKDF2(req.New); db.UpdateItem(user); return OK; }); } catch (Exception ex) { var t = Ceen.Extras.CRUDExceptionHelper.WrapExceptionMessage(ex); if (t != null) return t; throw; } } [HttpPut] [Ceen.Mvc.Name("password")] public Task<IResult> Put(UpdatePasswordInfo req) { // Non-admin users can only update their own password return UpdatePasswordAsync(Context.UserID, req); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Avalonia.Input; using Avalonia.Layout; namespace Avalonia.Controls { /// <summary> /// A panel that displays child controls at arbitrary locations. /// </summary> /// <remarks> /// Unlike other <see cref="Panel"/> implementations, the <see cref="Canvas"/> doesn't lay out /// its children in any particular layout. Instead, the positioning of each child control is /// defined by the <code>Canvas.Left</code>, <code>Canvas.Top</code>, <code>Canvas.Right</code> /// and <code>Canvas.Bottom</code> attached properties. /// </remarks> public class Canvas : Panel, INavigableContainer { /// <summary> /// Defines the Left attached property. /// </summary> public static readonly AttachedProperty<double> LeftProperty = AvaloniaProperty.RegisterAttached<Canvas, Control, double>("Left", double.NaN); /// <summary> /// Defines the Top attached property. /// </summary> public static readonly AttachedProperty<double> TopProperty = AvaloniaProperty.RegisterAttached<Canvas, Control, double>("Top", double.NaN); /// <summary> /// Defines the Right attached property. /// </summary> public static readonly AttachedProperty<double> RightProperty = AvaloniaProperty.RegisterAttached<Canvas, Control, double>("Right", double.NaN); /// <summary> /// Defines the Bottom attached property. /// </summary> public static readonly AttachedProperty<double> BottomProperty = AvaloniaProperty.RegisterAttached<Canvas, Control, double>("Bottom", double.NaN); /// <summary> /// Initializes static members of the <see cref="Canvas"/> class. /// </summary> static Canvas() { ClipToBoundsProperty.OverrideDefaultValue<Canvas>(false); AffectsCanvasArrange(LeftProperty, TopProperty, RightProperty, BottomProperty); } /// <summary> /// Gets the value of the Left attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <returns>The control's left coordinate.</returns> public static double GetLeft(AvaloniaObject element) { return element.GetValue(LeftProperty); } /// <summary> /// Sets the value of the Left attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <param name="value">The left value.</param> public static void SetLeft(AvaloniaObject element, double value) { element.SetValue(LeftProperty, value); } /// <summary> /// Gets the value of the Top attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <returns>The control's top coordinate.</returns> public static double GetTop(AvaloniaObject element) { return element.GetValue(TopProperty); } /// <summary> /// Sets the value of the Top attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <param name="value">The top value.</param> public static void SetTop(AvaloniaObject element, double value) { element.SetValue(TopProperty, value); } /// <summary> /// Gets the value of the Right attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <returns>The control's right coordinate.</returns> public static double GetRight(AvaloniaObject element) { return element.GetValue(RightProperty); } /// <summary> /// Sets the value of the Right attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <param name="value">The right value.</param> public static void SetRight(AvaloniaObject element, double value) { element.SetValue(RightProperty, value); } /// <summary> /// Gets the value of the Bottom attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <returns>The control's bottom coordinate.</returns> public static double GetBottom(AvaloniaObject element) { return element.GetValue(BottomProperty); } /// <summary> /// Sets the value of the Bottom attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <param name="value">The bottom value.</param> public static void SetBottom(AvaloniaObject element, double value) { element.SetValue(BottomProperty, value); } /// <summary> /// Gets the next control in the specified direction. /// </summary> /// <param name="direction">The movement direction.</param> /// <param name="from">The control from which movement begins.</param> /// <returns>The control.</returns> IInputElement INavigableContainer.GetControl(NavigationDirection direction, IInputElement from) { // TODO: Implement this return null; } /// <summary> /// Measures the control. /// </summary> /// <param name="availableSize">The available size.</param> /// <returns>The desired size of the control.</returns> protected override Size MeasureOverride(Size availableSize) { availableSize = new Size(double.PositiveInfinity, double.PositiveInfinity); foreach (Control child in Children) { child.Measure(availableSize); } return new Size(); } /// <summary> /// Arranges the control's children. /// </summary> /// <param name="finalSize">The size allocated to the control.</param> /// <returns>The space taken.</returns> protected override Size ArrangeOverride(Size finalSize) { foreach (Control child in Children) { double x = 0.0; double y = 0.0; double elementLeft = GetLeft(child); if (!double.IsNaN(elementLeft)) { x = elementLeft; } else { // Arrange with right. double elementRight = GetRight(child); if (!double.IsNaN(elementRight)) { x = finalSize.Width - child.DesiredSize.Width - elementRight; } } double elementTop = GetTop(child); if (!double.IsNaN(elementTop) ) { y = elementTop; } else { double elementBottom = GetBottom(child); if (!double.IsNaN(elementBottom)) { y = finalSize.Height - child.DesiredSize.Height - elementBottom; } } child.Arrange(new Rect(new Point(x, y), child.DesiredSize)); } return finalSize; } /// <summary> /// Marks a property on a child as affecting the canvas' arrangement. /// </summary> /// <param name="properties">The properties.</param> private static void AffectsCanvasArrange(params AvaloniaProperty[] properties) { foreach (var property in properties) { property.Changed.Subscribe(AffectsCanvasArrangeInvalidate); } } /// <summary> /// Calls <see cref="Layoutable.InvalidateArrange"/> on the parent of the control whose /// property changed, if that parent is a canvas. /// </summary> /// <param name="e">The event args.</param> private static void AffectsCanvasArrangeInvalidate(AvaloniaPropertyChangedEventArgs e) { var control = e.Sender as IControl; var canvas = control?.VisualParent as Canvas; canvas?.InvalidateArrange(); } } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ using UnityEngine; using System.Collections.Generic; /// <summary> /// Controls the player's movement in virtual reality. /// </summary> [RequireComponent(typeof(CharacterController))] public class OVRPlayerController : MonoBehaviour { /// <summary> /// The rate acceleration during movement. /// </summary> public float Acceleration = 0.1f; /// <summary> /// The rate of damping on movement. /// </summary> public float Damping = 0.3f; /// <summary> /// The rate of additional damping when moving sideways or backwards. /// </summary> public float BackAndSideDampen = 0.5f; /// <summary> /// The force applied to the character when jumping. /// </summary> public float JumpForce = 0.3f; /// <summary> /// The rate of rotation when using a gamepad. /// </summary> public float RotationAmount = 1.5f; /// <summary> /// The rate of rotation when using the keyboard. /// </summary> public float RotationRatchet = 45.0f; /// <summary> /// The player's current rotation about the Y axis. /// </summary> private float YRotation = 0.0f; /// <summary> /// If true, tracking data from a child OVRCameraRig will update the direction of movement. /// </summary> public bool HmdRotatesY = true; /// <summary> /// Modifies the strength of gravity. /// </summary> public float GravityModifier = 0.379f; private float MoveScale = 1.0f; private Vector3 MoveThrottle = Vector3.zero; private float FallSpeed = 0.0f; private OVRPose? InitialPose; /// <summary> /// If true, each OVRPlayerController will use the player's physical height. /// </summary> public bool useProfileHeight = true; protected CharacterController Controller = null; protected OVRCameraRig CameraController = null; private float MoveScaleMultiplier = 1.0f; private float RotationScaleMultiplier = 1.0f; private bool SkipMouseRotation = false; private bool HaltUpdateMovement = false; private bool prevHatLeft = false; private bool prevHatRight = false; private float SimulationRate = 60f; void Awake() { Controller = gameObject.GetComponent<CharacterController>(); if(Controller == null) Debug.LogWarning("OVRPlayerController: No CharacterController attached."); // We use OVRCameraRig to set rotations to cameras, // and to be influenced by rotation OVRCameraRig[] CameraControllers; CameraControllers = gameObject.GetComponentsInChildren<OVRCameraRig>(); if(CameraControllers.Length == 0) Debug.LogWarning("OVRPlayerController: No OVRCameraRig attached."); else if (CameraControllers.Length > 1) Debug.LogWarning("OVRPlayerController: More then 1 OVRCameraRig attached."); else CameraController = CameraControllers[0]; YRotation = transform.rotation.eulerAngles.y; #if UNITY_ANDROID && !UNITY_EDITOR OVRManager.display.RecenteredPose += ResetOrientation; #endif } protected virtual void Update() { if (useProfileHeight) { if (InitialPose == null) { InitialPose = new OVRPose() { position = CameraController.transform.localPosition, orientation = CameraController.transform.localRotation }; } var p = CameraController.transform.localPosition; p.y = 0.5f* Controller.height; p.z = OVRManager.profile.eyeDepth; CameraController.transform.localPosition = p; } else if (InitialPose != null) { CameraController.transform.localPosition = InitialPose.Value.position; CameraController.transform.localRotation = InitialPose.Value.orientation; InitialPose = null; } UpdateMovement(); Vector3 moveDirection = Vector3.zero; float motorDamp = (1.0f + (Damping * SimulationRate * Time.deltaTime)); MoveThrottle.x /= motorDamp; MoveThrottle.y = (MoveThrottle.y > 0.0f) ? (MoveThrottle.y / motorDamp) : MoveThrottle.y; MoveThrottle.z /= motorDamp; moveDirection += MoveThrottle * SimulationRate * Time.deltaTime; // Gravity if (Controller.isGrounded && FallSpeed <= 0) FallSpeed = ((Physics.gravity.y * (GravityModifier * 0.002f))); else FallSpeed += ((Physics.gravity.y * (GravityModifier * 0.002f)) * SimulationRate * Time.deltaTime); moveDirection.y += FallSpeed * SimulationRate * Time.deltaTime; // Offset correction for uneven ground float bumpUpOffset = 0.0f; if (Controller.isGrounded && MoveThrottle.y <= 0.001f) { bumpUpOffset = Mathf.Max(Controller.stepOffset, new Vector3(moveDirection.x, 0, moveDirection.z).magnitude); moveDirection -= bumpUpOffset * Vector3.up; } Vector3 predictedXZ = Vector3.Scale((Controller.transform.localPosition + moveDirection), new Vector3(1, 0, 1)); // Move contoller Controller.Move(moveDirection); Vector3 actualXZ = Vector3.Scale(Controller.transform.localPosition, new Vector3(1, 0, 1)); if (predictedXZ != actualXZ) MoveThrottle += (actualXZ - predictedXZ) / (SimulationRate * Time.deltaTime); } public virtual void UpdateMovement() { if (HaltUpdateMovement) return; bool moveForward = Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow); bool moveLeft = Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow); bool moveRight = Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow); bool moveBack = Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow); bool dpad_move = false; if (OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Up)) { moveForward = true; dpad_move = true; } if (OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Down)) { moveBack = true; dpad_move = true; } MoveScale = 1.0f; if ( (moveForward && moveLeft) || (moveForward && moveRight) || (moveBack && moveLeft) || (moveBack && moveRight) ) MoveScale = 0.70710678f; // No positional movement if we are in the air if (!Controller.isGrounded) MoveScale = 0.0f; MoveScale *= SimulationRate * Time.deltaTime; // Compute this for key movement float moveInfluence = Acceleration * 0.1f * MoveScale * MoveScaleMultiplier; // Run! if (dpad_move || Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) moveInfluence *= 2.0f; Quaternion ort = (HmdRotatesY) ? CameraController.centerEyeAnchor.rotation : transform.rotation; Vector3 ortEuler = ort.eulerAngles; ortEuler.z = ortEuler.x = 0f; ort = Quaternion.Euler(ortEuler); if (moveForward) MoveThrottle += ort * (transform.lossyScale.z * moveInfluence * Vector3.forward); if (moveBack) MoveThrottle += ort * (transform.lossyScale.z * moveInfluence * BackAndSideDampen * Vector3.back); if (moveLeft) MoveThrottle += ort * (transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.left); if (moveRight) MoveThrottle += ort * (transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.right); bool curHatLeft = OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.LeftShoulder); Vector3 euler = transform.rotation.eulerAngles; if (curHatLeft && !prevHatLeft) euler.y -= RotationRatchet; prevHatLeft = curHatLeft; bool curHatRight = OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.RightShoulder); if(curHatRight && !prevHatRight) euler.y += RotationRatchet; prevHatRight = curHatRight; //Use keys to ratchet rotation if (Input.GetKeyDown(KeyCode.Q)) euler.y -= RotationRatchet; if (Input.GetKeyDown(KeyCode.E)) euler.y += RotationRatchet; float rotateInfluence = SimulationRate * Time.deltaTime * RotationAmount * RotationScaleMultiplier; if (!SkipMouseRotation) euler.y += Input.GetAxis("Mouse X") * rotateInfluence * 3.25f; moveInfluence = SimulationRate * Time.deltaTime * Acceleration * 0.1f * MoveScale * MoveScaleMultiplier; #if !UNITY_ANDROID // LeftTrigger not avail on Android game pad moveInfluence *= 1.0f + OVRGamepadController.GPC_GetAxis(OVRGamepadController.Axis.LeftTrigger); #endif float leftAxisX = OVRGamepadController.GPC_GetAxis(OVRGamepadController.Axis.LeftXAxis); float leftAxisY = OVRGamepadController.GPC_GetAxis(OVRGamepadController.Axis.LeftYAxis); if(leftAxisY > 0.0f) MoveThrottle += ort * (leftAxisY * moveInfluence * Vector3.forward); if(leftAxisY < 0.0f) MoveThrottle += ort * (Mathf.Abs(leftAxisY) * moveInfluence * BackAndSideDampen * Vector3.back); if(leftAxisX < 0.0f) MoveThrottle += ort * (Mathf.Abs(leftAxisX) * moveInfluence * BackAndSideDampen * Vector3.left); if(leftAxisX > 0.0f) MoveThrottle += ort * (leftAxisX * moveInfluence * BackAndSideDampen * Vector3.right); float rightAxisX = OVRGamepadController.GPC_GetAxis(OVRGamepadController.Axis.RightXAxis); euler.y += rightAxisX * rotateInfluence; transform.rotation = Quaternion.Euler(euler); } /// <summary> /// Jump! Must be enabled manually. /// </summary> public bool Jump() { if (!Controller.isGrounded) return false; MoveThrottle += new Vector3(0, JumpForce, 0); return true; } /// <summary> /// Stop this instance. /// </summary> public void Stop() { Controller.Move(Vector3.zero); MoveThrottle = Vector3.zero; FallSpeed = 0.0f; } /// <summary> /// Gets the move scale multiplier. /// </summary> /// <param name="moveScaleMultiplier">Move scale multiplier.</param> public void GetMoveScaleMultiplier(ref float moveScaleMultiplier) { moveScaleMultiplier = MoveScaleMultiplier; } /// <summary> /// Sets the move scale multiplier. /// </summary> /// <param name="moveScaleMultiplier">Move scale multiplier.</param> public void SetMoveScaleMultiplier(float moveScaleMultiplier) { MoveScaleMultiplier = moveScaleMultiplier; } /// <summary> /// Gets the rotation scale multiplier. /// </summary> /// <param name="rotationScaleMultiplier">Rotation scale multiplier.</param> public void GetRotationScaleMultiplier(ref float rotationScaleMultiplier) { rotationScaleMultiplier = RotationScaleMultiplier; } /// <summary> /// Sets the rotation scale multiplier. /// </summary> /// <param name="rotationScaleMultiplier">Rotation scale multiplier.</param> public void SetRotationScaleMultiplier(float rotationScaleMultiplier) { RotationScaleMultiplier = rotationScaleMultiplier; } /// <summary> /// Gets the allow mouse rotation. /// </summary> /// <param name="skipMouseRotation">Allow mouse rotation.</param> public void GetSkipMouseRotation(ref bool skipMouseRotation) { skipMouseRotation = SkipMouseRotation; } /// <summary> /// Sets the allow mouse rotation. /// </summary> /// <param name="skipMouseRotation">If set to <c>true</c> allow mouse rotation.</param> public void SetSkipMouseRotation(bool skipMouseRotation) { SkipMouseRotation = skipMouseRotation; } /// <summary> /// Gets the halt update movement. /// </summary> /// <param name="haltUpdateMovement">Halt update movement.</param> public void GetHaltUpdateMovement(ref bool haltUpdateMovement) { haltUpdateMovement = HaltUpdateMovement; } /// <summary> /// Sets the halt update movement. /// </summary> /// <param name="haltUpdateMovement">If set to <c>true</c> halt update movement.</param> public void SetHaltUpdateMovement(bool haltUpdateMovement) { HaltUpdateMovement = haltUpdateMovement; } /// <summary> /// Resets the player look rotation when the device orientation is reset. /// </summary> public void ResetOrientation() { Vector3 euler = transform.rotation.eulerAngles; euler.y = YRotation; transform.rotation = Quaternion.Euler(euler); } }
public class TuSeq : TuObject { public override string getName() { return "Sequence"; } public string value = System.String.Empty; public char[] getAsCharArray() { return value.ToCharArray(); } public static new TuSeq createProto(TuState state) { TuSeq s = new TuSeq(); return s.proto(state) as TuSeq; } public static new TuSeq createObject(TuState state) { TuSeq s = new TuSeq(); return s.clone(state) as TuSeq; } public static TuSeq createObject(TuSeq symbol) { TuSeq seq = new TuSeq(); seq = seq.clone(symbol.getState()) as TuSeq; seq.value = symbol.value; return seq; } public static TuSeq createObject(TuState state, string symbol) { TuSeq seq = new TuSeq(); seq = seq.clone(state) as TuSeq; seq.value = symbol; return seq; } public static TuSeq createSymbolInMachine(TuState state, string symbol) { if (state.symbols[symbol] == null) state.symbols[symbol] = TuSeq.createObject(state, symbol); return state.symbols[symbol] as TuSeq; } public override TuObject proto(TuState state) { TuSeq pro = new TuSeq(); pro.setState(state); // pro.tag.cloneFunc = new IoTagCloneFunc(this.clone); // pro.tag.compareFunc = new IoTagCompareFunc(this.compare); pro.createSlots(); pro.createProtos(); state.registerProtoWithFunc(getName(), new TuStateProto(getName(), pro, new TuStateProtoFunc(this.proto))); pro.protos.Add(state.protoWithInitFunc("Object")); TuCFunction[] methodTable = new TuCFunction[] { new TuCFunction("appendSeq", new TuMethodFunc(TuSeq.slotAppendSeq)), new TuCFunction("+", new TuMethodFunc(TuSeq.slotAppendSeq)), new TuCFunction("at", new TuMethodFunc(TuSeq.slotAt)), new TuCFunction("split", new TuMethodFunc(TuSeq.split)), new TuCFunction("reverse", new TuMethodFunc(TuSeq.slotReverse)), new TuCFunction("size", new TuMethodFunc(TuSeq.size)), new TuCFunction("asNumber", new TuMethodFunc(TuSeq.asNumber)), new TuCFunction("interpolate", new TuMethodFunc(TuSeq.interpolate)), }; pro.addTaglessMethodTable(state, methodTable); return pro; } public static TuObject slotAppendSeq(TuObject target, TuObject locals, TuObject message) { TuSeq other = (message as TuMessage).localsSymbolArgAt(locals, 0); TuSeq self = target as TuSeq; if (other == null) return self; return TuSeq.createObject(self.getState(), self.value + other.value.Replace(@"\""", "\"")); } public static TuObject slotAt(TuObject target, TuObject locals, TuObject message) { TuMessage m = message as TuMessage; TuSeq o = target as TuSeq; TuSeq res = TuSeq.createObject(target.getState()); TuNumber arg = m.localsNumberArgAt(locals, 0); res.value += o.value.Substring(arg.asInt(), 1); return res; } public static TuObject split(TuObject target, TuObject locals, TuObject message) { TuMessage m = message as TuMessage; TuSeq o = target as TuSeq; TuList res = TuList.createObject(target.getState()); TuSeq separator = m.localsSymbolArgAt(locals, 0); foreach (var item in o.value.Split(separator.value)) { res.append(TuSeq.createObject(target.getState(), item)); } return res; } public static TuObject interpolate(TuObject target, TuObject locals, TuObject message) { TuMessage m = message as TuMessage; TuSeq o = target as TuSeq; TuSeq res = TuSeq.createObject(target.getState()); var pattern = @"(#\{(?:.*?)\})"; foreach (var item in System.Text.RegularExpressions.Regex.Split(o.value, pattern)) { if (item.StartsWith("#{")) { var to_interprete = item.Replace("#{","").Replace("}",""); var target_interpol = locals.rawGetSlot(target.getState().selfSymbol); if (target_interpol.slots.Count == 0) target_interpol = target.getState().lobby; var eval = target.getState().onDoCStringWithLabel(target_interpol, to_interprete, "interpolate"); res.value += eval.ToString(); } else { res.value += item; } } return res; } public static TuObject slotReverse(TuObject target, TuObject locals, TuObject message) { TuMessage m = message as TuMessage; TuSeq o = target as TuSeq; TuSeq res = TuSeq.createObject(target.getState()); char[] A = o.getAsCharArray(); System.Array.Reverse(A); res.value = new string(A); return res; } public static TuObject size(TuObject target, TuObject locals, TuObject message) { TuMessage m = message as TuMessage; TuSeq o = target as TuSeq; return TuNumber.newWithDouble(target.getState(), o.value.Length); } public static TuObject asNumber(TuObject target, TuObject locals, TuObject message) { TuMessage m = message as TuMessage; TuSeq o = target as TuSeq; return TuNumber.newWithDouble(target.getState(), double.Parse(o.value)); } public override TuObject clone(TuState state) { TuSeq proto = state.protoWithInitFunc(getName()) as TuSeq; TuSeq result = new TuSeq(); result.setState(state); result.value = proto.value; result.createProtos(); result.createSlots(); result.protos.Add(proto); return result; } public override int compare(TuObject v) { if (v is TuSeq) return this.value.CompareTo((v as TuSeq).value); return base.compare(v); } public override void print() { System.Console.Write("{0}", value); } public override string ToString() { return value.ToString(); } public static TuSeq rawAsUnquotedSymbol(TuSeq s) { string str = ""; if (s.value.StartsWith("\"")) str = s.value.Substring(1, s.value.Length - 1); if (s.value.EndsWith("\"")) str = str.Substring(0, s.value.Length - 2); return TuSeq.createObject(s.getState(), str); } public static TuSeq rawAsUnescapedSymbol(TuSeq s) { string str = ""; int i = 0; while (i < s.value.Length) { char c = s.value[i]; if (c != '\\') { str += c; } else { c = s.value[i]; switch (c) { case 'a': c = '\a'; break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'v': c = '\v'; break; case '\0': c = '\\'; break; default: if (c > '0' && c < '9') { c -= '0'; } break; } str += c; } i++; } return TuSeq.createObject(s.getState(), str); } }
// 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 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for VirtualNetworkGatewayConnectionsOperations. /// </summary> public static partial class VirtualNetworkGatewayConnectionsOperationsExtensions { /// <summary> /// The Put VirtualNetworkGatewayConnection operation creates/updates a /// virtual network gateway connection in the specified resource group /// through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway conenction. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Create or update Virtual Network Gateway /// connection operation through Network resource provider. /// </param> public static VirtualNetworkGatewayConnection CreateOrUpdate(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters) { return Task.Factory.StartNew(s => ((IVirtualNetworkGatewayConnectionsOperations)s).CreateOrUpdateAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put VirtualNetworkGatewayConnection operation creates/updates a /// virtual network gateway connection in the specified resource group /// through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway conenction. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Create or update Virtual Network Gateway /// connection operation through Network resource provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGatewayConnection> CreateOrUpdateAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The Put VirtualNetworkGatewayConnection operation creates/updates a /// virtual network gateway connection in the specified resource group /// through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway conenction. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Create or update Virtual Network Gateway /// connection operation through Network resource provider. /// </param> public static VirtualNetworkGatewayConnection BeginCreateOrUpdate(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters) { return Task.Factory.StartNew(s => ((IVirtualNetworkGatewayConnectionsOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put VirtualNetworkGatewayConnection operation creates/updates a /// virtual network gateway connection in the specified resource group /// through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway conenction. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Create or update Virtual Network Gateway /// connection operation through Network resource provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGatewayConnection> BeginCreateOrUpdateAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The Get VirtualNetworkGatewayConnection operation retrieves information /// about the specified virtual network gateway connection through Network /// resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> public static VirtualNetworkGatewayConnection Get(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName) { return Task.Factory.StartNew(s => ((IVirtualNetworkGatewayConnectionsOperations)s).GetAsync(resourceGroupName, virtualNetworkGatewayConnectionName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get VirtualNetworkGatewayConnection operation retrieves information /// about the specified virtual network gateway connection through Network /// resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGatewayConnection> GetAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The Delete VirtualNetworkGatewayConnection operation deletes the specifed /// virtual network Gateway connection through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> public static void Delete(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName) { Task.Factory.StartNew(s => ((IVirtualNetworkGatewayConnectionsOperations)s).DeleteAsync(resourceGroupName, virtualNetworkGatewayConnectionName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Delete VirtualNetworkGatewayConnection operation deletes the specifed /// virtual network Gateway connection through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// The Delete VirtualNetworkGatewayConnection operation deletes the specifed /// virtual network Gateway connection through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> public static void BeginDelete(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName) { Task.Factory.StartNew(s => ((IVirtualNetworkGatewayConnectionsOperations)s).BeginDeleteAsync(resourceGroupName, virtualNetworkGatewayConnectionName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Delete VirtualNetworkGatewayConnection operation deletes the specifed /// virtual network Gateway connection through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// The Get VirtualNetworkGatewayConnectionSharedKey operation retrieves /// information about the specified virtual network gateway connection shared /// key through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='connectionSharedKeyName'> /// The virtual network gateway connection shared key name. /// </param> public static ConnectionSharedKeyResult GetSharedKey(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string connectionSharedKeyName) { return Task.Factory.StartNew(s => ((IVirtualNetworkGatewayConnectionsOperations)s).GetSharedKeyAsync(resourceGroupName, connectionSharedKeyName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get VirtualNetworkGatewayConnectionSharedKey operation retrieves /// information about the specified virtual network gateway connection shared /// key through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='connectionSharedKeyName'> /// The virtual network gateway connection shared key name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ConnectionSharedKeyResult> GetSharedKeyAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string connectionSharedKeyName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetSharedKeyWithHttpMessagesAsync(resourceGroupName, connectionSharedKeyName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The List VirtualNetworkGatewayConnections operation retrieves all the /// virtual network gateways connections created. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<VirtualNetworkGatewayConnection> List(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName) { return Task.Factory.StartNew(s => ((IVirtualNetworkGatewayConnectionsOperations)s).ListAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List VirtualNetworkGatewayConnections operation retrieves all the /// virtual network gateways connections created. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetworkGatewayConnection>> ListAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The VirtualNetworkGatewayConnectionResetSharedKey operation resets the /// virtual network gateway connection shared key for passed virtual network /// gateway connection in the specified resource group through Network /// resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection reset shared key Name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Reset Virtual Network Gateway connection /// shared key operation through Network resource provider. /// </param> public static ConnectionResetSharedKey ResetSharedKey(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters) { return Task.Factory.StartNew(s => ((IVirtualNetworkGatewayConnectionsOperations)s).ResetSharedKeyAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The VirtualNetworkGatewayConnectionResetSharedKey operation resets the /// virtual network gateway connection shared key for passed virtual network /// gateway connection in the specified resource group through Network /// resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection reset shared key Name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Reset Virtual Network Gateway connection /// shared key operation through Network resource provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ConnectionResetSharedKey> ResetSharedKeyAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ResetSharedKeyWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The VirtualNetworkGatewayConnectionResetSharedKey operation resets the /// virtual network gateway connection shared key for passed virtual network /// gateway connection in the specified resource group through Network /// resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection reset shared key Name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Reset Virtual Network Gateway connection /// shared key operation through Network resource provider. /// </param> public static ConnectionResetSharedKey BeginResetSharedKey(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters) { return Task.Factory.StartNew(s => ((IVirtualNetworkGatewayConnectionsOperations)s).BeginResetSharedKeyAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The VirtualNetworkGatewayConnectionResetSharedKey operation resets the /// virtual network gateway connection shared key for passed virtual network /// gateway connection in the specified resource group through Network /// resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection reset shared key Name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Reset Virtual Network Gateway connection /// shared key operation through Network resource provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ConnectionResetSharedKey> BeginResetSharedKeyAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginResetSharedKeyWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the /// virtual network gateway connection shared key for passed virtual network /// gateway connection in the specified resource group through Network /// resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Set Virtual Network Gateway conection /// Shared key operation throughNetwork resource provider. /// </param> public static ConnectionSharedKey SetSharedKey(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters) { return Task.Factory.StartNew(s => ((IVirtualNetworkGatewayConnectionsOperations)s).SetSharedKeyAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the /// virtual network gateway connection shared key for passed virtual network /// gateway connection in the specified resource group through Network /// resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Set Virtual Network Gateway conection /// Shared key operation throughNetwork resource provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ConnectionSharedKey> SetSharedKeyAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.SetSharedKeyWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the /// virtual network gateway connection shared key for passed virtual network /// gateway connection in the specified resource group through Network /// resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Set Virtual Network Gateway conection /// Shared key operation throughNetwork resource provider. /// </param> public static ConnectionSharedKey BeginSetSharedKey(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters) { return Task.Factory.StartNew(s => ((IVirtualNetworkGatewayConnectionsOperations)s).BeginSetSharedKeyAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the /// virtual network gateway connection shared key for passed virtual network /// gateway connection in the specified resource group through Network /// resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Set Virtual Network Gateway conection /// Shared key operation throughNetwork resource provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ConnectionSharedKey> BeginSetSharedKeyAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginSetSharedKeyWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The List VirtualNetworkGatewayConnections operation retrieves all the /// virtual network gateways connections created. /// </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<VirtualNetworkGatewayConnection> ListNext(this IVirtualNetworkGatewayConnectionsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IVirtualNetworkGatewayConnectionsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List VirtualNetworkGatewayConnections operation retrieves all the /// virtual network gateways connections created. /// </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<VirtualNetworkGatewayConnection>> ListNextAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Linq; using System.Web.Mvc; using FluentSecurity.TestHelper.Expectations; using FluentSecurity.TestHelper.Specification.TestData; using NUnit.Framework; namespace FluentSecurity.TestHelper.Specification { [TestFixture] [Category("ExpectationExpressionSpec")] public class When_creating_an_expectation_expression_for_AdminController { private ExpectationExpression<AdminController> _expectationExpression; [SetUp] public void SetUp() { _expectationExpression = new ExpectationExpression<AdminController>(); } [Test] public void Should_have_type_set_to_AdminController() { Assert.That(_expectationExpression.Controller, Is.EqualTo(typeof(AdminController))); } [Test] public void Should_have_action_set_to_null() { Assert.That(_expectationExpression.Action, Is.Null); } [Test] public void Should_have_0_expectations() { Assert.That(_expectationExpression.Expectations.Count(), Is.EqualTo(0)); } } [TestFixture] [Category("ExpectationExpressionSpec")] public class When_creating_an_expectation_expression_for_AdminController_Login { private ExpectationExpression<AdminController> _expectationExpression; [SetUp] public void SetUp() { _expectationExpression = new ExpectationExpression<AdminController>(x => x.Login()); } [Test] public void Should_have_type_set_to_AdminController() { Assert.That(_expectationExpression.Controller, Is.EqualTo(typeof(AdminController))); } [Test] public void Should_have_action_set_to_null() { Assert.That(_expectationExpression.Action, Is.EqualTo("Login")); } [Test] public void Should_have_0_expectations() { Assert.That(_expectationExpression.Expectations.Count(), Is.EqualTo(0)); } } [TestFixture] [Category("ExpectationExpressionSpec")] public class When_adding_expectations_to_an_expectation_expression_for_AdminController_Login { private ExpectationExpression<AdminController> _expectationExpression; [SetUp] public void SetUp() { _expectationExpression = new ExpectationExpression<AdminController>(x => x.Login()); } [Test] public void Should_throw_when_expectation_is_null() { // Arrange IExpectation expectation = null; // Act & assert Assert.Throws<ArgumentNullException>(() => _expectationExpression.Add(expectation)); } [Test] public void Should_have_1_expectations() { // Arrange var expectation = new HasTypeExpectation<DenyInternetExplorerPolicy>(); // Act _expectationExpression.Add(expectation); // Assert Assert.That(_expectationExpression.Expectations.Count(), Is.EqualTo(1)); } [Test] public void Should_have_2_expectations() { // Arrange var expectation1 = new HasTypeExpectation<DenyInternetExplorerPolicy>(); var expectation2 = new DoesNotHaveTypeExpectation<DenyInternetExplorerPolicy>(); // Act _expectationExpression.Add(expectation1).Add(expectation2); // Assert Assert.That(_expectationExpression.Expectations.Count(), Is.EqualTo(2)); } } [TestFixture] [Category("ExpectationExpressionSpec")] public class When_creating_an_expectation_expression_for_SampleController_AliasedAction { private ExpectationExpression<SampleController> _expectationExpression; [SetUp] public void SetUp() { _expectationExpression = new ExpectationExpression<SampleController>(x => x.ActualAction()); } [Test] public void Should_resolve_actual_action_to_aliased_action() { Assert.That(_expectationExpression.Action, Is.EqualTo("AliasedAction")); } } [TestFixture] [Category("ExpectationExpressionSpec")] public class When_creating_an_expectation_expression_for_TaskController_ActionResult { private ExpectationExpression<TaskController> _expectationExpression; [SetUp] public void SetUp() { _expectationExpression = new ExpectationExpression<TaskController>(x => x.LongRunningAction()); _expectationExpression.Add(new HasTypeExpectation<DenyInternetExplorerPolicy>()); } [Test] public void Should_have_type_set_to_TypeController() { Assert.That(_expectationExpression.Controller, Is.EqualTo(typeof(TaskController))); } [Test] public void Should_have_action_set_to_LongRunningAction() { Assert.That(_expectationExpression.Action, Is.EqualTo("LongRunningAction")); } [Test] public void Should_have_1_expectations() { Assert.That(_expectationExpression.Expectations.Count(), Is.EqualTo(1)); } } [TestFixture] [Category("ExpectationExpressionSpec")] public class When_creating_an_expectation_expression_for_TaskController_JsonResult { private ExpectationExpression<TaskController> _expectationExpression; [SetUp] public void SetUp() { _expectationExpression = new ExpectationExpression<TaskController>(x => x.LongRunningJsonAction()); _expectationExpression.Add(new HasTypeExpectation<DenyInternetExplorerPolicy>()); } [Test] public void Should_have_type_set_to_TaskController() { Assert.That(_expectationExpression.Controller, Is.EqualTo(typeof(TaskController))); } [Test] public void Should_have_action_set_to_LongRunningAction() { Assert.That(_expectationExpression.Action, Is.EqualTo("LongRunningJsonAction")); } [Test] public void Should_have_1_expectations() { Assert.That(_expectationExpression.Expectations.Count(), Is.EqualTo(1)); } } [TestFixture] [Category("ExpectationExpressionSpec")] public class When_creating_an_expectation_expression_for_SampleController_VoidAction { private ExpectationExpression<SampleController> _expectationExpression; [SetUp] public void SetUp() { _expectationExpression = new ExpectationExpression<SampleController>(x => x.VoidAction()); _expectationExpression.Add(new HasTypeExpectation<DenyInternetExplorerPolicy>()); } [Test] public void Should_have_type_set_to_SampleController() { Assert.That(_expectationExpression.Controller, Is.EqualTo(typeof(SampleController))); } [Test] public void Should_have_action_set_to_VoidAction() { Assert.That(_expectationExpression.Action, Is.EqualTo("VoidAction")); } [Test] public void Should_have_1_expectations() { Assert.That(_expectationExpression.Expectations.Count(), Is.EqualTo(1)); } } }
/* * The MIT License (MIT) * * Copyright (c) 2013 Alistair Leslie-Hughes * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Runtime.InteropServices; namespace Microsoft.DirectX { [Serializable] public struct Quaternion { public float X; public float Y; public float Z; public float W; public static Quaternion Identity { get { Quaternion quat = new Quaternion(); quat.X = 0.0f; quat.Y = 0.0f; quat.Z = 0.0f; quat.W = 1.0f; return quat; } } [DllImport("d3dx9_43.dll")] private unsafe static extern Quaternion* D3DXQuaternionRotationMatrix(Quaternion *res, Matrix *src); public static Quaternion Zero { get { throw new NotImplementedException (); } } public override bool Equals (object compare) { throw new NotImplementedException (); } public static bool operator == (Quaternion left, Quaternion right) { throw new NotImplementedException (); } public static bool operator != (Quaternion left, Quaternion right) { throw new NotImplementedException (); } public override int GetHashCode () { throw new NotImplementedException (); } public Quaternion (float valueX, float valueY, float valueZ, float valueW) { throw new NotImplementedException (); } public override string ToString () { throw new NotImplementedException (); } public static Quaternion operator + (Quaternion left, Quaternion right) { throw new NotImplementedException (); } public static Quaternion operator * (Quaternion left, Quaternion right) { throw new NotImplementedException (); } public static Quaternion operator - (Quaternion left, Quaternion right) { throw new NotImplementedException (); } public static Quaternion Add (Quaternion m1, Quaternion m2) { throw new NotImplementedException (); } public static Quaternion Subtract (Quaternion m1, Quaternion m2) { throw new NotImplementedException (); } public float Length () { throw new NotImplementedException (); } public static float Length (Quaternion v) { throw new NotImplementedException (); } public float LengthSq () { throw new NotImplementedException (); } public static float LengthSq (Quaternion v) { throw new NotImplementedException (); } public static float Dot (Quaternion v1, Quaternion v2) { throw new NotImplementedException (); } public static Quaternion Conjugate (Quaternion q) { throw new NotImplementedException (); } public static void ToAxisAngle (Quaternion q, ref Vector3 axis, ref float angle) { throw new NotImplementedException (); } public unsafe static Quaternion RotationMatrix (Matrix m) { Quaternion result = new Quaternion(); D3DXQuaternionRotationMatrix(&result, &m); return result; } public static Quaternion RotationAxis (Vector3 v, float angle) { throw new NotImplementedException (); } public static Quaternion RotationYawPitchRoll (float yaw, float pitch, float roll) { throw new NotImplementedException (); } public void Multiply (Quaternion q) { throw new NotImplementedException (); } public static Quaternion Multiply (Quaternion m1, Quaternion m2) { throw new NotImplementedException (); } public void Normalize () { throw new NotImplementedException (); } public static Quaternion Normalize (Quaternion q) { throw new NotImplementedException (); } public void Invert () { throw new NotImplementedException (); } public static Quaternion Invert (Quaternion q) { throw new NotImplementedException (); } public void Ln () { throw new NotImplementedException (); } public static Quaternion Ln (Quaternion q) { throw new NotImplementedException (); } public void Exp () { throw new NotImplementedException (); } public static Quaternion Exp (Quaternion q) { throw new NotImplementedException (); } public static Quaternion Slerp (Quaternion q1, Quaternion q2, float t) { throw new NotImplementedException (); } public static Quaternion Squad (Quaternion q1, Quaternion a, Quaternion b, Quaternion c, float t) { throw new NotImplementedException (); } public static Quaternion BaryCentric (Quaternion q1, Quaternion q2, Quaternion q3, float f, float g) { throw new NotImplementedException (); } public static void SquadSetup (ref Quaternion outA, ref Quaternion outB, ref Quaternion outC, Quaternion q0, Quaternion q1, Quaternion q2, Quaternion q3) { throw new NotImplementedException (); } public void RotateMatrix (Matrix m) { throw new NotImplementedException (); } public void RotateAxis (Vector3 v, float angle) { throw new NotImplementedException (); } public void RotateYawPitchRoll (float yaw, float pitch, float roll) { throw new NotImplementedException (); } } }
// 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. #pragma warning disable 0420 // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // A lock-free, concurrent stack primitive, and its associated debugger view type. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.ConstrainedExecution; using System.Runtime.Serialization; using System.Security; using System.Threading; namespace System.Collections.Concurrent { // A stack that uses CAS operations internally to maintain thread-safety in a lock-free // manner. Attempting to push or pop concurrently from the stack will not trigger waiting, // although some optimistic concurrency and retry is used, possibly leading to lack of // fairness and/or livelock. The stack uses spinning and backoff to add some randomization, // in hopes of statistically decreasing the possibility of livelock. // // Note that we currently allocate a new node on every push. This avoids having to worry // about potential ABA issues, since the CLR GC ensures that a memory address cannot be // reused before all references to it have died. /// <summary> /// Represents a thread-safe last-in, first-out collection of objects. /// </summary> /// <typeparam name="T">Specifies the type of elements in the stack.</typeparam> /// <remarks> /// All public and protected members of <see cref="ConcurrentStack{T}"/> are thread-safe and may be used /// concurrently from multiple threads. /// </remarks> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<>))] internal class ConcurrentStack<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T> { /// <summary> /// A simple (internal) node type used to store elements of concurrent stacks and queues. /// </summary> private class Node { internal readonly T m_value; // Value of the node. internal Node m_next; // Next pointer. /// <summary> /// Constructs a new node with the specified value and no next node. /// </summary> /// <param name="value">The value of the node.</param> internal Node(T value) { m_value = value; m_next = null; } } private volatile Node m_head; // The stack is a singly linked list, and only remembers the head. private const int BACKOFF_MAX_YIELDS = 8; // Arbitrary number to cap backoff. /// <summary> /// Initializes a new instance of the <see cref="ConcurrentStack{T}"/> /// class. /// </summary> public ConcurrentStack() { } /// <summary> /// Gets the number of elements contained in the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <value>The number of elements contained in the <see cref="ConcurrentStack{T}"/>.</value> /// <remarks> /// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/> /// property is recommended rather than retrieving the number of items from the <see cref="Count"/> /// property and comparing it to 0. /// </remarks> public int Count { // Counts the number of entries in the stack. This is an O(n) operation. The answer may be out // of date before returning, but guarantees to return a count that was once valid. Conceptually, // the implementation snaps a copy of the list and then counts the entries, though physically // this is not what actually happens. get { int count = 0; // Just whip through the list and tally up the number of nodes. We rely on the fact that // node next pointers are immutable after being enqueued for the first time, even as // they are being dequeued. If we ever changed this (e.g. to pool nodes somehow), // we'd need to revisit this implementation. for (Node curr = m_head; curr != null; curr = curr.m_next) { count++; //we don't handle overflow, to be consistent with existing generic collection types in CLR } return count; } } /// <summary> /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is /// synchronized with the SyncRoot. /// </summary> /// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized /// with the SyncRoot; otherwise, false. For <see cref="ConcurrentStack{T}"/>, this property always /// returns false.</value> bool ICollection.IsSynchronized { // Gets a value indicating whether access to this collection is synchronized. Always returns // false. The reason is subtle. While access is in face thread safe, it's not the case that // locking on the SyncRoot would have prevented concurrent pushes and pops, as this property // would typically indicate; that's because we internally use CAS operations vs. true locks. get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see /// cref="T:System.Collections.ICollection"/>. This property is not supported. /// </summary> /// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported</exception> object ICollection.SyncRoot { get { throw new NotSupportedException(SR.ConcurrentCollection_SyncRoot_NotSupported); } } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see /// cref="T:System.Array"/>, starting at a particular /// <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of /// the elements copied from the /// <see cref="ConcurrentStack{T}"/>. The <see cref="T:System.Array"/> must /// have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"> /// <paramref name="array"/> is multidimensional. -or- /// <paramref name="array"/> does not have zero-based indexing. -or- /// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is /// greater than the available space from <paramref name="index"/> to the end of the destination /// <paramref name="array"/>. -or- The type of the source <see /// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the /// destination <paramref name="array"/>. /// </exception> void ICollection.CopyTo(Array array, int index) { // Validate arguments. if (array == null) { throw new ArgumentNullException(nameof(array)); } // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether // the array is sufficiently large to hold the stack's contents. ((ICollection)ToList()).CopyTo(array, index); } /// <summary> /// Copies the <see cref="ConcurrentStack{T}"/> elements to an existing one-dimensional <see /// cref="T:System.Array"/>, starting at the specified array index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of /// the elements copied from the /// <see cref="ConcurrentStack{T}"/>. The <see cref="T:System.Array"/> must have zero-based /// indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the /// length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="ConcurrentStack{T}"/> is greater than the /// available space from <paramref name="index"/> to the end of the destination <paramref /// name="array"/>. /// </exception> public void CopyTo(T[] array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether // the array is sufficiently large to hold the stack's contents. ToList().CopyTo(array, index); } /// <summary> /// Inserts an object at the top of the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <param name="item">The object to push onto the <see cref="ConcurrentStack{T}"/>. The value can be /// a null reference (Nothing in Visual Basic) for reference types. /// </param> public void Push(T item) { // Pushes a node onto the front of the stack thread-safely. Internally, this simply // swaps the current head pointer using a (thread safe) CAS operation to accomplish // lock freedom. If the CAS fails, we add some back off to statistically decrease // contention at the head, and then go back around and retry. Node newNode = new Node(item); newNode.m_next = m_head; if (Interlocked.CompareExchange(ref m_head, newNode, newNode.m_next) == newNode.m_next) { return; } // If we failed, go to the slow path and loop around until we succeed. PushCore(newNode, newNode); } /// <summary> /// Push one or many nodes into the stack, if head and tails are equal then push one node to the stack other wise push the list between head /// and tail to the stack /// </summary> /// <param name="head">The head pointer to the new list</param> /// <param name="tail">The tail pointer to the new list</param> private void PushCore(Node head, Node tail) { SpinWait spin = new SpinWait(); // Keep trying to CAS the exising head with the new node until we succeed. do { spin.SpinOnce(); // Reread the head and link our new node. tail.m_next = m_head; } while (Interlocked.CompareExchange( ref m_head, head, tail.m_next) != tail.m_next); } /// <summary> /// Attempts to pop and return the object at the top of the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <param name="result"> /// When this method returns, if the operation was successful, <paramref name="result"/> contains the /// object removed. If no object was available to be removed, the value is unspecified. /// </param> /// <returns>true if an element was removed and returned from the top of the <see /// cref="ConcurrentStack{T}"/> /// successfully; otherwise, false.</returns> public bool TryPop(out T result) { Node head = m_head; //stack is empty if (head == null) { result = default(T); return false; } if (Interlocked.CompareExchange(ref m_head, head.m_next, head) == head) { result = head.m_value; return true; } // Fall through to the slow path. return TryPopCore(out result); } /// <summary> /// Local helper function to Pop an item from the stack, slow path /// </summary> /// <param name="result">The popped item</param> /// <returns>True if succeeded, false otherwise</returns> private bool TryPopCore(out T result) { Node poppedNode; if (TryPopCore(1, out poppedNode) == 1) { result = poppedNode.m_value; return true; } result = default(T); return false; } /// <summary> /// Slow path helper for TryPop. This method assumes an initial attempt to pop an element /// has already occurred and failed, so it begins spinning right away. /// </summary> /// <param name="count">The number of items to pop.</param> /// <param name="poppedHead"> /// When this method returns, if the pop succeeded, contains the removed object. If no object was /// available to be removed, the value is unspecified. This parameter is passed uninitialized. /// </param> /// <returns>True if an element was removed and returned; otherwise, false.</returns> private int TryPopCore(int count, out Node poppedHead) { SpinWait spin = new SpinWait(); // Try to CAS the head with its current next. We stop when we succeed or // when we notice that the stack is empty, whichever comes first. Node head; Node next; int backoff = 1; Random r = null; while (true) { head = m_head; // Is the stack empty? if (head == null) { poppedHead = null; return 0; } next = head; int nodesCount = 1; for (; nodesCount < count && next.m_next != null; nodesCount++) { next = next.m_next; } // Try to swap the new head. If we succeed, break out of the loop. if (Interlocked.CompareExchange(ref m_head, next.m_next, head) == head) { // Return the popped Node. poppedHead = head; return nodesCount; } // We failed to CAS the new head. Spin briefly and retry. for (int i = 0; i < backoff; i++) { spin.SpinOnce(); } if (spin.NextSpinWillYield) { if (r == null) { r = new Random(); } backoff = r.Next(1, BACKOFF_MAX_YIELDS); } else { backoff *= 2; } } } /// <summary> /// Copies the items stored in the <see cref="ConcurrentStack{T}"/> to a new array. /// </summary> /// <returns>A new array containing a snapshot of elements copied from the <see /// cref="ConcurrentStack{T}"/>.</returns> public T[] ToArray() { return ToList().ToArray(); } /// <summary> /// Returns an array containing a snapshot of the list's contents, using /// the target list node as the head of a region in the list. /// </summary> /// <returns>An array of the list's contents.</returns> private List<T> ToList() { List<T> list = new List<T>(); Node curr = m_head; while (curr != null) { list.Add(curr.m_value); curr = curr.m_next; } return list; } /// <summary> /// Returns an enumerator that iterates through the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <returns>An enumerator for the <see cref="ConcurrentStack{T}"/>.</returns> /// <remarks> /// The enumeration represents a moment-in-time snapshot of the contents /// of the stack. It does not reflect any updates to the collection after /// <see cref="GetEnumerator"/> was called. The enumerator is safe to use /// concurrently with reads from and writes to the stack. /// </remarks> public IEnumerator<T> GetEnumerator() { // Returns an enumerator for the stack. This effectively takes a snapshot // of the stack's contents at the time of the call, i.e. subsequent modifications // (pushes or pops) will not be reflected in the enumerator's contents. //If we put yield-return here, the iterator will be lazily evaluated. As a result a snapshot of //the stack is not taken when GetEnumerator is initialized but when MoveNext() is first called. //This is inconsistent with existing generic collections. In order to prevent it, we capture the //value of m_head in a buffer and call out to a helper method return GetEnumerator(m_head); } private IEnumerator<T> GetEnumerator(Node head) { Node current = head; while (current != null) { yield return current.m_value; current = current.m_next; } } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns>An <see cref="T:System.Collections.IEnumerator"/> that can be used to iterate through /// the collection.</returns> /// <remarks> /// The enumeration represents a moment-in-time snapshot of the contents of the stack. It does not /// reflect any updates to the collection after /// <see cref="GetEnumerator"/> was called. The enumerator is safe to use concurrently with reads /// from and writes to the stack. /// </remarks> IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<T>)this).GetEnumerator(); } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Apache License, Version 2.0. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Diagnostics; using System.Collections; using System.IO; using System.Xml; using System.Xml.Schema; using System.Security; using Common; using System.Collections.ObjectModel; namespace Randoop { /// <summary> /// This is a special transformer that doesn't transform any state /// but instead represents a plan that yields a primitive value. /// </summary> public class PrimitiveValueTransformer : Transformer { public readonly Type ftype; public readonly object fvalue; private static Dictionary<TypeValuePair, PrimitiveValueTransformer> cachedTransformers = new Dictionary<TypeValuePair, PrimitiveValueTransformer>(); public static PrimitiveValueTransformer Get(Type type, object value) { //if (ReflectionUtils.IsStaticClass(type)) //{ // throw new ArgumentException("Type is static class: " + type.ToString()); //} TypeValuePair p = new TypeValuePair(type, value); PrimitiveValueTransformer t; cachedTransformers.TryGetValue(p, out t); if (t == null) cachedTransformers[p] = t = new PrimitiveValueTransformer(type, value); return t; } public override string MemberName { get { return "n/a"; } } public override int TupleIndexOfIthInputParam(int i) { throw new NotImplementedException("Operation not supported."); } public override Type[] TupleTypes { get { return new Type[] { ftype }; } } public override bool[] DefaultActiveTupleTypes { get { return new bool[] { true }; } } public override Type[] ParameterTypes { get { return new Type[0]; } } public bool IsNull { get { if (ftype.IsPrimitive) return false; if (fvalue == null) return true; else return false; } } private static Type systemEnum = Type.GetType("System.Enum"); /// <summary> /// Method returns "string_rep_not_available" when no string representation is available /// </summary> /// <returns></returns> public override string ToString() { if (fvalue == null) return "null"; if (fvalue.GetType().Equals(typeof(string))) { return SourceCodePrinting.toSourceCodeString((string)fvalue); } string fvalueToString = null; Type fvalueType = null; try { fvalueToString = fvalue.ToString(); fvalueType = fvalue.GetType(); } catch (Exception) { return "not_printable_ToString_Crashed"; } if (fvalueType.IsPrimitive) { if (fvalueType.Equals(typeof(bool))) return "(" + ftype.ToString() + ")" + (fvalueToString.ToLower()); if (fvalueType.Equals(typeof(byte))) return "(" + ftype.ToString() + ")" + SourceCodePrinting.ToCodeString2((byte)fvalue); if (fvalueType.Equals(typeof(short))) return "(" + ftype.ToString() + ")" + SourceCodePrinting.ToCodeString2((short)fvalue); if (fvalueType.Equals(typeof(int))) return "(" + ftype.ToString() + ")" + SourceCodePrinting.ToCodeString2((int)fvalue); if (fvalueType.Equals(typeof(long))) return "(" + ftype.ToString() + ")" + SourceCodePrinting.ToCodeString2((long)fvalue); if (fvalueType.Equals(typeof(float))) return "(" + ftype.ToString() + ")" + SourceCodePrinting.ToCodeString2((float)fvalue); if (fvalueType.Equals(typeof(double))) return "(" + ftype.ToString() + ")" + SourceCodePrinting.ToCodeString2((double)fvalue); if (fvalueType.Equals(typeof(char))) { return "\'" + fvalueToString + "\'"; } else return "(" + ftype.ToString() + ") (" + fvalueToString + ")"; } if (ftype.BaseType.Equals(systemEnum)) { return SourceCodePrinting.ToCodeString(ftype) + "." + fvalueToString; } if (fvalueType.IsValueType) { //check to see if this is the default value bool vEqArray = false; try { ValueType v = fvalue as ValueType; vEqArray = v.Equals(Array.CreateInstance(ftype, 1).GetValue(0)); } catch (Exception) { // Let vEqArray stay false. } if (vEqArray) { string tStr = "typeof(" + SourceCodePrinting.ToCodeString(ftype) + ")"; string s = "(" + SourceCodePrinting.ToCodeString(ftype) + ")(System.Array.CreateInstance(" + tStr + ", 1)).GetValue(0)"; return s; } else { try { //just perform a typecast to be sure (e.g. 1.1 is not recognized as a float unless cast return "(" + SourceCodePrinting.ToCodeString(ftype) + ")(" + fvalueToString + ")"; } catch { //This operation raises an exception sometime //Util.Warning("The default value of ValueType<" + ftype.Name + "> is not" + fvalue.ToString()); return ("\"__randoop_string_rep_not_available_forType<" + ftype.Name + ">\""); } } } //just plain unlucky in this case return ("\"__randoop_string_rep_not_available_forType<" + ftype.Name + ">\""); } // TODO Handle other cases (e.g. newlines?) private string ToSourceCodestring(string fvalueToString) { return fvalueToString.Replace("\\", "\\\\").Replace("\"", "\\\""); } public override bool Equals(object obj) { PrimitiveValueTransformer p = obj as PrimitiveValueTransformer; if (p == null) return false; if (!this.ftype.Equals(p.ftype)) return false; if (fvalue == null) { if (p.fvalue == null) return true; else return false; } else { try { return fvalue.Equals(p.fvalue); } catch (Exception) { // Execution of code under test led to an exception. return false; } } } public override int GetHashCode() { return ftype.GetHashCode() + ((fvalue == null || fvalue.GetType().IsValueType) ? 0 : fvalue.GetHashCode()); } private PrimitiveValueTransformer(Type type, object value) { if (type.IsValueType) { if (value == null) throw new ArgumentException("value can't be null for a value type."); if (!value.GetType().Equals(type)) throw new ArgumentException("type of value is not equal to type parameters."); } else { if (value != null && !value.GetType().Equals(typeof(string))) throw new ArgumentException("value must be null for a non-value, non-string type."); } this.ftype = type; this.fvalue = value; } public override string ToCSharpCode(ReadOnlyCollection<string> arguments, String newValueName) { StringBuilder b = new StringBuilder(); b.Append( SourceCodePrinting.ToCodeString(this.ftype) + " " + newValueName + " = " + this.ToString() + ";"); return b.ToString(); } public override bool Execute(out ResultTuple ret, ResultTuple[] results, Plan.ParameterChooser[] parameterMap, TextWriter executionLog, TextWriter debugLog, out Exception exceptionThrown, out bool contractViolated, bool forbidNull) { contractViolated = false; //if (forbidNull) // Util.Assert(fvalue != null); exceptionThrown = null; ret = new ResultTuple(ftype, new object[] { fvalue }); return true; } private void AddIfDifferentFromValue(Collection<object> l, object o) { if (!Util.SafeEqual(o, this.fvalue)) l.Add(o); } public override string Namespace { get { return this.ftype.Namespace; } } public override ReadOnlyCollection<Assembly> Assemblies { get { return ReflectionUtils.GetRelatedAssemblies(this.ftype); } } } }
namespace Factotum { partial class GridProcedureView { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GridProcedureView)); this.btnEdit = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.btnAdd = new System.Windows.Forms.Button(); this.btnDelete = new System.Windows.Forms.Button(); this.cboStatusFilter = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.dgvGridProcedureList = new Factotum.DataGridViewStd(); this.panel1 = new System.Windows.Forms.Panel(); this.cboInOutageFilter = new System.Windows.Forms.ComboBox(); this.label6 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.dgvGridProcedureList)).BeginInit(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // btnEdit // this.btnEdit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnEdit.Location = new System.Drawing.Point(11, 234); this.btnEdit.Name = "btnEdit"; this.btnEdit.Size = new System.Drawing.Size(64, 22); this.btnEdit.TabIndex = 2; this.btnEdit.Text = "Edit"; this.btnEdit.UseVisualStyleBackColor = true; this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(15, 71); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(102, 13); this.label1.TabIndex = 5; this.label1.Text = "Grid Procedures List"; // // btnAdd // this.btnAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnAdd.Location = new System.Drawing.Point(81, 234); this.btnAdd.Name = "btnAdd"; this.btnAdd.Size = new System.Drawing.Size(64, 22); this.btnAdd.TabIndex = 3; this.btnAdd.Text = "Add"; this.btnAdd.UseVisualStyleBackColor = true; this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); // // btnDelete // this.btnDelete.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnDelete.Location = new System.Drawing.Point(151, 234); this.btnDelete.Name = "btnDelete"; this.btnDelete.Size = new System.Drawing.Size(64, 22); this.btnDelete.TabIndex = 4; this.btnDelete.Text = "Delete"; this.btnDelete.UseVisualStyleBackColor = true; this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); // // cboStatusFilter // this.cboStatusFilter.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.cboStatusFilter.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboStatusFilter.FormattingEnabled = true; this.cboStatusFilter.Items.AddRange(new object[] { "Active", "Inactive"}); this.cboStatusFilter.Location = new System.Drawing.Point(235, 5); this.cboStatusFilter.Name = "cboStatusFilter"; this.cboStatusFilter.Size = new System.Drawing.Size(85, 21); this.cboStatusFilter.TabIndex = 3; this.cboStatusFilter.SelectedIndexChanged += new System.EventHandler(this.cboStatus_SelectedIndexChanged); // // label2 // this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(192, 8); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(37, 13); this.label2.TabIndex = 2; this.label2.Text = "Status"; // // dgvGridProcedureList // this.dgvGridProcedureList.AllowUserToAddRows = false; this.dgvGridProcedureList.AllowUserToDeleteRows = false; this.dgvGridProcedureList.AllowUserToOrderColumns = true; this.dgvGridProcedureList.AllowUserToResizeRows = false; this.dgvGridProcedureList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dgvGridProcedureList.Location = new System.Drawing.Point(15, 86); this.dgvGridProcedureList.MultiSelect = false; this.dgvGridProcedureList.Name = "dgvGridProcedureList"; this.dgvGridProcedureList.ReadOnly = true; this.dgvGridProcedureList.RowHeadersVisible = false; this.dgvGridProcedureList.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dgvGridProcedureList.Size = new System.Drawing.Size(328, 128); this.dgvGridProcedureList.StandardTab = true; this.dgvGridProcedureList.TabIndex = 6; this.dgvGridProcedureList.DoubleClick += new System.EventHandler(this.btnEdit_Click); this.dgvGridProcedureList.KeyDown += new System.Windows.Forms.KeyEventHandler(this.dgvGridProcedureList_KeyDown); // // panel1 // this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel1.Controls.Add(this.cboInOutageFilter); this.panel1.Controls.Add(this.label6); this.panel1.Controls.Add(this.cboStatusFilter); this.panel1.Controls.Add(this.label2); this.panel1.ForeColor = System.Drawing.SystemColors.ControlText; this.panel1.Location = new System.Drawing.Point(15, 18); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(327, 34); this.panel1.TabIndex = 1; // // cboInOutageFilter // this.cboInOutageFilter.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboInOutageFilter.FormattingEnabled = true; this.cboInOutageFilter.Items.AddRange(new object[] { "All", "Yes"}); this.cboInOutageFilter.Location = new System.Drawing.Point(65, 5); this.cboInOutageFilter.Name = "cboInOutageFilter"; this.cboInOutageFilter.Size = new System.Drawing.Size(85, 21); this.cboInOutageFilter.TabIndex = 1; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(5, 8); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(54, 13); this.label6.TabIndex = 0; this.label6.Text = "In Outage"; // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.ForeColor = System.Drawing.SystemColors.ControlText; this.label5.Location = new System.Drawing.Point(22, 9); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(53, 13); this.label5.TabIndex = 0; this.label5.Text = "List Filters"; // // GridProcedureView // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(355, 268); this.Controls.Add(this.label5); this.Controls.Add(this.panel1); this.Controls.Add(this.dgvGridProcedureList); this.Controls.Add(this.btnDelete); this.Controls.Add(this.btnAdd); this.Controls.Add(this.label1); this.Controls.Add(this.btnEdit); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(363, 302); this.Name = "GridProcedureView"; this.Text = " View Grid Procedures"; this.Load += new System.EventHandler(this.GridProcedureView_Load); this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.GridProcedureView_FormClosed); ((System.ComponentModel.ISupportInitialize)(this.dgvGridProcedureList)).EndInit(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnEdit; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button btnAdd; private System.Windows.Forms.Button btnDelete; private System.Windows.Forms.ComboBox cboStatusFilter; private System.Windows.Forms.Label label2; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label label5; private System.Windows.Forms.ComboBox cboInOutageFilter; private System.Windows.Forms.Label label6; private DataGridViewStd dgvGridProcedureList; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Sparrow; using Voron.Data.BTrees; using Voron.Data.Fixed; using Voron.Data.RawData; using Voron.Global; using Voron.Impl; using Voron.Impl.Paging; using Voron.Util.Conversion; namespace Voron.Data.Tables { public unsafe class Table : ICommittable { private readonly TableSchema _schema; private readonly Transaction _tx; private readonly Tree _tableTree; private ActiveRawDataSmallSection _activeDataSmallSection; private FixedSizeTree _fstKey; private FixedSizeTree _inactiveSections; private FixedSizeTree _activeCandidateSection; private readonly int _pageSize; private Dictionary<Slice, Tree> _treesBySliceCache; private readonly Dictionary<Slice, Dictionary<Slice, FixedSizeTree>> _fixedSizeTreeCache = new Dictionary<Slice, Dictionary<Slice, FixedSizeTree>>(SliceComparer.Instance); public readonly string Name; public long NumberOfEntries { get; private set; } public FixedSizeTree FixedSizeKey { get { if (_fstKey == null) _fstKey = GetFixedSizeTree(_tableTree, _schema.Key.NameAsSlice, sizeof(long)); return _fstKey; } } public FixedSizeTree InactiveSections { get { if (_inactiveSections == null) _inactiveSections = GetFixedSizeTree(_tableTree, TableSchema.InactiveSection, 0); return _inactiveSections; } } public FixedSizeTree ActiveCandidateSection { get { if (_activeCandidateSection == null) _activeCandidateSection = GetFixedSizeTree(_tableTree, TableSchema.ActiveCandidateSection, 0); return _activeCandidateSection; } } public ActiveRawDataSmallSection ActiveDataSmallSection { get { if (_activeDataSmallSection == null) { var readResult = _tableTree.Read(TableSchema.ActiveSection); if (readResult == null) throw new InvalidDataException($"Could not find active sections for {Name}"); long pageNumber = readResult.Reader.ReadLittleEndianInt64(); _activeDataSmallSection = new ActiveRawDataSmallSection(_tx.LowLevelTransaction, pageNumber); _activeDataSmallSection.DataMoved += OnDataMoved; } return _activeDataSmallSection; } } private void OnDataMoved(long previousId, long newId, byte* data, int size) { DeleteValueFromIndex(previousId, new TableValueReader(data, size)); InsertIndexValuesFor(newId, new TableValueReader(data, size)); } public Table(TableSchema schema, string name, Transaction tx) { Name = name; _schema = schema; _tx = tx; _pageSize = _tx.LowLevelTransaction.DataPager.PageSize; _tableTree = _tx.ReadTree(name); if (_tableTree == null) throw new InvalidDataException($"Cannot find collection name {name}"); var stats = (TableSchemaStats*)_tableTree.DirectRead(TableSchema.Stats); if (stats == null) throw new InvalidDataException($"Cannot find stats value for table {name}"); NumberOfEntries = stats->NumberOfEntries; _tx.Register(this); } /// <summary> /// this overload is meant to be used for global reads only, when want to use /// a global index to find data, without touching the actual table. /// </summary> public Table(TableSchema schema, Transaction tx) { _schema = schema; _tx = tx; _pageSize = _tx.LowLevelTransaction.DataPager.PageSize; } public TableValueReader ReadByKey(Slice key) { long id; if (TryFindIdFromPrimaryKey(key, out id) == false) return null; int size; var rawData = DirectRead(id, out size); return new TableValueReader(rawData, size) { Id = id }; } public bool VerifyKeyExists(Slice key) { long id; return TryFindIdFromPrimaryKey(key, out id); } private bool TryFindIdFromPrimaryKey(Slice key, out long id) { var pkTree = GetTree(_schema.Key); var readResult = pkTree.Read(key); if (readResult == null) { id = -1; return false; } id = readResult.Reader.ReadLittleEndianInt64(); return true; } public byte* DirectRead(long id, out int size) { var posInPage = id % _pageSize; if (posInPage == 0) // large { var page = _tx.LowLevelTransaction.GetPage(id / _pageSize); size = page.OverflowSize; return page.Pointer + sizeof(PageHeader); } // here we rely on the fact that RawDataSmallSection can // read any RawDataSmallSection piece of data, not just something that // it exists in its own section, but anything from other sections as well return RawDataSection.DirectRead(_tx.LowLevelTransaction, id, out size); } public long Update(long id, TableValueBuilder builder) { int size = builder.Size; // first, try to fit in place, either in small or large sections var prevIsSmall = id % _pageSize != 0; if (size < ActiveDataSmallSection.MaxItemSize) { byte* pos; if (prevIsSmall && ActiveDataSmallSection.TryWriteDirect(id, size, out pos)) { int oldDataSize; var oldData = ActiveDataSmallSection.DirectRead(id, out oldDataSize); DeleteValueFromIndex(id, new TableValueReader(oldData, oldDataSize)); // MemoryCopy into final position. builder.CopyTo(pos); InsertIndexValuesFor(id, new TableValueReader(pos, size)); return id; } } else if (prevIsSmall == false) { var pageNumber = id / _pageSize; var page = _tx.LowLevelTransaction.GetPage(pageNumber); var existingNumberOfPages = _tx.LowLevelTransaction.DataPager.GetNumberOfOverflowPages(page.OverflowSize); var newNumberOfPages = _tx.LowLevelTransaction.DataPager.GetNumberOfOverflowPages(size); if (existingNumberOfPages == newNumberOfPages) { page.OverflowSize = size; var pos = page.Pointer + sizeof(PageHeader); DeleteValueFromIndex(id, new TableValueReader(pos, size)); // MemoryCopy into final position. builder.CopyTo(pos); InsertIndexValuesFor(id, new TableValueReader(pos, size)); return id; } } // can't fit in place, will just delete & insert instead Delete(id); return Insert(builder); } public void Delete(long id) { int size; var ptr = DirectRead(id, out size); if (ptr == null) return; var stats = (TableSchemaStats*)_tableTree.DirectAdd(TableSchema.Stats, sizeof(TableSchemaStats)); NumberOfEntries--; stats->NumberOfEntries = NumberOfEntries; DeleteValueFromIndex(id, new TableValueReader(ptr, size)); var largeValue = (id % _pageSize) == 0; if (largeValue) { var page = _tx.LowLevelTransaction.GetPage(id / _pageSize); var numberOfPages = _tx.LowLevelTransaction.DataPager.GetNumberOfOverflowPages(page.OverflowSize); for (int i = 0; i < numberOfPages; i++) { _tx.LowLevelTransaction.FreePage(page.PageNumber + i); } return; } var density = ActiveDataSmallSection.Free(id); if (ActiveDataSmallSection.Contains(id) || density > 0.5) return; var sectionPageNumber = ActiveDataSmallSection.GetSectionPageNumber(id); if (density > 0.15) { ActiveCandidateSection.Add(sectionPageNumber); return; } // move all the data to the current active section (maybe creating a new one // if this is busy) // if this is in the active candidate list, remove it so it cannot be reused if the current // active is full and need a new one ActiveCandidateSection.Delete(sectionPageNumber); var idsInSection = ActiveDataSmallSection.GetAllIdsInSectionContaining(id); foreach (var idToMove in idsInSection) { int itemSize; var pos = ActiveDataSmallSection.DirectRead(idToMove, out itemSize); var newId = AllocateFromSmallActiveSection(itemSize); OnDataMoved(idToMove, newId, pos, itemSize); byte* writePos; if (ActiveDataSmallSection.TryWriteDirect(newId, itemSize, out writePos) == false) throw new InvalidDataException($"Cannot write to newly allocated size in {Name} during delete"); Memory.Copy(writePos, pos, itemSize); } ActiveDataSmallSection.DeleteSection(sectionPageNumber); } private void DeleteValueFromIndex(long id, TableValueReader value) { //TODO: Avoid all those allocations by using a single buffer if (_schema.Key != null) { var keySlice = _schema.Key.GetSlice(_tx.Allocator, value); var pkTree = GetTree(_schema.Key); pkTree.Delete(keySlice); } foreach (var indexDef in _schema.Indexes.Values) { // For now we wont create secondary indexes on Compact trees. var indexTree = GetTree(indexDef); var val = indexDef.GetSlice(_tx.Allocator, value); var fst = GetFixedSizeTree(indexTree, val.Clone(_tx.Allocator), 0); fst.Delete(id); } foreach (var indexDef in _schema.FixedSizeIndexes.Values) { var index = GetFixedSizeTree(indexDef); var key = indexDef.GetValue(value); index.Delete(key); } } public long Insert(TableValueBuilder builder) { var stats = (TableSchemaStats*)_tableTree.DirectAdd(TableSchema.Stats, sizeof(TableSchemaStats)); NumberOfEntries++; stats->NumberOfEntries = NumberOfEntries; int size = builder.Size; byte* pos; long id; if (size + sizeof(RawDataSection.RawDataEntrySizes) < ActiveDataSmallSection.MaxItemSize) { id = AllocateFromSmallActiveSection(size); if (ActiveDataSmallSection.TryWriteDirect(id, size, out pos) == false) throw new InvalidOperationException($"After successfully allocating {size:#,#;;0} bytes, failed to write them on {Name}"); // MemoryCopy into final position. builder.CopyTo(pos); } else { var numberOfOverflowPages = _tx.LowLevelTransaction.DataPager.GetNumberOfOverflowPages(size); var page = _tx.LowLevelTransaction.AllocatePage(numberOfOverflowPages); page.Flags = PageFlags.Overflow | PageFlags.RawData; page.OverflowSize = size; pos = page.Pointer + sizeof(PageHeader); builder.CopyTo(pos); id = page.PageNumber * _pageSize; } InsertIndexValuesFor(id, new TableValueReader(pos, size)); return id; } private void InsertIndexValuesFor(long id, TableValueReader value) { var pk = _schema.Key; if (pk != null) { var pkval = pk.GetSlice(_tx.Allocator, value); var pkIndex = GetTree(pk); pkIndex.Add(pkval, Slice.External(_tx.Allocator, (byte*)&id, sizeof(long))); } foreach (var indexDef in _schema.Indexes.Values) { // For now we wont create secondary indexes on Compact trees. var val = indexDef.GetSlice(_tx.Allocator, value); var indexTree = GetTree(indexDef); var index = GetFixedSizeTree(indexTree, val.Clone(_tx.Allocator), 0); index.Add(id); } foreach (var indexDef in _schema.FixedSizeIndexes.Values) { var index = GetFixedSizeTree(indexDef); long key = indexDef.GetValue(value); index.Add(key, Slice.External(_tx.Allocator, (byte*)&id, sizeof(long))); } } private FixedSizeTree GetFixedSizeTree(TableSchema.FixedSizeSchemaIndexDef indexDef) { if (indexDef.IsGlobal) return GetFixedSizeTree(_tx.LowLevelTransaction.RootObjects, indexDef.NameAsSlice, sizeof(long)); var tableTree = _tx.ReadTree(Name); return GetFixedSizeTree(tableTree, indexDef.NameAsSlice, sizeof(long)); } private FixedSizeTree GetFixedSizeTree(Tree parent, Slice name, ushort valSize) { Dictionary<Slice, FixedSizeTree> cache; var parentName = Slice.From( _tx.Allocator, parent.Name ?? Constants.RootTreeName, ByteStringType.Immutable); if (_fixedSizeTreeCache.TryGetValue(parentName, out cache) == false) { _fixedSizeTreeCache[parentName] = cache = new Dictionary<Slice, FixedSizeTree>(SliceComparer.Instance); } FixedSizeTree tree; if (cache.TryGetValue(name, out tree) == false) { var treeName = name.Clone(_tx.Allocator); var fixedSizeTree = new FixedSizeTree(_tx.LowLevelTransaction, parent, treeName, valSize); return cache[fixedSizeTree.Name] = fixedSizeTree; } return tree; } private long AllocateFromSmallActiveSection(int size) { long id; if (ActiveDataSmallSection.TryAllocate(size, out id) == false) { InactiveSections.Add(_activeDataSmallSection.PageNumber); using (var it = ActiveCandidateSection.Iterate()) { if (it.Seek(long.MinValue)) { do { var sectionPageNumber = it.CurrentKey; _activeDataSmallSection = new ActiveRawDataSmallSection(_tx.LowLevelTransaction, sectionPageNumber); if (_activeDataSmallSection.TryAllocate(size, out id)) { ActiveCandidateSection.Delete(sectionPageNumber); return id; } } while (it.MoveNext()); } } _activeDataSmallSection = ActiveRawDataSmallSection.Create(_tx.LowLevelTransaction, Name); var pageNumber = Slice.From(_tx.Allocator, EndianBitConverter.Little.GetBytes(_activeDataSmallSection.PageNumber), ByteStringType.Immutable); _tableTree.Add(TableSchema.ActiveSection, pageNumber); var allocationResult = _activeDataSmallSection.TryAllocate(size, out id); Debug.Assert(allocationResult); } return id; } internal Tree GetTree(Slice name) { if (_treesBySliceCache == null) _treesBySliceCache = new Dictionary<Slice, Tree>(SliceComparer.Instance); Tree tree; if (_treesBySliceCache.TryGetValue(name, out tree)) return tree; var treeHeader = _tableTree.DirectRead(name); if (treeHeader == null) throw new InvalidOperationException($"Cannot find tree {name} in table {Name}"); tree = Tree.Open(_tx.LowLevelTransaction, _tx, (TreeRootHeader*)treeHeader); _treesBySliceCache[name] = tree; return tree; } private Tree GetTree(TableSchema.SchemaIndexDef idx) { if (idx.IsGlobal) return _tx.ReadTree(idx.Name); return GetTree(idx.NameAsSlice); } public void DeleteByKey(Slice key) { var pk = _schema.Key; var pkTree = GetTree(_schema.Key); var readResult = pkTree.Read(key); if (readResult == null) return; // This is an implementation detail. We read the absolute location pointer (absolute offset on the file) long id = readResult.Reader.ReadLittleEndianInt64(); // And delete the element accordingly. Delete(id); } private IEnumerable<TableValueReader> GetSecondaryIndexForValue(Tree tree, Slice value) { var fstIndex = GetFixedSizeTree(tree, value, 0); using (var it = fstIndex.Iterate()) { if (it.Seek(long.MinValue) == false) yield break; do { yield return ReadById(it.CurrentKey); } while (it.MoveNext()); } } private TableValueReader ReadById(long id) { int size; var ptr = DirectRead(id, out size); var secondaryIndexForValue = new TableValueReader(ptr, size) { Id = id }; return secondaryIndexForValue; } public class SeekResult { public Slice Key; public IEnumerable<TableValueReader> Results; } public IEnumerable<SeekResult> SeekForwardFrom(TableSchema.SchemaIndexDef index, string value, bool startsWith = false) { return SeekForwardFrom(index, Slice.From(_tx.Allocator, value, ByteStringType.Immutable), startsWith); } public IEnumerable<SeekResult> SeekForwardFrom(TableSchema.SchemaIndexDef index, Slice value, bool startsWith = false) { var tree = GetTree(index); using (var it = tree.Iterate(false)) { if (startsWith) it.RequiredPrefix = value.Clone(_tx.Allocator); if (it.Seek(value) == false) yield break; do { yield return new SeekResult { Key = it.CurrentKey, Results = GetSecondaryIndexForValue(tree, it.CurrentKey.Clone(_tx.Allocator)) }; } while (it.MoveNext()); } } public IEnumerable<TableValueReader> SeekByPrimaryKey(Slice value) { var pk = _schema.Key; var tree = GetTree(pk); using (var it = tree.Iterate(false)) { if (it.Seek(value) == false) yield break; do { yield return GetTableValueReader(it); } while (it.MoveNext()); } } public TableValueReader SeekLastByPrimaryKey() { var pk = _schema.Key; var tree = GetTree(pk); using (var it = tree.Iterate(false)) { if (it.Seek(Slices.AfterAllKeys) == false) return null; return GetTableValueReader(it); } } public IEnumerable<TableValueReader> SeekForwardFrom(TableSchema.FixedSizeSchemaIndexDef index, long key) { var fst = GetFixedSizeTree(index); using (var it = fst.Iterate()) { if (it.Seek(key) == false) yield break; do { yield return GetTableValueReader(it); } while (it.MoveNext()); } } public IEnumerable<TableValueReader> SeekBackwardFrom(TableSchema.FixedSizeSchemaIndexDef index, long key) { var fst = GetFixedSizeTree(index); using (var it = fst.Iterate()) { if (it.Seek(key) == false && it.SeekToLast() == false) yield break; do { yield return GetTableValueReader(it); } while (it.MovePrev()); } } private TableValueReader GetTableValueReader(FixedSizeTree.IFixedSizeIterator it) { long id; it.Value.CopyTo((byte*)&id); int size; var ptr = DirectRead(id, out size); return new TableValueReader(ptr, size) { Id = id }; } private TableValueReader GetTableValueReader(IIterator it) { long id = it.CreateReaderForCurrent().ReadLittleEndianInt64(); int size; var ptr = DirectRead(id, out size); return new TableValueReader(ptr, size); } public long Set(TableValueBuilder builder) { int size; var read = builder.Read(_schema.Key.StartIndex, out size); long id; if (TryFindIdFromPrimaryKey(Slice.External(_tx.Allocator, read, (ushort)size), out id)) { id = Update(id, builder); return id; } return Insert(builder); } public void DeleteBackwardFrom(TableSchema.FixedSizeSchemaIndexDef index, long value, long numberOfEntriesToDelete) { if (numberOfEntriesToDelete < 0) throw new ArgumentOutOfRangeException(nameof(numberOfEntriesToDelete), "Number of entries should not be negative"); if (numberOfEntriesToDelete == 0) return; var toDelete = new List<long>(); var fst = GetFixedSizeTree(index); using (var it = fst.Iterate()) { if (it.Seek(value) == false && it.SeekToLast() == false) return; do { toDelete.Add(it.CreateReaderForCurrent().ReadLittleEndianInt64()); numberOfEntriesToDelete--; } while (numberOfEntriesToDelete > 0 && it.MovePrev()); } foreach (var id in toDelete) Delete(id); } public long DeleteForwardFrom(TableSchema.SchemaIndexDef index, Slice value, long numberOfEntriesToDelete) { if (numberOfEntriesToDelete < 0) throw new ArgumentOutOfRangeException(nameof(numberOfEntriesToDelete), "Number of entries should not be negative"); if (numberOfEntriesToDelete == 0) return 0; var toDelete = new List<long>(); var tree = GetTree(index); using (var it = tree.Iterate(false)) { if (it.Seek(value) == false) return 0; do { var fst = GetFixedSizeTree(tree, it.CurrentKey.Clone(_tx.Allocator), 0); using (var fstIt = fst.Iterate()) { if (fstIt.Seek(long.MinValue) == false) break; do { toDelete.Add(fstIt.CurrentKey); numberOfEntriesToDelete--; } while (numberOfEntriesToDelete > 0 && fstIt.MoveNext()); } } while (numberOfEntriesToDelete > 0 && it.MoveNext()); } foreach (var id in toDelete) Delete(id); return toDelete.Count; } public bool RequiresParticipation { get { return true; } } public void PrepareForCommit() { if (_treesBySliceCache == null) return; foreach( var item in _treesBySliceCache) { var tree = item.Value; if (!tree.State.IsModified) continue; var treeName = item.Key; var header = (TreeRootHeader*) _tableTree.DirectAdd(treeName, sizeof(TreeRootHeader)); tree.State.CopyTo(header); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests { public class ThenByDescendingTests : EnumerableTests { [Fact] public void SameResultsRepeatCallsIntQuery() { var q = from x1 in new int[] { 1, 6, 0, -1, 3 } from x2 in new int[] { 55, 49, 9, -100, 24, 25 } select new { a1 = x1, a2 = x2 }; Assert.Equal( q.OrderByDescending(e => e.a2).ThenByDescending(f => f.a1), q.OrderByDescending(e => e.a2).ThenByDescending(f => f.a1) ); } [Fact] public void SameResultsRepeatCallsStringQuery() { var q = from x1 in new[] { 55, 49, 9, -100, 24, 25, -1, 0 } from x2 in new[] { "!@#$%^", "C", "AAA", "", null, "Calling Twice", "SoS", string.Empty } where !string.IsNullOrEmpty(x2) select new { a1 = x1, a2 = x2 }; Assert.Equal( q.OrderBy(e => e.a1).ThenByDescending(f => f.a2), q.OrderBy(e => e.a1).ThenByDescending(f => f.a2) ); } [Fact] public void SourceEmpty() { int[] source = { }; Assert.Empty(source.OrderBy(e => e).ThenByDescending(e => e)); } [Fact] public void AscendingKeyThenDescendingKey() { var source = new[] { new { Name = "Jim", City = "Minneapolis", Country = "USA" }, new { Name = "Tim", City = "Seattle", Country = "USA" }, new { Name = "Philip", City = "Orlando", Country = "USA" }, new { Name = "Chris", City = "London", Country = "UK" }, new { Name = "Rob", City = "Kent", Country = "UK" } }; var expected = new[] { new { Name = "Chris", City = "London", Country = "UK" }, new { Name = "Rob", City = "Kent", Country = "UK" }, new { Name = "Tim", City = "Seattle", Country = "USA" }, new { Name = "Philip", City = "Orlando", Country = "USA" }, new { Name = "Jim", City = "Minneapolis", Country = "USA" } }; Assert.Equal(expected, source.OrderBy(e => e.Country).ThenByDescending(e => e.City)); } [Fact] public void DescendingKeyThenDescendingKey() { var source = new[] { new { Name = "Jim", City = "Minneapolis", Country = "USA" }, new { Name = "Tim", City = "Seattle", Country = "USA" }, new { Name = "Philip", City = "Orlando", Country = "USA" }, new { Name = "Chris", City = "London", Country = "UK" }, new { Name = "Rob", City = "Kent", Country = "UK" } }; var expected = new [] { new { Name = "Tim", City = "Seattle", Country = "USA" }, new { Name = "Philip", City = "Orlando", Country = "USA" }, new { Name = "Jim", City = "Minneapolis", Country = "USA" }, new { Name = "Chris", City = "London", Country = "UK" }, new { Name = "Rob", City = "Kent", Country = "UK" } }; Assert.Equal(expected, source.OrderByDescending(e => e.Country).ThenByDescending(e => e.City)); } [Fact] public void OrderIsStable() { var source = @"Because I could not stop for Death - He kindly stopped for me - The Carriage held but just Ourselves - And Immortality.".Split(new []{ ' ', '\n', '\r', '-' }, StringSplitOptions.RemoveEmptyEntries); var expected = new [] { "stopped", "kindly", "could", "stop", "held", "just", "not", "for", "for", "but", "me", "Immortality.", "Ourselves", "Carriage", "Because", "Death", "The", "And", "He", "I" }; Assert.Equal(expected, source.OrderBy(word => char.IsUpper(word[0])).ThenByDescending(word => word.Length)); } [Fact] public void OrderIsStableCustomComparer() { var source = @"Because I could not stop for Death - He kindly stopped for me - The Carriage held but just Ourselves - And Immortality.".Split(new[] { ' ', '\n', '\r', '-' }, StringSplitOptions.RemoveEmptyEntries); var expected = new[] { "me", "not", "for", "for", "but", "stop", "held", "just", "could", "kindly", "stopped", "I", "He", "The", "And", "Death", "Because", "Carriage", "Ourselves", "Immortality." }; Assert.Equal(expected, source.OrderBy(word => char.IsUpper(word[0])).ThenByDescending(word => word.Length, Comparer<int>.Create((w1, w2) => w2.CompareTo(w1)))); } [Fact] public void RunOnce() { var source = @"Because I could not stop for Death - He kindly stopped for me - The Carriage held but just Ourselves - And Immortality.".Split(new[] { ' ', '\n', '\r', '-' }, StringSplitOptions.RemoveEmptyEntries); var expected = new[] { "me", "not", "for", "for", "but", "stop", "held", "just", "could", "kindly", "stopped", "I", "He", "The", "And", "Death", "Because", "Carriage", "Ourselves", "Immortality." }; Assert.Equal(expected, source.RunOnce().OrderBy(word => char.IsUpper(word[0])).ThenByDescending(word => word.Length, Comparer<int>.Create((w1, w2) => w2.CompareTo(w1)))); } [Fact] public void NullSource() { IOrderedEnumerable<int> source = null; AssertExtensions.Throws<ArgumentNullException>("source", () => source.ThenByDescending(i => i)); } [Fact] public void NullKeySelector() { Func<DateTime, int> keySelector = null; AssertExtensions.Throws<ArgumentNullException>("keySelector", () => Enumerable.Empty<DateTime>().OrderBy(e => e).ThenByDescending(keySelector)); } [Fact] public void NullSourceComparer() { IOrderedEnumerable<int> source = null; AssertExtensions.Throws<ArgumentNullException>("source", () => source.ThenByDescending(i => i, null)); } [Fact] public void NullKeySelectorComparer() { Func<DateTime, int> keySelector = null; AssertExtensions.Throws<ArgumentNullException>("keySelector", () => Enumerable.Empty<DateTime>().OrderBy(e => e).ThenByDescending(keySelector, null)); } [Theory] [InlineData(1)] [InlineData(2)] [InlineData(3)] public void SortsLargeAscendingEnumerableCorrectly(int thenBys) { const int Items = 100_000; IEnumerable<int> expected = NumberRangeGuaranteedNotCollectionType(0, Items); IEnumerable<int> unordered = expected.Select(i => i); IOrderedEnumerable<int> ordered = unordered.OrderBy(_ => 0); switch (thenBys) { case 1: ordered = ordered.ThenByDescending(i => -i); break; case 2: ordered = ordered.ThenByDescending(i => 0).ThenByDescending(i => -i); break; case 3: ordered = ordered.ThenByDescending(i => 0).ThenByDescending(i => 0).ThenByDescending(i => -i); break; } Assert.Equal(expected, ordered); } [Theory] [InlineData(1)] [InlineData(2)] [InlineData(3)] public void SortsLargeDescendingEnumerableCorrectly(int thenBys) { const int Items = 100_000; IEnumerable<int> expected = NumberRangeGuaranteedNotCollectionType(0, Items); IEnumerable<int> unordered = expected.Select(i => Items - i - 1); IOrderedEnumerable<int> ordered = unordered.OrderBy(_ => 0); switch (thenBys) { case 1: ordered = ordered.ThenByDescending(i => -i); break; case 2: ordered = ordered.ThenByDescending(i => 0).ThenByDescending(i => -i); break; case 3: ordered = ordered.ThenByDescending(i => 0).ThenByDescending(i => 0).ThenByDescending(i => -i); break; } Assert.Equal(expected, ordered); } [Theory] [InlineData(1)] [InlineData(2)] [InlineData(3)] public void SortsLargeRandomizedEnumerableCorrectly(int thenBys) { const int Items = 100_000; var r = new Random(42); int[] randomized = Enumerable.Range(0, Items).Select(i => r.Next()).ToArray(); IOrderedEnumerable<int> orderedEnumerable = randomized.OrderBy(_ => 0); switch (thenBys) { case 1: orderedEnumerable = orderedEnumerable.ThenByDescending(i => -i); break; case 2: orderedEnumerable = orderedEnumerable.ThenByDescending(i => 0).ThenByDescending(i => -i); break; case 3: orderedEnumerable = orderedEnumerable.ThenByDescending(i => 0).ThenByDescending(i => 0).ThenByDescending(i => -i); break; } int[] ordered = orderedEnumerable.ToArray(); Array.Sort(randomized, (a, b) => a - b); Assert.Equal(randomized, orderedEnumerable); } } }
using System; using System.Reflection.Emit; using System.Security.Policy; using System.Web.UI.WebControls.WebParts; namespace dotless.Test.Specs { using System.Collections.Generic; using Core.Importers; using Core.Parser; using NUnit.Framework; using System.IO; using System.Reflection; class EmbeddedPathResolver : dotless.Core.Input.IPathResolver { public string GetFullPath(string path) { return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), path); } } public class ImportFixture : SpecFixtureBase { private static Parser GetEmbeddedParser(bool isUrlRewritingDisabled, bool importAllFilesAsLess, bool importCssInline) { var fileReader = new dotless.Core.Input.FileReader(new EmbeddedPathResolver()); return new Parser { Importer = new Importer(fileReader) { IsUrlRewritingDisabled = isUrlRewritingDisabled, ImportAllFilesAsLess = importAllFilesAsLess, InlineCssFiles = importCssInline } }; } private static Parser GetParser() { return GetParser(false, false, false); } private static Parser GetParser(bool isUrlRewritingDisabled, bool importAllFilesAsLess, bool importCssInline) { var imports = new Dictionary<string, string>(); imports[@"c:/absolute/file.less"] = @" .windowz .dos { border: none; } "; imports[@"import/error.less"] = @" .windowz .dos { border: none; } .error_mixin { .throw_error(); } "; imports[@"import/error2.less"] = @" .windowz .dos { border: none; } .error_mixin() { .throw_error(); } "; imports["import/other-protocol-test.less"] = @" .first { background-image: url('http://some.com/file.gif'); background-image: url('https://some.com/file.gif'); background-image: url('ftp://some.com/file.gif'); background-image: url('data:xxyhjgjshgjs'); } "; imports["import/twice/with/different/paths.less"] = @" @import-once ""../twice.less""; @import-once ""../other.less""; "; imports["import/twice/with/other.less"] = @" @import-once ""twice.less""; "; imports["import/twice/with/twice.less"] = @" body { background-color: foo; } "; imports["import/import-test-a.less"] = @" @import ""import-test-b.less""; @a: 20%; "; imports["import/import-test-b.less"] = @" @import 'import-test-c'; @b: 100%; .mixin { height: 10px; color: @c; } "; imports["import/import-test-c.less"] = @" @import ""import-test-d.css""; @c: red; #import { color: @c; } "; imports["import/first.less"] = @" @import ""sub1/second.less""; @path: ""../image.gif""; #first { background: url('../image.gif'); background: url(../image.gif); background: url(@path); } "; imports["import/sub1/second.less"] = @" @pathsep: '/'; #second { background: url(../image.gif); background: url(image.gif); background: url(sub2/image.gif); background: url(/sub2/image.gif); background: url(~""@{pathsep}sub2/image2.gif""); } "; imports["/import/absolute.less"] = @"body { background-color: black; }"; imports["import/define-variables.less"] = @"@color: 'blue';"; imports["import/use-variables.less"] = @".test { background-color: @color; }"; imports["empty.less"] = @""; imports["rule.less"] = @".rule { color: black; }"; imports["../import/relative-with-parent-dir.less"] = @"body { background-color: foo; }"; imports["foo.less"] = @"@import ""foo/bar.less"";"; imports["foo/bar.less"] = @"@import ""../lib/color.less"";"; imports["lib/color.less"] = "body { background-color: foo; }"; imports["247-2.less"] = @" @color: red; text { color: @color; }"; imports["247-1.less"] = @" #nsTwoCss { .css() { @import '247-2.less'; } }"; imports["foourl.less"] = @"@import url(""foo/barurl.less"");"; imports["foo/barurl.less"] = @"@import url(""../lib/colorurl.less"");"; imports["lib/colorurl.less"] = "body { background-color: foo; }"; imports["something.css"] = @"body { background-color: foo; invalid ""; }"; imports["isless.css"] = @" @a: 9px; body { margin-right: @a; }"; imports["vardef.less"] = @"@var: 9px;"; imports["css-as-less.css"] = @"@var1: 10px;"; imports["arbitrary-extension-as-less.ext"] = @"@var2: 11px;"; imports["simple-rule.less"] = ".rule { background-color: black; }"; imports["simple-rule.css"] = ".rule { background-color: black; }"; imports["media-scoped-rules.less"] = @"@media (screen) { .rule { background-color: black; } .another-rule { color: white; } }"; imports["nested-rules.less"] = @" .parent-selector { .rule { background-color: black; } .another-rule { color: white; } }"; imports["imports-simple-rule.less"] = @" @import ""simple-rule.less""; .rule2 { background-color: blue; }"; imports["two-level-import.less"] = @" @import ""simple-rule.less""; .rule3 { background-color: red; }"; imports["reference/main.less"] = @" @import ""mixins/test.less""; .mixin(red); "; imports["reference/mixins/test.less"] = @" .mixin(@arg) { .test-ruleset { background-color: @arg; } } "; imports["reference/ruleset-with-child-ruleset-and-rules.less"] = @" .parent { .child { background-color: black; } background-color: blue; } "; imports["two-level-import.less"] = @" @import ""simple-rule.less""; .rule3 { background-color: red; }"; imports["directives.less"] = @" @font-face { font-family: 'Glyphicons Halflings'; } "; imports["mixin-loop.less"] = @" @grid-columns: 12; .float-grid-columns(@class) { .col(@index) { // initial .col((@index + 1), """"); } .col(@index, @list) when (@index =< @grid-columns) { // general .col((@index + 1), """"); } .col(@index, @list) when (@index > @grid-columns) { // terminal } .col(1); // kickstart it } // Create grid for specific class .make-grid(@class) { .float-grid-columns(@class); } @media (screen) { .make-grid(sm); } "; imports["partial-reference-extends-another-reference.less"] = @" .parent { .test { color: black; } } .ext { &:extend(.test all); } "; imports["exact-reference-extends-another-reference.less"] = @" .test { color: black; } .ext { &:extend(.test); } "; imports["reference-with-multiple-selectors.less"] = @" .test, .test2 { color: black; } "; imports["comments.less"] = @" /* This is a comment */ "; imports["math.less"] = @" .rule { width: calc(10px + 2px); } "; imports["generated-selector.less"] = @" @selector: ~"".rule""; @{selector} { color: black; } "; imports["multiple-generated-selectors.less"] = @" @grid-columns: 12; .float-grid-columns(@class) { .col(@index) { // initial @item: ~"".col-@{class}-@{index}""; .col((@index + 1), @item); } .col(@index, @list) when (@index =< @grid-columns) { // general @item: ~"".col-@{class}-@{index}""; .col((@index + 1), ~""@{list}, @{item}""); } .col(@index, @list) when (@index > @grid-columns) { // terminal @{list} { float: left; } } .col(1); // kickstart it } .float-grid-columns(xs); "; imports["import-in-mixin/mixin-definition.less"] = @" .import() { @import ""relative-import.less""; } "; imports["import-in-mixin/relative-import.less"] = @" .rule { color: black; } "; imports["reference-mixin-issue.less"] = @" .mix-me { color: red; @media (min-width: 100px) { color: blue; } .mix-me-child { background-color: black; } }"; imports["nested-import-interpolation-1.less"] = @" @var: ""2""; @import ""nested-import-interpolation-@{var}.less""; "; imports["nested-import-interpolation-2.less"] = @" body { background-color: blue; } "; return new Parser { Importer = new Importer(new DictionaryReader(imports)) { IsUrlRewritingDisabled = isUrlRewritingDisabled, ImportAllFilesAsLess = importAllFilesAsLess, InlineCssFiles = importCssInline} }; } [Test] public void Test247() { var input = @" @import '247-1.less'; #nsTwo { #nsTwoCss > .css(); }"; var expected = @" #nsTwo text { color: red; }"; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void Imports() { var input = @" @import url(""import/import-test-a.less""); //@import url(""import/import-test-a.less""); #import-test { .mixin; width: 10px; height: @a + 10%; } "; var expected = @" @import ""import-test-d.css""; #import { color: red; } .mixin { height: 10px; color: red; } #import-test { height: 10px; color: #ff0000; width: 10px; height: 30%; } "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void OtherProtocolImportTest1() { var input = @" @import 'import/other-protocol-test.less'; "; var expected = @" .first { background-image: url('http://some.com/file.gif'); background-image: url('https://some.com/file.gif'); background-image: url('ftp://some.com/file.gif'); background-image: url('data:xxyhjgjshgjs'); } "; var parser = GetParser(); DictionaryReader dictionaryReader = (DictionaryReader)((Importer)parser.Importer).FileReader; AssertLess(input, expected, parser); // Calling the file reader with url's with a protocolis asking for trouble Assert.AreEqual(1, dictionaryReader.DoesFileExistCalls.Count, "We should not ask the file reader if a protocol file exists"); Assert.AreEqual(1, dictionaryReader.GetFileContentsCalls.Count, "We should not ask the file reader if a protocol file exists"); Assert.AreEqual(@"import/other-protocol-test.less", dictionaryReader.DoesFileExistCalls[0], "We should not ask the file reader if a protocol file exists"); Assert.AreEqual(@"import/other-protocol-test.less", dictionaryReader.GetFileContentsCalls[0], "We should not ask the file reader if a protocol file exists"); } [Test] public void OtherProtocolImportTest2() { var input = @" @import url(http://fonts.googleapis.com/css?family=Open+Sans:regular,bold);"; var parser = GetParser(); DictionaryReader dictionaryReader = (DictionaryReader)((Importer)parser.Importer).FileReader; AssertLessUnchanged(input, parser); // Calling the file reader with url's with a protocolis asking for trouble Assert.AreEqual(0, dictionaryReader.DoesFileExistCalls.Count, "We should not ask the file reader if a protocol file exists"); Assert.AreEqual(0, dictionaryReader.GetFileContentsCalls.Count, "We should not ask the file reader if a protocol file exists"); } [Test] public void OtherProtocolImportTest3() { var input = @" @import url('c:/absolute/file.less');"; var expected = @" .windowz .dos { border: none; } "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ErrorInImport() { var input = @" @import ""import/error.less"";"; var parser = GetParser(); AssertError(@" .throw_error is undefined on line 6 in file 'import/error.less': [5]: .error_mixin { [6]: .throw_error(); --^ [7]: }", input, parser); } [Test] public void ErrorInImport2() { var input = @" @import ""import/error2.less""; .a { .error_mixin(); }"; var parser = GetParser(); AssertError(@" .throw_error is undefined on line 6 in file 'import/error2.less': [5]: .error_mixin() { [6]: .throw_error(); --^ [7]: } from line 3 in file 'test.less': [3]: .error_mixin();", input, parser); } [Test] public void RelativeUrls() { var input = @" @import url(""import/first.less""); "; var expected = @" #second { background: url(import/image.gif); background: url(import/sub1/image.gif); background: url(import/sub1/sub2/image.gif); background: url(/sub2/image.gif); background: url(/sub2/image2.gif); } #first { background: url('image.gif'); background: url(image.gif); background: url(""image.gif""); } "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void RelativeUrlsWithRewritingOff() { var input = @" @import url(""import/first.less""); "; var expected = @" #second { background: url(../image.gif); background: url(image.gif); background: url(sub2/image.gif); background: url(/sub2/image.gif); background: url(/sub2/image2.gif); } #first { background: url('../image.gif'); background: url(../image.gif); background: url(""../image.gif""); } "; var parser = GetParser(true, false, false); AssertLess(input, expected, parser); } [Test] public void AbsoluteUrls() { var input = @" @import url(""/import/absolute.less""); "; var expected = @"body { background-color: black; }"; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void RelativeUrlWithParentDirReference() { var input = @" @import url(""../import/relative-with-parent-dir.less""); "; var expected = @"body { background-color: foo; }"; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportFileExtensionNotNecessary() { var input = @"@import url(""import/import-test-c"");"; var expected = @" @import ""import-test-d.css""; #import { color: red; }"; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportForUrlGetsOutput() { var input = @" @import url(""http://www.someone.com/external1.css""); @import ""http://www.someone.com/external2.css""; "; var parser = GetParser(); AssertLessUnchanged(input, parser); } [Test] public void ImportForMissingLessFileThrowsError1() { var input = @"@import url(""http://www.someone.com/external1.less"");"; var parser = GetParser(); AssertError(".less cannot import non local less files [http://www.someone.com/external1.less].", input, parser); } [Test] public void ImportForMissingLessFileThrowsError2() { var input = @"@import ""external1.less"";"; var parser = GetParser(); AssertError("You are importing a file ending in .less that cannot be found [external1.less].", input, parser); } [Test] public void ImportForMissingLessFileThrowsError3() { var input = @"@import ""http://www.someone.com/external1.less"";"; var parser = GetParser(); AssertError(".less cannot import non local less files [http://www.someone.com/external1.less].", input, parser); } [Test] public void ImportForMissingLessFileThrowsError4() { var input = @"@import ""dll://someassembly#missing.less"";"; var parser = GetParser(); AssertError("Unable to load resource [missing.less] in assembly [someassembly]", input, parser); } [Test] public void ImportForMissingCssFileAsLessThrowsError() { var input = @"@import ""dll://someassembly#missing.css"";"; var parser = GetParser(false, true, false); AssertError("Unable to load resource [missing.css] in assembly [someassembly]", input, parser); } [Test] public void ImportForMissingLessFileThrowsExceptionThatIncludesFileName() { var input = @"@import ""external1.less"";"; var parser = GetParser(); Assert.That(() => Evaluate(input, parser), Throws.InstanceOf<System.IO.FileNotFoundException>() .With.Property("FileName").EqualTo("external1.less")); } [Test] public void ImportCanNavigateIntoAndOutOfSubDirectory() { // Testing https://github.com/cloudhead/less.js/pull/514 var input = @"@import ""foo.less"";"; var expected = @"body { background-color: foo; }"; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportCanNavigateIntoAndOutOfSubDirectoryWithImport() { var input = @"@import url(""foourl.less"");"; var expected = @"body { background-color: foo; }"; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportWithMediaSpecificationsSupported() { var input = @" @import url(something.css) screen and (color) and (max-width: 600px);"; AssertLessUnchanged(input); } [Test] public void ImportInlinedWithMediaSpecificationsSupported() { var input = @" @import url(something.css) screen and (color) and (max-width: 600px);"; var expected = @" @media screen and (color) and (max-width: 600px) { body { background-color: foo; invalid ""; } } "; AssertLess(input, expected, GetParser(false, false, true)); } [Test] public void CanImportCssFilesAsLess() { var input = @" @import url(""isless.css""); "; var expected = @" body { margin-right: 9px; } "; AssertLess(input, expected, GetParser(false, true, false)); } [Test] public void LessImportWithMediaSpecificationsConverted() { var input = @" @import url(foo.less) screen and (color) and (max-width: 600px);"; var expected = @" @media screen and (color) and (max-width: 600px) { body { background-color: foo; } }"; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void LessImportWithMediaSpecificationsConvertedWithOnce() { var input = @" @import-once url(foo.less) screen and (color) and (max-width: 600px);"; var expected = @" @media screen and (color) and (max-width: 600px) { body { background-color: foo; } }"; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void LessImportWithMediaSpecificationsConvertedMultipleRequirements() { var input = @" @import url(foo.less) screen and (color) and (max-width: 600px), handheld and (min-width: 20em);"; var expected = @" @media screen and (color) and (max-width: 600px), handheld and (min-width: 20em) { body { background-color: foo; } }"; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportWithMediaSpecificationsSupportedWithVariable() { var input = @" @maxWidth: 600px; @requirement1: color; @import url(something.css) screen and (@requirement1) and (max-width: @maxWidth);"; var expected = @" @import url(something.css) screen and (color) and (max-width: 600px);"; AssertLess(input, expected); } [Test] public void LessImportWithMediaSpecificationsConvertedWithVariable() { var input = @" @maxWidth: 600px; @requirement1: color; @import url(foo.less) screen and (@requirement1) and (max-width: @maxWidth);"; var expected = @" @media screen and (color) and (max-width: 600px) { body { background-color: foo; } }"; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void LessImportFromEmbeddedResource() { var input = @" @import ""dll://dotless.Test.dll#dotless.Test.Resource.Embedded.less""; @import ""dll://dotless.Test.dll#dotless.Test.Resource.Embedded2.less"";"; var expected = @" #import { color: red; } #import { color: blue; }"; var parser = GetEmbeddedParser(false, false, false); AssertLess(input, expected, parser); } [Test] public void LessImportFromEmbeddedResourceWithDynamicAssembliesInAppDomain() { Assembly assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("dotless.dynamic.dll"), AssemblyBuilderAccess.RunAndSave); Assembly.Load(new AssemblyName("dotless.Test.EmbeddedResource")); try { Evaluate(@"@import ""dll://dotless.Test.EmbeddedResource.dll#dotless.Test.EmbeddedResource.Embedded.less"";", GetEmbeddedParser(false, false, false)); } catch (FileNotFoundException ex) { // If the import fails for the wrong reason (i.e., having the dynamic assembly loaded), // the failure will have a different exception message Assert.That(ex.Message, Is.EqualTo("You are importing a file ending in .less that cannot be found [nosuch.resource.less].")); } } [Test] public void CssImportFromEmbeddedResource() { var input = @" @import ""dll://dotless.Test.dll#dotless.Test.Resource.Embedded.css"";"; var expected = @" .windowz .dos { border: none; }"; var parser = GetEmbeddedParser(false, false, true); AssertLess(input, expected, parser); } [Test] public void ImportTwiceImportsOnce() { var input = @" @import ""lib/color.less""; @import ""lib/color.less"";"; var expected = @" body { background-color: foo; } "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportOnceTwiceImportsOnce() { var input = @" @import-once ""lib/color.less""; @import-once ""lib/color.less"";"; var expected = @" body { background-color: foo; } "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportTwiceWithDifferentRelativePathsImportsOnce() { var input = @" @import-once ""import/twice/with/different/paths.less"";"; var expected = @" body { background-color: foo; } "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void VariablesFromImportedFileAreAvailableToAnotherImportedFileWithinMediaBlock() { var input = @" @import ""import/define-variables.less""; @media only screen and (max-width: 700px) { @import ""import/use-variables.less""; } "; var expected = @" @media only screen and (max-width: 700px) { .test { background-color: 'blue'; } }"; AssertLess(input, expected, GetParser()); } [Test] public void EmptyImportDoesNotBreakSubsequentImports() { var input = @" @import ""empty.less""; @import ""rule.less""; .test { .rule; } "; var expected = @" .rule { color: black; } .test { color: #000000; } "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ExtendingNestedRulesFromReferenceImportsWorks() { var input = @" @import (reference) ""nested-rules.less""; .test:extend(.rule all) { } "; var expected = @" .parent-selector .test { background-color: black; } "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ExtendingNestedReferenceRulesIgnoresRulesFromParentRuleset() { var input = @" @import (reference) ""reference/ruleset-with-child-ruleset-and-rules.less""; .test:extend(.child all) { } "; var expected = @" .parent .test { background-color: black; } "; AssertLess(input, expected, GetParser()); } [Test] public void VariableInterpolationInQuotedCssImport() { var input = @" @var: ""foo""; @import ""@{var}/bar.css""; "; var expected = @" @import ""foo/bar.css""; "; } [Test] public void VariableInterpolationInQuotedLessImport() { var input = @" @component: ""color""; @import ""lib/@{component}.less""; "; var expected = @" body { background-color: foo; }"; AssertLess(input, expected, GetParser()); } [Test] public void VariableInterpolationInNestedLessImport() { var input = @" @import ""nested-import-interpolation-1.less""; "; var expected = @" body { background-color: blue; }"; AssertLess(input, expected, GetParser()); } [Test] public void ImportMultipleImportsMoreThanOnce() { var input = @" @import ""vardef.less""; @var: 10px; @import (multiple) ""vardef.less""; .rule { width: @var; } "; var expected = @" .rule { width: 9px; } "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportOptionalIgnoresFilesThatAreNotFound() { var input = @" @var: 10px; @import (optional) ""this-file-does-not-exist.less""; .rule { width: @var; } "; var expected = @" .rule { width: 10px; } "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportCssGeneratesImportDirective() { var input = @" @import (css) ""this-file-does-not-exist.less""; "; var expected = @" @import ""this-file-does-not-exist.less""; "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportLessParsesAnyExtensionAsLess() { var input = @" @import (less) ""css-as-less.css""; @import (less) ""arbitrary-extension-as-less.ext""; .rule { width: @var1; height: @var2; } "; var expected = @" .rule { width: 10px; height: 11px; }"; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportInlineIncludesContentsOfCssFile() { var input = @" @import (inline) ""something.css""; "; var expected = @" body { background-color: foo; invalid ""; } "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportReferenceAloneDoesNotProduceOutput() { var input = @" @import (reference) ""simple-rule.less""; "; var expected = @""; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportReferenceDoesNotOutputMediaBlocks() { var input = @" @import (reference) ""media-scoped-rules.less""; "; var expected = @""; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportReferenceDoesNotOutputRulesetsThatCallLoopingMixins() { var input = @" @import (reference) ""mixin-loop.less""; "; var expected = @""; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void PartialReferenceExtenderDoesNotCauseReferenceRulesetToBeOutput() { var input = @" @import (reference) ""partial-reference-extends-another-reference.less""; "; AssertLess(input, @"", GetParser()); } [Test] public void ExactReferenceExtenderDoesNotCauseReferenceRulesetToBeOutput() { var input = @" @import (reference) ""exact-reference-extends-another-reference.less""; "; AssertLess(input, @"", GetParser()); } [Test] public void ImportReferenceDoesNotOutputDirectives() { var input = @" @import (reference) ""directives.less""; "; AssertLess(input, @"", GetParser()); } [Test] public void ImportReferenceOutputsExtendedRulesFromMediaBlocks() { var input = @" @import (reference) ""media-scoped-rules.less""; .test:extend(.rule all) { } "; var expected = @" @media (screen) { .test { background-color: black; } } "; AssertLess(input, expected, GetParser()); } [Test] public void ImportReferenceDoesNotOutputMixinCalls() { var input = @" @import (reference) ""reference/main.less""; "; AssertLess(input, @"", GetParser()); } [Test] public void ExtendingReferencedImportOnlyOutputsExtendedSelector() { var input = @" @import (reference) ""reference-with-multiple-selectors.less""; .ext:extend(.test all) { } "; var expected = @" .ext { color: black; }"; AssertLess(input, expected, GetParser()); } [Test] public void ImportReferenceDoesNotOutputComments() { var input = @" @import (reference) ""comments.less""; "; AssertLess(input, @"", GetParser()); } [Test] public void ImportReferenceWithMixinCallProducesOutput() { var input = @" @import (reference) ""simple-rule.less""; .caller { .rule } "; var expected = @" .caller { background-color: #000000; } "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportReferenceDoesNotPreventNonReferenceImport() { var input = @" @import (reference) ""simple-rule.less""; @import ""simple-rule.less""; "; var expected = @" .rule { background-color: black; } "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ExtendingReferenceImportsWorks() { var input = @" @import (reference) ""simple-rule.less""; .test:extend(.rule all) { } "; var expected = @" .test { background-color: black; } "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportsFromReferenceImportsAreTreatedAsReferences() { var input = @" @import (reference) ""imports-simple-rule.less""; .test { .rule2; } "; var expected = @" .test { background-color: #0000ff; } "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void RecursiveImportsFromReferenceImportsAreTreatedAsReferences() { var input = @" @import (reference) ""two-level-import.less""; .test { background-color: blue; } "; var expected = @" .test { background-color: blue; } "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportingReferenceAsLessWorks() { var input = @" @import (reference, less) ""simple-rule.css""; .test { .rule } "; var expected = @" .test { background-color: #000000; } "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportingReferenceAsCssFails() { var input = @" @import (reference, css) ""simple-rule.css""; "; var expectedError = @" invalid combination of @import options (reference, css) -- specify either reference or css, but not both on line 1 in file 'test.less': []: /beginning of file [1]: @import (reference, css) ""simple-rule.css""; --------^ [2]: /end of file"; AssertError(expectedError, input); } [Test] public void ImportingAsBothCssAndLessFails() { var input = @" @import (css, less) ""simple-rule.css""; "; var expectedError = @" invalid combination of @import options (css, less) -- specify either css or less, but not both on line 1 in file 'test.less': []: /beginning of file [1]: @import (css, less) ""simple-rule.css""; --------^ [2]: /end of file"; AssertError(expectedError, input); } [Test] public void ImportingAsBothInlineAndReferenceFails() { var input = @" @import (inline, reference) ""simple-rule.css""; "; var expectedError = @" invalid combination of @import options (inline, reference) -- specify either inline or reference, but not both on line 1 in file 'test.less': []: /beginning of file [1]: @import (inline, reference) ""simple-rule.css""; --------^ [2]: /end of file"; AssertError(expectedError, input); } [Test] public void ImportingAsBothInlineAndCssFails() { var input = @" @import (inline, css) ""simple-rule.css""; "; var expectedError = @" invalid combination of @import options (inline, css) -- specify either inline or css, but not both on line 1 in file 'test.less': []: /beginning of file [1]: @import (inline, css) ""simple-rule.css""; --------^ [2]: /end of file"; AssertError(expectedError, input); } [Test] public void ImportingAsBothInlineAndLessFails() { var input = @" @import (inline, less) ""simple-rule.css""; "; var expectedError = @" invalid combination of @import options (inline, less) -- specify either inline or less, but not both on line 1 in file 'test.less': []: /beginning of file [1]: @import (inline, less) ""simple-rule.css""; --------^ [2]: /end of file"; AssertError(expectedError, input); } [Test] public void ImportingAsBothOnceAndMultipleFails() { var input = @" @import (once, multiple) ""simple-rule.css""; "; var expectedError = @" invalid combination of @import options (once, multiple) -- specify either once or multiple, but not both on line 1 in file 'test.less': []: /beginning of file [1]: @import (once, multiple) ""simple-rule.css""; --------^ [2]: /end of file"; AssertError(expectedError, input); } [Test] public void UnrecognizedImportOptionFails() { var input = @" @import (invalid-option) ""simple-rule.css""; "; var expectedError = @" unrecognized @import option 'invalid-option' on line 1 in file 'test.less': []: /beginning of file [1]: @import (invalid-option) ""simple-rule.css""; --------^ [2]: /end of file"; AssertError(expectedError, input); } [Test] public void ImportProtocolCssInsideMixinsWithNestedGuards() { var input = @" .generateImports(@fontFamily) { & when (@fontFamily = Lato) { @import url(https://fonts.googleapis.com/css?family=Lato); } & when (@fontFamily = Cabin) { @import url(https://fonts.googleapis.com/css?family=Cabin); } } .generateImports(Lato); .generateImports(Cabin); "; var expected = @" @import url(https://fonts.googleapis.com/css?family=Lato); @import url(https://fonts.googleapis.com/css?family=Cabin); "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportProtocolCssInsideMixinsWithGuards() { var input = @" .generateImports(@fontFamily) when (@fontFamily = Lato) { @import url(https://fonts.googleapis.com/css?family=Lato); } .generateImports(@fontFamily) when (@fontFamily = Cabin) { @import url(https://fonts.googleapis.com/css?family=Cabin); } .generateImports(Lato); .generateImports(Cabin); "; var expected = @" @import url(https://fonts.googleapis.com/css?family=Lato); @import url(https://fonts.googleapis.com/css?family=Cabin); "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void StrictMathIsHonoredInImports() { var input = @" @import ""math.less""; "; var expected = @" .rule { width: calc(10px + 2px); } "; var parser = GetParser(); parser.StrictMath = true; AssertLess(input, expected, parser); } [Test] public void ImportsWithinRulesets() { var input = @" .test { @import ""math.less""; } "; var expected = @" .test .rule { width: calc(12px); } "; AssertLess(input, expected, GetParser()); } [Test] public void ImportsWithGeneratedSelectorsWithinRulesets() { var input = @" .namespace { @import ""generated-selector.less""; } "; var expected = @" .namespace .rule { color: black; } "; AssertLess(input, expected, GetParser()); } [Test] public void NestedImportsWithinRulesets() { var input = @" .namespace { @import url(""import/import-test-a.less""); #import-test { .mixin; width: 10px; height: @a + 10%; } } "; var expected = @" @import ""import-test-d.css""; .namespace #import { color: red; } .namespace .mixin { height: 10px; color: red; } .namespace #import-test { height: 10px; color: #ff0000; width: 10px; height: 30%; } "; var parser = GetParser(); AssertLess(input, expected, parser); } [Test] public void ImportsWithinRulesetsGenerateCallableMixins() { var input = @" .namespace { @import ""reference/mixins/test.less""; .mixin(red); }"; var expected = @" .namespace .test-ruleset { background-color: red; }"; AssertLess(input, expected, GetParser()); } [Test] public void ExtendedReferenceImportWithMultipleGeneratedSelectorsOnlyOutputsExtendedSelectors() { var input = @" @import (reference) ""multiple-generated-selectors.less""; .test:extend(.col-xs-12 all) { } "; var expected = @" .test { float: left; }"; AssertLess(input, expected, GetParser()); } [Test] public void RelativeImportsHonorCurrentDirectory() { var input = @" @import ""import-test-a.less""; "; var expected = @" @import ""import-test-d.css""; #import { color: red; } .mixin { height: 10px; color: red; }"; var parser = GetParser(); parser.CurrentDirectory = "import"; AssertLess(input, expected, parser); } [Test] public void AbsolutePathImportsHonorsCurrentDirectory() { var input = @" @import 'c:/absolute/file.less';"; var expected = @" .windowz .dos { border: none; } "; var parser = GetParser(); parser.CurrentDirectory = "import"; AssertLess(input, expected, parser); } [Test] public void CssImportsAreHoistedToBeginningOfFile() { var input = @" @font-face { font-family: ""Epsilon""; src: url('data:font/x-woff;base64,...') } @import url(//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic); "; var expected = @" @import url(//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic); @font-face { font-family: ""Epsilon""; src: url('data:font/x-woff;base64,...'); }"; AssertLess(input, expected); } [Test] public void RelativeImportInMixinDefinition() { var input = @" @import ""import-in-mixin/mixin-definition.less""; .import(); "; var expected = @" .rule { color: black; }"; AssertLess(input, expected, GetParser()); } [Test] public void ReferenceImportDoesNotOutputUnreferencedStyles() { var input = @" @import (reference) ""reference-mixin-issue.less""; /* Styles */ .my-class { .mix-me(); }"; var expected = @" /* Styles */ .my-class { color: #ff0000; } @media (min-width: 100px) { .my-class { color: blue; } } .my-class .mix-me-child { background-color: black; }"; AssertLess(input, expected, GetParser()); } [Test] public void MixinWithMediaBlock() { var input = @" .mixin() { @media (min-width: 100px) { color: blue; } } .test { .mixin(); } "; var expected = @" @media (min-width: 100px) { .test { color: blue; } }"; AssertLess(input, expected, GetParser()); } } }
/*************************************************************************** * QueryBuilder.cs * * Copyright (C) 2005 Novell * Written by Aaron Bockover (aaron@aaronbock.net) ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Text.RegularExpressions; #if !win32 using GLib; using Gtk; using Mono.Unix; #else using System.Windows.Forms; using Banshee.Winforms; #endif namespace Banshee.SmartPlaylist { public sealed class QueryOperator { private string format; public string Format { get { return format; } } private QueryOperator (string format) { this.format = format; } public string FormatValues (bool text, string column, string value1, string value2) { if (text) return String.Format (format, "'", column, value1, value2); else return String.Format (format, "", column, value1, value2); } public bool MatchesCondition (string condition, out string column, out string value1, out string value2) { // Remove trailing parens from the end of the format b/c trailing parens are trimmed from the condition string regex = String.Format(format.Replace("(", "\\(").Replace(")", "\\)"), "'?", // ignore the single quotes if they exist "(.*)", // match the column "(.*)", // match the first value "(.*)" // match the second value ); //Console.WriteLine ("regex = {0}", regex); MatchCollection mc = System.Text.RegularExpressions.Regex.Matches (condition, regex); if (mc != null && mc.Count > 0 && mc[0].Groups.Count > 0) { column = mc[0].Groups[1].Captures[0].Value; value1 = mc[0].Groups[2].Captures[0].Value.Trim(new char[] {'\''}); if (mc[0].Groups.Count == 4) value2 = mc[0].Groups[3].Captures[0].Value.Trim(new char[] {'\''}); else value2 = null; return true; } else { column = value1 = value2 = null; return false; } } // calling lower() to have case insensitive comparisons with strings public static QueryOperator EQText = new QueryOperator("lower({1}) = {0}{2}{0}"); public static QueryOperator NotEQText = new QueryOperator("lower({1}) != {0}{2}{0}"); public static QueryOperator EQ = new QueryOperator("{1} = {0}{2}{0}"); public static QueryOperator NotEQ = new QueryOperator("{1} != {0}{2}{0}"); public static QueryOperator Between = new QueryOperator("{1} BETWEEN {0}{2}{0} AND {0}{3}{0}"); public static QueryOperator LT = new QueryOperator("{1} < {0}{2}{0}"); public static QueryOperator GT = new QueryOperator("{1} > {0}{2}{0}"); public static QueryOperator GTE = new QueryOperator("{1} >= {0}{2}{0}"); // Note, the following lower() calls are necessary b/c of a sqlite bug which makes the LIKE // command case sensitive with certain characters. public static QueryOperator Like = new QueryOperator("lower({1}) LIKE '%{2}%'"); public static QueryOperator NotLike = new QueryOperator("lower({1}) NOT LIKE '%{2}%'"); public static QueryOperator StartsWith = new QueryOperator("lower({1}) LIKE '{2}%'"); public static QueryOperator EndsWith = new QueryOperator("lower({1}) LIKE '%{2}'"); // TODO these should either be made generic or moved somewhere else since they are Banshee/Track/Playlist specific. public static QueryOperator InPlaylist = new QueryOperator("TrackID IN (SELECT TrackID FROM PlaylistEntries WHERE {1} = {0}{2}{0})"); public static QueryOperator NotInPlaylist = new QueryOperator("TrackID NOT IN (SELECT TrackID FROM PlaylistEntries WHERE {1} = {0}{2}{0})"); public static QueryOperator InSmartPlaylist = new QueryOperator("TrackID IN (SELECT TrackID FROM SmartPlaylistEntries WHERE {1} = {0}{2}{0})"); public static QueryOperator NotInSmartPlaylist = new QueryOperator("TrackID NOT IN (SELECT TrackID FROM SmartPlaylistEntries WHERE {1} = {0}{2}{0})"); } public sealed class QueryFilter { private string name; private QueryOperator op; public string Name { get { return name; } } public QueryOperator Operator { get { return op; } } private static Hashtable filters = new Hashtable(); private static ArrayList filters_array = new ArrayList(); public static QueryFilter GetByName (string name) { return filters[name] as QueryFilter; } public static ArrayList Filters { get { return filters_array; } } private static QueryFilter NewOperation (string name, QueryOperator op) { QueryFilter filter = new QueryFilter(name, op); filters[name] = filter; filters_array.Add (filter); return filter; } private QueryFilter (string name, QueryOperator op) { this.name = name; this.op = op; } public static QueryFilter InPlaylist = NewOperation ( Catalog.GetString ("is"), QueryOperator.InPlaylist ); public static QueryFilter NotInPlaylist = NewOperation ( Catalog.GetString ("is not"), QueryOperator.NotInPlaylist ); public static QueryFilter InSmartPlaylist = NewOperation ( Catalog.GetString ("is"), QueryOperator.InSmartPlaylist ); public static QueryFilter NotInSmartPlaylist = NewOperation ( Catalog.GetString ("is not"), QueryOperator.NotInSmartPlaylist ); // caution: the equal/not-equal operators for text fields (TextIs and TextNotIs) have to be defined // before the ones for non-text fields. Otherwise MatchesCondition will not return the right column names. // (because the regular expression for non-string fields machtes also for string fields) public static QueryFilter TextIs = NewOperation ( Catalog.GetString ("is"), QueryOperator.EQText ); public static QueryFilter TextIsNot = NewOperation ( Catalog.GetString ("is not"), QueryOperator.NotEQText ); public static QueryFilter Is = NewOperation ( Catalog.GetString ("is"), QueryOperator.EQ ); public static QueryFilter IsNot = NewOperation ( Catalog.GetString ("is not"), QueryOperator.NotEQ ); public static QueryFilter IsLessThan = NewOperation ( Catalog.GetString ("is less than"), QueryOperator.LT ); public static QueryFilter IsGreaterThan = NewOperation ( Catalog.GetString ("is greater than"), QueryOperator.GT ); public static QueryFilter MoreThan = NewOperation ( Catalog.GetString ("more than"), QueryOperator.GT ); public static QueryFilter LessThan = NewOperation ( Catalog.GetString ("less than"), QueryOperator.LT ); public static QueryFilter IsAtLeast = NewOperation ( Catalog.GetString ("is at least"), QueryOperator.GTE ); public static QueryFilter Contains = NewOperation ( Catalog.GetString ("contains"), QueryOperator.Like ); public static QueryFilter DoesNotContain = NewOperation ( Catalog.GetString ("does not contain"), QueryOperator.NotLike ); public static QueryFilter StartsWith = NewOperation ( Catalog.GetString ("starts with"), QueryOperator.StartsWith ); public static QueryFilter EndsWith = NewOperation ( Catalog.GetString ("ends with"), QueryOperator.EndsWith ); public static QueryFilter IsBefore = NewOperation ( Catalog.GetString ("is before"), QueryOperator.LT ); public static QueryFilter IsAfter = NewOperation ( Catalog.GetString ("is after"), QueryOperator.GT ); public static QueryFilter IsInTheRange = NewOperation ( Catalog.GetString ("is between"), QueryOperator.Between ); public static QueryFilter Between = NewOperation ( Catalog.GetString ("between"), QueryOperator.Between ); } #if !win32 public static class ComboBoxUtil { public static string GetActiveString(ComboBox box) { TreeIter iter; if(!box.GetActiveIter(out iter)) return null; return (string)box.Model.GetValue(iter, 0); } public static bool SetActiveString(ComboBox box, string val) { TreeIter iter; if (!box.Model.GetIterFirst(out iter)) return false; do { if (box.Model.GetValue (iter, 0) as string == val) { box.SetActiveIter(iter); return true; } } while (box.Model.IterNext (ref iter)); return false; } } #else public static class ComboBoxUtil { public static string GetActiveString(ComboBox box) { return box.SelectedItem.ToString(); } public static bool SetActiveString(ComboBox box, string val) { if (string.IsNullOrEmpty(val)) return false; box.SelectedText = val; return true; } } #endif // --- Base QueryMatch Class --- #if !win32 public abstract class QueryMatch { public string Column; public int Op; public abstract string Value1 { get; set; } public abstract string Value2 { get; set; } public abstract string FilterValues(); public abstract Widget DisplayWidget { get; } public abstract QueryFilter [] ValidFilters { get; } public virtual string SqlColumn { get { return Column; } } public QueryFilter Filter { get { return ValidFilters [Op]; } } protected static HBox BuildRangeBox(Widget a, Widget b) { HBox box = new HBox(); box.Spacing = 5; a.Show(); box.PackStart(a, false, false, 0); Label label = new Label(Catalog.GetString("to")); label.Show(); box.PackStart(label, false, false, 0); b.Show(); box.PackStart(b, false, false, 0); box.Show(); return box; } protected static string EscapeQuotes (string v) { return v == null ? String.Empty : v.Replace("'", "''"); } } #endif public abstract class QueryMatch { protected static Panel BuildRangeBox(Control a, Control b) { Panel p = new Panel(); p.Controls.Add(a); p.Controls.Add(b); return p; } public string Column; public int Op; public abstract string Value1 { get; set; } public abstract string Value2 { get; set; } public abstract string FilterValues(); public abstract QueryFilter[] ValidFilters { get; } public virtual string SqlColumn { get { return Column; } } public QueryFilter Filter { get { return ValidFilters[Op]; } } protected static string EscapeQuotes(string v) { return v == null ? String.Empty : v.Replace("'", "''"); } } // --- Base QueryBuilderModel Class --- public abstract class QueryBuilderModel : IEnumerable { private Hashtable fieldsMap; private Hashtable columnLookup; private Hashtable nameLookup; private Hashtable orderMap; private Hashtable mapOrder; private ArrayList fields = new ArrayList(); private ArrayList orders = new ArrayList(); public QueryBuilderModel() { fieldsMap = new Hashtable(); columnLookup = new Hashtable(); nameLookup = new Hashtable(); orderMap = new Hashtable(); mapOrder = new Hashtable(); } public Type this [string index] { get { return (Type)fieldsMap[index]; } } public IEnumerator GetEnumerator() { return fields.GetEnumerator(); } public void AddField(string name, string column, Type matchType) { fields.Add (name); fieldsMap[name] = matchType; columnLookup[name] = column; nameLookup[column] = name; fields.Sort(); } public void AddOrder(string name, string map) { orders.Add (name); orderMap[name] = map; mapOrder[map] = name; orders.Sort(); } public string GetOrder(string name) { return (string)orderMap[name]; } public string GetOrderName(string map) { return (string)mapOrder[map]; } public string GetColumn(string name) { return (string)columnLookup[name]; } public string GetName(string col) { return (string)nameLookup[col]; } public abstract string [] LimitCriteria { get; } public ICollection OrderCriteria { get { return orders; } } } // --- Query Builder Widgets #region GTK Widgets #if !win32 public class QueryBuilderMatchRow : HBox #else public class QueryBuilderMatchRow : Panel #endif { #if !win32 private VBox widgetBox; #else private Panel widgetBox; #endif private ComboBox fieldBox, opBox; private QueryBuilderModel model; private QueryMatch match; private Button buttonAdd; private Button buttonRemove; public event EventHandler AddRequest; public event EventHandler RemoveRequest; public QueryBuilderMatchRow(QueryBuilderModel model) : base() { this.model = model; #if !win32 fieldBox = ComboBox.NewText(); fieldBox.Changed += OnFieldComboBoxChanged; Spacing = 5; #else fieldBox.SelectedIndexChanged += new EventHandler(fieldBox_SelectedIndexChanged); #endif #if !win32 PackStart(fieldBox, false, false, 0); #endif fieldBox.Show(); #if !win32 opBox = ComboBox.NewText(); opBox.Changed += OnOpComboBoxChanged; #else opBox = new ComboBox(); opBox.SelectedIndexChanged += new EventHandler(opBox_SelectedIndexChanged); #endif #if !win32 PackStart(opBox, false, false, 0); #endif opBox.Show(); #if !win32 widgetBox = new VBox(); #else widgetBox = new Panel(); #endif widgetBox.Show(); #if !win32 PackStart(widgetBox, false, false, 0); #endif #if !win32 foreach(string fieldName in model) { fieldBox.AppendText(fieldName); } #else foreach (string fieldName in model) { fieldBox.Items.Add(fieldName); } #endif #if !win32 buttonRemove = new Button(imageRemove); buttonRemove.Relief = ReliefStyle.None; buttonRemove.Show(); Select(0); imageRemove.Show();Image imageRemove = new Image("gtk-remove", IconSize.Button); buttonRemove.Clicked += OnButtonRemoveClicked; PackEnd(buttonRemove, false, false, 0); Image imageAdd = new Image("gtk-add", IconSize.Button); buttonAdd = new Button(imageAdd); buttonAdd.Relief = ReliefStyle.None; buttonAdd.Show(); imageAdd.Show(); PackEnd(buttonAdd, false, false, 0); buttonAdd.Clicked += OnButtonAddClicked; #else System.Drawing.Image imageRemove = (System.Drawing.Image)System.Drawing.Bitmap.FromFile(@"\icons\list-remove.png"); buttonRemove = new Button(); buttonRemove.Image = imageRemove; buttonRemove.Click += new EventHandler(buttonRemove_Click); buttonAdd = new Button(); System.Drawing.Image imageAdd = (System.Drawing.Image)System.Drawing.Bitmap.FromFile(@"\icons\list-add.png"); buttonAdd.Click += new EventHandler(buttonAdd_Click); #endif } void opBox_SelectedIndexChanged(object sender, EventArgs e) { throw new Exception("The method or operation is not implemented."); } void buttonRemove_Click(object sender, EventArgs e) { throw new Exception("The method or operation is not implemented."); } void buttonAdd_Click(object sender, EventArgs e) { throw new Exception("The method or operation is not implemented."); } void fieldBox_SelectedIndexChanged(object sender, EventArgs e) { throw new Exception("The method or operation is not implemented."); } private void Select(int index) { #if !win32 TreeIter iter; if(!fieldBox.Model.IterNthChild(out iter, index)) return; fieldBox.SetActiveIter(iter); #else fieldBox.SelectedIndex = index; #endif } #if !win32 private void Select(TreeIter iter) { string fieldName = (string)fieldBox.Model.GetValue(iter, 0); Type matchType = model[fieldName]; match = Activator.CreateInstance(matchType) as QueryMatch; while(opBox.Model.IterNChildren() > 0) opBox.RemoveText(0); foreach(QueryFilter filter in match.ValidFilters) opBox.AppendText(filter.Name); TreeIter opIterFirst; if(!opBox.Model.IterNthChild(out opIterFirst, 0)) throw new Exception("Field has no operations"); match.Column = fieldName; opBox.SetActiveIter(opIterFirst); } #else private void Select(DataGridView view) { string fieldName = (string)fieldBox.Items[0].ToString(); Type matchType = model[fieldName]; match = Activator.CreateInstance(matchType) as QueryMatch; while (opBox.Items.Count >0) { opBox.Items.RemoveAt(opBox.Items.Count - 1); } match.Column = fieldName; //opBox.SelectedItem = } #endif #if !win32 private void OnFieldComboBoxChanged(object o, EventArgs args) { TreeIter iter; fieldBox.GetActiveIter(out iter); Select(iter); } private void OnOpComboBoxChanged(object o, EventArgs args) { TreeIter iter; opBox.GetActiveIter(out iter); //string opName = (string)opBox.Model.GetValue(iter, 0); match.Op = opBox.Active; widgetBox.Foreach(WidgetBoxForeachRemoveChild); widgetBox.Add(match.DisplayWidget); } #endif #if win32 private void WidgetBoxForeachRemoveChild(Control widget) { widgetBox.Controls.Remove(widget); } #else private void WidgetBoxForeachRemoveChild(Widget widget) { widgetBox.Remove(widget); } #endif private void OnButtonAddClicked(object o, EventArgs args) { EventHandler handler = AddRequest; if(handler != null) handler(this, new EventArgs()); } private void OnButtonRemoveClicked(object o, EventArgs args) { EventHandler handler = RemoveRequest; if(handler != null) handler(this, new EventArgs()); } public bool CanDelete { set { buttonRemove.Enabled = value; } } public string Query { get { match.Column = model.GetColumn(ComboBoxUtil.GetActiveString(fieldBox)); #if !win32 match.Op = opBox.Active; #else match.Op = opBox.SelectedIndex; #endif return match.FilterValues(); } } public ComboBox FieldBox { get { return fieldBox; } } public ComboBox FilterBox { get { return opBox; } } public QueryMatch Match { get { return match; } } } #if !win32 public class QueryBuilderMatches : VBox #else public class QueryBuilderMatches : Panel #endif { private QueryBuilderModel model; private QueryBuilderMatchRow first_row = null; public QueryBuilderMatchRow FirstRow { get { return first_row; } } public QueryBuilderMatches(QueryBuilderModel model) : base() { this.model = model; CreateRow(false); } public void CreateRow(bool canDelete) { QueryBuilderMatchRow row = new QueryBuilderMatchRow(model); row.Show(); #if !win32 PackStart(row, false, false, 0); #endif row.CanDelete = canDelete; row.AddRequest += OnRowAddRequest; row.RemoveRequest += OnRowRemoveRequest; if (first_row == null) { first_row = row; #if !win32 row.FieldBox.GrabFocus(); #else row.Select(); #endif } } public void OnRowAddRequest(object o, EventArgs args) { CreateRow(true); UpdateCanDelete(); } #if !win32 public void OnRowRemoveRequest(object o, EventArgs args) { Remove(o as Widget); UpdateCanDelete(); } #else public void OnRowRemoveRequest(object o, EventArgs args) { this.Controls.Remove(o as Control); UpdateCanDelete(); } #endif public void UpdateCanDelete() { #if !win32 ((QueryBuilderMatchRow)Children[0]).CanDelete = Children.Length > 1; #else ((QueryBuilderMatchRow)Controls[0]).CanDelete = Controls.Count > 1; #endif } #if !win32 public string BuildQuery(string join) { string query = null; for(int i = 0, n = Children.Length; i < n; i++) { QueryBuilderMatchRow match = Children[i] as QueryBuilderMatchRow; query += " (" + match.Query + ") "; if(i < n - 1) query += join; } return query; } #else public string BuildQuery(string join) { string query = null; for (int i = 0, n = Controls.Count; i < n; i++) { QueryBuilderMatchRow match = Controls[i] as QueryBuilderMatchRow; query += " (" + match.Query + ") "; if (i < n - 1) query += join; } return query; } #endif } #if !win32 public class QueryBuilder : VBox #else public class QueryBuilder : Panel #endif { #if !win32 private CheckButton matchCheckBox; private Entry limitEntry; #else private CheckBox matchCheckBox; private TextBox limitEntry; #endif private QueryBuilderModel model; private QueryBuilderMatches matchesBox; #if !win32 private CheckButton limitCheckBox; #else private CheckBox limitCheckBox; #endif private Label matchLabelFollowing; private ComboBox matchLogicCombo; private ComboBox limitComboBox; private ComboBox orderComboBox; public QueryBuilderMatches MatchesBox { get { return matchesBox; } } public QueryBuilder(QueryBuilderModel model) : base() { this.model = model; matchesBox = new QueryBuilderMatches(model); #if !win32 matchesBox.Spacing = 5; #endif matchesBox.Show(); #if !win32 Alignment matchesAlignment = new Alignment(0.0f, 0.0f, 1.0f, 1.0f); #endif #if !win32 matchesAlignment.Show(); matchesAlignment.SetPadding(10, 10, 10, 10); matchesAlignment.Add(matchesBox);Frame matchesFrame = new Frame(null); matchesFrame.Show(); matchesFrame.Add(matchesAlignment); matchesFrame.LabelWidget = BuildMatchHeader(); PackStart(matchesFrame, true, true, 0); PackStart(BuildLimitFooter(), false, false, 0); #endif Panel matchesFrame = new Panel(); this.Controls.Add(matchesFrame); matchesFrame.Controls.Add(BuildMatchHeader()); } #if !win32 private HBox BuildMatchHeader() #else private Panel BuildMatchHeader() #endif { #if !win32 HBox matchHeader = new HBox(); #else Panel matchHeader = new Panel(); #endif matchHeader.Show(); #if !win32 matchCheckBox = new CheckButton(Catalog.GetString("_Match")); matchCheckBox.Show(); matchCheckBox.Active = true; #else matchCheckBox = new CheckBox(); matchCheckBox.Text = "_Match"; matchCheckBox.Checked = true; #endif #if !win32 matchCheckBox.Toggled += OnMatchCheckBoxToggled; matchHeader.PackStart(matchCheckBox, false, false, 0); #else matchCheckBox.CheckedChanged += new EventHandler(matchCheckBox_CheckedChanged); #endif #if !win32 matchLogicCombo = ComboBox.NewText(); matchLogicCombo.AppendText(Catalog.GetString("all")); matchLogicCombo.AppendText(Catalog.GetString("any")); #else matchLogicCombo = new ComboBox(); matchLogicCombo.Items.Add("all"); matchLogicCombo.Items.Add("any"); #endif matchLogicCombo.Show(); #if !win32 matchLogicCombo.Active = 0; matchHeader.PackStart(matchLogicCombo, false, false, 0); matchLabelFollowing = new Label(Catalog.GetString("of the following:")); matchLabelFollowing.Show(); #else matchLabelFollowing = new Label(); matchLabelFollowing.Text = "of the following:"; this.Controls.Add(matchLabelFollowing); #endif #if !win32 matchLabelFollowing.Xalign = 0.0f; matchHeader.PackStart(matchLabelFollowing, true, true, 0); matchHeader.Spacing = 5; #endif //matchCheckBox.Active = false; //OnMatchCheckBoxToggled(matchCheckBox, null); return matchHeader; } void matchCheckBox_CheckedChanged(object sender, EventArgs e) { throw new Exception("The method or operation is not implemented."); } #if !win32 private HBox BuildLimitFooter() #else private Panel BuildLimitFooter() #endif { #if !win32 HBox limitFooter = new HBox(); #else Panel limitFooter = new Panel(); #endif limitFooter.Show(); #if !win32 limitFooter.Spacing = 5; limitCheckBox = new CheckButton(Catalog.GetString("_Limit to")); #else limitCheckBox = new CheckBox(); limitCheckBox.Text = "_Limit to"; #endif limitCheckBox.Show(); #if !win32 limitEntry = new Entry("25"); limitCheckBox.Toggled += OnLimitCheckBoxToggled; limitFooter.PackStart(limitCheckBox, false, false, 0); #else limitCheckBox.CheckedChanged += new EventHandler(limitCheckBox_CheckedChanged); limitEntry = new TextBox(); #endif limitEntry.Show(); #if !win32 limitEntry.SetSizeRequest(50, -1); limitFooter.PackStart(limitEntry, false, false, 0); limitComboBox = ComboBox.NewText(); #else limitComboBox = new ComboBox(); #endif limitComboBox.Show(); #if !win32 foreach(string criteria in model.LimitCriteria) limitComboBox.AppendText(criteria); limitComboBox.Active = 0; limitFooter.PackStart(limitComboBox, false, false, 0); #else foreach (string criteria in model.LimitCriteria) limitComboBox.Items.Add(criteria); #endif #if !win32 Label orderLabel = new Label(Catalog.GetString("selected by")); orderLabel.Show(); limitFooter.PackStart(orderLabel, false, false, 0); orderComboBox = ComboBox.NewText(); #else Label orderLabel = new Label(); orderLabel.Text = "selected by"; this.Controls.Add(orderLabel); orderComboBox = new ComboBox(); this.Controls.Add(orderComboBox); #endif #if !win32 orderComboBox.Show(); foreach(string order in model.OrderCriteria) orderComboBox.AppendText(order); orderComboBox.Active = 0; limitFooter.PackStart(orderComboBox, false, false, 0); limitCheckBox.Active = false; OnLimitCheckBoxToggled(limitCheckBox, null); #else foreach (string order in model.OrderCriteria) orderComboBox.Items.Add(order); #endif return limitFooter; } void limitCheckBox_CheckedChanged(object sender, EventArgs e) { throw new Exception("The method or operation is not implemented."); } #if !win32 private void OnMatchCheckBoxToggled(object o, EventArgs args) { matchesBox.Sensitive = matchCheckBox.Active; matchLogicCombo.Sensitive = matchCheckBox.Active; matchLabelFollowing.Sensitive = matchCheckBox.Active; } private void OnLimitCheckBoxToggled(object o, EventArgs args) { limitEntry.Sensitive = limitCheckBox.Active; limitComboBox.Sensitive = limitCheckBox.Active; orderComboBox.Sensitive = limitCheckBox.Active; } #else public bool MatchesEnabled { get { return matchCheckBox.Enabled; } set { matchCheckBox.Enabled = value; } } #endif public string MatchQuery { get { return matchesBox.BuildQuery( matchLogicCombo.Active == 0 ? "AND" : "OR" ); } set { if (value == null || value == String.Empty) { matchCheckBox.Active = false; return; } // Check for ANDs or ORs and split into conditions as needed string [] conditions; if (value.IndexOf(") AND (") != -1) { matchLogicCombo.Active = 0; conditions = System.Text.RegularExpressions.Regex.Split (value, "\\) AND \\("); } else if (value.IndexOf(") OR (") != -1) { matchLogicCombo.Active = 1; conditions = System.Text.RegularExpressions.Regex.Split (value, "\\) OR \\("); } else { conditions = new string [] {value}; } // Remove leading spaces and parens from the first condition conditions[0] = conditions[0].Remove(0, 2); // Remove trailing spaces and last paren from the last condition string tmp = conditions[conditions.Length-1]; tmp = tmp.TrimEnd(new char[] {' '}); tmp = tmp.Substring(0, tmp.Length - 1); conditions[conditions.Length-1] = tmp; matchCheckBox.Active = true; int count = 0; foreach (string condition in conditions) { // Add a new row for this condition string col, v1, v2; bool found_filter = false; foreach (QueryFilter filter in QueryFilter.Filters) { if (filter.Operator.MatchesCondition (condition, out col, out v1, out v2)) { //Console.WriteLine ("{0} is col: {1} with v1: {2} v2: {3}", condition, col, v1, v2); // The first row is already created if (count > 0) matchesBox.CreateRow(true); // Set the column QueryBuilderMatchRow row = matchesBox.Children[count] as QueryBuilderMatchRow; if (!ComboBoxUtil.SetActiveString (row.FieldBox, model.GetName(col))) { if (col.IndexOf ("current_timestamp") == -1) { Console.WriteLine ("Found col that can't place"); break; } else { bool found = false; foreach (string field in model) { if (col.IndexOf (model.GetColumn (field)) != -1) { ComboBoxUtil.SetActiveString (row.FieldBox, field); found = true; break; } } if (!found) { Console.WriteLine ("Found col that can't place"); break; } } } // Make sure we're on the right filter (as multiple filters can have the same operator) QueryFilter real_filter = filter; if (System.Array.IndexOf (row.Match.ValidFilters, filter) == -1) { foreach (QueryFilter f in row.Match.ValidFilters) { if (f.Operator == filter.Operator) { real_filter = f; break; } } } // Set the operator if (!ComboBoxUtil.SetActiveString (row.FilterBox, real_filter.Name)) { Console.WriteLine ("Found filter that can't place"); break; } // Set the values row.Match.Value1 = v1; row.Match.Value2 = v2; found_filter = true; break; } } // TODO should push error here instead if (!found_filter) Console.WriteLine ("Couldn't find appropriate filter for condition: {0}", condition); count++; matchesBox.UpdateCanDelete(); } } } public string LimitNumber { get { try { Convert.ToInt32(limitEntry.Text); return limitEntry.Text; } catch(Exception) { return "0"; } } set { limitEntry.Text = value; } } public int LimitCriterion { get { return limitComboBox.Active; } set { limitComboBox.Active = value; } } public bool Limit { get { return limitCheckBox.Active; } set { limitCheckBox.Active = value; } } public string OrderBy { get { return model.GetOrder(ComboBoxUtil.GetActiveString(orderComboBox)); } set { if (value == null) return; ComboBoxUtil.SetActiveString(orderComboBox, model.GetOrderName(value)); } } } #endregion }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using Roslyn.Utilities; using Ref = System.Reflection; namespace Microsoft.CodeAnalysis.Scripting { public abstract partial class ObjectFormatter { // internal for testing internal sealed class Formatter { private readonly ObjectFormatter _language; private readonly ObjectFormattingOptions _options; private HashSet<object> _lazyVisitedObjects; private HashSet<object> VisitedObjects { get { if (_lazyVisitedObjects == null) { _lazyVisitedObjects = new HashSet<object>(ReferenceEqualityComparer.Instance); } return _lazyVisitedObjects; } } public Formatter(ObjectFormatter language, ObjectFormattingOptions options) { _options = options ?? ObjectFormattingOptions.Default; _language = language; } private Builder MakeMemberBuilder(int limit) { return new Builder(Math.Min(_options.MaxLineLength, limit), _options, insertEllipsis: false); } public string FormatObject(object obj) { try { var builder = new Builder(_options.MaxOutputLength, _options, insertEllipsis: true); string _; return FormatObjectRecursive(builder, obj, _options.QuoteStrings, _options.MemberFormat, out _).ToString(); } catch (InsufficientExecutionStackException) { return ScriptingResources.StackOverflowWhileEvaluat; } } private Builder FormatObjectRecursive(Builder result, object obj, bool quoteStrings, MemberDisplayFormat memberFormat, out string name) { name = null; string primitive = _language.FormatPrimitive(obj, quoteStrings, _options.IncludeCodePoints, _options.UseHexadecimalNumbers); if (primitive != null) { result.Append(primitive); return result; } object originalObj = obj; Type originalType = originalObj.GetType(); // // Override KeyValuePair<,>.ToString() to get better dictionary elements formatting: // // { { format(key), format(value) }, ... } // instead of // { [key.ToString(), value.ToString()], ... } // // This is more general than overriding Dictionary<,> debugger proxy attribute since it applies on all // types that return an array of KeyValuePair in their DebuggerDisplay to display items. // if (originalType.IsGenericType && originalType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) { if (memberFormat != MemberDisplayFormat.InlineValue) { result.Append(_language.FormatTypeName(originalType, _options)); result.Append(' '); } FormatKeyValuePair(result, originalObj); return result; } if (originalType.IsArray) { if (!VisitedObjects.Add(originalObj)) { result.AppendInfiniteRecursionMarker(); return result; } FormatArray(result, (Array)originalObj, inline: memberFormat != MemberDisplayFormat.List); VisitedObjects.Remove(originalObj); return result; } DebuggerDisplayAttribute debuggerDisplay = GetApplicableDebuggerDisplayAttribute(originalType); if (debuggerDisplay != null) { name = debuggerDisplay.Name; } bool suppressMembers = false; // // TypeName(count) for ICollection implementers // or // TypeName([[DebuggerDisplay.Value]]) // Inline // [[DebuggerDisplay.Value]] // InlineValue // or // [[ToString()]] if ToString overridden // or // TypeName // ICollection collection; if ((collection = originalObj as ICollection) != null) { FormatCollectionHeader(result, collection); } else if (debuggerDisplay != null && !String.IsNullOrEmpty(debuggerDisplay.Value)) { if (memberFormat != MemberDisplayFormat.InlineValue) { result.Append(_language.FormatTypeName(originalType, _options)); result.Append('('); } FormatWithEmbeddedExpressions(result, debuggerDisplay.Value, originalObj); if (memberFormat != MemberDisplayFormat.InlineValue) { result.Append(')'); } suppressMembers = true; } else if (HasOverriddenToString(originalType)) { ObjectToString(result, originalObj); suppressMembers = true; } else { result.Append(_language.FormatTypeName(originalType, _options)); } if (memberFormat == MemberDisplayFormat.NoMembers) { return result; } bool includeNonPublic = memberFormat == MemberDisplayFormat.List; object proxy = GetDebuggerTypeProxy(obj); if (proxy != null) { obj = proxy; includeNonPublic = false; suppressMembers = false; } if (memberFormat != MemberDisplayFormat.List && suppressMembers) { return result; } // TODO (tomat): we should not use recursion RuntimeHelpers.EnsureSufficientExecutionStack(); result.Append(' '); if (!VisitedObjects.Add(originalObj)) { result.AppendInfiniteRecursionMarker(); return result; } // handle special types only if a proxy isn't defined if (proxy == null) { IDictionary dictionary; if ((dictionary = obj as IDictionary) != null) { FormatDictionary(result, dictionary, inline: memberFormat != MemberDisplayFormat.List); return result; } IEnumerable enumerable; if ((enumerable = obj as IEnumerable) != null) { FormatSequence(result, enumerable, inline: memberFormat != MemberDisplayFormat.List); return result; } } FormatObjectMembers(result, obj, originalType, includeNonPublic, inline: memberFormat != MemberDisplayFormat.List); VisitedObjects.Remove(obj); return result; } #region Members /// <summary> /// Formats object members to a list. /// /// Inline == false: /// <code> /// { A=true, B=false, C=new int[3] { 1, 2, 3 } } /// </code> /// /// Inline == true: /// <code> /// { /// A: true, /// B: false, /// C: new int[3] { 1, 2, 3 } /// } /// </code> /// </summary> private void FormatObjectMembers(Builder result, object obj, Type originalType, bool includeNonPublic, bool inline) { int lengthLimit = result.Remaining; if (lengthLimit < 0) { return; } var members = new List<FormattedMember>(); // Limits the number of members added into the result. Some more members may be added than it will fit into the result // and will be thrown away later but not many more. FormatObjectMembersRecursive(members, obj, includeNonPublic, ref lengthLimit); bool useCollectionFormat = UseCollectionFormat(members, originalType); result.AppendGroupOpening(); for (int i = 0; i < members.Count; i++) { result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline); if (useCollectionFormat) { members[i].AppendAsCollectionEntry(result); } else { members[i].Append(result, inline ? "=" : ": "); } if (result.LimitReached) { break; } } result.AppendGroupClosing(inline); } private static bool UseCollectionFormat(IEnumerable<FormattedMember> members, Type originalType) { return typeof(IEnumerable).IsAssignableFrom(originalType) && members.All(member => member.Index >= 0); } private struct FormattedMember { // Non-negative if the member is an inlined element of an array (DebuggerBrowsableState.RootHidden applied on a member of array type). public readonly int Index; // Formatted name of the member or null if it doesn't have a name (Index is >=0 then). public readonly string Name; // Formatted value of the member. public readonly string Value; public FormattedMember(int index, string name, string value) { Name = name; Index = index; Value = value; } public int MinimalLength { get { return (Name != null ? Name.Length : "[0]".Length) + Value.Length; } } public string GetDisplayName() { return Name ?? "[" + Index.ToString() + "]"; } public bool HasKeyName() { return Index >= 0 && Name != null && Name.Length >= 2 && Name[0] == '[' && Name[Name.Length - 1] == ']'; } public bool AppendAsCollectionEntry(Builder result) { // Some BCL collections use [{key.ToString()}]: {value.ToString()} pattern to display collection entries. // We want them to be printed initializer-style, i.e. { <key>, <value> } if (HasKeyName()) { result.AppendGroupOpening(); result.AppendCollectionItemSeparator(isFirst: true, inline: true); result.Append(Name, 1, Name.Length - 2); result.AppendCollectionItemSeparator(isFirst: false, inline: true); result.Append(Value); result.AppendGroupClosing(inline: true); } else { result.Append(Value); } return true; } public bool Append(Builder result, string separator) { result.Append(GetDisplayName()); result.Append(separator); result.Append(Value); return true; } } /// <summary> /// Enumerates sorted object members to display. /// </summary> private void FormatObjectMembersRecursive(List<FormattedMember> result, object obj, bool includeNonPublic, ref int lengthLimit) { Debug.Assert(obj != null); var type = obj.GetType(); var fields = type.GetFields(Ref.BindingFlags.Instance | Ref.BindingFlags.Public | Ref.BindingFlags.NonPublic); var properties = type.GetProperties(Ref.BindingFlags.Instance | Ref.BindingFlags.Public | Ref.BindingFlags.NonPublic); var members = new List<Ref.MemberInfo>(fields.Length + properties.Length); members.AddRange(fields); members.AddRange(properties); // kirillo: need case-sensitive comparison here so that the order of members is // always well-defined (members can differ by case only). And we don't want to // depend on that order. TODO (tomat): sort by visibility. members.Sort(new Comparison<Ref.MemberInfo>((x, y) => { int comparisonResult = StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name); if (comparisonResult == 0) { comparisonResult = StringComparer.Ordinal.Compare(x.Name, y.Name); } return comparisonResult; })); foreach (var member in members) { if (_language.IsHiddenMember(member)) { continue; } bool rootHidden = false, ignoreVisibility = false; var browsable = (DebuggerBrowsableAttribute)member.GetCustomAttributes(typeof(DebuggerBrowsableAttribute), false).FirstOrDefault(); if (browsable != null) { if (browsable.State == DebuggerBrowsableState.Never) { continue; } ignoreVisibility = true; rootHidden = browsable.State == DebuggerBrowsableState.RootHidden; } Ref.FieldInfo field = member as Ref.FieldInfo; if (field != null) { if (!(includeNonPublic || ignoreVisibility || field.IsPublic || field.IsFamily || field.IsFamilyOrAssembly)) { continue; } } else { Ref.PropertyInfo property = (Ref.PropertyInfo)member; var getter = property.GetGetMethod(nonPublic: true); var setter = property.GetSetMethod(nonPublic: true); if (!(includeNonPublic || ignoreVisibility || getter != null && (getter.IsPublic || getter.IsFamily || getter.IsFamilyOrAssembly) || setter != null && (setter.IsPublic || setter.IsFamily || setter.IsFamilyOrAssembly))) { continue; } if (getter.GetParameters().Length > 0) { continue; } } var debuggerDisplay = GetApplicableDebuggerDisplayAttribute(member); if (debuggerDisplay != null) { string k = FormatWithEmbeddedExpressions(lengthLimit, debuggerDisplay.Name, obj) ?? _language.FormatMemberName(member); string v = FormatWithEmbeddedExpressions(lengthLimit, debuggerDisplay.Value, obj) ?? String.Empty; // TODO: ? if (!AddMember(result, new FormattedMember(-1, k, v), ref lengthLimit)) { return; } continue; } Exception exception; object value = GetMemberValue(member, obj, out exception); if (exception != null) { var memberValueBuilder = MakeMemberBuilder(lengthLimit); FormatException(memberValueBuilder, exception); if (!AddMember(result, new FormattedMember(-1, _language.FormatMemberName(member), memberValueBuilder.ToString()), ref lengthLimit)) { return; } continue; } if (rootHidden) { if (value != null && !VisitedObjects.Contains(value)) { Array array; if ((array = value as Array) != null) // TODO (tomat): n-dim arrays { int i = 0; foreach (object item in array) { string name; Builder valueBuilder = MakeMemberBuilder(lengthLimit); FormatObjectRecursive(valueBuilder, item, _options.QuoteStrings, MemberDisplayFormat.InlineValue, out name); if (!String.IsNullOrEmpty(name)) { name = FormatWithEmbeddedExpressions(MakeMemberBuilder(lengthLimit), name, item).ToString(); } if (!AddMember(result, new FormattedMember(i, name, valueBuilder.ToString()), ref lengthLimit)) { return; } i++; } } else if (_language.FormatPrimitive(value, _options.QuoteStrings, _options.IncludeCodePoints, _options.UseHexadecimalNumbers) == null && VisitedObjects.Add(value)) { FormatObjectMembersRecursive(result, value, includeNonPublic, ref lengthLimit); VisitedObjects.Remove(value); } } } else { string name; Builder valueBuilder = MakeMemberBuilder(lengthLimit); FormatObjectRecursive(valueBuilder, value, _options.QuoteStrings, MemberDisplayFormat.InlineValue, out name); if (String.IsNullOrEmpty(name)) { name = _language.FormatMemberName(member); } else { name = FormatWithEmbeddedExpressions(MakeMemberBuilder(lengthLimit), name, value).ToString(); } if (!AddMember(result, new FormattedMember(-1, name, valueBuilder.ToString()), ref lengthLimit)) { return; } } } } private bool AddMember(List<FormattedMember> members, FormattedMember member, ref int remainingLength) { // Add this item even if we exceed the limit - its prefix might be appended to the result. members.Add(member); // We don't need to calculate an exact length, just a lower bound on the size. // We can add more members to the result than it will eventually fit, we shouldn't add less. // Add 2 more, even if only one or half of it fit, so that the separator is included in edge cases. if (remainingLength == Int32.MinValue) { return false; } remainingLength -= member.MinimalLength; if (remainingLength <= 0) { remainingLength = Int32.MinValue; } return true; } private void FormatException(Builder result, Exception exception) { result.Append("!<"); result.Append(_language.FormatTypeName(exception.GetType(), _options)); result.Append('>'); } #endregion #region Collections private void FormatKeyValuePair(Builder result, object obj) { Type type = obj.GetType(); object key = type.GetProperty("Key").GetValue(obj, SpecializedCollections.EmptyObjects); object value = type.GetProperty("Value").GetValue(obj, SpecializedCollections.EmptyObjects); string _; result.AppendGroupOpening(); result.AppendCollectionItemSeparator(isFirst: true, inline: true); FormatObjectRecursive(result, key, quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out _); result.AppendCollectionItemSeparator(isFirst: false, inline: true); FormatObjectRecursive(result, value, quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out _); result.AppendGroupClosing(inline: true); } private void FormatCollectionHeader(Builder result, ICollection collection) { Array array = collection as Array; if (array != null) { result.Append(_language.FormatArrayTypeName(array, _options)); return; } result.Append(_language.FormatTypeName(collection.GetType(), _options)); try { result.Append('('); result.Append(collection.Count.ToString()); result.Append(')'); } catch (Exception) { // skip } } private void FormatArray(Builder result, Array array, bool inline) { FormatCollectionHeader(result, array); if (array.Rank > 1) { FormatMultidimensionalArray(result, array, inline); } else { result.Append(' '); FormatSequence(result, (IEnumerable)array, inline); } } private void FormatDictionary(Builder result, IDictionary dict, bool inline) { result.AppendGroupOpening(); int i = 0; try { IDictionaryEnumerator enumerator = dict.GetEnumerator(); IDisposable disposable = enumerator as IDisposable; try { while (enumerator.MoveNext()) { var entry = enumerator.Entry; string _; result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline); result.AppendGroupOpening(); result.AppendCollectionItemSeparator(isFirst: true, inline: true); FormatObjectRecursive(result, entry.Key, quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out _); result.AppendCollectionItemSeparator(isFirst: false, inline: true); FormatObjectRecursive(result, entry.Value, quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out _); result.AppendGroupClosing(inline: true); i++; } } finally { if (disposable != null) { disposable.Dispose(); } } } catch (Exception e) { result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline); FormatException(result, e); result.Append(' '); result.Append(_options.Ellipsis); } result.AppendGroupClosing(inline); } private void FormatSequence(Builder result, IEnumerable sequence, bool inline) { result.AppendGroupOpening(); int i = 0; try { foreach (var item in sequence) { string name; result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline); FormatObjectRecursive(result, item, quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out name); i++; } } catch (Exception e) { result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline); FormatException(result, e); result.Append(" ..."); } result.AppendGroupClosing(inline); } private void FormatMultidimensionalArray(Builder result, Array array, bool inline) { Debug.Assert(array.Rank > 1); if (array.Length == 0) { result.AppendCollectionItemSeparator(isFirst: true, inline: true); result.AppendGroupOpening(); result.AppendGroupClosing(inline: true); return; } int[] indices = new int[array.Rank]; for (int i = array.Rank - 1; i >= 0; i--) { indices[i] = array.GetLowerBound(i); } int nesting = 0; int flatIndex = 0; while (true) { // increment indices (lower index overflows to higher): int i = indices.Length - 1; while (indices[i] > array.GetUpperBound(i)) { indices[i] = array.GetLowerBound(i); result.AppendGroupClosing(inline: inline || nesting != 1); nesting--; i--; if (i < 0) { return; } indices[i]++; } result.AppendCollectionItemSeparator(isFirst: flatIndex == 0, inline: inline || nesting != 1); i = indices.Length - 1; while (i >= 0 && indices[i] == array.GetLowerBound(i)) { result.AppendGroupOpening(); nesting++; // array isn't empty, so there is always an element following this separator result.AppendCollectionItemSeparator(isFirst: true, inline: inline || nesting != 1); i--; } string name; FormatObjectRecursive(result, array.GetValue(indices), quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out name); indices[indices.Length - 1]++; flatIndex++; } } #endregion #region Scalars private void ObjectToString(Builder result, object obj) { try { string str = obj.ToString(); result.Append('['); result.Append(str); result.Append(']'); } catch (Exception e) { FormatException(result, e); } } #endregion #region DebuggerDisplay Embedded Expressions /// <summary> /// Evaluate a format string with possible member references enclosed in braces. /// E.g. "foo = {GetFooString(),nq}, bar = {Bar}". /// </summary> /// <remarks> /// Although in theory any expression is allowed to be embedded in the string such behavior is in practice fundamentally broken. /// The attribute doesn't specify what language (VB, C#, F#, etc.) to use to parse these expressions. Even if it did all languages /// would need to be able to evaluate each other language's expressions, which is not viable and the Expression Evaluator doesn't /// work that way today. Instead it evaluates the embedded expressions in the language of the current method frame. When consuming /// VB objects from C#, for example, the evaluation migth fail due to language mismatch (evaluating VB expression using C# parser). /// /// Therefore we limit the expressions to a simple language independent syntax: {clr-member-name} '(' ')' ',nq', /// where parentheses and ,nq suffix (no-quotes) are optional and the name is an arbitrary CLR field, property, or method name. /// We then resolve the member by name using case-sensitive lookup first with fallback to case insensitive and evaluate it. /// If parentheses are present we only look for methods. /// Only parameter less members are considered. /// </remarks> private string FormatWithEmbeddedExpressions(int lengthLimit, string format, object obj) { if (String.IsNullOrEmpty(format)) { return null; } return FormatWithEmbeddedExpressions(new Builder(lengthLimit, _options, insertEllipsis: false), format, obj).ToString(); } private Builder FormatWithEmbeddedExpressions(Builder result, string format, object obj) { int i = 0; while (i < format.Length) { char c = format[i++]; if (c == '{') { if (i >= 2 && format[i - 2] == '\\') { result.Append('{'); } else { int expressionEnd = format.IndexOf('}', i); bool noQuotes, callableOnly; string memberName; if (expressionEnd == -1 || (memberName = ParseSimpleMemberName(format, i, expressionEnd, out noQuotes, out callableOnly)) == null) { // the expression isn't properly formatted result.Append(format, i - 1, format.Length - i + 1); break; } Ref.MemberInfo member = ResolveMember(obj, memberName, callableOnly); if (member == null) { result.AppendFormat(callableOnly ? "!<Method '{0}' not found>" : "!<Member '{0}' not found>", memberName); } else { Exception exception; object value = GetMemberValue(member, obj, out exception); if (exception != null) { FormatException(result, exception); } else { string name; FormatObjectRecursive(result, value, !noQuotes, MemberDisplayFormat.NoMembers, out name); } } i = expressionEnd + 1; } } else { result.Append(c); } } return result; } // Parses // <clr-member-name> // <clr-member-name> ',' 'nq' // <clr-member-name> '(' ')' // <clr-member-name> '(' ')' ',' 'nq' // // Internal for testing purposes. internal static string ParseSimpleMemberName(string str, int start, int end, out bool noQuotes, out bool isCallable) { Debug.Assert(str != null && start >= 0 && end >= start); isCallable = false; noQuotes = false; // no-quotes suffix: if (end - 3 >= start && str[end - 2] == 'n' && str[end - 1] == 'q') { int j = end - 3; while (j >= start && Char.IsWhiteSpace(str[j])) { j--; } if (j >= start && str[j] == ',') { noQuotes = true; end = j; } } int i = end - 1; EatTrailingWhiteSpace(str, start, ref i); if (i > start && str[i] == ')') { int closingParen = i; i--; EatTrailingWhiteSpace(str, start, ref i); if (str[i] != '(') { i = closingParen; } else { i--; EatTrailingWhiteSpace(str, start, ref i); isCallable = true; } } EatLeadingWhiteSpace(str, ref start, i); return str.Substring(start, i - start + 1); } private static void EatTrailingWhiteSpace(string str, int start, ref int i) { while (i >= start && Char.IsWhiteSpace(str[i])) { i--; } } private static void EatLeadingWhiteSpace(string str, ref int i, int end) { while (i < end && Char.IsWhiteSpace(str[i])) { i++; } } #endregion } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ApiManagement { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// NetworkStatusOperations operations. /// </summary> internal partial class NetworkStatusOperations : IServiceOperations<ApiManagementClient>, INetworkStatusOperations { /// <summary> /// Initializes a new instance of the NetworkStatusOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal NetworkStatusOperations(ApiManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the ApiManagementClient /// </summary> public ApiManagementClient Client { get; private set; } /// <summary> /// Gets the Connectivity Status to the external resources on which the Api /// Management service depends from inside the Cloud Service. This also returns /// the DNS Servers as visible to the CloudService. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<NetworkStatusContract>> ListByServiceWithHttpMessagesAsync(string resourceGroupName, string serviceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByService", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/networkstatus").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<NetworkStatusContract>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkStatusContract>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the Connectivity Status to the external resources on which the Api /// Management service depends from inside the Cloud Service. This also returns /// the DNS Servers as visible to the CloudService. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='locationName'> /// Location in which the API Management service is deployed. This is one of /// the Azure Regions like West US, East US, South Central US. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<NetworkStatusContract>> ListByLocationWithHttpMessagesAsync(string resourceGroupName, string serviceName, string locationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (locationName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "locationName"); } if (locationName != null) { if (locationName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "locationName", 1); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("locationName", locationName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByLocation", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/locations/{locationName}/networkstatus").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{locationName}", System.Uri.EscapeDataString(locationName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<NetworkStatusContract>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkStatusContract>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Dispatcher { using System.Diagnostics; using System.Runtime; using System.ServiceModel.Channels; using System.ServiceModel.Diagnostics; using System.Transactions; sealed class TransactedBatchContext : IEnlistmentNotification { SharedTransactedBatchContext shared; CommittableTransaction transaction; DateTime commitNotLaterThan; int commits; bool batchFinished; bool inDispatch; internal TransactedBatchContext(SharedTransactedBatchContext shared) { this.shared = shared; this.transaction = TransactionBehavior.CreateTransaction(shared.IsolationLevel, shared.TransactionTimeout); this.transaction.EnlistVolatile(this, EnlistmentOptions.None); if (shared.TransactionTimeout <= TimeSpan.Zero) this.commitNotLaterThan = DateTime.MaxValue; else this.commitNotLaterThan = DateTime.UtcNow + TimeSpan.FromMilliseconds(shared.TransactionTimeout.TotalMilliseconds * 4 / 5); this.commits = 0; this.batchFinished = false; this.inDispatch = false; } internal bool AboutToExpire { get { return DateTime.UtcNow > this.commitNotLaterThan; } } internal bool IsActive { get { if (this.batchFinished) return false; try { return TransactionStatus.Active == this.transaction.TransactionInformation.Status; } catch (ObjectDisposedException ex) { MsmqDiagnostics.ExpectedException(ex); return false; } } } internal bool InDispatch { get { return this.inDispatch; } set { if (this.inDispatch == value) { Fx.Assert("System.ServiceModel.Dispatcher.ChannelHandler.TransactedBatchContext.InDispatch: (inDispatch == value)"); } this.inDispatch = value; if (this.inDispatch) this.shared.DispatchStarted(); else this.shared.DispatchEnded(); } } internal SharedTransactedBatchContext Shared { get { return this.shared; } } internal void ForceRollback() { try { this.transaction.Rollback(); } catch (ObjectDisposedException ex) { MsmqDiagnostics.ExpectedException(ex); } catch (TransactionException ex) { MsmqDiagnostics.ExpectedException(ex); } this.batchFinished = true; } internal void ForceCommit() { try { this.transaction.Commit(); } catch (ObjectDisposedException ex) { MsmqDiagnostics.ExpectedException(ex); } catch (TransactionException ex) { MsmqDiagnostics.ExpectedException(ex); } this.batchFinished = true; } internal void Complete() { ++this.commits; if (this.commits >= this.shared.CurrentBatchSize || DateTime.UtcNow >= this.commitNotLaterThan) { ForceCommit(); } } void IEnlistmentNotification.Prepare(PreparingEnlistment preparingEnlistment) { preparingEnlistment.Prepared(); } void IEnlistmentNotification.Commit(Enlistment enlistment) { this.shared.ReportCommit(); this.shared.BatchDone(); enlistment.Done(); } void IEnlistmentNotification.Rollback(Enlistment enlistment) { this.shared.ReportAbort(); this.shared.BatchDone(); enlistment.Done(); } void IEnlistmentNotification.InDoubt(Enlistment enlistment) { this.shared.ReportAbort(); this.shared.BatchDone(); enlistment.Done(); } internal Transaction Transaction { get { return this.transaction; } } } sealed class SharedTransactedBatchContext { readonly int maxBatchSize; readonly int maxConcurrentBatches; readonly IsolationLevel isolationLevel; readonly TimeSpan txTimeout; int currentBatchSize; int currentConcurrentBatches; int currentConcurrentDispatches; int successfullCommits; object receiveLock = new object(); object thisLock = new object(); bool isBatching; ChannelHandler handler; internal SharedTransactedBatchContext(ChannelHandler handler, ChannelDispatcher dispatcher, int maxConcurrentBatches) { this.handler = handler; this.maxBatchSize = dispatcher.MaxTransactedBatchSize; this.maxConcurrentBatches = maxConcurrentBatches; this.currentBatchSize = dispatcher.MaxTransactedBatchSize; this.currentConcurrentBatches = 0; this.currentConcurrentDispatches = 0; this.successfullCommits = 0; this.isBatching = true; this.isolationLevel = dispatcher.TransactionIsolationLevel; this.txTimeout = TransactionBehavior.NormalizeTimeout(dispatcher.TransactionTimeout); BatchingStateChanged(this.isBatching); } internal TransactedBatchContext CreateTransactedBatchContext() { lock (thisLock) { TransactedBatchContext context = new TransactedBatchContext(this); ++this.currentConcurrentBatches; return context; } } internal void DispatchStarted() { lock (thisLock) { ++this.currentConcurrentDispatches; if (this.currentConcurrentDispatches == this.currentConcurrentBatches && this.currentConcurrentBatches < this.maxConcurrentBatches) { TransactedBatchContext context = new TransactedBatchContext(this); ++this.currentConcurrentBatches; ChannelHandler newHandler = new ChannelHandler(this.handler, context); ChannelHandler.Register(newHandler); } } } internal void DispatchEnded() { lock (thisLock) { --this.currentConcurrentDispatches; if (this.currentConcurrentDispatches < 0) { Fx.Assert("System.ServiceModel.Dispatcher.ChannelHandler.SharedTransactedBatchContext.BatchDone: (currentConcurrentDispatches < 0)"); } } } internal void BatchDone() { lock (thisLock) { --this.currentConcurrentBatches; if (this.currentConcurrentBatches < 0) { Fx.Assert("System.ServiceModel.Dispatcher.ChannelHandler.SharedTransactedBatchContext.BatchDone: (currentConcurrentBatches < 0)"); } } } internal int CurrentBatchSize { get { lock (thisLock) { return this.currentBatchSize; } } } internal IsolationLevel IsolationLevel { get { return this.isolationLevel; } } internal TimeSpan TransactionTimeout { get { return this.txTimeout; } } internal void ReportAbort() { lock (thisLock) { if (isBatching) { this.successfullCommits = 0; this.currentBatchSize = 1; this.isBatching = false; BatchingStateChanged(this.isBatching); } } } internal void ReportCommit() { lock (thisLock) { if (++this.successfullCommits >= this.maxBatchSize * 2) { this.successfullCommits = 0; if (!isBatching) { this.currentBatchSize = this.maxBatchSize; this.isBatching = true; BatchingStateChanged(this.isBatching); } } } } void BatchingStateChanged(bool batchingNow) { if (DiagnosticUtility.ShouldTraceVerbose) { TraceUtility.TraceEvent( TraceEventType.Verbose, batchingNow ? TraceCode.MsmqEnteredBatch : TraceCode.MsmqLeftBatch, batchingNow ? SR.GetString(SR.TraceCodeMsmqEnteredBatch) : SR.GetString(SR.TraceCodeMsmqLeftBatch), null, null, null); } } internal object ReceiveLock { get { return this.receiveLock; } } } }
// Copyright (c) 2016 Framefield. All rights reserved. // Released under the MIT license. (see LICENSE.txt) using System; using System.Collections.Generic; using System.Windows; using System.Windows.Input; using Framefield.Core; using SharpDX; using Key = System.Windows.Input.Key; using Keyboard = System.Windows.Input.Keyboard; using Point = System.Windows.Point; using Framefield.Tooll.Rendering; using Framefield.Core.OperatorPartTraits; namespace Framefield.Tooll.Components.SelectionView.ShowScene.CameraInteraction { /// <summary> /// Handles mouse and keyboard interaction of Scene Selection-Views. /// /// The steps for a mouse-klick to a camera-interaction could be like this... /// /// - WPF triggers MouseDown-event, which... /// - gets handled by MouseDown-Handler in ShowContentControl, which... /// - calls HandleMouseDown /// - set _XXXmouseButtonPressed members /// /// - on each frame WPF emits RenderCompositionTarget... /// - which gets handled by ShowContentControl.App_CompositionTargertRenderingHandler /// - which calls UpdateAndCheckIfRedrawRequired() /// - checks if we need to render because... /// /// - Camera has been changed from outside, or /// - asks the RawMouseInput for the latest MousePosition, and if... /// - mouse is interactive with a TransformGizmo, or... /// - Camera is been manipulated by Keyboard, Mouse (e.g. _XXXMouseButtonPressed), SpaceMouse, or... /// - Camera is been updated by a transition (flicking, etc.) /// /// For the transitions we slowly blend the scene's CameraPosition and CameraTarget into /// _cameraTargetGoal and _cameraPositionGoal. If the distance between camera and its "goal" is /// below a threshold, the transition stops and we no longer need to update (e.g. rerender) the view. /// /// If a camera-operator is selected it parameters get automatically manipulated, because we direcly /// set the scene's CameraPosition and CameraTarget-parameters, which does this check for us. /// /// </summary> public class CameraInteraction { public CameraInteraction(RenderViewConfiguration renderConfig, ShowContentControl showContentControl) { MaxMoveVelocity = (float)App.Current.ProjectSettings.GetOrSetDefault("Tooll.SelectionView.Camera.MaxVelocity", MAX_MOVE_VELOCITY_DEFAULT); _cameraAcceleration = (float)App.Current.ProjectSettings.GetOrSetDefault("Tooll.SelectionView.Camera.Acceleration", CAMERA_ACCELERATION_DEFAULT); _frictionKeyboardManipulation = (float)App.Current.ProjectSettings.GetOrSetDefault("Tooll.SelectionView.Camera.Friction", 0.3f); _showContentControl = showContentControl; _renderConfig = renderConfig; _spaceMouse = new SpaceMouse(this, renderConfig); GizmoPartHitIndex = -1; } public void Discard() { _spaceMouse.Discard(); } private Operator _lastRenderedOperator; public void SetCameraAfterExternalChanges(Vector3 newPosition, Vector3 newTarget) { _cameraPositionGoal = newPosition; _cameraTargetGoal = newTarget; } public bool UpdateAndCheckIfRedrawRequired() { if (_showContentControl.RenderSetup == null) return false; // Stop all transitions when switching between camera-ops if (_renderConfig.Operator != _lastRenderedOperator) { _lastRenderedOperator = _renderConfig.Operator; _cameraPositionGoal = _renderConfig.CameraSetup.Position; _cameraTargetGoal = _renderConfig.CameraSetup.Target; MoveVelocity = Vector3.Zero; SmoothedMovementInProgress = false; } var redrawRequired = false; UpdateRawMouseData(); if (_interactionLocked) return false; _interactionLocked = true; // Manipulation... redrawRequired |= ManipulateGizmos(); if (_renderConfig.TransformGizmo.State != TransformGizmo.TransformGizmo.GizmoStates.Dragged) { ManipulateCameraByMouse(); } _manipulatedByKeyboard = ManipulateCameraByKeyboard(); _spaceMouse.ManipulateCamera(); // Transition... redrawRequired |= ComputeSmoothMovement(); _interactionLocked = false; return redrawRequired; } /* * Returns false if camera didn't move */ private bool ComputeSmoothMovement() { var frameDurationFactor = (float)(App.Current.TimeSinceLastFrame) / FRAME_DURATION_AT_60_FPS; if (PositionDistance.Length() > STOP_DISTANCE_THRESHOLD || TargetDistance.Length() > STOP_DISTANCE_THRESHOLD || MoveVelocity.Length() > STOP_DISTANCE_THRESHOLD || _lookingAroundDelta.Length() > STOP_DISTANCE_THRESHOLD || _manipulatedByMouseWheel || _orbitDelta.Length() > 0.001f || _manipulatedByKeyboard) { if (_orbitDelta.Length() > 0.001f) { OrbitByAngle(_orbitDelta); _orbitDelta *= new Vector2(ORBIT_HORIZONTAL_FRICTION, ORBIT_VERTICAL_FRICTION) / frameDurationFactor; } if (MoveVelocity.Length() > MaxMoveVelocity) { MoveVelocity *= MaxMoveVelocity / MoveVelocity.Length(); } else if (!_manipulatedByKeyboard) { MoveVelocity *= (1 - _frictionKeyboardManipulation) / frameDurationFactor; } _cameraPositionGoal += MoveVelocity; _cameraTargetGoal += MoveVelocity + _lookingAroundDelta; _lookingAroundDelta = Vector3.Zero; PositionDistance *= CAMERA_MOVE_FRICTION / frameDurationFactor; TargetDistance *= CAMERA_MOVE_FRICTION / frameDurationFactor; SmoothedMovementInProgress = true; _manipulatedByMouseWheel = false; return true; } else { StopTransitionOfPositionTarget(); SmoothedMovementInProgress = false; return false; } } #region WPF event handles for mouse-keys, -wheel and keyboard /** * WPF will discard some mouse-wheel events on slow framerates which leads to a laggy * interaction in complex scenes. For that reason, we include the framerate into the zoom-speed * and -- sadly -- avoid transitions for for zooming. */ public void HandleMouseWheel(float delta) { var transitionActive = PositionDistance.Length() > STOP_DISTANCE_THRESHOLD || TargetDistance.Length() > STOP_DISTANCE_THRESHOLD; var viewDirection = transitionActive ? _cameraPositionGoal - _cameraTargetGoal : _renderConfig.CameraSetup.Position - _renderConfig.CameraSetup.Target; var frameDurationFactor = (float)(App.Current.TimeSinceLastFrame) / FRAME_DURATION_AT_60_FPS; var zoomFactorForCurrentFramerate = 1 + (ZOOM_SPEED * frameDurationFactor); if (delta < 0) { viewDirection *= zoomFactorForCurrentFramerate; } else { viewDirection /= zoomFactorForCurrentFramerate; } _renderConfig.CameraSetup.Position = _cameraPositionGoal = _cameraTargetGoal + viewDirection; _manipulatedByMouseWheel = true; } public void HandleMouseDown(MouseButton changedButton) { switch (changedButton) { case MouseButton.Left: _renderConfig.TransformGizmo.HandleLeftMouseDown(); _leftMouseButtonPressed = true; break; case MouseButton.Middle: _middleMouseButtonPressed = true; break; case MouseButton.Right: _rightMouseButtonPressed = true; _rightMousePressedAt = _mousePos; break; } } private Point _rightMousePressedAt; /// <summary> /// Uses the original mouse event to update local parameters for dragging the camera. /// </summary> /// <param name="changedButton"></param> /// <returns>true if right click detected</returns> public bool HandleMouseUp(MouseButton changedButton) { var wasRightClick = false; switch (changedButton) { case MouseButton.Left: _renderConfig.TransformGizmo.HandleLeftMouseUp(); _leftMouseButtonPressed = false; break; case MouseButton.Middle: _middleMouseButtonPressed = false; break; case MouseButton.Right: _rightMouseButtonPressed = false; var dragDistances = (_rightMousePressedAt - _mousePos).Length; wasRightClick = !AnyMouseButtonPressed() && dragDistances < SystemParameters.MinimumHorizontalDragDistance; break; } return wasRightClick; } public void HandleKeyDown(KeyEventArgs e) { var key = e.Key; // Ignore non-interaction keys and anything if control is pressed if (!INTERACTION_KEYS.Contains(key) || Keyboard.Modifiers.HasFlag(ModifierKeys.Control)) return; if (Keyboard.Modifiers.HasFlag(ModifierKeys.Alt)) key = e.SystemKey; // If Alt ist pressed, key must be stored as systemkey if (key != Key.LeftAlt) _pressedKeys.Add(key); } public bool HandleKeyUp(KeyEventArgs e) { if (!INTERACTION_KEYS.Contains(e.Key) || Keyboard.Modifiers.HasFlag(ModifierKeys.Control)) return true; _pressedKeys.Remove(e.Key); var key = e.Key; if (Keyboard.Modifiers.HasFlag(ModifierKeys.Alt)) key = e.SystemKey; _pressedKeys.Remove(key); return false; } public void HandleFocusLost() { _pressedKeys.Clear(); } #endregion #region Gizmo-Manimupulation private bool ManipulateGizmos() { if (!(_mouseMoveDelta.Length > MOUSE_MOVE_THRESHOLD)) return false; var rayInWorld = ComputeMouseViewRayInWorld(); var hitIndex = _renderConfig.TransformGizmo.CheckForManipulationByRay(rayInWorld); if (hitIndex == GizmoPartHitIndex) return false; GizmoPartHitIndex = hitIndex; _renderConfig.TransformGizmo.IndexOfGizmoPartBelowMouse = hitIndex; // Ugly hack so scene can set context-variable for hover return true; } private Ray ComputeMouseViewRayInWorld() { var windowPos = _showContentControl.PointFromScreen(_mousePos); var x = (float)(2.0 * windowPos.X / _showContentControl.ActualWidth - 1); var y = (float)-(2.0 * windowPos.Y / _showContentControl.ActualHeight - 1); var rayNds = new Vector3(x, y, 1.0f); // Normalized Device coordinates var rayClip = new Vector4(rayNds.X, rayNds.Y, -1, 1); var inverseProjection = (_renderConfig.CameraSetup.LastCameraProjection); inverseProjection.Invert(); var rayEye = Vector4.Transform(rayClip, inverseProjection); rayEye.Z = 1; rayEye.W = 0; var inverseViewMatrix = (_renderConfig.CameraSetup.LastWorldToCamera); inverseViewMatrix.Invert(); var rayDirectionInWorld = Vector4.Transform(rayEye, inverseViewMatrix); Vector3 raySourceInWorld = _renderConfig.CameraSetup.Position; var rayInWorld = new Ray(raySourceInWorld, new Vector3(rayDirectionInWorld.X, rayDirectionInWorld.Y, rayDirectionInWorld.Z)); return rayInWorld; } #endregion #region Mouse interaction private void ManipulateCameraByMouse() { var altPressed = Keyboard.Modifiers.HasFlag(ModifierKeys.Alt); var ctrlPressed = Keyboard.Modifiers.HasFlag(ModifierKeys.Control); if (_leftMouseButtonPressed) { if (altPressed) { Pan(); } else if (ctrlPressed) { LookAround(); } else { DragOrbit(); } } else if (_rightMouseButtonPressed) { Pan(); } else if (_middleMouseButtonPressed) { LookAround(); } _mouseDragDelta = new Vector(); } private void LookAround() { var factorX = (float)(_mouseDragDelta.X / _renderConfig.Height * ROTATE_MOUSE_SENSIVITY * Math.PI / 180.0); var factorY = (float)(_mouseDragDelta.Y / _renderConfig.Height * ROTATE_MOUSE_SENSIVITY * Math.PI / 180.0); Matrix rotAroundX = Matrix.RotationAxis(_renderConfig.CameraSetup.SideDir, factorY); Matrix rotAroundY = Matrix.RotationAxis(_renderConfig.CameraSetup.UpDir, factorX); Matrix rot = Matrix.Multiply(rotAroundX, rotAroundY); var viewDir2 = new Vector4(_cameraTargetGoal - _cameraPositionGoal, 1); var viewDirRotated = Vector4.Transform(viewDir2, rot); var newTarget = _cameraPositionGoal + new Vector3(viewDirRotated.X, viewDirRotated.Y, viewDirRotated.Z); _lookingAroundDelta = newTarget - _cameraTargetGoal; } private void DragOrbit() { _orbitDelta = new Vector2((float)(_mouseDragDelta.X / _renderConfig.Height * ORBIT_SENSIVITY * Math.PI / 180.0), (float)(_mouseDragDelta.Y / _renderConfig.Height * ORBIT_SENSIVITY * Math.PI / 180.0)); } private void OrbitByAngle(Vector2 rotationSpeed) { var currentTarget = _renderConfig.CameraSetup.Target; var viewDir = _renderConfig.CameraSetup.ViewDir; var viewDirLength = viewDir.Length(); viewDir /= viewDirLength; Matrix rotAroundX = Matrix.RotationAxis(_renderConfig.CameraSetup.SideDir, rotationSpeed.Y); Matrix rotAroundY = Matrix.RotationAxis(_renderConfig.CameraSetup.UpDir, rotationSpeed.X); Matrix rot = Matrix.Multiply(rotAroundX, rotAroundY); Vector4 newViewDir = Vector3.Transform(viewDir, rot); newViewDir.Normalize(); // Set new position and freeze cam-target transitions _renderConfig.CameraSetup.Position = _cameraPositionGoal = _renderConfig.CameraSetup.Target - newViewDir.ToVector3() * viewDirLength; _cameraTargetGoal = currentTarget; } private void Pan() { var factorX = (float)(-_mouseDragDelta.X / _renderConfig.Height); var factorY = (float)(_mouseDragDelta.Y / _renderConfig.Height); var length = (_cameraTargetGoal - _cameraPositionGoal).Length(); var sideDir = _renderConfig.CameraSetup.SideDir; var upDir = _renderConfig.CameraSetup.UpDir; sideDir *= factorX * length; upDir *= factorY * length; _cameraPositionGoal += sideDir + upDir; _cameraTargetGoal += sideDir + upDir; } #endregion #region Keyboard Interaction void StopTransitionOfPositionTarget() { _cameraTargetGoal = _renderConfig.CameraSetup.Target; _cameraPositionGoal = _renderConfig.CameraSetup.Position; } private bool ManipulateCameraByKeyboard() { var frameDurationFactor = (float)(App.Current.TimeSinceLastFrame); var sideDir = _renderConfig.CameraSetup.SideDir; var upDir = _renderConfig.CameraSetup.UpDir; var viewDir = _renderConfig.CameraSetup.ViewDir; var viewDirLength = viewDir.Length(); var initialVelocity = MoveVelocity.Length() < STOP_DISTANCE_THRESHOLD ? INITIAL_MOVE_VELOCITY : 0; var increaseAccelerationWithZoom = (_cameraPositionGoal - _cameraTargetGoal).Length() / 10f; var accelFactor = _cameraAcceleration * increaseAccelerationWithZoom; var interactionKeysPressedCount = 0; foreach (var key in _pressedKeys) { switch (key) { case Key.A: case Key.Left: MoveVelocity -= sideDir * (accelFactor + initialVelocity) * frameDurationFactor; interactionKeysPressedCount++; break; case Key.D: case Key.Right: MoveVelocity += sideDir * (accelFactor + initialVelocity) * frameDurationFactor; interactionKeysPressedCount++; break; case Key.W: case Key.Up: MoveVelocity += viewDir * (accelFactor + initialVelocity) / viewDirLength * frameDurationFactor; interactionKeysPressedCount++; break; case Key.S: case Key.Down: MoveVelocity -= viewDir * (accelFactor + initialVelocity) / viewDirLength * frameDurationFactor; interactionKeysPressedCount++; break; case Key.E: MoveVelocity += upDir * (accelFactor + initialVelocity) * frameDurationFactor; interactionKeysPressedCount++; break; case Key.X: MoveVelocity -= upDir * (accelFactor + initialVelocity) * frameDurationFactor; interactionKeysPressedCount++; break; case Key.F: MoveVelocity = Vector3.Zero; _cameraPositionGoal = new Vector3(0, 0, CameraSetup.DEFAULT_CAMERA_POSITION_Z); _cameraTargetGoal = new Vector3(0, 0, 0f); interactionKeysPressedCount++; break; // Center Camera case Key.C: var delta = _renderConfig.TransformGizmo.IsGizmoActive ? _renderConfig.TransformGizmo.GizmoToWorld.TranslationVector - _cameraTargetGoal : -_cameraTargetGoal; _cameraTargetGoal += delta; _cameraPositionGoal += delta; interactionKeysPressedCount++; break; } } return interactionKeysPressedCount > 0; } #endregion #region RAW-MouseData /** * Because MouseMove event is not triggered if CompositionTarget.Render * gets too complex, this method uses raw input from user32 as a workaround * to provide interactive mouse rotation. * * Because MouseDown/MouseUp events are also not triggered, we have to * rely on the virtual key for the left mouse button to check if a dragging * is currently happening. * * Read more at https://streber.framefield.com/5381 */ private void UpdateRawMouseData() { Win32RawInput.POINT screenSpacePoint; Win32RawInput.GetCursorPos(out screenSpacePoint); // note that screenSpacePoint is in screen-space pixel coordinates, // not the same WPF Units you get from the MouseMove event. // You may want to convert to WPF units when using GetCursorPos. var currentMousePosition = new Point(screenSpacePoint.X, screenSpacePoint.Y); const int LEFT_BUTTON_VIRTUAL_KEY_CODE = 0x01; const int RIGHT_BUTTON_VIRTUAL_KEY_CODE = 0x02; const int MIDDLE_BUTTON_VIRTUAL_KEY_CODE = 0x04; /** * sadly, we can't use this flags for anything more that determing with "something" was dragged with * "some" mouseButton. We can't assign this flags to the members controlled by the MouseDown/Up handlers * because this would interfer with the focus-state can the window's mouse capute and thus cause camera * manipulation even if the mouse is no longer inside the window. I know, that this is a mindfuck. */ var leftMousePressed = Convert.ToInt32(Win32RawInput.GetAsyncKeyState(LEFT_BUTTON_VIRTUAL_KEY_CODE)) != 0; var rightMousePressed = Convert.ToInt32(Win32RawInput.GetAsyncKeyState(RIGHT_BUTTON_VIRTUAL_KEY_CODE)) != 0; var middleMousePressed = Convert.ToInt32(Win32RawInput.GetAsyncKeyState(MIDDLE_BUTTON_VIRTUAL_KEY_CODE)) != 0; var mousePressed = leftMousePressed || rightMousePressed || middleMousePressed; if (_showContentControl.IsFocused && mousePressed) { if (_mouseWasReleased) { _mouseDragDelta = new Vector(); _mouseWasReleased = false; } else { _mouseDragDelta = currentMousePosition - _mousePos; } } else { _mouseDragDelta = new Vector(); _mouseWasReleased = true; } _mouseMoveDelta = currentMousePosition - _mousePos; _mousePos = currentMousePosition; } #endregion public bool AnyMouseButtonPressed() { return _leftMouseButtonPressed || _middleMouseButtonPressed || _rightMouseButtonPressed; } public int GizmoPartHitIndex { get; private set; } private Vector3 _cameraTargetGoal = Vector3.Zero; Vector3 TargetDistance { get { return _cameraTargetGoal - _renderConfig.CameraSetup.Target; } set { _renderConfig.CameraSetup.Target = _cameraTargetGoal - value; } } private Vector3 _cameraPositionGoal = new Vector3(0, 0, CameraSetup.DEFAULT_CAMERA_POSITION_Z); Vector3 PositionDistance { get { return _cameraPositionGoal - _renderConfig.CameraSetup.Position; } set { _renderConfig.CameraSetup.Position = _cameraPositionGoal - value; } } private Vector3 _lookingAroundDelta = Vector3.Zero; private Vector2 _orbitDelta; private const float ROTATE_MOUSE_SENSIVITY = 300; private const float ORBIT_SENSIVITY = 200; private const float ORBIT_HORIZONTAL_FRICTION = 0.92f; private const float ORBIT_VERTICAL_FRICTION = 0.86f; // A bit less to avoid sliding into gimbal lock private const float MOUSE_MOVE_THRESHOLD = 0.01f; private const float INITIAL_MOVE_VELOCITY = 0.0f; const float CAMERA_MOVE_FRICTION = 0.80f; private const float ZOOM_SPEED = 0.2f; private const float STOP_DISTANCE_THRESHOLD = 0.001f; private const float FRAME_DURATION_AT_60_FPS = 0.016f; private const float MAX_MOVE_VELOCITY_DEFAULT = 2f; private const float CAMERA_ACCELERATION_DEFAULT = 1f; private readonly ShowContentControl _showContentControl; internal bool SmoothedMovementInProgress; private bool _manipulatedByMouseWheel; private bool _manipulatedByKeyboard; private bool _leftMouseButtonPressed; private bool _middleMouseButtonPressed; private bool _rightMouseButtonPressed; /** * This list is an ugly repetion of the keys checked in ManiplulateCameryByKeyboard. * We need it to keep up a an array of pressed keys. This is prone to errors and should be refactored */ private static readonly List<Key> INTERACTION_KEYS = new List<Key> { Key.A, Key.S, Key.D, Key.E, Key.X, Key.F, Key.C, Key.W, }; internal Vector3 MoveVelocity = Vector3.Zero; // required by space-mouse internal readonly float MaxMoveVelocity; // set from Project-Settings in Constructor! private Point _mousePos; private Vector _mouseMoveDelta; private bool _mouseWasReleased = true; private bool _interactionLocked; private Vector _mouseDragDelta; private readonly HashSet<Key> _pressedKeys = new HashSet<Key>(); private readonly float _frictionKeyboardManipulation; // set from Project-Settings in Constructor! private readonly float _cameraAcceleration; // set from Project-Settings in Constructor! private readonly SpaceMouse _spaceMouse; private RenderViewConfiguration _renderConfig; } }
//------------------------------------------------------------------------------ // <copyright file="IISUnsafeMethods.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Hosting { using System; using System.Configuration; using System.Text; using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; [ System.Runtime.InteropServices.ComVisible(false), System.Security.SuppressUnmanagedCodeSecurityAttribute() ] // contains only method decls and data, so no instantiation internal unsafe static class UnsafeIISMethods { const string _IIS_NATIVE_DLL = ModName.MGDENG_FULL_NAME; static internal readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); [DllImport(_IIS_NATIVE_DLL)] internal unsafe static extern int MgdGetRequestBasics( IntPtr pRequestContext, out int pContentType, out int pContentTotalLength, out IntPtr pPathTranslated, out int pcchPathTranslated, out IntPtr pCacheUrl, out int pcchCacheUrl, out IntPtr pHttpMethod, out IntPtr pCookedUrl); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetHeaderChanges( IntPtr pRequestContext, bool fResponse, out IntPtr knownHeaderSnapshot, out int unknownHeaderSnapshotCount, out IntPtr unknownHeaderSnapshotNames, out IntPtr unknownHeaderSnapshotValues, out IntPtr diffKnownIndicies, out int diffUnknownCount, out IntPtr diffUnknownIndicies); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetServerVarChanges( IntPtr pRequestContext, out int count, out IntPtr names, out IntPtr values, out int diffCount, out IntPtr diffIndicies); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdGetServerVariableW( IntPtr pHandler, string pszVarName, out IntPtr ppBuffer, out int pcchBufferSize); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdGetServerVariableA( IntPtr pHandler, string pszVarName, out IntPtr ppBuffer, out int pcchBufferSize); [DllImport(_IIS_NATIVE_DLL)] internal static extern IntPtr MgdGetStopListeningEventHandle(); [DllImport(_IIS_NATIVE_DLL)] internal static extern void MgdSetBadRequestStatus( IntPtr pHandler); [DllImport(_IIS_NATIVE_DLL)] internal static extern void MgdSetManagedHttpContext( IntPtr pHandler, IntPtr pManagedHttpContext); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdSetStatusW( IntPtr pRequestContext, int dwStatusCode, int dwSubStatusCode, string pszReason, string pszErrorDescription /* optional, can be null */, bool fTrySkipCustomErrors); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdSetKnownHeader( IntPtr pRequestContext, bool fRequest, bool fReplace, ushort uHeaderIndex, byte[] value, ushort valueSize); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdSetUnknownHeader( IntPtr pRequestContext, bool fRequest, bool fReplace, byte [] header, byte [] value, ushort valueSize); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdFlushCore( IntPtr pRequestContext, bool keepConnected, int numBodyFragments, IntPtr[] bodyFragments, int[] bodyFragmentLengths, int[] fragmentsNative); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdSetKernelCachePolicy( IntPtr pHandler, int secondsToLive); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdFlushKernelCache( string cacheKey); [DllImport(_IIS_NATIVE_DLL)] internal static extern void MgdDisableKernelCache( IntPtr pHandler); [DllImport(_IIS_NATIVE_DLL)] internal static extern void MgdDisableUserCache( IntPtr pHandler); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdRegisterEventSubscription( IntPtr pAppContext, string pszModuleName, [MarshalAs(UnmanagedType.U4)] RequestNotification requestNotifications, [MarshalAs(UnmanagedType.U4)] RequestNotification postRequestNotifications, string pszModuleType, string pszModulePrecondition, IntPtr moduleSpecificData, bool useHighPriority); [DllImport(_IIS_NATIVE_DLL)] internal static extern void MgdIndicateCompletion( IntPtr pHandler, [MarshalAs(UnmanagedType.U4)] ref RequestNotificationStatus notificationStatus ); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdInsertEntityBody( IntPtr pHandler, byte[] buffer, int offset, int count); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdPostCompletion( IntPtr pHandler, [MarshalAs(UnmanagedType.U4)] RequestNotificationStatus notificationStatus ); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdReadEntityBody( IntPtr pHandler, byte[] pBuffer, int dwOffset, int dwBytesToRead, bool fAsync, out int pBytesRead, out IntPtr ppAsyncReceiveBuffer ); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdGetCorrelationIdHeader( IntPtr pHandler, out IntPtr correlationId, out ushort correlationIdLength, out bool base64BinaryFormat); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdGetUserToken( IntPtr pHandler, out IntPtr pToken ); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdGetVirtualToken( IntPtr pHandler, out IntPtr pToken ); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern bool MgdIsClientConnected( IntPtr pHandler); [DllImport(_IIS_NATIVE_DLL)] internal static extern bool MgdIsHandlerExecutionDenied( IntPtr pHandler); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "We carefully control this method's sole caller.")] internal static extern void MgdAbortConnection( IntPtr pHandler); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern void MgdCloseConnection( IntPtr pHandler); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdGetHandlerTypeString( IntPtr pHandler, out IntPtr ppszTypeString, out int pcchTypeString); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdGetApplicationInfo( IntPtr pHandler, out IntPtr pVirtualPath, out int cchVirtualPath, out IntPtr pPhysPath, out int cchPhysPath); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdGetUriPath( IntPtr pHandler, out IntPtr ppPath, out int pcchPath, bool fIncludePathInfo, bool fUseParentContext); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetPreloadedContent( IntPtr pHandler, byte[] pBuffer, int lOffset, int cbLen, out int pcbReceived); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetPreloadedSize( IntPtr pHandler, out int pcbAvailable); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdGetPrincipal( IntPtr pHandler, int dwRequestingAppDomainId, out IntPtr pToken, out IntPtr ppAuthType, ref int pcchAuthType, out IntPtr ppUserName, ref int pcchUserName, out IntPtr pManagedPrincipal); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdIsInRole( IntPtr pHandler, string pszRoleName, out bool pfIsInRole); [DllImport(_IIS_NATIVE_DLL)] internal static extern IntPtr MgdAllocateRequestMemory( IntPtr pHandler, int cbSize); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdAppDomainShutdown( IntPtr appContext ); // Buffer pool methods [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern IntPtr /* W3_MGD_BUFFER_POOL* */ MgdGetBufferPool(int cbBufferSize); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern IntPtr /* PBYTE * */ MgdGetBuffer(IntPtr pPool); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern IntPtr /* W3_MGD_BUFFER_POOL* */ MgdReturnBuffer(IntPtr pBuffer); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int /* DWORD */ MgdGetLocalPort(IntPtr context); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int /* DWORD */ MgdGetRemotePort(IntPtr context); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetUserAgent( IntPtr pRequestContext, out IntPtr pBuffer, out int cbBufferSize); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetCookieHeader( IntPtr pRequestContext, out IntPtr pBuffer, out int cbBufferSize); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdRewriteUrl( IntPtr pRequestContext, string pszUrl, bool fResetQueryString ); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetMaxConcurrentRequestsPerCPU(); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetMaxConcurrentThreadsPerCPU(); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdSetMaxConcurrentRequestsPerCPU(int value); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdSetMaxConcurrentThreadsPerCPU(int value); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetCurrentModuleName( IntPtr pHandler, out IntPtr pBuffer, out int cbBufferSize); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetCurrentNotification( IntPtr pRequestContext); [DllImport(_IIS_NATIVE_DLL)] internal static extern void MgdDisableNotifications( IntPtr pRequestContext, [MarshalAs(UnmanagedType.U4)] RequestNotification notifications, [MarshalAs(UnmanagedType.U4)] RequestNotification postNotifications); [DllImport(_IIS_NATIVE_DLL)] internal static extern void MgdSuppressSendResponseNotifications( IntPtr pRequestContext); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetNextNotification( IntPtr pRequestContext, [MarshalAs(UnmanagedType.U4)] RequestNotificationStatus dwStatus); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdClearResponse( IntPtr pRequestContext, bool fClearEntity, bool fClearHeaders); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdCreateNativeConfigSystem( out IntPtr ppConfigSystem); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdReleaseNativeConfigSystem( IntPtr pConfigSystem); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetRequestTraceGuid( IntPtr pRequestContext, out Guid traceContextId); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetStatusChanges( IntPtr pRequestContext, out ushort statusCode, out ushort subStatusCode, out IntPtr pBuffer, out ushort cbBufferSize); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetResponseChunks( IntPtr pRequestContext, ref int fragmentCount, IntPtr[] bodyFragments, int[] bodyFragmentLengths, int[] fragmentChunkType); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdEtwGetTraceConfig( IntPtr pRequestContext, out bool providerEnabled, out int flags, out int level); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdEmitSimpleTrace( IntPtr pRequestContext, int type, string eventData); [DllImport(_IIS_NATIVE_DLL, CharSet = CharSet.Unicode)] internal static extern int MgdEmitWebEventTrace( IntPtr pRequestContext, int webEventType, int fieldCount, string[] fieldNames, int[] fieldTypes, string[] fieldData); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdSetRequestPrincipal( IntPtr pRequestContext, string userName, string authType, IntPtr token); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern bool MgdCanDisposeManagedContext( IntPtr pRequestContext, [MarshalAs(UnmanagedType.U4)] RequestNotificationStatus dwStatus); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern bool MgdIsLastNotification( IntPtr pRequestContext, [MarshalAs(UnmanagedType.U4)] RequestNotificationStatus dwStatus); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern bool MgdIsWithinApp( IntPtr pConfigSystem, string siteName, string appPath, string virtualPath); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetSiteNameFromId( IntPtr pConfigSystem, [MarshalAs(UnmanagedType.U4)] uint siteId, out IntPtr bstrSiteName, out int cchSiteName); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdGetAppPathForPath( IntPtr pConfigSystem, [MarshalAs(UnmanagedType.U4)] uint siteId, string virtualPath, out IntPtr bstrPath, out int cchPath); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetMemoryLimitKB( out long limit); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetMimeMapCollection( IntPtr pConfigSystem, IntPtr appContext, out IntPtr pMimeMapCollection, out int count); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetModuleCollection( IntPtr pConfigSystem, IntPtr appContext, out IntPtr pModuleCollection, out int count); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetNextMimeMap( IntPtr pMimeMapCollection, uint dwIndex, out IntPtr bstrFileExtension, out int cchFileExtension, out IntPtr bstrMimeType, out int cchMimeType); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetNextModule( IntPtr pModuleCollection, ref uint dwIndex, out IntPtr bstrModuleName, out int cchModuleName, out IntPtr bstrModuleType, out int cchModuleType, out IntPtr bstrModulePrecondition, out int cchModulePrecondition); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdGetVrPathCreds( IntPtr pConfigSystem, string siteName, string virtualPath, out IntPtr bstrUserName, out int cchUserName, out IntPtr bstrPassword, out int cchPassword); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdGetAppCollection( IntPtr pConfigSystem, string siteName, string virtualPath, out IntPtr bstrPath, out int cchPath, out IntPtr pAppCollection, out int count); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetNextVPath( IntPtr pAppCollection, uint dwIndex, out IntPtr bstrPath, out int cchPath); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdInitNativeConfig(); [DllImport(_IIS_NATIVE_DLL)] internal static extern void MgdTerminateNativeConfig(); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdMapPathDirect( IntPtr pConfigSystem, string siteName, string virtualPath, out IntPtr bstrPhysicalPath, out int cchPath); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdMapHandler( IntPtr pHandler, string method, string virtualPath, out IntPtr ppszTypeString, out int pcchTypeString, bool convertNativeStaticFileModule, bool ignoreWildcardMappings); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdReMapHandler( IntPtr pHandler, string pszVirtualPath, out IntPtr ppszTypeString, out int pcchTypeString, out bool pfHandlerExists); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdSetRemapHandler( IntPtr pHandler, string pszName, string ppszType); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdSetScriptMapForRemapHandler( IntPtr pHandler); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdSetNativeConfiguration( IntPtr nativeConfig); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint MgdResolveSiteName( IntPtr pConfigSystem, string siteName); [DllImport(_IIS_NATIVE_DLL)] internal static extern void MgdSetResponseFilter( IntPtr context); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetFileChunkInfo( IntPtr context, int chunkOffset, out long offset, out long length); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdReadChunkHandle( IntPtr context, IntPtr FileHandle, long startOffset, ref int length, IntPtr chunkEntity); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdExplicitFlush( IntPtr context, bool async, out bool completedSynchronously); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdSetServerVariableW( IntPtr context, string variableName, string variableValue); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdExecuteUrl( IntPtr context, string url, bool resetQuerystring, bool preserveForm, byte[] entityBody, uint entityBodySize, string method, int numHeaders, string[] headersNames, string[] headersValues, bool preserveUser); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdGetClientCertificate( IntPtr pHandler, out IntPtr ppbClientCert, out int pcbClientCert, out IntPtr ppbClientCertIssuer, out int pcbClientCertIssuer, out IntPtr ppbClientCertPublicKey, out int pcbClientCertPublicKey, out uint pdwCertEncodingType, out long ftNotBefore, out long ftNotAfter); [DllImport(_IIS_NATIVE_DLL)] internal static extern int MgdGetChannelBindingToken( IntPtr pHandler, out IntPtr ppbToken, out int pcbTokenSize); [DllImport(_IIS_NATIVE_DLL)] internal static extern void MgdGetCurrentNotificationInfo( IntPtr pHandler, out int currentModuleIndex, out bool isPostNotification, out int currentNotification); [DllImport(_IIS_NATIVE_DLL)] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "We carefully control this method's sole caller.")] internal static extern int MgdAcceptWebSocket( IntPtr pHandler); [DllImport(_IIS_NATIVE_DLL)] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "We carefully control this method's sole caller.")] internal static extern int MgdGetWebSocketContext( IntPtr pHandler, out IntPtr ppWebSocketContext); [DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)] internal static extern int MgdGetAnonymousUserToken( IntPtr pHandler, out IntPtr pToken ); [DllImport(_IIS_NATIVE_DLL)] internal static extern void MgdGetIISVersionInformation( [Out] out uint pdwVersion, [Out] out bool pfIsIntegratedMode); [DllImport(_IIS_NATIVE_DLL)] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "We carefully control this method's callers.")] internal static extern int MgdConfigureAsyncDisconnectNotification( [In] IntPtr pHandler, [In] bool fEnable, [Out] out bool pfIsClientConnected); [DllImport(_IIS_NATIVE_DLL)] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "We carefully control this method's callers.")] internal static extern int MgdGetIsChildContext( [In] IntPtr pHandler, [Out] out bool pfIsChildContext); [DllImport(_IIS_NATIVE_DLL)] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "We carefully control this method's callers.")] internal static extern int MgdGetConfigProperty( [In, MarshalAs(UnmanagedType.BStr)] string appConfigMetabasePath, [In, MarshalAs(UnmanagedType.BStr)] string sectionName, [In, MarshalAs(UnmanagedType.BStr)] string propertyName, [Out, MarshalAs(UnmanagedType.Struct)] out object value); // marshaled as VARIANT [DllImport(_IIS_NATIVE_DLL)] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "We carefully control this method's callers.")] internal static extern int MgdPushPromise( [In] IntPtr context, [In, MarshalAs(UnmanagedType.LPWStr)] string path, [In, MarshalAs(UnmanagedType.LPWStr)] string queryString, [In, MarshalAs(UnmanagedType.LPStr)] string method, [In] int numHeaders, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPStr)] string[] headersNames, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr)] string[] headersValues); [DllImport(_IIS_NATIVE_DLL)] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "We carefully control this method's callers.")] internal static extern bool MgdIsAppPoolShuttingDown(); [DllImport(_IIS_NATIVE_DLL)] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "We carefully control this method's callers.")] internal static extern int MgdGetTlsTokenBindingIdentifiers( [In] IntPtr pHandler, [In, Out] ref IntPtr tokenBindingHandle, [Out] out IntPtr providedTokenIdentifier, [Out] out uint providedTokenIdentifierSize, [Out] out IntPtr referredTokenIdentifier, [Out] out uint referredTokenIdentifierSize); } }
using UnityEngine; using Pathfinding; using Pathfinding.Serialization; namespace Pathfinding { public class PointNode : GraphNode { public GraphNode[] connections; public uint[] connectionCosts; /** GameObject this node was created from (if any). * \warning When loading a graph from a saved file or from cache, this field will be null. */ public GameObject gameObject; /** Used for internal linked list structure. * \warning Do not modify */ public PointNode next; //public override Int3 Position {get { return position; } } public void SetPosition (Int3 value) { position = value; } public PointNode (AstarPath astar) : base (astar) { } public override void GetConnections (GraphNodeDelegate del) { if (connections == null) return; for (int i=0;i<connections.Length;i++) del (connections[i]); } public override void ClearConnections (bool alsoReverse) { if (alsoReverse && connections != null) { for (int i=0;i<connections.Length;i++) { connections[i].RemoveConnection (this); } } connections = null; connectionCosts = null; } public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) { UpdateG (path,pathNode); handler.PushNode (pathNode); for (int i=0;i<connections.Length;i++) { GraphNode other = connections[i]; PathNode otherPN = handler.GetPathNode (other); if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) { other.UpdateRecursiveG (path, otherPN,handler); } } } public override bool ContainsConnection (GraphNode node) { for (int i=0;i<connections.Length;i++) if (connections[i] == node) return true; return false; } /** Add a connection from this node to the specified node. * If the connection already exists, the cost will simply be updated and * no extra connection added. * * \note Only adds a one-way connection. Consider calling the same function on the other node * to get a two-way connection. */ public override void AddConnection (GraphNode node, uint cost) { if (connections != null) { for (int i=0;i<connections.Length;i++) { if (connections[i] == node) { connectionCosts[i] = cost; return; } } } int connLength = connections != null ? connections.Length : 0; GraphNode[] newconns = new GraphNode[connLength+1]; uint[] newconncosts = new uint[connLength+1]; for (int i=0;i<connLength;i++) { newconns[i] = connections[i]; newconncosts[i] = connectionCosts[i]; } newconns[connLength] = node; newconncosts[connLength] = cost; connections = newconns; connectionCosts = newconncosts; } /** Removes any connection from this node to the specified node. * If no such connection exists, nothing will be done. * * \note This only removes the connection from this node to the other node. * You may want to call the same function on the other node to remove its eventual connection * to this node. */ public override void RemoveConnection (GraphNode node) { if (connections == null) return; for (int i=0;i<connections.Length;i++) { if (connections[i] == node) { int connLength = connections.Length; GraphNode[] newconns = new GraphNode[connLength-1]; uint[] newconncosts = new uint[connLength-1]; for (int j=0;j<i;j++) { newconns[j] = connections[j]; newconncosts[j] = connectionCosts[j]; } for (int j=i+1;j<connLength;j++) { newconns[j-1] = connections[j]; newconncosts[j-1] = connectionCosts[j]; } connections = newconns; connectionCosts = newconncosts; return; } } } public override void Open (Path path, PathNode pathNode, PathHandler handler) { if (connections == null) return; for (int i=0;i<connections.Length;i++) { GraphNode other = connections[i]; if (path.CanTraverse (other)) { PathNode pathOther = handler.GetPathNode (other); if (pathOther.pathID != handler.PathID) { pathOther.parent = pathNode; pathOther.pathID = handler.PathID; pathOther.cost = connectionCosts[i]; pathOther.H = path.CalculateHScore (other); other.UpdateG (path, pathOther); handler.PushNode (pathOther); } else { //If not we can test if the path from this node to the other one is a better one then the one already used uint tmpCost = connectionCosts[i]; if (pathNode.G + tmpCost + path.GetTraversalCost(other) < pathOther.G) { pathOther.cost = tmpCost; pathOther.parent = pathNode; other.UpdateRecursiveG (path, pathOther,handler); //handler.PushNode (pathOther); } else if (pathOther.G+tmpCost+path.GetTraversalCost(this) < pathNode.G && other.ContainsConnection (this)) { //Or if the path from the other node to this one is better pathNode.parent = pathOther; pathNode.cost = tmpCost; UpdateRecursiveG (path, pathNode,handler); //handler.PushNode (pathNode); } } } } } public override void SerializeNode (GraphSerializationContext ctx) { base.SerializeNode (ctx); ctx.writer.Write (position.x); ctx.writer.Write (position.y); ctx.writer.Write (position.z); } public override void DeserializeNode (GraphSerializationContext ctx) { base.DeserializeNode (ctx); position = new Int3 (ctx.reader.ReadInt32(), ctx.reader.ReadInt32(), ctx.reader.ReadInt32()); } public override void SerializeReferences (GraphSerializationContext ctx) { if (connections == null) { ctx.writer.Write(-1); } else { ctx.writer.Write (connections.Length); for (int i=0;i<connections.Length;i++) { ctx.writer.Write (ctx.GetNodeIdentifier (connections[i])); ctx.writer.Write (connectionCosts[i]); } } } public override void DeserializeReferences (GraphSerializationContext ctx) { int count = ctx.reader.ReadInt32(); if (count == -1) { connections = null; connectionCosts = null; } else { connections = new GraphNode[count]; connectionCosts = new uint[count]; for (int i=0;i<count;i++) { connections[i] = ctx.GetNodeFromIdentifier (ctx.reader.ReadInt32()); connectionCosts[i] = ctx.reader.ReadUInt32(); } } } } }
// Copyright 2007-2017 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 MassTransit { using System; using System.Collections.Generic; using System.Linq; using Configurators; using GreenPipes; using GreenPipes.Configurators; using GreenPipes.Observers; using GreenPipes.Policies; using GreenPipes.Policies.ExceptionFilters; using GreenPipes.Specifications; public static class Retry { static readonly IExceptionFilter _all = new AllExceptionFilter(); /// <summary> /// Create a policy that does not retry any messages /// </summary> public static IRetryPolicy None { get; } = new NoRetryPolicy(new AllExceptionFilter()); /// <summary> /// Create an immediate retry policy with the specified number of retries, with no /// delay between attempts. /// </summary> /// <param name="retryLimit">The number of retries to attempt</param> /// <returns></returns> public static IRetryPolicy Immediate(int retryLimit) { return new ImmediateRetryPolicy(All(), retryLimit); } /// <summary> /// Create an immediate retry policy with the specified number of retries, with no /// delay between attempts. /// </summary> /// <param name="filter"></param> /// <param name="retryLimit">The number of retries to attempt</param> /// <returns></returns> public static IRetryPolicy Immediate(this IExceptionFilter filter, int retryLimit) { return new ImmediateRetryPolicy(filter, retryLimit); } /// <summary> /// Create an interval retry policy with the specified intervals. The retry count equals /// the number of intervals provided /// </summary> /// <param name="intervals">The intervals before each subsequent retry attempt</param> /// <returns></returns> public static IRetryPolicy Intervals(params TimeSpan[] intervals) { return new IntervalRetryPolicy(All(), intervals); } /// <summary> /// Create an interval retry policy with the specified intervals. The retry count equals /// the number of intervals provided /// </summary> /// <param name="filter"></param> /// <param name="intervals">The intervals before each subsequent retry attempt</param> /// <returns></returns> public static IRetryPolicy Intervals(this IExceptionFilter filter, params TimeSpan[] intervals) { return new IntervalRetryPolicy(filter, intervals); } /// <summary> /// Create an interval retry policy with the specified intervals. The retry count equals /// the number of intervals provided /// </summary> /// <param name="intervals">The intervals before each subsequent retry attempt</param> /// <returns></returns> public static IRetryPolicy Intervals(params int[] intervals) { return new IntervalRetryPolicy(All(), intervals); } /// <summary> /// Create an interval retry policy with the specified intervals. The retry count equals /// the number of intervals provided /// </summary> /// <param name="filter"></param> /// <param name="intervals">The intervals before each subsequent retry attempt</param> /// <returns></returns> public static IRetryPolicy Intervals(this IExceptionFilter filter, params int[] intervals) { return new IntervalRetryPolicy(filter, intervals); } /// <summary> /// Create an interval retry policy with the specified number of retries at a fixed interval /// </summary> /// <param name="retryCount">The number of retry attempts</param> /// <param name="interval">The interval between each retry attempt</param> /// <returns></returns> public static IRetryPolicy Interval(int retryCount, TimeSpan interval) { return new IntervalRetryPolicy(All(), Enumerable.Repeat(interval, retryCount).ToArray()); } /// <summary> /// Create an interval retry policy with the specified number of retries at a fixed interval /// </summary> /// <param name="retryCount">The number of retry attempts</param> /// <param name="interval">The interval between each retry attempt</param> /// <returns></returns> public static IRetryPolicy Interval(int retryCount, int interval) { return new IntervalRetryPolicy(All(), Enumerable.Repeat(interval, retryCount).ToArray()); } /// <summary> /// Create an interval retry policy with the specified number of retries at a fixed interval /// </summary> /// <param name="filter"></param> /// <param name="retryCount">The number of retry attempts</param> /// <param name="interval">The interval between each retry attempt</param> /// <returns></returns> public static IRetryPolicy Interval(this IExceptionFilter filter, int retryCount, TimeSpan interval) { return new IntervalRetryPolicy(filter, Enumerable.Repeat(interval, retryCount).ToArray()); } /// <summary> /// Create an exponential retry policy with the specified number of retries at exponential /// intervals /// </summary> /// <param name="retryLimit"></param> /// <param name="minInterval"></param> /// <param name="maxInterval"></param> /// <param name="intervalDelta"></param> /// <returns></returns> public static IRetryPolicy Exponential(int retryLimit, TimeSpan minInterval, TimeSpan maxInterval, TimeSpan intervalDelta) { return new ExponentialRetryPolicy(All(), retryLimit, minInterval, maxInterval, intervalDelta); } /// <summary> /// Create an exponential retry policy that never gives up /// intervals /// </summary> /// <param name="minInterval"></param> /// <param name="maxInterval"></param> /// <param name="intervalDelta"></param> /// <returns></returns> public static IRetryPolicy Exponential(TimeSpan minInterval, TimeSpan maxInterval, TimeSpan intervalDelta) { return new ExponentialRetryPolicy(All(), int.MaxValue, minInterval, maxInterval, intervalDelta); } /// <summary> /// Create an exponential retry policy with the specified number of retries at exponential /// intervals /// </summary> /// <param name="filter"></param> /// <param name="retryLimit"></param> /// <param name="minInterval"></param> /// <param name="maxInterval"></param> /// <param name="intervalDelta"></param> /// <returns></returns> public static IRetryPolicy Exponential(this IExceptionFilter filter, int retryLimit, TimeSpan minInterval, TimeSpan maxInterval, TimeSpan intervalDelta) { return new ExponentialRetryPolicy(filter, retryLimit, minInterval, maxInterval, intervalDelta); } /// <summary> /// Create an incremental retry policy with the specified number of retry attempts with an incrementing /// interval between retries /// </summary> /// <param name="retryLimit">The number of retry attempts</param> /// <param name="initialInterval">The initial retry interval</param> /// <param name="intervalIncrement">The interval to add to the retry interval with each subsequent retry</param> /// <returns></returns> public static IRetryPolicy Incremental(int retryLimit, TimeSpan initialInterval, TimeSpan intervalIncrement) { return new IncrementalRetryPolicy(All(), retryLimit, initialInterval, intervalIncrement); } /// <summary> /// Create an incremental retry policy with the specified number of retry attempts with an incrementing /// interval between retries /// </summary> /// <param name="filter"></param> /// <param name="retryLimit">The number of retry attempts</param> /// <param name="initialInterval">The initial retry interval</param> /// <param name="intervalIncrement">The interval to add to the retry interval with each subsequent retry</param> /// <returns></returns> public static IRetryPolicy Incremental(this IExceptionFilter filter, int retryLimit, TimeSpan initialInterval, TimeSpan intervalIncrement) { return new IncrementalRetryPolicy(filter, retryLimit, initialInterval, intervalIncrement); } public static IRetryPolicy CreatePolicy(Action<IRetryConfigurator> configure) { var configurator = new RetryConfigurator(); configure(configurator); return configurator.Build(); } /// <summary> /// Retry all exceptions except for the exception types specified /// </summary> /// <param name="exceptionTypes"></param> /// <returns></returns> public static IExceptionFilter Except(params Type[] exceptionTypes) { return new IgnoreExceptionFilter(exceptionTypes); } /// <summary> /// Retry all exceptions except for the exception types specified /// </summary> /// <returns></returns> public static IExceptionFilter Except<T1>() { return new IgnoreExceptionFilter(typeof(T1)); } /// <summary> /// Retry all exceptions except for the exception types specified /// </summary> /// <returns></returns> public static IExceptionFilter Except<T1, T2>() { return new IgnoreExceptionFilter(typeof(T1), typeof(T2)); } /// <summary> /// Retry all exceptions except for the exception types specified /// </summary> /// <returns></returns> public static IExceptionFilter Except<T1, T2, T3>() { return new IgnoreExceptionFilter(typeof(T1), typeof(T2), typeof(T3)); } /// <summary> /// Retry only the exception types specified /// </summary> /// <param name="exceptionTypes"></param> /// <returns></returns> public static IExceptionFilter Selected(params Type[] exceptionTypes) { return new HandleExceptionFilter(exceptionTypes); } /// <summary> /// Retry only the exception types specified /// </summary> /// <returns></returns> public static IExceptionFilter Selected<T1>() { return new HandleExceptionFilter(typeof(T1)); } /// <summary> /// Retry only the exception types specified /// </summary> /// <returns></returns> public static IExceptionFilter Selected<T1, T2>() { return new HandleExceptionFilter(typeof(T1), typeof(T2)); } /// <summary> /// Retry only the exception types specified /// </summary> /// <returns></returns> public static IExceptionFilter Selected<T1, T2, T3>() { return new HandleExceptionFilter(typeof(T1), typeof(T2), typeof(T3)); } /// <summary> /// Retry all exceptions /// </summary> /// <returns></returns> public static IExceptionFilter All() { return _all; } /// <summary> /// Filter an exception type /// </summary> /// <typeparam name="T">The exception type</typeparam> /// <param name="filter">The filter expression</param> /// <returns>True if the exception should be retried, otherwise false</returns> public static IExceptionFilter Filter<T>(Func<T, bool> filter) where T : Exception { return new FilterExceptionFilter<T>(filter); } class RetryConfigurator : ExceptionSpecification, IRetryConfigurator, ISpecification { readonly RetryObservable _observers; RetryPolicyFactory _policyFactory; public RetryConfigurator() { _observers = new RetryObservable(); } public void SetRetryPolicy(RetryPolicyFactory factory) { _policyFactory = factory; } ConnectHandle IRetryObserverConnector.ConnectRetryObserver(IRetryObserver observer) { return _observers.Connect(observer); } public IEnumerable<ValidationResult> Validate() { if (_policyFactory == null) yield return this.Failure("RetryPolicy", "must not be null"); } public IRetryPolicy Build() { var result = RetryConfigurationResult.CompileResults(Validate()); try { return _policyFactory(Filter); } catch (Exception ex) { throw new ConfigurationException(result, "An exception occurred during retry policy creation", ex); } } } } }
/* Copyright (c) 2016 Denis Zykov, GameDevWare.com This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. This source code is distributed via Unity Asset Store, to use it in your project you should accept Terms of Service and EULA https://unity3d.com/ru/legal/as_terms */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; // ReSharper disable once CheckNamespace namespace GameDevWare.Serialization.Metadata { internal static class GettersAndSetters { #if !NET_STANDARD_2_0 private static readonly bool AotRuntime; private static readonly Dictionary<MemberInfo, Func<object, object>> ReadFunctions; private static readonly Dictionary<MemberInfo, Action<object, object>> WriteFunctions; private static readonly Dictionary<MemberInfo, Func<object>> ConstructorFunctions; #endif #if !NET_STANDARD_2_0 static GettersAndSetters() { #if ((UNITY_WEBGL || UNITY_IOS || ENABLE_IL2CPP) && !UNITY_EDITOR) AotRuntime = true; #else try { Expression.Lambda<Func<bool>>(Expression.Constant(true)).Compile(); } catch (Exception) { AotRuntime = true; } #endif ReadFunctions = new Dictionary<MemberInfo, Func<object, object>>(); WriteFunctions = new Dictionary<MemberInfo, Action<object, object>>(); ConstructorFunctions = new Dictionary<MemberInfo, Func<object>>(); } #endif public static bool TryGetAssessors(MethodInfo getMethod, MethodInfo setMethod, out Func<object, object> getFn, out Action<object, object> setFn) { getFn = null; setFn = null; #if NET_STANDARD_2_0 return false; #else if (AotRuntime) return false; if (getMethod != null && !getMethod.IsStatic && getMethod.GetParameters().Length == 0) { lock (ReadFunctions) { if (ReadFunctions.TryGetValue(getMethod, out getFn) == false) { var instanceParam = Expression.Parameter(typeof(object), "instance"); var declaringType = getMethod.DeclaringType; Debug.Assert(declaringType != null, "getMethodDeclaringType != null"); getFn = Expression.Lambda<Func<object, object>>( Expression.Convert( Expression.Call( Expression.Convert(instanceParam, declaringType), getMethod), typeof(object)), instanceParam ).Compile(); ReadFunctions.Add(getMethod, getFn); } } } if (setMethod != null && !setMethod.IsStatic && setMethod.GetParameters().Length == 1 && setMethod.DeclaringType != null && setMethod.DeclaringType.IsValueType == false) { lock (WriteFunctions) { if (WriteFunctions.TryGetValue(setMethod, out setFn) == false) { var declaringType = setMethod.DeclaringType; var valueParameter = setMethod.GetParameters().Single(); Debug.Assert(declaringType != null, "getMethodDeclaringType != null"); var setDynamicMethod = new DynamicMethod(declaringType.FullName + "::" + setMethod.Name, typeof(void), new Type[] { typeof(object), typeof(object) }, restrictedSkipVisibility: true); var il = setDynamicMethod.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); // instance il.Emit(OpCodes.Castclass, declaringType); il.Emit(OpCodes.Ldarg_1); // value if (valueParameter.ParameterType.IsValueType) il.Emit(OpCodes.Unbox_Any, valueParameter.ParameterType); else il.Emit(OpCodes.Castclass, valueParameter.ParameterType); il.Emit(OpCodes.Callvirt, setMethod); // call instance.Set(value) il.Emit(OpCodes.Ret); setFn = (Action<object, object>)setDynamicMethod.CreateDelegate(typeof(Action<object, object>)); WriteFunctions.Add(setMethod, setFn); } } } return true; #endif } public static bool TryGetAssessors(FieldInfo fieldInfo, out Func<object, object> getFn, out Action<object, object> setFn) { getFn = null; setFn = null; #if NET_STANDARD_2_0 return false; #else if (AotRuntime || fieldInfo.IsStatic) return false; lock (ReadFunctions) { if (ReadFunctions.TryGetValue(fieldInfo, out getFn) == false) { var instanceParam = Expression.Parameter(typeof(object), "instance"); var declaringType = fieldInfo.DeclaringType; Debug.Assert(declaringType != null, "getMethodDeclaringType != null"); getFn = Expression.Lambda<Func<object, object>>( Expression.Convert( Expression.Field( Expression.Convert(instanceParam, declaringType), fieldInfo), typeof(object)), instanceParam ).Compile(); ReadFunctions.Add(fieldInfo, getFn); } } if (fieldInfo.IsInitOnly == false && fieldInfo.DeclaringType != null && fieldInfo.DeclaringType.IsValueType == false) { lock (WriteFunctions) { if (WriteFunctions.TryGetValue(fieldInfo, out setFn) == false) { var declaringType = fieldInfo.DeclaringType; var fieldType = fieldInfo.FieldType; Debug.Assert(declaringType != null, "getMethodDeclaringType != null"); var setDynamicMethod = new DynamicMethod(declaringType.FullName + "::" + fieldInfo.Name, typeof(void), new Type[] { typeof(object), typeof(object) }, restrictedSkipVisibility: true); var il = setDynamicMethod.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); // instance il.Emit(OpCodes.Castclass, declaringType); il.Emit(OpCodes.Ldarg_1); // value if (fieldType.IsValueType) il.Emit(OpCodes.Unbox_Any, fieldType); else il.Emit(OpCodes.Castclass, fieldType); il.Emit(OpCodes.Stfld, fieldInfo); // call instance.Set(value) il.Emit(OpCodes.Ret); setFn = (Action<object, object>)setDynamicMethod.CreateDelegate(typeof(Action<object, object>)); WriteFunctions.Add(fieldInfo, setFn); } } } return true; #endif } public static bool TryGetConstructor(Type type, out Func<object> ctrFn) { if (type == null) throw new ArgumentNullException("type"); ctrFn = null; #if NET_STANDARD_2_0 return false; #else if (AotRuntime || type.IsAbstract || type.IsInterface) return false; var defaultCtr = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault(ctr => ctr.GetParameters().Length == 0); if (defaultCtr == null) return false; lock (ConstructorFunctions) { if (ConstructorFunctions.TryGetValue(type, out ctrFn)) return true; ctrFn = Expression.Lambda<Func<object>>( Expression.Convert( Expression.New(defaultCtr), typeof(object)) ).Compile(); ConstructorFunctions.Add(type, ctrFn); } return true; #endif } } }
//----------------------------------------------------------------------- // <copyright company="Nuclei"> // Copyright 2013 Nuclei. Licensed under the Apache License, Version 2.0. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Security; namespace nRefs.Console.Nuclei.Fusion { /// <summary> /// Contains methods for assisting with the assembly loading process. /// </summary> /// <remarks> /// Note because these methods assist in the assembly loading process it /// is not possible to place this class in a separate assembly from the /// elements which need to provide assembly loading assistance. /// </remarks> /// <design> /// <para> /// The goal of the <c>FusionHelper</c> class is to provide a fallback for the /// assembly loading process. The <c>LocateAssemblyOnAssemblyLoadFailure</c> method /// is attached to the <c>AppDomain.AssemblyResolve</c> event. /// </para> /// <para> /// The <c>FusionHelper</c> searches through a set of directories or files for assembly files. /// The assembly files that are found are checked to see if they match with the requested /// assembly file. /// </para> /// <para> /// Note that this class is not threadsafe. This should however not be a problem because we /// provide the collections of directories and files before attaching the <c>FusionHelper</c> /// object to the <c>AppDomain.AssemblyResolve</c> event. Once attached the event will only /// be called from one thread. /// </para> /// </design> internal sealed class FusionHelper { /// <summary> /// The extension of an assembly. /// </summary> private const string AssemblyExtension = "dll"; /// <summary> /// Determines whether the assembly name fully qualified, i.e. contains the name, version, culture and public key. /// </summary> /// <param name="assemblyFullName">Full name of the assembly.</param> /// <returns> /// <see langword="true"/> if the assembly name is a fully qualified assembly name; otherwise, <see langword="false"/>. /// </returns> [SuppressMessage("Microsoft.StyleCop.CSharp.DocumentationRules", "SA1628:DocumentationTextMustBeginWithACapitalLetter", Justification = "Documentation can start with a language keyword")] private static bool IsAssemblyNameFullyQualified(string assemblyFullName) { Debug.Assert(!string.IsNullOrEmpty(assemblyFullName), "The assembly full name should not be empty."); // Assume that assembly file paths do not normally have commas in them return assemblyFullName.Contains(","); } /// <summary> /// Extracts the value from a key value pair which is embedded in the assembly full name. /// </summary> /// <param name="input">The input.</param> /// <returns> /// The value part of the key-value pair. /// </returns> private static string ExtractValueFromKeyValuePair(string input) { Debug.Assert(!string.IsNullOrEmpty(input), "The input should not be empty."); return input .Substring( input.IndexOf(AssemblyNameElements.KeyValueSeparator, StringComparison.OrdinalIgnoreCase) + AssemblyNameElements.KeyValueSeparator.Length) .Trim(); } /// <summary> /// Determines if the file at the specified <paramref name="filePath"/> is the assembly that the loader is /// looking for. /// </summary> /// <param name="filePath">The absolute file path to the file which might be the desired assembly.</param> /// <param name="fileName">The file name and extension for the desired assembly.</param> /// <param name="version">The version for the desired assembly.</param> /// <param name="culture">The culture for the desired assembly.</param> /// <param name="publicKey">The public key token for the desired assembly.</param> /// <returns> /// <see langword="true"/> if the filePath points to the desired assembly; otherwise <see langword="false"/>. /// </returns> [SuppressMessage("Microsoft.StyleCop.CSharp.DocumentationRules", "SA1628:DocumentationTextMustBeginWithACapitalLetter", Justification = "Documentation can start with a language keyword")] private static bool IsFileTheDesiredAssembly(string filePath, string fileName, string version, string culture, string publicKey) { Debug.Assert(!string.IsNullOrEmpty(filePath), "The assembly file path should not be empty."); if (!Path.GetFileName(filePath).Equals(fileName, StringComparison.CurrentCultureIgnoreCase)) { return false; } if ((!string.IsNullOrEmpty(version)) || (!string.IsNullOrEmpty(culture)) || (!string.IsNullOrEmpty(publicKey))) { AssemblyName assemblyName; try { // Load the assembly name but without loading the assembly file into the AppDomain. assemblyName = AssemblyName.GetAssemblyName(filePath); } catch (ArgumentException) { // filePath is invalid, e.g. an assembly with an invalid culture. return false; } catch (FileNotFoundException) { // filePath doesn't point to a valid file or doesn't exist return false; } catch (SecurityException) { // The caller doesn't have discovery permission for the given path return false; } catch (BadImageFormatException) { // The file is not a valid assembly file return false; } catch (FileLoadException) { // the file was already loaded but with a different set of evidence return false; } if (!string.IsNullOrEmpty(version)) { var expectedVersion = new Version(version); if (!expectedVersion.Equals(assemblyName.Version)) { return false; } } if (!string.IsNullOrEmpty(culture)) { // The 'Neutral' culture is actually the invariant culture. This is the culture an // assembly gets if no culture was specified so... if (culture.Equals(AssemblyNameElements.InvariantCulture, StringComparison.OrdinalIgnoreCase)) { culture = string.Empty; } var expectedCulture = new CultureInfo(culture); if (!expectedCulture.Equals(assemblyName.CultureInfo)) { return false; } } if ((!string.IsNullOrEmpty(publicKey)) && (!publicKey.Equals(AssemblyNameElements.NullString, StringComparison.OrdinalIgnoreCase))) { var actualPublicKeyToken = assemblyName.GetPublicKeyToken(); var str = actualPublicKeyToken.Aggregate( string.Empty, (current, value) => current + value.ToString("x2", CultureInfo.InvariantCulture)); return str.Equals(publicKey, StringComparison.OrdinalIgnoreCase); } } return true; } /// <summary> /// The delegate which is used to return a file enumerator based on a specific directory. /// </summary> private readonly Func<IEnumerable<string>> m_FileEnumerator; /// <summary> /// The delegate which is used to load an assembly from a specific file path. /// </summary> private Func<string, Assembly> m_AssemblyLoader; /// <summary> /// Initializes a new instance of the <see cref="FusionHelper"/> class. /// </summary> /// <param name="fileEnumerator">The enumerator which returns all the files that are potentially of interest.</param> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="fileEnumerator"/> is <see langword="null" />. /// </exception> public FusionHelper(Func<IEnumerable<string>> fileEnumerator) { { Lokad.Enforce.Argument(() => fileEnumerator); } m_FileEnumerator = fileEnumerator; } /// <summary> /// Gets the file enumerator which is used to enumerate the files in a specific directory. /// </summary> private Func<IEnumerable<string>> FileEnumerator { get { return m_FileEnumerator; } } /// <summary> /// Gets or sets the assembly loader which is used to load assemblies from a specific path. /// </summary> /// <todo> /// The assembly loader should also deal with NGEN-ed assemblies. This means that using /// Assembly.LoadFrom is not the best choice. /// </todo> internal Func<string, Assembly> AssemblyLoader { private get { return m_AssemblyLoader ?? (m_AssemblyLoader = path => Assembly.LoadFrom(path)); } set { m_AssemblyLoader = value; } } /// <summary> /// An event handler which is invoked when the search for an assembly fails. /// </summary> /// <param name="sender">The object which raised the event.</param> /// <param name="args"> /// The <see cref="System.ResolveEventArgs"/> instance containing the event data. /// </param> /// <returns> /// An assembly reference if the required assembly can be found; otherwise <see langword="null"/>. /// </returns> public Assembly LocateAssemblyOnAssemblyLoadFailure(object sender, ResolveEventArgs args) { return LocateAssembly(args.Name); } /// <summary> /// Tries to locate the assembly specified by the assembly name. /// </summary> /// <param name="assemblyFullName">Full name of the assembly.</param> /// <returns> /// The desired assembly if is is in the search path; otherwise, <see langword="null"/>. /// </returns> private Assembly LocateAssembly(string assemblyFullName) { Debug.Assert(assemblyFullName != null, "Expected a non-null assembly name string."); Debug.Assert(assemblyFullName.Length != 0, "Expected a non-empty assembly name string."); // @todo: We should be able to use an AssemblyName because we can just load it from a string. // It is not possible to use the AssemblyName class because that attempts to load the // assembly. Obviously we are currently trying to find the assembly. // So parse the actual assembly name from the name string // // First check if we have been passed a fully qualified name or only a module name string fileName = assemblyFullName; string version = string.Empty; string culture = string.Empty; string publicKey = string.Empty; if (IsAssemblyNameFullyQualified(assemblyFullName)) { // Split the assembly name out into different parts. The name // normally consists of: // - File name // - Version // - Culture // - PublicKeyToken // e.g.: mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 var nameSections = assemblyFullName.Split(','); Debug.Assert(nameSections.Length == 4, "There should be 4 sections in the assembly name."); fileName = nameSections[0].Trim(); version = ExtractValueFromKeyValuePair(nameSections[1]); culture = ExtractValueFromKeyValuePair(nameSections[2]); publicKey = ExtractValueFromKeyValuePair(nameSections[3]); } // If the file name already has the '.dll' extension then we don't need to add that, otherwise we do fileName = MakeModuleNameQualifiedFileName(fileName); var files = FileEnumerator(); var match = (from filePath in files where IsFileTheDesiredAssembly(filePath, fileName, version, culture, publicKey) select filePath) .FirstOrDefault(); if (match != null) { return AssemblyLoader(match); } return null; } /// <summary> /// Turns the module name into a qualified file name by adding the default assembly extension. /// </summary> /// <param name="moduleName">Name of the module.</param> /// <returns> /// The expected name of the assembly file that contains the module. /// </returns> private string MakeModuleNameQualifiedFileName(string moduleName) { Debug.Assert(!string.IsNullOrEmpty(moduleName), "The assembly file name should not be empty."); return (moduleName.IndexOf( string.Format( CultureInfo.InvariantCulture, ".{0}", AssemblyExtension), StringComparison.OrdinalIgnoreCase) < 0) ? string.Format(CultureInfo.InvariantCulture, "{0}.{1}", moduleName, AssemblyExtension) : moduleName; } } }
/* MIT License Copyright (c) 2017 Saied Zarrinmehr 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.Linq; using System.Text; using SpatialAnalysis.Agents.Visualization.AgentModel; using SpatialAnalysis.Geometry; using SpatialAnalysis.Data; using MathNet.Numerics.Distributions; using SpatialAnalysis.CellularEnvironment; namespace SpatialAnalysis.Agents.OptionalScenario { /// <summary> /// Class FreeNavigationAgent is a simple data model and does offer functionalities. /// </summary> public class FreeNavigationAgent: IAgent { /// <summary> /// Creates the specified current state. /// </summary> /// <param name="currentState">State of the current.</param> /// <returns>FreeNavigationAgent.</returns> public static FreeNavigationAgent Create(StateBase currentState) { FreeNavigationAgent agent = new FreeNavigationAgent { VisibilityCosineFactor = Math.Cos(Parameter.DefaultParameters[AgentParameters.GEN_VisibilityAngle].Value / 2), DecisionMakingPeriod = Parameter.DefaultParameters[AgentParameters.OPT_DecisionMakingPeriodLambdaFactor].Value, WalkTime = 0.0d, AngleDistributionLambdaFactor = Parameter.DefaultParameters[AgentParameters.OPT_AngleDistributionLambdaFactor].Value, DesirabilityDistributionLambdaFactor = Parameter.DefaultParameters[AgentParameters.OPT_DesirabilityDistributionLambdaFactor].Value, AngularVelocity = Parameter.DefaultParameters[AgentParameters.GEN_AngularVelocity].Value, BodySize = Parameter.DefaultParameters[AgentParameters.GEN_BodySize].Value, VelocityMagnitude = Parameter.DefaultParameters[AgentParameters.GEN_VelocityMagnitude].Value, CurrentState = currentState, Destination = null, VisibilityAngle = Parameter.DefaultParameters[AgentParameters.GEN_VisibilityAngle].Value, DecisionMakingPeriodLambdaFactor = Parameter.DefaultParameters[AgentParameters.OPT_DecisionMakingPeriodLambdaFactor].Value, DecisionMakingPeriodDistribution = new Exponential(1.0d / Parameter.DefaultParameters[AgentParameters.OPT_DecisionMakingPeriodLambdaFactor].Value), BodyElasticity = Parameter.DefaultParameters[AgentParameters.GEN_AgentBodyElasticity].Value, AccelerationMagnitude = Parameter.DefaultParameters[AgentParameters.GEN_AccelerationMagnitude].Value, BarrierFriction = Parameter.DefaultParameters[AgentParameters.GEN_BarrierFriction].Value, BarrierRepulsionRange = Parameter.DefaultParameters[AgentParameters.GEN_BarrierRepulsionRange].Value, RepulsionChangeRate = Parameter.DefaultParameters[AgentParameters.GEN_MaximumRepulsion].Value, EdgeCollisionState= null, TimeStep =0.0d, }; return agent; } private double _decisionMakingPeriodLambdaFactor; /// <summary> /// Gets or sets the decision making period lambda factor. /// </summary> /// <value>The decision making period lambda factor.</value> public double DecisionMakingPeriodLambdaFactor { get { return _decisionMakingPeriodLambdaFactor; } set { if (_decisionMakingPeriodLambdaFactor != value) { _decisionMakingPeriodLambdaFactor = value; this.DecisionMakingPeriodDistribution = new Exponential(1.0d / this._decisionMakingPeriodLambdaFactor); } } } /// <summary> /// Gets or sets the body elasticity. /// </summary> /// <value>The body elasticity.</value> public double BodyElasticity { get; set; } /// <summary> /// Gets or sets the barrier friction. /// </summary> /// <value>The barrier friction.</value> public double BarrierFriction { get; set; } /// <summary> /// Gets or sets the time-step. /// </summary> /// <value>The time step.</value> public double TimeStep { get; set; } /// <summary> /// The barrier repulsion range /// </summary> public double BarrierRepulsionRange; /// <summary> /// The repulsion change rate /// </summary> public double RepulsionChangeRate; /// <summary> /// The acceleration magnitude /// </summary> public double AccelerationMagnitude; /// <summary> /// The destination /// </summary> public UV Destination; /// <summary> /// The edge collision state /// </summary> public CollisionAnalyzer EdgeCollisionState; /// <summary> /// Gets or sets the decision making period distribution. /// </summary> /// <value>The decision making period distribution.</value> public Exponential DecisionMakingPeriodDistribution { get; set; } /// <summary> /// Gets or sets the angle distribution lambda factor. /// </summary> /// <value>The angle distribution lambda factor.</value> public double AngleDistributionLambdaFactor { get; set; } /// <summary> /// Gets or sets the desirability distribution lambda factor. /// </summary> /// <value>The desirability distribution lambda factor.</value> public double DesirabilityDistributionLambdaFactor { get; set; } /// <summary> /// Gets or sets the visibility cosine factor. /// </summary> /// <value>The visibility cosine factor.</value> public double VisibilityCosineFactor { get; set; } /// <summary> /// Gets or sets the decision making period. /// </summary> /// <value>The decision making period.</value> public double DecisionMakingPeriod { get; set; } /// <summary> /// Gets or sets the walk time. /// </summary> /// <value>The walk time.</value> public double WalkTime { get; set; } /// <summary> /// Gets or sets the angular velocity. /// </summary> /// <value>The angular velocity.</value> public double AngularVelocity { get; set; } /// <summary> /// Gets or sets the size of the body. /// </summary> /// <value>The size of the body.</value> public double BodySize { get; set; } /// <summary> /// Gets or sets the velocity magnitude. /// </summary> /// <value>The velocity magnitude.</value> public double VelocityMagnitude { get; set; } /// <summary> /// Gets or sets the current state of the agent. /// </summary> /// <value>The state of the current.</value> public StateBase CurrentState { get; set; } /// <summary> /// Gets or sets the visibility angle. /// </summary> /// <value>The visibility angle.</value> public double VisibilityAngle { get; set; } /// <summary> /// Initializes a new instance of the <see cref="FreeNavigationAgent"/> class. /// </summary> public FreeNavigationAgent() { } public static bool operator ==(FreeNavigationAgent a, FreeNavigationAgent b) { if ((object)a == null || (object)b == null) { return false; } bool result = a.AngularVelocity == b.AngularVelocity && a.CurrentState.Equals(b.CurrentState) && a.DecisionMakingPeriod == b.DecisionMakingPeriod && a.BodySize == b.BodySize && a.VelocityMagnitude == b.VelocityMagnitude && a.VisibilityAngle == b.VisibilityAngle && a.VisibilityCosineFactor == b.VisibilityCosineFactor && a.WalkTime == b.WalkTime && a.DesirabilityDistributionLambdaFactor == b.DesirabilityDistributionLambdaFactor && a.BodyElasticity == b.BodyElasticity && a.BodySize == b.BodySize && a.AccelerationMagnitude == b.AccelerationMagnitude && a.BarrierFriction == b.BarrierFriction && a.BarrierRepulsionRange == b.BarrierRepulsionRange && a.RepulsionChangeRate == b.RepulsionChangeRate && a.AngleDistributionLambdaFactor == b.AngleDistributionLambdaFactor; return result; } public static bool operator !=(FreeNavigationAgent a, FreeNavigationAgent b) { return !(a == b); } /// <summary> /// Copies this instance deeply. /// </summary> /// <returns>FreeNavigationAgent.</returns> public FreeNavigationAgent Copy() { FreeNavigationAgent copied = new FreeNavigationAgent() { AngleDistributionLambdaFactor = this.AngleDistributionLambdaFactor, AngularVelocity = this.AngularVelocity, DesirabilityDistributionLambdaFactor = this.DesirabilityDistributionLambdaFactor, CurrentState= this.CurrentState, DecisionMakingPeriod = this.DecisionMakingPeriod, BodySize = this.BodySize, VelocityMagnitude = this.VelocityMagnitude, VisibilityAngle = this.VisibilityAngle, VisibilityCosineFactor = this.VisibilityCosineFactor, WalkTime = this.WalkTime, RepulsionChangeRate = this.RepulsionChangeRate, BarrierRepulsionRange = this.BarrierRepulsionRange, BarrierFriction = this.BarrierFriction, AccelerationMagnitude = this.AccelerationMagnitude, BodyElasticity = this.BodyElasticity, }; return copied; } /// <summary> /// Gets or sets the barrier repulsion range. /// </summary> /// <value>The barrier repulsion range.</value> /// <exception cref="System.NotImplementedException"> /// </exception> double IAgent.BarrierRepulsionRange { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// Gets or sets the repulsion change rate. /// </summary> /// <value>The repulsion change rate.</value> /// <exception cref="System.NotImplementedException"> /// </exception> double IAgent.RepulsionChangeRate { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// Gets or sets the acceleration magnitude. /// </summary> /// <value>The acceleration magnitude.</value> /// <exception cref="System.NotImplementedException"> /// </exception> double IAgent.AccelerationMagnitude { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// Gets or sets the total walk time. /// </summary> /// <value>The total walk time.</value> /// <exception cref="System.NotImplementedException"> /// </exception> public double TotalWalkTime { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// Gets or sets the total walked length. /// </summary> /// <value>The total length of the walked.</value> /// <exception cref="System.NotImplementedException"> /// </exception> public double TotalWalkedLength { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// Gets or sets the state of the edge collision. /// </summary> /// <value>The state of the edge collision.</value> /// <exception cref="System.NotImplementedException"> /// </exception> CollisionAnalyzer IAgent.EdgeCollisionState { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// Updates the time-step. /// </summary> /// <exception cref="System.NotImplementedException"></exception> public void TimeStepUpdate() { throw new NotImplementedException(); } /// <summary> /// Loads the repulsion vector's magnitude. /// </summary> /// <returns>System.Double.</returns> /// <exception cref="System.NotImplementedException"></exception> public double LoadRepulsionMagnitude() { throw new NotImplementedException(); } } }
using System; using NUnit.Framework; using NServiceKit.Common.Tests.Models; namespace NServiceKit.OrmLite.FirebirdTests { /// <summary>An ORM lite create table with namig strategy tests.</summary> [TestFixture] public class OrmLiteCreateTableWithNamigStrategyTests : OrmLiteTestBase { /// <summary>Can create table with namig strategy table name underscore coumpound.</summary> [Test] public void Can_create_TableWithNamigStrategy_table_nameUnderscoreCoumpound() { OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = new UnderscoreSeparatedCompoundNamingStrategy(); using (var db = new OrmLiteConnectionFactory(ConnectionString, FirebirdDialect.Provider).Open()) { db.CreateTable<ModelWithOnlyStringFields>(true); } OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase(); } /// <summary>Can get data from table with namig strategy with get by identifier.</summary> [Test] public void Can_get_data_from_TableWithNamigStrategy_with_GetById() { OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = new PrefixNamingStrategy { TablePrefix = "tab_", ColumnPrefix = "col_", }; using (var db = new OrmLiteConnectionFactory(ConnectionString, FirebirdDialect.Provider).Open()) { db.CreateTable<ModelWithOnlyStringFields>(true); ModelWithOnlyStringFields m = new ModelWithOnlyStringFields() { Id= "999", AlbumId = "112", AlbumName="ElectroShip", Name = "MyNameIsBatman"}; db.Save<ModelWithOnlyStringFields>(m); var modelFromDb = db.GetById<ModelWithOnlyStringFields>("999"); Assert.AreEqual(m.Name, modelFromDb.Name); } OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase(); } /// <summary>Can get data from table with namig strategy with query by example.</summary> [Test] public void Can_get_data_from_TableWithNamigStrategy_with_query_by_example() { OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = new PrefixNamingStrategy { TablePrefix = "tab_", ColumnPrefix = "col_", }; using (var db = new OrmLiteConnectionFactory(ConnectionString, FirebirdDialect.Provider).Open()) { db.CreateTable<ModelWithOnlyStringFields>(true); ModelWithOnlyStringFields m = new ModelWithOnlyStringFields() { Id = "998", AlbumId = "112", AlbumName = "ElectroShip", Name = "QueryByExample" }; db.Save<ModelWithOnlyStringFields>(m); var modelFromDb = db.Where<ModelWithOnlyStringFields>(new { Name = "QueryByExample" })[0]; Assert.AreEqual(m.Name, modelFromDb.Name); } OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase(); } /// <summary> /// Can get data from table with namig strategy after changing naming strategy. /// </summary> [Test] public void Can_get_data_from_TableWithNamigStrategy_AfterChangingNamingStrategy() { OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = new PrefixNamingStrategy { TablePrefix = "tab_", ColumnPrefix = "col_", }; using (var db = new OrmLiteConnectionFactory(ConnectionString, FirebirdDialect.Provider).Open()) { db.CreateTable<ModelWithOnlyStringFields>(true); ModelWithOnlyStringFields m = new ModelWithOnlyStringFields() { Id = "998", AlbumId = "112", AlbumName = "ElectroShip", Name = "QueryByExample" }; db.Save<ModelWithOnlyStringFields>(m); var modelFromDb = db.Where<ModelWithOnlyStringFields>(new { Name = "QueryByExample" })[0]; Assert.AreEqual(m.Name, modelFromDb.Name); modelFromDb = db.GetById<ModelWithOnlyStringFields>("998"); Assert.AreEqual(m.Name, modelFromDb.Name); } OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase(); using (var db = new OrmLiteConnectionFactory(ConnectionString, FirebirdDialect.Provider).Open()) { db.CreateTable<ModelWithOnlyStringFields>(true); ModelWithOnlyStringFields m = new ModelWithOnlyStringFields() { Id = "998", AlbumId = "112", AlbumName = "ElectroShip", Name = "QueryByExample" }; db.Save<ModelWithOnlyStringFields>(m); var modelFromDb = db.Where<ModelWithOnlyStringFields>(new { Name = "QueryByExample" })[0]; Assert.AreEqual(m.Name, modelFromDb.Name); modelFromDb = db.GetById<ModelWithOnlyStringFields>("998"); Assert.AreEqual(m.Name, modelFromDb.Name); } OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = new PrefixNamingStrategy { TablePrefix = "tab_", ColumnPrefix = "col_", }; using (var db = new OrmLiteConnectionFactory(ConnectionString, FirebirdDialect.Provider).Open()) { db.CreateTable<ModelWithOnlyStringFields>(true); ModelWithOnlyStringFields m = new ModelWithOnlyStringFields() { Id = "998", AlbumId = "112", AlbumName = "ElectroShip", Name = "QueryByExample" }; db.Save<ModelWithOnlyStringFields>(m); var modelFromDb = db.Where<ModelWithOnlyStringFields>(new { Name = "QueryByExample" })[0]; Assert.AreEqual(m.Name, modelFromDb.Name); modelFromDb = db.GetById<ModelWithOnlyStringFields>("998"); Assert.AreEqual(m.Name, modelFromDb.Name); } OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase(); } } /// <summary>A prefix naming strategy.</summary> public class PrefixNamingStrategy : OrmLiteNamingStrategyBase { /// <summary>Gets or sets the table prefix.</summary> /// <value>The table prefix.</value> public string TablePrefix { get; set; } /// <summary>Gets or sets the column prefix.</summary> /// <value>The column prefix.</value> public string ColumnPrefix { get; set; } /// <summary>Gets table name.</summary> /// <param name="name">The name.</param> /// <returns>The table name.</returns> public override string GetTableName(string name) { return TablePrefix + name; } /// <summary>Gets column name.</summary> /// <param name="name">The name.</param> /// <returns>The column name.</returns> public override string GetColumnName(string name) { return ColumnPrefix + name; } } /// <summary>A lowercase naming strategy.</summary> public class LowercaseNamingStrategy : OrmLiteNamingStrategyBase { /// <summary>Gets table name.</summary> /// <param name="name">The name.</param> /// <returns>The table name.</returns> public override string GetTableName(string name) { return name.ToLower(); } /// <summary>Gets column name.</summary> /// <param name="name">The name.</param> /// <returns>The column name.</returns> public override string GetColumnName(string name) { return name.ToLower(); } } /// <summary>An underscore separated compound naming strategy.</summary> public class UnderscoreSeparatedCompoundNamingStrategy : OrmLiteNamingStrategyBase { /// <summary>Gets table name.</summary> /// <param name="name">The name.</param> /// <returns>The table name.</returns> public override string GetTableName(string name) { return toUnderscoreSeparatedCompound(name); } /// <summary>Gets column name.</summary> /// <param name="name">The name.</param> /// <returns>The column name.</returns> public override string GetColumnName(string name) { return toUnderscoreSeparatedCompound(name); } /// <summary>Converts a name to an underscore separated compound.</summary> /// <param name="name">The name.</param> /// <returns>name as a string.</returns> string toUnderscoreSeparatedCompound(string name) { string r = char.ToLower(name[0]).ToString(); for (int i = 1; i < name.Length; i++) { //char c = name[i]; if (char.IsUpper(name[i])) { r += "_"; r += char.ToLower(name[i]); } else { r += name[i]; } } return r; } } }