context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
namespace RRLab.PhysiologyDataWorkshop
{
partial class RecordingViewerPanel
{
/// <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 Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RecordingViewerPanel));
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.CellAnnotationsGroupBox = new System.Windows.Forms.GroupBox();
this.CellAnnotationsDataGridView = new System.Windows.Forms.DataGridView();
this.userIDDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.enteredDataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.textDataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.fKCellsCellsAnnotationsBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.CellsBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.RecordingSubtablesViewer = new RRLab.PhysiologyData.GUI.RecordingSubTablesViewer();
this.ProgramBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.RecordingAnnotationsGroupBox = new System.Windows.Forms.GroupBox();
this.RecordingAnnotationsDataGridView = new System.Windows.Forms.DataGridView();
this.userIDDataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.enteredDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.textDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.fKRecordingsRecordingsAnnotationsBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.RecordingsBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.cellAndRecordingInfoPanel1 = new RRLab.PhysiologyData.GUI.CellAndRecordingInfoPanel();
this.recordingDataGraphControl1 = new RRLab.PhysiologyData.GUI.RecordingDataGraphControl();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.toolStripButton1 = new System.Windows.Forms.ToolStripButton();
this.recordingsDropDownButton = new System.Windows.Forms.ToolStripDropDownButton();
this.toolStripButton5 = new System.Windows.Forms.ToolStripButton();
this.RecordingIndexToolStripLabel = new System.Windows.Forms.ToolStripLabel();
this.toolStripButton6 = new System.Windows.Forms.ToolStripButton();
this.toolStripButton4 = new System.Windows.Forms.ToolStripButton();
this.toolStripButton2 = new System.Windows.Forms.ToolStripDropDownButton();
this.cellToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.recordingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ExportMatlabToolStripButton = new System.Windows.Forms.ToolStripButton();
this.ActionsDropDownButton = new System.Windows.Forms.ToolStripDropDownButton();
this.toolStripButton3 = new System.Windows.Forms.ToolStripButton();
this.MainSplitContainer = new System.Windows.Forms.SplitContainer();
this.recordingIDLabel = new System.Windows.Forms.ToolStripLabel();
this.tableLayoutPanel1.SuspendLayout();
this.CellAnnotationsGroupBox.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.CellAnnotationsDataGridView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.fKCellsCellsAnnotationsBindingSource)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CellsBindingSource)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ProgramBindingSource)).BeginInit();
this.RecordingAnnotationsGroupBox.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.RecordingAnnotationsDataGridView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.fKRecordingsRecordingsAnnotationsBindingSource)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.RecordingsBindingSource)).BeginInit();
this.tableLayoutPanel2.SuspendLayout();
this.toolStrip1.SuspendLayout();
this.MainSplitContainer.Panel1.SuspendLayout();
this.MainSplitContainer.Panel2.SuspendLayout();
this.MainSplitContainer.SuspendLayout();
this.SuspendLayout();
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 1;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Controls.Add(this.CellAnnotationsGroupBox, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.RecordingSubtablesViewer, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.RecordingAnnotationsGroupBox, 0, 1);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 3;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(241, 532);
this.tableLayoutPanel1.TabIndex = 0;
//
// CellAnnotationsGroupBox
//
this.CellAnnotationsGroupBox.AutoSize = true;
this.CellAnnotationsGroupBox.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.CellAnnotationsGroupBox.Controls.Add(this.CellAnnotationsDataGridView);
this.CellAnnotationsGroupBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.CellAnnotationsGroupBox.Location = new System.Drawing.Point(3, 3);
this.CellAnnotationsGroupBox.Name = "CellAnnotationsGroupBox";
this.CellAnnotationsGroupBox.Size = new System.Drawing.Size(235, 171);
this.CellAnnotationsGroupBox.TabIndex = 2;
this.CellAnnotationsGroupBox.TabStop = false;
this.CellAnnotationsGroupBox.Text = "Cell Annotations";
//
// CellAnnotationsDataGridView
//
this.CellAnnotationsDataGridView.AutoGenerateColumns = false;
this.CellAnnotationsDataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.DisplayedCells;
this.CellAnnotationsDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.CellAnnotationsDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.userIDDataGridViewTextBoxColumn,
this.enteredDataGridViewTextBoxColumn1,
this.textDataGridViewTextBoxColumn1});
this.CellAnnotationsDataGridView.DataSource = this.fKCellsCellsAnnotationsBindingSource;
this.CellAnnotationsDataGridView.Dock = System.Windows.Forms.DockStyle.Fill;
this.CellAnnotationsDataGridView.Location = new System.Drawing.Point(3, 16);
this.CellAnnotationsDataGridView.Name = "CellAnnotationsDataGridView";
this.CellAnnotationsDataGridView.Size = new System.Drawing.Size(229, 152);
this.CellAnnotationsDataGridView.TabIndex = 0;
//
// userIDDataGridViewTextBoxColumn
//
this.userIDDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
this.userIDDataGridViewTextBoxColumn.DataPropertyName = "UserID";
this.userIDDataGridViewTextBoxColumn.HeaderText = "UserID";
this.userIDDataGridViewTextBoxColumn.Name = "userIDDataGridViewTextBoxColumn";
this.userIDDataGridViewTextBoxColumn.Width = 65;
//
// enteredDataGridViewTextBoxColumn1
//
this.enteredDataGridViewTextBoxColumn1.DataPropertyName = "Entered";
this.enteredDataGridViewTextBoxColumn1.HeaderText = "Entered";
this.enteredDataGridViewTextBoxColumn1.Name = "enteredDataGridViewTextBoxColumn1";
this.enteredDataGridViewTextBoxColumn1.Width = 69;
//
// textDataGridViewTextBoxColumn1
//
this.textDataGridViewTextBoxColumn1.DataPropertyName = "Text";
this.textDataGridViewTextBoxColumn1.HeaderText = "Text";
this.textDataGridViewTextBoxColumn1.Name = "textDataGridViewTextBoxColumn1";
this.textDataGridViewTextBoxColumn1.Width = 53;
//
// fKCellsCellsAnnotationsBindingSource
//
this.fKCellsCellsAnnotationsBindingSource.DataMember = "FK_Cells_Cells_Annotations";
this.fKCellsCellsAnnotationsBindingSource.DataSource = this.CellsBindingSource;
//
// CellsBindingSource
//
this.CellsBindingSource.DataMember = "Cells";
this.CellsBindingSource.DataSource = typeof(RRLab.PhysiologyWorkbench.Data.PhysiologyDataSet);
//
// RecordingSubtablesViewer
//
this.RecordingSubtablesViewer.CurrentRecordingID = ((long)(1));
this.RecordingSubtablesViewer.DataBindings.Add(new System.Windows.Forms.Binding("CurrentRecordingID", this.ProgramBindingSource, "CurrentRecordingID", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.RecordingSubtablesViewer.DataBindings.Add(new System.Windows.Forms.Binding("DataSet", this.ProgramBindingSource, "DataSet", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.RecordingSubtablesViewer.DataSet = null;
this.RecordingSubtablesViewer.Dock = System.Windows.Forms.DockStyle.Fill;
this.RecordingSubtablesViewer.Location = new System.Drawing.Point(3, 357);
this.RecordingSubtablesViewer.Name = "RecordingSubtablesViewer";
this.RecordingSubtablesViewer.Size = new System.Drawing.Size(235, 172);
this.RecordingSubtablesViewer.TabIndex = 0;
//
// ProgramBindingSource
//
this.ProgramBindingSource.DataSource = typeof(RRLab.PhysiologyDataWorkshop.PhysiologyDataWorkshopProgram);
//
// RecordingAnnotationsGroupBox
//
this.RecordingAnnotationsGroupBox.AutoSize = true;
this.RecordingAnnotationsGroupBox.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.RecordingAnnotationsGroupBox.Controls.Add(this.RecordingAnnotationsDataGridView);
this.RecordingAnnotationsGroupBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.RecordingAnnotationsGroupBox.Location = new System.Drawing.Point(3, 180);
this.RecordingAnnotationsGroupBox.Name = "RecordingAnnotationsGroupBox";
this.RecordingAnnotationsGroupBox.Size = new System.Drawing.Size(235, 171);
this.RecordingAnnotationsGroupBox.TabIndex = 1;
this.RecordingAnnotationsGroupBox.TabStop = false;
this.RecordingAnnotationsGroupBox.Text = "Recording Annotations";
//
// RecordingAnnotationsDataGridView
//
this.RecordingAnnotationsDataGridView.AutoGenerateColumns = false;
this.RecordingAnnotationsDataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.DisplayedCells;
this.RecordingAnnotationsDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.RecordingAnnotationsDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.userIDDataGridViewTextBoxColumn1,
this.enteredDataGridViewTextBoxColumn,
this.textDataGridViewTextBoxColumn});
this.RecordingAnnotationsDataGridView.DataSource = this.fKRecordingsRecordingsAnnotationsBindingSource;
this.RecordingAnnotationsDataGridView.Dock = System.Windows.Forms.DockStyle.Fill;
this.RecordingAnnotationsDataGridView.Location = new System.Drawing.Point(3, 16);
this.RecordingAnnotationsDataGridView.Name = "RecordingAnnotationsDataGridView";
this.RecordingAnnotationsDataGridView.Size = new System.Drawing.Size(229, 152);
this.RecordingAnnotationsDataGridView.TabIndex = 0;
//
// userIDDataGridViewTextBoxColumn1
//
this.userIDDataGridViewTextBoxColumn1.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
this.userIDDataGridViewTextBoxColumn1.DataPropertyName = "UserID";
this.userIDDataGridViewTextBoxColumn1.HeaderText = "UserID";
this.userIDDataGridViewTextBoxColumn1.Name = "userIDDataGridViewTextBoxColumn1";
this.userIDDataGridViewTextBoxColumn1.Width = 65;
//
// enteredDataGridViewTextBoxColumn
//
this.enteredDataGridViewTextBoxColumn.DataPropertyName = "Entered";
this.enteredDataGridViewTextBoxColumn.HeaderText = "Entered";
this.enteredDataGridViewTextBoxColumn.Name = "enteredDataGridViewTextBoxColumn";
this.enteredDataGridViewTextBoxColumn.Width = 69;
//
// textDataGridViewTextBoxColumn
//
this.textDataGridViewTextBoxColumn.DataPropertyName = "Text";
this.textDataGridViewTextBoxColumn.HeaderText = "Text";
this.textDataGridViewTextBoxColumn.Name = "textDataGridViewTextBoxColumn";
this.textDataGridViewTextBoxColumn.Width = 53;
//
// fKRecordingsRecordingsAnnotationsBindingSource
//
this.fKRecordingsRecordingsAnnotationsBindingSource.DataMember = "FK_Recordings_Recordings_Annotations";
this.fKRecordingsRecordingsAnnotationsBindingSource.DataSource = this.RecordingsBindingSource;
//
// RecordingsBindingSource
//
this.RecordingsBindingSource.DataMember = "FK_Cells_Recordings";
this.RecordingsBindingSource.DataSource = this.CellsBindingSource;
//
// tableLayoutPanel2
//
this.tableLayoutPanel2.ColumnCount = 1;
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel2.Controls.Add(this.cellAndRecordingInfoPanel1, 0, 0);
this.tableLayoutPanel2.Controls.Add(this.recordingDataGraphControl1, 0, 1);
this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel2.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
this.tableLayoutPanel2.RowCount = 2;
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel2.Size = new System.Drawing.Size(641, 532);
this.tableLayoutPanel2.TabIndex = 1;
//
// cellAndRecordingInfoPanel1
//
this.cellAndRecordingInfoPanel1.CurrentCellID = 1;
this.cellAndRecordingInfoPanel1.CurrentRecordingID = ((long)(0));
this.cellAndRecordingInfoPanel1.DataBindings.Add(new System.Windows.Forms.Binding("CurrentCellID", this.ProgramBindingSource, "CurrentCellID", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.cellAndRecordingInfoPanel1.DataBindings.Add(new System.Windows.Forms.Binding("CurrentRecordingID", this.ProgramBindingSource, "CurrentRecordingID", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.cellAndRecordingInfoPanel1.DataBindings.Add(new System.Windows.Forms.Binding("DataSet", this.ProgramBindingSource, "DataSet", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.cellAndRecordingInfoPanel1.DataSet = null;
this.cellAndRecordingInfoPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.cellAndRecordingInfoPanel1.Location = new System.Drawing.Point(3, 3);
this.cellAndRecordingInfoPanel1.MinimumSize = new System.Drawing.Size(535, 250);
this.cellAndRecordingInfoPanel1.Name = "cellAndRecordingInfoPanel1";
this.cellAndRecordingInfoPanel1.Size = new System.Drawing.Size(635, 250);
this.cellAndRecordingInfoPanel1.TabIndex = 0;
//
// recordingDataGraphControl1
//
this.recordingDataGraphControl1.CurrentRecordingID = ((long)(0));
this.recordingDataGraphControl1.DataBindings.Add(new System.Windows.Forms.Binding("CurrentRecordingID", this.ProgramBindingSource, "CurrentRecordingID", true, System.Windows.Forms.DataSourceUpdateMode.Never));
this.recordingDataGraphControl1.DataBindings.Add(new System.Windows.Forms.Binding("DataSet", this.ProgramBindingSource, "DataSet", true, System.Windows.Forms.DataSourceUpdateMode.Never));
this.recordingDataGraphControl1.DataSet = null;
this.recordingDataGraphControl1.DefaultAxisLocation = RRLab.PhysiologyData.GUI.RecordingDataGraphControl.AxisLocation.Left;
this.recordingDataGraphControl1.DefaultAxisMode = RRLab.PhysiologyData.GUI.RecordingDataGraphControl.AxisMode.Auto;
this.recordingDataGraphControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.recordingDataGraphControl1.GraphBackColor = System.Drawing.Color.LightGoldenrodYellow;
this.recordingDataGraphControl1.Location = new System.Drawing.Point(3, 259);
this.recordingDataGraphControl1.Name = "recordingDataGraphControl1";
this.recordingDataGraphControl1.Size = new System.Drawing.Size(635, 270);
this.recordingDataGraphControl1.TabIndex = 1;
//
// toolStrip1
//
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripButton1,
this.recordingsDropDownButton,
this.toolStripButton5,
this.recordingIDLabel,
this.RecordingIndexToolStripLabel,
this.toolStripButton6,
this.toolStripButton4,
this.toolStripButton2,
this.ExportMatlabToolStripButton,
this.ActionsDropDownButton,
this.toolStripButton3});
this.toolStrip1.Location = new System.Drawing.Point(0, 0);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(886, 25);
this.toolStrip1.TabIndex = 2;
this.toolStrip1.Text = "toolStrip1";
//
// toolStripButton1
//
this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolStripButton1.Enabled = false;
this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image")));
this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton1.Name = "toolStripButton1";
this.toolStripButton1.Size = new System.Drawing.Size(65, 22);
this.toolStripButton1.Text = "Select Cell";
//
// recordingsDropDownButton
//
this.recordingsDropDownButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.recordingsDropDownButton.Image = ((System.Drawing.Image)(resources.GetObject("recordingsDropDownButton.Image")));
this.recordingsDropDownButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.recordingsDropDownButton.Name = "recordingsDropDownButton";
this.recordingsDropDownButton.Size = new System.Drawing.Size(108, 22);
this.recordingsDropDownButton.Text = "Select Recording";
//
// toolStripButton5
//
this.toolStripButton5.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolStripButton5.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton5.Image")));
this.toolStripButton5.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton5.Name = "toolStripButton5";
this.toolStripButton5.Size = new System.Drawing.Size(56, 22);
this.toolStripButton5.Text = "Previous";
this.toolStripButton5.Click += new System.EventHandler(this.OnPreviousRecordingClicked);
//
// RecordingIndexToolStripLabel
//
this.RecordingIndexToolStripLabel.Name = "RecordingIndexToolStripLabel";
this.RecordingIndexToolStripLabel.Size = new System.Drawing.Size(36, 22);
this.RecordingIndexToolStripLabel.Text = "0 of 0";
//
// toolStripButton6
//
this.toolStripButton6.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolStripButton6.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton6.Image")));
this.toolStripButton6.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton6.Name = "toolStripButton6";
this.toolStripButton6.Size = new System.Drawing.Size(35, 22);
this.toolStripButton6.Text = "Next";
this.toolStripButton6.Click += new System.EventHandler(this.OnNextRecordingClicked);
//
// toolStripButton4
//
this.toolStripButton4.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolStripButton4.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton4.Image")));
this.toolStripButton4.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton4.Name = "toolStripButton4";
this.toolStripButton4.Size = new System.Drawing.Size(49, 22);
this.toolStripButton4.Text = "Update";
this.toolStripButton4.Click += new System.EventHandler(this.OnUpdateClicked);
//
// toolStripButton2
//
this.toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolStripButton2.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.cellToolStripMenuItem,
this.recordingToolStripMenuItem});
this.toolStripButton2.Enabled = false;
this.toolStripButton2.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton2.Image")));
this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton2.Name = "toolStripButton2";
this.toolStripButton2.Size = new System.Drawing.Size(53, 22);
this.toolStripButton2.Text = "Delete";
//
// cellToolStripMenuItem
//
this.cellToolStripMenuItem.Name = "cellToolStripMenuItem";
this.cellToolStripMenuItem.Size = new System.Drawing.Size(128, 22);
this.cellToolStripMenuItem.Text = "Cell";
//
// recordingToolStripMenuItem
//
this.recordingToolStripMenuItem.Name = "recordingToolStripMenuItem";
this.recordingToolStripMenuItem.Size = new System.Drawing.Size(128, 22);
this.recordingToolStripMenuItem.Text = "Recording";
//
// ExportMatlabToolStripButton
//
this.ExportMatlabToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.ExportMatlabToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("ExportMatlabToolStripButton.Image")));
this.ExportMatlabToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.ExportMatlabToolStripButton.Name = "ExportMatlabToolStripButton";
this.ExportMatlabToolStripButton.Size = new System.Drawing.Size(108, 22);
this.ExportMatlabToolStripButton.Text = "Export to MATLAB";
this.ExportMatlabToolStripButton.Click += new System.EventHandler(this.OnExportToMatlabClicked);
//
// ActionsDropDownButton
//
this.ActionsDropDownButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.ActionsDropDownButton.Image = ((System.Drawing.Image)(resources.GetObject("ActionsDropDownButton.Image")));
this.ActionsDropDownButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.ActionsDropDownButton.Name = "ActionsDropDownButton";
this.ActionsDropDownButton.Size = new System.Drawing.Size(60, 22);
this.ActionsDropDownButton.Text = "Actions";
//
// toolStripButton3
//
this.toolStripButton3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolStripButton3.Enabled = false;
this.toolStripButton3.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton3.Image")));
this.toolStripButton3.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton3.Name = "toolStripButton3";
this.toolStripButton3.Size = new System.Drawing.Size(74, 22);
this.toolStripButton3.Text = "Print Report";
//
// MainSplitContainer
//
this.MainSplitContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.MainSplitContainer.FixedPanel = System.Windows.Forms.FixedPanel.Panel2;
this.MainSplitContainer.Location = new System.Drawing.Point(0, 25);
this.MainSplitContainer.Name = "MainSplitContainer";
//
// MainSplitContainer.Panel1
//
this.MainSplitContainer.Panel1.Controls.Add(this.tableLayoutPanel2);
//
// MainSplitContainer.Panel2
//
this.MainSplitContainer.Panel2.Controls.Add(this.tableLayoutPanel1);
this.MainSplitContainer.Size = new System.Drawing.Size(886, 532);
this.MainSplitContainer.SplitterDistance = 641;
this.MainSplitContainer.TabIndex = 3;
//
// recordingIDLabel
//
this.recordingIDLabel.Name = "recordingIDLabel";
this.recordingIDLabel.Size = new System.Drawing.Size(0, 22);
//
// RecordingViewerPanel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.MainSplitContainer);
this.Controls.Add(this.toolStrip1);
this.Name = "RecordingViewerPanel";
this.Size = new System.Drawing.Size(886, 557);
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.CellAnnotationsGroupBox.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.CellAnnotationsDataGridView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.fKCellsCellsAnnotationsBindingSource)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CellsBindingSource)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.ProgramBindingSource)).EndInit();
this.RecordingAnnotationsGroupBox.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.RecordingAnnotationsDataGridView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.fKRecordingsRecordingsAnnotationsBindingSource)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.RecordingsBindingSource)).EndInit();
this.tableLayoutPanel2.ResumeLayout(false);
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.MainSplitContainer.Panel1.ResumeLayout(false);
this.MainSplitContainer.Panel2.ResumeLayout(false);
this.MainSplitContainer.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
private System.Windows.Forms.GroupBox CellAnnotationsGroupBox;
private System.Windows.Forms.DataGridView CellAnnotationsDataGridView;
private RRLab.PhysiologyData.GUI.RecordingSubTablesViewer RecordingSubtablesViewer;
private System.Windows.Forms.GroupBox RecordingAnnotationsGroupBox;
private System.Windows.Forms.DataGridView RecordingAnnotationsDataGridView;
private System.Windows.Forms.BindingSource CellsBindingSource;
private System.Windows.Forms.BindingSource RecordingsBindingSource;
private System.Windows.Forms.BindingSource fKCellsCellsAnnotationsBindingSource;
private System.Windows.Forms.BindingSource fKRecordingsRecordingsAnnotationsBindingSource;
private System.Windows.Forms.DataGridViewTextBoxColumn userIDDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn enteredDataGridViewTextBoxColumn1;
private System.Windows.Forms.DataGridViewTextBoxColumn textDataGridViewTextBoxColumn1;
private System.Windows.Forms.DataGridViewTextBoxColumn userIDDataGridViewTextBoxColumn1;
private System.Windows.Forms.DataGridViewTextBoxColumn enteredDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn textDataGridViewTextBoxColumn;
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripButton toolStripButton1;
private System.Windows.Forms.ToolStripDropDownButton recordingsDropDownButton;
private System.Windows.Forms.ToolStripDropDownButton toolStripButton2;
private System.Windows.Forms.ToolStripMenuItem cellToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem recordingToolStripMenuItem;
private System.Windows.Forms.ToolStripButton toolStripButton3;
private RRLab.PhysiologyData.GUI.CellAndRecordingInfoPanel cellAndRecordingInfoPanel1;
private System.Windows.Forms.ToolStripButton toolStripButton4;
private RRLab.PhysiologyData.GUI.RecordingDataGraphControl recordingDataGraphControl1;
private System.Windows.Forms.BindingSource ProgramBindingSource;
private System.Windows.Forms.SplitContainer MainSplitContainer;
private System.Windows.Forms.ToolStripButton toolStripButton5;
private System.Windows.Forms.ToolStripButton toolStripButton6;
private System.Windows.Forms.ToolStripLabel RecordingIndexToolStripLabel;
private System.Windows.Forms.ToolStripDropDownButton ActionsDropDownButton;
private System.Windows.Forms.ToolStripButton ExportMatlabToolStripButton;
private System.Windows.Forms.ToolStripLabel recordingIDLabel;
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="_ChunkParser.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Net.Configuration;
using System.Threading;
namespace System.Net
{
// This class is a helper for parsing chunked HTTP responses. Usage is to either call Read() ([....]) or ReadAsync()
// (async) methods to retrieve the response payload (without chunk metadata).
// The buffer passed to the .ctor is owned by the ChunkParser until the whole response is read (i.e. Read/
// ReadAsync return 0 bytes) or an error occurs.
// ChunkParser requires the whole metadata to be in the buffer, i.e. if only parts of a secion (chunk length/
// extension/trailer header etc.) fit into the buffer, ChunkParser will create a new, larger buffer until the
// data can be parsed or the buffer length limit is reached. The limit can be specified in the constructor.
internal sealed class ChunkParser
{
// 12 = CRLF <4-byte value in hex> CRLF: i.e. read CRLF of previous chunk + length + CRLF
private const int chunkLengthBuffer = 12;
private const int noChunkLength = -1;
private static readonly bool[] tokenChars;
private enum ReadState
{
ChunkLength = 0,
Extension,
Payload,
PayloadEnd, // read CRLF
Trailer,
Done,
Error
}
private byte[] buffer;
private int bufferCurrentPos;
private int bufferFillLength;
private int maxBufferLength;
private byte[] userBuffer;
private int userBufferOffset;
private int userBufferCount;
private LazyAsyncResult userAsyncResult;
private Stream dataSource;
private ReadState readState;
private int totalTrailerHeadersLength;
private int currentChunkLength;
private int currentChunkBytesRead; // Bytes read so far for the current chunk.
private int currentOperationBytesRead; // Bytes read so far for the current read operation.
private int syncResult;
private bool IsAsync
{
get { return userAsyncResult != null; }
}
static ChunkParser()
{
// The following was copied from System.Net.Http.HttpRuleParser. Consider combining the two implementations.
// token = 1*<any CHAR except CTLs or separators>
// CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
tokenChars = new bool[128]; // everything is false
for (int i = 33; i < 127; i++) // skip Space (32) & DEL (127)
{
tokenChars[i] = true;
}
// remove separators: these are not valid token characters
tokenChars[(byte)'('] = false;
tokenChars[(byte)')'] = false;
tokenChars[(byte)'<'] = false;
tokenChars[(byte)'>'] = false;
tokenChars[(byte)'@'] = false;
tokenChars[(byte)','] = false;
tokenChars[(byte)';'] = false;
tokenChars[(byte)':'] = false;
tokenChars[(byte)'\\'] = false;
tokenChars[(byte)'"'] = false;
tokenChars[(byte)'/'] = false;
tokenChars[(byte)'['] = false;
tokenChars[(byte)']'] = false;
tokenChars[(byte)'?'] = false;
tokenChars[(byte)'='] = false;
tokenChars[(byte)'{'] = false;
tokenChars[(byte)'}'] = false;
}
public ChunkParser(Stream dataSource, byte[] internalBuffer, int initialBufferOffset, int initialBufferCount,
int maxBufferLength)
{
Contract.Requires(dataSource != null);
Contract.Requires(internalBuffer != null);
Contract.Requires(internalBuffer.Length >= chunkLengthBuffer,
"Buffer must be big enough to hold the chunk length.");
Contract.Requires((initialBufferCount >= 0) && (initialBufferCount <= internalBuffer.Length));
Contract.Requires((initialBufferOffset >= 0) &&
(initialBufferOffset + initialBufferCount <= internalBuffer.Length));
this.dataSource = dataSource;
this.buffer = internalBuffer;
this.bufferCurrentPos = initialBufferOffset;
this.bufferFillLength = initialBufferOffset + initialBufferCount;
this.maxBufferLength = maxBufferLength;
this.currentChunkLength = noChunkLength;
this.readState = ReadState.ChunkLength;
}
public IAsyncResult ReadAsync(object caller, byte[] userBuffer, int userBufferOffset,
int userBufferCount, AsyncCallback callback, object state)
{
SetReadParameters(userBuffer, userBufferOffset, userBufferCount);
userAsyncResult = new LazyAsyncResult(caller, state, callback);
// Store to local var to handle inline completions that would reset 'userAsyncResult'.
IAsyncResult localResult = userAsyncResult;
try
{
ProcessResponse();
}
catch (Exception e)
{
CompleteUserRead(e);
}
return localResult;
}
public int Read(byte[] userBuffer, int userBufferOffset, int userBufferCount)
{
SetReadParameters(userBuffer, userBufferOffset, userBufferCount);
try
{
// By not setting userAsyncResult we indicate that this is a synchronous operation.
ProcessResponse();
}
catch (Exception)
{
TransitionToErrorState();
throw;
}
return syncResult;
}
private void SetReadParameters(byte[] userBuffer, int userBufferOffset, int userBufferCount)
{
Contract.Requires(userBuffer != null);
Contract.Requires((userBufferCount > 0) && (userBufferCount <= userBuffer.Length));
Contract.Requires((userBufferOffset >= 0) && (userBufferOffset + userBufferCount <= userBuffer.Length));
if (Interlocked.CompareExchange(ref this.userBuffer, userBuffer, null) != null)
{
// Overlapped read operations are not supported.
throw new InvalidOperationException(SR.GetString(SR.net_inasync));
}
Contract.Assert(userAsyncResult == null, "Overlapped read operations are not allowed.");
Contract.Assert((readState == ReadState.ChunkLength) || (readState == ReadState.PayloadEnd) ||
((readState == ReadState.Payload) && (currentChunkBytesRead < currentChunkLength)),
"Only one outstanding read operation at a time supported.");
this.userBufferCount = userBufferCount;
this.userBufferOffset = userBufferOffset;
}
public bool TryGetLeftoverBytes(out byte[] buffer, out int leftoverBufferOffset, out int leftoverBufferSize)
{
leftoverBufferOffset = 0;
leftoverBufferSize = 0;
buffer = null;
if (readState != ReadState.Done)
{
// The ConnectStream was closed before we completed reading the response (e.g. when closing the
// stream without consuming it).
return false;
}
Contract.Assert(userAsyncResult == null,
"If we're in the 'done' state we should not have pending operations.");
if (bufferCurrentPos == bufferFillLength)
{
// We consumed the whole buffer. No leftover bytes.
return false;
}
leftoverBufferOffset = bufferCurrentPos;
leftoverBufferSize = bufferFillLength - bufferCurrentPos;
buffer = this.buffer;
return true;
}
private void ProcessResponse()
{
Contract.Assert(readState < ReadState.Done, "We're already done. No need to process state.");
DataParseStatus result;
while (readState < ReadState.Done)
{
switch (readState)
{
case ReadState.ChunkLength:
result = ParseChunkLength();
break;
case ReadState.Extension:
result = ParseExtension();
break;
case ReadState.Payload:
result = HandlePayload();
break;
case ReadState.PayloadEnd:
result = ParsePayloadEnd();
break;
case ReadState.Trailer:
result = ParseTrailer();
break;
default:
Contract.Assert(false, "Unknown state");
throw new InternalException(); ;
}
switch (result)
{
case DataParseStatus.ContinueParsing:
// Continue with next loop iteration. Parsing was successful and we'll process the next state.
break;
case DataParseStatus.Done:
// Parsing was successful and we should return. We either have a result or we have a pending
// operation and will continue once the operation completes.
return;
case DataParseStatus.Invalid:
case DataParseStatus.DataTooBig:
CompleteUserRead(new IOException(
SR.GetString(SR.net_io_readfailure, SR.GetString(SR.net_io_connectionclosed))));
return;
case DataParseStatus.NeedMoreData:
if (!TryGetMoreData())
{
// Read operation didn't complete synchronously. Just return. The read completion
// callback will continue.
return;
}
// We already got more data, continue the loop.
break;
default:
Contract.Assert(false, "Unknown state");
throw new InternalException(); ;
}
}
}
private void CompleteUserRead(object result)
{
bool error = result is Exception;
// Reset user buffer information.
this.userBuffer = null;
this.userBufferCount = 0;
this.userBufferOffset = 0;
if (error)
{
TransitionToErrorState();
}
if (IsAsync)
{
LazyAsyncResult localResult = userAsyncResult;
userAsyncResult = null;
localResult.InvokeCallback(result);
}
else
{
if (error)
{
throw result as Exception;
}
Contract.Assert(result is int);
syncResult = (int)result;
}
}
private void TransitionToErrorState()
{
readState = ReadState.Error;
}
private bool TryGetMoreData()
{
PrepareBufferForMoreData();
int readSize = buffer.Length - bufferFillLength;
if (readState == ReadState.ChunkLength)
{
// When reading the chunk length we want to consume as few bytes from the network as possible (since
// the length information is just a few bytes). This will avoid copying large amounts of data to the
// user's buffer.
readSize = Math.Min(chunkLengthBuffer, readSize);
}
int bytesRead = 0;
if (IsAsync)
{
IAsyncResult ar = dataSource.BeginRead(buffer, bufferFillLength, readSize, ReadCallback, null);
CheckAsyncResult(ar);
if (!ar.CompletedSynchronously)
{
return false;
}
// The read operation already completed. Read the number of bytes read and continue processing.
bytesRead = dataSource.EndRead(ar);
}
else
{
bytesRead = dataSource.Read(buffer, bufferFillLength, readSize);
}
CompleteMetaDataReadOperation(bytesRead);
return true;
}
private void PrepareBufferForMoreData()
{
// If we have data left in the buffer, move it to the beginning of the buffer. If the whole buffer is
// filled with unconsumed data, increase the buffer to accommodate more data.
Contract.Assert(bufferCurrentPos <= bufferFillLength);
int currentPos = bufferCurrentPos;
bufferCurrentPos = 0;
if (currentPos == bufferFillLength)
{
// We have consumed all the data in the buffer (same scenario as having an empty buffer).
bufferFillLength = 0;
return;
}
if ((currentPos > 0) || (bufferFillLength < buffer.Length))
{
// We have consumed some data from the buffer. However, we need more data to process data left in
// the buffer. So move left data to the beginning of the buffer and fill the rest of the buffer.
if (currentPos > 0)
{
int count = bufferFillLength - currentPos;
Buffer.BlockCopy(buffer, currentPos, buffer, 0, count);
bufferFillLength = count;
}
return;
}
// The buffer is entirely filled and we haven't consumed a single byte. However, we need more data
// to be able to process it (e.g. if the whole buffer contains just part of a trailer header).
Contract.Assert(currentPos == 0);
Contract.Assert(bufferFillLength == buffer.Length);
if (buffer.Length == maxBufferLength)
{
throw new IOException(SR.GetString(SR.net_io_readfailure, SR.GetString(SR.net_io_connectionclosed)));
}
int newBufferLength = Math.Min(maxBufferLength, buffer.Length * 2);
byte[] newBuffer = new byte[newBufferLength];
Buffer.BlockCopy(buffer, 0, newBuffer, 0, buffer.Length);
buffer = newBuffer;
}
private void CheckAsyncResult(IAsyncResult ar)
{
// A null return indicates that the connection was closed underneath us.
if (ar == null)
{
throw new WebException(NetRes.GetWebStatusString("net_requestaborted",
WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
}
}
private void CompleteMetaDataReadOperation(int bytesRead)
{
if (bytesRead == 0)
{
// We don't expect a g----ful connection close from the server while we're in the middle of reading
// chunk metadata (chunk length, extension, trailer, etc.).
throw new IOException(SR.GetString(SR.net_io_readfailure, SR.GetString(SR.net_io_connectionclosed)));
}
bufferFillLength += bytesRead;
}
public void ReadCallback(IAsyncResult ar)
{
if (ar.CompletedSynchronously)
{
return;
}
try
{
int bytesRead = dataSource.EndRead(ar);
if (readState == ReadState.Payload)
{
// We received payload data and stored it in the user buffer. Validate the result and complete
// the IAsyncResult we returned to the caller. Next time ReadAsync() gets called we'll
// continue where we left off (i.e. read more data from the current chunk or if we already read
// the whole chunk, process the terminating CRLF and the next chunk/trailer).
CompletePayloadReadOperation(bytesRead);
return;
}
CompleteMetaDataReadOperation(bytesRead);
// We received data for our internal buffer. Process received data.
ProcessResponse();
}
catch (Exception e)
{
CompleteUserRead(e);
}
}
private DataParseStatus HandlePayload()
{
// Try to fill the user buffer with data from the internal buffer first.
if (bufferCurrentPos < bufferFillLength)
{
Contract.Assert(currentOperationBytesRead == 0,
"We only read chunk data from the buffer once per read operation.");
// We have chunk body data in our internal buffer. Copy it to the user buffer.
int bufferedBytesToRead = Math.Min(Math.Min(userBufferCount, bufferFillLength - bufferCurrentPos),
currentChunkLength - currentChunkBytesRead);
Buffer.BlockCopy(buffer, bufferCurrentPos, userBuffer, userBufferOffset, bufferedBytesToRead);
bufferCurrentPos += bufferedBytesToRead;
if ((currentChunkBytesRead + bufferedBytesToRead == currentChunkLength) ||
(bufferedBytesToRead == userBufferCount))
{
// We read the whole chunk or filled the user buffer entirely. Complete the operation.
CompletePayloadReadOperation(bufferedBytesToRead);
return DataParseStatus.Done;
}
// Remember how many bytes we copied from our internal buffer to the user buffer: We need to add this
// value to the amount of data read from the socket below.
currentOperationBytesRead += bufferedBytesToRead;
currentChunkBytesRead += bufferedBytesToRead;
}
Contract.Assert(bufferCurrentPos == bufferFillLength,
"We still have data buffered even though the user buffer is not filled yet.");
Contract.Assert(currentOperationBytesRead < userBufferCount);
// If we get here we either didn't have any chunk data buffered, or we had less bytes buffered than the
// user requested. Post a receive on the socket to retrieve more chunk data.
int bytesToRead = Math.Min(userBufferCount - currentOperationBytesRead,
currentChunkLength - currentChunkBytesRead);
if (IsAsync)
{
IAsyncResult ar = dataSource.BeginRead(userBuffer, userBufferOffset + currentOperationBytesRead,
bytesToRead, ReadCallback, null);
CheckAsyncResult(ar);
if (ar.CompletedSynchronously)
{
CompletePayloadReadOperation(dataSource.EndRead(ar));
}
}
else
{
int bytesRead = dataSource.Read(userBuffer, userBufferOffset + currentOperationBytesRead, bytesToRead);
CompletePayloadReadOperation(bytesRead);
}
return DataParseStatus.Done;
}
private void CompletePayloadReadOperation(int bytesRead)
{
Contract.Requires(bytesRead >= 0);
Contract.Assert(readState == ReadState.Payload,
"Chunk payload read completion must only be invoked when we're processing payload data.");
// Getting EOF in the middle of a chunk is a failure.
if (bytesRead == 0)
{
throw new WebException(NetRes.GetWebStatusString("net_requestaborted",
WebExceptionStatus.ConnectionClosed), WebExceptionStatus.ConnectionClosed);
}
currentChunkBytesRead += bytesRead;
Contract.Assert(currentChunkBytesRead <= currentChunkLength,
"Read more bytes than available in the current chunk.");
int totalBytesRead = currentOperationBytesRead + bytesRead;
if (currentChunkBytesRead == currentChunkLength)
{
// We're done reading this chunk.
readState = ReadState.PayloadEnd;
}
currentOperationBytesRead = 0;
CompleteUserRead(totalBytesRead);
}
private DataParseStatus ParseChunkLength()
{
Contract.Assert(currentChunkLength == noChunkLength);
int chunkLength = noChunkLength;
for (int i = bufferCurrentPos; i < bufferFillLength; i++)
{
byte c = buffer[i];
if (((c < '0') || (c > '9')) && ((c < 'A') || (c > 'F')) && ((c < 'a') || (c > 'f')))
{
// Not a hex number. Check if we had at least one hex digit. If not, then this is an invalid chunk.
if (chunkLength == noChunkLength)
{
return DataParseStatus.Invalid;
}
// Point to the first character after the chunk length that is not part of the length value.
bufferCurrentPos = i;
currentChunkLength = chunkLength;
readState = ReadState.Extension;
return DataParseStatus.ContinueParsing;
}
byte currentDigit = (byte)((c < (byte)'A') ? (c - (byte)'0') :
10 + ((c < (byte)'a') ? (c - (byte)'A') : (c - (byte)'a')));
if (chunkLength == noChunkLength)
{
chunkLength = currentDigit;
}
else
{
if (chunkLength >= 0x8000000)
{
// Shifting the value by an order of magnitude (hex) would result in a value > Int32.MaxValue.
// Currently only chunks up to 2GB are supported. The provided chunk length is too large.
return DataParseStatus.Invalid;
}
// Multiply current chunk length by 16 and add the current digit.
chunkLength = (chunkLength << 4) + currentDigit;
}
}
// The current buffer didn't include the whole chunk length information followed by a non-hex digit char.
return DataParseStatus.NeedMoreData;
}
private DataParseStatus ParseExtension()
{
int currentPos = bufferCurrentPos;
// After the chunk length we can only have <space> or <tab> chars. A LWS with CRLF would be ambiguous since
// CRLF also delimits the chunk length from chunk data.
DataParseStatus result = ParseWhitespaces(ref currentPos);
if (result != DataParseStatus.ContinueParsing)
{
return result;
}
result = ParseExtensionNameValuePairs(ref currentPos);
if (result != DataParseStatus.ContinueParsing)
{
return result;
}
result = ParseCRLF(ref currentPos);
if (result != DataParseStatus.ContinueParsing)
{
return result;
}
bufferCurrentPos = currentPos;
if (currentChunkLength == 0)
{
// zero-chunk read. We're done with the response. Consume trailer and complete.
readState = ReadState.Trailer;
}
else
{
readState = ReadState.Payload;
}
return DataParseStatus.ContinueParsing;
}
private DataParseStatus ParsePayloadEnd()
{
Contract.Assert(currentChunkBytesRead == currentChunkLength);
DataParseStatus crlfResult = ParseCRLF(ref bufferCurrentPos);
if (crlfResult != DataParseStatus.ContinueParsing)
{
return crlfResult;
}
currentChunkLength = noChunkLength;
currentChunkBytesRead = 0;
readState = ReadState.ChunkLength;
return DataParseStatus.ContinueParsing;
}
private DataParseStatus ParseTrailer()
{
if (ParseWhitespaces(ref bufferCurrentPos) == DataParseStatus.NeedMoreData)
{
return DataParseStatus.NeedMoreData;
}
int currentPos = bufferCurrentPos;
// Leverage WebHeaderCollection to parse the trailer.
DataParseStatus result;
WebParseError error;
error.Section = WebParseErrorSection.Generic;
error.Code = WebParseErrorCode.Generic;
WebHeaderCollection trailer = new WebHeaderCollection();
if (SettingsSectionInternal.Section.UseUnsafeHeaderParsing)
{
result = trailer.ParseHeaders(buffer, bufferFillLength, ref currentPos, ref totalTrailerHeadersLength,
maxBufferLength, ref error);
}
else
{
result = trailer.ParseHeadersStrict(buffer, bufferFillLength, ref currentPos,
ref totalTrailerHeadersLength, maxBufferLength, ref error);
}
Contract.Assert(result != DataParseStatus.ContinueParsing,
"ContinueParsing should never be returned by WebHeaderCollection.ParseHeaders*().");
if ((result == DataParseStatus.NeedMoreData) || (result == DataParseStatus.Done))
{
bufferCurrentPos = currentPos;
}
if (result != DataParseStatus.Done)
{
return result;
}
readState = ReadState.Done;
// We're done reading the whole response. Invoke the user callback with 0 bytes to indicate "end of stream".
CompleteUserRead(0);
return DataParseStatus.Done;
}
private DataParseStatus ParseCRLF(ref int pos)
{
Contract.Ensures((Contract.Result<DataParseStatus>() != DataParseStatus.Done) ||
(Contract.Result<DataParseStatus>() != DataParseStatus.DataTooBig));
const int crlfLength = 2;
if (pos + crlfLength > bufferFillLength)
{
return DataParseStatus.NeedMoreData;
}
if ((buffer[pos] != '\r') || (buffer[pos + 1] != '\n'))
{
return DataParseStatus.Invalid;
}
pos += crlfLength;
return DataParseStatus.ContinueParsing;
}
private DataParseStatus ParseWhitespaces(ref int pos)
{
Contract.Ensures((Contract.Result<DataParseStatus>() == DataParseStatus.ContinueParsing) ||
(Contract.Result<DataParseStatus>() == DataParseStatus.NeedMoreData) ||
(Contract.Result<DataParseStatus>() != DataParseStatus.DataTooBig));
int currentPos = pos;
while (currentPos < bufferFillLength)
{
byte c = buffer[currentPos];
if (!IsWhiteSpace(c))
{
// Point to the first character that is not a SP (space) or HT (horizontal tab).
pos = currentPos;
return DataParseStatus.ContinueParsing;
}
currentPos++;
}
// We only had whitespaces until the end of the buffer. Request more data to continue.
return DataParseStatus.NeedMoreData;
}
private static bool IsWhiteSpace(byte c)
{
return (c == ' ') || (c == '\t');
}
private DataParseStatus ParseExtensionNameValuePairs(ref int pos)
{
Contract.Ensures((Contract.Result<DataParseStatus>() != DataParseStatus.Done) ||
(Contract.Result<DataParseStatus>() != DataParseStatus.DataTooBig));
// chunk-extension= *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
// chunk-ext-name = token
// chunk-ext-val = token | quoted-string
DataParseStatus result;
int currentPos = pos;
while (buffer[currentPos] == ';')
{
currentPos++;
result = ParseWhitespaces(ref currentPos);
if (result != DataParseStatus.ContinueParsing)
{
return result;
}
result = ParseToken(ref currentPos);
if (result != DataParseStatus.ContinueParsing)
{
return result;
}
result = ParseWhitespaces(ref currentPos);
if (result != DataParseStatus.ContinueParsing)
{
return result;
}
Contract.Assert(currentPos < bufferFillLength,
"After skipping white spaces we should have at least one character.");
if (buffer[currentPos] == '=')
{
currentPos++;
result = ParseWhitespaces(ref currentPos);
if (result != DataParseStatus.ContinueParsing)
{
return result;
}
result = ParseToken(ref currentPos);
if (result == DataParseStatus.Invalid)
{
result = ParseQuotedString(ref currentPos);
}
if (result != DataParseStatus.ContinueParsing)
{
return result;
}
result = ParseWhitespaces(ref currentPos);
if (result != DataParseStatus.ContinueParsing)
{
return result;
}
}
}
pos = currentPos;
return DataParseStatus.ContinueParsing;
}
private DataParseStatus ParseQuotedString(ref int pos)
{
Contract.Ensures((Contract.Result<DataParseStatus>() != DataParseStatus.Done) ||
(Contract.Result<DataParseStatus>() != DataParseStatus.DataTooBig));
if (pos == bufferFillLength)
{
return DataParseStatus.NeedMoreData;
}
if (buffer[pos] != '"')
{
return DataParseStatus.Invalid;
}
int currentPos = pos + 1;
while (currentPos < bufferFillLength)
{
if ((buffer[currentPos] == '"'))
{
pos = currentPos + 1; // return index pointing to char after closing quote char.
return DataParseStatus.ContinueParsing;
}
// Note that for extensions we can't support backslash before the terminating quote: E.g. if we see
// \"\r\n we don't know if we have an escaped " followed by a LWS or if we're at the end of the quoted
// string followed by the extension-terminating CRLF. I.e. as soon as we see \" we interpret it as
// quoted pair.
if (buffer[currentPos] == '\\')
{
// We have a quoted pair. Make sure we have at least one more char in the buffer.
currentPos++;
if (currentPos == bufferFillLength)
{
return DataParseStatus.NeedMoreData;
}
// Only 0-127 values are allowed in a quoted pair. If the char after \ is > 127 then \ is not part
// of a quoted pair but a regular char in the quoted string.
if (buffer[currentPos] <= 0x7F)
{
currentPos++; // skip quoted pair
continue;
}
}
currentPos++;
}
return DataParseStatus.NeedMoreData;
}
private DataParseStatus ParseToken(ref int pos)
{
Contract.Ensures((Contract.Result<DataParseStatus>() != DataParseStatus.Done) ||
(Contract.Result<DataParseStatus>() != DataParseStatus.DataTooBig));
for (int currentPos = pos; currentPos < bufferFillLength; currentPos++)
{
if (!IsTokenChar(buffer[currentPos]))
{
// If we found at least one token character, we have a token. If not, indicate failure since
// we were supposed to parse a token but we didn't find one.
if (currentPos > pos)
{
pos = currentPos;
return DataParseStatus.ContinueParsing;
}
else
{
return DataParseStatus.Invalid;
}
}
}
return DataParseStatus.NeedMoreData;
}
private static bool IsTokenChar(byte character)
{
// Must be between 'space' (32) and 'DEL' (127)
if (character > 127)
{
return false;
}
return tokenChars[character];
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Prism.Events;
namespace Prism.Tests.Events
{
[TestClass]
public class EventSubscriptionFixture
{
[TestInitialize]
public void Setup()
{
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void NullTargetInActionThrows()
{
var actionDelegateReference = new MockDelegateReference()
{
Target = null
};
var filterDelegateReference = new MockDelegateReference()
{
Target = (Predicate<object>)(arg =>
{
return true;
})
};
var eventSubscription = new EventSubscription<object>(actionDelegateReference,
filterDelegateReference);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void DifferentTargetTypeInActionThrows()
{
var actionDelegateReference = new MockDelegateReference()
{
Target = (Action<int>)delegate { }
};
var filterDelegateReference = new MockDelegateReference()
{
Target = (Predicate<string>)(arg =>
{
return true;
})
};
var eventSubscription = new EventSubscription<string>(actionDelegateReference,
filterDelegateReference);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void NullActionThrows()
{
var filterDelegateReference = new MockDelegateReference()
{
Target = (Predicate<object>)(arg =>
{
return true;
})
};
var eventSubscription = new EventSubscription<object>(null, filterDelegateReference);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void NullTargetInFilterThrows()
{
var actionDelegateReference = new MockDelegateReference()
{
Target = (Action<object>)delegate { }
};
var filterDelegateReference = new MockDelegateReference()
{
Target = null
};
var eventSubscription = new EventSubscription<object>(actionDelegateReference,
filterDelegateReference);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void DifferentTargetTypeInFilterThrows()
{
var actionDelegateReference = new MockDelegateReference()
{
Target = (Action<string>)delegate { }
};
var filterDelegateReference = new MockDelegateReference()
{
Target = (Predicate<int>)(arg =>
{
return true;
})
};
var eventSubscription = new EventSubscription<string>(actionDelegateReference,
filterDelegateReference);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void NullFilterThrows()
{
var actionDelegateReference = new MockDelegateReference()
{
Target = (Action<object>)delegate { }
};
var eventSubscription = new EventSubscription<object>(actionDelegateReference,
null);
}
[TestMethod]
public void CanInitEventSubscription()
{
var actionDelegateReference = new MockDelegateReference((Action<object>)delegate { });
var filterDelegateReference = new MockDelegateReference((Predicate<object>)delegate { return true; });
var eventSubscription = new EventSubscription<object>(actionDelegateReference, filterDelegateReference);
var subscriptionToken = new SubscriptionToken(t => { });
eventSubscription.SubscriptionToken = subscriptionToken;
Assert.AreSame(actionDelegateReference.Target, eventSubscription.Action);
Assert.AreSame(filterDelegateReference.Target, eventSubscription.Filter);
Assert.AreSame(subscriptionToken, eventSubscription.SubscriptionToken);
}
[TestMethod]
public void GetPublishActionReturnsDelegateThatExecutesTheFilterAndThenTheAction()
{
var executedDelegates = new List<string>();
var actionDelegateReference =
new MockDelegateReference((Action<object>)delegate { executedDelegates.Add("Action"); });
var filterDelegateReference = new MockDelegateReference((Predicate<object>)delegate
{
executedDelegates.Add(
"Filter");
return true;
});
var eventSubscription = new EventSubscription<object>(actionDelegateReference, filterDelegateReference);
var publishAction = eventSubscription.GetExecutionStrategy();
Assert.IsNotNull(publishAction);
publishAction.Invoke(null);
Assert.AreEqual(2, executedDelegates.Count);
Assert.AreEqual("Filter", executedDelegates[0]);
Assert.AreEqual("Action", executedDelegates[1]);
}
[TestMethod]
public void GetPublishActionReturnsNullIfActionIsNull()
{
var actionDelegateReference = new MockDelegateReference((Action<object>)delegate { });
var filterDelegateReference = new MockDelegateReference((Predicate<object>)delegate { return true; });
var eventSubscription = new EventSubscription<object>(actionDelegateReference, filterDelegateReference);
var publishAction = eventSubscription.GetExecutionStrategy();
Assert.IsNotNull(publishAction);
actionDelegateReference.Target = null;
publishAction = eventSubscription.GetExecutionStrategy();
Assert.IsNull(publishAction);
}
[TestMethod]
public void GetPublishActionReturnsNullIfFilterIsNull()
{
var actionDelegateReference = new MockDelegateReference((Action<object>)delegate { });
var filterDelegateReference = new MockDelegateReference((Predicate<object>)delegate { return true; });
var eventSubscription = new EventSubscription<object>(actionDelegateReference, filterDelegateReference);
var publishAction = eventSubscription.GetExecutionStrategy();
Assert.IsNotNull(publishAction);
filterDelegateReference.Target = null;
publishAction = eventSubscription.GetExecutionStrategy();
Assert.IsNull(publishAction);
}
[TestMethod]
public void GetPublishActionDoesNotExecuteActionIfFilterReturnsFalse()
{
bool actionExecuted = false;
var actionDelegateReference = new MockDelegateReference()
{
Target = (Action<int>)delegate { actionExecuted = true; }
};
var filterDelegateReference = new MockDelegateReference((Predicate<int>)delegate
{
return false;
});
var eventSubscription = new EventSubscription<int>(actionDelegateReference, filterDelegateReference);
var publishAction = eventSubscription.GetExecutionStrategy();
publishAction.Invoke(new object[] { null });
Assert.IsFalse(actionExecuted);
}
[TestMethod]
public void StrategyPassesArgumentToDelegates()
{
string passedArgumentToAction = null;
string passedArgumentToFilter = null;
var actionDelegateReference = new MockDelegateReference((Action<string>)(obj => passedArgumentToAction = obj));
var filterDelegateReference = new MockDelegateReference((Predicate<string>)(obj =>
{
passedArgumentToFilter = obj;
return true;
}));
var eventSubscription = new EventSubscription<string>(actionDelegateReference, filterDelegateReference);
var publishAction = eventSubscription.GetExecutionStrategy();
publishAction.Invoke(new[] { "TestString" });
Assert.AreEqual("TestString", passedArgumentToAction);
Assert.AreEqual("TestString", passedArgumentToFilter);
}
}
}
| |
// 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 connection.
/// </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 connection.
/// </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 connection.
/// </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 connection.
/// </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 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 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 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 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 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 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 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 BeginDeleteAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, null, cancellationToken).ConfigureAwait(false);
}
/// <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 connection
/// 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 connection
/// 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 connection
/// 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 connection
/// 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 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='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection shared key name.
/// </param>
public static ConnectionSharedKey GetSharedKey(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName)
{
return Task.Factory.StartNew(s => ((IVirtualNetworkGatewayConnectionsOperations)s).GetSharedKeyAsync(resourceGroupName, virtualNetworkGatewayConnectionName), 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='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection shared key name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ConnectionSharedKey> GetSharedKeyAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSharedKeyWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, 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 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;
}
}
}
}
| |
// 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.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.X86;
using System.Runtime.Intrinsics;
namespace IntelHardwareIntrinsicTest
{
class Program
{
const int Pass = 100;
const int Fail = 0;
static unsafe int Main(string[] args)
{
int testResult = Pass;
if (Avx2.IsSupported)
{
using (TestTable<byte, byte, byte> byteTable = new TestTable<byte, byte, byte>(new byte[32] { 1, 5, 100, 0, 1, 5, 100, 0, 1, 5, 100, 0, 1, 5, 100, 0, 1, 5, 100, 0, 1, 5, 100, 0, 1, 5, 100, 0, 1, 5, 100, 0 }, new byte[32] { 22, 1, 50, 0, 22, 1, 50, 0, 22, 1, 50, 0, 22, 1, 50, 0, 22, 1, 50, 0, 22, 1, 50, 0, 22, 1, 50, 0, 22, 1, 50, 0 }, new byte[32]))
using (TestTable<sbyte, sbyte, sbyte> sbyteTable = new TestTable<sbyte, sbyte, sbyte>(new sbyte[32] { 1, -5, 100, 0, 1, -5, 100, 0, 1, -5, 100, 0, 1, -5, 100, 0, 1, -5, 100, 0, 1, -5, 100, 0, 1, -5, 100, 0, 1, -5, 100, 0 }, new sbyte[32] { 22, -1, -50, 0, 22, -1, -50, 0, 22, -1, -50, 0, 22, -1, -50, 0, 22, -1, -50, 0, 22, -1, -50, 0, 22, -1, -50, 0, 22, -1, -50, 0 }, new sbyte[32]))
using (TestTable<short, short, short> shortTable = new TestTable<short, short, short>(new short[16] { 1, -5, 100, 0, 1, -5, 100, 0, 1, -5, 100, 0, 1, -5, 100, 0 }, new short[16] { 22, -1, -50, 0, 22, -1, -50, 0, 22, -1, -50, 0, 22, -1, -50, 0}, new short[16]))
using (TestTable<ushort, ushort, ushort> ushortTable = new TestTable<ushort, ushort, ushort>(new ushort[16] { 1, 5, 100, 0, 1, 5, 100, 0, 1, 5, 100, 0, 1, 5, 100, 0 }, new ushort[16] { 22, 1, 50, 0, 22, 1, 50, 0, 22, 1, 50, 0, 22, 1, 50, 0 }, new ushort[16]))
using (TestTable<int, int, int> intTable = new TestTable<int, int, int>(new int[8] { 1, 5, 100, 0, 1, 5, 100, 0}, new int[8] { 22, 1, 50, 0, 22, 1, 50, 0 }, new int[8]))
using (TestTable<uint, uint, uint> uintTable = new TestTable<uint, uint, uint>(new uint[8] { 1, 5, 100, 0, 1, 5, 100, 0 }, new uint[8] { 22, 1, 50, 0, 22, 1, 50, 0 }, new uint[8]))
using (TestTable<long, long, long> longTable = new TestTable<long, long, long>(new long[4] { 1, -5, 100, 0 }, new long[4] { 22, -1, -50, 0}, new long[4]))
using (TestTable<ulong, ulong, ulong> ulongTable = new TestTable<ulong, ulong, ulong>(new ulong[4] { 1, 5, 100, 0 }, new ulong[4] { 22, 1, 50, 0 }, new ulong[4]))
{
var vb1 = Unsafe.Read<Vector256<byte>>(byteTable.inArray1Ptr);
var vb2 = Unsafe.Read<Vector256<byte>>(byteTable.inArray2Ptr);
var vb3 = Avx2.UnpackHigh(vb1, vb2);
Unsafe.Write(byteTable.outArrayPtr, vb3);
var vsb1 = Unsafe.Read<Vector256<sbyte>>(sbyteTable.inArray1Ptr);
var vsb2 = Unsafe.Read<Vector256<sbyte>>(sbyteTable.inArray2Ptr);
var vsb3 = Avx2.UnpackHigh(vsb1, vsb2);
Unsafe.Write(sbyteTable.outArrayPtr, vsb3);
var vs1 = Unsafe.Read<Vector256<short>>(shortTable.inArray1Ptr);
var vs2 = Unsafe.Read<Vector256<short>>(shortTable.inArray2Ptr);
var vs3 = Avx2.UnpackHigh(vs1, vs2);
Unsafe.Write(shortTable.outArrayPtr, vs3);
var vus1 = Unsafe.Read<Vector256<ushort>>(ushortTable.inArray1Ptr);
var vus2 = Unsafe.Read<Vector256<ushort>>(ushortTable.inArray2Ptr);
var vus3 = Avx2.UnpackHigh(vus1, vus2);
Unsafe.Write(ushortTable.outArrayPtr, vus3);
var vi1 = Unsafe.Read<Vector256<int>>(intTable.inArray1Ptr);
var vi2 = Unsafe.Read<Vector256<int>>(intTable.inArray2Ptr);
var vi3 = Avx2.UnpackHigh(vi1, vi2);
Unsafe.Write(intTable.outArrayPtr, vi3);
var vui1 = Unsafe.Read<Vector256<uint>>(uintTable.inArray1Ptr);
var vui2 = Unsafe.Read<Vector256<uint>>(uintTable.inArray2Ptr);
var vui3 = Avx2.UnpackHigh(vui1, vui2);
Unsafe.Write(uintTable.outArrayPtr, vui3);
var vl1 = Unsafe.Read<Vector256<long>>(longTable.inArray1Ptr);
var vl2 = Unsafe.Read<Vector256<long>>(longTable.inArray2Ptr);
var vl3 = Avx2.UnpackHigh(vl1, vl2);
Unsafe.Write(longTable.outArrayPtr, vl3);
var vul1 = Unsafe.Read<Vector256<ulong>>(ulongTable.inArray1Ptr);
var vul2 = Unsafe.Read<Vector256<ulong>>(ulongTable.inArray2Ptr);
var vul3 = Avx2.UnpackHigh(vul1, vul2);
Unsafe.Write(ulongTable.outArrayPtr, vul3);
if((byteTable.inArray1[8] != byteTable.outArray[0]) || (byteTable.inArray2[8] != byteTable.outArray[1]) ||
(byteTable.inArray1[9] != byteTable.outArray[2]) || (byteTable.inArray2[9] != byteTable.outArray[3]) ||
(byteTable.inArray1[10] != byteTable.outArray[4]) || (byteTable.inArray2[10] != byteTable.outArray[5]) ||
(byteTable.inArray1[11] != byteTable.outArray[6]) || (byteTable.inArray2[11] != byteTable.outArray[7]) ||
(byteTable.inArray1[12] != byteTable.outArray[8]) || (byteTable.inArray2[12] != byteTable.outArray[9]) ||
(byteTable.inArray1[13] != byteTable.outArray[10]) || (byteTable.inArray2[13] != byteTable.outArray[11]) ||
(byteTable.inArray1[14] != byteTable.outArray[12]) || (byteTable.inArray2[14] != byteTable.outArray[13]) ||
(byteTable.inArray1[15] != byteTable.outArray[14]) || (byteTable.inArray2[15] != byteTable.outArray[15]) ||
(byteTable.inArray1[24] != byteTable.outArray[16]) || (byteTable.inArray2[24] != byteTable.outArray[17]) ||
(byteTable.inArray1[25] != byteTable.outArray[18]) || (byteTable.inArray2[25] != byteTable.outArray[19]) ||
(byteTable.inArray1[26] != byteTable.outArray[20]) || (byteTable.inArray2[26] != byteTable.outArray[21]) ||
(byteTable.inArray1[27] != byteTable.outArray[22]) || (byteTable.inArray2[27] != byteTable.outArray[23]) ||
(byteTable.inArray1[28] != byteTable.outArray[24]) || (byteTable.inArray2[28] != byteTable.outArray[25]) ||
(byteTable.inArray1[29] != byteTable.outArray[26]) || (byteTable.inArray2[29] != byteTable.outArray[27]) ||
(byteTable.inArray1[30] != byteTable.outArray[28]) || (byteTable.inArray2[30] != byteTable.outArray[29]) ||
(byteTable.inArray1[31] != byteTable.outArray[30]) || (byteTable.inArray2[31] != byteTable.outArray[31]))
{
Console.WriteLine("AVX2 UnpackHigh failed on byte:");
Console.WriteLine($" left: ({string.Join(", ", byteTable.inArray1)})");
Console.WriteLine($" right: ({string.Join(", ", byteTable.inArray2)})");
Console.WriteLine($" result: ({string.Join(", ", byteTable.outArray)})");
Console.WriteLine();
testResult = Fail;
}
if((sbyteTable.inArray1[8] != sbyteTable.outArray[0]) || (sbyteTable.inArray2[8] != sbyteTable.outArray[1]) ||
(sbyteTable.inArray1[9] != sbyteTable.outArray[2]) || (sbyteTable.inArray2[9] != sbyteTable.outArray[3]) ||
(sbyteTable.inArray1[10] != sbyteTable.outArray[4]) || (sbyteTable.inArray2[10] != sbyteTable.outArray[5]) ||
(sbyteTable.inArray1[11] != sbyteTable.outArray[6]) || (sbyteTable.inArray2[11] != sbyteTable.outArray[7]) ||
(sbyteTable.inArray1[12] != sbyteTable.outArray[8]) || (sbyteTable.inArray2[12] != sbyteTable.outArray[9]) ||
(sbyteTable.inArray1[13] != sbyteTable.outArray[10]) || (sbyteTable.inArray2[13] != sbyteTable.outArray[11]) ||
(sbyteTable.inArray1[14] != sbyteTable.outArray[12]) || (sbyteTable.inArray2[14] != sbyteTable.outArray[13]) ||
(sbyteTable.inArray1[15] != sbyteTable.outArray[14]) || (sbyteTable.inArray2[15] != sbyteTable.outArray[15]) ||
(sbyteTable.inArray1[24] != sbyteTable.outArray[16]) || (sbyteTable.inArray2[24] != sbyteTable.outArray[17]) ||
(sbyteTable.inArray1[25] != sbyteTable.outArray[18]) || (sbyteTable.inArray2[25] != sbyteTable.outArray[19]) ||
(sbyteTable.inArray1[26] != sbyteTable.outArray[20]) || (sbyteTable.inArray2[26] != sbyteTable.outArray[21]) ||
(sbyteTable.inArray1[27] != sbyteTable.outArray[22]) || (sbyteTable.inArray2[27] != sbyteTable.outArray[23]) ||
(sbyteTable.inArray1[28] != sbyteTable.outArray[24]) || (sbyteTable.inArray2[28] != sbyteTable.outArray[25]) ||
(sbyteTable.inArray1[29] != sbyteTable.outArray[26]) || (sbyteTable.inArray2[29] != sbyteTable.outArray[27]) ||
(sbyteTable.inArray1[30] != sbyteTable.outArray[28]) || (sbyteTable.inArray2[30] != sbyteTable.outArray[29]) ||
(sbyteTable.inArray1[31] != sbyteTable.outArray[30]) || (sbyteTable.inArray2[31] != sbyteTable.outArray[31]))
{
Console.WriteLine("AVX2 UnpackHigh failed on sbyte:");
Console.WriteLine($" left: ({string.Join(", ", byteTable.inArray1)})");
Console.WriteLine($" right: ({string.Join(", ", byteTable.inArray2)})");
Console.WriteLine($" result: ({string.Join(", ", byteTable.outArray)})");
Console.WriteLine();
testResult = Fail;
}
if((shortTable.inArray1[4] != shortTable.outArray[0]) || (shortTable.inArray2[4] != shortTable.outArray[1]) ||
(shortTable.inArray1[5] != shortTable.outArray[2]) || (shortTable.inArray2[5] != shortTable.outArray[3]) ||
(shortTable.inArray1[6] != shortTable.outArray[4]) || (shortTable.inArray2[6] != shortTable.outArray[5]) ||
(shortTable.inArray1[7] != shortTable.outArray[6]) || (shortTable.inArray2[7] != shortTable.outArray[7]) ||
(shortTable.inArray1[12] != shortTable.outArray[8]) || (shortTable.inArray2[12] != shortTable.outArray[9]) ||
(shortTable.inArray1[13] != shortTable.outArray[10]) || (shortTable.inArray2[13] != shortTable.outArray[11]) ||
(shortTable.inArray1[14] != shortTable.outArray[12]) || (shortTable.inArray2[14] != shortTable.outArray[13]) ||
(shortTable.inArray1[15] != shortTable.outArray[14]) || (shortTable.inArray2[15] != shortTable.outArray[15]))
{
Console.WriteLine("AVX2 UnpackHigh failed on short:");
Console.WriteLine($" left: ({string.Join(", ", byteTable.inArray1)})");
Console.WriteLine($" right: ({string.Join(", ", byteTable.inArray2)})");
Console.WriteLine($" result: ({string.Join(", ", byteTable.outArray)})");
Console.WriteLine();
testResult = Fail;
}
if((ushortTable.inArray1[4] != ushortTable.outArray[0]) || (ushortTable.inArray2[4] != ushortTable.outArray[1]) ||
(ushortTable.inArray1[5] != ushortTable.outArray[2]) || (ushortTable.inArray2[5] != ushortTable.outArray[3]) ||
(ushortTable.inArray1[6] != ushortTable.outArray[4]) || (ushortTable.inArray2[6] != ushortTable.outArray[5]) ||
(ushortTable.inArray1[7] != ushortTable.outArray[6]) || (ushortTable.inArray2[7] != ushortTable.outArray[7]) ||
(ushortTable.inArray1[12] != ushortTable.outArray[8]) || (ushortTable.inArray2[12] != ushortTable.outArray[9]) ||
(ushortTable.inArray1[13] != ushortTable.outArray[10]) || (ushortTable.inArray2[13] != ushortTable.outArray[11]) ||
(ushortTable.inArray1[14] != ushortTable.outArray[12]) || (ushortTable.inArray2[14] != ushortTable.outArray[13]) ||
(ushortTable.inArray1[15] != ushortTable.outArray[14]) || (ushortTable.inArray2[15] != ushortTable.outArray[15]))
{
Console.WriteLine("AVX2 UnpackHigh failed on ushort:");
Console.WriteLine($" left: ({string.Join(", ", byteTable.inArray1)})");
Console.WriteLine($" right: ({string.Join(", ", byteTable.inArray2)})");
Console.WriteLine($" result: ({string.Join(", ", byteTable.outArray)})");
Console.WriteLine();
testResult = Fail;
}
if ((intTable.inArray1[2] != intTable.outArray[0]) || (intTable.inArray2[2] != intTable.outArray[1]) ||
(intTable.inArray1[3] != intTable.outArray[2]) || (intTable.inArray2[3] != intTable.outArray[3]) ||
(intTable.inArray1[6] != intTable.outArray[4]) || (intTable.inArray2[6] != intTable.outArray[5]) ||
(intTable.inArray1[7] != intTable.outArray[6]) || (intTable.inArray2[7] != intTable.outArray[7]))
{
Console.WriteLine("AVX2 UnpackHigh failed on int:");
Console.WriteLine($" left: ({string.Join(", ", byteTable.inArray1)})");
Console.WriteLine($" right: ({string.Join(", ", byteTable.inArray2)})");
Console.WriteLine($" result: ({string.Join(", ", byteTable.outArray)})");
Console.WriteLine();
testResult = Fail;
}
if ((uintTable.inArray1[2] != uintTable.outArray[0]) || (uintTable.inArray2[2] != uintTable.outArray[1]) ||
(uintTable.inArray1[3] != uintTable.outArray[2]) || (uintTable.inArray2[3] != uintTable.outArray[3]) ||
(uintTable.inArray1[6] != uintTable.outArray[4]) || (uintTable.inArray2[6] != uintTable.outArray[5]) ||
(uintTable.inArray1[7] != uintTable.outArray[6]) || (uintTable.inArray2[7] != uintTable.outArray[7]))
{
Console.WriteLine("AVX2 UnpackHigh failed on uint:");
Console.WriteLine($" left: ({string.Join(", ", byteTable.inArray1)})");
Console.WriteLine($" right: ({string.Join(", ", byteTable.inArray2)})");
Console.WriteLine($" result: ({string.Join(", ", byteTable.outArray)})");
Console.WriteLine();
testResult = Fail;
}
if ((longTable.inArray1[1] != longTable.outArray[0]) || (longTable.inArray2[1] != longTable.outArray[1]) ||
(longTable.inArray1[3] != longTable.outArray[2]) || (longTable.inArray2[3] != longTable.outArray[3]) )
{
Console.WriteLine("AVX2 UnpackHigh failed on long:");
Console.WriteLine($" left: ({string.Join(", ", byteTable.inArray1)})");
Console.WriteLine($" right: ({string.Join(", ", byteTable.inArray2)})");
Console.WriteLine($" result: ({string.Join(", ", byteTable.outArray)})");
Console.WriteLine();
testResult = Fail;
}
if ((ulongTable.inArray1[1] != ulongTable.outArray[0]) || (ulongTable.inArray2[1] != ulongTable.outArray[1]) ||
(ulongTable.inArray1[3] != ulongTable.outArray[2]) || (ulongTable.inArray2[3] != ulongTable.outArray[3]) )
{
Console.WriteLine("AVX2 UnpackHigh failed on ulong:");
Console.WriteLine($" left: ({string.Join(", ", byteTable.inArray1)})");
Console.WriteLine($" right: ({string.Join(", ", byteTable.inArray2)})");
Console.WriteLine($" result: ({string.Join(", ", byteTable.outArray)})");
Console.WriteLine();
testResult = Fail;
}
}
}
return testResult;
}
public unsafe struct TestTable<T1, T2, T3> : IDisposable where T1 : struct where T2 : struct where T3 : struct
{
public T1[] inArray1;
public T2[] inArray2;
public T3[] outArray;
public void* inArray1Ptr => inHandle1.AddrOfPinnedObject().ToPointer();
public void* inArray2Ptr => inHandle2.AddrOfPinnedObject().ToPointer();
public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer();
GCHandle inHandle1;
GCHandle inHandle2;
GCHandle outHandle;
public TestTable(T1[] a, T2[] b, T3[] c)
{
this.inArray1 = a;
this.inArray2 = b;
this.outArray = c;
inHandle1 = GCHandle.Alloc(inArray1, GCHandleType.Pinned);
inHandle2 = GCHandle.Alloc(inArray2, GCHandleType.Pinned);
outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned);
}
public bool CheckResult(Func<T1, T2, T3, bool> check)
{
for (int i = 0; i < inArray1.Length; i++)
{
if (!check(inArray1[i], inArray2[i], outArray[i]))
{
return false;
}
}
return true;
}
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
}
}
}
| |
//
// LuaTable.cs
//
// Author:
// Chris Howie <me@chrishowie.com>
//
// Copyright (c) 2013 Chris Howie
//
// 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.Collections;
using System.Linq;
namespace Eluant
{
public class LuaTable : LuaReference, IDictionary<LuaValue, LuaValue>
{
public LuaTable Metatable
{
get
{
CheckDisposed();
var top = LuaApi.lua_gettop(Runtime.LuaState);
Runtime.Push(this);
LuaApi.lua_getmetatable(Runtime.LuaState, -1);
LuaValue val;
try
{
val = Runtime.Wrap(-1);
}
finally
{
LuaApi.lua_settop(Runtime.LuaState, top);
}
return val as LuaTable;
}
}
internal LuaTable(LuaRuntime runtime, int reference) : base(runtime, reference)
{
Keys = new KeyCollection(this);
Values = new ValueCollection(this);
}
public override bool ToBoolean()
{
return true;
}
public override double? ToNumber()
{
return null;
}
public override string ToString()
{
return "[LuaTable]";
}
public LuaValue this[LuaValue key] {
get {
CheckDisposed();
var top = LuaApi.lua_gettop(Runtime.LuaState);
Runtime.Push(this);
Runtime.Push(key);
LuaApi.lua_gettable(Runtime.LuaState, -2);
LuaValue val;
try {
val = Runtime.Wrap(-1);
} finally {
LuaApi.lua_settop(Runtime.LuaState, top);
}
return val;
}
set {
CheckDisposed();
// Lua allows one to query the nil index (always returning nil) but never to set it.
if (key.IsNil()) { throw new ArgumentNullException("key"); }
var top = LuaApi.lua_gettop(Runtime.LuaState);
Runtime.Push(this);
Runtime.Push(key);
Runtime.Push(value);
LuaApi.lua_settable(Runtime.LuaState, -3);
LuaApi.lua_settop(Runtime.LuaState, top);
}
}
new public LuaWeakReference<LuaTable> CreateWeakReference()
{
CheckDisposed();
return Runtime.CreateWeakReference(this);
}
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region IEnumerable implementation
public IEnumerator<KeyValuePair<LuaValue, LuaValue>> GetEnumerator()
{
CheckDisposed();
return new LuaTableEnumerator(this);
}
#endregion
#region ICollection implementation
void ICollection<KeyValuePair<LuaValue, LuaValue>>.Add(KeyValuePair<LuaValue, LuaValue> item)
{
CheckDisposed();
Add(item.Key, item.Value);
}
public void Clear()
{
CheckDisposed();
Runtime.Push(this);
// Go over each key and remove it until the table is empty.
for (;;) {
LuaApi.lua_pushnil(Runtime.LuaState);
if (LuaApi.lua_next(Runtime.LuaState, -2) == 0) {
// Table is empty.
LuaApi.lua_pop(Runtime.LuaState, 1);
break;
}
// Replace the value with nil and set the key.
LuaApi.lua_pop(Runtime.LuaState, 1);
LuaApi.lua_pushnil(Runtime.LuaState);
LuaApi.lua_settable(Runtime.LuaState, -3);
// Next iteration will start from the next key by using a nil key again.
}
}
public bool Contains(KeyValuePair<LuaValue, LuaValue> item)
{
CheckDisposed();
using (var v = this[item.Key]) {
return v.Equals(item.Value);
}
}
public void CopyTo(KeyValuePair<LuaValue, LuaValue>[] array, int arrayIndex)
{
CheckDisposed();
foreach (var p in this) {
array[arrayIndex++] = p;
}
}
public bool Remove(KeyValuePair<LuaValue, LuaValue> item)
{
CheckDisposed();
using (var v = this[item.Key]) {
if (v.Equals(item.Key)) {
return Remove(item.Key);
}
}
return false;
}
public int Count
{
get {
CheckDisposed();
// Lua provides no way to retrieve the number of items in a table short of iterating the whole thing. :(
int count = 0;
Runtime.Push(this);
LuaApi.lua_pushnil(Runtime.LuaState);
while (LuaApi.lua_next(Runtime.LuaState, -2) != 0) {
++count;
LuaApi.lua_pop(Runtime.LuaState, 1);
}
LuaApi.lua_pop(Runtime.LuaState, 1);
return count;
}
}
bool ICollection<KeyValuePair<LuaValue, LuaValue>>.IsReadOnly
{
get { return false; }
}
#endregion
#region IDictionary implementation
public void Add(LuaValue key, LuaValue value)
{
CheckDisposed();
if (key.IsNil()) { throw new ArgumentNullException("key"); }
Runtime.Push(this);
Runtime.Push(key);
LuaApi.lua_gettable(Runtime.LuaState, -2);
if (LuaApi.lua_type(Runtime.LuaState, -1) != LuaApi.LuaType.Nil) {
// Slot is occupied.
LuaApi.lua_pop(Runtime.LuaState, 2);
throw new ArgumentException("Table already contains given key.", "key");
}
// Slot is unoccupied. Leave the nil there for now, we'll pop ALL the things at the end.
Runtime.Push(key);
Runtime.Push(value);
LuaApi.lua_settable(Runtime.LuaState, -4);
// Pop table and nil value.
LuaApi.lua_pop(Runtime.LuaState, 2);
}
public bool ContainsKey(LuaValue key)
{
CheckDisposed();
using (var v = this[key]) {
return !v.IsNil();
}
}
public bool Remove(LuaValue key)
{
// Wouldn't it be nice to do this?
// this[key] = null;
//
// But we can't, since we have to return true if the item existed. :(
// However, we can fast-fail if the key is nil.
if (key.IsNil()) { return false; }
// this[] will CheckDisposed()
using (var v = this[key]) {
if (v.IsNil()) {
return false;
}
}
this[key] = null;
return true;
}
public bool TryGetValue(LuaValue key, out LuaValue value)
{
// This is tricky... since this[] never throws but instead returns nil, what do we do here? I think that
// it's still a good idea to return false here.
//
// Thankfully, the indexer makes this really easy to implement.
value = this[key];
return !value.IsNil();
}
public ICollection<LuaValue> Keys { get; private set; }
public ICollection<LuaValue> Values { get; private set; }
#endregion
private class LuaTableEnumerator : IEnumerator<KeyValuePair<LuaValue, LuaValue>>
{
private LuaTable table;
private bool atEnd = false;
private LuaValue currentKey;
private KeyValuePair<LuaValue, LuaValue> current;
internal LuaTableEnumerator(LuaTable table)
{
this.table = table;
}
private void CheckDisposed()
{
if (table == null) { throw new ObjectDisposedException(GetType().FullName); }
table.CheckDisposed();
}
#region IDisposable implementation
public void Dispose()
{
table = null;
if (currentKey != null) {
currentKey.Dispose();
currentKey = null;
}
current = new KeyValuePair<LuaValue, LuaValue>();
}
#endregion
#region IEnumerator implementation
public bool MoveNext()
{
CheckDisposed();
// Fast-fail if we reached the end previously.
if (atEnd) { return false; }
var runtime = table.Runtime;
runtime.Push(table);
// Will push nil on first iteration, which is exactly what lua_next() expects.
runtime.Push(currentKey);
if (LuaApi.lua_next(runtime.LuaState, -2) == 0) {
// At the end, so only the table is on the stack now.
atEnd = true;
LuaApi.lua_pop(runtime.LuaState, 1);
return false;
}
var newValue = runtime.Wrap(-1);
var newKey = runtime.Wrap(-2);
current = new KeyValuePair<LuaValue, LuaValue>(newKey, newValue);
if (currentKey != null) {
currentKey.Dispose();
}
currentKey = current.Key.CopyReference();
LuaApi.lua_pop(runtime.LuaState, 3);
return true;
}
public void Reset()
{
CheckDisposed();
atEnd = false;
if (currentKey != null) {
currentKey.Dispose();
currentKey = null;
}
current = new KeyValuePair<LuaValue, LuaValue>();
}
object IEnumerator.Current
{
get {
CheckDisposed();
return current;
}
}
#endregion
#region IEnumerator implementation
public KeyValuePair<LuaValue, LuaValue> Current
{
get {
CheckDisposed();
return current;
}
}
#endregion
}
private abstract class LuaValueCollection : ICollection<LuaValue>
{
protected LuaTable Table { get; private set; }
internal LuaValueCollection(LuaTable table)
{
Table = table;
}
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region IEnumerable implementation
public IEnumerator<LuaValue> GetEnumerator()
{
return Table.Select(pair => GetValueFromPair(pair)).GetEnumerator();
}
#endregion
#region ICollection implementation
public void Add(LuaValue item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public abstract bool Contains(LuaValue item);
public void CopyTo(LuaValue[] array, int arrayIndex)
{
foreach (var pair in Table) {
array[arrayIndex++] = GetValueFromPair(pair);
}
}
public bool Remove(LuaValue item)
{
throw new NotSupportedException();
}
public int Count
{
get { return Table.Count; }
}
public bool IsReadOnly
{
get { return true; }
}
#endregion
protected abstract LuaValue GetValueFromPair(KeyValuePair<LuaValue, LuaValue> pair);
}
private class KeyCollection : LuaValueCollection
{
internal KeyCollection(LuaTable table) : base(table) { }
public override bool Contains(LuaValue item)
{
return Table.ContainsKey(item);
}
protected override LuaValue GetValueFromPair(KeyValuePair<LuaValue, LuaValue> pair)
{
return pair.Key;
}
}
private class ValueCollection : LuaValueCollection
{
internal ValueCollection(LuaTable table) : base(table) { }
public override bool Contains(LuaValue item)
{
bool found;
foreach (var pair in Table) {
found = pair.Value.Equals(item);
pair.Dispose();
if (found) { return true; }
}
return false;
}
protected override LuaValue GetValueFromPair(KeyValuePair<LuaValue, LuaValue> pair)
{
return pair.Value;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Monitor.Fluent
{
using Microsoft.Azure.Management.Monitor.Fluent.ActivityLogAlert.Definition;
using Microsoft.Azure.Management.Monitor.Fluent.ActivityLogAlert.Update;
using Microsoft.Azure.Management.Monitor.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Implementation for ActivityLogAlert.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50Lm1vbml0b3IuaW1wbGVtZW50YXRpb24uQWN0aXZpdHlMb2dBbGVydEltcGw=
internal partial class ActivityLogAlertImpl :
GroupableResource<
IActivityLogAlert,
ActivityLogAlertResourceInner,
ActivityLogAlertImpl,
MonitorManager,
ActivityLogAlert.Definition.IBlank,
ActivityLogAlert.Definition.IWithScopes,
ActivityLogAlert.Definition.IWithCreate,
ActivityLogAlert.Update.IUpdate>,
IActivityLogAlert,
IDefinition,
IUpdate,
IWithActivityLogUpdate
{
private Dictionary<string, string> conditions;
///GENMHASH:BB950CA14FF4F1F69C522AF91F90FC34:408D5FE696EAF2806ED2D70B7393F055
internal ActivityLogAlertImpl(string name, ActivityLogAlertResourceInner innerModel, MonitorManager monitorManager)
: base(name, innerModel, monitorManager)
{
this.conditions = new Dictionary<string, string>();
if (innerModel.Condition != null && innerModel.Condition.AllOf != null)
{
foreach (var aac in innerModel.Condition.AllOf)
{
this.conditions[aac.Field] = aac.EqualsTo;
}
}
}
///GENMHASH:5AD91481A0966B059A478CD4E9DD9466:1DCFF5A76BE07CD1A05C937F9EDA2875
protected override async Task<Models.ActivityLogAlertResourceInner> GetInnerAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return await this.Manager.Inner.ActivityLogAlerts.GetAsync(this.ResourceGroupName, this.Name, cancellationToken);
}
///GENMHASH:66DC6CE2AC9BE61B5E666402EB693221:5E24241966A03424F2E45A8D9C85B7E3
public IReadOnlyCollection<string> ActionGroupIds()
{
var ids = new List<string>();
if (this.Inner.Actions != null && this.Inner.Actions.ActionGroups != null)
{
foreach (var alaag in this.Inner.Actions.ActionGroups)
{
ids.Add(alaag.ActionGroupId);
}
}
return ids;
}
///GENMHASH:0202A00A1DCF248D2647DBDBEF2CA865:9B7B9E01CD94CAAB45F3A60AA8B80787
public override async Task<Microsoft.Azure.Management.Monitor.Fluent.IActivityLogAlert> CreateResourceAsync(CancellationToken cancellationToken = default(CancellationToken))
{
this.Inner.Location = "global";
var condition = new ActivityLogAlertAllOfCondition();
condition.AllOf = new List<ActivityLogAlertLeafCondition>();
foreach (var cds in conditions)
{
var alalc = new ActivityLogAlertLeafCondition();
alalc.Field = cds.Key;
alalc.EqualsTo = cds.Value;
condition.AllOf.Add(alalc);
}
this.Inner.Condition = condition;
this.SetInner(await this.Manager.Inner.ActivityLogAlerts.CreateOrUpdateAsync(this.ResourceGroupName, this.Name, this.Inner, cancellationToken));
return this;
}
///GENMHASH:7B3CA3D467253D93C6FF7587C3C0D0B7:F5293CC540B22E551BB92F6FCE17DE2C
public string Description()
{
return this.Inner.Description;
}
///GENMHASH:1703877FCECC33D73EA04EEEF89045EF:EB71563FB99F270D0827FDCDA083A584
public bool Enabled()
{
return (this.Inner.Enabled.HasValue == false) ? false : this.Inner.Enabled.Value;
}
///GENMHASH:98F3CB7FC44C6127EC66A44A86617755:C847040A726E35E60A000ACD7F24E314
public IReadOnlyDictionary<string, string> EqualsConditions()
{
return this.conditions;
}
///GENMHASH:C457EEA978B7A6C6C56D90DDF5271FFB:82059B9BE2545D9387D9EA1B5A801869
public IReadOnlyCollection<string> Scopes()
{
return this.Inner.Scopes.ToList();
}
///GENMHASH:8251517CD3DB23FD0217AD932D86E975:C86469D57481319F5A214F5EC8087A9A
public ActivityLogAlertImpl WithActionGroups(params string[] actionGroupId)
{
if (this.Inner.Actions == null)
{
this.Inner.Actions = new ActivityLogAlertActionList();
this.Inner.Actions.ActionGroups = new List<ActivityLogAlertActionGroup>();
}
this.Inner.Actions.ActionGroups.Clear();
foreach (var agid in actionGroupId)
{
var aaa = new ActivityLogAlertActionGroup();
aaa.ActionGroupId = agid;
this.Inner.Actions.ActionGroups.Add(aaa);
}
return this;
}
///GENMHASH:016764F09D1966D691B5DE3A7FD47AC9:5D67BF1D9DA1008F878F13C112FF5F35
public ActivityLogAlertImpl WithDescription(string description)
{
this.Inner.Description = description;
return this;
}
///GENMHASH:1A83DF7BBE2B0E999F6ABB21FE550BDC:D499B9B549494173D48F5774E68D385F
public ActivityLogAlertImpl WithEqualsCondition(string field, string equals)
{
this.WithoutEqualsCondition(field);
this.conditions[field] = equals;
return this;
}
///GENMHASH:012586BEA031ABB7E8D7DA7C5407D11D:5CD188D9DC123B8EF062D3406B1366C7
public ActivityLogAlertImpl WithEqualsConditions(IDictionary<string, string> fieldEqualsMap)
{
this.conditions.Clear();
foreach (var kvPair in fieldEqualsMap)
{
this.conditions.Add(kvPair.Key, kvPair.Value);
}
return this;
}
///GENMHASH:ED05B641BBACDA0FE20CB8084C06E215:7D2C8F9251DDB86FA30AE515EE6BAA94
public ActivityLogAlertImpl WithoutActionGroup(string actionGroupId)
{
if (this.Inner.Actions != null && this.Inner.Actions.ActionGroups != null)
{
var toDelete = new List<ActivityLogAlertActionGroup>();
foreach (var aaa in this.Inner.Actions.ActionGroups)
{
if (aaa.ActionGroupId.Equals(actionGroupId, System.StringComparison.OrdinalIgnoreCase))
{
toDelete.Add(aaa);
}
}
foreach (var aaa in toDelete)
{
this.Inner.Actions.ActionGroups.Remove(aaa);
}
}
return this;
}
///GENMHASH:237AE1DD2F36D83D699F312F5527B0A4:BD960AA3B170F286E76A114183EF968A
public ActivityLogAlertImpl WithoutEqualsCondition(string field)
{
if (this.conditions.ContainsKey(field))
{
this.conditions.Remove(field);
}
return this;
}
///GENMHASH:19D591A5811CC295B77719A40CEB3F64:9A4882A827B87B926799484B506DA9A3
public ActivityLogAlertImpl WithRuleDisabled()
{
this.Inner.Enabled = false;
return this;
}
///GENMHASH:1952D7AE67830F92010B1423D9533A88:B605F0C6D20484DEA14055C58519B8C8
public ActivityLogAlertImpl WithRuleEnabled()
{
this.Inner.Enabled = true;
return this;
}
///GENMHASH:21C5E913CC99F20E7CFF02057B43ED9D:252983E9D051F9EAAC0EB5276C560315
public ActivityLogAlertImpl WithTargetResource(string resourceId)
{
this.Inner.Scopes = new List<string>();
this.Inner.Scopes.Add(resourceId);
return this;
}
///GENMHASH:FF34A220CBD022BF5822C4584DEEE94E:A6098866C47E7A7E582B09209AD5C53E
public ActivityLogAlertImpl WithTargetResource(IHasId resource)
{
return this.WithTargetResource(resource.Id);
}
///GENMHASH:F4B0D12B9C1C3B68E6A05E465C7B1E57:5956998ECA780A89CC7DB7F37D0036EB
public ActivityLogAlertImpl WithTargetSubscription(string targetSubscriptionId)
{
return this.WithTargetResource("/subscriptions/" + targetSubscriptionId);
}
}
}
| |
// 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.Globalization;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.ExceptionServices;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Threading;
namespace System.Net.Mail
{
internal partial class SmtpConnection
{
private static readonly ContextCallback s_AuthenticateCallback = new ContextCallback(AuthenticateCallback);
private BufferBuilder _bufferBuilder = new BufferBuilder();
private bool _isConnected;
private bool _isClosed;
private bool _isStreamOpen;
private EventHandler _onCloseHandler;
internal SmtpTransport _parent;
private SmtpClient _client;
private NetworkStream _networkStream;
internal TcpClient _tcpClient;
internal string _host = null;
internal int _port = 0;
private SmtpReplyReaderFactory _responseReader;
private ICredentialsByHost _credentials;
private int _timeout = 100000;
private string[] _extensions;
private ChannelBinding _channelBindingToken = null;
private bool _enableSsl;
private X509CertificateCollection _clientCertificates;
internal SmtpConnection(SmtpTransport parent, SmtpClient client, ICredentialsByHost credentials, ISmtpAuthenticationModule[] authenticationModules)
{
_client = client;
_credentials = credentials;
_authenticationModules = authenticationModules;
_parent = parent;
_tcpClient = new TcpClient();
_onCloseHandler = new EventHandler(OnClose);
}
internal BufferBuilder BufferBuilder => _bufferBuilder;
internal bool IsConnected => _isConnected;
internal bool IsStreamOpen => _isStreamOpen;
internal SmtpReplyReaderFactory Reader => _responseReader;
internal bool EnableSsl
{
get
{
return _enableSsl;
}
set
{
_enableSsl = value;
}
}
internal int Timeout
{
get
{
return _timeout;
}
set
{
_timeout = value;
}
}
internal X509CertificateCollection ClientCertificates
{
get
{
return _clientCertificates;
}
set
{
_clientCertificates = value;
}
}
internal void InitializeConnection(string host, int port)
{
_tcpClient.Connect(host, port);
_networkStream = _tcpClient.GetStream();
}
internal IAsyncResult BeginInitializeConnection(string host, int port, AsyncCallback callback, object state)
{
return _tcpClient.BeginConnect(host, port, callback, state);
}
internal void EndInitializeConnection(IAsyncResult result)
{
_tcpClient.EndConnect(result);
_networkStream = _tcpClient.GetStream();
}
internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback callback, object state, string host, int port)
{
ConnectAndHandshakeAsyncResult result = new ConnectAndHandshakeAsyncResult(this, host, port, outerResult, callback, state);
result.GetConnection();
return result;
}
internal IAsyncResult BeginFlush(AsyncCallback callback, object state)
{
return _networkStream.BeginWrite(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length, callback, state);
}
internal void EndFlush(IAsyncResult result)
{
_networkStream.EndWrite(result);
_bufferBuilder.Reset();
}
internal void Flush()
{
_networkStream.Write(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length);
_bufferBuilder.Reset();
}
internal void ReleaseConnection()
{
if (!_isClosed)
{
lock (this)
{
if (!_isClosed && _tcpClient != null)
{
//free cbt buffer
if (_channelBindingToken != null)
{
_channelBindingToken.Close();
}
_networkStream?.Close();
_tcpClient.Dispose();
}
_isClosed = true;
}
}
_isConnected = false;
}
internal void Abort()
{
if (!_isClosed)
{
lock (this)
{
if (!_isClosed && _tcpClient != null)
{
//free CBT buffer
if (_channelBindingToken != null)
{
_channelBindingToken.Close();
}
// must destroy manually since sending a QUIT here might not be
// interpreted correctly by the server if it's in the middle of a
// DATA command or some similar situation. This may send a RST
// but this is ok in this situation. Do not reuse this connection
_tcpClient.LingerState = new LingerOption(true, 0);
_networkStream.Close();
_tcpClient.Dispose();
}
_isClosed = true;
}
}
_isConnected = false;
}
internal void GetConnection(string host, int port)
{
if (_isConnected)
{
throw new InvalidOperationException(SR.SmtpAlreadyConnected);
}
InitializeConnection(host, port);
_responseReader = new SmtpReplyReaderFactory(_networkStream);
LineInfo info = _responseReader.GetNextReplyReader().ReadLine();
switch (info.StatusCode)
{
case SmtpStatusCode.ServiceReady:
break;
default:
throw new SmtpException(info.StatusCode, info.Line, true);
}
try
{
_extensions = EHelloCommand.Send(this, _client.clientDomain);
ParseExtensions(_extensions);
}
catch (SmtpException e)
{
if ((e.StatusCode != SmtpStatusCode.CommandUnrecognized)
&& (e.StatusCode != SmtpStatusCode.CommandNotImplemented))
{
throw;
}
HelloCommand.Send(this, _client.clientDomain);
//if ehello isn't supported, assume basic login
_supportedAuth = SupportedAuth.Login;
}
if (_enableSsl)
{
if (!_serverSupportsStartTls)
{
// Either TLS is already established or server does not support TLS
if (!(_networkStream is TlsStream))
{
throw new SmtpException(SR.MailServerDoesNotSupportStartTls);
}
}
StartTlsCommand.Send(this);
TlsStream tlsStream = new TlsStream(_networkStream, _tcpClient.Client, host, _clientCertificates);
tlsStream.AuthenticateAsClient();
_networkStream = tlsStream;
_responseReader = new SmtpReplyReaderFactory(_networkStream);
// According to RFC 3207: The client SHOULD send an EHLO command
// as the first command after a successful TLS negotiation.
_extensions = EHelloCommand.Send(this, _client.clientDomain);
ParseExtensions(_extensions);
}
// if no credentials were supplied, try anonymous
// servers don't appear to anounce that they support anonymous login.
if (_credentials != null)
{
for (int i = 0; i < _authenticationModules.Length; i++)
{
//only authenticate if the auth protocol is supported - chadmu
if (!AuthSupported(_authenticationModules[i]))
{
continue;
}
NetworkCredential credential = _credentials.GetCredential(host, port, _authenticationModules[i].AuthenticationType);
if (credential == null)
continue;
Authorization auth = SetContextAndTryAuthenticate(_authenticationModules[i], credential, null);
if (auth != null && auth.Message != null)
{
info = AuthCommand.Send(this, _authenticationModules[i].AuthenticationType, auth.Message);
if (info.StatusCode == SmtpStatusCode.CommandParameterNotImplemented)
{
continue;
}
while ((int)info.StatusCode == 334)
{
auth = _authenticationModules[i].Authenticate(info.Line, null, this, _client.TargetName, _channelBindingToken);
if (auth == null)
{
throw new SmtpException(SR.SmtpAuthenticationFailed);
}
info = AuthCommand.Send(this, auth.Message);
if ((int)info.StatusCode == 235)
{
_authenticationModules[i].CloseContext(this);
_isConnected = true;
return;
}
}
}
}
}
_isConnected = true;
}
private Authorization SetContextAndTryAuthenticate(ISmtpAuthenticationModule module, NetworkCredential credential, ContextAwareResult context)
{
// We may need to restore user thread token here
if (ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials))
{
#if DEBUG
if (context != null && !context.IdentityRequested)
{
NetEventSource.Fail(this, "Authentication required when it wasn't expected. (Maybe Credentials was changed on another thread?)");
}
#endif
try
{
ExecutionContext x = context == null ? null : context.ContextCopy;
if (x != null)
{
AuthenticateCallbackContext authenticationContext =
new AuthenticateCallbackContext(this, module, credential, _client.TargetName, _channelBindingToken);
ExecutionContext.Run(x, s_AuthenticateCallback, authenticationContext);
return authenticationContext._result;
}
else
{
return module.Authenticate(null, credential, this, _client.TargetName, _channelBindingToken);
}
}
catch
{
// Prevent the impersonation from leaking to upstack exception filters.
throw;
}
}
return module.Authenticate(null, credential, this, _client.TargetName, _channelBindingToken);
}
private static void AuthenticateCallback(object state)
{
AuthenticateCallbackContext context = (AuthenticateCallbackContext)state;
context._result = context._module.Authenticate(null, context._credential, context._thisPtr, context._spn, context._token);
}
private class AuthenticateCallbackContext
{
internal AuthenticateCallbackContext(SmtpConnection thisPtr, ISmtpAuthenticationModule module, NetworkCredential credential, string spn, ChannelBinding Token)
{
_thisPtr = thisPtr;
_module = module;
_credential = credential;
_spn = spn;
_token = Token;
_result = null;
}
internal readonly SmtpConnection _thisPtr;
internal readonly ISmtpAuthenticationModule _module;
internal readonly NetworkCredential _credential;
internal readonly string _spn;
internal readonly ChannelBinding _token;
internal Authorization _result;
}
internal void EndGetConnection(IAsyncResult result)
{
ConnectAndHandshakeAsyncResult.End(result);
}
internal Stream GetClosableStream()
{
ClosableStream cs = new ClosableStream(_networkStream, _onCloseHandler);
_isStreamOpen = true;
return cs;
}
private void OnClose(object sender, EventArgs args)
{
_isStreamOpen = false;
DataStopCommand.Send(this);
}
private class ConnectAndHandshakeAsyncResult : LazyAsyncResult
{
private string _authResponse;
private SmtpConnection _connection;
private int _currentModule = -1;
private int _port;
private static AsyncCallback s_handshakeCallback = new AsyncCallback(HandshakeCallback);
private static AsyncCallback s_sendEHelloCallback = new AsyncCallback(SendEHelloCallback);
private static AsyncCallback s_sendHelloCallback = new AsyncCallback(SendHelloCallback);
private static AsyncCallback s_authenticateCallback = new AsyncCallback(AuthenticateCallback);
private static AsyncCallback s_authenticateContinueCallback = new AsyncCallback(AuthenticateContinueCallback);
private string _host;
private readonly ContextAwareResult _outerResult;
internal ConnectAndHandshakeAsyncResult(SmtpConnection connection, string host, int port, ContextAwareResult outerResult, AsyncCallback callback, object state) :
base(null, state, callback)
{
_connection = connection;
_host = host;
_port = port;
_outerResult = outerResult;
}
internal static void End(IAsyncResult result)
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result;
object connectResult = thisPtr.InternalWaitForCompletion();
if (connectResult is Exception e)
{
ExceptionDispatchInfo.Throw(e);
}
}
internal void GetConnection()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (_connection._isConnected)
{
throw new InvalidOperationException(SR.SmtpAlreadyConnected);
}
InitializeConnection();
}
private void InitializeConnection()
{
IAsyncResult result = _connection.BeginInitializeConnection(_host, _port, InitializeConnectionCallback, this);
if (result.CompletedSynchronously)
{
try
{
_connection.EndInitializeConnection(result);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Connect returned");
Handshake();
}
catch (Exception e)
{
InvokeCallback(e);
}
}
}
private static void InitializeConnectionCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
try
{
thisPtr._connection.EndInitializeConnection(result);
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Connect returned {thisPtr}");
thisPtr.Handshake();
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
private void Handshake()
{
_connection._responseReader = new SmtpReplyReaderFactory(_connection._networkStream);
SmtpReplyReader reader = _connection.Reader.GetNextReplyReader();
IAsyncResult result = reader.BeginReadLine(s_handshakeCallback, this);
if (!result.CompletedSynchronously)
{
return;
}
LineInfo info = reader.EndReadLine(result);
if (info.StatusCode != SmtpStatusCode.ServiceReady)
{
throw new SmtpException(info.StatusCode, info.Line, true);
}
try
{
if (!SendEHello())
{
return;
}
}
catch
{
if (!SendHello())
{
return;
}
}
}
private static void HandshakeCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
try
{
try
{
LineInfo info = thisPtr._connection.Reader.CurrentReader.EndReadLine(result);
if (info.StatusCode != SmtpStatusCode.ServiceReady)
{
thisPtr.InvokeCallback(new SmtpException(info.StatusCode, info.Line, true));
return;
}
if (!thisPtr.SendEHello())
{
return;
}
}
catch (SmtpException)
{
if (!thisPtr.SendHello())
{
return;
}
}
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
private bool SendEHello()
{
IAsyncResult result = EHelloCommand.BeginSend(_connection, _connection._client.clientDomain, s_sendEHelloCallback, this);
if (result.CompletedSynchronously)
{
_connection._extensions = EHelloCommand.EndSend(result);
_connection.ParseExtensions(_connection._extensions);
// If we already have a TlsStream, this is the second EHLO cmd
// that we sent after TLS handshake compelted. So skip TLS and
// continue with Authenticate.
if (_connection._networkStream is TlsStream)
{
Authenticate();
return true;
}
if (_connection.EnableSsl)
{
if (!_connection._serverSupportsStartTls)
{
// Either TLS is already established or server does not support TLS
if (!(_connection._networkStream is TlsStream))
{
throw new SmtpException(SR.Format(SR.MailServerDoesNotSupportStartTls));
}
}
SendStartTls();
}
else
{
Authenticate();
}
return true;
}
return false;
}
private static void SendEHelloCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
try
{
try
{
thisPtr._connection._extensions = EHelloCommand.EndSend(result);
thisPtr._connection.ParseExtensions(thisPtr._connection._extensions);
// If we already have a SSlStream, this is the second EHLO cmd
// that we sent after TLS handshake compelted. So skip TLS and
// continue with Authenticate.
if (thisPtr._connection._networkStream is TlsStream)
{
thisPtr.Authenticate();
return;
}
}
catch (SmtpException e)
{
if ((e.StatusCode != SmtpStatusCode.CommandUnrecognized)
&& (e.StatusCode != SmtpStatusCode.CommandNotImplemented))
{
throw;
}
if (!thisPtr.SendHello())
{
return;
}
}
if (thisPtr._connection.EnableSsl)
{
if (!thisPtr._connection._serverSupportsStartTls)
{
// Either TLS is already established or server does not support TLS
if (!(thisPtr._connection._networkStream is TlsStream))
{
throw new SmtpException(SR.MailServerDoesNotSupportStartTls);
}
}
thisPtr.SendStartTls();
}
else
{
thisPtr.Authenticate();
}
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
private bool SendHello()
{
IAsyncResult result = HelloCommand.BeginSend(_connection, _connection._client.clientDomain, s_sendHelloCallback, this);
//if ehello isn't supported, assume basic auth
if (result.CompletedSynchronously)
{
_connection._supportedAuth = SupportedAuth.Login;
HelloCommand.EndSend(result);
Authenticate();
return true;
}
return false;
}
private static void SendHelloCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
try
{
HelloCommand.EndSend(result);
thisPtr.Authenticate();
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
private bool SendStartTls()
{
IAsyncResult result = StartTlsCommand.BeginSend(_connection, SendStartTlsCallback, this);
if (result.CompletedSynchronously)
{
StartTlsCommand.EndSend(result);
TlsStreamAuthenticate();
return true;
}
return false;
}
private static void SendStartTlsCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
try
{
StartTlsCommand.EndSend(result);
thisPtr.TlsStreamAuthenticate();
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
private bool TlsStreamAuthenticate()
{
_connection._networkStream = new TlsStream(_connection._networkStream, _connection._tcpClient.Client, _host, _connection._clientCertificates);
IAsyncResult result = (_connection._networkStream as TlsStream).BeginAuthenticateAsClient(TlsStreamAuthenticateCallback, this);
if (result.CompletedSynchronously)
{
(_connection._networkStream as TlsStream).EndAuthenticateAsClient(result);
_connection._responseReader = new SmtpReplyReaderFactory(_connection._networkStream);
SendEHello();
return true;
}
return false;
}
private static void TlsStreamAuthenticateCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
try
{
(thisPtr._connection._networkStream as TlsStream).EndAuthenticateAsClient(result);
thisPtr._connection._responseReader = new SmtpReplyReaderFactory(thisPtr._connection._networkStream);
thisPtr.SendEHello();
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
private void Authenticate()
{
//if no credentials were supplied, try anonymous
//servers don't appear to anounce that they support anonymous login.
if (_connection._credentials != null)
{
while (++_currentModule < _connection._authenticationModules.Length)
{
//only authenticate if the auth protocol is supported
ISmtpAuthenticationModule module = _connection._authenticationModules[_currentModule];
if (!_connection.AuthSupported(module))
{
continue;
}
NetworkCredential credential = _connection._credentials.GetCredential(_host, _port, module.AuthenticationType);
if (credential == null)
continue;
Authorization auth = _connection.SetContextAndTryAuthenticate(module, credential, _outerResult);
if (auth != null && auth.Message != null)
{
IAsyncResult result = AuthCommand.BeginSend(_connection, _connection._authenticationModules[_currentModule].AuthenticationType, auth.Message, s_authenticateCallback, this);
if (!result.CompletedSynchronously)
{
return;
}
LineInfo info = AuthCommand.EndSend(result);
if ((int)info.StatusCode == 334)
{
_authResponse = info.Line;
if (!AuthenticateContinue())
{
return;
}
}
else if ((int)info.StatusCode == 235)
{
module.CloseContext(_connection);
_connection._isConnected = true;
break;
}
}
}
}
_connection._isConnected = true;
InvokeCallback();
}
private static void AuthenticateCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
try
{
LineInfo info = AuthCommand.EndSend(result);
if ((int)info.StatusCode == 334)
{
thisPtr._authResponse = info.Line;
if (!thisPtr.AuthenticateContinue())
{
return;
}
}
else if ((int)info.StatusCode == 235)
{
thisPtr._connection._authenticationModules[thisPtr._currentModule].CloseContext(thisPtr._connection);
thisPtr._connection._isConnected = true;
thisPtr.InvokeCallback();
return;
}
thisPtr.Authenticate();
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
private bool AuthenticateContinue()
{
for (;;)
{
// We don't need credential on the continued auth assuming they were captured on the first call.
// That should always work, otherwise what if a new credential has been returned?
Authorization auth = _connection._authenticationModules[_currentModule].Authenticate(_authResponse, null, _connection, _connection._client.TargetName, _connection._channelBindingToken);
if (auth == null)
{
throw new SmtpException(SR.Format(SR.SmtpAuthenticationFailed));
}
IAsyncResult result = AuthCommand.BeginSend(_connection, auth.Message, s_authenticateContinueCallback, this);
if (!result.CompletedSynchronously)
{
return false;
}
LineInfo info = AuthCommand.EndSend(result);
if ((int)info.StatusCode == 235)
{
_connection._authenticationModules[_currentModule].CloseContext(_connection);
_connection._isConnected = true;
InvokeCallback();
return false;
}
else if ((int)info.StatusCode != 334)
{
return true;
}
_authResponse = info.Line;
}
}
private static void AuthenticateContinueCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
try
{
LineInfo info = AuthCommand.EndSend(result);
if ((int)info.StatusCode == 235)
{
thisPtr._connection._authenticationModules[thisPtr._currentModule].CloseContext(thisPtr._connection);
thisPtr._connection._isConnected = true;
thisPtr.InvokeCallback();
return;
}
else if ((int)info.StatusCode == 334)
{
thisPtr._authResponse = info.Line;
if (!thisPtr.AuthenticateContinue())
{
return;
}
}
thisPtr.Authenticate();
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
}
}
}
| |
// 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!
namespace Google.Cloud.Compute.V1.Snippets
{
using Google.Api.Gax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using lro = Google.LongRunning;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedResourcePoliciesClientSnippets
{
/// <summary>Snippet for AggregatedList</summary>
public void AggregatedListRequestObject()
{
// Snippet: AggregatedList(AggregatedListResourcePoliciesRequest, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.Create();
// Initialize request argument(s)
AggregatedListResourcePoliciesRequest request = new AggregatedListResourcePoliciesRequest
{
OrderBy = "",
Project = "",
Filter = "",
IncludeAllScopes = false,
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<ResourcePolicyAggregatedList, KeyValuePair<string, ResourcePoliciesScopedList>> response = resourcePoliciesClient.AggregatedList(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (KeyValuePair<string, ResourcePoliciesScopedList> item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ResourcePolicyAggregatedList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, ResourcePoliciesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, ResourcePoliciesScopedList>> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, ResourcePoliciesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListAsync</summary>
public async Task AggregatedListRequestObjectAsync()
{
// Snippet: AggregatedListAsync(AggregatedListResourcePoliciesRequest, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = await ResourcePoliciesClient.CreateAsync();
// Initialize request argument(s)
AggregatedListResourcePoliciesRequest request = new AggregatedListResourcePoliciesRequest
{
OrderBy = "",
Project = "",
Filter = "",
IncludeAllScopes = false,
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<ResourcePolicyAggregatedList, KeyValuePair<string, ResourcePoliciesScopedList>> response = resourcePoliciesClient.AggregatedListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((KeyValuePair<string, ResourcePoliciesScopedList> item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ResourcePolicyAggregatedList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, ResourcePoliciesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, ResourcePoliciesScopedList>> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, ResourcePoliciesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedList</summary>
public void AggregatedList()
{
// Snippet: AggregatedList(string, string, int?, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
PagedEnumerable<ResourcePolicyAggregatedList, KeyValuePair<string, ResourcePoliciesScopedList>> response = resourcePoliciesClient.AggregatedList(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (KeyValuePair<string, ResourcePoliciesScopedList> item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ResourcePolicyAggregatedList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, ResourcePoliciesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, ResourcePoliciesScopedList>> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, ResourcePoliciesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListAsync</summary>
public async Task AggregatedListAsync()
{
// Snippet: AggregatedListAsync(string, string, int?, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = await ResourcePoliciesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
PagedAsyncEnumerable<ResourcePolicyAggregatedList, KeyValuePair<string, ResourcePoliciesScopedList>> response = resourcePoliciesClient.AggregatedListAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((KeyValuePair<string, ResourcePoliciesScopedList> item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ResourcePolicyAggregatedList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, ResourcePoliciesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, ResourcePoliciesScopedList>> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, ResourcePoliciesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void DeleteRequestObject()
{
// Snippet: Delete(DeleteResourcePolicyRequest, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.Create();
// Initialize request argument(s)
DeleteResourcePolicyRequest request = new DeleteResourcePolicyRequest
{
RequestId = "",
Region = "",
ResourcePolicy = "",
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = resourcePoliciesClient.Delete(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = resourcePoliciesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteRequestObjectAsync()
{
// Snippet: DeleteAsync(DeleteResourcePolicyRequest, CallSettings)
// Additional: DeleteAsync(DeleteResourcePolicyRequest, CancellationToken)
// Create client
ResourcePoliciesClient resourcePoliciesClient = await ResourcePoliciesClient.CreateAsync();
// Initialize request argument(s)
DeleteResourcePolicyRequest request = new DeleteResourcePolicyRequest
{
RequestId = "",
Region = "",
ResourcePolicy = "",
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await resourcePoliciesClient.DeleteAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await resourcePoliciesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void Delete()
{
// Snippet: Delete(string, string, string, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string resourcePolicy = "";
// Make the request
lro::Operation<Operation, Operation> response = resourcePoliciesClient.Delete(project, region, resourcePolicy);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = resourcePoliciesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteAsync()
{
// Snippet: DeleteAsync(string, string, string, CallSettings)
// Additional: DeleteAsync(string, string, string, CancellationToken)
// Create client
ResourcePoliciesClient resourcePoliciesClient = await ResourcePoliciesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string resourcePolicy = "";
// Make the request
lro::Operation<Operation, Operation> response = await resourcePoliciesClient.DeleteAsync(project, region, resourcePolicy);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await resourcePoliciesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Get</summary>
public void GetRequestObject()
{
// Snippet: Get(GetResourcePolicyRequest, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.Create();
// Initialize request argument(s)
GetResourcePolicyRequest request = new GetResourcePolicyRequest
{
Region = "",
ResourcePolicy = "",
Project = "",
};
// Make the request
ResourcePolicy response = resourcePoliciesClient.Get(request);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetRequestObjectAsync()
{
// Snippet: GetAsync(GetResourcePolicyRequest, CallSettings)
// Additional: GetAsync(GetResourcePolicyRequest, CancellationToken)
// Create client
ResourcePoliciesClient resourcePoliciesClient = await ResourcePoliciesClient.CreateAsync();
// Initialize request argument(s)
GetResourcePolicyRequest request = new GetResourcePolicyRequest
{
Region = "",
ResourcePolicy = "",
Project = "",
};
// Make the request
ResourcePolicy response = await resourcePoliciesClient.GetAsync(request);
// End snippet
}
/// <summary>Snippet for Get</summary>
public void Get()
{
// Snippet: Get(string, string, string, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string resourcePolicy = "";
// Make the request
ResourcePolicy response = resourcePoliciesClient.Get(project, region, resourcePolicy);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetAsync()
{
// Snippet: GetAsync(string, string, string, CallSettings)
// Additional: GetAsync(string, string, string, CancellationToken)
// Create client
ResourcePoliciesClient resourcePoliciesClient = await ResourcePoliciesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string resourcePolicy = "";
// Make the request
ResourcePolicy response = await resourcePoliciesClient.GetAsync(project, region, resourcePolicy);
// End snippet
}
/// <summary>Snippet for GetIamPolicy</summary>
public void GetIamPolicyRequestObject()
{
// Snippet: GetIamPolicy(GetIamPolicyResourcePolicyRequest, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.Create();
// Initialize request argument(s)
GetIamPolicyResourcePolicyRequest request = new GetIamPolicyResourcePolicyRequest
{
Region = "",
Resource = "",
Project = "",
OptionsRequestedPolicyVersion = 0,
};
// Make the request
Policy response = resourcePoliciesClient.GetIamPolicy(request);
// End snippet
}
/// <summary>Snippet for GetIamPolicyAsync</summary>
public async Task GetIamPolicyRequestObjectAsync()
{
// Snippet: GetIamPolicyAsync(GetIamPolicyResourcePolicyRequest, CallSettings)
// Additional: GetIamPolicyAsync(GetIamPolicyResourcePolicyRequest, CancellationToken)
// Create client
ResourcePoliciesClient resourcePoliciesClient = await ResourcePoliciesClient.CreateAsync();
// Initialize request argument(s)
GetIamPolicyResourcePolicyRequest request = new GetIamPolicyResourcePolicyRequest
{
Region = "",
Resource = "",
Project = "",
OptionsRequestedPolicyVersion = 0,
};
// Make the request
Policy response = await resourcePoliciesClient.GetIamPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for GetIamPolicy</summary>
public void GetIamPolicy()
{
// Snippet: GetIamPolicy(string, string, string, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string resource = "";
// Make the request
Policy response = resourcePoliciesClient.GetIamPolicy(project, region, resource);
// End snippet
}
/// <summary>Snippet for GetIamPolicyAsync</summary>
public async Task GetIamPolicyAsync()
{
// Snippet: GetIamPolicyAsync(string, string, string, CallSettings)
// Additional: GetIamPolicyAsync(string, string, string, CancellationToken)
// Create client
ResourcePoliciesClient resourcePoliciesClient = await ResourcePoliciesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string resource = "";
// Make the request
Policy response = await resourcePoliciesClient.GetIamPolicyAsync(project, region, resource);
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void InsertRequestObject()
{
// Snippet: Insert(InsertResourcePolicyRequest, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.Create();
// Initialize request argument(s)
InsertResourcePolicyRequest request = new InsertResourcePolicyRequest
{
RequestId = "",
ResourcePolicyResource = new ResourcePolicy(),
Region = "",
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = resourcePoliciesClient.Insert(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = resourcePoliciesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertRequestObjectAsync()
{
// Snippet: InsertAsync(InsertResourcePolicyRequest, CallSettings)
// Additional: InsertAsync(InsertResourcePolicyRequest, CancellationToken)
// Create client
ResourcePoliciesClient resourcePoliciesClient = await ResourcePoliciesClient.CreateAsync();
// Initialize request argument(s)
InsertResourcePolicyRequest request = new InsertResourcePolicyRequest
{
RequestId = "",
ResourcePolicyResource = new ResourcePolicy(),
Region = "",
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await resourcePoliciesClient.InsertAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await resourcePoliciesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void Insert()
{
// Snippet: Insert(string, string, ResourcePolicy, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
ResourcePolicy resourcePolicyResource = new ResourcePolicy();
// Make the request
lro::Operation<Operation, Operation> response = resourcePoliciesClient.Insert(project, region, resourcePolicyResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = resourcePoliciesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertAsync()
{
// Snippet: InsertAsync(string, string, ResourcePolicy, CallSettings)
// Additional: InsertAsync(string, string, ResourcePolicy, CancellationToken)
// Create client
ResourcePoliciesClient resourcePoliciesClient = await ResourcePoliciesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
ResourcePolicy resourcePolicyResource = new ResourcePolicy();
// Make the request
lro::Operation<Operation, Operation> response = await resourcePoliciesClient.InsertAsync(project, region, resourcePolicyResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await resourcePoliciesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for List</summary>
public void ListRequestObject()
{
// Snippet: List(ListResourcePoliciesRequest, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.Create();
// Initialize request argument(s)
ListResourcePoliciesRequest request = new ListResourcePoliciesRequest
{
Region = "",
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<ResourcePolicyList, ResourcePolicy> response = resourcePoliciesClient.List(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (ResourcePolicy item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ResourcePolicyList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ResourcePolicy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ResourcePolicy> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ResourcePolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListRequestObjectAsync()
{
// Snippet: ListAsync(ListResourcePoliciesRequest, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = await ResourcePoliciesClient.CreateAsync();
// Initialize request argument(s)
ListResourcePoliciesRequest request = new ListResourcePoliciesRequest
{
Region = "",
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<ResourcePolicyList, ResourcePolicy> response = resourcePoliciesClient.ListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ResourcePolicy item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ResourcePolicyList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ResourcePolicy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ResourcePolicy> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ResourcePolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for List</summary>
public void List()
{
// Snippet: List(string, string, string, int?, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
// Make the request
PagedEnumerable<ResourcePolicyList, ResourcePolicy> response = resourcePoliciesClient.List(project, region);
// Iterate over all response items, lazily performing RPCs as required
foreach (ResourcePolicy item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ResourcePolicyList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ResourcePolicy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ResourcePolicy> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ResourcePolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListAsync()
{
// Snippet: ListAsync(string, string, string, int?, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = await ResourcePoliciesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
// Make the request
PagedAsyncEnumerable<ResourcePolicyList, ResourcePolicy> response = resourcePoliciesClient.ListAsync(project, region);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ResourcePolicy item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ResourcePolicyList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ResourcePolicy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ResourcePolicy> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ResourcePolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for SetIamPolicy</summary>
public void SetIamPolicyRequestObject()
{
// Snippet: SetIamPolicy(SetIamPolicyResourcePolicyRequest, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.Create();
// Initialize request argument(s)
SetIamPolicyResourcePolicyRequest request = new SetIamPolicyResourcePolicyRequest
{
Region = "",
Resource = "",
Project = "",
RegionSetPolicyRequestResource = new RegionSetPolicyRequest(),
};
// Make the request
Policy response = resourcePoliciesClient.SetIamPolicy(request);
// End snippet
}
/// <summary>Snippet for SetIamPolicyAsync</summary>
public async Task SetIamPolicyRequestObjectAsync()
{
// Snippet: SetIamPolicyAsync(SetIamPolicyResourcePolicyRequest, CallSettings)
// Additional: SetIamPolicyAsync(SetIamPolicyResourcePolicyRequest, CancellationToken)
// Create client
ResourcePoliciesClient resourcePoliciesClient = await ResourcePoliciesClient.CreateAsync();
// Initialize request argument(s)
SetIamPolicyResourcePolicyRequest request = new SetIamPolicyResourcePolicyRequest
{
Region = "",
Resource = "",
Project = "",
RegionSetPolicyRequestResource = new RegionSetPolicyRequest(),
};
// Make the request
Policy response = await resourcePoliciesClient.SetIamPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for SetIamPolicy</summary>
public void SetIamPolicy()
{
// Snippet: SetIamPolicy(string, string, string, RegionSetPolicyRequest, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string resource = "";
RegionSetPolicyRequest regionSetPolicyRequestResource = new RegionSetPolicyRequest();
// Make the request
Policy response = resourcePoliciesClient.SetIamPolicy(project, region, resource, regionSetPolicyRequestResource);
// End snippet
}
/// <summary>Snippet for SetIamPolicyAsync</summary>
public async Task SetIamPolicyAsync()
{
// Snippet: SetIamPolicyAsync(string, string, string, RegionSetPolicyRequest, CallSettings)
// Additional: SetIamPolicyAsync(string, string, string, RegionSetPolicyRequest, CancellationToken)
// Create client
ResourcePoliciesClient resourcePoliciesClient = await ResourcePoliciesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string resource = "";
RegionSetPolicyRequest regionSetPolicyRequestResource = new RegionSetPolicyRequest();
// Make the request
Policy response = await resourcePoliciesClient.SetIamPolicyAsync(project, region, resource, regionSetPolicyRequestResource);
// End snippet
}
/// <summary>Snippet for TestIamPermissions</summary>
public void TestIamPermissionsRequestObject()
{
// Snippet: TestIamPermissions(TestIamPermissionsResourcePolicyRequest, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.Create();
// Initialize request argument(s)
TestIamPermissionsResourcePolicyRequest request = new TestIamPermissionsResourcePolicyRequest
{
Region = "",
Resource = "",
Project = "",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
// Make the request
TestPermissionsResponse response = resourcePoliciesClient.TestIamPermissions(request);
// End snippet
}
/// <summary>Snippet for TestIamPermissionsAsync</summary>
public async Task TestIamPermissionsRequestObjectAsync()
{
// Snippet: TestIamPermissionsAsync(TestIamPermissionsResourcePolicyRequest, CallSettings)
// Additional: TestIamPermissionsAsync(TestIamPermissionsResourcePolicyRequest, CancellationToken)
// Create client
ResourcePoliciesClient resourcePoliciesClient = await ResourcePoliciesClient.CreateAsync();
// Initialize request argument(s)
TestIamPermissionsResourcePolicyRequest request = new TestIamPermissionsResourcePolicyRequest
{
Region = "",
Resource = "",
Project = "",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
// Make the request
TestPermissionsResponse response = await resourcePoliciesClient.TestIamPermissionsAsync(request);
// End snippet
}
/// <summary>Snippet for TestIamPermissions</summary>
public void TestIamPermissions()
{
// Snippet: TestIamPermissions(string, string, string, TestPermissionsRequest, CallSettings)
// Create client
ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string resource = "";
TestPermissionsRequest testPermissionsRequestResource = new TestPermissionsRequest();
// Make the request
TestPermissionsResponse response = resourcePoliciesClient.TestIamPermissions(project, region, resource, testPermissionsRequestResource);
// End snippet
}
/// <summary>Snippet for TestIamPermissionsAsync</summary>
public async Task TestIamPermissionsAsync()
{
// Snippet: TestIamPermissionsAsync(string, string, string, TestPermissionsRequest, CallSettings)
// Additional: TestIamPermissionsAsync(string, string, string, TestPermissionsRequest, CancellationToken)
// Create client
ResourcePoliciesClient resourcePoliciesClient = await ResourcePoliciesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string resource = "";
TestPermissionsRequest testPermissionsRequestResource = new TestPermissionsRequest();
// Make the request
TestPermissionsResponse response = await resourcePoliciesClient.TestIamPermissionsAsync(project, region, resource, testPermissionsRequestResource);
// End snippet
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeDom.Compiler
{
using System;
using Microsoft.CodeDom;
using System.ComponentModel;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
[ComVisible(true)]
public abstract class CodeDomProvider : IDisposable
{
[ComVisible(false)]
public static CodeDomProvider CreateProvider(String language, System.Collections.Generic.IDictionary<String, String> providerOptions)
{
CompilerInfo compilerInfo = GetCompilerInfo(language);
return compilerInfo.CreateProvider(providerOptions);
}
[ComVisible(false)]
public static CodeDomProvider CreateProvider(String language)
{
CompilerInfo compilerInfo = GetCompilerInfo(language);
return compilerInfo.CreateProvider();
}
[ComVisible(false)]
public static String GetLanguageFromExtension(String extension)
{
CompilerInfo compilerInfo = (CompilerInfo)GetCompilerInfoForExtensionNoThrow(extension);
if (compilerInfo == null)
throw new ConfigurationErrorsException(SRCodeDom.CodeDomProvider_NotDefined);
return compilerInfo._compilerLanguages[0]; // Return the first language name. There has to be one.
}
[ComVisible(false)]
public static bool IsDefinedLanguage(String language)
{
return (GetCompilerInfoForLanguageNoThrow(language) != null);
}
[ComVisible(false)]
public static bool IsDefinedExtension(String extension)
{
return (GetCompilerInfoForExtensionNoThrow(extension) != null);
}
[ComVisible(false)]
public static CompilerInfo GetCompilerInfo(String language)
{
CompilerInfo compilerInfo = GetCompilerInfoForLanguageNoThrow(language);
if (compilerInfo == null)
throw new ConfigurationErrorsException(SRCodeDom.CodeDomProvider_NotDefined);
return compilerInfo;
}
// Do argument validation but don't throw if there's no compiler defined for a language.
private static CompilerInfo GetCompilerInfoForLanguageNoThrow(String language)
{
if (language == null)
throw new ArgumentNullException("language");
CompilerInfo compilerInfo = (CompilerInfo)Config._compilerLanguages[language.Trim()];
return compilerInfo;
}
// Do argument validation but don't throw if there's no compiler defined for a language.
private static CompilerInfo GetCompilerInfoForExtensionNoThrow(String extension)
{
if (extension == null)
throw new ArgumentNullException("extension");
CompilerInfo compilerInfo = (CompilerInfo)Config._compilerExtensions[extension.Trim()];
return compilerInfo;
}
[ComVisible(false)]
public static CompilerInfo[] GetAllCompilerInfo()
{
ArrayList values = Config._allCompilerInfo;
CompilerInfo[] compilerInfos = (CompilerInfo[])values.ToArray(typeof(CompilerInfo));
return compilerInfos;
}
// Don't cache the configuration since things are different for asp.net scenarios.
private static CodeDomCompilationConfiguration Config
{
get
{
CodeDomCompilationConfiguration _configuration = new CodeDomCompilationConfiguration();
return _configuration;
}
}
/// <devdoc>
/// <para>Retrieves the default extension to use when saving files using this code dom provider.</para>
/// </devdoc>
public virtual string FileExtension
{
get
{
return string.Empty;
}
}
/// <devdoc>
/// <para>Returns flags representing language variations.</para>
/// </devdoc>
public virtual LanguageOptions LanguageOptions
{
get
{
return LanguageOptions.None;
}
}
[Obsolete("Callers should not use the ICodeGenerator interface and should instead use the methods directly on the CodeDomProvider class. Those inheriting from CodeDomProvider must still implement this interface, and should exclude this warning or also obsolete this method.")]
public abstract ICodeGenerator CreateGenerator();
#pragma warning disable 618
public virtual ICodeGenerator CreateGenerator(TextWriter output)
{
return CreateGenerator();
}
public virtual ICodeGenerator CreateGenerator(string fileName)
{
return CreateGenerator();
}
#pragma warning restore 618
[Obsolete("Callers should not use the ICodeCompiler interface and should instead use the methods directly on the CodeDomProvider class. Those inheriting from CodeDomProvider must still implement this interface, and should exclude this warning or also obsolete this method.")]
public abstract ICodeCompiler CreateCompiler();
[Obsolete("Callers should not use the ICodeParser interface and should instead use the methods directly on the CodeDomProvider class. Those inheriting from CodeDomProvider must still implement this interface, and should exclude this warning or also obsolete this method.")]
public virtual ICodeParser CreateParser()
{
return null;
}
/// <devdoc>
/// This method allows a code dom provider implementation to provide a different type converter
/// for a given data type. At design time, a designer may pass data types through this
/// method to see if the code dom provider wants to provide an additional converter.
/// As typical way this would be used is if the language this code dom provider implements
/// does not support all of the values of MemberAttributes enumeration, or if the language
/// uses different names (Protected instead of Family, for example). The default
/// implementation just calls TypeDescriptor.GetConverter for the given type.
/// </devdoc>
public virtual TypeConverter GetConverter(Type type)
{
return TypeDescriptor.GetConverter(type);
}
/// <devdoc>
/// <para>
/// Creates an assembly based on options, with the information from the compile units
/// </para>
/// </devdoc>
public virtual CompilerResults CompileAssemblyFromDom(CompilerParameters options, params CodeCompileUnit[] compilationUnits)
{
return CreateCompilerHelper().CompileAssemblyFromDomBatch(options, compilationUnits);
}
/// <devdoc>
/// <para>
/// Creates an assembly based on options, with the contents of the files
/// </para>
/// </devdoc>
public virtual CompilerResults CompileAssemblyFromFile(CompilerParameters options, params string[] fileNames)
{
return CreateCompilerHelper().CompileAssemblyFromFileBatch(options, fileNames);
}
/// <devdoc>
/// <para>
/// Creates an assembly based on options, with the information from sources
/// </para>
/// </devdoc>
public virtual CompilerResults CompileAssemblyFromSource(CompilerParameters options, params string[] sources)
{
return CreateCompilerHelper().CompileAssemblyFromSourceBatch(options, sources);
}
/// <devdoc>
/// <para>
/// Gets a value indicating whether
/// the specified value is a valid identifier for this language.
/// </para>
/// </devdoc>
public virtual bool IsValidIdentifier(string value)
{
return CreateGeneratorHelper().IsValidIdentifier(value);
}
public virtual string CreateEscapedIdentifier(string value)
{
return CreateGeneratorHelper().CreateEscapedIdentifier(value);
}
public virtual string CreateValidIdentifier(string value)
{
return CreateGeneratorHelper().CreateValidIdentifier(value);
}
public virtual string GetTypeOutput(CodeTypeReference type)
{
return CreateGeneratorHelper().GetTypeOutput(type);
}
public virtual bool Supports(GeneratorSupport generatorSupport)
{
return CreateGeneratorHelper().Supports(generatorSupport);
}
/// <devdoc>
/// <para>
/// Generates code from the specified expression and
/// outputs it to the specified textwriter.
/// </para>
/// </devdoc>
public virtual void GenerateCodeFromExpression(CodeExpression expression, TextWriter writer, CodeGeneratorOptions options)
{
CreateGeneratorHelper().GenerateCodeFromExpression(expression, writer, options);
}
/// <devdoc>
/// <para>
/// Outputs the language specific representaion of the CodeDom tree
/// refered to by statement, into writer.
/// </para>
/// </devdoc>
public virtual void GenerateCodeFromStatement(CodeStatement statement, TextWriter writer, CodeGeneratorOptions options)
{
CreateGeneratorHelper().GenerateCodeFromStatement(statement, writer, options);
}
/// <devdoc>
/// <para>
/// Outputs the language specific representaion of the CodeDom tree
/// refered to by codeNamespace, into writer.
/// </para>
/// </devdoc>
public virtual void GenerateCodeFromNamespace(CodeNamespace codeNamespace, TextWriter writer, CodeGeneratorOptions options)
{
CreateGeneratorHelper().GenerateCodeFromNamespace(codeNamespace, writer, options);
}
/// <devdoc>
/// <para>
/// Outputs the language specific representaion of the CodeDom tree
/// refered to by compileUnit, into writer.
/// </para>
/// </devdoc>
public virtual void GenerateCodeFromCompileUnit(CodeCompileUnit compileUnit, TextWriter writer, CodeGeneratorOptions options)
{
CreateGeneratorHelper().GenerateCodeFromCompileUnit(compileUnit, writer, options);
}
/// <devdoc>
/// <para>
/// Outputs the language specific representaion of the CodeDom tree
/// refered to by codeType, into writer.
/// </para>
/// </devdoc>
public virtual void GenerateCodeFromType(CodeTypeDeclaration codeType, TextWriter writer, CodeGeneratorOptions options)
{
CreateGeneratorHelper().GenerateCodeFromType(codeType, writer, options);
}
public virtual void GenerateCodeFromMember(CodeTypeMember member, TextWriter writer, CodeGeneratorOptions options)
{
throw new NotImplementedException(SRCodeDom.NotSupported_CodeDomAPI);
}
/// <devdoc>
/// <para>
/// Compiles the given text stream into a CodeCompile unit.
/// </para>
/// </devdoc>
public virtual CodeCompileUnit Parse(TextReader codeStream)
{
return CreateParserHelper().Parse(codeStream);
}
#pragma warning disable 618
private ICodeCompiler CreateCompilerHelper()
{
ICodeCompiler compiler = CreateCompiler();
if (compiler == null)
{
throw new NotImplementedException(SRCodeDom.NotSupported_CodeDomAPI);
}
return compiler;
}
private ICodeGenerator CreateGeneratorHelper()
{
ICodeGenerator generator = CreateGenerator();
if (generator == null)
{
throw new NotImplementedException(SRCodeDom.NotSupported_CodeDomAPI);
}
return generator;
}
private ICodeParser CreateParserHelper()
{
ICodeParser parser = CreateParser();
if (parser == null)
{
throw new NotImplementedException(SRCodeDom.NotSupported_CodeDomAPI);
}
return parser;
}
#region IDisposable Support
private bool _disposedValue; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects).
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
_disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~CodeDomProvider() {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
#pragma warning restore 618
}
}
| |
/******************************************************************************
* Copyright (C) Leap Motion, Inc. 2011-2017. *
* Leap Motion proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
******************************************************************************/
using UnityEngine;
using UnityEngine.VR;
using System;
using System.Collections;
using System.Collections.Generic;
using Leap.Unity.Attributes;
namespace Leap.Unity {
/// <summary>
/// Implements spatial alignment of cameras and synchronization with images.
/// </summary>
public class LeapVRTemporalWarping : MonoBehaviour {
private const long MAX_LATENCY = 200000;
#region Inspector
[SerializeField]
private LeapServiceProvider provider;
[Tooltip("The transform that represents the head object.")]
[SerializeField]
private Transform _headTransform;
[Tooltip("The transform that is the anchor that tracking movement is relative to. Can be null if head motion is in world space.")]
[SerializeField]
private Transform _trackingAnchor;
// Spatial recalibration
[Tooltip("Key to recenter the VR tracking space.")]
[SerializeField]
private KeyCode _recenter = KeyCode.R;
[Tooltip("Allows smooth enabling or disabling of the Image-Warping feature. Usually should match rotation warping.")]
[Range(0, 1)]
[SerializeField]
private float _tweenImageWarping = 0f;
public float tweenImageWarping {
get {
return _tweenImageWarping;
}
set {
_tweenImageWarping = Mathf.Clamp01(value);
}
}
[Tooltip("Allows smooth enabling or disabling of the Rotational warping of Leap Space. Usually should match image warping.")]
[Range(0, 1)]
[SerializeField]
private float _tweenRotationalWarping = 0f;
public float tweenRotationalWarping {
get {
return _tweenRotationalWarping;
}
set {
_tweenRotationalWarping = Mathf.Clamp01(value);
}
}
[Tooltip("Allows smooth enabling or disabling of the Positional warping of Leap Space. Usually should be disabled when using image warping.")]
[Range(0, 1)]
[SerializeField]
private float _tweenPositionalWarping = 0f;
public float tweenPositionalWarping {
get {
return _tweenPositionalWarping;
}
set {
_tweenPositionalWarping = Mathf.Clamp01(value);
}
}
[Tooltip("Controls when this script synchronizes the time warp of images. Use LowLatency for VR, and SyncWithImages for AR.")]
[SerializeField]
private SyncMode _syncMode = SyncMode.LOW_LATENCY;
public SyncMode temporalSyncMode {
get {
return _syncMode;
}
set {
_syncMode = value;
}
}
[Header("Advanced")]
[Tooltip("Forces an update of the temporal warping to happen in Late Update using the existing head transform. Should not be enabled if you " +
"are using the default Unity VR integration!")]
[SerializeField]
private bool _forceCustomUpdate = false;
// Manual Time Alignment
[Tooltip("Allow manual adjustment of the rewind time.")]
[SerializeField]
private bool _allowManualTimeAlignment;
[Tooltip("Timestamps and other uncertanties can lead to sub-optimal alignment, this value can be tuned to get desired alignment.")]
[SerializeField]
private int _warpingAdjustment = 60; //Milliseconds
public float warpingAdjustment {
get {
return _warpingAdjustment;
}
}
[SerializeField]
private KeyCode _unlockHold = KeyCode.RightShift;
[SerializeField]
private KeyCode _moreRewind = KeyCode.LeftArrow;
[SerializeField]
private KeyCode _lessRewind = KeyCode.RightArrow;
// Manual Device Offset
private const float DEFAULT_DEVICE_OFFSET_Y_AXIS = 0f;
private const float DEFAULT_DEVICE_OFFSET_Z_AXIS = 0.12f;
private const float DEFAULT_DEVICE_TILT_X_AXIS = 5f;
[Tooltip("Allow manual adjustment of the Leap device's virtual offset and tilt. These "
+ "settings can be used to match the physical position and orientation of the "
+ "Leap Motion sensor on a tracked device it is mounted on (such as a VR "
+ "headset.)")]
[SerializeField, OnEditorChange("allowManualDeviceOffset")]
private bool _allowManualDeviceOffset;
public bool allowManualDeviceOffset {
get { return _allowManualDeviceOffset; }
set {
_allowManualDeviceOffset = value;
if (!_allowManualDeviceOffset) {
deviceOffsetYAxis = DEFAULT_DEVICE_OFFSET_Y_AXIS;
deviceOffsetZAxis = DEFAULT_DEVICE_OFFSET_Z_AXIS;
deviceTiltXAxis = DEFAULT_DEVICE_TILT_X_AXIS;
}
}
}
[Tooltip("Adjusts the Leap Motion device's virtual height offset from the tracked "
+ "headset position.")]
[SerializeField]
[Range(-0.5F, 0.5F)]
private float _deviceOffsetYAxis = DEFAULT_DEVICE_OFFSET_Y_AXIS;
public float deviceOffsetYAxis {
get {
return _deviceOffsetYAxis;
}
set {
_deviceOffsetYAxis = value;
}
}
[Tooltip("Adjusts the Leap Motion device's virtual depth offset from the tracked "
+ "headset position.")]
[SerializeField]
[Range(-0.5F, 0.5F)]
private float _deviceOffsetZAxis = DEFAULT_DEVICE_OFFSET_Z_AXIS;
public float deviceOffsetZAxis {
get {
return _deviceOffsetZAxis;
}
set {
_deviceOffsetZAxis = value;
}
}
[Tooltip("Adjusts the Leap Motion device's virtual X axis tilt.")]
[SerializeField]
[Range(-90.0F, 90.0F)]
private float _deviceTiltXAxis = DEFAULT_DEVICE_TILT_X_AXIS;
public float deviceTiltXAxis {
get {
return _deviceTiltXAxis;
}
set {
_deviceTiltXAxis = value;
}
}
#endregion
#region Public API
/// <summary>
/// Provides the position of a Leap Anchor at a given Leap Time. Cannot extrapolate.
/// </summary>
public bool TryGetWarpedTransform(WarpedAnchor anchor, out Vector3 rewoundPosition, out Quaternion rewoundRotation, long leapTime) {
// Operation is only valid if we have a head transform.
if (_headTransform == null) {
rewoundPosition = Vector3.one;
rewoundRotation = Quaternion.identity;
return false;
}
// Prepare past transform data.
TransformData past = transformAtTime((leapTime - _warpingAdjustment * 1000) + (_syncMode == SyncMode.SYNC_WITH_IMAGES ? 20000 : 0));
// Prepare device offset parameters.
Quaternion deviceTilt = Quaternion.Euler(deviceTiltXAxis, 0f, 0f);
Vector3 deviceOffset = new Vector3(0f, deviceOffsetYAxis, deviceOffsetZAxis);
// TODO: We no longer use deviceInfo.forwardOffset. We should consider removing it
// entirely or more approrpriately when we collapse the rig hierarchy. 9/1/17
// Rewind position and rotation.
if (_trackingAnchor == null) {
rewoundRotation = past.localRotation * deviceTilt;
rewoundPosition = past.localPosition + rewoundRotation * deviceOffset;
} else {
rewoundRotation = _trackingAnchor.rotation * past.localRotation * deviceTilt;
rewoundPosition = _trackingAnchor.TransformPoint(past.localPosition) + rewoundRotation * deviceOffset;
}
// Move position if we are left-eye-only or right-eye-only.
switch (anchor) {
case WarpedAnchor.CENTER:
break;
case WarpedAnchor.LEFT:
rewoundPosition += rewoundRotation * Vector3.left * _deviceInfo.baseline * 0.5f;
break;
case WarpedAnchor.RIGHT:
rewoundPosition += rewoundRotation * Vector3.right * _deviceInfo.baseline * 0.5f;
break;
default:
throw new Exception("Unexpected Rewind Type " + anchor);
}
return true;
}
public bool TryGetWarpedTransform(WarpedAnchor anchor, out Vector3 rewoundPosition, out Quaternion rewoundRotation) {
long timestamp = provider.imageTimeStamp;
if (TryGetWarpedTransform(anchor, out rewoundPosition, out rewoundRotation, timestamp)) {
return true;
}
rewoundPosition = Vector3.zero;
rewoundRotation = Quaternion.identity;
return false;
}
/// <summary>
/// Use this method when not using Unity default VR integration. This method should be called directly after
/// the head transform has been updated using your input tracking solution.
/// </summary>
public void ManuallyUpdateTemporalWarping() {
if (_trackingAnchor == null) {
updateHistory(_headTransform.position, _headTransform.rotation);
updateTemporalWarping(_headTransform.position, _headTransform.rotation);
} else {
updateHistory(_trackingAnchor.InverseTransformPoint(_headTransform.position),
Quaternion.Inverse(_trackingAnchor.rotation) * _headTransform.rotation);
}
}
#endregion
#region Unity Events
protected void Reset() {
_headTransform = transform.parent;
if (_headTransform != null) {
_trackingAnchor = _headTransform.parent;
}
}
protected void OnValidate() {
if (_headTransform == null) {
_headTransform = transform.parent;
}
#if UNITY_EDITOR
if (_headTransform != null && UnityEditor.PlayerSettings.virtualRealitySupported) {
_trackingAnchor = _headTransform.parent;
}
#endif
}
protected void OnEnable() {
LeapVRCameraControl.OnValidCameraParams -= onValidCameraParams; //avoid multiple subscription
LeapVRCameraControl.OnValidCameraParams += onValidCameraParams;
}
protected void OnDisable() {
LeapVRCameraControl.OnValidCameraParams -= onValidCameraParams;
}
protected void Start() {
if (provider.IsConnected()) {
_deviceInfo = provider.GetDeviceInfo();
_shouldSetLocalPosition = true;
LeapVRCameraControl.OnValidCameraParams += onValidCameraParams;
} else {
StartCoroutine(waitForConnection());
Controller controller = provider.GetLeapController();
controller.Device += OnDevice;
}
}
private IEnumerator waitForConnection() {
while (!provider.IsConnected()) {
yield return null;
}
LeapVRCameraControl.OnValidCameraParams -= onValidCameraParams; //avoid multiple subscription
LeapVRCameraControl.OnValidCameraParams += onValidCameraParams;
}
private bool _shouldSetLocalPosition = false;
protected void OnDevice(object sender, DeviceEventArgs args) {
_deviceInfo = provider.GetDeviceInfo();
_shouldSetLocalPosition = true;
//Get a callback right as rendering begins for this frame so we can update the history and warping.
LeapVRCameraControl.OnValidCameraParams -= onValidCameraParams; //avoid multiple subscription
LeapVRCameraControl.OnValidCameraParams += onValidCameraParams;
}
protected void Update() {
if (_shouldSetLocalPosition) {
transform.localPosition = transform.forward * _deviceInfo.forwardOffset;
_shouldSetLocalPosition = false;
}
if (Input.GetKeyDown(_recenter) && VRSettings.enabled && VRDevice.isPresent) {
InputTracking.Recenter();
}
// Manual Time Alignment
if (_allowManualTimeAlignment) {
if (_unlockHold == KeyCode.None || Input.GetKey(_unlockHold)) {
if (Input.GetKeyDown(_moreRewind)) {
_warpingAdjustment += 1;
}
if (Input.GetKeyDown(_lessRewind)) {
_warpingAdjustment -= 1;
}
}
}
}
protected void LateUpdate() {
if (_forceCustomUpdate) {
ManuallyUpdateTemporalWarping();
} else if (VRSettings.enabled) {
updateTemporalWarping(InputTracking.GetLocalPosition(VRNode.CenterEye),
InputTracking.GetLocalRotation(VRNode.CenterEye));
}
}
private void onValidCameraParams(LeapVRCameraControl.CameraParams cameraParams) {
_projectionMatrix = cameraParams.ProjectionMatrix;
if (VRSettings.enabled) {
if (provider != null) {
updateHistory(InputTracking.GetLocalPosition(VRNode.CenterEye),
InputTracking.GetLocalRotation(VRNode.CenterEye));
}
if (_syncMode == SyncMode.LOW_LATENCY) {
updateTemporalWarping(InputTracking.GetLocalPosition(VRNode.CenterEye),
InputTracking.GetLocalRotation(VRNode.CenterEye));
}
}
}
#endregion
#region Temporal Warping
private LeapDeviceInfo _deviceInfo;
private Matrix4x4 _projectionMatrix;
private List<TransformData> _history = new List<TransformData>();
private void updateHistory(Vector3 currLocalPosition, Quaternion currLocalRotation) {
long leapNow = provider.GetLeapController().Now();
_history.Add(new TransformData() {
leapTime = leapNow,
localPosition = currLocalPosition,
localRotation = currLocalRotation
});
// Reduce history length
while (_history.Count > 0 &&
MAX_LATENCY < leapNow - _history[0].leapTime) {
_history.RemoveAt(0);
}
}
private void updateTemporalWarping(Vector3 currLocalPosition, Quaternion currLocalRotation) {
if (_trackingAnchor == null || provider.GetLeapController() == null) {
return;
}
Vector3 currCenterPos = _trackingAnchor.TransformPoint(currLocalPosition);
Quaternion currCenterRot = _trackingAnchor.rotation * currLocalRotation;
//Get the transform at the time when the latest frame was captured
long rewindTime = provider.CurrentFrame.Timestamp - _warpingAdjustment * 1000;
long imageRewindTime = provider.imageTimeStamp - _warpingAdjustment * 1000;
TransformData imagePast = transformAtTime(imageRewindTime);
Quaternion imagePastCenterRot = _trackingAnchor.rotation * imagePast.localRotation;
//Apply only a rotation ~ assume all objects are infinitely distant
Quaternion imageReferenceRotation = Quaternion.Slerp(currCenterRot, imagePastCenterRot, _tweenImageWarping);
Quaternion imageQuatWarp = Quaternion.Inverse(currCenterRot) * imageReferenceRotation;
imageQuatWarp = Quaternion.Euler(imageQuatWarp.eulerAngles.x, imageQuatWarp.eulerAngles.y, -imageQuatWarp.eulerAngles.z);
Matrix4x4 imageMatWarp = _projectionMatrix * Matrix4x4.TRS(Vector3.zero, imageQuatWarp, Vector3.one) * _projectionMatrix.inverse;
Shader.SetGlobalMatrix("_LeapGlobalWarpedOffset", imageMatWarp);
TransformData past = transformAtTime(rewindTime);
Vector3 pastCenterPos = _trackingAnchor.TransformPoint(past.localPosition);
Quaternion pastCenterRot = _trackingAnchor.rotation * past.localRotation;
transform.position = Vector3.Lerp(currCenterPos, pastCenterPos, _tweenPositionalWarping);
transform.rotation = Quaternion.Slerp(currCenterRot, pastCenterRot, _tweenRotationalWarping);
transform.position += transform.forward * deviceOffsetZAxis;
}
/* Returns the VR Center Eye Transform information interpolated to the given leap timestamp. If the desired
* timestamp is outside of the recorded range, interpolation will fail and the returned transform will not
* have the desired time.
*/
private TransformData transformAtTime(long time) {
if (_history.Count == 0) {
return new TransformData() {
leapTime = 0,
localPosition = Vector3.zero,
localRotation = Quaternion.identity
};
}
if (_history[0].leapTime >= time) {
// Expect this when using LOW LATENCY image retrieval, which can yield negative latency estimates due to incorrect clock synchronization
return _history[0];
}
int t = 1;
while (t < _history.Count &&
_history[t].leapTime <= time) {
t++;
}
if (!(t < _history.Count)) {
// Expect this for initial frames which will have a very low frame rate
return _history[_history.Count - 1];
}
return TransformData.Lerp(_history[t - 1], _history[t], time);
}
#endregion
#region Support
public enum WarpedAnchor {
CENTER,
LEFT,
RIGHT,
}
public enum SyncMode {
/* SyncWithImages causes both Images and the Transform to be updated at the same time during LateUpdate. This causes
* the images to line up properly, but the images will lag behind the virtual world, causing drift. */
SYNC_WITH_IMAGES,
/* LowLatency causes the Images to be warped directly prior to rendering, causing them to line up better with virtual
* objects. Since transforms cannot be modified at this point in the update step, the Transform will still be updated
* during LateUpdate, causing a misalignment between images and leap space. */
LOW_LATENCY
}
protected struct TransformData {
public long leapTime; // microseconds
public Vector3 localPosition; //meters
public Quaternion localRotation; //magic
public static TransformData Lerp(TransformData from, TransformData to, long time) {
if (from.leapTime == to.leapTime) {
return from;
}
float fraction = (float)(time - from.leapTime) / (float)(to.leapTime - from.leapTime);
return new TransformData() {
leapTime = time,
localPosition = Vector3.Lerp(from.localPosition, to.localPosition, fraction),
localRotation = Quaternion.Slerp(from.localRotation, to.localRotation, fraction)
};
}
}
#endregion
}
}
| |
/*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
namespace Org.OpenAPITools.Model
{
/// <summary>
/// GithubContent
/// </summary>
[DataContract]
public partial class GithubContent : IEquatable<GithubContent>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="GithubContent" /> class.
/// </summary>
/// <param name="name">name.</param>
/// <param name="sha">sha.</param>
/// <param name="_class">_class.</param>
/// <param name="repo">repo.</param>
/// <param name="size">size.</param>
/// <param name="owner">owner.</param>
/// <param name="path">path.</param>
/// <param name="base64Data">base64Data.</param>
public GithubContent(string name = default(string), string sha = default(string), string _class = default(string), string repo = default(string), int size = default(int), string owner = default(string), string path = default(string), string base64Data = default(string))
{
this.Name = name;
this.Sha = sha;
this.Class = _class;
this.Repo = repo;
this.Size = size;
this.Owner = owner;
this.Path = path;
this.Base64Data = base64Data;
}
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets Sha
/// </summary>
[DataMember(Name="sha", EmitDefaultValue=false)]
public string Sha { get; set; }
/// <summary>
/// Gets or Sets Class
/// </summary>
[DataMember(Name="_class", EmitDefaultValue=false)]
public string Class { get; set; }
/// <summary>
/// Gets or Sets Repo
/// </summary>
[DataMember(Name="repo", EmitDefaultValue=false)]
public string Repo { get; set; }
/// <summary>
/// Gets or Sets Size
/// </summary>
[DataMember(Name="size", EmitDefaultValue=false)]
public int Size { get; set; }
/// <summary>
/// Gets or Sets Owner
/// </summary>
[DataMember(Name="owner", EmitDefaultValue=false)]
public string Owner { get; set; }
/// <summary>
/// Gets or Sets Path
/// </summary>
[DataMember(Name="path", EmitDefaultValue=false)]
public string Path { get; set; }
/// <summary>
/// Gets or Sets Base64Data
/// </summary>
[DataMember(Name="base64Data", EmitDefaultValue=false)]
public string Base64Data { 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 GithubContent {\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Sha: ").Append(Sha).Append("\n");
sb.Append(" Class: ").Append(Class).Append("\n");
sb.Append(" Repo: ").Append(Repo).Append("\n");
sb.Append(" Size: ").Append(Size).Append("\n");
sb.Append(" Owner: ").Append(Owner).Append("\n");
sb.Append(" Path: ").Append(Path).Append("\n");
sb.Append(" Base64Data: ").Append(Base64Data).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 virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as GithubContent);
}
/// <summary>
/// Returns true if GithubContent instances are equal
/// </summary>
/// <param name="input">Instance of GithubContent to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(GithubContent input)
{
if (input == null)
return false;
return
(
this.Name == input.Name ||
(this.Name != null &&
this.Name.Equals(input.Name))
) &&
(
this.Sha == input.Sha ||
(this.Sha != null &&
this.Sha.Equals(input.Sha))
) &&
(
this.Class == input.Class ||
(this.Class != null &&
this.Class.Equals(input.Class))
) &&
(
this.Repo == input.Repo ||
(this.Repo != null &&
this.Repo.Equals(input.Repo))
) &&
(
this.Size == input.Size ||
(this.Size != null &&
this.Size.Equals(input.Size))
) &&
(
this.Owner == input.Owner ||
(this.Owner != null &&
this.Owner.Equals(input.Owner))
) &&
(
this.Path == input.Path ||
(this.Path != null &&
this.Path.Equals(input.Path))
) &&
(
this.Base64Data == input.Base64Data ||
(this.Base64Data != null &&
this.Base64Data.Equals(input.Base64Data))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Name != null)
hashCode = hashCode * 59 + this.Name.GetHashCode();
if (this.Sha != null)
hashCode = hashCode * 59 + this.Sha.GetHashCode();
if (this.Class != null)
hashCode = hashCode * 59 + this.Class.GetHashCode();
if (this.Repo != null)
hashCode = hashCode * 59 + this.Repo.GetHashCode();
if (this.Size != null)
hashCode = hashCode * 59 + this.Size.GetHashCode();
if (this.Owner != null)
hashCode = hashCode * 59 + this.Owner.GetHashCode();
if (this.Path != null)
hashCode = hashCode * 59 + this.Path.GetHashCode();
if (this.Base64Data != null)
hashCode = hashCode * 59 + this.Base64Data.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
function MyModule::create( %this )
{
//SCENE GROUPS:
// 0: Background/Walls
// 1: Tanks
// 2: weapons/attacks
// 3: powerups
// 4: Scenery
// 5: Mines
// 6: AI Enemies
// Load GUI profiles.
exec("./gui/guiProfiles.cs");
exec("./scripts/menus/menu.cs");
exec("./scripts/misc/effects.cs");
exec("./scripts/misc/misc.cs");
exec("./scripts/mapping/scenery/crate.cs");
exec("./scripts/mapping/scenery/rock.cs");
exec("./scripts/mapping/scenery/barrel.cs");
exec("./scripts/mapping/wall/barrier.cs");
exec("./scripts/mapping/powerups/powerup.cs");
exec("./scripts/mapping/powerups/powerupSpawner.cs");
exec("./scripts/scenewindow.cs");
exec("./scripts/scene.cs");
exec("./scripts/background.cs");
exec("./scripts/player/tank.cs");
exec("./scripts/enemy/turret.cs");
//Behaviors
//Player Controls
exec("./scripts/behaviors/scene/Pause.cs");
exec("./scripts/behaviors/controls/TankControls.cs");
exec("./scripts/behaviors/controls/PrimaryAbility.cs");
exec("./scripts/behaviors/controls/SecondaryAbility.cs");
//Vehicles
exec("./scripts/behaviors/vehicles/tanks/TankMovement.cs");
//Main Weapon
exec("./scripts/behaviors/combat/ChargeShot.cs");
//Weapon Powerups
exec("./scripts/behaviors/combat/powerups/LaserBeam.cs");
exec("./scripts/behaviors/combat/powerups/SpreadShot.cs");
exec("./scripts/behaviors/combat/powerups/MineShot.cs");
exec("./scripts/behaviors/combat/powerups/SniperShot.cs");
//Utility Powerups
exec("./scripts/behaviors/combat/powerups/Regeneration.cs");
exec("./scripts/behaviors/combat/powerups/Teleport.cs");
exec("./scripts/behaviors/combat/powerups/SpeedBoost.cs");
exec("./scripts/behaviors/combat/damage/TakesDamage.cs");
exec("./scripts/behaviors/combat/damage/DealsDamage.cs");
exec("./scripts/behaviors/combat/damage/SlowOnDamage.cs");
exec("./scripts/behaviors/combat/damage/FixedHealthBar.cs");
exec("./scripts/behaviors/spawn/PowerupSpawner.cs");
//Misc
exec("./scripts/behaviors/misc/ProximitySensor.cs");
//AI
exec("./scripts/behaviors/AI/turret/TurretAbility.cs");
exec("./scripts/behaviors/AI/turret/TurretAI.cs");
//Teams
exec("./scripts/behaviors/team/Team.cs");
%id = %this.getId();
GlobalActionMap.bindCmd(keyboard, "enter", "", %id @ ".resetMap1();");
GlobalActionMap.bindCmd(keyboard, "escape", "", %id @ ".resetMenu();");
setRandomSeed();
createSceneWindow();
createScene();
mySceneWindow.setScene(myScene);
//myScene.setDebugOn("collision", "position");
$p1TankFrame = 0;
$p2TankFrame = 8;
$maxTankFrame = 64;
alxPlay("MyModule:introMusic");
%this.resetMenu();
}
function MyModule::destroy( %this )
{
destroySceneWindow();
alxStopAll();
}
function MyModule::resetMenu(%this)
{
%this.unbind();
//alxStopAll();
myScene.clear();
%id = %this.getId();
GlobalActionMap.bindCmd(keyboard, "v", "",%id @ ".changeColorP1L();");
GlobalActionMap.bindCmd(keyboard, "b", "",%id @ ".changeColorP1R();");
GlobalActionMap.bindCmd(keyboard, ",", "",%id @ ".changeColorP2L();");
GlobalActionMap.bindCmd(keyboard, ".", "",%id @ ".changeColorP2R();");
%items = createMenuItems(0, 0, 25);
for(%i = 0 ; %i<getWordCount(%items);%i++) {
myScene.add(getWord(%items, %i));
}
%tankP1 = createBasicTank($p1TankFrame, -25, 20);
%tankP1.Angle = -120;
%tankP1.Size = "15 16";
myScene.add(%tankP1);
%tankP2 = createBasicTank($p2TankFrame, 25, 20);
%tankP2.Angle = 120;
%tankP2.Size = "15 16";
myScene.add(%tankP2);
}
function MyModule::unbind(%this)
{
GlobalActionMap.unbind(keyboard, "v");
GlobalActionMap.unbind(keyboard, "b");
GlobalActionMap.unbind(keyboard, ",");
GlobalActionMap.unbind(keyboard, ".");
}
function MyModule::changeColorP1R(%this)
{
$p1TankFrame = ($p1TankFrame + 8) % $maxTankFrame;
%this.resetMenu();
}
function MyModule::changeColorP2R(%this)
{
$p2TankFrame = ($p2TankFrame + 8) % $maxTankFrame;
%this.resetMenu();
}
function MyModule::changeColorP1L(%this)
{
$p1TankFrame = $p1TankFrame <= 0 ? $maxTankFrame - 8 : ($p1TankFrame - 8) % $maxTankFrame;
%this.resetMenu();
}
function MyModule::changeColorP2L(%this)
{
$p2TankFrame = $p2TankFrame <= 0 ? $maxTankFrame - 8 : ($p2TankFrame - 8) % $maxTankFrame;
%this.resetMenu();
}
function MyModule::resetMap1(%this)
{
%this.unbind();
alxStopAll();
myScene.clear();
myScene.add(createBackground());
/////////////////////////////TWEAK AND USE AS POWERUP AURA
//Decrease tranparency
//Change color depending on the powerup (create six particles, one for each powerup?)
//Add and remove aura when powerup is picked up? (search for "secondaryKey")
%test = new ParticlePlayer();
%test.Particle = "ToyAssets:ForceBubble";
%test.Position = "15 0";
%test.setSizeScale(0.1);
%test.setBlendAlpha(1);
myScene.add(%test);
%tankP1 = createPlayer1Tank($p1TankFrame, -45, 0, -90);
myScene.add(%tankP1.healthBar);
myScene.add(%tankP1);
%tankP2 = createPlayer2Tank($p2TankFrame, 45, 0, 90);
myScene.add(%tankP2.healthBar);
myScene.add(%tankP2);
//Top Powerup Area
myScene.add(createBarrier(0,45, 20, 5));
myScene.add(createBarrier(-16,40, 20, 5, 35));
myScene.add(createBarrier(16,40, 20, 5, -35));
myScene.add(createBarrier(0,25, 15, 5));
//Bottom Powerup Area
myScene.add(createBarrier(0,-45, 20, 5));
myScene.add(createBarrier(-16,-40, 20, 5, -35));
myScene.add(createBarrier(16,-40, 20, 5, 35));
myScene.add(createBarrier(0,-25, 15, 5));
//Left Area
myScene.add(createBarrier(-28,-12, 5, 15, -25));
myScene.add(createBarrier(-28,12, 5, 15, 25));
//Right Area
myScene.add(createBarrier(28,-12, 5, 15, 25));
myScene.add(createBarrier(28,12, 5, 15, -25));
//Middle Area
myScene.add(createBarrier(0,0, 5, 15));
//Powerups
myScene.add(createPowerupSpawner(0, 35, "0 3 5"));
myScene.add(createPowerupSpawner(0, -35, "1 2 4 6"));
// Corner Turrets
myScene.add(createRandomTurret(47, 47, 16, 130));
myScene.add(createRandomTurret(-47, 47, 16, -130));
myScene.add(createRandomTurret(47, -47, 16, 50));
myScene.add(createRandomTurret(-47, -47, 16,-50));
// Powerup Turrets
myScene.add(createRandomTurret(22, 47, 13, -130));
myScene.add(createRandomTurret(-22, 47, 13, 130));
myScene.add(createRandomTurret(22, -47, 13, -50));
myScene.add(createRandomTurret(-22, -47, 13,50));
}
function createPlayer1Tank(%initialFrame, %x_pos, %y_pos, %angle)
{
%p1Tank = createTank(%initialFrame, %x_pos, %y_pos);
%p1Tank.Angle = %angle;
//Controls
%primary = PrimaryAbilityBehavior.createInstance();
%primary.key = "keyboard v";
%secondary = SecondaryAbilityBehavior.createInstance();
%secondary.key = "keyboard b";
%p1Tank.addBehavior(%primary);
%p1Tank.addBehavior(%secondary);
%controlsP1 = TankControlsBehavior.createInstance();
%controlsP1.forwardKey = "keyboard w";
%controlsP1.backwardKey = "keyboard s";
%controlsP1.leftKey = "keyboard a";
%controlsP1.rightKey = "keyboard d";
%p1Tank.addBehavior(%controlsP1);
//Weapons
%chargeShotP1 = ChargeShotBehavior.createInstance();
%p1Tank.addBehavior(%chargeShotP1);
%team1 = TeamBehavior.createInstance();
%team1.teamID = 1;
%p1Tank.addBehavior(%team1);
return %p1Tank;
}
function createPlayer2Tank(%initialFrame, %x_pos, %y_pos, %angle)
{
%p2Tank = createTank(%initialFrame, %x_pos, %y_pos);
%p2Tank.Angle = %angle;
%primary = PrimaryAbilityBehavior.createInstance();
%primary.key = "keyboard ,";
%secondary = SecondaryAbilityBehavior.createInstance();
%secondary.key = "keyboard .";
%p2Tank.addBehavior(%primary);
%p2Tank.addBehavior(%secondary);
%controlsP2 = TankControlsBehavior.createInstance();
%controlsP2.forwardKey = "keyboard up";
%controlsP2.backwardKey = "keyboard down";
%controlsP2.leftKey = "keyboard left";
%controlsP2.rightKey = "keyboard right";
%p2Tank.addBehavior(%controlsP2);
%chargeShotP2 = ChargeShotBehavior.createInstance();
%p2Tank.addBehavior(%chargeShotP2);
%team2 = TeamBehavior.createInstance();
%team2.teamID = 2;
%p2Tank.addBehavior(%team2);
return %p2Tank;
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Text.RegularExpressions.Regex.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Text.RegularExpressions
{
public partial class Regex : System.Runtime.Serialization.ISerializable
{
#region Methods and constructors
public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname)
{
}
public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[] attributes)
{
}
public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[] attributes, string resourceFile)
{
}
public static string Escape(string str)
{
return default(string);
}
public string[] GetGroupNames()
{
Contract.Ensures(Contract.Result<string[]>() != null);
return default(string[]);
}
public int[] GetGroupNumbers()
{
Contract.Ensures(Contract.Result<int[]>() != null);
return default(int[]);
}
public string GroupNameFromNumber(int i)
{
return default(string);
}
public int GroupNumberFromName(string name)
{
return default(int);
}
protected void InitializeReferences()
{
}
public bool IsMatch(string input)
{
Contract.Ensures(0 <= input.Length);
return default(bool);
}
public bool IsMatch(string input, int startat)
{
Contract.Ensures((startat - input.Length) <= 0);
Contract.Ensures(0 <= input.Length);
return default(bool);
}
public static bool IsMatch(string input, string pattern, RegexOptions options)
{
Contract.Ensures(0 <= input.Length);
return default(bool);
}
public static bool IsMatch(string input, string pattern)
{
Contract.Ensures(0 <= input.Length);
return default(bool);
}
public System.Text.RegularExpressions.Match Match(string input)
{
Contract.Ensures(0 <= input.Length);
return default(System.Text.RegularExpressions.Match);
}
public System.Text.RegularExpressions.Match Match(string input, int beginning, int length)
{
Contract.Ensures((length - input.Length) <= 0);
Contract.Ensures(0 <= input.Length);
return default(System.Text.RegularExpressions.Match);
}
public static System.Text.RegularExpressions.Match Match(string input, string pattern, RegexOptions options)
{
Contract.Ensures(0 <= input.Length);
return default(System.Text.RegularExpressions.Match);
}
public System.Text.RegularExpressions.Match Match(string input, int startat)
{
Contract.Ensures((startat - input.Length) <= 0);
Contract.Ensures(0 <= input.Length);
return default(System.Text.RegularExpressions.Match);
}
public static Match Match(string input, string pattern)
{
Contract.Ensures(0 <= input.Length);
return default(Match);
}
public static MatchCollection Matches(string input, string pattern, RegexOptions options)
{
Contract.Ensures(Contract.Result<System.Text.RegularExpressions.MatchCollection>() != null);
return default(MatchCollection);
}
public MatchCollection Matches(string input)
{
Contract.Ensures(Contract.Result<System.Text.RegularExpressions.MatchCollection>() != null);
return default(MatchCollection);
}
public static MatchCollection Matches(string input, string pattern)
{
Contract.Ensures(Contract.Result<System.Text.RegularExpressions.MatchCollection>() != null);
return default(MatchCollection);
}
public MatchCollection Matches(string input, int startat)
{
Contract.Ensures(Contract.Result<System.Text.RegularExpressions.MatchCollection>() != null);
return default(MatchCollection);
}
public Regex(string pattern, RegexOptions options)
{
}
protected Regex(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
Contract.Requires(info != null);
}
public Regex(string pattern)
{
}
protected Regex()
{
}
public static string Replace(string input, string pattern, MatchEvaluator evaluator)
{
return default(string);
}
public string Replace(string input, string replacement, int count)
{
return default(string);
}
public string Replace(string input, string replacement, int count, int startat)
{
return default(string);
}
public string Replace(string input, string replacement)
{
return default(string);
}
public static string Replace(string input, string pattern, string replacement)
{
return default(string);
}
public static string Replace(string input, string pattern, string replacement, RegexOptions options)
{
return default(string);
}
public string Replace(string input, MatchEvaluator evaluator, int count)
{
return default(string);
}
public string Replace(string input, MatchEvaluator evaluator, int count, int startat)
{
return default(string);
}
public static string Replace(string input, string pattern, MatchEvaluator evaluator, RegexOptions options)
{
return default(string);
}
public string Replace(string input, MatchEvaluator evaluator)
{
return default(string);
}
public string[] Split(string input, int count, int startat)
{
return default(string[]);
}
public string[] Split(string input)
{
return default(string[]);
}
public static string[] Split(string input, string pattern, RegexOptions options)
{
return default(string[]);
}
public static string[] Split(string input, string pattern)
{
return default(string[]);
}
public string[] Split(string input, int count)
{
return default(string[]);
}
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext context)
{
}
public override string ToString()
{
return default(string);
}
public static string Unescape(string str)
{
return default(string);
}
protected bool UseOptionC()
{
Contract.Ensures(Contract.Result<bool>() == ((((this.roptions & ((System.Text.RegularExpressions.RegexOptions)(8)))) == ((System.Text.RegularExpressions.RegexOptions)(0))) == false));
return default(bool);
}
protected bool UseOptionR()
{
Contract.Ensures(Contract.Result<bool>() == ((((this.roptions & ((System.Text.RegularExpressions.RegexOptions)(64)))) == ((System.Text.RegularExpressions.RegexOptions)(0))) == false));
return default(bool);
}
#endregion
#region Properties and indexers
public static int CacheSize
{
get
{
return default(int);
}
set
{
}
}
public RegexOptions Options
{
get
{
Contract.Ensures(Contract.Result<System.Text.RegularExpressions.RegexOptions>() == this.roptions);
return default(RegexOptions);
}
}
public bool RightToLeft
{
get
{
Contract.Ensures(Contract.Result<bool>() == ((((this.roptions & ((System.Text.RegularExpressions.RegexOptions)(64)))) == ((System.Text.RegularExpressions.RegexOptions)(0))) == false));
return default(bool);
}
}
#endregion
#region Fields
internal protected System.Collections.Hashtable capnames;
internal protected System.Collections.Hashtable caps;
internal protected int capsize;
internal protected string[] capslist;
internal protected RegexRunnerFactory factory;
internal protected string pattern;
internal protected RegexOptions roptions;
#endregion
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2015 FUJIWARA, Yusuke
//
// 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 -- License Terms --
#if UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
#if UNITY
using System.Collections;
#endif // UNITY
using System.Collections.Generic;
#if UNITY
using System.Reflection;
#endif // UNITY
using System.Runtime.Serialization;
namespace MsgPack.Serialization.CollectionSerializers
{
/// <summary>
/// Provides basic features for generic dictionary serializers.
/// </summary>
/// <typeparam name="TDictionary">The type of the dictionary.</typeparam>
/// <typeparam name="TKey">The type of the key of dictionary.</typeparam>
/// <typeparam name="TValue">The type of the value of dictionary.</typeparam>
/// <remarks>
/// This class provides framework to implement variable collection serializer, and this type seals some virtual members to maximize future backward compatibility.
/// If you cannot use this class, you can implement your own serializer which inherits <see cref="MessagePackSerializer{T}"/> and implements <see cref="ICollectionInstanceFactory"/>.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes", Justification = "By design" )]
public abstract class DictionaryMessagePackSerializer<TDictionary, TKey, TValue> : MessagePackSerializer<TDictionary>, ICollectionInstanceFactory
where TDictionary : IDictionary<TKey, TValue>
{
private readonly MessagePackSerializer<TKey> _keySerializer;
private readonly MessagePackSerializer<TValue> _valueSerializer;
/// <summary>
/// Initializes a new instance of the <see cref="DictionaryMessagePackSerializer{TDictionary, TKey, TValue}"/> class.
/// </summary>
/// <param name="ownerContext">A <see cref="SerializationContext"/> which owns this serializer.</param>
/// <param name="schema">
/// The schema for collection itself or its items for the member this instance will be used to.
/// <c>null</c> will be considered as <see cref="PolymorphismSchema.Default"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="ownerContext"/> is <c>null</c>.
/// </exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by base .ctor" )]
protected DictionaryMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema )
: base( ownerContext )
{
var safeSchema = schema ?? PolymorphismSchema.Default;
this._keySerializer = ownerContext.GetSerializer<TKey>( safeSchema.KeySchema );
this._valueSerializer = ownerContext.GetSerializer<TValue>( safeSchema.ItemSchema );
}
/// <summary>
/// Serializes specified object with specified <see cref="Packer"/>.
/// </summary>
/// <param name="packer"><see cref="Packer"/> which packs values in <paramref name="objectTree"/>. This value will not be <c>null</c>.</param>
/// <param name="objectTree">Object to be serialized.</param>
/// <exception cref="SerializationException">
/// <typeparamref name="TDictionary"/> is not serializable etc.
/// </exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )]
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )]
protected internal sealed override void PackToCore( Packer packer, TDictionary objectTree )
{
#if ( !UNITY && !XAMIOS ) || AOT_CHECK
packer.PackMapHeader( objectTree.Count );
foreach ( var item in objectTree )
{
this._keySerializer.PackTo( packer, item.Key );
this._valueSerializer.PackTo( packer, item.Value );
}
#else
// .constraind call for TDictionary.get_Count/TDictionary.GetEnumerator() causes AOT error.
// So use cast and invoke as normal call (it might cause boxing, but most collection should be reference type).
packer.PackMapHeader( ( objectTree as IDictionary<TKey, TValue> ).Count );
foreach ( var item in objectTree as IEnumerable<KeyValuePair<TKey,TValue>> )
{
this._keySerializer.PackTo( packer, item.Key );
this._valueSerializer.PackTo( packer, item.Value );
}
#endif // ( !UNITY && !XAMIOS ) || AOT_CHECK
}
/// <summary>
/// Deserializes object with specified <see cref="Unpacker"/>.
/// </summary>
/// <param name="unpacker"><see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param>
/// <returns>Deserialized object.</returns>
/// <exception cref="SerializationException">
/// Failed to deserialize object due to invalid unpacker state, stream content, or so.
/// </exception>
/// <exception cref="MessageTypeException">
/// Failed to deserialize object due to invalid unpacker state, stream content, or so.
/// </exception>
/// <exception cref="InvalidMessagePackStreamException">
/// Failed to deserialize object due to invalid unpacker state, stream content, or so.
/// </exception>
/// <exception cref="NotSupportedException">
/// <typeparamref name="TDictionary"/> is abstract type.
/// </exception>
/// <remarks>
/// This method invokes <see cref="CreateInstance(int)"/>, and then fill deserialized items to resultong collection.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )]
protected internal sealed override TDictionary UnpackFromCore( Unpacker unpacker )
{
if ( !unpacker.IsMapHeader )
{
throw SerializationExceptions.NewIsNotArrayHeader();
}
return this.InternalUnpackFromCore( unpacker );
}
internal virtual TDictionary InternalUnpackFromCore( Unpacker unpacker )
{
var itemsCount = UnpackHelpers.GetItemsCount( unpacker );
var collection = this.CreateInstance( itemsCount );
this.UnpackToCore( unpacker, collection, itemsCount );
return collection;
}
/// <summary>
/// Creates a new collection instance with specified initial capacity.
/// </summary>
/// <param name="initialCapacity">
/// The initial capacy of creating collection.
/// Note that this parameter may <c>0</c> for non-empty collection.
/// </param>
/// <returns>
/// New collection instance. This value will not be <c>null</c>.
/// </returns>
/// <remarks>
/// An author of <see cref="Unpacker" /> could implement unpacker for non-MessagePack format,
/// so implementer of this interface should not rely on that <paramref name="initialCapacity" /> reflects actual items count.
/// For example, JSON unpacker cannot supply collection items count efficiently.
/// </remarks>
/// <seealso cref="ICollectionInstanceFactory.CreateInstance"/>
protected abstract TDictionary CreateInstance( int initialCapacity );
object ICollectionInstanceFactory.CreateInstance( int initialCapacity )
{
return this.CreateInstance( initialCapacity );
}
/// <summary>
/// Deserializes collection items with specified <see cref="Unpacker"/> and stores them to <paramref name="collection"/>.
/// </summary>
/// <param name="unpacker"><see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param>
/// <param name="collection">Collection that the items to be stored. This value will not be <c>null</c>.</param>
/// <exception cref="SerializationException">
/// Failed to deserialize object due to invalid unpacker state, stream content, or so.
/// </exception>
/// <exception cref="NotSupportedException">
/// <typeparamref name="TDictionary"/> is not collection.
/// </exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )]
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )]
protected internal sealed override void UnpackToCore( Unpacker unpacker, TDictionary collection )
{
if ( !unpacker.IsMapHeader )
{
throw SerializationExceptions.NewIsNotArrayHeader();
}
this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) );
}
private void UnpackToCore( Unpacker unpacker, TDictionary collection, int itemsCount )
{
for ( int i = 0; i < itemsCount; i++ )
{
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewMissingItem( i );
}
TKey key;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
key = this._keySerializer.UnpackFrom( unpacker );
}
else
{
using ( var subtreeUnpacker = unpacker.ReadSubtree() )
{
key = this._keySerializer.UnpackFrom( subtreeUnpacker );
}
}
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewMissingItem( i );
}
TValue value;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
value = this._valueSerializer.UnpackFrom( unpacker );
}
else
{
using ( var subtreeUnpacker = unpacker.ReadSubtree() )
{
value = this._valueSerializer.UnpackFrom( subtreeUnpacker );
}
}
#if ( !UNITY && !XAMIOS ) || AOT_CHECK
collection.Add( key, value );
#else
// .constraind call for TDictionary.Add causes AOT error.
// So use cast and invoke as normal call (it might cause boxing, but most collection should be reference type).
( collection as IDictionary<TKey, TValue> ).Add( key, value );
#endif // ( !UNITY && !XAMIOS ) || AOT_CHECK
}
}
}
#if UNITY
internal abstract class UnityDictionaryMessagePackSerializer : NonGenericMessagePackSerializer,
ICollectionInstanceFactory
{
private readonly IMessagePackSingleObjectSerializer _keySerializer;
private readonly IMessagePackSingleObjectSerializer _valueSerializer;
private readonly MethodInfo _add;
private readonly MethodInfo _getCount;
private readonly MethodInfo _getKey;
private readonly MethodInfo _getValue;
protected UnityDictionaryMessagePackSerializer(
SerializationContext ownerContext,
Type targetType,
Type keyType,
Type valueType,
CollectionTraits traits,
PolymorphismSchema schema
)
: base( ownerContext, targetType )
{
var safeSchema = schema ?? PolymorphismSchema.Default;
this._keySerializer = ownerContext.GetSerializer( keyType, safeSchema.KeySchema );
this._valueSerializer = ownerContext.GetSerializer( valueType, safeSchema.ItemSchema );
this._add = traits.AddMethod;
this._getCount = traits.CountPropertyGetter;
this._getKey = traits.ElementType.GetProperty( "Key" ).GetGetMethod();
this._getValue = traits.ElementType.GetProperty( "Value" ).GetGetMethod();
}
protected internal override sealed void PackToCore( Packer packer, object objectTree )
{
packer.PackMapHeader( ( int )this._getCount.InvokePreservingExceptionType( objectTree ) );
// ReSharper disable once PossibleNullReferenceException
foreach ( var item in objectTree as IEnumerable )
{
this._keySerializer.PackTo( packer, this._getKey.InvokePreservingExceptionType( item ) );
this._valueSerializer.PackTo( packer, this._getValue.InvokePreservingExceptionType( item ) );
}
}
protected internal override sealed object UnpackFromCore( Unpacker unpacker )
{
if ( !unpacker.IsMapHeader )
{
throw SerializationExceptions.NewIsNotArrayHeader();
}
return this.InternalUnpackFromCore( unpacker );
}
internal virtual object InternalUnpackFromCore( Unpacker unpacker )
{
var itemsCount = UnpackHelpers.GetItemsCount( unpacker );
var collection = this.CreateInstance( itemsCount );
this.UnpackToCore( unpacker, collection, itemsCount );
return collection;
}
protected abstract object CreateInstance( int initialCapacity );
object ICollectionInstanceFactory.CreateInstance( int initialCapacity )
{
return this.CreateInstance( initialCapacity );
}
protected internal override sealed void UnpackToCore( Unpacker unpacker, object collection )
{
if ( !unpacker.IsMapHeader )
{
throw SerializationExceptions.NewIsNotArrayHeader();
}
this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) );
}
private void UnpackToCore( Unpacker unpacker, object collection, int itemsCount )
{
for ( int i = 0; i < itemsCount; i++ )
{
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewMissingItem( i );
}
object key;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
key = this._keySerializer.UnpackFrom( unpacker );
}
else
{
using ( var subtreeUnpacker = unpacker.ReadSubtree() )
{
key = this._keySerializer.UnpackFrom( subtreeUnpacker );
}
}
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewMissingItem( i );
}
object value;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
value = this._valueSerializer.UnpackFrom( unpacker );
}
else
{
using ( var subtreeUnpacker = unpacker.ReadSubtree() )
{
value = this._valueSerializer.UnpackFrom( subtreeUnpacker );
}
}
this._add.InvokePreservingExceptionType( collection, key, value );
}
}
}
#endif // UNITY
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license 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.Security.Permissions;
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<>))]
[HostProtection(Synchronization = true, ExternalThreading = true)]
#if !FEATURE_CORECLR
[Serializable]
#endif //!FEATURE_CORECLR
public 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;
}
}
#if !FEATURE_CORECLR
[NonSerialized]
#endif //!FEATURE_CORECLR
private volatile Node m_head; // The stack is a singly linked list, and only remembers the head.
#if !FEATURE_CORECLR
private T[] m_serializationArray; // Used for custom serialization.
#endif //!FEATURE_CORECLR
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>
/// Initializes a new instance of the <see cref="ConcurrentStack{T}"/>
/// class that contains elements copied from the specified collection
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new <see
/// cref="ConcurrentStack{T}"/>.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="collection"/> argument is
/// null.</exception>
public ConcurrentStack(IEnumerable<T> collection)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
InitializeFromCollection(collection);
}
/// <summary>
/// Initializes the contents of the stack from an existing collection.
/// </summary>
/// <param name="collection">A collection from which to copy elements.</param>
private void InitializeFromCollection(IEnumerable<T> collection)
{
// We just copy the contents of the collection to our stack.
Node lastNode = null;
foreach (T element in collection)
{
Node newNode = new Node(element);
newNode.m_next = lastNode;
lastNode = newNode;
}
m_head = lastNode;
}
#if !FEATURE_CORECLR
/// <summary>
/// Get the data array to be serialized
/// </summary>
[OnSerializing]
private void OnSerializing(StreamingContext context)
{
// save the data into the serialization array to be saved
m_serializationArray = ToArray();
}
/// <summary>
/// Construct the stack from a previously seiralized one
/// </summary>
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
Contract.Assert(m_serializationArray != null);
// Add the elements to our stack. We need to add them from head-to-tail, to
// preserve the original ordering of the stack before serialization.
Node prevNode = null;
Node head = null;
for (int i = 0; i < m_serializationArray.Length; i++)
{
Node currNode = new Node(m_serializationArray[i]);
if (prevNode == null)
{
head = currNode;
}
else
{
prevNode.m_next = currNode;
}
prevNode = currNode;
}
m_head = head;
m_serializationArray = null;
}
#endif //!FEATURE_CORECLR
/// <summary>
/// Gets a value that indicates whether the <see cref="ConcurrentStack{T}"/> is empty.
/// </summary>
/// <value>true if the <see cref="ConcurrentStack{T}"/> is empty; otherwise, false.</value>
/// <remarks>
/// For determining whether the collection contains any items, use of this property is recommended
/// rather than retrieving the number of items from the <see cref="Count"/> property and comparing it
/// to 0. However, as this collection is intended to be accessed concurrently, it may be the case
/// that another thread will modify the collection after <see cref="IsEmpty"/> returns, thus invalidating
/// the result.
/// </remarks>
public bool IsEmpty
{
// Checks whether the stack is empty. Clearly the answer may be out of date even prior to
// the function returning (i.e. if another thread concurrently adds to the stack). It does
// guarantee, however, that, if another thread does not mutate the stack, a subsequent call
// to TryPop will return true -- i.e. it will also read the stack as non-empty.
get { return m_head == null; }
}
/// <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(Environment.GetResourceString("ConcurrentCollection_SyncRoot_NotSupported"));
}
}
/// <summary>
/// Removes all objects from the <see cref="ConcurrentStack{T}"/>.
/// </summary>
public void Clear()
{
// Clear the list by setting the head to null. We don't need to use an atomic
// operation for this: anybody who is mutating the head by pushing or popping
// will need to use an atomic operation to guarantee they serialize and don't
// overwrite our setting of the head to null.
m_head = null;
}
/// <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("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("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>
/// Inserts multiple objects at the top of the <see cref="ConcurrentStack{T}"/> atomically.
/// </summary>
/// <param name="items">The objects to push onto the <see cref="ConcurrentStack{T}"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference
/// (Nothing in Visual Basic).</exception>
/// <remarks>
/// When adding multiple items to the stack, using PushRange is a more efficient
/// mechanism than using <see cref="Push"/> one item at a time. Additionally, PushRange
/// guarantees that all of the elements will be added atomically, meaning that no other threads will
/// be able to inject elements between the elements being pushed. Items at lower indices in
/// the <paramref name="items"/> array will be pushed before items at higher indices.
/// </remarks>
public void PushRange(T[] items)
{
if (items == null)
{
throw new ArgumentNullException("items");
}
PushRange(items, 0, items.Length);
}
/// <summary>
/// Inserts multiple objects at the top of the <see cref="ConcurrentStack{T}"/> atomically.
/// </summary>
/// <param name="items">The objects to push onto the <see cref="ConcurrentStack{T}"/>.</param>
/// <param name="startIndex">The zero-based offset in <paramref name="items"/> at which to begin
/// inserting elements onto the top of the <see cref="ConcurrentStack{T}"/>.</param>
/// <param name="count">The number of elements to be inserted onto the top of the <see
/// cref="ConcurrentStack{T}"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference
/// (Nothing in Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="startIndex"/> or <paramref
/// name="count"/> is negative. Or <paramref name="startIndex"/> is greater than or equal to the length
/// of <paramref name="items"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="startIndex"/> + <paramref name="count"/> is
/// greater than the length of <paramref name="items"/>.</exception>
/// <remarks>
/// When adding multiple items to the stack, using PushRange is a more efficient
/// mechanism than using <see cref="Push"/> one item at a time. Additionally, PushRange
/// guarantees that all of the elements will be added atomically, meaning that no other threads will
/// be able to inject elements between the elements being pushed. Items at lower indices in the
/// <paramref name="items"/> array will be pushed before items at higher indices.
/// </remarks>
public void PushRange(T[] items, int startIndex, int count)
{
ValidatePushPopRangeInput(items, startIndex, count);
// No op if the count is zero
if (count == 0)
return;
Node head, tail;
head = tail = new Node(items[startIndex]);
for (int i = startIndex + 1; i < startIndex + count; i++)
{
Node node = new Node(items[i]);
node.m_next = head;
head = node;
}
tail.m_next = m_head;
if (Interlocked.CompareExchange(ref m_head, head, tail.m_next) == tail.m_next)
{
return;
}
// If we failed, go to the slow path and loop around until we succeed.
PushCore(head, tail);
}
/// <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);
#if !FEATURE_CORECLR
if (CDSCollectionETWBCLProvider.Log.IsEnabled())
{
CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPushFailed(spin.Count);
}
#endif // !FEATURE_CORECLR
}
/// <summary>
/// Local helper function to validate the Pop Push range methods input
/// </summary>
private void ValidatePushPopRangeInput(T[] items, int startIndex, int count)
{
if (items == null)
{
throw new ArgumentNullException("items");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ConcurrentStack_PushPopRange_CountOutOfRange"));
}
int length = items.Length;
if (startIndex >= length || startIndex < 0)
{
throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ConcurrentStack_PushPopRange_StartOutOfRange"));
}
if (length - count < startIndex) //instead of (startIndex + count > items.Length) to prevent overflow
{
throw new ArgumentException(Environment.GetResourceString("ConcurrentStack_PushPopRange_InvalidCount"));
}
}
/// <summary>
/// Attempts to add an object to the <see
/// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>.
/// </summary>
/// <param name="item">The object to add to the <see
/// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. The value can be a null
/// reference (Nothing in Visual Basic) for reference types.
/// </param>
/// <returns>true if the object was added successfully; otherwise, false.</returns>
/// <remarks>For <see cref="ConcurrentStack{T}"/>, this operation
/// will always insert the object onto the top of the <see cref="ConcurrentStack{T}"/>
/// and return true.</remarks>
bool IProducerConsumerCollection<T>.TryAdd(T item)
{
Push(item);
return true;
}
/// <summary>
/// Attempts to return an object from the top of the <see cref="ConcurrentStack{T}"/>
/// without removing it.
/// </summary>
/// <param name="result">When this method returns, <paramref name="result"/> contains an object from
/// the top of the <see cref="T:System.Collections.Concurrent.ConccurrentStack{T}"/> or an
/// unspecified value if the operation failed.</param>
/// <returns>true if and object was returned successfully; otherwise, false.</returns>
public bool TryPeek(out T result)
{
Node head = m_head;
// If the stack is empty, return false; else return the element and true.
if (head == null)
{
result = default(T);
return false;
}
else
{
result = head.m_value;
return true;
}
}
/// <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}"/>
/// succesfully; 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>
/// Attempts to pop and return multiple objects from the top of the <see cref="ConcurrentStack{T}"/>
/// atomically.
/// </summary>
/// <param name="items">
/// The <see cref="T:System.Array"/> to which objects popped from the top of the <see
/// cref="ConcurrentStack{T}"/> will be added.
/// </param>
/// <returns>The number of objects successfully popped from the top of the <see
/// cref="ConcurrentStack{T}"/> and inserted in
/// <paramref name="items"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="items"/> is a null argument (Nothing
/// in Visual Basic).</exception>
/// <remarks>
/// When popping multiple items, if there is little contention on the stack, using
/// TryPopRange can be more efficient than using <see cref="TryPop"/>
/// once per item to be removed. Nodes fill the <paramref name="items"/>
/// with the first node to be popped at the startIndex, the second node to be popped
/// at startIndex + 1, and so on.
/// </remarks>
public int TryPopRange(T[] items)
{
if (items == null)
{
throw new ArgumentNullException("items");
}
return TryPopRange(items, 0, items.Length);
}
/// <summary>
/// Attempts to pop and return multiple objects from the top of the <see cref="ConcurrentStack{T}"/>
/// atomically.
/// </summary>
/// <param name="items">
/// The <see cref="T:System.Array"/> to which objects popped from the top of the <see
/// cref="ConcurrentStack{T}"/> will be added.
/// </param>
/// <param name="startIndex">The zero-based offset in <paramref name="items"/> at which to begin
/// inserting elements from the top of the <see cref="ConcurrentStack{T}"/>.</param>
/// <param name="count">The number of elements to be popped from top of the <see
/// cref="ConcurrentStack{T}"/> and inserted into <paramref name="items"/>.</param>
/// <returns>The number of objects successfully popped from the top of
/// the <see cref="ConcurrentStack{T}"/> and inserted in <paramref name="items"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference
/// (Nothing in Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="startIndex"/> or <paramref
/// name="count"/> is negative. Or <paramref name="startIndex"/> is greater than or equal to the length
/// of <paramref name="items"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="startIndex"/> + <paramref name="count"/> is
/// greater than the length of <paramref name="items"/>.</exception>
/// <remarks>
/// When popping multiple items, if there is little contention on the stack, using
/// TryPopRange can be more efficient than using <see cref="TryPop"/>
/// once per item to be removed. Nodes fill the <paramref name="items"/>
/// with the first node to be popped at the startIndex, the second node to be popped
/// at startIndex + 1, and so on.
/// </remarks>
public int TryPopRange(T[] items, int startIndex, int count)
{
ValidatePushPopRangeInput(items, startIndex, count);
// No op if the count is zero
if (count == 0)
return 0;
Node poppedHead;
int nodesCount = TryPopCore(count, out poppedHead);
if (nodesCount > 0)
{
CopyRemovedItems(poppedHead, items, startIndex, nodesCount);
}
return nodesCount;
}
/// <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 = new Random(Environment.TickCount & Int32.MaxValue); // avoid the case where TickCount could return Int32.MinValue
while (true)
{
head = m_head;
// Is the stack empty?
if (head == null)
{
#if !FEATURE_CORECLR
if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled())
{
CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count);
}
#endif //!FEATURE_CORECLR
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)
{
#if !FEATURE_CORECLR
if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled())
{
CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count);
}
#endif //!FEATURE_CORECLR
// 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();
}
backoff = spin.NextSpinWillYield ? r.Next(1, BACKOFF_MAX_YIELDS) : backoff * 2;
}
}
/// <summary>
/// Local helper function to copy the poped elements into a given collection
/// </summary>
/// <param name="head">The head of the list to be copied</param>
/// <param name="collection">The collection to place the popped items in</param>
/// <param name="startIndex">the beginning of index of where to place the popped items</param>
/// <param name="nodesCount">The number of nodes.</param>
private void CopyRemovedItems(Node head, T[] collection, int startIndex, int nodesCount)
{
Node current = head;
for (int i = startIndex; i < startIndex + nodesCount; i++)
{
collection[i] = current.m_value;
current = current.m_next;
}
}
/// <summary>
/// Attempts to remove and return an object from the <see
/// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>.
/// </summary>
/// <param name="item">
/// When this method returns, if the operation was successful, <paramref name="item"/> 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 succesfully; otherwise, false.</returns>
/// <remarks>For <see cref="ConcurrentStack{T}"/>, this operation will attempt to pope the object at
/// the top of the <see cref="ConcurrentStack{T}"/>.
/// </remarks>
bool IProducerConsumerCollection<T>.TryTake(out T item)
{
return TryPop(out item);
}
/// <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();
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoad.Business.ERCLevel
{
/// <summary>
/// D05_SubContinent_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="D05_SubContinent_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="D04_SubContinent"/> collection.
/// </remarks>
[Serializable]
public partial class D05_SubContinent_ReChild : BusinessBase<D05_SubContinent_ReChild>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="SubContinent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> SubContinent_Child_NameProperty = RegisterProperty<string>(p => p.SubContinent_Child_Name, "Countries Child Name");
/// <summary>
/// Gets or sets the Countries Child Name.
/// </summary>
/// <value>The Countries Child Name.</value>
public string SubContinent_Child_Name
{
get { return GetProperty(SubContinent_Child_NameProperty); }
set { SetProperty(SubContinent_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="D05_SubContinent_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="D05_SubContinent_ReChild"/> object.</returns>
internal static D05_SubContinent_ReChild NewD05_SubContinent_ReChild()
{
return DataPortal.CreateChild<D05_SubContinent_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="D05_SubContinent_ReChild"/> object, based on given parameters.
/// </summary>
/// <param name="subContinent_ID2">The SubContinent_ID2 parameter of the D05_SubContinent_ReChild to fetch.</param>
/// <returns>A reference to the fetched <see cref="D05_SubContinent_ReChild"/> object.</returns>
internal static D05_SubContinent_ReChild GetD05_SubContinent_ReChild(int subContinent_ID2)
{
return DataPortal.FetchChild<D05_SubContinent_ReChild>(subContinent_ID2);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="D05_SubContinent_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public D05_SubContinent_ReChild()
{
// 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="D05_SubContinent_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="D05_SubContinent_ReChild"/> object from the database, based on given criteria.
/// </summary>
/// <param name="subContinent_ID2">The Sub Continent ID2.</param>
protected void Child_Fetch(int subContinent_ID2)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetD05_SubContinent_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID2", subContinent_ID2).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, subContinent_ID2);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
// check all object rules and property rules
BusinessRules.CheckRules();
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="D05_SubContinent_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(SubContinent_Child_NameProperty, dr.GetString("SubContinent_Child_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="D05_SubContinent_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(D04_SubContinent parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddD05_SubContinent_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID2", parent.SubContinent_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@SubContinent_Child_Name", ReadProperty(SubContinent_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="D05_SubContinent_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(D04_SubContinent parent)
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateD05_SubContinent_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID2", parent.SubContinent_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@SubContinent_Child_Name", ReadProperty(SubContinent_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="D05_SubContinent_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(D04_SubContinent parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteD05_SubContinent_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID2", parent.SubContinent_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
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
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web;
using HttpServer;
using log4net;
namespace OpenSim.Framework.Servers.HttpServer
{
public class OSHttpRequest : IOSHttpRequest
{
private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected IHttpRequest _request = null;
protected IHttpClientContext _context = null;
public string[] AcceptTypes
{
get { return _request.AcceptTypes; }
}
public Encoding ContentEncoding
{
get { return _contentEncoding; }
}
private Encoding _contentEncoding;
public long ContentLength
{
get { return _request.ContentLength; }
}
public long ContentLength64
{
get { return ContentLength; }
}
public string ContentType
{
get { return _contentType; }
}
private string _contentType;
public HttpCookieCollection Cookies
{
get
{
RequestCookies cookies = _request.Cookies;
HttpCookieCollection httpCookies = new HttpCookieCollection();
foreach (RequestCookie cookie in cookies)
httpCookies.Add(new HttpCookie(cookie.Name, cookie.Value));
return httpCookies;
}
}
public bool HasEntityBody
{
get { return _request.ContentLength != 0; }
}
public NameValueCollection Headers
{
get { return _request.Headers; }
}
public string HttpMethod
{
get { return _request.Method; }
}
public Stream InputStream
{
get { return _request.Body; }
}
public bool IsSecured
{
get { return _context.IsSecured; }
}
public bool KeepAlive
{
get { return ConnectionType.KeepAlive == _request.Connection; }
}
public NameValueCollection QueryString
{
get { return _queryString; }
}
private NameValueCollection _queryString;
public Hashtable Query
{
get { return _query; }
}
private Hashtable _query;
/// <value>
/// POST request values, if applicable
/// </value>
// public Hashtable Form { get; private set; }
public string RawUrl
{
get { return _request.Uri.AbsolutePath; }
}
public IPEndPoint RemoteIPEndPoint
{
get { return _remoteIPEndPoint; }
}
private IPEndPoint _remoteIPEndPoint;
public Uri Url
{
get { return _request.Uri; }
}
public string UserAgent
{
get { return _userAgent; }
}
private string _userAgent;
internal IHttpRequest IHttpRequest
{
get { return _request; }
}
internal IHttpClientContext IHttpClientContext
{
get { return _context; }
}
/// <summary>
/// Internal whiteboard for handlers to store temporary stuff
/// into.
/// </summary>
internal Dictionary<string, object> Whiteboard
{
get { return _whiteboard; }
}
private Dictionary<string, object> _whiteboard = new Dictionary<string, object>();
public OSHttpRequest() {}
public OSHttpRequest(IHttpClientContext context, IHttpRequest req)
{
_request = req;
_context = context;
if (null != req.Headers["content-encoding"])
{
try
{
_contentEncoding = Encoding.GetEncoding(_request.Headers["content-encoding"]);
}
catch (Exception)
{
// ignore
}
}
if (null != req.Headers["content-type"])
_contentType = _request.Headers["content-type"];
if (null != req.Headers["user-agent"])
_userAgent = req.Headers["user-agent"];
if (null != req.Headers["remote_addr"])
{
try
{
IPAddress addr = IPAddress.Parse(req.Headers["remote_addr"]);
// sometimes req.Headers["remote_port"] returns a comma separated list, so use
// the first one in the list and log it
string[] strPorts = req.Headers["remote_port"].Split(new char[] { ',' });
if (strPorts.Length > 1)
{
_log.ErrorFormat("[OSHttpRequest]: format exception on addr/port {0}:{1}, ignoring",
req.Headers["remote_addr"], req.Headers["remote_port"]);
}
int port = Int32.Parse(strPorts[0]);
_remoteIPEndPoint = new IPEndPoint(addr, port);
}
catch (FormatException)
{
_log.ErrorFormat("[OSHttpRequest]: format exception on addr/port {0}:{1}, ignoring",
req.Headers["remote_addr"], req.Headers["remote_port"]);
}
}
_queryString = new NameValueCollection();
_query = new Hashtable();
try
{
foreach (HttpInputItem item in req.QueryString)
{
try
{
_queryString.Add(item.Name, item.Value);
_query[item.Name] = item.Value;
}
catch (InvalidCastException)
{
_log.DebugFormat("[OSHttpRequest]: error parsing {0} query item, skipping it", item.Name);
continue;
}
}
}
catch (Exception)
{
_log.ErrorFormat("[OSHttpRequest]: Error parsing querystring");
}
// Form = new Hashtable();
// foreach (HttpInputItem item in req.Form)
// {
// _log.DebugFormat("[OSHttpRequest]: Got form item {0}={1}", item.Name, item.Value);
// Form.Add(item.Name, item.Value);
// }
}
public override string ToString()
{
StringBuilder me = new StringBuilder();
me.Append(String.Format("OSHttpRequest: {0} {1}\n", HttpMethod, RawUrl));
foreach (string k in Headers.AllKeys)
{
me.Append(String.Format(" {0}: {1}\n", k, Headers[k]));
}
if (null != RemoteIPEndPoint)
{
me.Append(String.Format(" IP: {0}\n", RemoteIPEndPoint));
}
return me.ToString();
}
}
}
| |
//
// ConsoleCrayon.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.Runtime.InteropServices;
namespace Hyena
{
public static class ConsoleCrayon
{
#region Public API
private static ConsoleColor foreground_color;
public static ConsoleColor ForegroundColor {
get { return foreground_color; }
set {
foreground_color = value;
SetColor (foreground_color, true);
}
}
private static ConsoleColor background_color;
public static ConsoleColor BackgroundColor {
get { return background_color; }
set {
background_color = value;
SetColor (background_color, false);
}
}
public static void ResetColor ()
{
if (XtermColors) {
Console.Write (GetAnsiResetControlCode ());
} else if (Environment.OSVersion.Platform != PlatformID.Unix && !RuntimeIsMono) {
Console.ResetColor ();
}
}
private static void SetColor (ConsoleColor color, bool isForeground)
{
if (color < ConsoleColor.Black || color > ConsoleColor.White) {
throw new ArgumentOutOfRangeException ("color", "Not a ConsoleColor value.");
}
if (XtermColors) {
Console.Write (GetAnsiColorControlCode (color, isForeground));
} else if (Environment.OSVersion.Platform != PlatformID.Unix && !RuntimeIsMono) {
if (isForeground) {
Console.ForegroundColor = color;
} else {
Console.BackgroundColor = color;
}
}
}
#endregion
#region Ansi/VT Code Calculation
// Modified from Mono's System.TermInfoDriver
// License: MIT/X11
// Authors: Gonzalo Paniagua Javier <gonzalo@ximian.com>
// (C) 2005-2006 Novell, Inc <http://www.novell.com>
private static int TranslateColor (ConsoleColor desired, out bool light)
{
light = false;
switch (desired) {
// Dark colors
case ConsoleColor.Black: return 0;
case ConsoleColor.DarkRed: return 1;
case ConsoleColor.DarkGreen: return 2;
case ConsoleColor.DarkYellow: return 3;
case ConsoleColor.DarkBlue: return 4;
case ConsoleColor.DarkMagenta: return 5;
case ConsoleColor.DarkCyan: return 6;
case ConsoleColor.Gray: return 7;
// Light colors
case ConsoleColor.DarkGray: light = true; return 0;
case ConsoleColor.Red: light = true; return 1;
case ConsoleColor.Green: light = true; return 2;
case ConsoleColor.Yellow: light = true; return 3;
case ConsoleColor.Blue: light = true; return 4;
case ConsoleColor.Magenta: light = true; return 5;
case ConsoleColor.Cyan: light = true; return 6;
case ConsoleColor.White: default: light = true; return 7;
}
}
private static string GetAnsiColorControlCode (ConsoleColor color, bool isForeground)
{
// lighter fg colours are 90 -> 97 rather than 30 -> 37
// lighter bg colours are 100 -> 107 rather than 40 -> 47
bool light;
int code = TranslateColor (color, out light) + (isForeground ? 30 : 40) + (light ? 60 : 0);
return String.Format ("\x001b[{0}m", code);
}
private static string GetAnsiResetControlCode ()
{
return "\x001b[0m";
}
#endregion
#region xterm Detection
private static bool? xterm_colors = null;
public static bool XtermColors {
get {
if (xterm_colors == null) {
DetectXtermColors ();
}
return xterm_colors.Value;
}
}
[System.Runtime.InteropServices.DllImport ("libc", EntryPoint="isatty", CallingConvention = CallingConvention.Cdecl)]
private extern static int _isatty (int fd);
private static bool isatty (int fd)
{
try {
return _isatty (fd) == 1;
} catch {
return false;
}
}
private static void DetectXtermColors ()
{
bool _xterm_colors = false;
switch (Environment.GetEnvironmentVariable ("TERM")) {
case "xterm":
case "rxvt":
case "rxvt-unicode":
if (Environment.GetEnvironmentVariable ("COLORTERM") != null) {
_xterm_colors = true;
}
break;
case "xterm-color":
_xterm_colors = true;
break;
}
xterm_colors = _xterm_colors && isatty (1) && isatty (2);
}
#endregion
#region Runtime Detection
private static bool? runtime_is_mono;
public static bool RuntimeIsMono {
get {
if (runtime_is_mono == null) {
runtime_is_mono = Type.GetType ("System.MonoType") != null;
}
return runtime_is_mono.Value;
}
}
#endregion
#region Tests
public static void Test ()
{
TestSelf ();
Console.WriteLine ();
TestAnsi ();
Console.WriteLine ();
TestRuntime ();
}
private static void TestSelf ()
{
Console.WriteLine ("==SELF TEST==");
foreach (ConsoleColor color in Enum.GetValues (typeof (ConsoleColor))) {
ForegroundColor = color;
Console.Write (color);
ResetColor ();
Console.Write (" :: ");
BackgroundColor = color;
Console.Write (color);
ResetColor ();
Console.WriteLine ();
}
}
private static void TestAnsi ()
{
Console.WriteLine ("==ANSI TEST==");
foreach (ConsoleColor color in Enum.GetValues (typeof (ConsoleColor))) {
string color_code_fg = GetAnsiColorControlCode (color, true);
string color_code_bg = GetAnsiColorControlCode (color, false);
Console.Write ("{0}{1}: {2}{3} :: {4}{1}: {5}{3}", color_code_fg, color, color_code_fg.Substring (2),
GetAnsiResetControlCode (), color_code_bg, color_code_bg.Substring (2));
Console.WriteLine ();
}
}
private static void TestRuntime ()
{
Console.WriteLine ("==RUNTIME TEST==");
foreach (ConsoleColor color in Enum.GetValues (typeof (ConsoleColor))) {
Console.ForegroundColor = color;
Console.Write (color);
Console.ResetColor ();
Console.Write (" :: ");
Console.BackgroundColor = color;
Console.Write (color);
Console.ResetColor ();
Console.WriteLine ();
}
}
#endregion
}
}
| |
// Copyright (c) 2014-2015 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file).
// Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE
using System;
using System.Collections.Generic;
using SharpNav.Collections.Generic;
using SharpNav.Geometry;
using SharpNav.Pathfinding;
#if MONOGAME
using Vector3 = Microsoft.Xna.Framework.Vector3;
#elif OPENTK
using Vector3 = OpenTK.Vector3;
#elif SHARPDX
using Vector3 = SharpDX.Vector3;
#endif
namespace SharpNav.Crowds
{
/// <summary>
/// The LocalBoundary class stores segments and polygon indices for temporary use.
/// </summary>
public class LocalBoundary
{
#region Fields
private const int MaxLocalSegs = 8;
private const int MaxLocalPolys = 16;
private Vector3 center;
private Segment[] segs;
private int segCount;
private int[] polys;
private int numPolys;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LocalBoundary" /> class.
/// </summary>
public LocalBoundary()
{
Reset();
segs = new Segment[MaxLocalSegs];
polys = new int[MaxLocalPolys];
}
#endregion
#region Properties
/// <summary>
/// Gets the center
/// </summary>
public Vector3 Center
{
get
{
return center;
}
}
/// <summary>
/// Gets the segments
/// </summary>
public Segment[] Segs
{
get
{
return segs;
}
}
/// <summary>
/// Gets the number of segments
/// </summary>
public int SegCount
{
get
{
return segCount;
}
}
#endregion
#region Methods
/// <summary>
/// Reset all the internal data
/// </summary>
public void Reset()
{
center = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
segCount = 0;
numPolys = 0;
}
/// <summary>
/// Add a line segment
/// </summary>
/// <param name="dist">The distance</param>
/// <param name="s">The line segment</param>
public void AddSegment(float dist, Segment s)
{
//insert neighbour based on distance
int segPos = 0;
if (segCount == 0)
{
segPos = 0;
}
else if (dist >= segs[segCount - 1].Dist)
{
//further than the last segment, skip
if (segCount >= MaxLocalSegs)
return;
//last, trivial accept
segPos = segCount;
}
else
{
//insert inbetween
int i;
for (i = 0; i < segCount; i++)
if (dist <= segs[i].Dist)
break;
int tgt = i + 1;
int n = Math.Min(segCount - i, MaxLocalSegs - tgt);
if (n > 0)
{
for (int j = 0; j < n; j++)
segs[tgt + j] = segs[i + j];
}
segPos = i;
}
segs[segPos].Dist = dist;
segs[segPos].Start = s.Start;
segs[segPos].End = s.End;
if (segCount < MaxLocalSegs)
segCount++;
}
/// <summary>
/// Examine polygons in the NavMeshQuery and add polygon edges
/// </summary>
/// <param name="reference">The starting polygon reference</param>
/// <param name="pos">Current position</param>
/// <param name="collisionQueryRange">Range to query</param>
/// <param name="navquery">The NavMeshQuery</param>
public void Update(int reference, Vector3 pos, float collisionQueryRange, NavMeshQuery navquery)
{
const int MAX_SEGS_PER_POLY = PathfindingCommon.VERTS_PER_POLYGON;
if (reference == 0)
{
this.center = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
this.segCount = 0;
this.numPolys = 0;
return;
}
this.center = pos;
//first query non-overlapping polygons
int[] tempArray = new int[polys.Length];
navquery.FindLocalNeighbourhood(new NavPoint(reference, pos), collisionQueryRange, polys, tempArray, ref numPolys, MaxLocalPolys);
//secondly, store all polygon edges
this.segCount = 0;
Segment[] segs = new Segment[MAX_SEGS_PER_POLY];
int numSegs = 0;
for (int j = 0; j < numPolys; j++)
{
tempArray = new int[segs.Length];
navquery.GetPolyWallSegments(polys[j], segs, tempArray, ref numSegs, MAX_SEGS_PER_POLY);
for (int k = 0; k < numSegs; k++)
{
//skip too distant segments
float tseg;
float distSqr = Distance.PointToSegment2DSquared(ref pos, ref segs[k].Start, ref segs[k].End, out tseg);
if (distSqr > collisionQueryRange * collisionQueryRange)
continue;
AddSegment(distSqr, segs[k]);
}
}
}
/// <summary>
/// Determines whether the polygon reference is a part of the NavMeshQuery.
/// </summary>
/// <param name="navquery">The NavMeshQuery</param>
/// <returns>True if valid, false if not</returns>
public bool IsValid(NavMeshQuery navquery)
{
if (numPolys == 0)
return false;
for (int i = 0; i < numPolys; i++)
{
if (!navquery.IsValidPolyRef(polys[i]))
return false;
}
return true;
}
#endregion
/// <summary>
/// A line segment contains two points
/// </summary>
public struct Segment
{
/// <summary>
/// Start and end points
/// </summary>
public Vector3 Start, End;
/// <summary>
/// Distance for pruning
/// </summary>
public float Dist;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System
{
[DebuggerDisplay("{DebuggerDisplay,nq}")]
[DebuggerTypeProxy(typeof(MemoryDebugView<>))]
public struct ReadOnlyMemory<T>
{
// The highest order bit of _index is used to discern whether _arrayOrOwnedMemory is an array or an owned memory
// if (_index >> 31) == 1, object _arrayOrOwnedMemory is an OwnedMemory<T>
// else, object _arrayOrOwnedMemory is a T[]
private readonly object _arrayOrOwnedMemory;
private readonly int _index;
private readonly int _length;
private const int RemoveOwnedFlagBitMask = 0x7FFFFFFF;
/// <summary>
/// Creates a new memory over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
_arrayOrOwnedMemory = array;
_index = 0;
_length = array.Length;
}
/// <summary>
/// Creates a new memory over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory(T[] array, int start, int length)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
_arrayOrOwnedMemory = array;
_index = start;
_length = length;
}
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ReadOnlyMemory(OwnedMemory<T> owner, int index, int length)
{
if (owner == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.ownedMemory);
if (index < 0 || length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
_arrayOrOwnedMemory = owner;
_index = index | (1 << 31); // Before using _index, check if _index < 0, then 'and' it with RemoveOwnedFlagBitMask
_length = length;
}
//Debugger Display = {T[length]}
private string DebuggerDisplay => string.Format("{{{0}[{1}]}}", typeof(T).Name, _length);
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="Memory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(T[] array) => new ReadOnlyMemory<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> arraySegment) => new ReadOnlyMemory<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
/// <summary>
/// Returns an empty <see cref="Memory{T}"/>
/// </summary>
public static ReadOnlyMemory<T> Empty { get; } = Array.Empty<T>();
/// <summary>
/// The number of items in the memory.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory<T> Slice(int start)
{
if ((uint)start > (uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException();
if (_index < 0)
return new ReadOnlyMemory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, _length - start);
return new ReadOnlyMemory<T>((T[])_arrayOrOwnedMemory, _index + start, _length - start);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
if (_index < 0)
return new ReadOnlyMemory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, length);
return new ReadOnlyMemory<T>((T[])_arrayOrOwnedMemory, _index + start, length);
}
/// <summary>
/// Returns a span from the memory.
/// </summary>
public ReadOnlySpan<T> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (_index < 0)
return ((OwnedMemory<T>)_arrayOrOwnedMemory).Span.Slice(_index & RemoveOwnedFlagBitMask, _length);
return new ReadOnlySpan<T>((T[])_arrayOrOwnedMemory, _index, _length);
}
}
public unsafe MemoryHandle Retain(bool pin = false)
{
MemoryHandle memoryHandle;
if (pin)
{
if (_index < 0)
{
memoryHandle = ((OwnedMemory<T>)_arrayOrOwnedMemory).Pin();
memoryHandle.AddOffset((_index & RemoveOwnedFlagBitMask) * Unsafe.SizeOf<T>());
}
else
{
var array = (T[])_arrayOrOwnedMemory;
var handle = GCHandle.Alloc(array, GCHandleType.Pinned);
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref array.GetRawSzArrayData()), _index);
memoryHandle = new MemoryHandle(null, pointer, handle);
}
}
else
{
if (_index < 0)
{
((OwnedMemory<T>)_arrayOrOwnedMemory).Retain();
memoryHandle = new MemoryHandle((OwnedMemory<T>)_arrayOrOwnedMemory);
}
else
{
memoryHandle = new MemoryHandle(null);
}
}
return memoryHandle;
}
/// <summary>
/// Get an array segment from the underlying memory.
/// If unable to get the array segment, return false with a default array segment.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool DangerousTryGetArray(out ArraySegment<T> arraySegment)
{
if (_index < 0)
{
if (((OwnedMemory<T>)_arrayOrOwnedMemory).TryGetArray(out var segment))
{
arraySegment = new ArraySegment<T>(segment.Array, segment.Offset + (_index & RemoveOwnedFlagBitMask), _length);
return true;
}
}
else
{
arraySegment = new ArraySegment<T>((T[])_arrayOrOwnedMemory, _index, _length);
return true;
}
arraySegment = default(ArraySegment<T>);
return false;
}
/// <summary>
/// Copies the contents from the memory into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray() => Span.ToArray();
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
if (obj is ReadOnlyMemory<T> readOnlyMemory)
{
return Equals(readOnlyMemory);
}
else if (obj is Memory<T> memory)
{
return Equals(memory);
}
else
{
return false;
}
}
/// <summary>
/// Returns true if the memory points to the same array and has the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public bool Equals(ReadOnlyMemory<T> other)
{
return
_arrayOrOwnedMemory == other._arrayOrOwnedMemory &&
_index == other._index &&
_length == other._length;
}
[EditorBrowsable( EditorBrowsableState.Never)]
public override int GetHashCode()
{
return CombineHashCodes(_arrayOrOwnedMemory.GetHashCode(), (_index & RemoveOwnedFlagBitMask).GetHashCode(), _length.GetHashCode());
}
private static int CombineHashCodes(int left, int right)
{
return ((left << 5) + left) ^ right;
}
private static int CombineHashCodes(int h1, int h2, int h3)
{
return CombineHashCodes(CombineHashCodes(h1, h2), h3);
}
}
}
| |
//#define IMITATE_BATCH_MODE //uncomment if you want to imitate batch mode behaviour in non-batch mode mode run
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityTest.IntegrationTestRunner;
namespace UnityTest
{
[Serializable]
public class TestRunner : MonoBehaviour
{
static public string integrationTestsConfigFileName = "integrationtestsconfig.txt";
static public string batchRunFileMarker = "batchrun.txt";
static public string defaultResulFilePostfix = "TestResults.xml";
static private TestResultRenderer resultRenderer = new TestResultRenderer ();
public TestComponent currentTest;
private List<TestResult> resultList = new List<TestResult> ();
private List<TestComponent> testComponents;
public bool isInitializedByRunner
{
get
{
#if UNITY_EDITOR && !IMITATE_BATCH_MODE
if (!UnityEditorInternal.InternalEditorUtility.inBatchMode) return true;
#endif
return false;
}
}
private double startTime;
private bool readyToRun;
private AssertionComponent[] assertionsToCheck = null;
private string testMessages;
private string stacktrace;
private TestState testState = TestState.Running;
public TestRunnerCallbackList TestRunnerCallback = new TestRunnerCallbackList();
private IntegrationTestsProvider testsProvider;
private const string startedMessage = "IntegrationTest started";
private const string finishedMessage = "IntegrationTest finished";
private const string timeoutMessage = "IntegrationTest timeout";
private const string failedMessage = "IntegrationTest failed";
private const string failedExceptionMessage = "IntegrationTest failed with exception";
private const string ignoredMessage = "IntegrationTest ignored";
private const string interruptedMessage = "IntegrationTest Run interrupted";
public void Awake ()
{
#if UNITY_EDITOR && !IMITATE_BATCH_MODE
if (!UnityEditorInternal.InternalEditorUtility.inBatchMode) return;
#endif
TestComponent.DisableAllTests ();
}
public void Start()
{
#if UNITY_EDITOR && !IMITATE_BATCH_MODE
if (!UnityEditorInternal.InternalEditorUtility.inBatchMode) return;
#endif
TestComponent.DestroyAllDynamicTests ();
var dynamicTestTypes = TestComponent.GetTypesWithHelpAttribute (Application.loadedLevelName);
foreach (var dynamicTestType in dynamicTestTypes)
TestComponent.CreateDynamicTest (dynamicTestType);
var tests = TestComponent.FindAllTestsOnScene ();
InitRunner (tests, dynamicTestTypes.Select (type => type.AssemblyQualifiedName).ToList ());
}
public void InitRunner(List<TestComponent> tests, List<string> dynamicTestsToRun)
{
Application.RegisterLogCallback(LogHandler);
//Init dynamic tests
foreach (var typeName in dynamicTestsToRun)
{
var t = Type.GetType (typeName);
if (t == null) continue;
var scriptComponents = Resources.FindObjectsOfTypeAll (t) as MonoBehaviour[];
if (scriptComponents.Length == 0)
{
Debug.LogWarning (t + " not found. Skipping.");
continue;
}
if (scriptComponents.Length > 1) Debug.LogWarning ("Multiple GameObjects refer to " + typeName);
tests.Add (scriptComponents.First().GetComponent<TestComponent> ());
}
//create test structure
testComponents = ParseListForGroups (tests).ToList ();
//create results for tests
resultList = testComponents.Select (component => new TestResult (component)).ToList ();
//init test provider
testsProvider = new IntegrationTestsProvider (resultList.Select (result => result.TestComponent as ITestComponent));
readyToRun = true;
}
private static IEnumerable<TestComponent> ParseListForGroups ( IEnumerable<TestComponent> tests )
{
var results = new HashSet<TestComponent> ();
foreach (var testResult in tests)
{
if (testResult.IsTestGroup ())
{
var childrenTestResult = testResult.gameObject.GetComponentsInChildren (typeof (TestComponent), true)
.Where (t=>t!=testResult)
.Cast<TestComponent> ()
.ToArray ();
foreach (var result in childrenTestResult)
{
if(!result.IsTestGroup())
results.Add (result);
}
continue;
}
results.Add (testResult);
}
return results;
}
public void Update ()
{
if (readyToRun && Time.frameCount > 1)
{
readyToRun = false;
StartCoroutine ("StateMachine");
}
}
public void OnDestroy()
{
if (currentTest != null)
{
var testResult = resultList.Single (result => result.TestComponent == currentTest);
testResult.messages += "Test run interrupted (crash?)";
LogMessage(interruptedMessage);
FinishTest(TestResult.ResultType.Failed);
}
if (currentTest != null || (testsProvider != null && testsProvider.AnyTestsLeft ()))
{
var remainingTests = testsProvider.GetRemainingTests ();
TestRunnerCallback.TestRunInterrupted( remainingTests.ToList () );
}
Application.RegisterLogCallback(null);
}
private void LogHandler (string condition, string stacktrace, LogType type)
{
testMessages += condition + "\n";
if (type == LogType.Exception)
{
var exceptionType = condition.Substring (0, condition.IndexOf(':'));
if (currentTest.IsExceptionExpected (exceptionType))
{
testMessages += exceptionType + " was expected\n";
if (currentTest.ShouldSucceedOnException())
{
testState = TestState.Success;
}
}
else
{
testState = TestState.Exception;
this.stacktrace = stacktrace;
}
}
else if (type == LogType.Log)
{
if (testState == TestState.Running && condition.StartsWith (IntegrationTest.passMessage))
{
testState = TestState.Success;
}
if (condition.StartsWith(IntegrationTest.failMessage))
{
testState = TestState.Failure;
}
}
}
public IEnumerator StateMachine ()
{
TestRunnerCallback.RunStarted (Application.platform.ToString (), testComponents);
while (true)
{
if (!testsProvider.AnyTestsLeft() && currentTest == null)
{
FinishTestRun ();
yield break;
}
if (currentTest == null)
{
StartNewTest ();
}
if (currentTest != null)
{
if (testState == TestState.Running)
{
if (assertionsToCheck != null && assertionsToCheck.All (a => a.checksPerformed > 0))
{
IntegrationTest.Pass (currentTest.gameObject);
testState = TestState.Success;
}
if (currentTest != null && Time.time > startTime + currentTest.GetTimeout())
{
testState = TestState.Timeout;
}
}
switch (testState)
{
case TestState.Success:
LogMessage (finishedMessage);
FinishTest (TestResult.ResultType.Success);
break;
case TestState.Failure:
LogMessage (failedMessage);
FinishTest (TestResult.ResultType.Failed);
break;
case TestState.Exception:
LogMessage (failedExceptionMessage);
FinishTest (TestResult.ResultType.FailedException);
break;
case TestState.Timeout:
LogMessage(timeoutMessage);
FinishTest(TestResult.ResultType.Timeout);
break;
case TestState.Ignored:
LogMessage (ignoredMessage);
FinishTest(TestResult.ResultType.Ignored);
break;
}
}
yield return null;
}
}
private void LogMessage(string message)
{
if (currentTest != null)
Debug.Log (message + " (" + currentTest.Name + ")", currentTest.gameObject);
else
Debug.Log (message);
}
private void FinishTestRun ()
{
if (IsBatchRun ())
SaveResults ();
PrintResultToLog ();
TestRunnerCallback.RunFinished (resultList);
LoadNextLevelOrQuit ();
}
private void PrintResultToLog ()
{
var resultString = "";
resultString += "Passed: " + resultList.Count (t => t.IsSuccess);
if (resultList.Any (result => result.IsFailure))
{
resultString += " Failed: " + resultList.Count (t => t.IsFailure);
Debug.Log ("Failed tests: " + string.Join (", ", resultList.Where (t => t.IsFailure).Select (result => result.Name).ToArray ()));
}
if (resultList.Any (result => result.IsIgnored))
{
resultString += " Ignored: " + resultList.Count (t => t.IsIgnored);
Debug.Log ("Ignored tests: " + string.Join (", ",
resultList.Where (t => t.IsIgnored).Select (result => result.Name).ToArray ()));
}
Debug.Log (resultString);
}
private void LoadNextLevelOrQuit ()
{
if (isInitializedByRunner) return;
if (Application.loadedLevel < Application.levelCount - 1)
Application.LoadLevel (Application.loadedLevel + 1);
else
{
#if UNITY_EDITOR && !IMITATE_BATCH_MODE
UnityEditor.EditorApplication.Exit (0);
#else
resultRenderer.ShowResults ();
if(IsBatchRun())
Application.Quit ();
#endif
}
}
public void OnGUI ()
{
resultRenderer.Draw ();
}
private void SaveResults ()
{
if (!IsFileSavingSupported ()) return;
var resultDestiantion = GetResultDestiantion ();
var resultFileName = Application.loadedLevelName;
if (resultFileName != "")
resultFileName += "-";
resultFileName += defaultResulFilePostfix;
var resultWriter = new XmlResultWriter (Application.loadedLevelName, resultList.ToArray ());
#if !UNITY_METRO
Uri uri;
if ( Uri.TryCreate (resultDestiantion, UriKind.Absolute, out uri) && uri.Scheme == Uri.UriSchemeFile)
{
resultWriter.WriteToFile (resultDestiantion, resultFileName);
}
else
{
Debug.LogError ("Provided path is invalid");
}
#endif
}
private bool IsFileSavingSupported ()
{
#if UNITY_EDITOR || UNITY_STANDALONE
return true;
#else
return false;
#endif
}
private string GetResultDestiantion ()
{
var nameWithoutExtension = integrationTestsConfigFileName.Substring (0, integrationTestsConfigFileName.LastIndexOf ('.'));
var resultpathFile = Resources.Load (nameWithoutExtension) as TextAsset;
var resultDestiantion = Application.dataPath;
if (resultpathFile != null)
resultDestiantion = resultpathFile.text;
#if UNITY_EDITOR
var resultsFileDirectory = "-resultsFileDirectory=";
if (UnityEditorInternal.InternalEditorUtility.inBatchMode && Environment.GetCommandLineArgs ().Any (s => s.StartsWith (resultsFileDirectory)))
resultDestiantion = Environment.GetCommandLineArgs ().First (s => s.StartsWith (resultsFileDirectory)).Substring (resultsFileDirectory.Length);
#endif
return resultDestiantion;
}
private bool IsBatchRun ()
{
#if UNITY_EDITOR && !IMITATE_BATCH_MODE
if (UnityEditorInternal.InternalEditorUtility.inBatchMode) return true;
#endif
var nameWithoutExtension = batchRunFileMarker.Substring (0, batchRunFileMarker.LastIndexOf ('.'));
var resultpathFile = Resources.Load (nameWithoutExtension) as TextAsset;
return resultpathFile != null;
}
private void StartNewTest ()
{
this.testMessages = "";
this.stacktrace = "";
testState = TestState.Running;
assertionsToCheck = null;
startTime = Time.time;
currentTest = testsProvider.GetNextTest () as TestComponent;
var testResult = resultList.Single (result => result.TestComponent == currentTest);
if (currentTest.ShouldSucceedOnAssertions ())
{
var assertionList = currentTest.gameObject.GetComponentsInChildren<AssertionComponent> ().Where (a => a.enabled);
if(assertionList.Any())
assertionsToCheck = assertionList.ToArray();
}
if (currentTest.IsExludedOnThisPlatform ())
{
testState = TestState.Ignored;
Debug.Log(currentTest.gameObject.name + " is excluded on this platform");
}
//don't ignore test if user initiated it from the runner and it's the only test that is being run
if (currentTest.IsIgnored () && !(isInitializedByRunner && resultList.Count == 1)) testState = TestState.Ignored;
LogMessage(startedMessage);
TestRunnerCallback.TestStarted (testResult);
}
private void FinishTest(TestResult.ResultType result)
{
testsProvider.FinishTest (currentTest);
var testResult = resultList.Single (t => t.GameObject == currentTest.gameObject);
testResult.resultType = result;
testResult.duration = Time.time - startTime;
testResult.messages = testMessages;
testResult.stacktrace = stacktrace;
TestRunnerCallback.TestFinished (testResult);
currentTest = null;
//currentTest2 = null;
if (!testResult.IsSuccess
&& testResult.Executed
&& !testResult.IsIgnored) resultRenderer.AddResults (Application.loadedLevelName, testResult);
}
#region Test Runner Helpers
public static TestRunner GetTestRunner ()
{
TestRunner testRunnerComponent = null;
var testRunnerComponents = Resources.FindObjectsOfTypeAll(typeof(TestRunner));
if (testRunnerComponents.Count () > 1)
foreach (var t in testRunnerComponents) DestroyImmediate((t as TestRunner).gameObject);
else if (!testRunnerComponents.Any())
testRunnerComponent = Create().GetComponent<TestRunner>();
else
testRunnerComponent = testRunnerComponents.Single() as TestRunner;
return testRunnerComponent;
}
private static GameObject Create()
{
var runner = new GameObject ("TestRunner");
var component = runner.AddComponent<TestRunner> ();
component.hideFlags = HideFlags.NotEditable;
Debug.Log ("Created Test Runner");
return runner;
}
#endregion
enum TestState
{
Running,
Success,
Failure,
Exception,
Timeout,
Ignored
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/api.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Protobuf {
namespace Proto {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Api {
#region Descriptor
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static Api() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chlnb29nbGUvcHJvdG9idWYvYXBpLnByb3RvEg9nb29nbGUucHJvdG9idWYa",
"JGdvb2dsZS9wcm90b2J1Zi9zb3VyY2VfY29udGV4dC5wcm90bxoaZ29vZ2xl",
"L3Byb3RvYnVmL3R5cGUucHJvdG8isAEKA0FwaRIMCgRuYW1lGAEgASgJEigK",
"B21ldGhvZHMYAiADKAsyFy5nb29nbGUucHJvdG9idWYuTWV0aG9kEigKB29w",
"dGlvbnMYAyADKAsyFy5nb29nbGUucHJvdG9idWYuT3B0aW9uEg8KB3ZlcnNp",
"b24YBCABKAkSNgoOc291cmNlX2NvbnRleHQYBSABKAsyHi5nb29nbGUucHJv",
"dG9idWYuU291cmNlQ29udGV4dCKsAQoGTWV0aG9kEgwKBG5hbWUYASABKAkS",
"GAoQcmVxdWVzdF90eXBlX3VybBgCIAEoCRIZChFyZXF1ZXN0X3N0cmVhbWlu",
"ZxgDIAEoCBIZChFyZXNwb25zZV90eXBlX3VybBgEIAEoCRIaChJyZXNwb25z",
"ZV9zdHJlYW1pbmcYBSABKAgSKAoHb3B0aW9ucxgGIAMoCzIXLmdvb2dsZS5w",
"cm90b2J1Zi5PcHRpb25CIQoTY29tLmdvb2dsZS5wcm90b2J1ZkIIQXBpUHJv",
"dG9QAWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.Proto.SourceContext.Descriptor, global::Google.Protobuf.Proto.Type.Descriptor, },
new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] {
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Api), new[]{ "Name", "Methods", "Options", "Version", "SourceContext" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Method), new[]{ "Name", "RequestTypeUrl", "RequestStreaming", "ResponseTypeUrl", "ResponseStreaming", "Options" }, null, null, null)
}));
}
#endregion
}
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Api : pb::IMessage<Api> {
private static readonly pb::MessageParser<Api> _parser = new pb::MessageParser<Api>(() => new Api());
public static pb::MessageParser<Api> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.Proto.Api.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public Api() {
OnConstruction();
}
partial void OnConstruction();
public Api(Api other) : this() {
name_ = other.name_;
methods_ = other.methods_.Clone();
options_ = other.options_.Clone();
version_ = other.version_;
SourceContext = other.sourceContext_ != null ? other.SourceContext.Clone() : null;
}
public Api Clone() {
return new Api(this);
}
public const int NameFieldNumber = 1;
private string name_ = "";
public string Name {
get { return name_; }
set {
name_ = pb::Preconditions.CheckNotNull(value, "value");
}
}
public const int MethodsFieldNumber = 2;
private static readonly pb::FieldCodec<global::Google.Protobuf.Method> _repeated_methods_codec
= pb::FieldCodec.ForMessage(18, global::Google.Protobuf.Method.Parser);
private readonly pbc::RepeatedField<global::Google.Protobuf.Method> methods_ = new pbc::RepeatedField<global::Google.Protobuf.Method>();
public pbc::RepeatedField<global::Google.Protobuf.Method> Methods {
get { return methods_; }
}
public const int OptionsFieldNumber = 3;
private static readonly pb::FieldCodec<global::Google.Protobuf.Option> _repeated_options_codec
= pb::FieldCodec.ForMessage(26, global::Google.Protobuf.Option.Parser);
private readonly pbc::RepeatedField<global::Google.Protobuf.Option> options_ = new pbc::RepeatedField<global::Google.Protobuf.Option>();
public pbc::RepeatedField<global::Google.Protobuf.Option> Options {
get { return options_; }
}
public const int VersionFieldNumber = 4;
private string version_ = "";
public string Version {
get { return version_; }
set {
version_ = pb::Preconditions.CheckNotNull(value, "value");
}
}
public const int SourceContextFieldNumber = 5;
private global::Google.Protobuf.SourceContext sourceContext_;
public global::Google.Protobuf.SourceContext SourceContext {
get { return sourceContext_; }
set {
sourceContext_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as Api);
}
public bool Equals(Api other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if(!methods_.Equals(other.methods_)) return false;
if(!options_.Equals(other.options_)) return false;
if (Version != other.Version) return false;
if (!object.Equals(SourceContext, other.SourceContext)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
hash ^= methods_.GetHashCode();
hash ^= options_.GetHashCode();
if (Version.Length != 0) hash ^= Version.GetHashCode();
if (sourceContext_ != null) hash ^= SourceContext.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
methods_.WriteTo(output, _repeated_methods_codec);
options_.WriteTo(output, _repeated_options_codec);
if (Version.Length != 0) {
output.WriteRawTag(34);
output.WriteString(Version);
}
if (sourceContext_ != null) {
output.WriteRawTag(42);
output.WriteMessage(SourceContext);
}
}
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
size += methods_.CalculateSize(_repeated_methods_codec);
size += options_.CalculateSize(_repeated_options_codec);
if (Version.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Version);
}
if (sourceContext_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(SourceContext);
}
return size;
}
public void MergeFrom(Api other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
methods_.Add(other.methods_);
options_.Add(other.options_);
if (other.Version.Length != 0) {
Version = other.Version;
}
if (other.sourceContext_ != null) {
if (sourceContext_ == null) {
sourceContext_ = new global::Google.Protobuf.SourceContext();
}
SourceContext.MergeFrom(other.SourceContext);
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
methods_.AddEntriesFrom(input, _repeated_methods_codec);
break;
}
case 26: {
options_.AddEntriesFrom(input, _repeated_options_codec);
break;
}
case 34: {
Version = input.ReadString();
break;
}
case 42: {
if (sourceContext_ == null) {
sourceContext_ = new global::Google.Protobuf.SourceContext();
}
input.ReadMessage(sourceContext_);
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Method : pb::IMessage<Method> {
private static readonly pb::MessageParser<Method> _parser = new pb::MessageParser<Method>(() => new Method());
public static pb::MessageParser<Method> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.Proto.Api.Descriptor.MessageTypes[1]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public Method() {
OnConstruction();
}
partial void OnConstruction();
public Method(Method other) : this() {
name_ = other.name_;
requestTypeUrl_ = other.requestTypeUrl_;
requestStreaming_ = other.requestStreaming_;
responseTypeUrl_ = other.responseTypeUrl_;
responseStreaming_ = other.responseStreaming_;
options_ = other.options_.Clone();
}
public Method Clone() {
return new Method(this);
}
public const int NameFieldNumber = 1;
private string name_ = "";
public string Name {
get { return name_; }
set {
name_ = pb::Preconditions.CheckNotNull(value, "value");
}
}
public const int RequestTypeUrlFieldNumber = 2;
private string requestTypeUrl_ = "";
public string RequestTypeUrl {
get { return requestTypeUrl_; }
set {
requestTypeUrl_ = pb::Preconditions.CheckNotNull(value, "value");
}
}
public const int RequestStreamingFieldNumber = 3;
private bool requestStreaming_;
public bool RequestStreaming {
get { return requestStreaming_; }
set {
requestStreaming_ = value;
}
}
public const int ResponseTypeUrlFieldNumber = 4;
private string responseTypeUrl_ = "";
public string ResponseTypeUrl {
get { return responseTypeUrl_; }
set {
responseTypeUrl_ = pb::Preconditions.CheckNotNull(value, "value");
}
}
public const int ResponseStreamingFieldNumber = 5;
private bool responseStreaming_;
public bool ResponseStreaming {
get { return responseStreaming_; }
set {
responseStreaming_ = value;
}
}
public const int OptionsFieldNumber = 6;
private static readonly pb::FieldCodec<global::Google.Protobuf.Option> _repeated_options_codec
= pb::FieldCodec.ForMessage(50, global::Google.Protobuf.Option.Parser);
private readonly pbc::RepeatedField<global::Google.Protobuf.Option> options_ = new pbc::RepeatedField<global::Google.Protobuf.Option>();
public pbc::RepeatedField<global::Google.Protobuf.Option> Options {
get { return options_; }
}
public override bool Equals(object other) {
return Equals(other as Method);
}
public bool Equals(Method other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (RequestTypeUrl != other.RequestTypeUrl) return false;
if (RequestStreaming != other.RequestStreaming) return false;
if (ResponseTypeUrl != other.ResponseTypeUrl) return false;
if (ResponseStreaming != other.ResponseStreaming) return false;
if(!options_.Equals(other.options_)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (RequestTypeUrl.Length != 0) hash ^= RequestTypeUrl.GetHashCode();
if (RequestStreaming != false) hash ^= RequestStreaming.GetHashCode();
if (ResponseTypeUrl.Length != 0) hash ^= ResponseTypeUrl.GetHashCode();
if (ResponseStreaming != false) hash ^= ResponseStreaming.GetHashCode();
hash ^= options_.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (RequestTypeUrl.Length != 0) {
output.WriteRawTag(18);
output.WriteString(RequestTypeUrl);
}
if (RequestStreaming != false) {
output.WriteRawTag(24);
output.WriteBool(RequestStreaming);
}
if (ResponseTypeUrl.Length != 0) {
output.WriteRawTag(34);
output.WriteString(ResponseTypeUrl);
}
if (ResponseStreaming != false) {
output.WriteRawTag(40);
output.WriteBool(ResponseStreaming);
}
options_.WriteTo(output, _repeated_options_codec);
}
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (RequestTypeUrl.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(RequestTypeUrl);
}
if (RequestStreaming != false) {
size += 1 + 1;
}
if (ResponseTypeUrl.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ResponseTypeUrl);
}
if (ResponseStreaming != false) {
size += 1 + 1;
}
size += options_.CalculateSize(_repeated_options_codec);
return size;
}
public void MergeFrom(Method other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.RequestTypeUrl.Length != 0) {
RequestTypeUrl = other.RequestTypeUrl;
}
if (other.RequestStreaming != false) {
RequestStreaming = other.RequestStreaming;
}
if (other.ResponseTypeUrl.Length != 0) {
ResponseTypeUrl = other.ResponseTypeUrl;
}
if (other.ResponseStreaming != false) {
ResponseStreaming = other.ResponseStreaming;
}
options_.Add(other.options_);
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
RequestTypeUrl = input.ReadString();
break;
}
case 24: {
RequestStreaming = input.ReadBool();
break;
}
case 34: {
ResponseTypeUrl = input.ReadString();
break;
}
case 40: {
ResponseStreaming = input.ReadBool();
break;
}
case 50: {
options_.AddEntriesFrom(input, _repeated_options_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// 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.Text;
using System.IO;
using System.Xml;
using Microsoft.Test.ModuleCore;
using XmlCoreTest.Common;
public enum NodeFlags
{
None = 0,
EmptyElement = 1,
HasValue = 2,
SingleQuote = 4,
DefaultAttribute = 8,
UnparsedEntities = 16,
IsWhitespace = 32,
DocumentRoot = 64,
AttributeTextNode = 128,
MixedContent = 256,
Indent = 512
}
abstract public class CXmlBase
{
protected XmlNodeType pnType;
protected string pstrName;
protected string pstrLocalName;
protected string pstrPrefix;
protected string pstrNamespace;
internal int pnDepth;
internal NodeFlags peFlags = NodeFlags.None;
internal CXmlBase prNextNode = null;
internal CXmlBase prParentNode = null;
internal CXmlBase prFirstChildNode = null;
internal CXmlBase prLastChildNode = null;
internal int pnChildNodes = 0;
//
// Constructors
//
public CXmlBase(string strPrefix, string strName, string strLocalName, XmlNodeType NodeType, string strNamespace)
{
pstrPrefix = strPrefix;
pstrName = strName;
pstrLocalName = strLocalName;
pnType = NodeType;
pstrNamespace = strNamespace;
}
public CXmlBase(string strPrefix, string strName, XmlNodeType NodeType, string strNamespace)
: this(strPrefix, strName, strName, NodeType, strNamespace)
{ }
public CXmlBase(string strPrefix, string strName, XmlNodeType NodeType)
: this(strPrefix, strName, strName, NodeType, "")
{ }
public CXmlBase(string strName, XmlNodeType NodeType)
: this("", strName, strName, NodeType, "")
{ }
//
// Virtual Methods and Properties
//
abstract public void Write(XmlWriter rXmlWriter);
abstract public string Xml { get; }
abstract public void WriteXml(TextWriter rTW);
abstract public string Value { get; }
//
// Public Methods and Properties
//
public string Name
{
get { return pstrName; }
}
public string LocalName
{
get { return pstrLocalName; }
}
public string Prefix
{
get { return pstrPrefix; }
}
public string Namespace
{
get { return pstrNamespace; }
}
public int Depth
{
get { return pnDepth; }
}
public XmlNodeType NodeType
{
get { return pnType; }
}
public NodeFlags Flags
{
get { return peFlags; }
}
public int ChildNodeCount
{
get { return pnChildNodes; }
}
public void InsertNode(CXmlBase rNode)
{
if (prFirstChildNode == null)
{
prFirstChildNode = prLastChildNode = rNode;
}
else
{
prLastChildNode.prNextNode = rNode;
prLastChildNode = rNode;
}
if ((this.peFlags & NodeFlags.IsWhitespace) == 0)
pnChildNodes++;
rNode.prParentNode = this;
}
//
// Internal Methods and Properties
//
internal CXmlBase _Child(int n)
{
int i;
int j;
CXmlBase rChild = prFirstChildNode;
for (i = 0, j = 0; rChild != null; i++, rChild = rChild.prNextNode)
{
if ((rChild.peFlags & NodeFlags.IsWhitespace) == 0)
{
if (j++ == n) break;
}
}
return rChild;
}
internal CXmlBase _Child(string str)
{
CXmlBase rChild;
for (rChild = prFirstChildNode; rChild != null; rChild = rChild.prNextNode)
if (rChild.Name == str) break;
return rChild;
}
}
public class CXmlAttribute : CXmlBase
{
//
// Constructor
//
public CXmlAttribute(XmlReader rXmlReader)
: base(rXmlReader.Prefix, rXmlReader.Name, rXmlReader.LocalName, rXmlReader.NodeType, rXmlReader.NamespaceURI)
{
if (rXmlReader.IsDefault)
peFlags |= NodeFlags.DefaultAttribute;
}
//
// Public Methods and Properties (Override)
//
override public void Write(XmlWriter rXmlWriter)
{
CXmlBase rNode;
if ((this.peFlags & NodeFlags.DefaultAttribute) == 0)
{
rXmlWriter.WriteStartAttribute(this.Prefix, this.LocalName, this.Namespace);
for (rNode = this.prFirstChildNode; rNode != null; rNode = rNode.prNextNode)
{
rNode.Write(rXmlWriter);
}
rXmlWriter.WriteEndAttribute();
}
}
override public string Xml
{
get
{
CXmlCache._rBufferWriter.Dispose();
WriteXml(CXmlCache._rBufferWriter);
return CXmlCache._rBufferWriter.ToString();
}
}
override public void WriteXml(TextWriter rTW)
{
if ((this.peFlags & NodeFlags.DefaultAttribute) == 0)
{
CXmlBase rNode;
rTW.Write(' ' + this.Name + '=' + this.Quote);
for (rNode = this.prFirstChildNode; rNode != null; rNode = rNode.prNextNode)
{
rNode.WriteXml(rTW);
}
rTW.Write(this.Quote);
}
}
//
// Public Methods and Properties
//
override public string Value
{
get
{
CXmlNode rNode;
string strValue = string.Empty;
for (rNode = (CXmlNode)this.prFirstChildNode; rNode != null; rNode = rNode.NextNode)
strValue += rNode.Value;
return strValue;
}
}
public CXmlAttribute NextAttribute
{
get { return (CXmlAttribute)this.prNextNode; }
}
public char Quote
{
get { return ((base.peFlags & NodeFlags.SingleQuote) != 0 ? '\'' : '"'); }
set { if (value == '\'') base.peFlags |= NodeFlags.SingleQuote; else base.peFlags &= ~NodeFlags.SingleQuote; }
}
public CXmlNode FirstChild
{
get { return (CXmlNode)base.prFirstChildNode; }
}
public CXmlNode Child(int n)
{
return (CXmlNode)base._Child(n);
}
public CXmlNode Child(string str)
{
return (CXmlNode)base._Child(str);
}
}
public class CXmlNode : CXmlBase
{
internal string _strValue = null;
private CXmlAttribute _rFirstAttribute = null;
private CXmlAttribute _rLastAttribute = null;
private int _nAttributeCount = 0;
//
// Constructors
//
public CXmlNode(string strPrefix, string strName, XmlNodeType NodeType)
: base(strPrefix, strName, NodeType)
{ }
public CXmlNode(XmlReader rXmlReader)
: base(rXmlReader.Prefix, rXmlReader.Name, rXmlReader.LocalName, rXmlReader.NodeType, rXmlReader.NamespaceURI)
{
peFlags |= CXmlCache._eDefaultFlags;
if (NodeType == XmlNodeType.Whitespace ||
NodeType == XmlNodeType.SignificantWhitespace)
{
peFlags |= NodeFlags.IsWhitespace;
}
if (rXmlReader.IsEmptyElement)
{
peFlags |= NodeFlags.EmptyElement;
}
if (rXmlReader.HasValue)
{
peFlags |= NodeFlags.HasValue;
_strValue = rXmlReader.Value;
}
}
//
// Public Methods and Properties (Override)
//
override public void Write(XmlWriter rXmlWriter)
{
CXmlBase rNode;
CXmlAttribute rAttribute;
string DocTypePublic = null;
string DocTypeSystem = null;
switch (this.NodeType)
{
case XmlNodeType.CDATA:
rXmlWriter.WriteCData(_strValue);
break;
case XmlNodeType.Comment:
rXmlWriter.WriteComment(_strValue);
break;
case XmlNodeType.DocumentType:
for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute)
{
if (rAttribute.Name == "PUBLIC") { DocTypePublic = rAttribute.Value; }
if (rAttribute.Name == "SYSTEM") { DocTypeSystem = rAttribute.Value; }
}
rXmlWriter.WriteDocType(this.Name, DocTypePublic, DocTypeSystem, _strValue);
break;
case XmlNodeType.EntityReference:
rXmlWriter.WriteEntityRef(this.Name);
break;
case XmlNodeType.ProcessingInstruction:
rXmlWriter.WriteProcessingInstruction(this.Name, _strValue);
break;
case XmlNodeType.Text:
if (this.Name == string.Empty)
{
if ((this.Flags & NodeFlags.UnparsedEntities) == 0)
{
rXmlWriter.WriteString(_strValue);
}
else
{
rXmlWriter.WriteRaw(_strValue.ToCharArray(), 0, _strValue.Length);
}
}
else
{
if (this.pstrName[0] == '#')
rXmlWriter.WriteCharEntity(_strValue[0]);
else
rXmlWriter.WriteEntityRef(this.Name);
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
if ((this.prParentNode.peFlags & NodeFlags.DocumentRoot) != 0)
rXmlWriter.WriteRaw(_strValue.ToCharArray(), 0, _strValue.Length);
else
rXmlWriter.WriteString(_strValue);
break;
case XmlNodeType.Element:
rXmlWriter.WriteStartElement(this.Prefix, this.LocalName, null);
for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute)
{
rAttribute.Write(rXmlWriter);
}
if ((this.Flags & NodeFlags.EmptyElement) == 0)
rXmlWriter.WriteString(string.Empty);
for (rNode = base.prFirstChildNode; rNode != null; rNode = rNode.prNextNode)
{
rNode.Write(rXmlWriter);
}
// Should only produce empty tag if the original document used empty tag
if ((this.Flags & NodeFlags.EmptyElement) == 0)
rXmlWriter.WriteFullEndElement();
else
rXmlWriter.WriteEndElement();
break;
case XmlNodeType.XmlDeclaration:
rXmlWriter.WriteRaw("<?xml " + _strValue + "?>");
break;
default:
throw (new Exception("Node.Write: Unhandled node type " + this.NodeType.ToString()));
}
}
override public string Xml
{
get
{
CXmlCache._rBufferWriter.Dispose();
WriteXml(CXmlCache._rBufferWriter);
return CXmlCache._rBufferWriter.ToString();
}
}
override public void WriteXml(TextWriter rTW)
{
String strXml;
CXmlAttribute rAttribute;
CXmlBase rNode;
switch (this.pnType)
{
case XmlNodeType.Text:
if (this.pstrName == "")
{
rTW.Write(_strValue);
}
else
{
if (this.pstrName.StartsWith("#"))
{
rTW.Write("&" + Convert.ToString(Convert.ToInt32(_strValue[0])) + ";");
}
else
{
rTW.Write("&" + this.Name + ";");
}
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.DocumentType:
rTW.Write(_strValue);
break;
case XmlNodeType.Element:
strXml = this.Name;
rTW.Write('<' + strXml);
//Put in all the Attributes
for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute)
{
rAttribute.WriteXml(rTW);
}
//If there is children, put those in, otherwise close the tag.
if ((base.peFlags & NodeFlags.EmptyElement) == 0)
{
rTW.Write('>');
for (rNode = base.prFirstChildNode; rNode != null; rNode = rNode.prNextNode)
{
rNode.WriteXml(rTW);
}
rTW.Write("</" + strXml + ">");
}
else
{
rTW.Write(" />");
}
break;
case XmlNodeType.EntityReference:
rTW.Write("&" + this.pstrName + ";");
break;
case XmlNodeType.Notation:
rTW.Write("<!NOTATION " + _strValue + ">");
break;
case XmlNodeType.CDATA:
rTW.Write("<![CDATA[" + _strValue + "]]>");
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
rTW.Write("<?" + this.pstrName + " " + _strValue + "?>");
break;
case XmlNodeType.Comment:
rTW.Write("<!--" + _strValue + "-->");
break;
default:
throw (new Exception("Unhandled NodeType " + this.pnType.ToString()));
}
}
//
// Public Methods and Properties
//
public string NodeValue
{
get { return _strValue; }
}
override public string Value
{
get
{
string strValue = "";
CXmlNode rChild;
if ((this.peFlags & NodeFlags.HasValue) != 0)
{
char chEnt;
int nIndexAmp = 0;
int nIndexSem = 0;
if ((this.peFlags & NodeFlags.UnparsedEntities) == 0)
return _strValue;
strValue = _strValue;
while ((nIndexAmp = strValue.IndexOf('&', nIndexAmp)) != -1)
{
nIndexSem = strValue.IndexOf(';', nIndexAmp);
chEnt = ResolveCharEntity(strValue.Substring(nIndexAmp + 1, nIndexSem - nIndexAmp - 1));
if (chEnt != char.MinValue)
{
strValue = strValue.Substring(0, nIndexAmp) + chEnt + strValue.Substring(nIndexSem + 1);
nIndexAmp++;
}
else
nIndexAmp = nIndexSem;
}
return strValue;
}
for (rChild = (CXmlNode)this.prFirstChildNode; rChild != null; rChild = (CXmlNode)rChild.prNextNode)
{
strValue = strValue + rChild.Value;
}
return strValue;
}
}
public CXmlNode NextNode
{
get
{
CXmlBase rNode = this.prNextNode;
while (rNode != null &&
(rNode.Flags & NodeFlags.IsWhitespace) != 0)
rNode = rNode.prNextNode;
return (CXmlNode)rNode;
}
}
public CXmlNode FirstChild
{
get
{
CXmlBase rNode = this.prFirstChildNode;
while (rNode != null &&
(rNode.Flags & NodeFlags.IsWhitespace) != 0)
rNode = rNode.prNextNode;
return (CXmlNode)rNode;
}
}
public CXmlNode Child(int n)
{
int i;
CXmlNode rChild;
i = 0;
for (rChild = FirstChild; rChild != null; rChild = rChild.NextNode)
if (i++ == n) break;
return rChild;
}
public CXmlNode Child(string str)
{
return (CXmlNode)base._Child(str);
}
public int Type
{
get { return Convert.ToInt32(base.pnType); }
}
public CXmlAttribute FirstAttribute
{
get { return _rFirstAttribute; }
}
public int AttributeCount
{
get { return _nAttributeCount; }
}
public CXmlAttribute Attribute(int n)
{
int i;
CXmlAttribute rAttribute;
i = 0;
for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute)
if (i++ == n) break;
return rAttribute;
}
public CXmlAttribute Attribute(string str)
{
CXmlAttribute rAttribute;
for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute)
{
if (rAttribute.Name == str) break;
}
return rAttribute;
}
public void AddAttribute(CXmlAttribute rAttribute)
{
if (_rFirstAttribute == null)
{
_rFirstAttribute = rAttribute;
}
else
{
_rLastAttribute.prNextNode = rAttribute;
}
_rLastAttribute = rAttribute;
_nAttributeCount++;
}
private char ResolveCharEntity(string strName)
{
if (strName[0] == '#')
if (strName[1] == 'x')
return Convert.ToChar(Convert.ToInt32(strName.Substring(2), 16));
else
return Convert.ToChar(Convert.ToInt32(strName.Substring(1)));
if (strName == "lt")
return '<';
if (strName == "gt")
return '>';
if (strName == "amp")
return '&';
if (strName == "apos")
return '\'';
if (strName == "quot")
return '"';
return char.MinValue;
}
}
public class CXmlCache
{
//CXmlCache Properties
private bool _fTrace = false;
private bool _fThrow = true;
private bool _fReadNode = true;
private int _hr = 0;
private Encoding _eEncoding = System.Text.Encoding.UTF8;
private string _strParseError = "";
//XmlReader Properties
private bool _fNamespaces = true;
private bool _fValidationCallback = false;
private bool _fExpandAttributeValues = false;
//Internal stuff
protected XmlReader prXmlReader = null;
protected CXmlNode prDocumentRootNode;
protected CXmlNode prRootNode = null;
internal static NodeFlags _eDefaultFlags = NodeFlags.None;
static internal BufferWriter _rBufferWriter = new BufferWriter();
//
// Constructor
//
public CXmlCache() { }
//
// Public Methods and Properties
//
public virtual bool Load(XmlReader rXmlReader)
{
//Hook up your reader as my reader
prXmlReader = rXmlReader;
//Process the Document
try
{
prDocumentRootNode = new CXmlNode("", "", XmlNodeType.Element);
prDocumentRootNode.peFlags = NodeFlags.DocumentRoot | NodeFlags.Indent;
Process(prDocumentRootNode);
for (prRootNode = prDocumentRootNode.FirstChild; prRootNode != null && prRootNode.NodeType != XmlNodeType.Element; prRootNode = prRootNode.NextNode) ;
}
catch (Exception e)
{
//Unhook your reader
prXmlReader = null;
_strParseError = e.ToString();
if (_fThrow)
{
throw (e);
}
if (_hr == 0)
_hr = -1;
return false;
}
//Unhook your reader
prXmlReader = null;
return true;
}
public bool Load(string strFileName)
{
XmlReader rXmlTextReader;
bool fRet;
rXmlTextReader = XmlReader.Create(FilePathUtil.getStream(strFileName));
fRet = Load(rXmlTextReader);
return fRet;
}
public void Save(string strName)
{
Save(strName, false, _eEncoding);
}
public void Save(string strName, bool fOverWrite)
{
Save(strName, fOverWrite, _eEncoding);
}
public void Save(string strName, bool fOverWrite, System.Text.Encoding Encoding)
{
CXmlBase rNode;
XmlWriter rXmlTextWriter = null;
try
{
rXmlTextWriter = XmlWriter.Create(FilePathUtil.getStream(strName));
for (rNode = prDocumentRootNode.prFirstChildNode; rNode != null; rNode = rNode.prNextNode)
{
rNode.Write(rXmlTextWriter);
}
rXmlTextWriter.Dispose();
}
catch (Exception e)
{
DebugTrace(e.ToString());
if (rXmlTextWriter != null)
rXmlTextWriter.Dispose();
throw (e);
}
}
virtual public string Xml
{
get
{
_rBufferWriter.Dispose();
WriteXml(_rBufferWriter);
return _rBufferWriter.ToString();
}
}
public void WriteXml(TextWriter rTW)
{
CXmlBase rNode;
//Spit out the document
for (rNode = prDocumentRootNode.prFirstChildNode; rNode != null; rNode = rNode.prNextNode)
rNode.WriteXml(rTW);
}
public CXmlNode RootNode
{
get { return prRootNode; }
}
public string ParseError
{
get { return _strParseError; }
}
public int ParseErrorCode
{
get { return _hr; }
}
//
// XmlReader Properties
//
public bool Namespaces
{
set { _fNamespaces = value; }
get { return _fNamespaces; }
}
public bool UseValidationCallback
{
set { _fValidationCallback = value; }
get { return _fValidationCallback; }
}
public bool ExpandAttributeValues
{
set { _fExpandAttributeValues = value; }
get { return _fExpandAttributeValues; }
}
//
// Internal Properties
//
public bool Throw
{
get { return _fThrow; }
set { _fThrow = value; }
}
public bool Trace
{
set { _fTrace = value; }
get { return _fTrace; }
}
//
//Private Methods
//
private void DebugTrace(string str)
{
DebugTrace(str, 0);
}
private void DebugTrace(string str, int nDepth)
{
if (_fTrace)
{
int i;
for (i = 0; i < nDepth; i++)
TestLog.Write(" ");
TestLog.WriteLine(str);
}
}
private void DebugTrace(XmlReader rXmlReader)
{
if (_fTrace)
{
string str;
str = rXmlReader.NodeType.ToString() + ", Depth=" + rXmlReader.Depth + " Name=";
if (rXmlReader.Prefix != "")
{
str += rXmlReader.Prefix + ":";
}
str += rXmlReader.LocalName;
if (rXmlReader.HasValue)
str += " Value=" + rXmlReader.Value;
DebugTrace(str, rXmlReader.Depth);
}
}
protected void Process(CXmlBase rParentNode)
{
CXmlNode rNewNode;
while (true)
{
//We want to pop if Read() returns false, aka EOF
if (_fReadNode)
{
if (!prXmlReader.Read())
{
DebugTrace("Read() == false");
return;
}
}
else
{
if (!prXmlReader.ReadAttributeValue())
{
DebugTrace("ReadAttributeValue() == false");
return;
}
}
DebugTrace(prXmlReader);
//We also want to pop if we get an EndElement or EndEntity
if (prXmlReader.NodeType == XmlNodeType.EndElement ||
prXmlReader.NodeType == XmlNodeType.EndEntity)
{
DebugTrace("NodeType == EndElement or EndEntity");
return;
}
rNewNode = GetNewNode(prXmlReader);
rNewNode.pnDepth = prXmlReader.Depth;
// Test for MixedContent and set Indent if necessary
if ((rParentNode.Flags & NodeFlags.MixedContent) != 0)
{
rNewNode.peFlags |= NodeFlags.MixedContent;
// Indent is off for all new nodes
}
else
{
rNewNode.peFlags |= NodeFlags.Indent; // Turn on Indent for current Node
}
// Set all Depth 0 nodes to No Mixed Content and Indent True
if (prXmlReader.Depth == 0)
{
rNewNode.peFlags |= NodeFlags.Indent; // Turn on Indent
rNewNode.peFlags &= ~NodeFlags.MixedContent; // Turn off MixedContent
}
rParentNode.InsertNode(rNewNode);
//Do some special stuff based on NodeType
switch (prXmlReader.NodeType)
{
case XmlNodeType.Element:
if (prXmlReader.MoveToFirstAttribute())
{
do
{
CXmlAttribute rNewAttribute = new CXmlAttribute(prXmlReader);
rNewNode.AddAttribute(rNewAttribute);
if (_fExpandAttributeValues)
{
DebugTrace("Attribute: " + prXmlReader.Name);
_fReadNode = false;
Process(rNewAttribute);
_fReadNode = true;
}
else
{
CXmlNode rValueNode = new CXmlNode("", "", XmlNodeType.Text);
rValueNode.peFlags = _eDefaultFlags | NodeFlags.HasValue;
rValueNode._strValue = prXmlReader.Value;
DebugTrace(" Value=" + rValueNode.Value, prXmlReader.Depth + 1);
rNewAttribute.InsertNode(rValueNode);
}
} while (prXmlReader.MoveToNextAttribute());
}
if ((rNewNode.Flags & NodeFlags.EmptyElement) == 0)
Process(rNewNode);
break;
case XmlNodeType.XmlDeclaration:
string strValue = rNewNode.NodeValue;
int nPos = strValue.IndexOf("encoding");
if (nPos != -1)
{
int nEnd;
nPos = strValue.IndexOf("=", nPos); //Find the = sign
nEnd = strValue.IndexOf("\"", nPos) + 1; //Find the next " character
nPos = strValue.IndexOf("'", nPos) + 1; //Find the next ' character
if (nEnd == 0 || (nPos < nEnd && nPos > 0)) //Pick the one that's closer to the = sign
{
nEnd = strValue.IndexOf("'", nPos);
}
else
{
nPos = nEnd;
nEnd = strValue.IndexOf("\"", nPos);
}
string sEncodeName = strValue.Substring(nPos, nEnd - nPos);
DebugTrace("XMLDecl contains encoding " + sEncodeName);
if (sEncodeName.ToUpper() == "UCS-2")
{
sEncodeName = "unicode";
}
_eEncoding = System.Text.Encoding.GetEncoding(sEncodeName);
}
break;
case XmlNodeType.ProcessingInstruction:
break;
case XmlNodeType.Text:
if (!_fReadNode)
{
rNewNode.peFlags = _eDefaultFlags | NodeFlags.AttributeTextNode;
}
rNewNode.peFlags |= NodeFlags.MixedContent; // turn on Mixed Content for current node
rNewNode.peFlags &= ~NodeFlags.Indent; // turn off Indent for current node
rParentNode.peFlags |= NodeFlags.MixedContent; // turn on Mixed Content for Parent Node
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.CDATA:
rNewNode.peFlags |= NodeFlags.MixedContent; // turn on Mixed Content for current node
rNewNode.peFlags &= ~NodeFlags.Indent; // turn off Indent for current node
rParentNode.peFlags |= NodeFlags.MixedContent; // turn on Mixed Content for Parent Node
break;
case XmlNodeType.Comment:
case XmlNodeType.Notation:
break;
case XmlNodeType.DocumentType:
if (prXmlReader.MoveToFirstAttribute())
{
do
{
CXmlAttribute rNewAttribute = new CXmlAttribute(prXmlReader);
rNewNode.AddAttribute(rNewAttribute);
CXmlNode rValueNode = new CXmlNode(prXmlReader);
rValueNode._strValue = prXmlReader.Value;
rNewAttribute.InsertNode(rValueNode);
} while (prXmlReader.MoveToNextAttribute());
}
break;
default:
TestLog.WriteLine("UNHANDLED TYPE, " + prXmlReader.NodeType.ToString() + " IN Process()!");
break;
}
}
}
protected virtual CXmlNode GetNewNode(XmlReader rXmlReader)
{
return new CXmlNode(rXmlReader);
}
}
public class ChecksumWriter : TextWriter
{
private int _nPosition = 0;
private Decimal _dResult = 0;
private Encoding _encoding;
// --------------------------------------------------------------------------------------------------
// Constructor
// --------------------------------------------------------------------------------------------------
public ChecksumWriter()
{
_encoding = Encoding.UTF8;
}
// --------------------------------------------------------------------------------------------------
// Properties
// --------------------------------------------------------------------------------------------------
public Decimal CheckSum
{
get { return _dResult; }
}
public override Encoding Encoding
{
get { return _encoding; }
}
// --------------------------------------------------------------------------------------------------
// Public methods
// --------------------------------------------------------------------------------------------------
override public void Write(String str)
{
int i;
int m;
m = str.Length;
for (i = 0; i < m; i++)
{
Write(str[i]);
}
}
override public void Write(Char[] rgch)
{
int i;
int m;
m = rgch.Length;
for (i = 0; i < m; i++)
{
Write(rgch[i]);
}
}
override public void Write(Char[] rgch, Int32 iOffset, Int32 iCount)
{
int i;
int m;
m = iOffset + iCount;
for (i = iOffset; i < m; i++)
{
Write(rgch[i]);
}
}
override public void Write(Char ch)
{
_dResult += Math.Round((Decimal)(ch / (_nPosition + 1.0)), 10);
_nPosition++;
}
public new void Dispose()
{
_nPosition = 0;
_dResult = 0;
}
}
public class BufferWriter : TextWriter
{
private int _nBufferSize = 0;
private int _nBufferUsed = 0;
private int _nBufferGrow = 1024;
private Char[] _rgchBuffer = null;
private Encoding _encoding;
// --------------------------------------------------------------------------------------------------
// Constructor
// --------------------------------------------------------------------------------------------------
public BufferWriter()
{
_encoding = Encoding.UTF8;
}
// --------------------------------------------------------------------------------------------------
// Properties
// --------------------------------------------------------------------------------------------------
override public string ToString()
{
return new String(_rgchBuffer, 0, _nBufferUsed);
}
public override Encoding Encoding
{
get { return _encoding; }
}
// --------------------------------------------------------------------------------------------------
// Public methods
// --------------------------------------------------------------------------------------------------
override public void Write(String str)
{
int i;
int m;
m = str.Length;
for (i = 0; i < m; i++)
{
Write(str[i]);
}
}
override public void Write(Char[] rgch)
{
int i;
int m;
m = rgch.Length;
for (i = 0; i < m; i++)
{
Write(rgch[i]);
}
}
override public void Write(Char[] rgch, Int32 iOffset, Int32 iCount)
{
int i;
int m;
m = iOffset + iCount;
for (i = iOffset; i < m; i++)
{
Write(rgch[i]);
}
}
override public void Write(Char ch)
{
if (_nBufferUsed == _nBufferSize)
{
Char[] rgchTemp = new Char[_nBufferSize + _nBufferGrow];
for (_nBufferUsed = 0; _nBufferUsed < _nBufferSize; _nBufferUsed++)
rgchTemp[_nBufferUsed] = _rgchBuffer[_nBufferUsed];
_rgchBuffer = rgchTemp;
_nBufferSize += _nBufferGrow;
if (_nBufferGrow < (1024 * 1024))
_nBufferGrow *= 2;
}
_rgchBuffer[_nBufferUsed++] = ch;
}
public new void Dispose()
{
//Set nBufferUsed to 0, so we start writing from the beginning of the buffer.
_nBufferUsed = 0;
}
}
| |
/****************************************************************************
Tilde
Copyright (c) 2008 Tantalus Media Pty
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Tilde.Framework.Model;
using System.Drawing;
namespace Tilde.Framework.Controller
{
public class EnumParser<T>
{
public static T Parse(string value, T defaultValue)
{
try
{
return (T) Enum.Parse(typeof(T), value);
}
catch (Exception)
{
return defaultValue;
}
}
}
public enum OptionLocation
{
Project,
User,
Registry
}
public class OptionsManager
{
private IManager mManager;
private ListCollection<IOptions> mOptions;
private SortedDictionary<OptionLocation, IOptionsDatabase> mDatabases;
public OptionsManager(IManager manager)
{
mManager = manager;
mManager.ProjectOpened += new ProjectOpenedEventHandler(Manager_ProjectOpened);
mManager.ProjectClosed += new ProjectClosedEventHandler(Manager_ProjectClosed);
mOptions = new ListCollection<IOptions>();
mOptions.ItemAdded += new ListCollection<IOptions>.ItemAddedDelegate(Options_ItemAdded);
mDatabases = new SortedDictionary<OptionLocation, IOptionsDatabase>();
mDatabases[OptionLocation.Project] = null ;
mDatabases[OptionLocation.User] = null;
mDatabases[OptionLocation.Registry] = new RegistryOptionsDatabase();
}
/// <summary>
/// These IOptions objects are managed by the OptionsManager. When added to the collection,
/// the options are loaded and then stored back again (so a new option has the default value
/// saved off).
/// </summary>
public ListCollection<IOptions> Options
{
get { return mOptions; }
}
public IOptionsDatabase RegistryDatabase
{
get { return mDatabases[OptionLocation.Registry]; }
}
public IOptionsDatabase ProjectDatabase
{
get { return mDatabases[OptionLocation.Project]; }
}
public IOptionsDatabase UserDatabase
{
get { return mDatabases[OptionLocation.User]; }
}
void Options_ItemAdded(ListCollection<IOptions> sender, IOptions item)
{
Load(item);
Store(item);
}
public void Load(IOptions options)
{
foreach (PropertyInfo property in options.GetType().GetProperties())
{
object[] attrs = property.GetCustomAttributes(typeof(OptionAttribute), true);
if(attrs.Length == 1)
{
OptionAttribute attr = (OptionAttribute) attrs[0];
IOptionsDatabase database = mDatabases[attr.Location];
object value;
if (database == null)
{
value = attr.DefaultValue;
}
else
{
if (typeof(String).IsAssignableFrom(property.PropertyType))
value = database.GetStringOption(attr.Path, (string)attr.DefaultValue);
else if (typeof(Boolean).IsAssignableFrom(property.PropertyType))
value = database.GetBooleanOption(attr.Path, (bool)attr.DefaultValue);
else if (typeof(Enum).IsAssignableFrom(property.PropertyType))
{
try
{
value = Enum.Parse(property.PropertyType, database.GetStringOption(attr.Path, ""));
}
catch (Exception)
{
value = attr.DefaultValue;
}
}
else if (typeof(Int32).IsAssignableFrom(property.PropertyType))
value = database.GetIntegerOption(attr.Path, (int)attr.DefaultValue);
else if (typeof(Color).IsAssignableFrom(property.PropertyType))
{
try
{
string name = database.GetStringOption(attr.Path, (string)attr.DefaultValue);
if (name.Contains(","))
{
string[] components = name.Split(new char[] { ',' });
value = Color.FromArgb(Int32.Parse(components[0]), Int32.Parse(components[1]), Int32.Parse(components[2]));
}
else
value = Color.FromName(name);
}
catch (System.Exception)
{
value = attr.DefaultValue;
}
}
else if (typeof(string[]).IsAssignableFrom(property.PropertyType))
value = database.GetStringArrayOption(attr.Path, (string[])attr.DefaultValue);
else
throw new ApplicationException("Don't know how to load option of type: " + property.PropertyType.ToString());
}
property.SetValue(options, value, null);
}
}
}
public void Store(IOptions options)
{
foreach (PropertyInfo property in options.GetType().GetProperties())
{
object[] attrs = property.GetCustomAttributes(typeof(OptionAttribute), true);
if (attrs.Length == 1)
{
StoreOption((OptionAttribute)attrs[0], property, options, false);
}
}
}
private bool StoreOption(OptionAttribute attr, PropertyInfo property, IOptions options, bool validateOnly)
{
IOptionsDatabase database = mDatabases[attr.Location];
bool success;
if (database == null)
success = false;
else if (typeof(String).IsAssignableFrom(property.PropertyType))
success = database.SetStringOption(attr.Path, (string)property.GetValue(options, null), validateOnly);
else if (typeof(bool).IsAssignableFrom(property.PropertyType))
success = database.SetBooleanOption(attr.Path, (bool)property.GetValue(options, null), validateOnly);
else if (typeof(Int32).IsAssignableFrom(property.PropertyType))
success = database.SetIntegerOption(attr.Path, (int)property.GetValue(options, null), validateOnly);
else if (typeof(Enum).IsAssignableFrom(property.PropertyType))
success = database.SetStringOption(attr.Path, property.GetValue(options, null).ToString(), validateOnly);
else if (typeof(string[]).IsAssignableFrom(property.PropertyType))
success = database.SetStringArrayOption(attr.Path, (string[])property.GetValue(options, null), validateOnly);
else if (typeof(Color).IsAssignableFrom(property.PropertyType))
{
Color color = (Color)property.GetValue(options, null);
KnownColor knownColor = color.ToKnownColor();
if (knownColor != 0)
success = database.SetStringOption(attr.Path, knownColor.ToString(), validateOnly);
else
success = database.SetStringOption(attr.Path, String.Join(",", new string[] { color.R.ToString(), color.G.ToString(), color.B.ToString() }), validateOnly);
}
else
success = database.SetStringOption(attr.Path, property.GetValue(options, null).ToString(), validateOnly);
return success;
}
public bool Copy(IOptions from, IOptions to, bool store)
{
System.Diagnostics.Debug.Assert(to.GetType().IsAssignableFrom(from.GetType()));
foreach (PropertyInfo property in from.GetType().GetProperties())
{
object[] attrs = property.GetCustomAttributes(typeof(OptionAttribute), true);
if (attrs.Length == 1)
{
OptionAttribute attr = (OptionAttribute)attrs[0];
if (store && !StoreOption(attr, property, from, false))
return false;
object value = property.GetValue(from, null);
property.SetValue(to, value, null);
}
}
return true;
}
public bool Validate(IOptions from, IOptions to)
{
System.Diagnostics.Debug.Assert(to.GetType().IsAssignableFrom(from.GetType()));
foreach (PropertyInfo property in from.GetType().GetProperties())
{
object[] attrs = property.GetCustomAttributes(typeof(OptionAttribute), true);
if (attrs.Length == 1)
{
OptionAttribute attr = (OptionAttribute)attrs[0];
if(!StoreOption(attr, property, from, true))
return false;
}
}
return true;
}
void Manager_ProjectOpened(IManager sender, Project project)
{
mDatabases[OptionLocation.Project] = project.ProjectOptions;
mDatabases[OptionLocation.User] = project.UserOptions;
foreach (IOptions options in mOptions)
{
Load(options);
Store(options);
}
project.ProjectReloaded += new ProjectReloadedHandler(Project_ProjectReloaded);
}
void Manager_ProjectClosed(IManager sender)
{
mDatabases[OptionLocation.Project] = null;
mDatabases[OptionLocation.User] = null;
}
void Project_ProjectReloaded(Project sender, Tilde.Framework.Model.ProjectHierarchy.ProjectDocumentItem reloadedItem)
{
mDatabases[OptionLocation.Project] = sender.ProjectOptions;
mDatabases[OptionLocation.User] = sender.UserOptions;
foreach (IOptions options in mOptions)
Load(options);
}
}
}
| |
namespace Meziantou.Framework.CodeDom;
public partial class CSharpCodeGenerator
{
private static readonly IDictionary<string, string> s_predefinedTypes = new Dictionary<string, string>(StringComparer.Ordinal)
{
[typeof(bool).FullName!] = "bool",
[typeof(byte).FullName!] = "byte",
[typeof(char).FullName!] = "char",
[typeof(decimal).FullName!] = "decimal",
[typeof(double).FullName!] = "double",
[typeof(float).FullName!] = "float",
[typeof(int).FullName!] = "int",
[typeof(long).FullName!] = "long",
[typeof(object).FullName!] = "object",
[typeof(sbyte).FullName!] = "sbyte",
[typeof(short).FullName!] = "short",
[typeof(string).FullName!] = "string",
[typeof(uint).FullName!] = "uint",
[typeof(ulong).FullName!] = "ulong",
[typeof(ushort).FullName!] = "ushort",
[typeof(void).FullName!] = "void",
};
private static readonly string[] s_keywords = new string[]
{
"bool", "byte", "sbyte", "short", "ushort", "int", "uint", "long", "ulong", "double", "float", "decimal",
"string", "char", "void", "object", "typeof", "sizeof", "null", "true", "false", "if", "else", "while", "for", "foreach", "do", "switch",
"case", "default", "lock", "try", "throw", "catch", "finally", "goto", "break", "continue", "return", "public", "private", "internal",
"protected", "static", "readonly", "sealed", "const", "fixed", "stackalloc", "volatile", "new", "override", "abstract", "virtual",
"event", "extern", "ref", "out", "in", "is", "as", "params", "__arglist", "__makeref", "__reftype", "__refvalue", "this", "base",
"namespace", "using", "class", "struct", "interface", "enum", "delegate", "checked", "unchecked", "unsafe", "operator", "implicit", "explicit",
};
public string Write(CodeObject codeObject!!)
{
using var sw = new StringWriter();
Write(sw, codeObject);
return sw.ToString();
}
public void Write(TextWriter writer!!, CodeObject codeObject!!)
{
using var indentedTextWriter = new IndentedTextWriter(writer, IndentedTextWriter.DefaultTabString, closeWriter: false)
{
NewLine = "\n",
};
Write(indentedTextWriter, codeObject);
}
public void Write(IndentedTextWriter writer!!, CodeObject codeObject!!)
{
switch (codeObject)
{
case CompilationUnit o:
WriteCompilationUnit(writer, o);
break;
case NamespaceDeclaration o:
WriteNamespaceDeclaration(writer, o);
break;
case TypeDeclaration o:
WriteTypeDeclaration(writer, o);
break;
case Expression o:
WriteExpression(writer, o);
break;
case Statement o:
WriteStatement(writer, o);
break;
case Directive o:
WriteDirective(writer, o);
break;
case MemberDeclaration o:
WriteMemberDeclaration(writer, o);
break;
case MethodArgumentDeclaration o:
WriteMethodArgument(writer, o);
break;
case CustomAttribute o:
WriteCustomAttribute(writer, o);
break;
case CustomAttributeArgument o:
WriteCustomAttributeArgument(writer, o);
break;
case CatchClauseCollection o:
WriteCatchClauseCollection(writer, o);
break;
case CatchClause o:
WriteCatchClause(writer, o);
break;
case ConstructorInitializer o:
WriteConstructorInitializer(writer, o);
break;
case TypeParameterConstraint o:
WriteTypeParameterConstraint(writer, o);
break;
case Comment o:
WriteComment(writer, o);
break;
case XmlComment o:
WriteXmlComment(writer, o);
break;
default:
throw new NotSupportedException();
}
}
protected virtual void WriteCompilationUnit(IndentedTextWriter writer, CompilationUnit unit)
{
WriteBeforeComments(writer, unit);
WriteNullableContextBefore(writer, unit);
Write(writer, unit.Usings, writer.NewLine);
Write(writer, unit.Namespaces, writer.NewLine);
Write(writer, unit.Types, writer.NewLine);
WriteAfterComments(writer, unit);
}
protected virtual void WriteNamespaceDeclaration(IndentedTextWriter writer, NamespaceDeclaration ns)
{
WriteBeforeComments(writer, ns);
writer.Write("namespace ");
WriteIdentifier(writer, ns.Name);
writer.WriteLine();
writer.WriteLine("{");
writer.Indent++;
Write(writer, ns.Usings, writer.NewLine);
Write(writer, ns.Types, writer.NewLine);
Write(writer, ns.Namespaces, writer.NewLine);
writer.Indent--;
writer.WriteLine("}");
WriteAfterComments(writer, ns);
}
protected virtual void WriteTypeDeclaration(IndentedTextWriter writer, TypeDeclaration type)
{
WriteNullableContextBefore(writer, type);
WriteXmlComments(writer, type);
WriteBeforeComments(writer, type);
WriteCustomAttributes(writer, type.CustomAttributes);
WriteModifiers(writer, type.Modifiers);
switch (type)
{
case ClassDeclaration o:
WriteClassDeclaration(writer, o);
break;
case StructDeclaration o:
WriteStructDeclaration(writer, o);
break;
case EnumerationDeclaration o:
WriteEnumerationDeclaration(writer, o);
break;
case InterfaceDeclaration o:
WriteInterfaceDeclaration(writer, o);
break;
case DelegateDeclaration o:
WriteDelegateDeclaration(writer, o);
break;
case RecordDeclaration o:
WriteRecordDeclaration(writer, o);
break;
default:
throw new NotSupportedException();
}
WriteAfterComments(writer, type);
WriteNullableContextAfter(writer, type);
}
protected virtual void WriteEnumerationDeclaration(IndentedTextWriter writer, EnumerationDeclaration enumeration)
{
writer.Write("enum ");
WriteIdentifier(writer, enumeration.Name);
if (enumeration.BaseType != null)
{
writer.Write(" : ");
WriteTypeReference(writer, enumeration.BaseType);
}
writer.WriteLine();
writer.WriteLine("{");
writer.Indent++;
Write(writer, enumeration.Members, (e) =>
{
if (!e.Last)
{
writer.WriteLine(",");
}
});
writer.WriteLine();
writer.Indent--;
writer.WriteLine("}");
}
protected virtual void WriteEnumerationMember(IndentedTextWriter writer, EnumerationMember member)
{
WriteCustomAttributes(writer, member.CustomAttributes);
WriteIdentifier(writer, member.Name);
if (member.Value != null)
{
writer.Write(" = ");
WriteExpression(writer, member.Value);
}
}
protected virtual void WriteDelegateDeclaration(IndentedTextWriter writer, DelegateDeclaration d)
{
writer.Write("delegate ");
if (d.ReturnType == null)
{
writer.Write("void ");
}
else
{
WriteTypeReference(writer, d.ReturnType);
writer.Write(" ");
}
WriteIdentifier(writer, d.Name);
WriteGenericParameters(writer, d);
writer.Write("(");
WriteMethodArguments(writer, d.Arguments);
writer.Write(")");
WriteGenericParameterConstraints(writer, d);
if (d.HasConstraints())
{
writer.Indent++;
writer.WriteLine(";");
writer.Indent--;
}
else
{
writer.WriteLine(";");
}
}
protected virtual void WriteMethodDeclaration(IndentedTextWriter writer, MethodDeclaration member)
{
WriteCustomAttributes(writer, member.CustomAttributes);
WriteModifiers(writer, member.Modifiers);
if (member.ReturnType == null)
{
writer.Write("void ");
}
else
{
WriteTypeReference(writer, member.ReturnType);
writer.Write(' ');
}
if (member.PrivateImplementationType != null)
{
WriteTypeReference(writer, member.PrivateImplementationType);
writer.Write('.');
}
WriteIdentifier(writer, member.Name);
WriteGenericParameters(writer, member);
writer.Write("(");
WriteMethodArguments(writer, member.Arguments);
writer.Write(")");
if (member.Statements != null || member.HasConstraints())
{
writer.WriteLine();
}
WriteGenericParameterConstraints(writer, member);
if (member.Statements == null)
{
if (member.HasConstraints())
{
writer.Indent++;
writer.WriteLine(";");
writer.Indent--;
}
else
{
writer.WriteLine(";");
}
}
else
{
WriteStatements(writer, member.Statements);
}
}
protected virtual void WriteOperatorDeclaration(IndentedTextWriter writer, OperatorDeclaration member)
{
var isConversion = member.Modifiers.HasFlag(Modifiers.Implicit) || member.Modifiers.HasFlag(Modifiers.Explicit);
WriteCustomAttributes(writer, member.CustomAttributes);
WriteModifiers(writer, member.Modifiers);
if (isConversion)
{
writer.Write("operator ");
if (member.ReturnType != null)
{
WriteTypeReference(writer, member.ReturnType);
}
else
{
var declaringType = member.SelfOrAnscestorOfType<TypeDeclaration>();
if (declaringType != null)
{
WriteIdentifier(writer, declaringType.Name);
}
}
}
else
{
if (member.ReturnType != null)
{
WriteTypeReference(writer, member.ReturnType);
writer.Write(' ');
}
writer.Write("operator ");
}
WriteIdentifier(writer, member.Name);
writer.Write("(");
WriteMethodArguments(writer, member.Arguments);
writer.Write(")");
writer.WriteLine();
WriteStatements(writer, member.Statements);
}
protected virtual void WriteMethodArguments(IndentedTextWriter writer, MethodArgumentCollection args)
{
Write(writer, args, ", ");
}
protected virtual void WriteMethodArgument(IndentedTextWriter writer, MethodArgumentDeclaration arg)
{
WriteBeforeComments(writer, arg);
WriteCustomAttributes(writer, arg.CustomAttributes);
if (arg.IsExtension)
{
writer.Write("this ");
}
WriteDirection(writer, arg.Direction);
WriteTypeReference(writer, arg.Type);
writer.Write(" ");
WriteIdentifier(writer, arg.Name);
if (arg.DefaultValue != null)
{
writer.Write(" = ");
WriteExpression(writer, arg.DefaultValue);
}
WriteAfterComments(writer, arg);
}
protected virtual void WriteDirection(IndentedTextWriter writer, Direction direction)
{
switch (direction)
{
case Direction.Out:
writer.Write("out ");
break;
case Direction.InOut:
writer.Write("ref ");
break;
case Direction.ReadOnlyRef:
writer.Write("in ");
break;
case Direction.In:
break;
default:
throw new ArgumentOutOfRangeException(nameof(direction));
}
}
protected virtual void WriteFieldDeclaration(IndentedTextWriter writer, FieldDeclaration member)
{
WriteCustomAttributes(writer, member.CustomAttributes);
WriteModifiers(writer, member.Modifiers);
if (member.Type == null)
{
writer.Write("var ");
}
else
{
WriteTypeReference(writer, member.Type);
writer.Write(" ");
}
WriteIdentifier(writer, member.Name);
if (member.InitExpression != null)
{
writer.Write(" = ");
WriteExpression(writer, member.InitExpression);
}
writer.WriteLine(";");
}
protected virtual void WriteEventFieldDeclaration(IndentedTextWriter writer, EventFieldDeclaration member)
{
WriteCustomAttributes(writer, member.CustomAttributes);
WriteModifiers(writer, member.Modifiers);
writer.Write("event ");
if (member.Type != null)
{
WriteTypeReference(writer, member.Type);
writer.Write(" ");
}
if (member.PrivateImplementationType != null)
{
WriteTypeReference(writer, member.PrivateImplementationType);
writer.Write('.');
}
WriteIdentifier(writer, member.Name);
if (member.AddAccessor == null && member.RemoveAccessor == null)
{
writer.WriteLine(";");
}
else
{
writer.WriteLine();
writer.WriteLine("{");
writer.Indent++;
if (member.AddAccessor != null)
{
writer.WriteLine("add");
WriteStatements(writer, member.AddAccessor);
}
if (member.RemoveAccessor != null)
{
writer.WriteLine("remove");
WriteStatements(writer, member.RemoveAccessor);
}
writer.Indent--;
writer.WriteLine("}");
}
}
protected virtual void WriteConstructorDeclaration(IndentedTextWriter writer, ConstructorDeclaration member)
{
WriteCustomAttributes(writer, member.CustomAttributes);
WriteModifiers(writer, member.Modifiers);
var name = member.ParentType?.Name ?? member.Name;
if (name != null)
{
WriteIdentifier(writer, name);
}
writer.Write("(");
WriteMethodArguments(writer, member.Arguments);
writer.Write(")");
if (member.Initializer != null)
{
writer.WriteLine();
writer.Indent++;
WriteConstructorInitializer(writer, member.Initializer);
writer.Indent--;
}
writer.WriteLine();
WriteStatements(writer, member.Statements);
}
protected virtual void WritePropertyDeclaration(IndentedTextWriter writer, PropertyDeclaration member)
{
WriteCustomAttributes(writer, member.CustomAttributes);
WriteModifiers(writer, member.Modifiers);
WriteTypeReference(writer, member.Type);
writer.Write(" ");
if (member.PrivateImplementationType != null)
{
WriteTypeReference(writer, member.PrivateImplementationType);
writer.Write('.');
}
WriteIdentifier(writer, member.Name);
writer.WriteLine();
writer.WriteLine("{");
writer.Indent++;
if (member.Getter != null)
{
WriteCustomAttributes(writer, member.Getter.CustomAttributes);
WriteModifiers(writer, member.Getter.Modifiers);
if (member.Getter.Statements != null)
{
writer.WriteLine("get");
WriteStatements(writer, member.Getter.Statements);
}
else
{
writer.WriteLine("get;");
}
}
if (member.Setter != null)
{
WriteCustomAttributes(writer, member.Setter.CustomAttributes);
WriteModifiers(writer, member.Setter.Modifiers);
if (member.Setter.Statements != null)
{
writer.WriteLine("set");
WriteStatements(writer, member.Setter.Statements);
}
else
{
writer.WriteLine("set;");
}
}
writer.Indent--;
writer.WriteLine("}");
}
protected virtual void WriteClassDeclaration(IndentedTextWriter writer, ClassDeclaration type)
{
writer.Write("class ");
WriteIdentifier(writer, type.Name);
WriteGenericParameters(writer, type);
var baseTypes = GetBaseTypes(type);
if (baseTypes.Any())
{
writer.Write(" : ");
WriteTypeReferences(writer, baseTypes, ", ");
}
writer.WriteLine();
WriteGenericParameterConstraints(writer, type);
writer.WriteLine("{");
writer.Indent++;
WriteLines(writer, Concat(type.Members, type.Types), endOfLine: null);
writer.Indent--;
writer.WriteLine("}");
}
protected virtual void WriteRecordDeclaration(IndentedTextWriter writer, RecordDeclaration type)
{
writer.Write("record ");
WriteIdentifier(writer, type.Name);
WriteGenericParameters(writer, type);
var baseTypes = GetBaseTypes(type);
if (baseTypes.Any())
{
writer.Write(" : ");
WriteTypeReferences(writer, baseTypes, ", ");
}
writer.WriteLine();
WriteGenericParameterConstraints(writer, type);
writer.WriteLine("{");
writer.Indent++;
WriteLines(writer, Concat(type.Members, type.Types), endOfLine: null);
writer.Indent--;
writer.WriteLine("}");
}
protected virtual void WriteStructDeclaration(IndentedTextWriter writer, StructDeclaration type)
{
writer.Write("struct ");
WriteIdentifier(writer, type.Name);
WriteGenericParameters(writer, type);
var baseTypes = type.Implements;
if (baseTypes.Any())
{
writer.Write(" : ");
WriteTypeReferences(writer, baseTypes, ", ");
}
writer.WriteLine();
WriteGenericParameterConstraints(writer, type);
writer.WriteLine("{");
writer.Indent++;
WriteLines(writer, Concat(type.Members, type.Types), endOfLine: null);
writer.Indent--;
writer.WriteLine("}");
}
protected virtual void WriteInterfaceDeclaration(IndentedTextWriter writer, InterfaceDeclaration type)
{
writer.Write("interface ");
WriteIdentifier(writer, type.Name);
WriteGenericParameters(writer, type);
var baseTypes = GetBaseTypes(type);
if (baseTypes.Any())
{
writer.Write(" : ");
WriteTypeReferences(writer, baseTypes, ", ");
}
writer.WriteLine();
WriteGenericParameterConstraints(writer, type);
writer.WriteLine("{");
writer.Indent++;
Write(writer, type.Members, writer.NewLine);
Write(writer, type.Types, writer.NewLine);
writer.Indent--;
writer.WriteLine("}");
}
protected virtual void WriteModifiers(IndentedTextWriter writer, Modifiers modifiers)
{
if ((modifiers & Modifiers.Private) == Modifiers.Private)
{
writer.Write("private ");
}
if ((modifiers & Modifiers.Protected) == Modifiers.Protected)
{
writer.Write("protected ");
}
if ((modifiers & Modifiers.Internal) == Modifiers.Internal)
{
writer.Write("internal ");
}
if ((modifiers & Modifiers.Public) == Modifiers.Public)
{
writer.Write("public ");
}
if ((modifiers & Modifiers.Abstract) == Modifiers.Abstract)
{
writer.Write("abstract ");
}
if ((modifiers & Modifiers.Override) == Modifiers.Override)
{
writer.Write("override ");
}
if ((modifiers & Modifiers.Sealed) == Modifiers.Sealed)
{
writer.Write("sealed ");
}
if ((modifiers & Modifiers.Static) == Modifiers.Static)
{
writer.Write("static ");
}
if ((modifiers & Modifiers.Async) == Modifiers.Async)
{
writer.Write("async ");
}
if ((modifiers & Modifiers.Const) == Modifiers.Const)
{
writer.Write("const ");
}
if ((modifiers & Modifiers.New) == Modifiers.New)
{
writer.Write("new ");
}
if ((modifiers & Modifiers.Ref) == Modifiers.Ref)
{
writer.Write("ref ");
}
if ((modifiers & Modifiers.ReadOnly) == Modifiers.ReadOnly)
{
writer.Write("readonly ");
}
if ((modifiers & Modifiers.Partial) == Modifiers.Partial)
{
writer.Write("partial ");
}
if ((modifiers & Modifiers.Unsafe) == Modifiers.Unsafe)
{
writer.Write("unsafe ");
}
if ((modifiers & Modifiers.Virtual) == Modifiers.Virtual)
{
writer.Write("virtual ");
}
if ((modifiers & Modifiers.Volatile) == Modifiers.Volatile)
{
writer.Write("volatile ");
}
if ((modifiers & Modifiers.Implicit) == Modifiers.Implicit)
{
writer.Write("implicit ");
}
if ((modifiers & Modifiers.Explicit) == Modifiers.Explicit)
{
writer.Write("explicit ");
}
}
protected virtual void WriteCustomAttributes(IndentedTextWriter writer, CodeObjectCollection<CustomAttribute> attributes)
{
if (attributes.Count > 0)
{
Write(writer, attributes, writer.NewLine);
writer.WriteLine();
}
}
protected virtual void WriteCustomAttribute(IndentedTextWriter writer, CustomAttribute attribute)
{
WriteBeforeComments(writer, attribute);
writer.Write("[");
if (attribute.Target.HasValue)
{
writer.Write(WriteCustomAttributeTarget(attribute.Target.Value));
writer.Write(": ");
}
WriteTypeReference(writer, attribute.Type);
if (attribute.Arguments.Count > 0)
{
writer.Write("(");
Write(writer, attribute.Arguments.OrderBy(GetSortOrder), ", ");
writer.Write(")");
}
writer.Write("]");
WriteAfterComments(writer, attribute);
static int GetSortOrder(CustomAttributeArgument arg)
{
if (arg.PropertyName == null)
return 0;
return 1;
}
}
protected virtual void WriteCustomAttributeArgument(IndentedTextWriter writer, CustomAttributeArgument arg)
{
WriteBeforeComments(writer, arg);
if (!string.IsNullOrEmpty(arg.PropertyName))
{
WriteIdentifier(writer, arg.PropertyName);
writer.Write(" = ");
}
WriteExpression(writer, arg.Value);
WriteAfterComments(writer, arg);
}
protected virtual void WriteMemberDeclaration(IndentedTextWriter writer, MemberDeclaration member)
{
WriteNullableContextBefore(writer, member);
WriteXmlComments(writer, member);
WriteBeforeComments(writer, member);
switch (member)
{
case EnumerationMember o:
WriteEnumerationMember(writer, o);
break;
case MethodDeclaration o:
WriteMethodDeclaration(writer, o);
break;
case OperatorDeclaration o:
WriteOperatorDeclaration(writer, o);
break;
case FieldDeclaration o:
WriteFieldDeclaration(writer, o);
break;
case ConstructorDeclaration o:
WriteConstructorDeclaration(writer, o);
break;
case PropertyDeclaration o:
WritePropertyDeclaration(writer, o);
break;
case EventFieldDeclaration o:
WriteEventFieldDeclaration(writer, o);
break;
default:
throw new NotSupportedException();
}
WriteAfterComments(writer, member);
WriteNullableContextAfter(writer, member);
}
protected virtual void WriteDirective(IndentedTextWriter writer, Directive directive)
{
WriteBeforeComments(writer, directive);
switch (directive)
{
case UsingDirective o:
WriteUsingDirective(writer, o);
break;
default:
throw new NotSupportedException();
}
WriteAfterComments(writer, directive);
}
protected virtual void WriteUsingDirective(IndentedTextWriter writer, UsingDirective usingDirective)
{
writer.Write("using ");
writer.Write(usingDirective.Namespace);
writer.Write(";");
}
protected virtual void WriteCatchClause(IndentedTextWriter writer, CatchClause catchClause)
{
WriteBeforeComments(writer, catchClause);
writer.Write("catch");
if (catchClause.ExceptionType != null)
{
writer.Write(" (");
WriteTypeReference(writer, catchClause.ExceptionType);
if (!string.IsNullOrEmpty(catchClause.ExceptionVariableName))
{
writer.Write(" ");
writer.Write(catchClause.ExceptionVariableName);
}
writer.Write(")");
}
writer.WriteLine();
WriteStatements(writer, catchClause.Body);
WriteAfterComments(writer, catchClause);
}
protected virtual void WriteCatchClauseCollection(IndentedTextWriter writer, CatchClauseCollection clauses)
{
Write(writer, clauses, "");
}
protected virtual void WriteConstructorInitializer(IndentedTextWriter writer, ConstructorInitializer initializer)
{
WriteBeforeComments(writer, initializer);
writer.Write(": ");
switch (initializer)
{
case ConstructorThisInitializer _:
writer.Write("this");
break;
case ConstructorBaseInitializer _:
writer.Write("base");
break;
default:
throw new ArgumentOutOfRangeException(nameof(initializer));
}
writer.Write('(');
Write(writer, initializer.Arguments, ", ");
writer.Write(')');
WriteAfterComments(writer, initializer);
}
protected virtual void WriteTypeParameterConstraint(IndentedTextWriter writer, TypeParameterConstraint constraint)
{
switch (constraint)
{
case BaseTypeParameterConstraint o:
WriteBaseTypeParameterContraint(writer, o);
break;
case ClassTypeParameterConstraint o:
WriteClassTypeParameterConstraint(writer, o);
break;
case ValueTypeTypeParameterConstraint o:
WriteValueTypeParameterContraint(writer, o);
break;
case ConstructorParameterConstraint o:
WriteConstructParameterConstraint(writer, o);
break;
case UnmanagedTypeParameterConstraint o:
WriteUnmanagedTypeParameterConstraint(writer, o);
break;
default:
throw new NotSupportedException();
}
}
protected virtual void WriteBaseTypeParameterContraint(IndentedTextWriter writer, BaseTypeParameterConstraint constraint)
{
WriteTypeReference(writer, constraint.Type);
}
protected virtual void WriteClassTypeParameterConstraint(IndentedTextWriter writer, ClassTypeParameterConstraint constraint)
{
writer.Write("class");
}
protected virtual void WriteValueTypeParameterContraint(IndentedTextWriter writer, ValueTypeTypeParameterConstraint constraint)
{
writer.Write("struct");
}
protected virtual void WriteUnmanagedTypeParameterConstraint(IndentedTextWriter writer, UnmanagedTypeParameterConstraint constraint)
{
writer.Write("unmanaged");
}
protected virtual void WriteConstructParameterConstraint(IndentedTextWriter writer, ConstructorParameterConstraint constraint)
{
writer.Write("new()");
}
protected virtual CommentType WriteComment(IndentedTextWriter writer, Comment comment)
{
switch (comment.Type)
{
case CommentType.LineComment:
WriteLineComment(writer, comment.Text);
return CommentType.LineComment;
case CommentType.InlineComment:
if (TryWriteInlineComment(writer, comment.Text))
return CommentType.InlineComment;
return CommentType.LineComment;
default:
throw new ArgumentOutOfRangeException(nameof(comment));
}
}
protected virtual void WriteXmlComment(IndentedTextWriter writer, XmlComment comment)
{
WriteDocumentationComment(writer, comment.Element?.ToString());
}
protected virtual string WriteBinaryOperator(BinaryOperator op)
{
return op switch
{
BinaryOperator.None => "",
BinaryOperator.Equals => "==",
BinaryOperator.NotEquals => "!=",
BinaryOperator.LessThan => "<",
BinaryOperator.LessThanOrEqual => "<=",
BinaryOperator.GreaterThan => ">",
BinaryOperator.GreaterThanOrEqual => ">=",
BinaryOperator.Or => "||",
BinaryOperator.BitwiseOr => "|",
BinaryOperator.And => "&&",
BinaryOperator.BitwiseAnd => "&",
BinaryOperator.Add => "+",
BinaryOperator.Substract => "-",
BinaryOperator.Multiply => "*",
BinaryOperator.Divide => "/",
BinaryOperator.Modulo => "%",
BinaryOperator.ShiftLeft => "<<",
BinaryOperator.ShiftRight => ">>",
BinaryOperator.Xor => "^",
_ => throw new ArgumentOutOfRangeException(nameof(op)),
};
}
[SuppressMessage("Style", "IDE0066:Convert switch statement to expression", Justification = "Better readability")]
protected virtual bool IsPrefixOperator(UnaryOperator op)
{
switch (op)
{
case UnaryOperator.None:
case UnaryOperator.Not:
case UnaryOperator.Complement:
case UnaryOperator.Plus:
case UnaryOperator.Minus:
case UnaryOperator.PreIncrement:
case UnaryOperator.PreDecrement:
return true;
case UnaryOperator.PostIncrement:
case UnaryOperator.PostDecrement:
return false;
default:
throw new ArgumentOutOfRangeException(nameof(op));
}
}
protected virtual string WriteUnaryOperator(UnaryOperator op)
{
return op switch
{
UnaryOperator.None => "",
UnaryOperator.Not => "!",
UnaryOperator.Complement => "~",
UnaryOperator.Plus => "+",
UnaryOperator.Minus => "-",
UnaryOperator.PreIncrement or UnaryOperator.PostIncrement => "++",
UnaryOperator.PreDecrement or UnaryOperator.PostDecrement => "--",
_ => throw new ArgumentOutOfRangeException(nameof(op)),
};
}
protected virtual string WriteCustomAttributeTarget(CustomAttributeTarget target)
{
return target switch
{
CustomAttributeTarget.Assembly => "assembly",
CustomAttributeTarget.Module => "module",
CustomAttributeTarget.Field => "field",
CustomAttributeTarget.Event => "event",
CustomAttributeTarget.Method => "method",
CustomAttributeTarget.Param => "param",
CustomAttributeTarget.Property => "property",
CustomAttributeTarget.Return => "return",
CustomAttributeTarget.Type => "type",
_ => throw new ArgumentOutOfRangeException(nameof(target)),
};
}
protected virtual void WriteIdentifier(IndentedTextWriter writer, string? name)
{
if (name == null)
return;
if (s_keywords.Contains(name, StringComparer.Ordinal))
{
writer.Write("@");
}
writer.Write(name);
}
protected virtual void WriteStatements(IndentedTextWriter writer, StatementCollection? statements)
{
writer.WriteLine("{");
writer.Indent++;
if (statements != null)
{
var mustAddNewLine = false;
foreach (var statement in statements)
{
if (mustAddNewLine)
{
writer.WriteLine();
mustAddNewLine = false;
}
WriteStatement(writer, statement);
mustAddNewLine = IsBlockStatement(statement);
}
}
writer.Indent--;
writer.WriteLine("}");
static bool IsBlockStatement(Statement statement)
{
return statement is ConditionStatement
|| statement is IterationStatement
|| statement is TryCatchFinallyStatement
|| statement is UsingStatement
|| statement is WhileStatement;
}
}
protected virtual void WriteConstraints(IndentedTextWriter writer, TypeParameter parameter)
{
// 1. class, struct, unmanaged
// 2. base
// 3. new()
var orderedConstraints = new List<TypeParameterConstraint>(parameter.Constraints.Count);
orderedConstraints.AddRange(parameter.Constraints.Where(p => p is ValueTypeTypeParameterConstraint || p is ClassTypeParameterConstraint || p is UnmanagedTypeParameterConstraint));
orderedConstraints.AddRange(parameter.Constraints.Where(p => p is BaseTypeParameterConstraint));
orderedConstraints.AddRange(parameter.Constraints.Where(p => p is ConstructorParameterConstraint));
writer.Write("where ");
writer.Write(parameter.Name);
writer.Write(" : ");
Write(writer, orderedConstraints, ", ");
}
protected virtual void WriteDocumentationComment(IndentedTextWriter writer, string? comment)
{
if (comment == null)
return;
using var sr = new StringReader(comment);
string? line;
while ((line = sr.ReadLine()) != null)
{
if (string.IsNullOrEmpty(line))
{
writer.WriteLine("///");
}
else
{
writer.WriteLine("/// " + line);
}
}
}
protected virtual void WriteLineComment(IndentedTextWriter writer, string? comment)
{
if (comment == null)
{
writer.WriteLine("//");
return;
}
using var sr = new StringReader(comment);
string? line;
while ((line = sr.ReadLine()) != null)
{
if (string.IsNullOrEmpty(line))
{
writer.WriteLine("//");
}
else
{
writer.WriteLine("// " + line);
}
}
}
protected virtual bool TryWriteInlineComment(IndentedTextWriter writer, string? comment)
{
if (comment == null)
{
writer.WriteLine("/* */");
return true;
}
if (comment.Contains("*/", StringComparison.Ordinal))
{
WriteLineComment(writer, comment);
return false;
}
else
{
writer.Write("/* ");
writer.Write(comment);
writer.Write(" */");
return true;
}
}
protected virtual void WriteXmlComments(IndentedTextWriter writer, IXmlCommentable commentable)
{
foreach (var comment in commentable.XmlComments)
{
WriteXmlComment(writer, comment);
}
}
protected virtual void WriteBeforeComments(IndentedTextWriter writer, ICommentable commentable)
{
CommentType type = default;
var first = true;
foreach (var c in commentable.CommentsBefore)
{
if (!first)
{
if (type == CommentType.InlineComment)
{
writer.Write(' ');
}
}
type = WriteComment(writer, c);
first = false;
}
if (!first && type == CommentType.InlineComment)
{
writer.Write(' ');
}
}
protected virtual void WriteAfterComments(IndentedTextWriter writer, ICommentable commentable)
{
var isInlined = commentable is Expression;
CommentType type = default;
var first = true;
foreach (var c in commentable.CommentsAfter)
{
if ((isInlined && first) || (type == CommentType.InlineComment && c.Type == CommentType.InlineComment))
{
writer.Write(' ');
}
type = WriteComment(writer, c);
first = false;
}
}
private void WriteGenericParameters(IndentedTextWriter writer, IList<TypeReference> types)
{
if (types.Any())
{
writer.Write("<");
WriteTypeReferences(writer, types, ", ");
writer.Write(">");
}
}
private static void WriteGenericParameters(IndentedTextWriter writer, IParametrableType type)
{
if (type.Parameters.Any())
{
writer.Write("<");
WriteValues(writer, type.Parameters.Select(p => p.Name), ", ");
writer.Write(">");
}
}
private void WriteGenericParameterConstraints(IndentedTextWriter writer, IParametrableType type)
{
writer.Indent++;
foreach (var parameter in type.Parameters)
{
if (parameter.HasConstraints())
{
WriteConstraints(writer, parameter);
writer.WriteLine();
}
}
writer.Indent--;
}
private static List<TypeReference> GetBaseTypes(IInheritanceParameters c)
{
var list = new List<TypeReference>();
if (c.BaseType != null)
{
list.Add(c.BaseType);
}
foreach (var type in c.Implements)
{
list.Add(type);
}
return list;
}
private static void WriteValues<T>(IndentedTextWriter writer, IEnumerable<T> objects, string separator)
{
var first = true;
foreach (var o in objects)
{
if (!first)
{
writer.Write(separator);
}
writer.Write(o);
first = false;
}
}
private void Write<T>(IndentedTextWriter writer, IEnumerable<T> objects, string separator) where T : CodeObject
{
var first = true;
foreach (var o in objects)
{
if (!first && separator != null)
{
writer.Write(separator);
}
Write(writer, o);
first = false;
}
}
private void WriteLines<T>(IndentedTextWriter writer, IEnumerable<T> objects, string? endOfLine)
where T : CodeObject
{
var first = true;
foreach (var o in objects)
{
if (!first)
{
writer.WriteLine(endOfLine);
}
Write(writer, o);
first = false;
}
}
private void Write<T>(IndentedTextWriter writer, IReadOnlyList<T> objects, Action<(T Item, bool First, bool Last)> afterItemAction) where T : CodeObject
{
for (var i = 0; i < objects.Count; i++)
{
var o = objects[i];
Write(writer, o);
afterItemAction((o, i == 0, i == objects.Count - 1));
}
}
protected virtual void WriteTypeReference(IndentedTextWriter writer, TypeReference? type)
{
if (type == null)
return;
if (s_predefinedTypes.TryGetValue(type.ClrFullTypeNameWithoutArray, out var keyword))
{
writer.Write(keyword);
}
else
{
if (type.TypeName != null)
{
writer.Write(type.TypeName.Replace('+', '.'));
}
WriteGenericParameters(writer, type.Parameters);
}
if (type.Nullable == NullableAnnotation.Nullable)
{
writer.Write('?');
}
if (type.IsArray)
{
writer.Write('[');
for (var i = 1; i < type.ArrayRank; i++)
{
writer.Write(',');
}
writer.Write(']');
}
}
protected virtual void WriteTypeReferences(IndentedTextWriter writer, IEnumerable<TypeReference?> types, string separator)
{
var first = true;
foreach (var type in types)
{
if (type != null)
{
if (!first)
{
writer.Write(separator);
}
WriteTypeReference(writer, type);
first = false;
}
}
}
protected virtual void WriteNullableContextBefore(IndentedTextWriter writer, INullableContext nullableContext)
{
switch (nullableContext.NullableContext)
{
case NullableContext.Enable:
writer.EnsureNewLine();
writer.WriteLineNoTabs("#nullable enable");
break;
case NullableContext.Disable:
writer.EnsureNewLine();
writer.WriteLineNoTabs("#nullable disable");
break;
}
}
protected virtual void WriteNullableContextAfter(IndentedTextWriter writer, INullableContext nullableContext)
{
switch (nullableContext.NullableContext)
{
case NullableContext.Enable:
writer.EnsureNewLine();
writer.WriteLineNoTabs("#nullable disable");
break;
case NullableContext.Disable:
writer.EnsureNewLine();
writer.WriteLineNoTabs("#nullable enable");
break;
}
}
private static IEnumerable<CodeObject> Concat(IEnumerable<CodeObject> items1, IEnumerable<CodeObject> items2)
{
foreach (var item in items1)
yield return item;
foreach (var item in items2)
yield return item;
}
}
| |
// -----------------------------------------------------------
//
// This file was generated, please do not modify.
//
// -----------------------------------------------------------
namespace EmptyKeys.UserInterface.Generated {
using System;
using System.CodeDom.Compiler;
using System.Collections.ObjectModel;
using EmptyKeys.UserInterface;
using EmptyKeys.UserInterface.Charts;
using EmptyKeys.UserInterface.Data;
using EmptyKeys.UserInterface.Controls;
using EmptyKeys.UserInterface.Controls.Primitives;
using EmptyKeys.UserInterface.Input;
using EmptyKeys.UserInterface.Interactions.Core;
using EmptyKeys.UserInterface.Interactivity;
using EmptyKeys.UserInterface.Media;
using EmptyKeys.UserInterface.Media.Effects;
using EmptyKeys.UserInterface.Media.Animation;
using EmptyKeys.UserInterface.Media.Imaging;
using EmptyKeys.UserInterface.Shapes;
using EmptyKeys.UserInterface.Renderers;
using EmptyKeys.UserInterface.Themes;
[GeneratedCodeAttribute("Empty Keys UI Generator", "3.3.0.0")]
public sealed class Dictionary : ResourceDictionary {
private static Dictionary singleton = new Dictionary();
public Dictionary() {
this.InitializeResources();
}
public static Dictionary Instance {
get {
return singleton;
}
}
private void InitializeResources() {
// Resource - [buttonAnimStyle] Style
var r_0_s_bo = this[typeof(Button)];
Style r_0_s = new Style(typeof(Button), r_0_s_bo as Style);
Setter r_0_s_S_0 = new Setter(Button.WidthProperty, 200F);
r_0_s.Setters.Add(r_0_s_S_0);
Setter r_0_s_S_1 = new Setter(Button.MarginProperty, new Thickness(0F, 1F, 0F, 1F));
r_0_s.Setters.Add(r_0_s_S_1);
Setter r_0_s_S_2 = new Setter(Button.SnapsToDevicePixelsProperty, false);
r_0_s.Setters.Add(r_0_s_S_2);
EventTrigger r_0_s_ET_0 = new EventTrigger(Button.MouseEnterEvent);
r_0_s.Triggers.Add(r_0_s_ET_0);
BeginStoryboard r_0_s_ET_0_AC_0 = new BeginStoryboard();
r_0_s_ET_0_AC_0.Name = "r_0_s_ET_0_AC_0";
r_0_s_ET_0.AddAction(r_0_s_ET_0_AC_0);
Storyboard r_0_s_ET_0_AC_0_SB = new Storyboard();
r_0_s_ET_0_AC_0.Storyboard = r_0_s_ET_0_AC_0_SB;
r_0_s_ET_0_AC_0_SB.Name = "r_0_s_ET_0_AC_0_SB";
ThicknessAnimation r_0_s_ET_0_AC_0_SB_TL_0 = new ThicknessAnimation();
r_0_s_ET_0_AC_0_SB_TL_0.Name = "r_0_s_ET_0_AC_0_SB_TL_0";
r_0_s_ET_0_AC_0_SB_TL_0.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 500));
r_0_s_ET_0_AC_0_SB_TL_0.From = new Thickness(0F, 1F, 0F, 1F);
r_0_s_ET_0_AC_0_SB_TL_0.To = new Thickness(0F, 5F, 0F, 5F);
SineEase r_0_s_ET_0_AC_0_SB_TL_0_EA = new SineEase();
r_0_s_ET_0_AC_0_SB_TL_0.EasingFunction = r_0_s_ET_0_AC_0_SB_TL_0_EA;
Storyboard.SetTargetProperty(r_0_s_ET_0_AC_0_SB_TL_0, Button.MarginProperty);
r_0_s_ET_0_AC_0_SB.Children.Add(r_0_s_ET_0_AC_0_SB_TL_0);
FloatAnimation r_0_s_ET_0_AC_0_SB_TL_1 = new FloatAnimation();
r_0_s_ET_0_AC_0_SB_TL_1.Name = "r_0_s_ET_0_AC_0_SB_TL_1";
r_0_s_ET_0_AC_0_SB_TL_1.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 500));
r_0_s_ET_0_AC_0_SB_TL_1.To = 220F;
SineEase r_0_s_ET_0_AC_0_SB_TL_1_EA = new SineEase();
r_0_s_ET_0_AC_0_SB_TL_1.EasingFunction = r_0_s_ET_0_AC_0_SB_TL_1_EA;
Storyboard.SetTargetProperty(r_0_s_ET_0_AC_0_SB_TL_1, Button.WidthProperty);
r_0_s_ET_0_AC_0_SB.Children.Add(r_0_s_ET_0_AC_0_SB_TL_1);
EventTrigger r_0_s_ET_1 = new EventTrigger(Button.MouseLeaveEvent);
r_0_s.Triggers.Add(r_0_s_ET_1);
BeginStoryboard r_0_s_ET_1_AC_0 = new BeginStoryboard();
r_0_s_ET_1_AC_0.Name = "r_0_s_ET_1_AC_0";
r_0_s_ET_1.AddAction(r_0_s_ET_1_AC_0);
Storyboard r_0_s_ET_1_AC_0_SB = new Storyboard();
r_0_s_ET_1_AC_0.Storyboard = r_0_s_ET_1_AC_0_SB;
r_0_s_ET_1_AC_0_SB.Name = "r_0_s_ET_1_AC_0_SB";
ThicknessAnimation r_0_s_ET_1_AC_0_SB_TL_0 = new ThicknessAnimation();
r_0_s_ET_1_AC_0_SB_TL_0.Name = "r_0_s_ET_1_AC_0_SB_TL_0";
r_0_s_ET_1_AC_0_SB_TL_0.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 500));
r_0_s_ET_1_AC_0_SB_TL_0.From = new Thickness(0F, 5F, 0F, 5F);
r_0_s_ET_1_AC_0_SB_TL_0.To = new Thickness(0F, 1F, 0F, 1F);
SineEase r_0_s_ET_1_AC_0_SB_TL_0_EA = new SineEase();
r_0_s_ET_1_AC_0_SB_TL_0.EasingFunction = r_0_s_ET_1_AC_0_SB_TL_0_EA;
Storyboard.SetTargetProperty(r_0_s_ET_1_AC_0_SB_TL_0, Button.MarginProperty);
r_0_s_ET_1_AC_0_SB.Children.Add(r_0_s_ET_1_AC_0_SB_TL_0);
FloatAnimation r_0_s_ET_1_AC_0_SB_TL_1 = new FloatAnimation();
r_0_s_ET_1_AC_0_SB_TL_1.Name = "r_0_s_ET_1_AC_0_SB_TL_1";
r_0_s_ET_1_AC_0_SB_TL_1.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 500));
r_0_s_ET_1_AC_0_SB_TL_1.To = 200F;
SineEase r_0_s_ET_1_AC_0_SB_TL_1_EA = new SineEase();
r_0_s_ET_1_AC_0_SB_TL_1.EasingFunction = r_0_s_ET_1_AC_0_SB_TL_1_EA;
Storyboard.SetTargetProperty(r_0_s_ET_1_AC_0_SB_TL_1, Button.WidthProperty);
r_0_s_ET_1_AC_0_SB.Children.Add(r_0_s_ET_1_AC_0_SB_TL_1);
this.Add("buttonAnimStyle", r_0_s);
// Resource - [buttonStyle] Style
var r_1_s_bo = this[typeof(Button)];
Style r_1_s = new Style(typeof(Button), r_1_s_bo as Style);
Setter r_1_s_S_0 = new Setter(Button.BackgroundProperty, new SolidColorBrush(new ColorW(255, 140, 0, 255)));
r_1_s.Setters.Add(r_1_s_S_0);
this.Add("buttonStyle", r_1_s);
// Resource - [CustomWindowTemplate] ControlTemplate
Func<UIElement, UIElement> r_2_ctFunc = r_2_ctMethod;
ControlTemplate r_2_ct = new ControlTemplate(r_2_ctFunc);
this.Add("CustomWindowTemplate", r_2_ct);
// Resource - [DataTemplateKey(GameData.CustomWindow)] DataTemplate
Func<UIElement, UIElement> r_3_dtFunc = r_3_dtMethod;
this.Add(typeof(GameData.CustomWindow), new DataTemplate(typeof(GameData.CustomWindow), r_3_dtFunc));
// Resource - [DataTemplateKey(GameData.DragDropItem)] DataTemplate
Func<UIElement, UIElement> r_4_dtFunc = r_4_dtMethod;
this.Add(typeof(GameData.DragDropItem), new DataTemplate(typeof(GameData.DragDropItem), r_4_dtFunc));
// Resource - [DataTemplateKey(GameData.TestTreeDataItem)] DataTemplate
Func<UIElement, UIElement> r_5_dtFunc = r_5_dtMethod;
this.Add(typeof(GameData.TestTreeDataItem), new DataTemplate(typeof(GameData.TestTreeDataItem), r_5_dtFunc));
// Resource - [Image] BitmapImage
BitmapImage r_6_bm = new BitmapImage();
r_6_bm.TextureAsset = "Images/MonoGameLogo";
this.Add("Image", r_6_bm);
// Resource - [Sounds] SoundSourceCollection
var r_7_sounds = new SoundSourceCollection();
SoundManager.Instance.AddSound("Click");
r_7_sounds.Add(new SoundSource { SoundType = SoundType.ButtonsClick, SoundAsset = "Click", Volume = 1f });
SoundManager.Instance.AddSound("KeyPress");
r_7_sounds.Add(new SoundSource { SoundType = SoundType.TextBoxKeyPress, SoundAsset = "KeyPress", Volume = 1f });
SoundManager.Instance.AddSound("Move");
r_7_sounds.Add(new SoundSource { SoundType = SoundType.TabControlMove, SoundAsset = "Move", Volume = 1f });
SoundManager.Instance.AddSound("Select");
r_7_sounds.Add(new SoundSource { SoundType = SoundType.TabControlSelect, SoundAsset = "Select", Volume = 1f });
this.Add("Sounds", r_7_sounds);
// Resource - [TetrisBorderBrush] SolidColorBrush
this.Add("TetrisBorderBrush", new SolidColorBrush(new ColorW(114, 176, 218, 255)));
// Resource - [TetrisBorderStyle] Style
Style r_9_s = new Style(typeof(Border));
Setter r_9_s_S_0 = new Setter(Border.SnapsToDevicePixelsProperty, true);
r_9_s.Setters.Add(r_9_s_S_0);
Setter r_9_s_S_1 = new Setter(Border.BackgroundProperty, new ResourceReferenceExpression("TetrisWindowBackground"));
r_9_s.Setters.Add(r_9_s_S_1);
Setter r_9_s_S_2 = new Setter(Border.BorderBrushProperty, new ResourceReferenceExpression("TetrisBorderBrush"));
r_9_s.Setters.Add(r_9_s_S_2);
Setter r_9_s_S_3 = new Setter(Border.BorderThicknessProperty, new Thickness(1F));
r_9_s.Setters.Add(r_9_s_S_3);
Setter r_9_s_S_4 = new Setter(Border.OpacityProperty, 0.9F);
r_9_s.Setters.Add(r_9_s_S_4);
this.Add("TetrisBorderStyle", r_9_s);
// Resource - [TetrisForeground] SolidColorBrush
this.Add("TetrisForeground", new SolidColorBrush(new ColorW(255, 255, 255, 255)));
// Resource - [TetrisWindowBackground] SolidColorBrush
this.Add("TetrisWindowBackground", new SolidColorBrush(new ColorW(0, 0, 0, 255)));
// Resource - [TitleResource] String
this.Add("TitleResource", "Basic UI Example");
ImageManager.Instance.AddImage("Images/MonoGameLogo");
GeneratedPropertyInfo.RegisterGeneratedProperty(typeof(GameData.CustomWindow), "TextData", typeof(EmptyKeys.UserInterface.Generated.Dictionary_Bindings.CustomWindow_TextData_PropertyInfo));
GeneratedPropertyInfo.RegisterGeneratedProperty(typeof(GameData.CustomWindow), "HideCommand", typeof(EmptyKeys.UserInterface.Generated.Dictionary_Bindings.CustomWindow_HideCommand_PropertyInfo));
GeneratedPropertyInfo.RegisterGeneratedProperty(typeof(GameData.DragDropItem), "Name", typeof(EmptyKeys.UserInterface.Generated.Dictionary_Bindings.DragDropItem_Name_PropertyInfo));
GeneratedPropertyInfo.RegisterGeneratedProperty(typeof(GameData.TestTreeDataItem), "Name", typeof(EmptyKeys.UserInterface.Generated.Dictionary_Bindings.TestTreeDataItem_Name_PropertyInfo));
}
private static UIElement r_2_ctMethod(UIElement parent) {
// e_0 element
Grid e_0 = new Grid();
e_0.Parent = parent;
e_0.Name = "e_0";
RowDefinition row_e_0_0 = new RowDefinition();
row_e_0_0.Height = new GridLength(20F, GridUnitType.Pixel);
e_0.RowDefinitions.Add(row_e_0_0);
RowDefinition row_e_0_1 = new RowDefinition();
e_0.RowDefinitions.Add(row_e_0_1);
// PART_WindowTitleBorder element
Border PART_WindowTitleBorder = new Border();
e_0.Children.Add(PART_WindowTitleBorder);
PART_WindowTitleBorder.Name = "PART_WindowTitleBorder";
PART_WindowTitleBorder.Background = new SolidColorBrush(new ColorW(255, 255, 255, 255));
// e_1 element
ContentPresenter e_1 = new ContentPresenter();
e_0.Children.Add(e_1);
e_1.Name = "e_1";
Grid.SetRow(e_1, 1);
Binding binding_e_1_Content = new Binding();
e_1.SetBinding(ContentPresenter.ContentProperty, binding_e_1_Content);
return e_0;
}
private static UIElement r_3_dtMethod(UIElement parent) {
// e_2 element
Border e_2 = new Border();
e_2.Parent = parent;
e_2.Name = "e_2";
e_2.Background = new SolidColorBrush(new ColorW(0, 0, 255, 255));
e_2.BorderBrush = new SolidColorBrush(new ColorW(128, 128, 128, 255));
e_2.BorderThickness = new Thickness(2F, 2F, 2F, 2F);
// e_3 element
StackPanel e_3 = new StackPanel();
e_2.Child = e_3;
e_3.Name = "e_3";
// e_4 element
TextBlock e_4 = new TextBlock();
e_3.Children.Add(e_4);
e_4.Name = "e_4";
e_4.HorizontalAlignment = HorizontalAlignment.Center;
e_4.VerticalAlignment = VerticalAlignment.Center;
Binding binding_e_4_Text = new Binding("TextData");
binding_e_4_Text.UseGeneratedBindings = true;
e_4.SetBinding(TextBlock.TextProperty, binding_e_4_Text);
// e_5 element
TextBlock e_5 = new TextBlock();
e_3.Children.Add(e_5);
e_5.Name = "e_5";
e_5.HorizontalAlignment = HorizontalAlignment.Center;
e_5.VerticalAlignment = VerticalAlignment.Center;
Binding binding_e_5_Text = new Binding("ManualBinding");
binding_e_5_Text.UseGeneratedBindings = true;
e_5.SetBinding(TextBlock.TextProperty, binding_e_5_Text);
// e_6 element
Button e_6 = new Button();
e_3.Children.Add(e_6);
e_6.Name = "e_6";
e_6.Content = "Hide Window ddddddddddddddddddddddddddddddddddddddddddddddd";
Binding binding_e_6_Command = new Binding("HideCommand");
binding_e_6_Command.UseGeneratedBindings = true;
e_6.SetBinding(Button.CommandProperty, binding_e_6_Command);
// PART_WindowResizeBorder element
Border PART_WindowResizeBorder = new Border();
e_3.Children.Add(PART_WindowResizeBorder);
PART_WindowResizeBorder.Name = "PART_WindowResizeBorder";
PART_WindowResizeBorder.Height = 15F;
PART_WindowResizeBorder.Width = 100F;
PART_WindowResizeBorder.Background = new SolidColorBrush(new ColorW(0, 128, 0, 255));
return e_2;
}
private static UIElement r_4_dtMethod(UIElement parent) {
// e_7 element
TextBlock e_7 = new TextBlock();
e_7.Parent = parent;
e_7.Name = "e_7";
e_7.Margin = new Thickness(5F, 5F, 5F, 5F);
Binding binding_e_7_Text = new Binding("Name");
binding_e_7_Text.UseGeneratedBindings = true;
e_7.SetBinding(TextBlock.TextProperty, binding_e_7_Text);
return e_7;
}
private static UIElement r_5_dtMethod(UIElement parent) {
// e_8 element
TextBlock e_8 = new TextBlock();
e_8.Parent = parent;
e_8.Name = "e_8";
e_8.Margin = new Thickness(2F, 2F, 2F, 2F);
Binding binding_e_8_Text = new Binding("Name");
binding_e_8_Text.UseGeneratedBindings = true;
e_8.SetBinding(TextBlock.TextProperty, binding_e_8_Text);
return e_8;
}
}
}
| |
// 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 osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Framework.Platform;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Models;
using osu.Game.Tournament.Screens.Ladder.Components;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tournament.Screens.TeamIntro
{
public class SeedingScreen : TournamentScreen, IProvideVideo
{
private Container mainContainer;
private readonly Bindable<TournamentMatch> currentMatch = new Bindable<TournamentMatch>();
private readonly Bindable<TournamentTeam> currentTeam = new Bindable<TournamentTeam>();
[BackgroundDependencyLoader]
private void load(Storage storage)
{
RelativeSizeAxes = Axes.Both;
InternalChildren = new Drawable[]
{
new TourneyVideo("seeding")
{
RelativeSizeAxes = Axes.Both,
Loop = true,
},
mainContainer = new Container
{
RelativeSizeAxes = Axes.Both,
},
new ControlPanel
{
Children = new Drawable[]
{
new TourneyButton
{
RelativeSizeAxes = Axes.X,
Text = "Show first team",
Action = () => currentTeam.Value = currentMatch.Value.Team1.Value,
},
new TourneyButton
{
RelativeSizeAxes = Axes.X,
Text = "Show second team",
Action = () => currentTeam.Value = currentMatch.Value.Team2.Value,
},
new SettingsTeamDropdown(LadderInfo.Teams)
{
LabelText = "Show specific team",
Bindable = currentTeam,
}
}
}
};
currentMatch.BindValueChanged(matchChanged);
currentMatch.BindTo(LadderInfo.CurrentMatch);
currentTeam.BindValueChanged(teamChanged, true);
}
private void teamChanged(ValueChangedEvent<TournamentTeam> team)
{
if (team.NewValue == null)
{
mainContainer.Clear();
return;
}
showTeam(team.NewValue);
}
private void matchChanged(ValueChangedEvent<TournamentMatch> match) =>
currentTeam.Value = currentMatch.Value.Team1.Value;
private void showTeam(TournamentTeam team)
{
mainContainer.Children = new Drawable[]
{
new LeftInfo(team) { Position = new Vector2(55, 150), },
new RightInfo(team) { Position = new Vector2(500, 150), },
};
}
private class RightInfo : CompositeDrawable
{
public RightInfo(TournamentTeam team)
{
FillFlowContainer fill;
Width = 400;
InternalChildren = new Drawable[]
{
fill = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
},
};
foreach (var seeding in team.SeedingResults)
{
fill.Add(new ModRow(seeding.Mod.Value, seeding.Seed.Value));
foreach (var beatmap in seeding.Beatmaps)
fill.Add(new BeatmapScoreRow(beatmap));
}
}
private class BeatmapScoreRow : CompositeDrawable
{
public BeatmapScoreRow(SeedingBeatmap beatmap)
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
InternalChildren = new Drawable[]
{
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(5),
Children = new Drawable[]
{
new TournamentSpriteText { Text = beatmap.BeatmapInfo.Metadata.Title, Colour = Color4.Black, },
new TournamentSpriteText { Text = "by", Colour = Color4.Black, Font = OsuFont.Torus.With(weight: FontWeight.Regular) },
new TournamentSpriteText { Text = beatmap.BeatmapInfo.Metadata.Artist, Colour = Color4.Black, Font = OsuFont.Torus.With(weight: FontWeight.Regular) },
}
},
new FillFlowContainer
{
AutoSizeAxes = Axes.Y,
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(40),
Children = new Drawable[]
{
new TournamentSpriteText { Text = beatmap.Score.ToString("#,0"), Colour = Color4.Black, Width = 80 },
new TournamentSpriteText { Text = "#" + beatmap.Seed.Value.ToString("#,0"), Colour = Color4.Black, Font = OsuFont.Torus.With(weight: FontWeight.Regular) },
}
},
};
}
}
private class ModRow : CompositeDrawable
{
private readonly string mods;
private readonly int seeding;
public ModRow(string mods, int seeding)
{
this.mods = mods;
this.seeding = seeding;
Padding = new MarginPadding { Vertical = 10 };
AutoSizeAxes = Axes.Y;
}
[BackgroundDependencyLoader]
private void load(TextureStore textures)
{
InternalChildren = new Drawable[]
{
new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(5),
Children = new Drawable[]
{
new Sprite
{
Texture = textures.Get($"mods/{mods.ToLower()}"),
Scale = new Vector2(0.5f)
},
new Container
{
Size = new Vector2(50, 16),
CornerRadius = 10,
Masking = true,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black,
},
new TournamentSpriteText
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Text = seeding.ToString("#,0"),
},
}
},
}
},
};
}
}
}
private class LeftInfo : CompositeDrawable
{
public LeftInfo(TournamentTeam team)
{
FillFlowContainer fill;
Width = 200;
if (team == null) return;
InternalChildren = new Drawable[]
{
fill = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new TeamDisplay(team) { Margin = new MarginPadding { Bottom = 30 } },
new RowDisplay("Average Rank:", $"#{team.AverageRank:#,0}"),
new RowDisplay("Seed:", team.Seed.Value),
new RowDisplay("Last year's placing:", team.LastYearPlacing.Value > 0 ? $"#{team.LastYearPlacing:#,0}" : "0"),
new Container { Margin = new MarginPadding { Bottom = 30 } },
}
},
};
foreach (var p in team.Players)
fill.Add(new RowDisplay(p.Username, p.Statistics?.Ranks.Global?.ToString("\\##,0") ?? "-"));
}
internal class RowDisplay : CompositeDrawable
{
public RowDisplay(string left, string right)
{
AutoSizeAxes = Axes.Y;
RelativeSizeAxes = Axes.X;
var colour = OsuColour.Gray(0.3f);
InternalChildren = new Drawable[]
{
new TournamentSpriteText
{
Text = left,
Colour = colour,
Font = OsuFont.Torus.With(size: 22),
},
new TournamentSpriteText
{
Text = right,
Colour = colour,
Anchor = Anchor.TopRight,
Origin = Anchor.TopLeft,
Font = OsuFont.Torus.With(size: 22, weight: FontWeight.Regular),
},
};
}
}
private class TeamDisplay : DrawableTournamentTeam
{
public TeamDisplay(TournamentTeam team)
: base(team)
{
AutoSizeAxes = Axes.Both;
Flag.RelativeSizeAxes = Axes.None;
Flag.Size = new Vector2(300, 200);
Flag.Scale = new Vector2(0.3f);
InternalChild = new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 5),
Children = new Drawable[]
{
Flag,
new OsuSpriteText
{
Text = team?.FullName.Value ?? "???",
Font = OsuFont.Torus.With(size: 32, weight: FontWeight.SemiBold),
Colour = Color4.Black,
},
}
};
}
}
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
namespace Microsoft.CodeAnalysis.MSBuild
{
internal sealed partial class SolutionFile
{
private readonly IEnumerable<string> headerLines;
private readonly string visualStudioVersionLineOpt;
private readonly string minimumVisualStudioVersionLineOpt;
private readonly IEnumerable<ProjectBlock> projectBlocks;
private readonly IEnumerable<SectionBlock> globalSectionBlocks;
public SolutionFile(
IEnumerable<string> headerLines,
string visualStudioVersionLineOpt,
string minimumVisualStudioVersionLineOpt,
IEnumerable<ProjectBlock> projectBlocks,
IEnumerable<SectionBlock> globalSectionBlocks)
{
if (headerLines == null)
{
//throw new ArgumentNullException("headerLines");
throw new ArgumentException();
}
if (projectBlocks == null)
{
//throw new ArgumentNullException("projectBlocks");
throw new ArgumentException();
}
if (globalSectionBlocks == null)
{
//throw new ArgumentNullException("globalSectionBlocks");
throw new ArgumentException();
}
this.headerLines = headerLines.ToList();
this.visualStudioVersionLineOpt = visualStudioVersionLineOpt;
this.minimumVisualStudioVersionLineOpt = minimumVisualStudioVersionLineOpt;
this.projectBlocks = projectBlocks.ToList();
this.globalSectionBlocks = globalSectionBlocks.ToList();
}
public IEnumerable<string> HeaderLines
{
get { return headerLines; }
}
public string VisualStudioVersionLineOpt
{
get { return visualStudioVersionLineOpt; }
}
public string MinimumVisualStudioVersionLineOpt
{
get { return minimumVisualStudioVersionLineOpt; }
}
public IEnumerable<ProjectBlock> ProjectBlocks
{
get { return projectBlocks; }
}
public IEnumerable<SectionBlock> GlobalSectionBlocks
{
get { return globalSectionBlocks; }
}
public string GetText()
{
var builder = new StringBuilder();
builder.AppendLine();
foreach (var headerLine in headerLines)
{
builder.AppendLine(headerLine);
}
foreach (var block in projectBlocks)
{
builder.Append(block.GetText());
}
builder.AppendLine("Global");
foreach (var block in globalSectionBlocks)
{
builder.Append(block.GetText(indent: 1));
}
builder.AppendLine("EndGlobal");
return builder.ToString();
}
public static SolutionFile Parse(TextReader reader)
{
var headerLines = new List<string>();
var headerLine1 = GetNextNonEmptyLine(reader);
if (headerLine1 == null || !headerLine1.StartsWith("Microsoft Visual Studio Solution File"))
{
//throw new Exception(string.Format(WorkspacesResources.MissingHeaderInSolutionFile, "Microsoft Visual Studio Solution File"));
throw new Exception();
}
headerLines.Add(headerLine1);
// skip comment lines and empty lines
while (reader.Peek() != -1 && "#\r\n".Contains((char)reader.Peek()))
{
headerLines.Add(reader.ReadLine());
}
string visualStudioVersionLineOpt = null;
if (reader.Peek() == 'V')
{
visualStudioVersionLineOpt = GetNextNonEmptyLine(reader);
if (!visualStudioVersionLineOpt.StartsWith("VisualStudioVersion"))
{
//throw new Exception(string.Format(WorkspacesResources.MissingHeaderInSolutionFile, "VisualStudioVersion"));
throw new Exception();
}
}
string minimumVisualStudioVersionLineOpt = null;
if (reader.Peek() == 'M')
{
minimumVisualStudioVersionLineOpt = GetNextNonEmptyLine(reader);
if (!minimumVisualStudioVersionLineOpt.StartsWith("MinimumVisualStudioVersion"))
{
//throw new Exception(string.Format(WorkspacesResources.MissingHeaderInSolutionFile, "MinimumVisualStudioVersion"));
throw new Exception();
}
}
var projectBlocks = new List<ProjectBlock>();
// Parse project blocks while we have them
while (reader.Peek() == 'P')
{
projectBlocks.Add(ProjectBlock.Parse(reader));
while (reader.Peek() != -1 && "#\r\n".Contains((char)reader.Peek()))
{
// Comments and Empty Lines between the Project Blocks are skipped
reader.ReadLine();
}
}
// We now have a global block
var globalSectionBlocks = ParseGlobal(reader);
// We should now be at the end of the file
if (reader.Peek() != -1)
{
//throw new Exception(WorkspacesResources.MissingEndOfFileInSolutionFile);
throw new Exception();
}
return new SolutionFile(headerLines, visualStudioVersionLineOpt, minimumVisualStudioVersionLineOpt, projectBlocks, globalSectionBlocks);
}
[SuppressMessage("", "RS0001")] // TODO: This suppression should be removed once we have rulesets in place for Roslyn.sln
private static IEnumerable<SectionBlock> ParseGlobal(TextReader reader)
{
if (reader.Peek() == -1)
{
return Enumerable.Empty<SectionBlock>();
}
if (GetNextNonEmptyLine(reader) != "Global")
{
//throw new Exception(string.Format(WorkspacesResources.MissingLineInSolutionFile, "Global"));
throw new Exception();
}
var globalSectionBlocks = new List<SectionBlock>();
// The blocks inside here are indented
while (reader.Peek() != -1 && char.IsWhiteSpace((char)reader.Peek()))
{
globalSectionBlocks.Add(SectionBlock.Parse(reader));
}
if (GetNextNonEmptyLine(reader) != "EndGlobal")
{
//throw new Exception(string.Format(WorkspacesResources.MissingLineInSolutionFile, "EndGlobal"));
throw new Exception();
}
// Consume potential empty lines at the end of the global block
while (reader.Peek() != -1 && "\r\n".Contains((char)reader.Peek()))
{
reader.ReadLine();
}
return globalSectionBlocks;
}
private static string GetNextNonEmptyLine(TextReader reader)
{
string line = null;
do
{
line = reader.ReadLine();
}
while (line != null && line.Trim() == string.Empty);
return line;
}
}
}
| |
// 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;
/// <summary>
/// System.MathF.Sign(System.Single)
/// </summary>
public class MathFSign
{
public static int Main(string[] args)
{
MathFSign test = new MathFSign();
TestLibrary.TestFramework.BeginTestCase("Testing System.MathF.Sign(System.Single).");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
TestLibrary.TestFramework.LogInformation("[Negtive]");
retVal = NegTest1() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify float.MaxValue is a positive number.");
try
{
float s = float.MaxValue;
if (MathF.Sign(s) != 1)
{
TestLibrary.TestFramework.LogError("P01.1", "float.MaxValue is not a positive number!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P01.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify float.MinValue is a negative number.");
try
{
float s = float.MinValue;
if (MathF.Sign(s) != -1)
{
TestLibrary.TestFramework.LogError("P02.1", "float.MinValue is not a negative number!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P02.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify float.PositiveInfinity is a positive number.");
try
{
float s = float.PositiveInfinity;
if (MathF.Sign(s) != 1)
{
TestLibrary.TestFramework.LogError("P03.1", "float.PositiveInfinity is not a positive number!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P03.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify float.NegativeInfinity is a negative number.");
try
{
float s = float.NegativeInfinity;
if (MathF.Sign(s) != -1)
{
TestLibrary.TestFramework.LogError("P04.1", "float.NegativeInfinity is not a negative number!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P04.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Verify float.Epsilon is a positive number.");
try
{
float s = float.Epsilon;
if (MathF.Sign(s) != 1)
{
TestLibrary.TestFramework.LogError("P05.1", "float.Epsilon is not a positive number!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P05.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest6: Verify the return value should be 1 when the float is positive.");
try
{
float s = TestLibrary.Generator.GetSingle(-55);
while (s <= 0)
{
s = TestLibrary.Generator.GetSingle(-55);
}
if (MathF.Sign(s) != 1)
{
TestLibrary.TestFramework.LogError("P06.1", "The return value is not 1 when the float is positive!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P06.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest7: Verify the return value should be -1 when the float is negative.");
try
{
float s = TestLibrary.Generator.GetSingle(-55);
while (s <= 0)
{
s = TestLibrary.Generator.GetSingle(-55);
}
if (MathF.Sign(-s) != -1)
{
TestLibrary.TestFramework.LogError("P07.1", "The return value is not -1 when the float is negative!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P07.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest8: Verify the return value should be 0 when the float is zero.");
try
{
float s = 0.0f;
if (MathF.Sign(s) != 0)
{
TestLibrary.TestFramework.LogError("P08.1", "The return value is not -1 when the float is negative!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P08.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: ArithmeticException should be thrown when value is equal to NaN.");
try
{
float s = float.NaN;
MathF.Sign(s);
TestLibrary.TestFramework.LogError("N01.1", "ArithmeticException is not thrown when value is equal to NaN!");
retVal = false;
}
catch (ArithmeticException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N01.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.EnterpriseServices;
using System.Reflection;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
using System.Xml;
using SR = System.ServiceModel.SR;
class ComPlusTypeLoader : IContractResolver
{
ServiceInfo info;
bool transactionFlow;
ITypeCacheManager interfaceResolver;
Dictionary<Guid, ContractDescription> contracts;
public ComPlusTypeLoader(ServiceInfo info)
{
this.info = info;
this.transactionFlow = info.TransactionOption == TransactionOption.Required ||
info.TransactionOption == TransactionOption.Supported;
this.interfaceResolver = new TypeCacheManager();
this.contracts = new Dictionary<Guid, ContractDescription>();
}
void ValidateInterface(Guid iid)
{
// Filter known invalid IIDs
if (!ComPlusTypeValidator.IsValidInterface(iid))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.InvalidWebServiceInterface, iid)));
}
// Filter out interfaces with no configured methods
bool configuredInterface = false;
foreach (ContractInfo contractInfo in this.info.Contracts)
{
if (contractInfo.IID == iid)
{
if (contractInfo.Operations.Count == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.RequireConfiguredMethods, iid)));
}
configuredInterface = true;
break;
}
}
// Filter out interfaces that aren't configured at all
if (!configuredInterface)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.RequireConfiguredInterfaces, iid)));
}
}
ContractDescription CreateContractDescriptionInternal(Guid iid, Type type)
{
ComContractElement contractConfigElement = ConfigLoader.LookupComContract(iid);
if (contractConfigElement == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.InterfaceNotFoundInConfig, iid)));
if (String.IsNullOrEmpty(contractConfigElement.Name) || String.IsNullOrEmpty(contractConfigElement.Namespace))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.CannotHaveNullOrEmptyNameOrNamespaceForIID, iid)));
ContractDescription contract = new ContractDescription(contractConfigElement.Name, contractConfigElement.Namespace);
contract.ContractType = type;
contract.SessionMode = contractConfigElement.RequiresSession ? SessionMode.Required : SessionMode.Allowed;
bool methodFound = false;
List<Guid> guidList = new List<Guid>();
foreach (ComPersistableTypeElement typeElement in contractConfigElement.PersistableTypes)
{
Guid typeGuid = Fx.CreateGuid(typeElement.ID);
guidList.Add(typeGuid);
}
IDataContractSurrogate contractSurrogate = null;
// We create a surrogate when the persistable types config section is there
// even if we have no types that we allow.
// That way we have control over the error when the client tries to make a call
// persistable type.
if (guidList.Count > 0 || contractConfigElement.PersistableTypes.EmitClear)
{
contractSurrogate = new DataContractSurrogateForPersistWrapper(guidList.ToArray());
}
foreach (ComMethodElement configMethod in contractConfigElement.ExposedMethods)
{
methodFound = false;
foreach (MethodInfo method in type.GetMethods())
{
if (method.Name == configMethod.ExposedMethod)
{
OperationDescription operation = CreateOperationDescription(contract, method, contractConfigElement, (null != contractSurrogate));
ConfigureOperationDescriptionBehaviors(operation, contractSurrogate);
contract.Operations.Add(operation);
methodFound = true;
break;
}
}
if (!methodFound)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.MethodGivenInConfigNotFoundOnInterface, configMethod.ExposedMethod, iid)));
}
if (contract.Operations.Count == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.NoneOfTheMethodsForInterfaceFoundInConfig, iid)));
ConfigureContractDescriptionBehaviors(contract);
return contract;
}
void ConfigureContractDescriptionBehaviors(ContractDescription contract)
{
// OperationSelectorBehavior
contract.Behaviors.Add(new OperationSelectorBehavior());
// ComPlusContractBehavior
ComPlusContractBehavior comPlusContractBehavior = new ComPlusContractBehavior(this.info);
contract.Behaviors.Add(comPlusContractBehavior);
}
void ConfigureOperationDescriptionBehaviors(OperationDescription operation, IDataContractSurrogate contractSurrogate)
{
// DataContractSerializerOperationBehavior
DataContractSerializerOperationBehavior contractSerializer = new DataContractSerializerOperationBehavior(operation, TypeLoader.DefaultDataContractFormatAttribute);
if (null != contractSurrogate)
{
contractSerializer.DataContractSurrogate = contractSurrogate;
}
operation.Behaviors.Add(contractSerializer);
// OperationInvokerBehavior
operation.Behaviors.Add(new OperationInvokerBehavior());
if (info.TransactionOption == TransactionOption.Supported || info.TransactionOption == TransactionOption.Required)
{
operation.Behaviors.Add(new TransactionFlowAttribute(TransactionFlowOption.Allowed));
}
// OperationBehaviorAttribute
OperationBehaviorAttribute operationBehaviorAttribute = new OperationBehaviorAttribute();
operationBehaviorAttribute.TransactionAutoComplete = true;
operationBehaviorAttribute.TransactionScopeRequired = false;
operation.Behaviors.Add(operationBehaviorAttribute);
}
//
// Note - the code below this line a paraphrase of the SM reflection code in TypeLoader.cs
// Ideally we would be re-using their code, but our assumptions are too disjoint
// for that to be realistic at the time of writing (12/2004).
//
OperationDescription CreateOperationDescription(ContractDescription contract, MethodInfo methodInfo, ComContractElement config, bool allowReferences)
{
XmlName operationName = new XmlName(ServiceReflector.GetLogicalName(methodInfo));
XmlName returnValueName = TypeLoader.GetReturnValueName(operationName);
if (ServiceReflector.IsBegin(methodInfo) || ServiceReflector.IsTask(methodInfo))
{
Fx.Assert("No async operations allowed");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.NoAsyncOperationsAllowed());
}
if (contract.Operations.FindAll(operationName.EncodedName).Count != 0)
{
Fx.Assert("Duplicate operation name");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.DuplicateOperation());
}
OperationDescription operationDescription = new OperationDescription(operationName.EncodedName, contract);
operationDescription.SyncMethod = methodInfo;
operationDescription.IsInitiating = true;
operationDescription.IsTerminating = false;
operationDescription.KnownTypes.Add(typeof(Array));
operationDescription.KnownTypes.Add(typeof(DBNull));
operationDescription.KnownTypes.Add(typeof(CurrencyWrapper));
operationDescription.KnownTypes.Add(typeof(ErrorWrapper));
if (allowReferences)
operationDescription.KnownTypes.Add(typeof(PersistStreamTypeWrapper));
foreach (ComUdtElement udt in config.UserDefinedTypes)
{
Type knownType;
Guid typeLibID = Fx.CreateGuid(udt.TypeLibID);
TypeCacheManager.Provider.FindOrCreateType(typeLibID, udt.TypeLibVersion, Fx.CreateGuid(udt.TypeDefID), out knownType, false);
this.info.AddUdt(knownType, typeLibID);
operationDescription.KnownTypes.Add(knownType);
}
string ns = contract.Namespace;
XmlQualifiedName contractQName = new XmlQualifiedName(contract.Name, ns);
string requestAction = NamingHelper.GetMessageAction(contractQName,
operationName.DecodedName,
null,
false);
string responseAction = NamingHelper.GetMessageAction(contractQName,
operationName.DecodedName,
null,
true);
MessageDescription inMessage = CreateIncomingMessageDescription(contract,
methodInfo,
ns,
requestAction,
allowReferences);
MessageDescription outMessage = CreateOutgoingMessageDescription(contract,
methodInfo,
returnValueName,
ns,
responseAction,
allowReferences);
operationDescription.Messages.Add(inMessage);
operationDescription.Messages.Add(outMessage);
return operationDescription;
}
MessageDescription CreateIncomingMessageDescription(ContractDescription contract,
MethodInfo methodInfo,
string ns,
string action,
bool allowReferences)
{
ParameterInfo[] parameters = ServiceReflector.GetInputParameters(methodInfo, false);
return CreateParameterMessageDescription(contract,
parameters,
null,
null,
null,
methodInfo.Name,
ns,
action,
MessageDirection.Input,
allowReferences);
}
MessageDescription CreateOutgoingMessageDescription(ContractDescription contract,
MethodInfo methodInfo,
XmlName returnValueName,
string ns,
string action,
bool allowReferences)
{
ParameterInfo[] parameters = ServiceReflector.GetOutputParameters(methodInfo, false);
return CreateParameterMessageDescription(contract,
parameters,
methodInfo.ReturnType,
methodInfo.ReturnTypeCustomAttributes,
returnValueName,
methodInfo.Name,
ns,
action,
MessageDirection.Output,
allowReferences);
}
MessageDescription CreateParameterMessageDescription(ContractDescription contract,
ParameterInfo[] parameters,
Type returnType,
ICustomAttributeProvider returnCustomAttributes,
XmlName returnValueName,
string methodName,
string ns,
string action,
MessageDirection direction,
bool allowReferences)
{
MessageDescription messageDescription = new MessageDescription(action, direction);
messageDescription.Body.WrapperNamespace = ns;
for (int index = 0; index < parameters.Length; index++)
{
ParameterInfo parameter = parameters[index];
Type parameterType = TypeLoader.GetParameterType(parameter);
if (!ComPlusTypeValidator.IsValidParameter(parameterType, parameter, allowReferences))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.InvalidWebServiceParameter,
parameter.Name,
parameterType.Name,
methodName,
contract.Name)));
}
MessagePartDescription messagePart = CreateMessagePartDescription(parameterType,
new XmlName(parameter.Name),
ns,
index);
messageDescription.Body.Parts.Add(messagePart);
}
XmlName xmlName = new XmlName(methodName);
if (returnType == null)
{
messageDescription.Body.WrapperName = xmlName.EncodedName;
}
else
{
messageDescription.Body.WrapperName = TypeLoader.GetBodyWrapperResponseName(xmlName).EncodedName;
if (!ComPlusTypeValidator.IsValidParameter(returnType, returnCustomAttributes, allowReferences))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.InvalidWebServiceReturnValue,
returnType.Name,
methodName,
contract.Name)));
}
MessagePartDescription messagePart = CreateMessagePartDescription(returnType,
returnValueName,
ns,
0);
messageDescription.Body.ReturnValue = messagePart;
}
return messageDescription;
}
MessagePartDescription CreateMessagePartDescription(Type bodyType,
XmlName name,
string ns,
int index)
{
MessagePartDescription partDescription = new MessagePartDescription(name.EncodedName, ns);
partDescription.SerializationPosition = index;
partDescription.MemberInfo = null;
partDescription.Type = bodyType;
partDescription.Index = index;
return partDescription;
}
ContractDescription ResolveIMetadataExchangeToContract()
{
// Use ServiceModel's TypeLoader to load the IMetadataExchange contract
TypeLoader typeLoader = new TypeLoader();
return typeLoader.LoadContractDescription(typeof(IMetadataExchange));
}
public ContractDescription ResolveContract(string contractTypeString)
{
Guid iid;
if (ServiceMetadataBehavior.MexContractName == contractTypeString)
iid = typeof(IMetadataExchange).GUID;
else
{
if (!DiagnosticUtility.Utility.TryCreateGuid(contractTypeString, out iid))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.ContractTypeNotAnIID, contractTypeString)));
}
ValidateInterface(iid);
}
// Check our cache to see if we already have one
ContractDescription contract;
if (this.contracts.TryGetValue(iid, out contract))
{
return contract;
}
// If this is not IMetadataExchange continue
if (iid != typeof(IMetadataExchange).GUID)
{
Type type;
// Generate a managed type corresponding to the interface in question
try
{
this.interfaceResolver.FindOrCreateType(this.info.ServiceType, iid, out type, false, true);
}
catch (InvalidOperationException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(e.Message));
}
contract = CreateContractDescriptionInternal(iid, type);
}
else
contract = ResolveIMetadataExchangeToContract();
contracts.Add(iid, contract);
ComPlusServiceHostTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationServiceHostCreatedServiceContract,
SR.TraceCodeComIntegrationServiceHostCreatedServiceContract, this.info, contract);
return contract;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="SourceSafe.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
//-----------------------------------------------------------------------
namespace MSBuild.ExtensionPack.VisualStudio
{
using System;
using System.Globalization;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Win32;
/// <summary>
/// Please be aware that this is a very light wrapper for ss.exe<para/>
/// See the Command Line Reference on MSDN (http://msdn.microsoft.com/en-us/library/003ssz4z(VS.80).aspx) for full details.
/// <para/>
/// <b>Sample TaskActions are as follows, HOWEVER use the URL above for full guidance and additional TaskActions:</b>
/// <para><i>Checkout</i> (<b>Required: </b> FilePath <b>Optional: </b>Arguments, Database, SSVersion, SuppressI)</para>
/// <para><i>Checkin</i> (<b>Required: </b> FilePath <b>Optional: </b>Arguments, Database, SSVersion, SuppressI)</para>
/// <para><i>Cloak</i> (<b>Required: </b> FilePath <b>Optional: </b>Arguments, Database, SSVersion, SuppressI)</para>
/// <para><i>Create</i> (<b>Required: </b> FilePath <b>Optional: </b>Arguments, Database, SSVersion, SuppressI)</para>
/// <para><i>Decloak</i> (<b>Required: </b> FilePath <b>Optional: </b>Arguments, Database, SSVersion, SuppressI)</para>
/// <para><i>Delete</i> (<b>Required: </b> FilePath <b>Optional: </b>Arguments, Database, SSVersion, SuppressI)</para>
/// <para><i>Destroy</i> (<b>Required: </b> FilePath <b>Optional: </b>Arguments, SSVersion, SuppressI)</para>
/// <para><i>Get</i> (<b>Required: </b> FilePath <b>Optional: </b>Arguments, Database, SSVersion, SuppressI)</para>
/// <para><b>Remote Execution Support:</b> No</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="3.5" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <Target Name="Default">
/// <!-- Perfrom various source control operations -->
/// <MSBuild.ExtensionPack.VisualStudio.SourceSafe TaskAction="Get" Database="C:\SourceSafe\2005" UserName="AUser" FilePath="$//DemoFtd" Arguments="-GLC:\Demo2 -R"/>
/// <!-- This will perform a recursive checkout to C:\Demo2 -->
/// <MSBuild.ExtensionPack.VisualStudio.SourceSafe TaskAction="Checkout" Database="C:\SourceSafe" UserName="AUser" FilePath="$//DemoFtd/*.*" Arguments="-GLC:\Demo2 -R" ContinueOnError="true"/>
/// <MSBuild.ExtensionPack.VisualStudio.SourceSafe TaskAction="Checkin" Database="C:\SourceSafe\2005" UserName="AUser" FilePath="$//DemoFtd/*.*" ContinueOnError="true"/>
/// <MSBuild.ExtensionPack.VisualStudio.SourceSafe TaskAction="Checkout" Database="C:\SourceSafe\2005" UserName="AUser" FilePath="$//DemoFtd/dts.wav" ContinueOnError="true"/>
/// <MSBuild.ExtensionPack.VisualStudio.SourceSafe TaskAction="Checkin" Database="C:\SourceSafe\2005" UserName="AUser" FilePath="$//DemoFtd/dts.wav" ContinueOnError="true"/>
/// <MSBuild.ExtensionPack.VisualStudio.SourceSafe TaskAction="Cloak" Database="C:\SourceSafe\2005" UserName="AUser" FilePath="$//DemoFtd" ContinueOnError="true"/>
/// <MSBuild.ExtensionPack.VisualStudio.SourceSafe TaskAction="Decloak" Database="C:\SourceSafe\2005" UserName="AUser" FilePath="$//DemoFtd" ContinueOnError="true"/>
/// <MSBuild.ExtensionPack.VisualStudio.SourceSafe TaskAction="Create" Database="C:\SourceSafe\2005" UserName="AUser" FilePath="$//DemoFtd22" ContinueOnError="true"/>
/// <MSBuild.ExtensionPack.VisualStudio.SourceSafe TaskAction="Delete" Database="C:\SourceSafe\2005" UserName="AUser" FilePath="$//DemoFtd22" Arguments="-I-Y" ContinueOnError="true"/>
/// <MSBuild.ExtensionPack.VisualStudio.SourceSafe TaskAction="Destroy" Database="C:\SourceSafe\2005" UserName="AUser" FilePath="$//DemoFtd22" Arguments="-I-Y" ContinueOnError="true"/>
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
[HelpUrl("http://www.msbuildextensionpack.com/help/3.5.12.0/html/bed0ab5a-a18e-b41d-9809-75deacc056e3.htm")]
public class SourceSafe : BaseTask
{
private const string CheckoutTaskAction = "Checkout";
private const string CheckinTaskAction = "Checkin";
private const string CloakTaskAction = "Cloak";
private const string CreateTaskAction = "Create";
private const string DecloakTaskAction = "Decloak";
private const string DeleteTaskAction = "Delete";
private const string DestroyTaskAction = "Destroy";
private const string GetTaskAction = "Get";
private ShellWrapper shellWrapper;
private string sourceSafeVersion = "2005";
private string fileName = "ss.exe";
[DropdownValue(CheckoutTaskAction)]
[DropdownValue(CheckinTaskAction)]
[DropdownValue(CloakTaskAction)]
[DropdownValue(CreateTaskAction)]
[DropdownValue(DecloakTaskAction)]
[DropdownValue(DeleteTaskAction)]
[DropdownValue(DestroyTaskAction)]
[DropdownValue(GetTaskAction)]
public override string TaskAction
{
get { return base.TaskAction; }
set { base.TaskAction = value; }
}
/// <summary>
/// Sets the FilePath
/// </summary>
[Required]
[TaskAction(CheckoutTaskAction, true)]
[TaskAction(CheckinTaskAction, true)]
[TaskAction(CloakTaskAction, true)]
[TaskAction(CreateTaskAction, true)]
[TaskAction(DecloakTaskAction, true)]
[TaskAction(DeleteTaskAction, true)]
[TaskAction(DestroyTaskAction, true)]
[TaskAction(GetTaskAction, true)]
public string FilePath { get; set; }
/// <summary>
/// Set to true to prevent -I- being added to your custom Arguments. Default is False
/// </summary>
[TaskAction(CheckoutTaskAction, false)]
[TaskAction(CheckinTaskAction, false)]
[TaskAction(CloakTaskAction, false)]
[TaskAction(CreateTaskAction, false)]
[TaskAction(DecloakTaskAction, false)]
[TaskAction(DeleteTaskAction, false)]
[TaskAction(DestroyTaskAction, false)]
[TaskAction(GetTaskAction, false)]
public bool SuppressI { get; set; }
/// <summary>
/// Sets the Arguments. Defaults to -I- (Ignores all and tells the command not to ask for input under any circumstances) unless SuppressI is set to true. See http://msdn.microsoft.com/en-us/library/hsxzf2az(VS.80).aspx for full options.
/// </summary>
[TaskAction(CheckoutTaskAction, false)]
[TaskAction(CheckinTaskAction, false)]
[TaskAction(CloakTaskAction, false)]
[TaskAction(CreateTaskAction, false)]
[TaskAction(DecloakTaskAction, false)]
[TaskAction(DeleteTaskAction, false)]
[TaskAction(DestroyTaskAction, false)]
[TaskAction(GetTaskAction, false)]
public string Arguments { get; set; }
/// <summary>
/// Sets the SourceSafe version. Supports 2005 and 6d. Default is 2005
/// </summary>
[TaskAction(CheckoutTaskAction, false)]
[TaskAction(CheckinTaskAction, false)]
[TaskAction(CloakTaskAction, false)]
[TaskAction(CreateTaskAction, false)]
[TaskAction(DecloakTaskAction, false)]
[TaskAction(DeleteTaskAction, false)]
[TaskAction(DestroyTaskAction, false)]
[TaskAction(GetTaskAction, false)]
public string SSVersion
{
get { return this.sourceSafeVersion; }
set { this.sourceSafeVersion = value; }
}
/// <summary>
/// Sets the database.
/// </summary>
[TaskAction(CheckoutTaskAction, false)]
[TaskAction(CheckinTaskAction, false)]
[TaskAction(CloakTaskAction, false)]
[TaskAction(CreateTaskAction, false)]
[TaskAction(DecloakTaskAction, false)]
[TaskAction(DeleteTaskAction, false)]
[TaskAction(GetTaskAction, false)]
public ITaskItem Database { get; set; }
/// <summary>
/// Performs the action of this task.
/// </summary>
protected override void InternalExecute()
{
if (this.GetVersionInformation() == false)
{
return;
}
if (string.IsNullOrEmpty(this.Arguments))
{
if (!this.SuppressI)
{
this.Arguments = "-I-";
}
}
else
{
if (this.Arguments.IndexOf("-I-", StringComparison.Ordinal) < 0 && !this.SuppressI)
{
this.Arguments += " -I-";
}
}
string args = string.Format(CultureInfo.CurrentCulture, "{0} \"{1}\" {2}", this.TaskAction, this.FilePath, this.Arguments);
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Executing: {0} {1}", this.fileName, args));
this.ExecuteVisualSourceSafe(args);
}
private bool GetVersionInformation()
{
this.LogTaskMessage(MessageImportance.Low, "Getting version information");
RegistryKey vssKey;
switch (this.SSVersion)
{
case "6d":
vssKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\6.0\Setup\Microsoft Visual SourceSafe Server") ??
Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\6.0\Setup\Microsoft Visual SourceSafe");
if (vssKey != null)
{
string pathToSourceSafe = Convert.ToString(vssKey.GetValue("ProductDir"), CultureInfo.CurrentCulture);
this.fileName = Path.Combine(pathToSourceSafe, @"win32\ss.exe");
vssKey.Close();
}
break;
case "2005":
vssKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\8.0\Setup\VS\VSS");
if (vssKey != null)
{
string pathToSourceSafe = Convert.ToString(vssKey.GetValue("ProductDir"), CultureInfo.CurrentCulture);
this.fileName = Path.Combine(pathToSourceSafe, "ss.exe");
vssKey.Close();
}
break;
default:
this.Log.LogError("Invalid SSVersion. Valid options are 6d or 2005");
return false;
}
this.shellWrapper = new ShellWrapper(this.fileName);
if (this.Database != null)
{
this.shellWrapper.EnvironmentVariables.Add("SSDIR", this.Database.GetMetadata("FullPath"));
}
if (string.IsNullOrEmpty(this.UserName))
{
this.UserName = Environment.UserName;
}
this.shellWrapper.EnvironmentVariables.Add("SSUSER", this.UserName);
if (!string.IsNullOrEmpty(this.UserPassword))
{
this.shellWrapper.EnvironmentVariables.Add("SSPWD", this.UserPassword);
}
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Using UserName: {0} and Password: {1}", this.UserName, this.UserPassword));
return true;
}
private void ExecuteVisualSourceSafe(string args)
{
this.shellWrapper.Arguments = args;
int returncode = this.shellWrapper.Execute();
if (string.IsNullOrEmpty(this.shellWrapper.StandardOutput.Trim()) == false)
{
this.LogTaskMessage(this.shellWrapper.StandardOutput);
}
if (string.IsNullOrEmpty(this.shellWrapper.StandardError.Trim()) == false)
{
this.LogTaskMessage(this.shellWrapper.StandardError);
}
if (returncode != 0)
{
this.Log.LogError(this.shellWrapper.StandardError + "(" + returncode + ")");
}
}
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System;
using Markdig.Helpers;
using Markdig.Syntax;
namespace Markdig.Parsers
{
/// <summary>
/// Block parser for a <see cref="HtmlBlock"/>.
/// </summary>
/// <seealso cref="BlockParser" />
public class HtmlBlockParser : BlockParser
{
/// <summary>
/// Initializes a new instance of the <see cref="HtmlBlockParser"/> class.
/// </summary>
public HtmlBlockParser()
{
OpeningCharacters = new[] { '<' };
}
public override BlockState TryOpen(BlockProcessor processor)
{
var result = MatchStart(processor);
// An end-tag can occur on the same line, so we try to parse it here
if (result == BlockState.Continue)
{
result = MatchEnd(processor, (HtmlBlock) processor.NewBlocks.Peek());
}
return result;
}
public override BlockState TryContinue(BlockProcessor processor, Block block)
{
var htmlBlock = (HtmlBlock) block;
return MatchEnd(processor, htmlBlock);
}
private BlockState MatchStart(BlockProcessor state)
{
if (state.IsCodeIndent)
{
return BlockState.None;
}
var line = state.Line;
var startPosition = line.Start;
line.NextChar();
var result = TryParseTagType16(state, line, state.ColumnBeforeIndent, startPosition);
// HTML blocks of type 7 cannot interrupt a paragraph:
if (result == BlockState.None && !(state.CurrentBlock is ParagraphBlock))
{
result = TryParseTagType7(state, line, state.ColumnBeforeIndent, startPosition);
}
return result;
}
private BlockState TryParseTagType7(BlockProcessor state, StringSlice line, int startColumn, int startPosition)
{
var builder = StringBuilderCache.Local();
var c = line.CurrentChar;
var result = BlockState.None;
if ((c == '/' && HtmlHelper.TryParseHtmlCloseTag(ref line, builder)) || HtmlHelper.TryParseHtmlTagOpenTag(ref line, builder))
{
// Must be followed by whitespace only
bool hasOnlySpaces = true;
c = line.CurrentChar;
while (true)
{
if (c == '\0')
{
break;
}
if (!c.IsWhitespace())
{
hasOnlySpaces = false;
break;
}
c = line.NextChar();
}
if (hasOnlySpaces)
{
result = CreateHtmlBlock(state, HtmlBlockType.NonInterruptingBlock, startColumn, startPosition);
}
}
builder.Length = 0;
return result;
}
private BlockState TryParseTagType16(BlockProcessor state, StringSlice line, int startColumn, int startPosition)
{
char c;
c = line.CurrentChar;
if (c == '!')
{
c = line.NextChar();
if (c == '-' && line.PeekChar() == '-')
{
return CreateHtmlBlock(state, HtmlBlockType.Comment, startColumn, startPosition); // group 2
}
if (c.IsAlphaUpper())
{
return CreateHtmlBlock(state, HtmlBlockType.DocumentType, startColumn, startPosition); // group 4
}
if (c == '[' && line.Match("CDATA[", 1))
{
return CreateHtmlBlock(state, HtmlBlockType.CData, startColumn, startPosition); // group 5
}
return BlockState.None;
}
if (c == '?')
{
return CreateHtmlBlock(state, HtmlBlockType.ProcessingInstruction, startColumn, startPosition); // group 3
}
var hasLeadingClose = c == '/';
if (hasLeadingClose)
{
c = line.NextChar();
}
var tag = new char[10];
var count = 0;
for (; count < tag.Length; count++)
{
if (!c.IsAlphaNumeric())
{
break;
}
tag[count] = char.ToLowerInvariant(c);
c = line.NextChar();
}
if (
!(c == '>' || (!hasLeadingClose && c == '/' && line.PeekChar() == '>') || c.IsWhitespace() ||
c == '\0'))
{
return BlockState.None;
}
if (count == 0)
{
return BlockState.None;
}
var tagName = new string(tag, 0, count);
var tagIndex = Array.BinarySearch(HtmlTags, tagName, StringComparer.Ordinal);
if (tagIndex < 0)
{
return BlockState.None;
}
// Cannot start with </script </pre or </style
if ((tagIndex == 49 || tagIndex == 50 || tagIndex == 53))
{
if (c == '/' || hasLeadingClose)
{
return BlockState.None;
}
return CreateHtmlBlock(state, HtmlBlockType.ScriptPreOrStyle, startColumn, startPosition);
}
return CreateHtmlBlock(state, HtmlBlockType.InterruptingBlock, startColumn, startPosition);
}
private const string EndOfComment = "-->";
private const string EndOfCDATA = "]]>";
private const string EndOfProcessingInstruction = "?>";
private BlockState MatchEnd(BlockProcessor state, HtmlBlock htmlBlock)
{
state.GoToColumn(state.ColumnBeforeIndent);
// Early exit if it is not starting by an HTML tag
var line = state.Line;
var result = BlockState.Continue;
int index;
switch (htmlBlock.Type)
{
case HtmlBlockType.Comment:
index = line.IndexOf(EndOfComment);
if (index >= 0)
{
htmlBlock.UpdateSpanEnd(index + EndOfComment.Length);
result = BlockState.Break;
}
break;
case HtmlBlockType.CData:
index = line.IndexOf(EndOfCDATA);
if (index >= 0)
{
htmlBlock.UpdateSpanEnd(index + EndOfCDATA.Length);
result = BlockState.Break;
}
break;
case HtmlBlockType.ProcessingInstruction:
index = line.IndexOf(EndOfProcessingInstruction);
if (index >= 0)
{
htmlBlock.UpdateSpanEnd(index + EndOfProcessingInstruction.Length);
result = BlockState.Break;
}
break;
case HtmlBlockType.DocumentType:
index = line.IndexOf('>');
if (index >= 0)
{
htmlBlock.UpdateSpanEnd(index + 1);
result = BlockState.Break;
}
break;
case HtmlBlockType.ScriptPreOrStyle:
index = line.IndexOf("</script>", 0, true);
if (index >= 0)
{
htmlBlock.UpdateSpanEnd(index + "</script>".Length);
result = BlockState.Break;
}
else
{
index = line.IndexOf("</pre>", 0, true);
if (index >= 0)
{
htmlBlock.UpdateSpanEnd(index + "</pre>".Length);
result = BlockState.Break;
}
else
{
index = line.IndexOf("</style>", 0, true);
if (index >= 0)
{
htmlBlock.UpdateSpanEnd(index + "</style>".Length);
result = BlockState.Break;
}
}
}
break;
case HtmlBlockType.InterruptingBlock:
if (state.IsBlankLine)
{
result = BlockState.BreakDiscard;
}
break;
case HtmlBlockType.NonInterruptingBlock:
if (state.IsBlankLine)
{
result = BlockState.BreakDiscard;
}
break;
}
// Update only if we don't have a break discard
if (result != BlockState.BreakDiscard)
{
htmlBlock.Span.End = line.End;
}
return result;
}
private BlockState CreateHtmlBlock(BlockProcessor state, HtmlBlockType type, int startColumn, int startPosition)
{
state.NewBlocks.Push(new HtmlBlock(this)
{
Column = startColumn,
Type = type,
// By default, setup to the end of line
Span = new SourceSpan(startPosition, startPosition + state.Line.End)
});
return BlockState.Continue;
}
private static readonly string[] HtmlTags =
{
"address", // 0
"article", // 1
"aside", // 2
"base", // 3
"basefont", // 4
"blockquote", // 5
"body", // 6
"caption", // 7
"center", // 8
"col", // 9
"colgroup", // 10
"dd", // 11
"details", // 12
"dialog", // 13
"dir", // 14
"div", // 15
"dl", // 16
"dt", // 17
"fieldset", // 18
"figcaption", // 19
"figure", // 20
"footer", // 21
"form", // 22
"frame", // 23
"frameset", // 24
"h1", // 25
"h2", // 26
"h3", // 27
"h4", // 28
"h5", // 29
"h6", // 30
"head", // 31
"header", // 32
"hr", // 33
"html", // 34
"iframe", // 35
"legend", // 36
"li", // 37
"link", // 38
"main", // 39
"menu", // 40
"menuitem", // 41
"nav", // 42
"noframes", // 43
"ol", // 44
"optgroup", // 45
"option", // 46
"p", // 47
"param", // 48
"pre", // 49 <=== special group 1
"script", // 50 <=== special group 1
"section", // 51
"source", // 52
"style", // 53 <=== special group 1
"summary", // 54
"table", // 55
"tbody", // 56
"td", // 57
"tfoot", // 58
"th", // 59
"thead", // 60
"title", // 61
"tr", // 62
"track", // 63
"ul", // 64
};
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
namespace System.Reflection.Metadata
{
partial class MetadataReader
{
internal const string ClrPrefix = "<CLR>";
internal static readonly byte[] WinRTPrefix = new[] {
(byte)'<',
(byte)'W',
(byte)'i',
(byte)'n',
(byte)'R',
(byte)'T',
(byte)'>'
};
#region Projection Tables
// Maps names of projected types to projection information for each type.
// Both arrays are of the same length and sorted by the type name.
private static string[] s_projectedTypeNames;
private static ProjectionInfo[] s_projectionInfos;
private struct ProjectionInfo
{
public readonly string WinRTNamespace;
public readonly StringHandle.VirtualIndex ClrNamespace;
public readonly StringHandle.VirtualIndex ClrName;
public readonly AssemblyReferenceHandle.VirtualIndex AssemblyRef;
public readonly TypeDefTreatment Treatment;
public readonly TypeRefSignatureTreatment SignatureTreatment;
public readonly bool IsIDisposable;
public ProjectionInfo(
string winRtNamespace,
StringHandle.VirtualIndex clrNamespace,
StringHandle.VirtualIndex clrName,
AssemblyReferenceHandle.VirtualIndex clrAssembly,
TypeDefTreatment treatment = TypeDefTreatment.RedirectedToClrType,
TypeRefSignatureTreatment signatureTreatment = TypeRefSignatureTreatment.None,
bool isIDisposable = false)
{
this.WinRTNamespace = winRtNamespace;
this.ClrNamespace = clrNamespace;
this.ClrName = clrName;
this.AssemblyRef = clrAssembly;
this.Treatment = treatment;
this.SignatureTreatment = signatureTreatment;
this.IsIDisposable = isIDisposable;
}
}
private TypeDefTreatment GetWellKnownTypeDefinitionTreatment(TypeDefinitionHandle typeDef)
{
InitializeProjectedTypes();
StringHandle name = TypeDefTable.GetName(typeDef);
int index = StringStream.BinarySearchRaw(s_projectedTypeNames, name);
if (index < 0)
{
return TypeDefTreatment.None;
}
StringHandle namespaceName = TypeDefTable.GetNamespace(typeDef);
if (StringStream.EqualsRaw(namespaceName, StringStream.GetVirtualValue(s_projectionInfos[index].ClrNamespace)))
{
return s_projectionInfos[index].Treatment;
}
// TODO: we can avoid this comparison if info.DotNetNamespace == info.WinRtNamespace
if (StringStream.EqualsRaw(namespaceName, s_projectionInfos[index].WinRTNamespace))
{
return s_projectionInfos[index].Treatment | TypeDefTreatment.MarkInternalFlag;
}
return TypeDefTreatment.None;
}
private int GetProjectionIndexForTypeReference(TypeReferenceHandle typeRef, out bool isIDisposable)
{
InitializeProjectedTypes();
int index = StringStream.BinarySearchRaw(s_projectedTypeNames, TypeRefTable.GetName(typeRef));
if (index >= 0 && StringStream.EqualsRaw(TypeRefTable.GetNamespace(typeRef), s_projectionInfos[index].WinRTNamespace))
{
isIDisposable = s_projectionInfos[index].IsIDisposable;
return index;
}
isIDisposable = false;
return -1;
}
internal static AssemblyReferenceHandle GetProjectedAssemblyRef(int projectionIndex)
{
Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length);
return AssemblyReferenceHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].AssemblyRef);
}
internal static StringHandle GetProjectedName(int projectionIndex)
{
Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length);
return StringHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].ClrName);
}
internal static StringHandle GetProjectedNamespace(int projectionIndex)
{
Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length);
return StringHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].ClrNamespace);
}
internal static TypeRefSignatureTreatment GetProjectedSignatureTreatment(int projectionIndex)
{
Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length);
return s_projectionInfos[projectionIndex].SignatureTreatment;
}
private static void InitializeProjectedTypes()
{
if (s_projectedTypeNames == null || s_projectionInfos == null)
{
var systemRuntimeWindowsRuntime = AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime;
var systemRuntime = AssemblyReferenceHandle.VirtualIndex.System_Runtime;
var systemObjectModel = AssemblyReferenceHandle.VirtualIndex.System_ObjectModel;
var systemRuntimeWindowsUiXaml = AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml;
var systemRuntimeInterop = AssemblyReferenceHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime;
var systemNumericsVectors = AssemblyReferenceHandle.VirtualIndex.System_Numerics_Vectors;
// sorted by name
var keys = new string[50];
var values = new ProjectionInfo[50];
int k = 0, v = 0;
// WARNING: Keys must be sorted by name and must only contain ASCII characters. WinRTNamespace must also be ASCII only.
keys[k++] = "AttributeTargets"; values[v++] = new ProjectionInfo("Windows.Foundation.Metadata", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.AttributeTargets, systemRuntime);
keys[k++] = "AttributeUsageAttribute"; values[v++] = new ProjectionInfo("Windows.Foundation.Metadata", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.AttributeUsageAttribute, systemRuntime, treatment: TypeDefTreatment.RedirectedToClrAttribute);
keys[k++] = "Color"; values[v++] = new ProjectionInfo("Windows.UI", StringHandle.VirtualIndex.Windows_UI, StringHandle.VirtualIndex.Color, systemRuntimeWindowsRuntime);
keys[k++] = "CornerRadius"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.CornerRadius, systemRuntimeWindowsUiXaml);
keys[k++] = "DateTime"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.DateTimeOffset, systemRuntime);
keys[k++] = "Duration"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.Duration, systemRuntimeWindowsUiXaml);
keys[k++] = "DurationType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.DurationType, systemRuntimeWindowsUiXaml);
keys[k++] = "EventHandler`1"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.EventHandler1, systemRuntime);
keys[k++] = "EventRegistrationToken"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime, StringHandle.VirtualIndex.EventRegistrationToken, systemRuntimeInterop);
keys[k++] = "GeneratorPosition"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Controls.Primitives", StringHandle.VirtualIndex.Windows_UI_Xaml_Controls_Primitives, StringHandle.VirtualIndex.GeneratorPosition, systemRuntimeWindowsUiXaml);
keys[k++] = "GridLength"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.GridLength, systemRuntimeWindowsUiXaml);
keys[k++] = "GridUnitType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.GridUnitType, systemRuntimeWindowsUiXaml);
keys[k++] = "HResult"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Exception, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToClass);
keys[k++] = "IBindableIterable"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections, StringHandle.VirtualIndex.IEnumerable, systemRuntime);
keys[k++] = "IBindableVector"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections, StringHandle.VirtualIndex.IList, systemRuntime);
keys[k++] = "IClosable"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.IDisposable, systemRuntime, isIDisposable: true);
keys[k++] = "ICommand"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Input", StringHandle.VirtualIndex.System_Windows_Input, StringHandle.VirtualIndex.ICommand, systemObjectModel);
keys[k++] = "IIterable`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IEnumerable1, systemRuntime);
keys[k++] = "IKeyValuePair`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.KeyValuePair2, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToValueType);
keys[k++] = "IMapView`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IReadOnlyDictionary2, systemRuntime);
keys[k++] = "IMap`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IDictionary2, systemRuntime);
keys[k++] = "INotifyCollectionChanged"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.INotifyCollectionChanged, systemObjectModel);
keys[k++] = "INotifyPropertyChanged"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.INotifyPropertyChanged, systemObjectModel);
keys[k++] = "IReference`1"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Nullable1, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToValueType);
keys[k++] = "IVectorView`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IReadOnlyList1, systemRuntime);
keys[k++] = "IVector`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IList1, systemRuntime);
keys[k++] = "KeyTime"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.KeyTime, systemRuntimeWindowsUiXaml);
keys[k++] = "Matrix"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media", StringHandle.VirtualIndex.Windows_UI_Xaml_Media, StringHandle.VirtualIndex.Matrix, systemRuntimeWindowsUiXaml);
keys[k++] = "Matrix3D"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Media3D", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Media3D, StringHandle.VirtualIndex.Matrix3D, systemRuntimeWindowsUiXaml);
keys[k++] = "Matrix3x2"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Matrix3x2, systemNumericsVectors);
keys[k++] = "Matrix4x4"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Matrix4x4, systemNumericsVectors);
keys[k++] = "NotifyCollectionChangedAction"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedAction, systemObjectModel);
keys[k++] = "NotifyCollectionChangedEventArgs"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedEventArgs, systemObjectModel);
keys[k++] = "NotifyCollectionChangedEventHandler"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedEventHandler, systemObjectModel);
keys[k++] = "Plane"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Plane, systemNumericsVectors);
keys[k++] = "Point"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Point, systemRuntimeWindowsRuntime);
keys[k++] = "PropertyChangedEventArgs"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.PropertyChangedEventArgs, systemObjectModel);
keys[k++] = "PropertyChangedEventHandler"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.PropertyChangedEventHandler, systemObjectModel);
keys[k++] = "Quaternion"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Quaternion, systemNumericsVectors);
keys[k++] = "Rect"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Rect, systemRuntimeWindowsRuntime);
keys[k++] = "RepeatBehavior"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.RepeatBehavior, systemRuntimeWindowsUiXaml);
keys[k++] = "RepeatBehaviorType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.RepeatBehaviorType, systemRuntimeWindowsUiXaml);
keys[k++] = "Size"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Size, systemRuntimeWindowsRuntime);
keys[k++] = "Thickness"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.Thickness, systemRuntimeWindowsUiXaml);
keys[k++] = "TimeSpan"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.TimeSpan, systemRuntime);
keys[k++] = "TypeName"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Type, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToClass);
keys[k++] = "Uri"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Uri, systemRuntime);
keys[k++] = "Vector2"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector2, systemNumericsVectors);
keys[k++] = "Vector3"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector3, systemNumericsVectors);
keys[k++] = "Vector4"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector4, systemNumericsVectors);
Debug.Assert(k == keys.Length && v == keys.Length && k == v);
AssertSorted(keys);
s_projectedTypeNames = keys;
s_projectionInfos = values;
}
}
[Conditional("DEBUG")]
private static void AssertSorted(string[] keys)
{
for (int i = 0; i < keys.Length - 1; i++)
{
Debug.Assert(String.CompareOrdinal(keys[i], keys[i + 1]) < 0);
}
}
// test only
internal static string[] GetProjectedTypeNames()
{
InitializeProjectedTypes();
return s_projectedTypeNames;
}
#endregion
private static uint TreatmentAndRowId(byte treatment, int rowId)
{
return ((uint)treatment << TokenTypeIds.RowIdBitCount) | (uint)rowId;
}
#region TypeDef
[MethodImpl(MethodImplOptions.NoInlining)]
internal uint CalculateTypeDefTreatmentAndRowId(TypeDefinitionHandle handle)
{
Debug.Assert(_metadataKind != MetadataKind.Ecma335);
TypeDefTreatment treatment;
TypeAttributes flags = TypeDefTable.GetFlags(handle);
EntityHandle extends = TypeDefTable.GetExtends(handle);
if ((flags & TypeAttributes.WindowsRuntime) != 0)
{
if (_metadataKind == MetadataKind.WindowsMetadata)
{
treatment = GetWellKnownTypeDefinitionTreatment(handle);
if (treatment != TypeDefTreatment.None)
{
return TreatmentAndRowId((byte)treatment, handle.RowId);
}
// Is this an attribute?
if (extends.Kind == HandleKind.TypeReference && IsSystemAttribute((TypeReferenceHandle)extends))
{
treatment = TypeDefTreatment.NormalAttribute;
}
else
{
treatment = TypeDefTreatment.NormalNonAttribute;
}
}
else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && NeedsWinRTPrefix(flags, extends))
{
// WinMDExp emits two versions of RuntimeClasses and Enums:
//
// public class Foo {} // the WinRT reference class
// internal class <CLR>Foo {} // the implementation class that we want WinRT consumers to ignore
//
// The adapter's job is to undo WinMDExp's transformations. I.e. turn the above into:
//
// internal class <WinRT>Foo {} // the WinRT reference class that we want CLR consumers to ignore
// public class Foo {} // the implementation class
//
// We only add the <WinRT> prefix here since the WinRT view is the only view that is marked WindowsRuntime
// De-mangling the CLR name is done below.
// tomat: The CLR adapter implements a back-compat quirk: Enums exported with an older WinMDExp have only one version
// not marked with tdSpecialName. These enums should *not* be mangled and flipped to private.
// We don't implement this flag since the WinMDs producted by the older WinMDExp are not used in the wild.
treatment = TypeDefTreatment.PrefixWinRTName;
}
else
{
treatment = TypeDefTreatment.None;
}
// Scan through Custom Attributes on type, looking for interesting bits. We only
// need to do this for RuntimeClasses
if ((treatment == TypeDefTreatment.PrefixWinRTName || treatment == TypeDefTreatment.NormalNonAttribute))
{
if ((flags & TypeAttributes.Interface) == 0
&& HasAttribute(handle, "Windows.UI.Xaml", "TreatAsAbstractComposableClassAttribute"))
{
treatment |= TypeDefTreatment.MarkAbstractFlag;
}
}
}
else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && IsClrImplementationType(handle))
{
// <CLR> implementation classes are not marked WindowsRuntime, but still need to be modified
// by the adapter.
treatment = TypeDefTreatment.UnmangleWinRTName;
}
else
{
treatment = TypeDefTreatment.None;
}
return TreatmentAndRowId((byte)treatment, handle.RowId);
}
private bool IsClrImplementationType(TypeDefinitionHandle typeDef)
{
var attrs = TypeDefTable.GetFlags(typeDef);
if ((attrs & (TypeAttributes.VisibilityMask | TypeAttributes.SpecialName)) != TypeAttributes.SpecialName)
{
return false;
}
return StringStream.StartsWithRaw(TypeDefTable.GetName(typeDef), ClrPrefix);
}
#endregion
#region TypeRef
internal uint CalculateTypeRefTreatmentAndRowId(TypeReferenceHandle handle)
{
Debug.Assert(_metadataKind != MetadataKind.Ecma335);
bool isIDisposable;
int projectionIndex = GetProjectionIndexForTypeReference(handle, out isIDisposable);
if (projectionIndex >= 0)
{
return TreatmentAndRowId((byte)TypeRefTreatment.UseProjectionInfo, projectionIndex);
}
else
{
return TreatmentAndRowId((byte)GetSpecialTypeRefTreatment(handle), handle.RowId);
}
}
private TypeRefTreatment GetSpecialTypeRefTreatment(TypeReferenceHandle handle)
{
if (StringStream.EqualsRaw(TypeRefTable.GetNamespace(handle), "System"))
{
StringHandle name = TypeRefTable.GetName(handle);
if (StringStream.EqualsRaw(name, "MulticastDelegate"))
{
return TypeRefTreatment.SystemDelegate;
}
if (StringStream.EqualsRaw(name, "Attribute"))
{
return TypeRefTreatment.SystemAttribute;
}
}
return TypeRefTreatment.None;
}
private bool IsSystemAttribute(TypeReferenceHandle handle)
{
return StringStream.EqualsRaw(TypeRefTable.GetNamespace(handle), "System") &&
StringStream.EqualsRaw(TypeRefTable.GetName(handle), "Attribute");
}
private bool IsSystemEnum(TypeReferenceHandle handle)
{
return StringStream.EqualsRaw(TypeRefTable.GetNamespace(handle), "System") &&
StringStream.EqualsRaw(TypeRefTable.GetName(handle), "Enum");
}
private bool NeedsWinRTPrefix(TypeAttributes flags, EntityHandle extends)
{
if ((flags & (TypeAttributes.VisibilityMask | TypeAttributes.Interface)) != TypeAttributes.Public)
{
return false;
}
if (extends.Kind != HandleKind.TypeReference)
{
return false;
}
// Check if the type is a delegate, struct, or attribute
TypeReferenceHandle extendsRefHandle = (TypeReferenceHandle)extends;
if (StringStream.EqualsRaw(TypeRefTable.GetNamespace(extendsRefHandle), "System"))
{
StringHandle nameHandle = TypeRefTable.GetName(extendsRefHandle);
if (StringStream.EqualsRaw(nameHandle, "MulticastDelegate")
|| StringStream.EqualsRaw(nameHandle, "ValueType")
|| StringStream.EqualsRaw(nameHandle, "Attribute"))
{
return false;
}
}
return true;
}
#endregion
#region MethodDef
private uint CalculateMethodDefTreatmentAndRowId(MethodDefinitionHandle methodDef)
{
MethodDefTreatment treatment = MethodDefTreatment.Implementation;
TypeDefinitionHandle parentTypeDef = GetDeclaringType(methodDef);
TypeAttributes parentFlags = TypeDefTable.GetFlags(parentTypeDef);
if ((parentFlags & TypeAttributes.WindowsRuntime) != 0)
{
if (IsClrImplementationType(parentTypeDef))
{
treatment = MethodDefTreatment.Implementation;
}
else if (parentFlags.IsNested())
{
treatment = MethodDefTreatment.Implementation;
}
else if ((parentFlags & TypeAttributes.Interface) != 0)
{
treatment = MethodDefTreatment.InterfaceMethod;
}
else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && (parentFlags & TypeAttributes.Public) == 0)
{
treatment = MethodDefTreatment.Implementation;
}
else
{
treatment = MethodDefTreatment.Other;
var parentBaseType = TypeDefTable.GetExtends(parentTypeDef);
if (parentBaseType.Kind == HandleKind.TypeReference)
{
switch (GetSpecialTypeRefTreatment((TypeReferenceHandle)parentBaseType))
{
case TypeRefTreatment.SystemAttribute:
treatment = MethodDefTreatment.AttributeMethod;
break;
case TypeRefTreatment.SystemDelegate:
treatment = MethodDefTreatment.DelegateMethod | MethodDefTreatment.MarkPublicFlag;
break;
}
}
}
}
if (treatment == MethodDefTreatment.Other)
{
// we want to hide the method if it implements
// only redirected interfaces
// We also want to check if the methodImpl is IClosable.Close,
// so we can change the name
bool seenRedirectedInterfaces = false;
bool seenNonRedirectedInterfaces = false;
bool isIClosableClose = false;
foreach (var methodImplHandle in new MethodImplementationHandleCollection(this, parentTypeDef))
{
MethodImplementation methodImpl = GetMethodImplementation(methodImplHandle);
if (methodImpl.MethodBody == methodDef)
{
EntityHandle declaration = methodImpl.MethodDeclaration;
// See if this MethodImpl implements a redirected interface
// In WinMD, MethodImpl will always use MemberRef and TypeRefs to refer to redirected interfaces,
// even if they are in the same module.
if (declaration.Kind == HandleKind.MemberReference &&
ImplementsRedirectedInterface((MemberReferenceHandle)declaration, out isIClosableClose))
{
seenRedirectedInterfaces = true;
if (isIClosableClose)
{
// This method implements IClosable.Close
// Let's rename to IDisposable later
// Once we know this implements IClosable.Close, we are done
// looking
break;
}
}
else
{
// Now we know this implements a non-redirected interface
// But we need to keep looking, just in case we got a methodimpl that
// implements the IClosable.Close method and needs to be renamed
seenNonRedirectedInterfaces = true;
}
}
}
if (isIClosableClose)
{
treatment = MethodDefTreatment.DisposeMethod;
}
else if (seenRedirectedInterfaces && !seenNonRedirectedInterfaces)
{
// Only hide if all the interfaces implemented are redirected
treatment = MethodDefTreatment.HiddenInterfaceImplementation;
}
}
// If treatment is other, then this is a non-managed WinRT runtime class definition
// Find out about various bits that we apply via attributes and name parsing
if (treatment == MethodDefTreatment.Other)
{
treatment |= GetMethodTreatmentFromCustomAttributes(methodDef);
}
return TreatmentAndRowId((byte)treatment, methodDef.RowId);
}
private MethodDefTreatment GetMethodTreatmentFromCustomAttributes(MethodDefinitionHandle methodDef)
{
MethodDefTreatment treatment = 0;
foreach (var caHandle in GetCustomAttributes(methodDef))
{
StringHandle namespaceHandle, nameHandle;
if (!GetAttributeTypeNameRaw(caHandle, out namespaceHandle, out nameHandle))
{
continue;
}
Debug.Assert(!namespaceHandle.IsVirtual && !nameHandle.IsVirtual);
if (StringStream.EqualsRaw(namespaceHandle, "Windows.UI.Xaml"))
{
if (StringStream.EqualsRaw(nameHandle, "TreatAsPublicMethodAttribute"))
{
treatment |= MethodDefTreatment.MarkPublicFlag;
}
if (StringStream.EqualsRaw(nameHandle, "TreatAsAbstractMethodAttribute"))
{
treatment |= MethodDefTreatment.MarkAbstractFlag;
}
}
}
return treatment;
}
#endregion
#region FieldDef
/// <summary>
/// The backing field of a WinRT enumeration type is not public although the backing fields
/// of managed enumerations are. To allow managed languages to directly access this field,
/// it is made public by the metadata adapter.
/// </summary>
private uint CalculateFieldDefTreatmentAndRowId(FieldDefinitionHandle handle)
{
var flags = FieldTable.GetFlags(handle);
FieldDefTreatment treatment = FieldDefTreatment.None;
if ((flags & FieldAttributes.RTSpecialName) != 0 && StringStream.EqualsRaw(FieldTable.GetName(handle), "value__"))
{
TypeDefinitionHandle typeDef = GetDeclaringType(handle);
EntityHandle baseTypeHandle = TypeDefTable.GetExtends(typeDef);
if (baseTypeHandle.Kind == HandleKind.TypeReference)
{
var typeRef = (TypeReferenceHandle)baseTypeHandle;
if (StringStream.EqualsRaw(TypeRefTable.GetName(typeRef), "Enum") &&
StringStream.EqualsRaw(TypeRefTable.GetNamespace(typeRef), "System"))
{
treatment = FieldDefTreatment.EnumValue;
}
}
}
return TreatmentAndRowId((byte)treatment, handle.RowId);
}
#endregion
#region MemberRef
private uint CalculateMemberRefTreatmentAndRowId(MemberReferenceHandle handle)
{
MemberRefTreatment treatment;
// We need to rename the MemberRef for IClosable.Close as well
// so that the MethodImpl for the Dispose method can be correctly shown
// as IDisposable.Dispose instead of IDisposable.Close
bool isIDisposable;
if (ImplementsRedirectedInterface(handle, out isIDisposable) && isIDisposable)
{
treatment = MemberRefTreatment.Dispose;
}
else
{
treatment = MemberRefTreatment.None;
}
return TreatmentAndRowId((byte)treatment, handle.RowId);
}
/// <summary>
/// We want to know if a given method implements a redirected interface.
/// For example, if we are given the method RemoveAt on a class "A"
/// which implements the IVector interface (which is redirected
/// to IList in .NET) then this method would return true. The most
/// likely reason why we would want to know this is that we wish to hide
/// (mark private) all methods which implement methods on a redirected
/// interface.
/// </summary>
/// <param name="memberRef">The declaration token for the method</param>
/// <param name="isIDisposable">
/// Returns true if the redirected interface is <see cref="IDisposable"/>.
/// </param>
/// <returns>True if the method implements a method on a redirected interface.
/// False otherwise.</returns>
private bool ImplementsRedirectedInterface(MemberReferenceHandle memberRef, out bool isIDisposable)
{
isIDisposable = false;
EntityHandle parent = MemberRefTable.GetClass(memberRef);
TypeReferenceHandle typeRef;
if (parent.Kind == HandleKind.TypeReference)
{
typeRef = (TypeReferenceHandle)parent;
}
else if (parent.Kind == HandleKind.TypeSpecification)
{
BlobHandle blob = TypeSpecTable.GetSignature((TypeSpecificationHandle)parent);
BlobReader sig = new BlobReader(BlobStream.GetMemoryBlock(blob));
if (sig.Length < 2 ||
sig.ReadByte() != (byte)CorElementType.ELEMENT_TYPE_GENERICINST ||
sig.ReadByte() != (byte)CorElementType.ELEMENT_TYPE_CLASS)
{
return false;
}
EntityHandle token = sig.ReadTypeHandle();
if (token.Kind != HandleKind.TypeReference)
{
return false;
}
typeRef = (TypeReferenceHandle)token;
}
else
{
return false;
}
return GetProjectionIndexForTypeReference(typeRef, out isIDisposable) >= 0;
}
#endregion
#region AssemblyRef
private int FindMscorlibAssemblyRefNoProjection()
{
for (int i = 1; i <= AssemblyRefTable.NumberOfNonVirtualRows; i++)
{
if (StringStream.EqualsRaw(AssemblyRefTable.GetName(i), "mscorlib"))
{
return i;
}
}
throw new BadImageFormatException(SR.WinMDMissingMscorlibRef);
}
#endregion
#region CustomAttribute
internal CustomAttributeValueTreatment CalculateCustomAttributeValueTreatment(CustomAttributeHandle handle)
{
Debug.Assert(_metadataKind != MetadataKind.Ecma335);
var parent = CustomAttributeTable.GetParent(handle);
// Check for Windows.Foundation.Metadata.AttributeUsageAttribute.
// WinMD rules:
// - The attribute is only applicable on TypeDefs.
// - Constructor must be a MemberRef with TypeRef.
if (!IsWindowsAttributeUsageAttribute(parent, handle))
{
return CustomAttributeValueTreatment.None;
}
var targetTypeDef = (TypeDefinitionHandle)parent;
if (StringStream.EqualsRaw(TypeDefTable.GetNamespace(targetTypeDef), "Windows.Foundation.Metadata"))
{
if (StringStream.EqualsRaw(TypeDefTable.GetName(targetTypeDef), "VersionAttribute"))
{
return CustomAttributeValueTreatment.AttributeUsageVersionAttribute;
}
if (StringStream.EqualsRaw(TypeDefTable.GetName(targetTypeDef), "DeprecatedAttribute"))
{
return CustomAttributeValueTreatment.AttributeUsageDeprecatedAttribute;
}
}
bool allowMultiple = HasAttribute(targetTypeDef, "Windows.Foundation.Metadata", "AllowMultipleAttribute");
return allowMultiple ? CustomAttributeValueTreatment.AttributeUsageAllowMultiple : CustomAttributeValueTreatment.AttributeUsageAllowSingle;
}
private bool IsWindowsAttributeUsageAttribute(EntityHandle targetType, CustomAttributeHandle attributeHandle)
{
// Check for Windows.Foundation.Metadata.AttributeUsageAttribute.
// WinMD rules:
// - The attribute is only applicable on TypeDefs.
// - Constructor must be a MemberRef with TypeRef.
if (targetType.Kind != HandleKind.TypeDefinition)
{
return false;
}
var attributeCtor = CustomAttributeTable.GetConstructor(attributeHandle);
if (attributeCtor.Kind != HandleKind.MemberReference)
{
return false;
}
var attributeType = MemberRefTable.GetClass((MemberReferenceHandle)attributeCtor);
if (attributeType.Kind != HandleKind.TypeReference)
{
return false;
}
var attributeTypeRef = (TypeReferenceHandle)attributeType;
return StringStream.EqualsRaw(TypeRefTable.GetName(attributeTypeRef), "AttributeUsageAttribute") &&
StringStream.EqualsRaw(TypeRefTable.GetNamespace(attributeTypeRef), "Windows.Foundation.Metadata");
}
private bool HasAttribute(EntityHandle token, string asciiNamespaceName, string asciiTypeName)
{
foreach (var caHandle in GetCustomAttributes(token))
{
StringHandle namespaceName, typeName;
if (GetAttributeTypeNameRaw(caHandle, out namespaceName, out typeName) &&
StringStream.EqualsRaw(typeName, asciiTypeName) &&
StringStream.EqualsRaw(namespaceName, asciiNamespaceName))
{
return true;
}
}
return false;
}
private bool GetAttributeTypeNameRaw(CustomAttributeHandle caHandle, out StringHandle namespaceName, out StringHandle typeName)
{
namespaceName = typeName = default(StringHandle);
EntityHandle typeDefOrRef = GetAttributeTypeRaw(caHandle);
if (typeDefOrRef.IsNil)
{
return false;
}
if (typeDefOrRef.Kind == HandleKind.TypeReference)
{
TypeReferenceHandle typeRef = (TypeReferenceHandle)typeDefOrRef;
var resolutionScope = TypeRefTable.GetResolutionScope(typeRef);
if (!resolutionScope.IsNil && resolutionScope.Kind == HandleKind.TypeReference)
{
// we don't need to handle nested types
return false;
}
// other resolution scopes don't affect full name
typeName = TypeRefTable.GetName(typeRef);
namespaceName = TypeRefTable.GetNamespace(typeRef);
}
else if (typeDefOrRef.Kind == HandleKind.TypeDefinition)
{
TypeDefinitionHandle typeDef = (TypeDefinitionHandle)typeDefOrRef;
if (TypeDefTable.GetFlags(typeDef).IsNested())
{
// we don't need to handle nested types
return false;
}
typeName = TypeDefTable.GetName(typeDef);
namespaceName = TypeDefTable.GetNamespace(typeDef);
}
else
{
// invalid metadata
return false;
}
return true;
}
/// <summary>
/// Returns the type definition or reference handle of the attribute type.
/// </summary>
/// <returns><see cref="TypeDefinitionHandle"/> or <see cref="TypeReferenceHandle"/> or nil token if the metadata is invalid and the type can't be determined.</returns>
private EntityHandle GetAttributeTypeRaw(CustomAttributeHandle handle)
{
var ctor = CustomAttributeTable.GetConstructor(handle);
if (ctor.Kind == HandleKind.MethodDefinition)
{
return GetDeclaringType((MethodDefinitionHandle)ctor);
}
if (ctor.Kind == HandleKind.MemberReference)
{
// In general the parent can be MethodDef, ModuleRef, TypeDef, TypeRef, or TypeSpec.
// For attributes only TypeDef and TypeRef are applicable.
EntityHandle typeDefOrRef = MemberRefTable.GetClass((MemberReferenceHandle)ctor);
HandleKind handleType = typeDefOrRef.Kind;
if (handleType == HandleKind.TypeReference || handleType == HandleKind.TypeDefinition)
{
return typeDefOrRef;
}
}
return default(EntityHandle);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace Sce.Atf.Gui.TitleBarTab
{
/// <summary>
/// Provides the base functionality for any tab renderer, taking care of actually rendering and detecting whether the cursor is over a tab. Any custom
/// tab renderer needs to inherit from this class, just as <see cref="ChromeTabRenderer" /> does.
/// </summary>
public abstract class BaseTabRenderer
{
/// <summary>
/// Background of the content area for the tab when the tab is active; its width also determines how wide the default content area for the tab
/// is.
/// </summary>
protected Image _activeCenterImage;
/// <summary>Image to display on the left side of an active tab.</summary>
protected Image _activeLeftSideImage;
/// <summary>Image to display on the right side of an active tab.</summary>
protected Image _activeRightSideImage;
/// <summary>Area on the screen where the add button is located.</summary>
protected Rectangle _addButtonArea;
/// <summary>Image to display when the user hovers over the add button.</summary>
protected Bitmap _addButtonHoverImage;
/// <summary>Image to display for the add button when the user is not hovering over it.</summary>
protected Bitmap _addButtonImage;
/// <summary>The background, if any, that should be displayed in the non-client area behind the actual tabs.</summary>
protected Image _background;
/// <summary>The hover-over image that should be displayed on each tab to close that tab.</summary>
protected Image _closeButtonHoverImage;
/// <summary>The image that should be displayed on each tab to close that tab.</summary>
protected Image _closeButtonImage;
/// <summary>When the user is dragging a tab, this represents the point where the user first clicked to start the drag operation.</summary>
protected Point? _dragStart = null;
/// <summary>
/// Background of the content area for the tab when the tab is inactive; its width also determines how wide the default content area for the tab
/// is.
/// </summary>
protected Image _inactiveCenterImage;
/// <summary>Image to display on the left side of an inactive tab.</summary>
protected Image _inactiveLeftSideImage;
/// <summary>Image to display on the right side of an inactive tab.</summary>
protected Image _inactiveRightSideImage;
/// <summary>Flag indicating whether or not a tab is being repositioned.</summary>
protected bool _isTabRepositioning = false;
/// <summary>Maximum area on the screen that tabs may take up for this application.</summary>
protected Rectangle _maxTabArea = new Rectangle();
/// <summary>The parent window that this renderer instance belongs to.</summary>
protected TitleBarTabMainForm _parentWindow;
/// <summary>The number of tabs that were present when we last rendered; used to determine whether or not we need to redraw tab instances.</summary>
protected int _previousTabCount;
/// <summary>Flag indicating whether or not rendering has been suspended while we perform some operation.</summary>
protected bool _suspendRendering = false;
/// <summary>When the user is dragging a tab, this represents the horizontal offset within the tab where the user clicked to start the drag operation.</summary>
protected int? _tabClickOffset = null;
/// <summary>The width of the content area that we should use for each tab.</summary>
protected int _tabContentWidth;
/// <summary>Flag indicating whether or not a tab was being repositioned.</summary>
protected bool _wasTabRepositioning = false;
/// <summary>Default constructor that initializes the <see cref="_parentWindow" /> and <see cref="ShowAddButton" /> properties.</summary>
/// <param name="parentWindow">The parent window that this renderer instance belongs to.</param>
protected BaseTabRenderer(TitleBarTabMainForm parentWindow)
{
_parentWindow = parentWindow;
ShowAddButton = true;
TabRepositionDragDistance = 10;
TabTearDragDistance = 10;
parentWindow.Tabs.CollectionModified += Tabs_CollectionModified;
if (parentWindow._overlay != null)
{
parentWindow._overlay.MouseMove += Overlay_MouseMove;
parentWindow._overlay.MouseUp += Overlay_MouseUp;
parentWindow._overlay.MouseDown += Overlay_MouseDown;
}
}
/// <summary>Height of the tab content area; derived from the height of <see cref="_activeCenterImage" />.</summary>
public virtual int TabHeight
{
get
{
return _activeCenterImage.Height;
}
}
/// <summary>Flag indicating whether or not we should display the add button.</summary>
public bool ShowAddButton
{
get;
set;
}
/// <summary>Amount of space we should put to the left of the caption when rendering the content area of the tab.</summary>
public int CaptionMarginLeft
{
get;
set;
}
/// <summary>Amount of space that we should leave to the right of the caption when rendering the content area of the tab.</summary>
public int CaptionMarginRight
{
get;
set;
}
/// <summary>Amount of space that we should leave between the top of the content area and the top of the caption text.</summary>
public int CaptionMarginTop
{
get;
set;
}
/// <summary>Amount of space we should put to the left of the tab icon when rendering the content area of the tab.</summary>
public int IconMarginLeft
{
get;
set;
}
/// <summary>Amount of space that we should leave to the right of the icon when rendering the content area of the tab.</summary>
public int IconMarginRight
{
get;
set;
}
/// <summary>Amount of space that we should leave between the top of the content area and the top of the icon.</summary>
public int IconMarginTop
{
get;
set;
}
/// <summary>Amount of space that we should put to the left of the close button when rendering the content area of the tab.</summary>
public int CloseButtonMarginLeft
{
get;
set;
}
/// <summary>Amount of space that we should leave to the right of the close button when rendering the content area of the tab.</summary>
public int CloseButtonMarginRight
{
get;
set;
}
/// <summary>Amount of space that we should leave between the top of the content area and the top of the close button.</summary>
public int CloseButtonMarginTop
{
get;
set;
}
/// <summary>Amount of space that we should put to the left of the add tab button when rendering the content area of the tab.</summary>
public int AddButtonMarginLeft
{
get;
set;
}
/// <summary>Amount of space that we should leave to the right of the add tab button when rendering the content area of the tab.</summary>
public int AddButtonMarginRight
{
get;
set;
}
/// <summary>Amount of space that we should leave between the top of the content area and the top of the add tab button.</summary>
public int AddButtonMarginTop
{
get;
set;
}
/// <summary>
/// If the renderer overlaps the tabs (like Chrome), this is the width that the tabs should overlap by. For renderers that do not overlap tabs (like
/// Firefox), this should be left at 0.
/// </summary>
public virtual int OverlapWidth
{
get
{
return 0;
}
}
/// <summary>Horizontal distance that a tab must be dragged before it starts to be repositioned.</summary>
public int TabRepositionDragDistance
{
get;
set;
}
/// <summary>Distance that a user must drag a tab outside of the tab area before it shows up as "torn" from its parent window.</summary>
public int TabTearDragDistance
{
get;
set;
}
/// <summary>Flag indicating whether or not a tab is being repositioned.</summary>
public bool IsTabRepositioning
{
get
{
return _isTabRepositioning;
}
internal set
{
_isTabRepositioning = value;
if (!_isTabRepositioning)
{
_dragStart = null;
}
}
}
/// <summary>Width of the content area of the tabs.</summary>
public int TabContentWidth
{
get
{
return _tabContentWidth;
}
}
/// <summary>Maximum area that the tabs can occupy. Excludes the add button.</summary>
public Rectangle MaxTabArea
{
get
{
return _maxTabArea;
}
}
/// <summary>Initialize the <see cref="_dragStart" /> and <see cref="_tabClickOffset" /> fields in case the user starts dragging a tab.</summary>
/// <param name="sender">Object from which this event originated.</param>
/// <param name="e">Arguments associated with the event.</param>
protected internal virtual void Overlay_MouseDown(object sender, MouseEventArgs e)
{
_wasTabRepositioning = false;
_dragStart = e.Location;
_tabClickOffset = _parentWindow._overlay.GetRelativeCursorPosition(e.Location).X - _parentWindow.SelectedTab.Area.Location.X;
}
/// <summary>
/// End the drag operation by resetting the <see cref="_dragStart" /> and <see cref="_tabClickOffset" /> fields and setting
/// <see cref="IsTabRepositioning" /> to false.
/// </summary>
/// <param name="sender">Object from which this event originated.</param>
/// <param name="e">Arguments associated with the event.</param>
protected internal virtual void Overlay_MouseUp(object sender, MouseEventArgs e)
{
_dragStart = null;
_tabClickOffset = null;
_wasTabRepositioning = IsTabRepositioning;
IsTabRepositioning = false;
if (_wasTabRepositioning)
{
_parentWindow._overlay.Render(true);
}
}
/// <summary>
/// If the user is dragging the mouse, see if they have passed the <see cref="TabRepositionDragDistance" /> threshold and, if so, officially begin the
/// tab drag operation.
/// </summary>
/// <param name="sender">Object from which this event originated.</param>
/// <param name="e">Arguments associated with the event.</param>
protected internal virtual void Overlay_MouseMove(object sender, MouseEventArgs e)
{
if (_dragStart != null && !IsTabRepositioning &&
(Math.Abs(e.X - _dragStart.Value.X) > TabRepositionDragDistance || Math.Abs(e.Y - _dragStart.Value.Y) > TabRepositionDragDistance))
{
IsTabRepositioning = true;
}
}
/// <summary>
/// When items are added to the tabs collection, we need to ensure that the <see cref="_parentWindow" />'s minimum width is set so that we can display at
/// least each tab and its close buttons.
/// </summary>
/// <param name="sender">List of tabs in the <see cref="_parentWindow" />.</param>
/// <param name="e">Arguments associated with the event.</param>
private void Tabs_CollectionModified(object sender, NotifyCollectionChangedEventArgs e)
{
ListWithEvents<TitleBarTabItem> tabs = (ListWithEvents<TitleBarTabItem>) sender;
if (tabs.Count == 0)
{
return;
}
int minimumWidth = tabs.Sum(
tab => (tab.Active
? _activeLeftSideImage.Width
: _inactiveLeftSideImage.Width) + (tab.Active
? _activeRightSideImage.Width
: _inactiveRightSideImage.Width) +
(tab.ShowCloseButton
? tab.CloseButtonArea.Width + CloseButtonMarginLeft
: 0));
minimumWidth += OverlapWidth;
minimumWidth += (_parentWindow.ControlBox
? SystemInformation.CaptionButtonSize.Width
: 0) -
(_parentWindow.MinimizeBox
? SystemInformation.CaptionButtonSize.Width
: 0) -
(_parentWindow.MaximizeBox
? SystemInformation.CaptionButtonSize.Width
: 0) + (ShowAddButton
? _addButtonImage.Width + AddButtonMarginLeft +
AddButtonMarginRight
: 0);
_parentWindow.MinimumSize = new Size(minimumWidth, 0);
}
/// <summary>
/// Called from the <see cref="_parentWindow" /> to determine which, if any, of the <paramref name="tabs" /> the <paramref name="cursor" /> is
/// over.
/// </summary>
/// <param name="tabs">The list of tabs that we should check.</param>
/// <param name="cursor">The relative position of the cursor within the window.</param>
/// <returns>The tab within <paramref name="tabs" /> that the <paramref name="cursor" /> is over; if none, then null is returned.</returns>
public virtual TitleBarTabItem OverTab(IEnumerable<TitleBarTabItem> tabs, Point cursor)
{
TitleBarTabItem overTab = null;
foreach (TitleBarTabItem tab in tabs.Where(tab => tab.TabImage != null))
{
// We have to loop through each of the tabs in turn and check their status; if the tabs overlap, then their areas overlap as well, which means
// that we may find see that the cursor is over an inactive tab, but we need to check the active tabs as well, since they may overlap their
// areas and take precedence.
if (tab.Active && IsOverTab(tab, cursor))
{
overTab = tab;
break;
}
if (IsOverTab(tab, cursor))
{
overTab = tab;
}
}
return overTab;
}
/// <summary>
/// Helper method to detect whether the <paramref name="cursor" /> is within the given <paramref name="area" /> and, if it is, whether it is over a
/// non-transparent pixel in the given <paramref name="image" />.
/// </summary>
/// <param name="area">Screen area that we should check to see if the <paramref name="cursor" /> is within.</param>
/// <param name="image">
/// Image contained within <paramref name="area" /> that we should check to see if the <paramref name="cursor" /> is over a non-
/// transparent pixel.
/// </param>
/// <param name="cursor">Current location of the cursor.</param>
/// <returns>
/// True if the <paramref name="cursor" /> is within the given <paramref name="area" /> and is over a non-transparent pixel in the
/// <paramref name="image" />.
/// </returns>
protected bool IsOverNonTransparentArea(Rectangle area, Bitmap image, Point cursor)
{
if (!area.Contains(cursor))
{
return false;
}
// Get the relative location of the cursor within the image and then get the RGBA value of that pixel
Point relativePoint = new Point(cursor.X - area.Location.X, cursor.Y - area.Location.Y);
Color pixel = image.GetPixel(relativePoint.X, relativePoint.Y);
// If the alpha channel of the pixel is greater than 0, then we're considered "over" the image
return pixel.A > 0;
}
/// <summary>Tests whether the <paramref name="cursor" /> is hovering over the add tab button.</summary>
/// <param name="cursor">Current location of the cursor.</param>
/// <returns>
/// True if the <paramref name="cursor" /> is within <see cref="_addButtonArea" /> and is over a non-transparent pixel of
/// <see cref="_addButtonHoverImage" />, false otherwise.
/// </returns>
public virtual bool IsOverAddButton(Point cursor)
{
return !_wasTabRepositioning && IsOverNonTransparentArea(_addButtonArea, _addButtonHoverImage, cursor);
}
/// <summary>Tests whether the <paramref name="cursor" /> is hovering over the given <paramref name="tab" />.</summary>
/// <param name="tab">Tab that we are to see if the cursor is hovering over.</param>
/// <param name="cursor">Current location of the cursor.</param>
/// <returns>
/// True if the <paramref name="cursor" /> is within the <see cref="TitleBarTabItem.Area" /> of the <paramref name="tab" /> and is over a non- transparent
/// pixel of <see cref="TitleBarTabItem.TabImage" />, false otherwise.
/// </returns>
protected virtual bool IsOverTab(TitleBarTabItem tab, Point cursor)
{
return IsOverNonTransparentArea(tab.Area, tab.TabImage, cursor);
}
/// <summary>Checks to see if the <paramref name="cursor" /> is over the <see cref="TitleBarTabItem.CloseButtonArea" /> of the given <paramref name="tab" />.</summary>
/// <param name="tab">The tab whose <see cref="TitleBarTabItem.CloseButtonArea" /> we are to check to see if it contains <paramref name="cursor" />.</param>
/// <param name="cursor">Current position of the cursor.</param>
/// <returns>True if the <paramref name="tab" />'s <see cref="TitleBarTabItem.CloseButtonArea" /> contains <paramref name="cursor" />, false otherwise.</returns>
public virtual bool IsOverCloseButton(TitleBarTabItem tab, Point cursor)
{
if (!tab.ShowCloseButton || _wasTabRepositioning)
{
return false;
}
Rectangle absoluteCloseButtonArea = new Rectangle(
tab.Area.X + tab.CloseButtonArea.X, tab.Area.Y + tab.CloseButtonArea.Y, tab.CloseButtonArea.Width, tab.CloseButtonArea.Height);
return absoluteCloseButtonArea.Contains(cursor);
}
/// <summary>Renders the list of <paramref name="tabs" /> to the screen using the given <paramref name="graphicsContext" />.</summary>
/// <param name="tabs">List of tabs that we are to render.</param>
/// <param name="graphicsContext">Graphics context that we should use while rendering.</param>
/// <param name="cursor">Current location of the cursor on the screen.</param>
/// <param name="forceRedraw">Flag indicating whether or not the redraw should be forced.</param>
/// <param name="offset">Offset within <paramref name="graphicsContext" /> that the tabs should be rendered.</param>
public virtual void Render(ListWithEvents<TitleBarTabItem> tabs, Graphics graphicsContext, Point offset, Point cursor, bool forceRedraw = false)
{
if (_suspendRendering)
{
return;
}
if (tabs == null || tabs.Count == 0)
{
return;
}
Point screenCoordinates = _parentWindow.PointToScreen(_parentWindow.ClientRectangle.Location);
// Calculate the maximum tab area, excluding the add button and any minimize/maximize/close buttons in the window
_maxTabArea.Location = new Point(SystemInformation.BorderSize.Width + offset.X + screenCoordinates.X, offset.Y + screenCoordinates.Y);
_maxTabArea.Width = (_parentWindow.ClientRectangle.Width - offset.X -
(ShowAddButton
? _addButtonImage.Width + AddButtonMarginLeft +
AddButtonMarginRight
: 0) - (tabs.Count() * OverlapWidth) -
(_parentWindow.ControlBox
? SystemInformation.CaptionButtonSize.Width
: 0) -
(_parentWindow.MinimizeBox
? SystemInformation.CaptionButtonSize.Width
: 0) -
(_parentWindow.MaximizeBox
? SystemInformation.CaptionButtonSize.Width
: 0));
_maxTabArea.Height = _activeCenterImage.Height;
// Get the width of the content area for each tab by taking the parent window's client width, subtracting the left and right border widths and the
// add button area (if applicable) and then dividing by the number of tabs
int tabContentWidth = Math.Min(_activeCenterImage.Width, Convert.ToInt32(Math.Floor(Convert.ToDouble(_maxTabArea.Width / tabs.Count()))));
// Determine if we need to redraw the TabImage properties for each tab by seeing if the content width that we calculated above is equal to content
// width we had in the previous rendering pass
bool redraw = (tabContentWidth != _tabContentWidth || forceRedraw);
if (redraw)
{
_tabContentWidth = tabContentWidth;
}
int i = tabs.Count - 1;
List<Tuple<TitleBarTabItem, Rectangle>> activeTabs = new List<Tuple<TitleBarTabItem, Rectangle>>();
// Render the background image
if (_background != null)
{
graphicsContext.DrawImage(_background, offset.X, offset.Y, _parentWindow.Width, _activeCenterImage.Height);
}
int selectedIndex = tabs.FindIndex(t => t.Active);
if (selectedIndex != -1)
{
Rectangle tabArea = new Rectangle(
SystemInformation.BorderSize.Width + offset.X +
(selectedIndex * (tabContentWidth + _activeLeftSideImage.Width + _activeRightSideImage.Width - OverlapWidth)),
offset.Y, tabContentWidth + _activeLeftSideImage.Width + _activeRightSideImage.Width,
_activeCenterImage.Height);
if (IsTabRepositioning && _tabClickOffset != null)
{
// Make sure that the user doesn't move the tab past the beginning of the list or the outside of the window
tabArea.X = cursor.X - _tabClickOffset.Value;
tabArea.X = Math.Max(SystemInformation.BorderSize.Width + offset.X, tabArea.X);
tabArea.X =
Math.Min(
SystemInformation.BorderSize.Width + (_parentWindow.WindowState == FormWindowState.Maximized
? _parentWindow.ClientRectangle.Width - (_parentWindow.ControlBox
? SystemInformation.CaptionButtonSize.Width
: 0) -
(_parentWindow.MinimizeBox
? SystemInformation.CaptionButtonSize.Width
: 0) -
(_parentWindow.MaximizeBox
? SystemInformation.CaptionButtonSize.Width
: 0)
: _parentWindow.ClientRectangle.Width) - tabArea.Width, tabArea.X);
int dropIndex = 0;
// Figure out which slot the active tab is being "dropped" over
if (tabArea.X - SystemInformation.BorderSize.Width - offset.X - TabRepositionDragDistance > 0)
{
dropIndex =
Math.Min(
Convert.ToInt32(
Math.Round(
Convert.ToDouble(tabArea.X - SystemInformation.BorderSize.Width - offset.X - TabRepositionDragDistance) /
Convert.ToDouble(tabArea.Width - OverlapWidth))), tabs.Count - 1);
}
// If the tab has been moved over another slot, move the tab object in the window's tab list
if (dropIndex != selectedIndex)
{
TitleBarTabItem tab = tabs[selectedIndex];
_parentWindow.Tabs.SuppressEvents();
_parentWindow.Tabs.Remove(tab);
_parentWindow.Tabs.Insert(dropIndex, tab);
_parentWindow.Tabs.ResumeEvents();
}
}
activeTabs.Add(new Tuple<TitleBarTabItem, Rectangle>(tabs[selectedIndex], tabArea));
}
// Loop through the tabs in reverse order since we need the ones farthest on the left to overlap those to their right
foreach (TitleBarTabItem tab in ((IEnumerable<TitleBarTabItem>) tabs).Reverse())
{
Rectangle tabArea =
new Rectangle(
SystemInformation.BorderSize.Width + offset.X +
(i * (tabContentWidth + _activeLeftSideImage.Width + _activeRightSideImage.Width - OverlapWidth)),
offset.Y, tabContentWidth + _activeLeftSideImage.Width + _activeRightSideImage.Width,
_activeCenterImage.Height);
// If we need to redraw the tab image, null out the property so that it will be recreated in the call to Render() below
if (redraw)
{
tab.TabImage = null;
}
// In this first pass, we only render the inactive tabs since we need the active tabs to show up on top of everything else
if (!tab.Active)
{
Render(graphicsContext, tab, tabArea, cursor);
}
i--;
}
// In the second pass, render all of the active tabs identified in the previous pass
foreach (Tuple<TitleBarTabItem, Rectangle> tab in activeTabs)
{
Render(graphicsContext, tab.Item1, tab.Item2, cursor);
}
_previousTabCount = tabs.Count;
// Render the add tab button to the screen
if (ShowAddButton && !IsTabRepositioning)
{
_addButtonArea =
new Rectangle(
(_previousTabCount *
(tabContentWidth + _activeLeftSideImage.Width + _activeRightSideImage.Width - OverlapWidth)) +
_activeRightSideImage.Width + AddButtonMarginLeft + offset.X,
AddButtonMarginTop + offset.Y, _addButtonImage.Width, _addButtonImage.Height);
bool cursorOverAddButton = IsOverAddButton(cursor);
graphicsContext.DrawImage(
cursorOverAddButton
? _addButtonHoverImage
: _addButtonImage, _addButtonArea, 0, 0, cursorOverAddButton
? _addButtonHoverImage.Width
: _addButtonImage.Width,
cursorOverAddButton
? _addButtonHoverImage.Height
: _addButtonImage.Height, GraphicsUnit.Pixel);
}
}
/// <summary>Internal method for rendering an individual <paramref name="tab" /> to the screen.</summary>
/// <param name="graphicsContext">Graphics context to use when rendering the tab.</param>
/// <param name="tab">Individual tab that we are to render.</param>
/// <param name="area">Area of the screen that the tab should be rendered to.</param>
/// <param name="cursor">Current position of the cursor.</param>
protected virtual void Render(Graphics graphicsContext, TitleBarTabItem tab, Rectangle area, Point cursor)
{
if (_suspendRendering)
{
return;
}
// If we need to redraw the tab image
if (tab.TabImage == null)
{
// We render the tab to an internal property so that we don't necessarily have to redraw it in every rendering pass, only if its width or
// status have changed
tab.TabImage = new Bitmap(
area.Width, tab.Active
? _activeCenterImage.Height
: _inactiveCenterImage.Height);
using (Graphics tabGraphicsContext = Graphics.FromImage(tab.TabImage))
{
// Draw the left, center, and right portions of the tab
tabGraphicsContext.DrawImage(
tab.Active
? _activeLeftSideImage
: _inactiveLeftSideImage, new Rectangle(
0, 0, tab.Active
? _activeLeftSideImage
.Width
: _inactiveLeftSideImage
.Width,
tab.Active
? _activeLeftSideImage.
Height
: _inactiveLeftSideImage
.Height), 0, 0,
tab.Active
? _activeLeftSideImage.Width
: _inactiveLeftSideImage.Width, tab.Active
? _activeLeftSideImage.Height
: _inactiveLeftSideImage.Height,
GraphicsUnit.Pixel);
tabGraphicsContext.DrawImage(
tab.Active
? _activeCenterImage
: _inactiveCenterImage, new Rectangle(
(tab.Active
? _activeLeftSideImage.
Width
: _inactiveLeftSideImage
.Width), 0,
_tabContentWidth, tab.Active
? _activeCenterImage
.
Height
: _inactiveCenterImage
.
Height),
0, 0, _tabContentWidth, tab.Active
? _activeCenterImage.Height
: _inactiveCenterImage.Height,
GraphicsUnit.Pixel);
tabGraphicsContext.DrawImage(
tab.Active
? _activeRightSideImage
: _inactiveRightSideImage, new Rectangle(
(tab.Active
? _activeLeftSideImage
.Width
: _inactiveLeftSideImage
.Width) +
_tabContentWidth, 0,
tab.Active
? _activeRightSideImage
.Width
: _inactiveRightSideImage
.Width,
tab.Active
? _activeRightSideImage
.Height
: _inactiveRightSideImage
.Height), 0, 0,
tab.Active
? _activeRightSideImage.Width
: _inactiveRightSideImage.Width, tab.Active
? _activeRightSideImage.Height
: _inactiveRightSideImage.
Height,
GraphicsUnit.Pixel);
// Draw the close button
if (tab.ShowCloseButton)
{
Image closeButtonImage = IsOverCloseButton(tab, cursor)
? _closeButtonHoverImage
: _closeButtonImage;
tab.CloseButtonArea = new Rectangle(
area.Width - (tab.Active
? _activeRightSideImage.Width
: _inactiveRightSideImage.Width) -
CloseButtonMarginRight - closeButtonImage.Width,
CloseButtonMarginTop, closeButtonImage.Width,
closeButtonImage.Height);
tabGraphicsContext.DrawImage(
closeButtonImage, tab.CloseButtonArea, 0, 0,
closeButtonImage.Width, closeButtonImage.Height,
GraphicsUnit.Pixel);
}
}
tab.Area = area;
}
// Render the tab's saved image to the screen
graphicsContext.DrawImage(
tab.TabImage, area, 0, 0, tab.TabImage.Width, tab.TabImage.Height,
GraphicsUnit.Pixel);
// Render the icon for the tab's content, if it exists and there's room for it in the tab's content area
if (tab.Content.ShowIcon && _tabContentWidth > 16 + IconMarginLeft + (tab.ShowCloseButton
? CloseButtonMarginLeft +
tab.CloseButtonArea.Width +
CloseButtonMarginRight
: 0))
{
graphicsContext.DrawIcon(
new Icon(tab.Content.Icon, 16, 16),
new Rectangle(area.X + OverlapWidth + IconMarginLeft, IconMarginTop + area.Y, 16, 16));
}
// Render the caption for the tab's content if there's room for it in the tab's content area
if (_tabContentWidth > (tab.Content.ShowIcon
? 16 + IconMarginLeft + IconMarginRight
: 0) + CaptionMarginLeft + CaptionMarginRight + (tab.ShowCloseButton
? CloseButtonMarginLeft +
tab.CloseButtonArea.Width +
CloseButtonMarginRight
: 0))
{
graphicsContext.DrawString(
tab.Caption, SystemFonts.CaptionFont, Brushes.Black,
new Rectangle(
area.X + OverlapWidth + CaptionMarginLeft + (tab.Content.ShowIcon
? IconMarginLeft +
16 +
IconMarginRight
: 0),
CaptionMarginTop + area.Y,
_tabContentWidth - (tab.Content.ShowIcon
? IconMarginLeft + 16 + IconMarginRight
: 0) - (tab.ShowCloseButton
? _closeButtonImage.Width +
CloseButtonMarginRight +
CloseButtonMarginLeft
: 0), tab.TabImage.Height),
new StringFormat(StringFormatFlags.NoWrap)
{
Trimming = StringTrimming.EllipsisCharacter
});
}
}
/// <summary>
/// Called when a torn tab is dragged into the <see cref="TitleBarTabMainForm.TabDropArea" /> of <see cref="_parentWindow" />. Places the tab in the list and
/// sets <see cref="IsTabRepositioning" /> to true to simulate the user continuing to drag the tab around in the window.
/// </summary>
/// <param name="tab">Tab that was dragged into this window.</param>
/// <param name="cursorLocation">Location of the user's cursor.</param>
internal virtual void CombineTab(TitleBarTabItem tab, Point cursorLocation)
{
// Stop rendering to prevent weird stuff from happening like the wrong tab being focused
_suspendRendering = true;
// Find out where to insert the tab in the list
int dropIndex = _parentWindow.Tabs.FindIndex(t => t.Area.Left <= cursorLocation.X && t.Area.Right >= cursorLocation.X);
// Simulate the user having clicked in the middle of the tab when they started dragging it so that the tab will move correctly within the window
// when the user continues to move the mouse
if (_parentWindow.Tabs.Count > 0)
{
_tabClickOffset = _parentWindow.Tabs.First().Area.Width / 2;
}
else
{
_tabClickOffset = 0;
}
IsTabRepositioning = true;
tab.Parent = _parentWindow;
if (dropIndex == -1)
{
_parentWindow.Tabs.Add(tab);
dropIndex = _parentWindow.Tabs.Count - 1;
}
else
{
_parentWindow.Tabs.Insert(dropIndex, tab);
}
// Resume rendering
_suspendRendering = false;
_parentWindow.SelectedTabIndex = dropIndex;
_parentWindow.ResizeTabContents();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.AspNetCore.Routing;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.Navigation;
using OrchardCore.Queries.ViewModels;
using OrchardCore.Routing;
using OrchardCore.Settings;
using YesSql;
namespace OrchardCore.Queries.Controllers
{
public class AdminController : Controller
{
private readonly IAuthorizationService _authorizationService;
private readonly ISiteService _siteService;
private readonly INotifier _notifier;
private readonly IQueryManager _queryManager;
private readonly IEnumerable<IQuerySource> _querySources;
private readonly IDisplayManager<Query> _displayManager;
private readonly ISession _session;
private readonly IUpdateModelAccessor _updateModelAccessor;
private readonly IHtmlLocalizer H;
private readonly dynamic New;
public AdminController(
IDisplayManager<Query> displayManager,
IAuthorizationService authorizationService,
ISiteService siteService,
IShapeFactory shapeFactory,
IHtmlLocalizer<AdminController> htmlLocalizer,
INotifier notifier,
IQueryManager queryManager,
IEnumerable<IQuerySource> querySources,
ISession session,
IUpdateModelAccessor updateModelAccessor)
{
_session = session;
_displayManager = displayManager;
_authorizationService = authorizationService;
_siteService = siteService;
_queryManager = queryManager;
_querySources = querySources;
_updateModelAccessor = updateModelAccessor;
New = shapeFactory;
_notifier = notifier;
H = htmlLocalizer;
}
public async Task<IActionResult> Index(QueryIndexOptions options, PagerParameters pagerParameters)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageQueries))
{
return Forbid();
}
var siteSettings = await _siteService.GetSiteSettingsAsync();
var pager = new Pager(pagerParameters, siteSettings.PageSize);
// default options
if (options == null)
{
options = new QueryIndexOptions();
}
var queries = await _queryManager.ListQueriesAsync();
queries = queries.OrderBy(x => x.Name);
if (!string.IsNullOrWhiteSpace(options.Search))
{
queries = queries.Where(q => q.Name.IndexOf(options.Search, StringComparison.OrdinalIgnoreCase) >= 0);
}
var results = queries
.Skip(pager.GetStartIndex())
.Take(pager.PageSize)
.ToList();
// Maintain previous route data when generating page links
var routeData = new RouteData();
routeData.Values.Add("Options.Search", options.Search);
var pagerShape = (await New.Pager(pager)).TotalItemCount(queries.Count()).RouteData(routeData);
var model = new QueriesIndexViewModel
{
Queries = new List<QueryEntry>(),
Options = options,
Pager = pagerShape,
QuerySourceNames = _querySources.Select(x => x.Name).ToList()
};
foreach (var query in results)
{
model.Queries.Add(new QueryEntry
{
Query = query,
Shape = await _displayManager.BuildDisplayAsync(query, _updateModelAccessor.ModelUpdater, "SummaryAdmin")
});
}
return View(model);
}
[HttpPost, ActionName("Index")]
[FormValueRequired("submit.Filter")]
public ActionResult IndexFilterPOST(QueriesIndexViewModel model)
{
return RedirectToAction("Index", new RouteValueDictionary {
{ "Options.Search", model.Options.Search }
});
}
public async Task<IActionResult> Create(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageQueries))
{
return Forbid();
}
var query = _querySources.FirstOrDefault(x => x.Name == id)?.Create();
if (query == null)
{
return NotFound();
}
var model = new QueriesCreateViewModel
{
Editor = await _displayManager.BuildEditorAsync(query, updater: _updateModelAccessor.ModelUpdater, isNew: true),
SourceName = id
};
return View(model);
}
[HttpPost, ActionName(nameof(Create))]
public async Task<IActionResult> CreatePost(QueriesCreateViewModel model)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageQueries))
{
return Forbid();
}
var query = _querySources.FirstOrDefault(x => x.Name == model.SourceName)?.Create();
if (query == null)
{
return NotFound();
}
var editor = await _displayManager.UpdateEditorAsync(query, updater: _updateModelAccessor.ModelUpdater, isNew: true);
if (ModelState.IsValid)
{
await _queryManager.SaveQueryAsync(query.Name, query);
_notifier.Success(H["Query created successfully"]);
return RedirectToAction("Index");
}
// If we got this far, something failed, redisplay form
model.Editor = editor;
return View(model);
}
public async Task<IActionResult> Edit(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageQueries))
{
return Forbid();
}
var query = await _queryManager.GetQueryAsync(id);
if (query == null)
{
return NotFound();
}
var model = new QueriesEditViewModel
{
SourceName = query.Source,
Name = query.Name,
Schema = query.Schema,
Editor = await _displayManager.BuildEditorAsync(query, updater: _updateModelAccessor.ModelUpdater, isNew: false)
};
return View(model);
}
[HttpPost, ActionName("Edit")]
public async Task<IActionResult> EditPost(QueriesEditViewModel model)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageQueries))
{
return Forbid();
}
var query = (await _queryManager.LoadQueryAsync(model.Name));
if (query == null)
{
return NotFound();
}
var editor = await _displayManager.UpdateEditorAsync(query, updater: _updateModelAccessor.ModelUpdater, isNew: false);
if (ModelState.IsValid)
{
await _queryManager.SaveQueryAsync(model.Name, query);
_notifier.Success(H["Query updated successfully"]);
return RedirectToAction("Index");
}
model.Editor = editor;
// If we got this far, something failed, redisplay form
return View(model);
}
[HttpPost]
public async Task<IActionResult> Delete(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageQueries))
{
return Forbid();
}
var query = await _queryManager.LoadQueryAsync(id);
if (query == null)
{
return NotFound();
}
await _queryManager.DeleteQueryAsync(id);
_notifier.Success(H["Query deleted successfully"]);
return RedirectToAction("Index");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using TicTacToe.Web.Areas.HelpPage.ModelDescriptions;
using TicTacToe.Web.Areas.HelpPage.Models;
namespace TicTacToe.Web.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Cache
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Expiry;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cache.Query.Continuous;
using Apache.Ignite.Core.Cluster;
/// <summary>
/// Wraps IGridCache implementation to simplify async mode testing.
/// </summary>
internal class CacheTestAsyncWrapper<TK, TV> : ICache<TK, TV>
{
private readonly ICache<TK, TV> _cache;
/// <summary>
/// Initializes a new instance of the <see cref="CacheTestAsyncWrapper{K, V}"/> class.
/// </summary>
/// <param name="cache">The cache to be wrapped.</param>
public CacheTestAsyncWrapper(ICache<TK, TV> cache)
{
Debug.Assert(cache != null);
_cache = cache;
}
/** <inheritDoc /> */
public string Name
{
get { return _cache.Name; }
}
/** <inheritDoc /> */
public IIgnite Ignite
{
get { return _cache.Ignite; }
}
/** <inheritDoc /> */
public CacheConfiguration GetConfiguration()
{
return _cache.GetConfiguration();
}
/** <inheritDoc /> */
public bool IsEmpty()
{
return _cache.IsEmpty();
}
/** <inheritDoc /> */
public bool IsKeepBinary
{
get { return _cache.IsKeepBinary; }
}
/** <inheritDoc /> */
public bool IsAllowAtomicOpsInTx
{
get { return false; }
}
/** <inheritDoc /> */
public ICache<TK, TV> WithSkipStore()
{
return _cache.WithSkipStore().WrapAsync();
}
/** <inheritDoc /> */
public ICache<TK, TV> WithExpiryPolicy(IExpiryPolicy plc)
{
return _cache.WithExpiryPolicy(plc).WrapAsync();
}
/** <inheritDoc /> */
public ICache<TK1, TV1> WithKeepBinary<TK1, TV1>()
{
return _cache.WithKeepBinary<TK1, TV1>().WrapAsync();
}
/** <inheritDoc /> */
public ICache<TK, TV> WithAllowAtomicOpsInTx()
{
return this;
}
/** <inheritDoc /> */
public void LoadCache(ICacheEntryFilter<TK, TV> p, params object[] args)
{
_cache.LoadCacheAsync(p, args).WaitResult();
}
/** <inheritDoc /> */
public Task LoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args)
{
return _cache.LoadCacheAsync(p, args);
}
/** <inheritDoc /> */
public void LocalLoadCache(ICacheEntryFilter<TK, TV> p, params object[] args)
{
_cache.LocalLoadCacheAsync(p, args).WaitResult();
}
/** <inheritDoc /> */
public Task LocalLoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args)
{
return _cache.LocalLoadCacheAsync(p, args);
}
/** <inheritDoc /> */
public void LoadAll(IEnumerable<TK> keys, bool replaceExistingValues)
{
_cache.LoadAll(keys, replaceExistingValues);
}
/** <inheritDoc /> */
public Task LoadAllAsync(IEnumerable<TK> keys, bool replaceExistingValues)
{
return _cache.LoadAllAsync(keys, replaceExistingValues);
}
/** <inheritDoc /> */
public bool ContainsKey(TK key)
{
return _cache.ContainsKeyAsync(key).GetResult();
}
/** <inheritDoc /> */
public Task<bool> ContainsKeyAsync(TK key)
{
return _cache.ContainsKeyAsync(key);
}
/** <inheritDoc /> */
public bool ContainsKeys(IEnumerable<TK> keys)
{
return _cache.ContainsKeysAsync(keys).GetResult();
}
/** <inheritDoc /> */
public Task<bool> ContainsKeysAsync(IEnumerable<TK> keys)
{
return _cache.ContainsKeysAsync(keys);
}
/** <inheritDoc /> */
public TV LocalPeek(TK key, params CachePeekMode[] modes)
{
return _cache.LocalPeek(key, modes);
}
/** <inheritDoc /> */
public bool TryLocalPeek(TK key, out TV value, params CachePeekMode[] modes)
{
return _cache.TryLocalPeek(key, out value, modes);
}
/** <inheritDoc /> */
public TV this[TK key]
{
get { return _cache[key]; }
set { _cache[key] = value; }
}
/** <inheritDoc /> */
public TV Get(TK key)
{
return _cache.GetAsync(key).GetResult();
}
/** <inheritDoc /> */
public Task<TV> GetAsync(TK key)
{
return _cache.GetAsync(key);
}
/** <inheritDoc /> */
public bool TryGet(TK key, out TV value)
{
return _cache.TryGet(key, out value);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> TryGetAsync(TK key)
{
return _cache.TryGetAsync(key);
}
/** <inheritDoc /> */
public ICollection<ICacheEntry<TK, TV>> GetAll(IEnumerable<TK> keys)
{
return _cache.GetAllAsync(keys).GetResult();
}
/** <inheritDoc /> */
public Task<ICollection<ICacheEntry<TK, TV>>> GetAllAsync(IEnumerable<TK> keys)
{
return _cache.GetAllAsync(keys);
}
/** <inheritDoc /> */
public void Put(TK key, TV val)
{
_cache.PutAsync(key, val).WaitResult();
}
/** <inheritDoc /> */
public Task PutAsync(TK key, TV val)
{
return _cache.PutAsync(key, val);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndPut(TK key, TV val)
{
return _cache.GetAndPutAsync(key, val).GetResult();
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutAsync(TK key, TV val)
{
return _cache.GetAndPutAsync(key, val);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndReplace(TK key, TV val)
{
return _cache.GetAndReplaceAsync(key, val).GetResult();
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndReplaceAsync(TK key, TV val)
{
return _cache.GetAndReplaceAsync(key, val);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndRemove(TK key)
{
return _cache.GetAndRemoveAsync(key).GetResult();
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndRemoveAsync(TK key)
{
return _cache.GetAndRemoveAsync(key);
}
/** <inheritDoc /> */
public bool PutIfAbsent(TK key, TV val)
{
return _cache.PutIfAbsentAsync(key, val).GetResult();
}
/** <inheritDoc /> */
public Task<bool> PutIfAbsentAsync(TK key, TV val)
{
return _cache.PutIfAbsentAsync(key, val);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndPutIfAbsent(TK key, TV val)
{
return _cache.GetAndPutIfAbsentAsync(key, val).GetResult();
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutIfAbsentAsync(TK key, TV val)
{
return _cache.GetAndPutIfAbsentAsync(key, val);
}
/** <inheritDoc /> */
public bool Replace(TK key, TV val)
{
return _cache.ReplaceAsync(key, val).GetResult();
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV val)
{
return _cache.ReplaceAsync(key, val);
}
/** <inheritDoc /> */
public bool Replace(TK key, TV oldVal, TV newVal)
{
return _cache.ReplaceAsync(key, oldVal, newVal).GetResult();
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV oldVal, TV newVal)
{
return _cache.ReplaceAsync(key, oldVal, newVal);
}
/** <inheritDoc /> */
public void PutAll(IEnumerable<KeyValuePair<TK, TV>> vals)
{
_cache.PutAllAsync(vals).WaitResult();
}
/** <inheritDoc /> */
public Task PutAllAsync(IEnumerable<KeyValuePair<TK, TV>> vals)
{
return _cache.PutAllAsync(vals);
}
/** <inheritDoc /> */
public void LocalEvict(IEnumerable<TK> keys)
{
_cache.LocalEvict(keys);
}
/** <inheritDoc /> */
public void Clear()
{
_cache.ClearAsync().WaitResult();
}
/** <inheritDoc /> */
public Task ClearAsync()
{
return _cache.ClearAsync();
}
/** <inheritDoc /> */
public void Clear(TK key)
{
_cache.ClearAsync(key).WaitResult();
}
/** <inheritDoc /> */
public Task ClearAsync(TK key)
{
return _cache.ClearAsync(key);
}
/** <inheritDoc /> */
public void ClearAll(IEnumerable<TK> keys)
{
_cache.ClearAllAsync(keys).WaitResult();
}
/** <inheritDoc /> */
public Task ClearAllAsync(IEnumerable<TK> keys)
{
return _cache.ClearAllAsync(keys);
}
/** <inheritDoc /> */
public void LocalClear(TK key)
{
_cache.LocalClear(key);
}
/** <inheritDoc /> */
public void LocalClearAll(IEnumerable<TK> keys)
{
_cache.LocalClearAll(keys);
}
/** <inheritDoc /> */
public bool Remove(TK key)
{
return _cache.RemoveAsync(key).GetResult();
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key)
{
return _cache.RemoveAsync(key);
}
/** <inheritDoc /> */
public bool Remove(TK key, TV val)
{
return _cache.RemoveAsync(key, val).GetResult();
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key, TV val)
{
return _cache.RemoveAsync(key, val);
}
/** <inheritDoc /> */
public void RemoveAll(IEnumerable<TK> keys)
{
Task task = _cache.RemoveAllAsync(keys);
task.WaitResult();
}
/** <inheritDoc /> */
public Task RemoveAllAsync(IEnumerable<TK> keys)
{
return _cache.RemoveAllAsync(keys);
}
/** <inheritDoc /> */
public void RemoveAll()
{
Task task = _cache.RemoveAllAsync();
task.WaitResult();
}
/** <inheritDoc /> */
public Task RemoveAllAsync()
{
return _cache.RemoveAllAsync();
}
/** <inheritDoc /> */
public int GetLocalSize(params CachePeekMode[] modes)
{
return _cache.GetLocalSize(modes);
}
/** <inheritDoc /> */
public int GetSize(params CachePeekMode[] modes)
{
return _cache.GetSizeAsync(modes).GetResult();
}
/** <inheritDoc /> */
public Task<int> GetSizeAsync(params CachePeekMode[] modes)
{
return _cache.GetSizeAsync(modes);
}
/** <inheritDoc /> */
public long GetSizeLong(params CachePeekMode[] modes)
{
return _cache.GetSizeLongAsync(modes).GetResult();
}
/** <inheritDoc /> */
public long GetSizeLong(int partition, params CachePeekMode[] modes)
{
return _cache.GetSizeLongAsync(partition, modes).GetResult();
}
/** <inheritDoc /> */
public Task<long> GetSizeLongAsync(params CachePeekMode[] modes)
{
return _cache.GetSizeLongAsync(modes);
}
/** <inheritDoc /> */
public Task<long> GetSizeLongAsync(int partition, params CachePeekMode[] modes)
{
return _cache.GetSizeLongAsync(partition, modes);
}
/** <inheritDoc /> */
public long GetLocalSizeLong(params CachePeekMode[] modes)
{
return _cache.GetLocalSizeLong(modes);
}
/** <inheritDoc /> */
public long GetLocalSizeLong(int partition, params CachePeekMode[] modes)
{
return _cache.GetLocalSizeLong(partition, modes);
}
/** <inheritDoc /> */
public IQueryCursor<ICacheEntry<TK, TV>> Query(QueryBase qry)
{
return _cache.Query(qry);
}
/** <inheritDoc /> */
public IFieldsQueryCursor Query(SqlFieldsQuery qry)
{
return _cache.Query(qry);
}
/** <inheritDoc /> */
[Obsolete]
public IQueryCursor<IList> QueryFields(SqlFieldsQuery qry)
{
return _cache.QueryFields(qry);
}
/** <inheritDoc /> */
IContinuousQueryHandle ICache<TK, TV>.QueryContinuous(ContinuousQuery<TK, TV> qry)
{
return _cache.QueryContinuous(qry);
}
/** <inheritDoc /> */
public IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuous(ContinuousQuery<TK, TV> qry, QueryBase initialQry)
{
return _cache.QueryContinuous(qry, initialQry);
}
/** <inheritDoc /> */
public IEnumerable<ICacheEntry<TK, TV>> GetLocalEntries(params CachePeekMode[] peekModes)
{
return _cache.GetLocalEntries(peekModes);
}
/** <inheritDoc /> */
public TRes Invoke<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
return _cache.InvokeAsync(key, processor, arg).GetResult();
}
/** <inheritDoc /> */
public Task<TRes> InvokeAsync<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
return _cache.InvokeAsync(key, processor, arg);
}
/** <inheritDoc /> */
public ICollection<ICacheEntryProcessorResult<TK, TRes>> InvokeAll<TArg, TRes>(IEnumerable<TK> keys,
ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
return _cache.InvokeAllAsync(keys, processor, arg).GetResult();
}
/** <inheritDoc /> */
public Task<ICollection<ICacheEntryProcessorResult<TK, TRes>>> InvokeAllAsync<TArg, TRes>(IEnumerable<TK> keys, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
return _cache.InvokeAllAsync(keys, processor, arg);
}
/** <inheritDoc /> */
public ICacheLock Lock(TK key)
{
return _cache.Lock(key);
}
/** <inheritDoc /> */
public ICacheLock LockAll(IEnumerable<TK> keys)
{
return _cache.LockAll(keys);
}
/** <inheritDoc /> */
public bool IsLocalLocked(TK key, bool byCurrentThread)
{
return _cache.IsLocalLocked(key, byCurrentThread);
}
/** <inheritDoc /> */
public ICacheMetrics GetMetrics()
{
return _cache.GetMetrics();
}
/** <inheritDoc /> */
public ICacheMetrics GetMetrics(IClusterGroup clusterGroup)
{
return _cache.GetMetrics(clusterGroup);
}
/** <inheritDoc /> */
public ICacheMetrics GetLocalMetrics()
{
return _cache.GetLocalMetrics();
}
/** <inheritDoc /> */
public Task Rebalance()
{
return _cache.Rebalance();
}
/** <inheritDoc /> */
public ICache<TK, TV> WithNoRetries()
{
return _cache.WithNoRetries();
}
/** <inheritDoc /> */
public ICache<TK, TV> WithPartitionRecover()
{
return _cache.WithPartitionRecover();
}
/** <inheritDoc /> */
public ICollection<int> GetLostPartitions()
{
return _cache.GetLostPartitions();
}
/** <inheritDoc /> */
public IEnumerator<ICacheEntry<TK, TV>> GetEnumerator()
{
return _cache.GetEnumerator();
}
/** <inheritDoc /> */
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IQueryMetrics GetQueryMetrics()
{
return _cache.GetQueryMetrics();
}
public void ResetQueryMetrics()
{
_cache.ResetQueryMetrics();
}
public void PreloadPartition(int partition)
{
_cache.PreloadPartitionAsync(partition).WaitResult();
}
public Task PreloadPartitionAsync(int partition)
{
return _cache.PreloadPartitionAsync(partition);
}
public bool LocalPreloadPartition(int partition)
{
return _cache.LocalPreloadPartition(partition);
}
}
/// <summary>
/// Extension methods for IGridCache.
/// </summary>
public static class CacheExtensions
{
/// <summary>
/// Wraps specified instance into GridCacheTestAsyncWrapper.
/// </summary>
public static ICache<TK, TV> WrapAsync<TK, TV>(this ICache<TK, TV> cache)
{
return new CacheTestAsyncWrapper<TK, TV>(cache);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Net;
namespace DDay.Update
{
public class Manifest
{
#region Static Protected Methods
static protected XmlNamespaceManager GetNamespaceManager(XmlDocument doc)
{
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace(string.Empty, "urn:schemas-microsoft-com:asm.v2");
nsmgr.AddNamespace("dsig", "http://www.w3.org/2000/09/xmldsig#");
nsmgr.AddNamespace("asmv1", "urn:schemas-microsoft-com:asm.v1");
nsmgr.AddNamespace("asmv2", "urn:schemas-microsoft-com:asm.v2");
nsmgr.AddNamespace("xrml", "urn:mpeg:mpeg21:2003:01-REL-R-NS");
nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
return nsmgr;
}
#endregion
#region Private Fields
private XmlDocument _Document;
private XmlNamespaceManager _NamespaceManager;
private List<Dependency> _Dependencies;
private Uri _Uri;
private string _Username;
private string _Password;
private string _Domain;
private Dependency _Parent = null;
private AssemblyIdentity _AssemblyIdentity;
private bool _SuccessfullyLoaded = false;
#endregion
#region Protected Properties
protected XmlDocument Document
{
get { return _Document; }
set { _Document = value; }
}
protected XmlNamespaceManager NamespaceManager
{
get { return _NamespaceManager; }
set { _NamespaceManager = value; }
}
#endregion
#region Public Properties
public List<Dependency> Dependencies
{
get { return _Dependencies; }
set { _Dependencies = value; }
}
public IEnumerable<DependentAssembly> DependentAssemblies
{
get
{
foreach (Dependency dependency in Dependencies)
{
if (dependency is DependentAssembly)
yield return (DependentAssembly)dependency;
foreach (DependentAssembly d in dependency.DependentAssemblies)
yield return d;
}
}
}
public Uri Uri
{
get { return _Uri; }
set { _Uri = value; }
}
public string Username
{
get { return _Username; }
set { _Username = value; }
}
public string Password
{
get { return _Password; }
set { _Password = value; }
}
public string Domain
{
get { return _Domain; }
set { _Domain = value; }
}
public Dependency Parent
{
get { return _Parent; }
set { _Parent = value; }
}
public AssemblyIdentity AssemblyIdentity
{
get { return _AssemblyIdentity; }
set { _AssemblyIdentity = value; }
}
public Version CurrentPublishedVersion
{
get
{
if (Document != null)
{
// Determine the version of the application from the server
XmlElement elm = Document.SelectSingleNode(
"/asmv1:assembly/asmv1:assemblyIdentity",
NamespaceManager) as XmlElement;
return new Version(elm.Attributes["version"].Value);
}
return new Version(0, 0, 0, 0);
}
}
public DeploymentManifest DeploymentManifest
{
get
{
Manifest manifest = this;
while (manifest.Parent != null &&
!(manifest is DeploymentManifest))
manifest = manifest.Parent.Parent;
if (manifest is DeploymentManifest)
return (DeploymentManifest)manifest;
else return null;
}
}
public bool SuccessfullyLoaded
{
get { return _SuccessfullyLoaded; }
}
#endregion
#region Constructors
public Manifest()
{
Dependencies = new List<Dependency>();
}
public Manifest(Uri uri) : this(null, uri, null, null, null) {}
public Manifest(Uri uri, string username, string password, string domain)
: this(null, uri, username, password, domain) {}
public Manifest(Dependency parent, Uri uri, string username, string password, string domain)
: this()
{
Parent = parent;
LoadFromUri(uri, username, password, domain);
}
#endregion
#region Public Methods
/// <summary>
/// Given a URI downloads the XML Manifest file
/// </summary>
/// <returns>An XML Document with the contents of the manifest</returns>
public XmlDocument LoadFromUri(Uri uri) { return LoadFromUri(uri, null, null, null); }
virtual public XmlDocument LoadFromUri(Uri uri, string username, string password, string domain)
{
WebClient client = new WebClient();
if (username != null &&
password != null)
client.Credentials = new NetworkCredential(username, password, domain);
// Create an XPath document using the downloaded manifest
Stream clientStream = client.OpenRead(uri);
Document = new XmlDocument();
Document.Load(clientStream);
clientStream.Close();
// Load a namespace manager for this Manifest
NamespaceManager = GetNamespaceManager(Document);
// Record Uri, username, password, and domain
Uri = uri;
Username = username;
Password = password;
Domain = domain;
// Load assembly identity
XmlNode aiNode = Document.SelectSingleNode(
"/asmv1:assembly/asmv1:assemblyIdentity",
NamespaceManager);
if (aiNode != null)
{
AssemblyIdentity = new AssemblyIdentity(this, aiNode, NamespaceManager);
}
// Load each dependency
foreach (XmlNode node in Document.SelectNodes(
"/asmv1:assembly/asmv2:dependency",
NamespaceManager))
{
Dependencies.Add(new Dependency(this, node, NamespaceManager));
}
_SuccessfullyLoaded = true;
return Document;
}
virtual public void Save(string filePath)
{
// Create the directory, if it doesn't exist!
string directoryName = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directoryName))
Directory.CreateDirectory(directoryName);
FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
XmlTextWriter xtw = new XmlTextWriter(fs, Encoding.UTF8);
xtw.Formatting = Formatting.Indented;
xtw.Indentation = 4;
xtw.IndentChar = ' ';
Document.WriteTo(xtw);
xtw.Close();
}
#endregion
}
}
| |
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
namespace AllReady.Models
{
public class AllReadyContext : IdentityDbContext<ApplicationUser>
{
public AllReadyContext() { }
public AllReadyContext(DbContextOptions options) : base(options) { }
public DbSet<Organization> Organizations { get; set; }
public DbSet<Campaign> Campaigns { get; set; }
public DbSet<CampaignGoal> CampaignGoals { get; set; }
public DbSet<Event> Events { get; set; }
public DbSet<EventSkill> EventSkills { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<PostalCodeGeo> PostalCodes { get; set; }
public DbSet<VolunteerTask> VolunteerTasks { get; set; }
public DbSet<VolunteerTaskSkill> VolunteerTaskSkills { get; set; }
public DbSet<VolunteerTaskSignup> VolunteerTaskSignups { get; set; }
public DbSet<Resource> Resources { get; set; }
public DbSet<Skill> Skills { get; set; }
public DbSet<UserSkill> UserSkills { get; set; }
public DbSet<Contact> Contacts { get; set; }
public DbSet<OrganizationContact> OrganizationContacts { get; set; }
public DbSet<CampaignContact> CampaignContacts { get; set; }
public DbSet<ClosestLocation> ClosestLocations { get; set; }
public DbSet<PostalCodeGeoCoordinate> PostalCodeGeoCoordinates { get; set; }
public DbSet<Request> Requests { get; set; }
public DbSet<Itinerary> Itineraries { get; set; }
public DbSet<ItineraryRequest> ItineraryRequests { get; set; }
public DbSet<CampaignManager> CampaignManagers { get; set; }
public DbSet<EventManager> EventManagers { get; set; }
public DbSet<EventManagerInvite> EventManagerInvites { get; set; }
public DbSet<CampaignManagerInvite> CampaignManagerInvites { get; set; }
public DbSet<FileAttachment> Attachments { get; set; }
public DbSet<RequestComment> RequestComments { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Keep old database table naming convention
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
entity.Relational().TableName = entity.DisplayName();
}
Map(modelBuilder.Entity<Location>());
Map(modelBuilder.Entity<Campaign>());
Map(modelBuilder.Entity<CampaignSponsors>());
Map(modelBuilder.Entity<Event>());
Map(modelBuilder.Entity<EventSkill>());
Map(modelBuilder.Entity<VolunteerTask>());
Map(modelBuilder.Entity<VolunteerTaskSkill>());
Map(modelBuilder.Entity<VolunteerTaskSignup>());
Map(modelBuilder.Entity<PostalCodeGeo>());
Map(modelBuilder.Entity<Skill>());
Map(modelBuilder.Entity<UserSkill>());
Map(modelBuilder.Entity<ApplicationUser>());
Map(modelBuilder.Entity<Organization>());
Map(modelBuilder.Entity<OrganizationContact>());
Map(modelBuilder.Entity<CampaignContact>());
Map(modelBuilder.Entity<Contact>());
Map(modelBuilder.Entity<CampaignGoal>());
Map(modelBuilder.Entity<ClosestLocation>());
Map(modelBuilder.Entity<PostalCodeGeoCoordinate>());
Map(modelBuilder.Entity<Request>());
Map(modelBuilder.Entity<Itinerary>());
Map(modelBuilder.Entity<ItineraryRequest>());
Map(modelBuilder.Entity<CampaignManager>());
Map(modelBuilder.Entity<EventManager>());
Map(modelBuilder.Entity<EventManagerInvite>());
Map(modelBuilder.Entity<CampaignManagerInvite>());
Map(modelBuilder.Entity<FileAttachment>());
Map(modelBuilder.Entity<RequestComment>());
}
private void Map(EntityTypeBuilder<Location> builder)
{
builder.HasKey(x => x.Id);
builder.Ignore(x => x.FullAddress);
}
private void Map(EntityTypeBuilder<Request> builder)
{
builder.HasKey(x => x.RequestId);
builder.HasOne(r => r.Organization).WithMany(o => o.Requests).HasForeignKey(r => r.OrganizationId);
builder.HasOne(r => r.Itinerary);
}
private void Map(EntityTypeBuilder<CampaignGoal> builder)
{
builder.HasOne(c => c.Campaign);
builder.Ignore(c => c.PercentComplete);
}
private void Map(EntityTypeBuilder<CampaignContact> builder)
{
builder.HasKey(tc => new { tc.CampaignId, tc.ContactId, tc.ContactType });
builder.HasOne(tc => tc.Contact).WithMany(x => x.CampaignContacts).HasForeignKey(x => x.ContactId);
builder.HasOne(tc => tc.Campaign);
}
private void Map(EntityTypeBuilder<Contact> builder)
{
builder.HasMany(c => c.OrganizationContacts);
builder.HasMany(c => c.CampaignContacts);
}
private void Map(EntityTypeBuilder<OrganizationContact> builder)
{
builder.HasKey(tc => new { tc.OrganizationId, tc.ContactId, tc.ContactType });
builder.HasOne(tc => tc.Contact).WithMany(x => x.OrganizationContacts).HasForeignKey(x => x.ContactId);
builder.HasOne(tc => tc.Organization);
}
private void Map(EntityTypeBuilder<Organization> builder)
{
builder.HasOne(t => t.Location);
builder.HasMany(t => t.OrganizationContacts);
builder.Property(t => t.Name).IsRequired();
}
private void Map(EntityTypeBuilder<PostalCodeGeo> builder)
{
builder.HasKey(k => k.PostalCode);
}
private void Map(EntityTypeBuilder<VolunteerTaskSignup> builder)
{
builder.HasOne(u => u.VolunteerTask).WithMany(x => x.AssignedVolunteers).HasForeignKey(x => x.VolunteerTaskId);
}
private void Map(EntityTypeBuilder<VolunteerTask> builder)
{
builder.HasOne(t => t.Event).WithMany(e => e.VolunteerTasks).HasForeignKey(t => t.EventId);
builder.HasOne(t => t.Organization);
builder.HasMany(t => t.AssignedVolunteers)
.WithOne(ts => ts.VolunteerTask).HasForeignKey(ts => ts.VolunteerTaskId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasMany(t => t.RequiredSkills).WithOne(ts => ts.VolunteerTask);
builder.Property(p => p.Name).IsRequired();
builder.HasMany(t => t.Attachments);
}
private void Map(EntityTypeBuilder<VolunteerTaskSkill> builder)
{
builder.HasKey(acsk => new { TaskId = acsk.VolunteerTaskId, acsk.SkillId });
builder.HasOne(x => x.VolunteerTask).WithMany(x => x.RequiredSkills).HasForeignKey(x => x.VolunteerTaskId);
}
private void Map(EntityTypeBuilder<Event> builder)
{
builder.HasOne(a => a.Campaign).WithMany(x => x.Events).HasForeignKey(x => x.CampaignId).IsRequired();
builder.HasOne(a => a.Location);
builder.HasMany(a => a.VolunteerTasks)
.WithOne(t => t.Event)
.OnDelete(DeleteBehavior.Cascade);
builder.HasMany(a => a.RequiredSkills).WithOne(acsk => acsk.Event);
builder.Property(p => p.Name).IsRequired();
builder.HasMany(x => x.Itineraries).WithOne(x => x.Event).HasForeignKey(x => x.EventId).IsRequired();
builder.HasMany(x => x.Requests).WithOne(x => x.Event).HasForeignKey(x => x.EventId).IsRequired(false).OnDelete(DeleteBehavior.SetNull);
}
private void Map(EntityTypeBuilder<EventSkill> builder)
{
builder.HasKey(acsk => new { acsk.EventId, acsk.SkillId });
}
private void Map(EntityTypeBuilder<Skill> builder)
{
builder.HasOne(s => s.ParentSkill).WithMany(s => s.ChildSkills).HasForeignKey(s => s.ParentSkillId);
builder.Ignore(s => s.HierarchicalName);
builder.Ignore(s => s.DescendantIds);
}
private void Map(EntityTypeBuilder<CampaignSponsors> builder)
{
builder.HasOne(s => s.Campaign)
.WithMany(c => c.ParticipatingOrganizations);
builder.HasOne(s => s.Organization);
}
private void Map(EntityTypeBuilder<Campaign> builder)
{
builder.HasOne(c => c.ManagingOrganization).WithMany(x => x.Campaigns).HasForeignKey(x => x.ManagingOrganizationId);
builder.HasMany(c => c.CampaignGoals);
builder.HasMany(c => c.Events);
builder.HasMany(c => c.Resources).WithOne(c => c.Campaign).HasForeignKey(c => c.CampaignId);
builder.HasOne(t => t.Location);
builder.HasMany(t => t.CampaignContacts);
builder.Property(a => a.Name).IsRequired();
}
private void Map(EntityTypeBuilder<Resource> builder)
{
builder.HasKey(r => r.Id);
builder.HasOne(r => r.Campaign);
builder.Property(r => r.Description).IsRequired();
builder.Property(r => r.Name).IsRequired();
builder.Property(r => r.ResourceUrl).IsRequired();
}
private void Map(EntityTypeBuilder<ApplicationUser> builder)
{
builder.HasMany(u => u.AssociatedSkills).WithOne(us => us.User);
builder.HasMany(e => e.Claims)
.WithOne()
.HasForeignKey(e => e.UserId)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
builder.HasMany(e => e.Logins)
.WithOne()
.HasForeignKey(e => e.UserId)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
builder.HasMany(e => e.Roles)
.WithOne()
.HasForeignKey(e => e.UserId)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);}
private void Map(EntityTypeBuilder<UserSkill> builder)
{
builder.HasKey(us => new { us.UserId, us.SkillId });
}
private void Map(EntityTypeBuilder<ClosestLocation> builder)
{
builder.HasKey(us => new { us.PostalCode });
}
private void Map(EntityTypeBuilder<PostalCodeGeoCoordinate> builder)
{
builder.HasKey(us => new { us.Latitude, us.Longitude });
}
public void Map(EntityTypeBuilder<Itinerary> builder)
{
builder.HasKey(x => x.Id);
builder.HasMany(x => x.Requests).WithOne(x => x.Itinerary).HasForeignKey((x => x.ItineraryId));
builder.HasMany(x => x.TeamMembers).WithOne(x => x.Itinerary).HasForeignKey(x => x.ItineraryId).IsRequired(false);
builder.HasOne(x => x.StartLocation);
builder.HasOne(x => x.EndLocation);
// Ignore computed properties which are not stored in the database
builder.Ignore(b => b.StartAddress);
builder.Ignore(b => b.EndAddress);
builder.Ignore(b => b.HasAddresses);
}
public void Map(EntityTypeBuilder<ItineraryRequest> builder)
{
builder.HasKey(x => new { x.ItineraryId, x.RequestId });
builder.HasIndex(x => x.RequestId).IsUnique();
builder.HasOne(x => x.Itinerary).WithMany(x => x.Requests).HasForeignKey(x => x.ItineraryId);
builder.HasOne(x => x.Request).WithMany().HasForeignKey(x => x.RequestId);
}
private void Map(EntityTypeBuilder<CampaignManager> builder)
{
builder.HasKey(x => new { x.UserId, x.CampaignId });
builder.HasOne(x => x.User)
.WithMany(u => u.ManagedCampaigns)
.HasForeignKey(x => x.UserId);
builder.HasOne(x => x.Campaign)
.WithMany(u => u.CampaignManagers)
.HasForeignKey(x => x.CampaignId);
}
private void Map(EntityTypeBuilder<EventManager> builder)
{
builder.HasKey(x => new { x.UserId, x.EventId });
builder.HasOne(x => x.User)
.WithMany(u => u.ManagedEvents)
.HasForeignKey(x => x.UserId);
builder.HasOne(x => x.Event)
.WithMany(u => u.EventManagers)
.HasForeignKey(x => x.EventId);
}
private void Map(EntityTypeBuilder<EventManagerInvite> builder)
{
builder.HasKey(x => x.Id);
builder.Property(a => a.InviteeEmailAddress).IsRequired();
builder.Property(a => a.SenderUserId).IsRequired();
builder.HasOne(x => x.SenderUser)
.WithMany(u => u.SentEventManagerInvites)
.HasForeignKey(x => x.SenderUserId)
.IsRequired();
builder.HasOne(x => x.Event)
.WithMany(u => u.ManagementInvites)
.HasForeignKey(x => x.EventId)
.IsRequired();
builder.Ignore(x => x.IsAccepted);
builder.Ignore(x => x.IsRejected);
builder.Ignore(x => x.IsRevoked);
builder.Ignore(x => x.IsPending);
}
private void Map(EntityTypeBuilder<CampaignManagerInvite> builder)
{
builder.HasKey(x => x.Id);
builder.Property(a => a.InviteeEmailAddress).IsRequired();
builder.Property(a => a.SenderUserId).IsRequired();
builder.HasOne(x => x.SenderUser)
.WithMany(u => u.SentCampaignManagerInvites)
.HasForeignKey(x => x.SenderUserId)
.IsRequired();
builder.HasOne(x => x.Campaign)
.WithMany(u => u.ManagementInvites)
.HasForeignKey(x => x.CampaignId)
.IsRequired();
builder.Ignore(x => x.IsAccepted);
builder.Ignore(x => x.IsRejected);
builder.Ignore(x => x.IsRevoked);
builder.Ignore(x => x.IsPending);
}
public void Map(EntityTypeBuilder<FileAttachment> builder)
{
builder.HasKey(a => a.Id);
builder.HasOne(a => a.VolunteerTask);
builder.Property(a => a.Name).IsRequired();
}
public void Map(EntityTypeBuilder<RequestComment> builder)
{
builder.HasKey(rc => rc.Id);
builder.HasOne(rc => rc.Request).WithMany(r => r.RequestComments).HasForeignKey(rc => rc.RequestId);
builder.HasOne(rc => rc.User).WithMany(r => r.RequestComments).HasForeignKey(rc => rc.UserId);
builder.Property(a => a.Comment).IsRequired();
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#if !SILVERLIGHT
using System;
using System.Collections;
using System.Reflection;
using System.Runtime.Serialization;
using System.Diagnostics.Contracts;
namespace System.Collections.Specialized
{
// Summary:
// Represents a collection of associated System.String keys and System.String
// values that can be accessed either with the key or with the index.
public class NameValueCollection : NameObjectCollectionBase
{
// Summary:
// Initializes a new instance of the System.Collections.Specialized.NameValueCollection
// class that is empty, has the default initial capacity and uses the default
// case-insensitive hash code provider and the default case-insensitive comparer.
extern public NameValueCollection();
//
// Summary:
// Initializes a new instance of the System.Collections.Specialized.NameValueCollection
// class that is empty, has the default initial capacity, and uses the specified
// System.Collections.IEqualityComparer object.
//
// Parameters:
// equalityComparer:
// The System.Collections.IEqualityComparer object to use to determine whether
// two keys are equal and to generate hash codes for the keys in the collection.
extern public NameValueCollection(IEqualityComparer equalityComparer);
//
// Summary:
// Initializes a new instance of the System.Collections.Specialized.NameValueCollection
// class that is empty, has the specified initial capacity and uses the default
// case-insensitive hash code provider and the default case-insensitive comparer.
//
// Parameters:
// capacity:
// The initial number of entries that the System.Collections.Specialized.NameValueCollection
// can contain.
//
// Exceptions:
// System.ArgumentOutOfRangeException:
// capacity is less than zero.
public NameValueCollection(int capacity)
{
Contract.Requires(capacity >= 0);
}
//
// Summary:
// Copies the entries from the specified System.Collections.Specialized.NameValueCollection
// to a new System.Collections.Specialized.NameValueCollection with the same
// initial capacity as the number of entries copied and using the same hash
// code provider and the same comparer as the source collection.
//
// Parameters:
// col:
// The System.Collections.Specialized.NameValueCollection to copy to the new
// System.Collections.Specialized.NameValueCollection instance.
//
// Exceptions:
// System.ArgumentNullException:
// col is null.
public NameValueCollection(NameValueCollection col)
{
Contract.Requires(col != null);
}
//
// Summary:
// Initializes a new instance of the System.Collections.Specialized.NameValueCollection
// class that is empty, has the specified initial capacity, and uses the specified
// System.Collections.IEqualityComparer object.
//
// Parameters:
// capacity:
// The initial number of entries that the System.Collections.Specialized.NameValueCollection
// object can contain.
//
// equalityComparer:
// The System.Collections.IEqualityComparer object to use to determine whether
// two keys are equal and to generate hash codes for the keys in the collection.
//
// Exceptions:
// System.ArgumentOutOfRangeException:
// capacity is less than zero.
public NameValueCollection(int capacity, IEqualityComparer equalityComparer)
{
Contract.Requires(capacity >= 0);
}
//
// Summary:
// Copies the entries from the specified System.Collections.Specialized.NameValueCollection
// to a new System.Collections.Specialized.NameValueCollection with the specified
// initial capacity or the same initial capacity as the number of entries copied,
// whichever is greater, and using the default case-insensitive hash code provider
// and the default case-insensitive comparer.
//
// Parameters:
// capacity:
// The initial number of entries that the System.Collections.Specialized.NameValueCollection
// can contain.
//
// col:
// The System.Collections.Specialized.NameValueCollection to copy to the new
// System.Collections.Specialized.NameValueCollection instance.
//
// Exceptions:
// System.ArgumentOutOfRangeException:
// capacity is less than zero.
//
// System.ArgumentNullException:
// col is null.
public NameValueCollection(int capacity, NameValueCollection col)
{
Contract.Requires(capacity >= 0);
Contract.Requires(col != null);
}
//
// Summary:
// Initializes a new instance of the System.Collections.Specialized.NameValueCollection
// class that is serializable and uses the specified System.Runtime.Serialization.SerializationInfo
// and System.Runtime.Serialization.StreamingContext.
//
// Parameters:
// info:
// A System.Runtime.Serialization.SerializationInfo object that contains the
// information required to serialize the new System.Collections.Specialized.NameValueCollection
// instance.
//
// context:
// A System.Runtime.Serialization.StreamingContext object that contains the
// source and destination of the serialized stream associated with the new System.Collections.Specialized.NameValueCollection
// instance.
extern protected NameValueCollection(SerializationInfo info, StreamingContext context);
// Summary:
// Gets all the keys in the System.Collections.Specialized.NameValueCollection.
//
// Returns:
// A System.String array that contains all the keys of the System.Collections.Specialized.NameValueCollection.
public virtual string[] AllKeys
{
get
{
Contract.Ensures(Contract.Result<string[]>() != null);
return default(string[]);
}
}
// Summary:
// Gets the entry at the specified index of the System.Collections.Specialized.NameValueCollection.
//
// Parameters:
// index:
// The zero-based index of the entry to locate in the collection.
//
// Returns:
// A System.String that contains the comma-separated list of values at the specified
// index of the collection.
//
// Exceptions:
// System.ArgumentOutOfRangeException:
// index is outside the valid range of indexes for the collection.
public string this[int index]
{
get
{
Contract.Requires(index >= 0);
Contract.Requires(index < this.Count);
return default(string);
}
}
//
// Summary:
// Gets or sets the entry with the specified key in the System.Collections.Specialized.NameValueCollection.
//
// Parameters:
// name:
// The System.String key of the entry to locate. The key can be null.
//
// Returns:
// A System.String that contains the comma-separated list of values associated
// with the specified key, if found; otherwise, null.
//
// Exceptions:
// System.NotSupportedException:
// The collection is read-only and the operation attempts to modify the collection.
extern public string this[string name] { get; set; }
// Summary:
// Copies the entries in the specified System.Collections.Specialized.NameValueCollection
// to the current System.Collections.Specialized.NameValueCollection.
//
// Parameters:
// c:
// The System.Collections.Specialized.NameValueCollection to copy to the current
// System.Collections.Specialized.NameValueCollection.
//
// Exceptions:
// System.NotSupportedException:
// The collection is read-only.
//
// System.ArgumentNullException:
// c is null.
public void Add(NameValueCollection c)
{
Contract.Requires(c != null);
}
//
// Summary:
// Adds an entry with the specified name and value to the System.Collections.Specialized.NameValueCollection.
//
// Parameters:
// name:
// The System.String key of the entry to add. The key can be null.
//
// value:
// The System.String value of the entry to add. The value can be null.
//
// Exceptions:
// System.NotSupportedException:
// The collection is read-only.
extern public virtual void Add(string name, string value);
//
// Summary:
// Invalidates the cached arrays and removes all entries from the System.Collections.Specialized.NameValueCollection.
//
// Exceptions:
// System.NotSupportedException:
// The collection is read-only.
public virtual void Clear()
{
Contract.Ensures(Count == 0);
}
//
// Summary:
// Copies the entire System.Collections.Specialized.NameValueCollection to a
// compatible one-dimensional System.Array, starting at the specified index
// of the target array.
//
// Parameters:
// dest:
// The one-dimensional System.Array that is the destination of the elements
// copied from System.Collections.Specialized.NameValueCollection. The System.Array
// must have zero-based indexing.
//
// index:
// The zero-based index in dest at which copying begins.
//
// Exceptions:
// System.ArgumentNullException:
// dest is null.
//
// System.ArgumentOutOfRangeException:
// index is less than zero.
//
// System.ArgumentException:
// dest is multidimensional. -or- index is equal to or greater than the length
// of dest. -or- The number of elements in the source System.Collections.Specialized.NameValueCollection
// is greater than the available space from index to the end of the destination
// dest.
//
// System.InvalidCastException:
// The type of the source System.Collections.Specialized.NameValueCollection
// cannot be cast automatically to the type of the destination dest.
public void CopyTo(Array dest, int index)
{
Contract.Requires(dest != null);
Contract.Requires(dest.Rank == 1);
Contract.Requires(index >= 0);
Contract.Requires(this.Count + index < dest.Length);
}
//
// Summary:
// Gets the values at the specified index of the System.Collections.Specialized.NameValueCollection
// combined into one comma-separated list.
//
// Parameters:
// index:
// The zero-based index of the entry that contains the values to get from the
// collection.
//
// Returns:
// A System.String that contains a comma-separated list of the values at the
// specified index of the System.Collections.Specialized.NameValueCollection,
// if found; otherwise, null.
//
// Exceptions:
// System.ArgumentOutOfRangeException:
// index is outside the valid range of indexes for the collection.
[Pure]
public virtual string Get(int index)
{
Contract.Requires(index >= 0);
Contract.Requires(index < Count);
return default(string);
}
//
// Summary:
// Gets the values associated with the specified key from the System.Collections.Specialized.NameValueCollection
// combined into one comma-separated list.
//
// Parameters:
// name:
// The System.String key of the entry that contains the values to get. The key
// can be null.
//
// Returns:
// A System.String that contains a comma-separated list of the values associated
// with the specified key from the System.Collections.Specialized.NameValueCollection,
// if found; otherwise, null.
[Pure]
extern public virtual string Get(string name);
//
// Summary:
// Gets the key at the specified index of the System.Collections.Specialized.NameValueCollection.
//
// Parameters:
// index:
// The zero-based index of the key to get from the collection.
//
// Returns:
// A System.String that contains the key at the specified index of the System.Collections.Specialized.NameValueCollection,
// if found; otherwise, null.
//
// Exceptions:
// System.ArgumentOutOfRangeException:
// index is outside the valid range of indexes for the collection.
[Pure]
public virtual string GetKey(int index)
{
Contract.Requires(index >= 0);
Contract.Requires(index < Count);
return default(string);
}
//
// Summary:
// Gets the values at the specified index of the System.Collections.Specialized.NameValueCollection.
//
// Parameters:
// index:
// The zero-based index of the entry that contains the values to get from the
// collection.
//
// Returns:
// A System.String array that contains the values at the specified index of
// the System.Collections.Specialized.NameValueCollection, if found; otherwise,
// null.
//
// Exceptions:
// System.ArgumentOutOfRangeException:
// index is outside the valid range of indexes for the collection.
[Pure]
public virtual string[] GetValues(int index)
{
Contract.Requires(index >= 0);
Contract.Requires(index < Count);
return default(string[]);
}
//
// Summary:
// Gets the values associated with the specified key from the System.Collections.Specialized.NameValueCollection.
//
// Parameters:
// name:
// The System.String key of the entry that contains the values to get. The key
// can be null.
//
// Returns:
// A System.String array that contains the values associated with the specified
// key from the System.Collections.Specialized.NameValueCollection, if found;
// otherwise, null.
[Pure]
extern public virtual string[] GetValues(string name);
//
// Summary:
// Gets a value indicating whether the System.Collections.Specialized.NameValueCollection
// contains keys that are not null.
//
// Returns:
// true if the System.Collections.Specialized.NameValueCollection contains keys
// that are not null; otherwise, false.
[Pure]
extern public bool HasKeys();
//
// Summary:
// Resets the cached arrays of the collection to null.
extern protected void InvalidateCachedArrays();
//
// Summary:
// Removes the entries with the specified key from the System.Collections.Specialized.NameObjectCollectionBase
// instance.
//
// Parameters:
// name:
// The System.String key of the entry to remove. The key can be null.
//
// Exceptions:
// System.NotSupportedException:
// The collection is read-only.
extern public virtual void Remove(string name);
//
// Summary:
// Sets the value of an entry in the System.Collections.Specialized.NameValueCollection.
//
// Parameters:
// name:
// The System.String key of the entry to add the new value to. The key can be
// null.
//
// value:
// The System.Object that represents the new value to add to the specified entry.
// The value can be null.
//
// Exceptions:
// System.NotSupportedException:
// The collection is read-only.
extern public virtual void Set(string name, string value);
}
}
#endif
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using WebsitePanel.Providers.Web;
using WebsitePanel.Providers.ResultObjects;
namespace WebsitePanel.Portal
{
public partial class WebSitesHeliconApeControl : WebsitePanelControlBase
{
private bool IsSecuredFoldersInstalled
{
get { return ViewState["IsSecuredFoldersInstalled"] != null ? (bool)ViewState["IsSecuredFoldersInstalled"] : false; }
set { ViewState["IsSecuredFoldersInstalled"] = value; }
}
private HeliconApeStatus HeliconApeStatus
{
get
{
if (null == ViewState["HeliconApeStatus"])
{
HeliconApeStatus nullstatus = new HeliconApeStatus();
return nullstatus;
}
else
{
return (HeliconApeStatus)ViewState["HeliconApeStatus"];
}
}
set { ViewState["HeliconApeStatus"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cs = Page.ClientScript;
cs.RegisterClientScriptInclude("jquery", ResolveUrl("~/JavaScript/jquery-1.4.4.min.js"));
if (HeliconApeStatus.IsInstalled)
{
if (!IsPostBack)
{
WebSite site = null;
try
{
site = ES.Services.WebServers.GetWebSite(PanelRequest.ItemID);
}
catch (Exception ex)
{
HostModule.ShowErrorMessage("WEB_GET_SITE", ex);
return;
}
if (site == null)
RedirectToBrowsePage();
BindHeliconApe(site);
}
}
}
public void BindHeliconApe(WebSite site)
{
// save initial state
this.IsSecuredFoldersInstalled = site.SecuredFoldersInstalled;
this.HeliconApeStatus = site.HeliconApeStatus;
// Render a warning message about the automatic site's settings change
if (site.IIs7)
{
if (!HeliconApeStatus.IsEnabled)
{
// Ensure the message is displayed only when neccessary
if (site.EnableWindowsAuthentication || !site.AspNetInstalled.EndsWith("I") || site.SecuredFoldersInstalled)
{
// TODO: show warning, do not force to enable integrated pool
string warningStr = GetLocalizedString("EnableFoldersIIs7Warning.Text");
// Render a warning only if specified
if (!String.IsNullOrEmpty(warningStr))
btnToggleHeliconApe.OnClientClick = String.Format("return confirm('{0}')", warningStr);
}
}
}
// toggle
ToggleControls();
}
private void ToggleControls()
{
if (HeliconApeStatus.IsInstalled)
{
bool IsHeliconApeEnabled = HeliconApeStatus.IsEnabled;
// toggle button
if (IsHeliconApeEnabled)
{
btnToggleHeliconApe.Text = GetLocalizedString("DisableHeliconApe.Text");
}
else
{
btnToggleHeliconApe.Text = GetLocalizedString("EnableHeliconApe.Text");
}
// toggle panels
HeliconApeFoldersPanel.Visible = IsHeliconApeEnabled;
panelHeliconApeIsNotEnabledMessage.Visible = !IsHeliconApeEnabled;
// bind items
if (IsHeliconApeEnabled)
{
BindFolders();
BindUsers();
BindGroups();
}
}
else
{
// Display the module not installed message for informational purposes.
panelHeliconApeIsNotInstalledMessage.Visible = true;
//
btnToggleHeliconApe.Visible = false;
HeliconApeFoldersPanel.Visible = false;
}
}
private void BindFolders()
{
gvHeliconApeFolders.DataSource = ES.Services.WebServers.GetHeliconApeFolders(PanelRequest.ItemID);
gvHeliconApeFolders.DataBind();
}
private void BindUsers()
{
gvHeliconApeUsers.DataSource = ES.Services.WebServers.GetHeliconApeUsers(PanelRequest.ItemID);
gvHeliconApeUsers.DataBind();
}
private void BindGroups()
{
gvHeliconApeGroups.DataSource = ES.Services.WebServers.GetHeliconApeGroups(PanelRequest.ItemID);
gvHeliconApeGroups.DataBind();
}
protected void btnToggleHeliconApe_Click(object sender, EventArgs e)
{
try
{
int result = 0;
if (HeliconApeStatus.IsEnabled)
{
// uninstall folders
result = ES.Services.WebServers.DisableHeliconApe(PanelRequest.ItemID);
}
else
{
// install folders
result = ES.Services.WebServers.EnableHeliconApe(PanelRequest.ItemID);
}
if (result < 0)
{
HostModule.ShowResultMessage(result);
return;
}
}
catch (Exception ex)
{
HostModule.ShowErrorMessage("WEB_INSTALL_HTACCESS", ex);
return;
}
// change state
HeliconApeStatus status = HeliconApeStatus;
status.IsEnabled = !status.IsEnabled;
HeliconApeStatus = status;
// bind items
ToggleControls();
}
public string GetEditUrl(string ctrlKey, string name)
{
name = Server.UrlEncode(name);
return HostModule.EditUrl("ItemID", PanelRequest.ItemID.ToString(), ctrlKey,
"Name=" + name);
}
protected void btnAddHeliconApeFolder_Click(object sender, EventArgs e)
{
RedirectToEditControl("edit_htaccessfolder", "");
}
public void RedirectToEditControl(string ctrlKey, string name)
{
Response.Redirect(GetEditControlUrl(ctrlKey, name));
}
public string GetEditControlUrl(string ctrlKey, string name)
{
return HostModule.EditUrl("ItemID", PanelRequest.ItemID.ToString(), ctrlKey,
"Name=" + name,
PortalUtils.SPACE_ID_PARAM + "=" + PanelSecurity.PackageId.ToString());
}
private bool DeleteFolder(string name)
{
try
{
int result = ES.Services.WebServers.DeleteHeliconApeFolder(PanelRequest.ItemID, name);
if (result < 0)
{
HostModule.ShowResultMessage(result);
return false;
}
}
catch (Exception ex)
{
HostModule.ShowErrorMessage("WEB_DELETE_HELICON_APE_FOLDER", ex);
return false;
}
return true;
}
protected void gvHeliconApeFolders_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// delete folder
string folderName = (string)gvHeliconApeFolders.DataKeys[e.RowIndex][1];
if (DeleteFolder(folderName))
{
// reb-bind folders
BindFolders();
}
// cancel command
e.Cancel = true;
}
protected void btnAddHeliconApeUser_Click(object sender, EventArgs e)
{
RedirectToEditControl("edit_htaccessuser", "");
}
protected void btnAddHeliconApeGroup_Click(object sender, EventArgs e)
{
RedirectToEditControl("edit_htaccessgroup", "");
}
private bool DeleteUser(string name)
{
try
{
int result = ES.Services.WebServers.DeleteHeliconApeUser(PanelRequest.ItemID, name);
if (result < 0)
{
HostModule.ShowResultMessage(result);
return false;
}
}
catch (Exception ex)
{
HostModule.ShowErrorMessage("WEB_DELETE_HeliconApe_USER", ex);
return false;
}
return true;
}
protected void gvHeliconApeUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// delete user
string name = (string)gvHeliconApeUsers.DataKeys[e.RowIndex][0];
if (DeleteUser(name))
{
// reb-bind users
BindUsers();
}
// cancel command
e.Cancel = true;
}
private bool DeleteGroup(string name)
{
try
{
int result = ES.Services.WebServers.DeleteHeliconApeGroup(PanelRequest.ItemID, name);
if (result < 0)
{
HostModule.ShowResultMessage(result);
return false;
}
}
catch (Exception ex)
{
HostModule.ShowErrorMessage("WEB_DELETE_HeliconApe_GROUP", ex);
return false;
}
return true;
}
protected void gvHeliconApeGroups_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// delete group
string name = (string)gvHeliconApeGroups.DataKeys[e.RowIndex][0];
if (DeleteGroup(name))
{
// reb-bind groups
BindGroups();
}
// cancel command
e.Cancel = true;
}
protected string GetHtaccessPathOnSite(string path)
{
path = path.Replace('\\', '/');
if (!path.EndsWith("/"))
{
path += "/";
}
path += ".htaccess";
return path;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Dumps commands in QueryStatus and Exec.
// #define DUMP_COMMANDS
using System;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.InteractiveWindow;
namespace Microsoft.VisualStudio.InteractiveWindow.Shell
{
internal sealed class VsInteractiveWindowCommandFilter : IOleCommandTarget
{
//
// Command filter chain:
// *window* -> VsTextView -> ... -> *pre-language + the current language service's filter* -> editor services -> *preEditor* -> editor
//
private IOleCommandTarget _preLanguageCommandFilter;
private IOleCommandTarget _editorServicesCommandFilter;
private IOleCommandTarget _preEditorCommandFilter;
private IOleCommandTarget _editorCommandFilter;
// we route undo/redo commands to this target:
internal IOleCommandTarget currentBufferCommandHandler;
internal IOleCommandTarget firstLanguageServiceCommandFilter;
private readonly IInteractiveWindow _window;
internal readonly IVsTextView textViewAdapter;
private readonly IWpfTextViewHost _textViewHost;
public VsInteractiveWindowCommandFilter(IVsEditorAdaptersFactoryService adapterFactory, IInteractiveWindow window, IVsTextView textViewAdapter, IVsTextBuffer bufferAdapter)
{
_window = window;
this.textViewAdapter = textViewAdapter;
// make us a code window so we'll have the same colors as a normal code window.
IVsTextEditorPropertyContainer propContainer;
ErrorHandler.ThrowOnFailure(((IVsTextEditorPropertyCategoryContainer)textViewAdapter).GetPropertyCategory(Microsoft.VisualStudio.Editor.DefGuidList.guidEditPropCategoryViewMasterSettings, out propContainer));
propContainer.SetProperty(VSEDITPROPID.VSEDITPROPID_ViewComposite_AllCodeWindowDefaults, true);
propContainer.SetProperty(VSEDITPROPID.VSEDITPROPID_ViewGlobalOpt_AutoScrollCaretOnTextEntry, true);
// editor services are initialized in textViewAdapter.Initialize - hook underneath them:
_preEditorCommandFilter = new CommandFilter(this, CommandFilterLayer.PreEditor);
ErrorHandler.ThrowOnFailure(textViewAdapter.AddCommandFilter(_preEditorCommandFilter, out _editorCommandFilter));
textViewAdapter.Initialize(
(IVsTextLines)bufferAdapter,
IntPtr.Zero,
(uint)TextViewInitFlags.VIF_HSCROLL | (uint)TextViewInitFlags.VIF_VSCROLL | (uint)TextViewInitFlags3.VIF_NO_HWND_SUPPORT,
new[] { new INITVIEW { fSelectionMargin = 0, fWidgetMargin = 0, fVirtualSpace = 0, fDragDropMove = 1 } });
// disable change tracking because everything will be changed
var textViewHost = adapterFactory.GetWpfTextViewHost(textViewAdapter);
_preLanguageCommandFilter = new CommandFilter(this, CommandFilterLayer.PreLanguage);
ErrorHandler.ThrowOnFailure(textViewAdapter.AddCommandFilter(_preLanguageCommandFilter, out _editorServicesCommandFilter));
_textViewHost = textViewHost;
}
private IOleCommandTarget TextViewCommandFilterChain
{
get
{
// Non-character command processing starts with WindowFrame which calls ReplWindow.Exec.
// We need to invoke the view's Exec method in order to invoke its full command chain
// (features add their filters to the view).
return (IOleCommandTarget)textViewAdapter;
}
}
#region IOleCommandTarget
public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
{
var nextTarget = TextViewCommandFilterChain;
return nextTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
}
public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
var nextTarget = TextViewCommandFilterChain;
return nextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
#endregion
public IWpfTextViewHost TextViewHost
{
get
{
return _textViewHost;
}
}
private enum CommandFilterLayer
{
PreLanguage,
PreEditor
}
private sealed class CommandFilter : IOleCommandTarget
{
private readonly VsInteractiveWindowCommandFilter _window;
private readonly CommandFilterLayer _layer;
public CommandFilter(VsInteractiveWindowCommandFilter window, CommandFilterLayer layer)
{
_window = window;
_layer = layer;
}
public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
{
switch (_layer)
{
case CommandFilterLayer.PreLanguage:
return _window.PreLanguageCommandFilterQueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
case CommandFilterLayer.PreEditor:
return _window.PreEditorCommandFilterQueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
}
throw new InvalidOperationException();
}
public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
switch (_layer)
{
case CommandFilterLayer.PreLanguage:
return _window.PreLanguageCommandFilterExec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
case CommandFilterLayer.PreEditor:
return _window.PreEditorCommandFilterExec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
throw new InvalidOperationException();
}
}
private int PreEditorCommandFilterQueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
{
return _editorCommandFilter.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
}
private int PreEditorCommandFilterExec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
var nextTarget = _editorCommandFilter;
if (pguidCmdGroup == Guids.InteractiveCommandSetId)
{
switch ((CommandIds)nCmdID)
{
case CommandIds.BreakLine:
if (_window.Operations.BreakLine())
{
return VSConstants.S_OK;
}
break;
}
}
else if (pguidCmdGroup == VSConstants.VSStd2K)
{
switch ((VSConstants.VSStd2KCmdID)nCmdID)
{
case VSConstants.VSStd2KCmdID.RETURN:
if (_window.Operations.Return())
{
return VSConstants.S_OK;
}
break;
// TODO:
//case VSConstants.VSStd2KCmdID.DELETEWORDLEFT:
//case VSConstants.VSStd2KCmdID.DELETEWORDRIGHT:
// break;
case VSConstants.VSStd2KCmdID.BACKSPACE:
if (_window.Operations.Backspace())
{
return VSConstants.S_OK;
}
break;
case VSConstants.VSStd2KCmdID.UP:
if (_window.CurrentLanguageBuffer != null && !_window.IsRunning && CaretAtEnd && UseSmartUpDown)
{
_window.Operations.HistoryPrevious();
return VSConstants.S_OK;
}
break;
case VSConstants.VSStd2KCmdID.DOWN:
if (_window.CurrentLanguageBuffer != null && !_window.IsRunning && CaretAtEnd && UseSmartUpDown)
{
_window.Operations.HistoryNext();
return VSConstants.S_OK;
}
break;
case VSConstants.VSStd2KCmdID.CANCEL:
if (_window.TextView.Selection.IsEmpty)
{
_window.Operations.Cancel();
}
break;
case VSConstants.VSStd2KCmdID.BOL:
_window.Operations.Home(false);
return VSConstants.S_OK;
case VSConstants.VSStd2KCmdID.BOL_EXT:
_window.Operations.Home(true);
return VSConstants.S_OK;
case VSConstants.VSStd2KCmdID.EOL:
_window.Operations.End(false);
return VSConstants.S_OK;
case VSConstants.VSStd2KCmdID.EOL_EXT:
_window.Operations.End(true);
return VSConstants.S_OK;
}
}
else if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
{
// undo/redo support:
switch ((VSConstants.VSStd97CmdID)nCmdID)
{
case VSConstants.VSStd97CmdID.Paste:
_window.Operations.Paste();
return VSConstants.S_OK;
case VSConstants.VSStd97CmdID.Cut:
_window.Operations.Cut();
return VSConstants.S_OK;
case VSConstants.VSStd97CmdID.Delete:
if (_window.Operations.Delete())
{
return VSConstants.S_OK;
}
break;
case VSConstants.VSStd97CmdID.SelectAll:
_window.Operations.SelectAll();
return VSConstants.S_OK;
}
}
return nextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
private int PreLanguageCommandFilterQueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
{
var nextTarget = firstLanguageServiceCommandFilter;
if (pguidCmdGroup == Guids.InteractiveCommandSetId)
{
switch ((CommandIds)prgCmds[0].cmdID)
{
case CommandIds.HistoryNext:
case CommandIds.HistoryPrevious:
case CommandIds.SearchHistoryNext:
case CommandIds.SearchHistoryPrevious:
// TODO: Submit?
prgCmds[0].cmdf = _window.CurrentLanguageBuffer != null ? CommandEnabled : CommandDisabled;
break;
case CommandIds.AbortExecution:
prgCmds[0].cmdf = _window.IsRunning ? CommandEnabled : CommandDisabled;
break;
case CommandIds.Reset:
prgCmds[0].cmdf = !_window.IsResetting ? CommandEnabled : CommandDisabled;
break;
default:
prgCmds[0].cmdf = CommandEnabled;
break;
}
prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU;
}
else if (currentBufferCommandHandler != null && pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
{
// undo/redo support:
switch ((VSConstants.VSStd97CmdID)prgCmds[0].cmdID)
{
case VSConstants.VSStd97CmdID.Undo:
case VSConstants.VSStd97CmdID.MultiLevelUndo:
case VSConstants.VSStd97CmdID.MultiLevelUndoList:
case VSConstants.VSStd97CmdID.Redo:
case VSConstants.VSStd97CmdID.MultiLevelRedo:
case VSConstants.VSStd97CmdID.MultiLevelRedoList:
return currentBufferCommandHandler.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
}
}
if (nextTarget != null)
{
var result = nextTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
#if DUMP_COMMANDS
//DumpCmd("QS", result, ref pguidCmdGroup, prgCmds[0].cmdID, prgCmds[0].cmdf);
#endif
return result;
}
return VSConstants.E_FAIL;
}
private int PreLanguageCommandFilterExec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
var nextTarget = firstLanguageServiceCommandFilter ?? _editorServicesCommandFilter;
if (pguidCmdGroup == Guids.InteractiveCommandSetId)
{
switch ((CommandIds)nCmdID)
{
case CommandIds.AbortExecution: _window.AbortCommand(); return VSConstants.S_OK;
case CommandIds.Reset: _window.Operations.ResetAsync(); return VSConstants.S_OK;
case CommandIds.SmartExecute: _window.Operations.ExecuteInput(); return VSConstants.S_OK;
case CommandIds.HistoryNext: _window.Operations.HistoryNext(); return VSConstants.S_OK;
case CommandIds.HistoryPrevious: _window.Operations.HistoryPrevious(); return VSConstants.S_OK;
case CommandIds.ClearScreen: _window.Operations.ClearView(); return VSConstants.S_OK;
case CommandIds.SearchHistoryNext:
_window.Operations.HistorySearchNext();
return VSConstants.S_OK;
case CommandIds.SearchHistoryPrevious:
_window.Operations.HistorySearchPrevious();
return VSConstants.S_OK;
}
}
else if (pguidCmdGroup == VSConstants.VSStd2K)
{
switch ((VSConstants.VSStd2KCmdID)nCmdID)
{
case VSConstants.VSStd2KCmdID.TYPECHAR:
_window.Operations.Delete();
break;
case VSConstants.VSStd2KCmdID.RETURN:
if (_window.Operations.TrySubmitStandardInput())
{
return VSConstants.S_OK;
}
break;
case VSConstants.VSStd2KCmdID.SHOWCONTEXTMENU:
ShowContextMenu();
return VSConstants.S_OK;
}
}
else if (currentBufferCommandHandler != null && pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
{
// undo/redo support:
switch ((VSConstants.VSStd97CmdID)nCmdID)
{
case VSConstants.VSStd97CmdID.Undo:
case VSConstants.VSStd97CmdID.MultiLevelUndo:
case VSConstants.VSStd97CmdID.MultiLevelUndoList:
case VSConstants.VSStd97CmdID.Redo:
case VSConstants.VSStd97CmdID.MultiLevelRedo:
case VSConstants.VSStd97CmdID.MultiLevelRedoList:
return currentBufferCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
}
int res = nextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
#if DUMP_COMMANDS
DumpCmd("Exec", result, ref pguidCmdGroup, nCmdID, 0);
#endif
return res;
}
private void ShowContextMenu()
{
var uishell = (IVsUIShell)InteractiveWindowPackage.GetGlobalService(typeof(SVsUIShell));
if (uishell != null)
{
var pt = System.Windows.Forms.Cursor.Position;
var position = new[] { new POINTS { x = (short)pt.X, y = (short)pt.Y } };
var guid = Guids.InteractiveCommandSetId;
ErrorHandler.ThrowOnFailure(uishell.ShowContextMenu(0, ref guid, (int)MenuIds.InteractiveWindowContextMenu, position, this));
}
}
private const uint CommandEnabled = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED);
private const uint CommandDisabled = (uint)(OLECMDF.OLECMDF_SUPPORTED);
private const uint CommandDisabledAndHidden = (uint)(OLECMDF.OLECMDF_INVISIBLE | OLECMDF.OLECMDF_SUPPORTED);
private bool CaretAtEnd
{
get
{
var caret = _window.TextView.Caret;
return caret.Position.BufferPosition.Position == caret.Position.BufferPosition.Snapshot.Length;
}
}
private bool UseSmartUpDown
{
get
{
return _window.TextView.Options.GetOptionValue(InteractiveWindowOptions.SmartUpDown);
}
}
public IOleCommandTarget EditorServicesCommandFilter
{
get
{
return _editorServicesCommandFilter;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.IO.Tests
{
public class FileStream_ctor_str_fm : FileSystemTest
{
protected virtual FileStream CreateFileStream(string path, FileMode mode)
{
return new FileStream(path, mode);
}
[Fact]
public void NullPathThrows()
{
Assert.Throws<ArgumentNullException>(() => CreateFileStream(null, FileMode.Open));
}
[Fact]
public void EmptyPathThrows()
{
Assert.Throws<ArgumentException>(() => CreateFileStream(String.Empty, FileMode.Open));
}
[Fact]
public void DirectoryThrows()
{
Assert.Throws<UnauthorizedAccessException>(() => CreateFileStream(".", FileMode.Open));
}
[Fact]
public void InvalidModeThrows()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => CreateFileStream(GetTestFilePath(), ~FileMode.Open));
}
[Theory, MemberData(nameof(TrailingCharacters))]
public void MissingFile_ThrowsFileNotFound(char trailingChar)
{
string path = GetTestFilePath() + trailingChar;
Assert.Throws<FileNotFoundException>(() => CreateFileStream(path, FileMode.Open));
}
[ActiveIssue(19965, TestPlatforms.AnyUnix)]
[Theory, MemberData(nameof(TrailingCharacters))]
public void MissingDirectory_ThrowsDirectoryNotFound(char trailingChar)
{
string path = Path.Combine(GetTestFilePath(), "file" + trailingChar);
Assert.Throws<DirectoryNotFoundException>(() => CreateFileStream(path, FileMode.Open));
}
[Fact]
public void FileModeCreate()
{
using (CreateFileStream(GetTestFilePath(), FileMode.Create))
{ }
}
[Fact]
public void FileModeCreateExisting()
{
string fileName = GetTestFilePath();
using (FileStream fs = CreateFileStream(fileName, FileMode.Create))
{
fs.WriteByte(0);
}
using (FileStream fs = CreateFileStream(fileName, FileMode.Create))
{
// Ensure that the file was re-created
Assert.Equal(0L, fs.Length);
Assert.Equal(0L, fs.Position);
Assert.True(fs.CanRead);
Assert.True(fs.CanWrite);
}
}
[Fact]
public void FileModeCreateNew()
{
using (CreateFileStream(GetTestFilePath(), FileMode.CreateNew))
{ }
}
[Fact]
public void FileModeCreateNewExistingThrows()
{
string fileName = GetTestFilePath();
using (FileStream fs = CreateFileStream(fileName, FileMode.CreateNew))
{
fs.WriteByte(0);
Assert.True(fs.CanRead);
Assert.True(fs.CanWrite);
}
Assert.Throws<IOException>(() => CreateFileStream(fileName, FileMode.CreateNew));
}
[Fact]
public void FileModeOpenThrows()
{
string fileName = GetTestFilePath();
FileNotFoundException fnfe = Assert.Throws<FileNotFoundException>(() => CreateFileStream(fileName, FileMode.Open));
Assert.Equal(fileName, fnfe.FileName);
}
[Fact]
public void FileModeOpenExisting()
{
string fileName = GetTestFilePath();
using (FileStream fs = CreateFileStream(fileName, FileMode.Create))
{
fs.WriteByte(0);
}
using (FileStream fs = CreateFileStream(fileName, FileMode.Open))
{
// Ensure that the file was re-opened
Assert.Equal(1L, fs.Length);
Assert.Equal(0L, fs.Position);
Assert.True(fs.CanRead);
Assert.True(fs.CanWrite);
}
}
[Fact]
public void FileModeOpenOrCreate()
{
using (CreateFileStream(GetTestFilePath(), FileMode.OpenOrCreate))
{}
}
[Fact]
public void FileModeOpenOrCreateExisting()
{
string fileName = GetTestFilePath();
using (FileStream fs = CreateFileStream(fileName, FileMode.Create))
{
fs.WriteByte(0);
}
using (FileStream fs = CreateFileStream(fileName, FileMode.OpenOrCreate))
{
// Ensure that the file was re-opened
Assert.Equal(1L, fs.Length);
Assert.Equal(0L, fs.Position);
Assert.True(fs.CanRead);
Assert.True(fs.CanWrite);
}
}
[Fact]
public void FileModeTruncateThrows()
{
string fileName = GetTestFilePath();
FileNotFoundException fnfe = Assert.Throws<FileNotFoundException>(() => CreateFileStream(fileName, FileMode.Truncate));
Assert.Equal(fileName, fnfe.FileName);
}
[Fact]
public void FileModeTruncateExisting()
{
string fileName = GetTestFilePath();
using (FileStream fs = CreateFileStream(fileName, FileMode.Create))
{
fs.WriteByte(0);
}
using (FileStream fs = CreateFileStream(fileName, FileMode.Truncate))
{
// Ensure that the file was re-opened and truncated
Assert.Equal(0L, fs.Length);
Assert.Equal(0L, fs.Position);
Assert.True(fs.CanRead);
Assert.True(fs.CanWrite);
}
}
[Fact]
public virtual void FileModeAppend()
{
using (FileStream fs = CreateFileStream(GetTestFilePath(), FileMode.Append))
{
Assert.Equal(false, fs.CanRead);
Assert.Equal(true, fs.CanWrite);
}
}
[Fact]
public virtual void FileModeAppendExisting()
{
string fileName = GetTestFilePath();
using (FileStream fs = CreateFileStream(fileName, FileMode.Create))
{
fs.WriteByte(0);
}
using (FileStream fs = CreateFileStream(fileName, FileMode.Append))
{
// Ensure that the file was re-opened and position set to end
Assert.Equal(1L, fs.Length);
Assert.Equal(1L, fs.Position);
Assert.False(fs.CanRead);
Assert.True(fs.CanSeek);
Assert.True(fs.CanWrite);
Assert.Throws<IOException>(() => fs.Seek(-1, SeekOrigin.Current));
Assert.Throws<NotSupportedException>(() => fs.ReadByte());
}
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using FluentAssertions;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.EntityFrameworkCore;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.ReadWrite.Deleting
{
public sealed class DeleteResourceTests : IClassFixture<IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext>>
{
private readonly IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> _testContext;
private readonly ReadWriteFakers _fakers = new();
public DeleteResourceTests(IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<WorkItemsController>();
testContext.UseController<WorkItemGroupsController>();
testContext.UseController<RgbColorsController>();
}
[Fact]
public async Task Can_delete_existing_resource()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
await dbContext.SaveChangesAsync();
});
string route = $"/workItems/{existingWorkItem.StringId}";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem workItemsInDatabase = await dbContext.WorkItems.FirstWithIdOrDefaultAsync(existingWorkItem.Id);
workItemsInDatabase.Should().BeNull();
});
}
[Fact]
public async Task Cannot_delete_unknown_resource()
{
// Arrange
string workItemId = Unknown.StringId.For<WorkItem, int>();
string route = $"/workItems/{workItemId}";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.NotFound);
error.Title.Should().Be("The requested resource does not exist.");
error.Detail.Should().Be($"Resource of type 'workItems' with ID '{workItemId}' does not exist.");
}
[Fact]
public async Task Can_delete_resource_with_OneToOne_relationship_from_dependent_side()
{
// Arrange
RgbColor existingColor = _fakers.RgbColor.Generate();
existingColor.Group = _fakers.WorkItemGroup.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.RgbColors.Add(existingColor);
await dbContext.SaveChangesAsync();
});
string route = $"/rgbColors/{existingColor.StringId}";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
RgbColor colorsInDatabase = await dbContext.RgbColors.FirstWithIdOrDefaultAsync(existingColor.Id);
colorsInDatabase.Should().BeNull();
WorkItemGroup groupInDatabase = await dbContext.Groups.FirstWithIdAsync(existingColor.Group.Id);
groupInDatabase.Color.Should().BeNull();
});
}
[Fact]
public async Task Can_delete_existing_resource_with_OneToOne_relationship_from_principal_side()
{
// Arrange
WorkItemGroup existingGroup = _fakers.WorkItemGroup.Generate();
existingGroup.Color = _fakers.RgbColor.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Groups.Add(existingGroup);
await dbContext.SaveChangesAsync();
});
string route = $"/workItemGroups/{existingGroup.StringId}";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItemGroup groupsInDatabase = await dbContext.Groups.FirstWithIdOrDefaultAsync(existingGroup.Id);
groupsInDatabase.Should().BeNull();
RgbColor colorInDatabase = await dbContext.RgbColors.FirstWithIdOrDefaultAsync(existingGroup.Color.Id);
colorInDatabase.Should().NotBeNull();
colorInDatabase.Group.Should().BeNull();
});
}
[Fact]
public async Task Can_delete_existing_resource_with_OneToMany_relationship()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
existingWorkItem.Subscribers = _fakers.UserAccount.Generate(2).ToHashSet();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
await dbContext.SaveChangesAsync();
});
string route = $"/workItems/{existingWorkItem.StringId}";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem workItemInDatabase = await dbContext.WorkItems.FirstWithIdOrDefaultAsync(existingWorkItem.Id);
workItemInDatabase.Should().BeNull();
List<UserAccount> userAccountsInDatabase = await dbContext.UserAccounts.ToListAsync();
userAccountsInDatabase.Should().ContainSingle(userAccount => userAccount.Id == existingWorkItem.Subscribers.ElementAt(0).Id);
userAccountsInDatabase.Should().ContainSingle(userAccount => userAccount.Id == existingWorkItem.Subscribers.ElementAt(1).Id);
});
}
[Fact]
public async Task Can_delete_resource_with_ManyToMany_relationship()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
existingWorkItem.Tags = _fakers.WorkTag.Generate(1).ToHashSet();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
await dbContext.SaveChangesAsync();
});
string route = $"/workItems/{existingWorkItem.StringId}";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem workItemInDatabase = await dbContext.WorkItems.FirstWithIdOrDefaultAsync(existingWorkItem.Id);
workItemInDatabase.Should().BeNull();
WorkTag tagInDatabase = await dbContext.WorkTags.FirstWithIdOrDefaultAsync(existingWorkItem.Tags.ElementAt(0).Id);
tagInDatabase.Should().NotBeNull();
});
}
}
}
| |
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.IO;
using Microsoft.TeamFoundation.Build.WebApi;
using Microsoft.VisualStudio.Services.Agent.Worker.Maintenance;
namespace Microsoft.VisualStudio.Services.Agent.Worker.Build
{
[ServiceLocator(Default = typeof(BuildDirectoryManager))]
public interface IBuildDirectoryManager : IAgentService
{
TrackingConfig PrepareDirectory(
IExecutionContext executionContext,
ServiceEndpoint endpoint,
ISourceProvider sourceProvider);
void CreateDirectory(
IExecutionContext executionContext,
string description, string path,
bool deleteExisting);
void SaveDevelopmentSnapshot(
IExecutionContext executionContext,
string name
);
void RestoreDevelopmentSnapshot(
IExecutionContext executionContext,
string name
);
}
public sealed class BuildDirectoryManager : AgentService, IBuildDirectoryManager, IMaintenanceServiceProvider
{
public string MaintenanceDescription => StringUtil.Loc("DeleteUnusedBuildDir");
public Type ExtensionType => typeof(IMaintenanceServiceProvider);
public TrackingConfig PrepareDirectory(
IExecutionContext executionContext,
ServiceEndpoint endpoint,
ISourceProvider sourceProvider)
{
// Validate parameters.
Trace.Entering();
ArgUtil.NotNull(executionContext, nameof(executionContext));
ArgUtil.NotNull(executionContext.Variables, nameof(executionContext.Variables));
ArgUtil.NotNull(endpoint, nameof(endpoint));
ArgUtil.NotNull(sourceProvider, nameof(sourceProvider));
var trackingManager = HostContext.GetService<ITrackingManager>();
// Defer to the source provider to calculate the hash key.
Trace.Verbose("Calculating build directory hash key.");
string hashKey = sourceProvider.GetBuildDirectoryHashKey(executionContext, endpoint);
Trace.Verbose($"Hash key: {hashKey}");
// Load the existing tracking file if one already exists.
string trackingFile = Path.Combine(
IOUtil.GetWorkPath(HostContext),
Constants.Build.Path.SourceRootMappingDirectory,
executionContext.Variables.System_CollectionId,
executionContext.Variables.System_DefinitionId,
Constants.Build.Path.TrackingConfigFile);
Trace.Verbose($"Loading tracking config if exists: {trackingFile}");
TrackingConfigBase existingConfig = trackingManager.LoadIfExists(executionContext, trackingFile);
// Check if the build needs to be garbage collected. If the hash key
// has changed, then the existing build directory cannot be reused.
TrackingConfigBase garbageConfig = null;
if (existingConfig != null
&& !string.Equals(existingConfig.HashKey, hashKey, StringComparison.OrdinalIgnoreCase))
{
// Just store a reference to the config for now. It can safely be
// marked for garbage collection only after the new build directory
// config has been created.
Trace.Verbose($"Hash key from existing tracking config does not match. Existing key: {existingConfig.HashKey}");
garbageConfig = existingConfig;
existingConfig = null;
}
// Create a new tracking config if required.
TrackingConfig newConfig;
if (existingConfig == null)
{
Trace.Verbose("Creating a new tracking config file.");
newConfig = trackingManager.Create(
executionContext,
endpoint,
hashKey,
trackingFile,
sourceProvider.TestOverrideBuildDirectory());
ArgUtil.NotNull(newConfig, nameof(newConfig));
}
else
{
// Convert legacy format to the new format if required.
newConfig = ConvertToNewFormat(executionContext, endpoint, existingConfig);
// For existing tracking config files, update the job run properties.
Trace.Verbose("Updating job run properties.");
trackingManager.UpdateJobRunProperties(executionContext, newConfig, trackingFile);
}
// Mark the old configuration for garbage collection.
if (garbageConfig != null)
{
Trace.Verbose("Marking existing config for garbage collection.");
trackingManager.MarkForGarbageCollection(executionContext, garbageConfig);
}
// Prepare the build directory.
// There are 2 ways to provide build directory clean policy.
// 1> set definition variable build.clean or agent.clean.buildDirectory. (on-prem user need to use this, since there is no Web UI in TFS 2016)
// 2> select source clean option in definition repository tab. (VSTS will have this option in definition designer UI)
BuildCleanOption cleanOption = GetBuildDirectoryCleanOption(executionContext, endpoint);
CreateDirectory(
executionContext,
description: "build directory",
path: Path.Combine(IOUtil.GetWorkPath(HostContext), newConfig.BuildDirectory),
deleteExisting: cleanOption == BuildCleanOption.All);
CreateDirectory(
executionContext,
description: "artifacts directory",
path: Path.Combine(IOUtil.GetWorkPath(HostContext), newConfig.ArtifactsDirectory),
deleteExisting: true);
CreateDirectory(
executionContext,
description: "test results directory",
path: Path.Combine(IOUtil.GetWorkPath(HostContext), newConfig.TestResultsDirectory),
deleteExisting: true);
CreateDirectory(
executionContext,
description: "binaries directory",
path: Path.Combine(IOUtil.GetWorkPath(HostContext), newConfig.BuildDirectory, Constants.Build.Path.BinariesDirectory),
deleteExisting: cleanOption == BuildCleanOption.Binary);
CreateDirectory(
executionContext,
description: "source directory",
path: Path.Combine(IOUtil.GetWorkPath(HostContext), newConfig.BuildDirectory, Constants.Build.Path.SourcesDirectory),
deleteExisting: cleanOption == BuildCleanOption.Source);
return newConfig;
}
public void SaveDevelopmentSnapshot(IExecutionContext executionContext, string name)
{
Trace.Entering();
IOUtil.DeleteDirectory(
Path.Combine(IOUtil.GetDevelopmentPath(HostContext), name),
executionContext.CancellationToken);
IOUtil.CopyDirectory(
executionContext.Variables.Agent_BuildDirectory,
Path.Combine(IOUtil.GetDevelopmentPath(HostContext), name),
executionContext.CancellationToken);
}
public void RestoreDevelopmentSnapshot(IExecutionContext executionContext, string name)
{
Trace.Entering();
IOUtil.DeleteDirectory(
executionContext.Variables.Agent_BuildDirectory,
executionContext.CancellationToken);
IOUtil.CopyDirectory(
Path.Combine(IOUtil.GetDevelopmentPath(HostContext), name),
executionContext.Variables.Agent_BuildDirectory,
executionContext.CancellationToken);
}
public void RunMaintenanceOperation(IExecutionContext executionContext)
{
Trace.Entering();
ArgUtil.NotNull(executionContext, nameof(executionContext));
var trackingManager = HostContext.GetService<ITrackingManager>();
int staleBuildDirThreshold = executionContext.Variables.GetInt("maintenance.deleteworkingdirectory.daysthreshold") ?? 0;
if (staleBuildDirThreshold > 0)
{
// scan unused build directories
executionContext.Output(StringUtil.Loc("DiscoverBuildDir", staleBuildDirThreshold));
trackingManager.MarkExpiredForGarbageCollection(executionContext, TimeSpan.FromDays(staleBuildDirThreshold));
}
else
{
executionContext.Output(StringUtil.Loc("GCBuildDirNotEnabled"));
return;
}
executionContext.Output(StringUtil.Loc("GCBuildDir"));
// delete unused build directories
trackingManager.DisposeCollectedGarbage(executionContext);
}
private TrackingConfig ConvertToNewFormat(
IExecutionContext executionContext,
ServiceEndpoint endpoint,
TrackingConfigBase config)
{
Trace.Entering();
// If it's already in the new format, return it.
TrackingConfig newConfig = config as TrackingConfig;
if (newConfig != null)
{
return newConfig;
}
// Delete the legacy artifact/staging directories.
LegacyTrackingConfig legacyConfig = config as LegacyTrackingConfig;
DeleteDirectory(
executionContext,
description: "legacy artifacts directory",
path: Path.Combine(legacyConfig.BuildDirectory, Constants.Build.Path.LegacyArtifactsDirectory));
DeleteDirectory(
executionContext,
description: "legacy staging directory",
path: Path.Combine(legacyConfig.BuildDirectory, Constants.Build.Path.LegacyStagingDirectory));
// Determine the source directory name. Check if the directory is named "s" already.
// Convert the source directory to be named "s" if there is a problem with the old name.
string sourcesDirectoryNameOnly = Constants.Build.Path.SourcesDirectory;
if (!Directory.Exists(Path.Combine(legacyConfig.BuildDirectory, sourcesDirectoryNameOnly))
&& !String.Equals(endpoint.Name, Constants.Build.Path.ArtifactsDirectory, StringComparison.OrdinalIgnoreCase)
&& !String.Equals(endpoint.Name, Constants.Build.Path.LegacyArtifactsDirectory, StringComparison.OrdinalIgnoreCase)
&& !String.Equals(endpoint.Name, Constants.Build.Path.LegacyStagingDirectory, StringComparison.OrdinalIgnoreCase)
&& !String.Equals(endpoint.Name, Constants.Build.Path.TestResultsDirectory, StringComparison.OrdinalIgnoreCase)
&& !endpoint.Name.Contains("\\")
&& !endpoint.Name.Contains("/")
&& Directory.Exists(Path.Combine(legacyConfig.BuildDirectory, endpoint.Name)))
{
sourcesDirectoryNameOnly = endpoint.Name;
}
// Convert to the new format.
newConfig = new TrackingConfig(
executionContext,
legacyConfig,
sourcesDirectoryNameOnly,
// The legacy artifacts directory has been deleted at this point - see above - so
// switch the configuration to using the new naming scheme.
useNewArtifactsDirectoryName: true);
return newConfig;
}
public void CreateDirectory(IExecutionContext executionContext, string description, string path, bool deleteExisting)
{
// Delete.
if (deleteExisting)
{
executionContext.Debug($"Delete existing {description}: '{path}'");
DeleteDirectory(executionContext, description, path);
}
// Create.
if (!Directory.Exists(path))
{
executionContext.Debug($"Creating {description}: '{path}'");
Trace.Info($"Creating {description}.");
Directory.CreateDirectory(path);
}
}
private void DeleteDirectory(IExecutionContext executionContext, string description, string path)
{
Trace.Info($"Checking if {description} exists: '{path}'");
if (Directory.Exists(path))
{
executionContext.Debug($"Deleting {description}: '{path}'");
IOUtil.DeleteDirectory(path, executionContext.CancellationToken);
}
}
// Prefer variable over endpoint data when get build directory clean option.
// Prefer agent.clean.builddirectory over build.clean when use variable
// available value for build.clean or agent.clean.builddirectory:
// Delete entire build directory if build.clean=all is set.
// Recreate binaries dir if clean=binary is set.
// Recreate source dir if clean=src is set.
private BuildCleanOption GetBuildDirectoryCleanOption(IExecutionContext executionContext, ServiceEndpoint endpoint)
{
BuildCleanOption? cleanOption = executionContext.Variables.Build_Clean;
if (cleanOption != null)
{
return cleanOption.Value;
}
bool clean = false;
if (endpoint.Data.ContainsKey(WellKnownEndpointData.Clean))
{
clean = StringUtil.ConvertToBoolean(endpoint.Data[WellKnownEndpointData.Clean]);
}
if (clean && endpoint.Data.ContainsKey("cleanOptions"))
{
RepositoryCleanOptions? cleanOptionFromEndpoint = EnumUtil.TryParse<RepositoryCleanOptions>(endpoint.Data["cleanOptions"]);
if (cleanOptionFromEndpoint != null)
{
if (cleanOptionFromEndpoint == RepositoryCleanOptions.AllBuildDir)
{
return BuildCleanOption.All;
}
else if (cleanOptionFromEndpoint == RepositoryCleanOptions.SourceDir)
{
return BuildCleanOption.Source;
}
else if (cleanOptionFromEndpoint == RepositoryCleanOptions.SourceAndOutput)
{
return BuildCleanOption.Binary;
}
}
}
return BuildCleanOption.None;
}
}
// TODO: use enum defined in build2.webapi when it's available.
public enum RepositoryCleanOptions
{
Source,
SourceAndOutput,
SourceDir,
AllBuildDir,
}
}
| |
/*===============================================================================
Copyright (c) 2015-2016 PTC Inc. All Rights Reserved.
Copyright (c) 2012-2014 Qualcomm Connected Experiences, Inc. All Rights Reserved.
Vuforia is a trademark of PTC Inc., registered in the United States and other
countries.
==============================================================================*/
using UnityEngine;
using Vuforia;
using System.Collections;
/// <summary>
/// The VideoPlaybackBehaviour manages the appearance of a video that can be superimposed on a target.
/// Playback controls are shown on top of it to control the video.
/// </summary>
public class VideoPlaybackBehaviour : MonoBehaviour
{
#region PUBLIC_MEMBER_VARIABLES
/// <summary>
/// URL of the video, either a path to a local file or a remote address
/// </summary>
public string m_path = null;
/// <summary>
/// Texture for the play icon
/// </summary>
public Texture m_playTexture = null;
/// <summary>
/// Texture for the busy icon
/// </summary>
public Texture m_busyTexture = null;
/// <summary>
/// Texture for the error icon
/// </summary>
public Texture m_errorTexture = null;
/// <summary>
/// Define whether video should automatically start
/// </summary>
public bool m_autoPlay = false;
#endregion // PUBLIC_MEMBER_VARIABLES
#region PRIVATE_MEMBER_VARIABLES
private static bool sLoadingLocked = false;
private VideoPlayerHelper mVideoPlayer = null;
private bool mIsInited = false;
private bool mInitInProgess = false;
private bool mAppPaused = false;
private Texture2D mVideoTexture = null;
[SerializeField]
[HideInInspector]
private Texture mKeyframeTexture = null;
private VideoPlayerHelper.MediaType mMediaType =
VideoPlayerHelper.MediaType.ON_TEXTURE_FULLSCREEN;
private VideoPlayerHelper.MediaState mCurrentState =
VideoPlayerHelper.MediaState.NOT_READY;
private float mSeekPosition = 0.0f;
private bool isPlayableOnTexture;
private GameObject mIconPlane = null;
private bool mIconPlaneActive = false;
#endregion // PRIVATE_MEMBER_VARIABLES
#region PROPERTIES
/// <summary>
/// Returns the video player
/// </summary>
public VideoPlayerHelper VideoPlayer
{
get { return mVideoPlayer; }
}
/// <summary>
/// Returns the current playback state
/// </summary>
public VideoPlayerHelper.MediaState CurrentState
{
get { return mCurrentState; }
}
/// <summary>
/// Type of playback (on-texture only, fullscreen only, or both)
/// </summary>
public VideoPlayerHelper.MediaType MediaType
{
get { return mMediaType; }
set { mMediaType = value; }
}
/// <summary>
/// Texture displayed before video playback begins
/// </summary>
public Texture KeyframeTexture
{
get { return mKeyframeTexture; }
set { mKeyframeTexture = value; }
}
/// <summary>
/// Returns whether the video should automatically start
/// </summary>
public bool AutoPlay
{
get { return m_autoPlay; }
}
#endregion // PROPERTIES
#region UNITY_MONOBEHAVIOUR_METHODS
void Start()
{
// Find the icon plane (child of this object)
mIconPlane = transform.Find("Icon").gameObject;
// A filename or url must be set in the inspector
if (m_path == null || m_path.Length == 0)
{
Debug.Log("Please set a video url in the Inspector");
HandleStateChange(VideoPlayerHelper.MediaState.ERROR);
mCurrentState = VideoPlayerHelper.MediaState.ERROR;
this.enabled = false;
}
else
{
// Set the current state to Not Ready
HandleStateChange(VideoPlayerHelper.MediaState.NOT_READY);
mCurrentState = VideoPlayerHelper.MediaState.NOT_READY;
}
// Create the video player and set the filename
mVideoPlayer = new VideoPlayerHelper();
mVideoPlayer.SetFilename(m_path);
// Flip the plane as the video texture is mirrored on the horizontal
transform.localScale = new Vector3(-1 * Mathf.Abs(transform.localScale.x),
transform.localScale.y, transform.localScale.z);
// Scale the icon
ScaleIcon();
}
void OnRenderObject()
{
if (mAppPaused) return;
CheckIconPlaneVisibility();
if (!mIsInited)
{
if (!mInitInProgess)
{
mInitInProgess = true;
StartCoroutine(InitVideoPlayer());
}
return;
}
if (isPlayableOnTexture)
{
// Update the video texture with the latest video frame
VideoPlayerHelper.MediaState state = mVideoPlayer.UpdateVideoData();
if ((state == VideoPlayerHelper.MediaState.PLAYING)
|| (state == VideoPlayerHelper.MediaState.PLAYING_FULLSCREEN))
{
#if UNITY_WSA_10_0 && !UNITY_EDITOR
// For Direct3D video texture update, we need to be on the rendering thread
GL.IssuePluginEvent(VideoPlayerHelper.GetNativeRenderEventFunc(), 0);
#else
GL.InvalidateState();
#endif
}
// Check for playback state change
if (state != mCurrentState)
{
HandleStateChange(state);
mCurrentState = state;
}
}
else
{
// Get the current status
VideoPlayerHelper.MediaState state = mVideoPlayer.GetStatus();
if ((state == VideoPlayerHelper.MediaState.PLAYING)
|| (state == VideoPlayerHelper.MediaState.PLAYING_FULLSCREEN))
{
GL.InvalidateState();
}
// Check for playback state change
if (state != mCurrentState)
{
HandleStateChange(state);
mCurrentState = state;
}
}
}
private IEnumerator InitVideoPlayer()
{
// Initialize the video player
bool isMetalRendering = (VuforiaRenderer.Instance.GetRendererAPI() == VuforiaRenderer.RendererAPI.METAL);
if (mVideoPlayer.Init(isMetalRendering))
{
yield return new WaitForEndOfFrame();
// Wait in case other videos are loading at the same time
while (sLoadingLocked)
{
yield return new WaitForSeconds(0.5f);
}
// Now we can proceed to load the video
StartCoroutine(LoadVideo());
}
else
{
Debug.Log("Could not initialize video player");
HandleStateChange(VideoPlayerHelper.MediaState.ERROR);
this.enabled = false;
}
}
private IEnumerator LoadVideo()
{
// Lock file loading
sLoadingLocked = true;
// Load the video
if (mVideoPlayer.Load(m_path, mMediaType, false, 0))
{
yield return new WaitForEndOfFrame();
#if UNITY_WSA_10_0 && !UNITY_EDITOR
// On Windows 10 (WSA), we need to wait a little bit after loading a video,
// to avoid potential conflicts when loading multiple videos
yield return new WaitForSeconds(1.5f);
#endif
// Unlock file loading
sLoadingLocked = false;
// Proceed to video preparation
StartCoroutine( PrepareVideo() );
}
else
{
// Unlock file loading
sLoadingLocked = false;
Debug.Log("Could not load video '" + m_path + "' for media type " + mMediaType);
HandleStateChange(VideoPlayerHelper.MediaState.ERROR);
this.enabled = false;
}
}
private IEnumerator PrepareVideo()
{
// Get the video player status
VideoPlayerHelper.MediaState state = mVideoPlayer.GetStatus();
if (state == VideoPlayerHelper.MediaState.ERROR)
{
Debug.Log("Cannot prepare video, as the player is in error state.");
HandleStateChange(VideoPlayerHelper.MediaState.ERROR);
this.enabled = false;
}
else
{
// Not in error state, we can move on...
while (mVideoPlayer.GetStatus() == VideoPlayerHelper.MediaState.NOT_READY)
{
// Wait one or few frames for video state to become ready
yield return new WaitForEndOfFrame();
}
// Video player is ready
Debug.Log("VideoPlayer ready.");
// Initialize the video texture
bool isOpenGLRendering = (VuforiaRenderer.Instance.GetRendererAPI() == VuforiaRenderer.RendererAPI.GL_20);
InitVideoTexture(isOpenGLRendering);
// Can we play this video on a texture?
isPlayableOnTexture = mVideoPlayer.IsPlayableOnTexture();
if (isPlayableOnTexture)
{
// Pass the video texture id to the video player
mVideoPlayer.SetVideoTexturePtr(mVideoTexture.GetNativeTexturePtr());
// Get the video width and height
int videoWidth = mVideoPlayer.GetVideoWidth();
int videoHeight = mVideoPlayer.GetVideoHeight();
if (videoWidth > 0 && videoHeight > 0)
{
// Scale the video plane to match the video aspect ratio
float aspect = videoHeight / (float)videoWidth;
// Flip the plane as the video texture is mirrored on the horizontal
transform.localScale = new Vector3(-0.1f, 0.1f, 0.1f * aspect);
}
// Seek ahead if necessary
if (mSeekPosition > 0)
{
mVideoPlayer.SeekTo(mSeekPosition);
}
}
else
{
// Handle the state change
state = mVideoPlayer.GetStatus();
HandleStateChange(state);
mCurrentState = state;
}
// Scale the icon
ScaleIcon();
mIsInited = true;
}
mInitInProgess = false;
yield return new WaitForEndOfFrame();
}
void OnApplicationPause(bool pause)
{
mAppPaused = pause;
if (!mIsInited)
return;
if (pause)
{
// Handle pause event natively
mVideoPlayer.OnPause();
// Store the playback position for later
mSeekPosition = mVideoPlayer.GetCurrentPosition();
// Deinit the video
mVideoPlayer.Deinit();
// Reset initialization parameters
mIsInited = false;
mInitInProgess = false;
// Set the current state to Not Ready
HandleStateChange(VideoPlayerHelper.MediaState.NOT_READY);
mCurrentState = VideoPlayerHelper.MediaState.NOT_READY;
}
}
void OnDestroy()
{
// Deinit the video
mVideoPlayer.Deinit();
}
#endregion // UNITY_MONOBEHAVIOUR_METHODS
#region PUBLIC_METHODS
/// <summary>
/// Displays the busy icon on top of the video
/// </summary>
public void ShowBusyIcon()
{
mIconPlane.GetComponent<Renderer>().material.mainTexture = m_busyTexture;
}
/// <summary>
/// Displays the play icon on top of the video
/// </summary>
public void ShowPlayIcon()
{
mIconPlane.GetComponent<Renderer>().material.mainTexture = m_playTexture;
}
#endregion // PUBLIC_METHODS
#region PRIVATE_METHODS
// Initialize the video texture
private void InitVideoTexture(bool isOpenGLRendering)
{
// Create texture whose content will be updated in native plugin code.
// Note: width and height don't matter and may be zero for OpenGL textures,
// as we update the texture content via glTexImage;
// however they MUST be correctly initialized for iOS METAL and D3D textures;
// similarly, the format must be correctly initialized to 4 bytes (BGRA32) per pixel
int w = mVideoPlayer.GetVideoWidth();
int h = mVideoPlayer.GetVideoHeight();
Debug.Log("InitVideoTexture with size: " + w + " x " + h);
mVideoTexture = isOpenGLRendering ?
new Texture2D(0, 0, TextureFormat.RGB565, false) :
new Texture2D(w, h, TextureFormat.BGRA32, false);
mVideoTexture.filterMode = FilterMode.Bilinear;
mVideoTexture.wrapMode = TextureWrapMode.Clamp;
}
// Handle video playback state changes
private void HandleStateChange(VideoPlayerHelper.MediaState newState)
{
// If the movie is playing or paused render the video texture
// Otherwise render the keyframe
if (newState == VideoPlayerHelper.MediaState.PLAYING ||
newState == VideoPlayerHelper.MediaState.PAUSED)
{
Material mat = GetComponent<Renderer>().material;
mat.mainTexture = mVideoTexture;
mat.mainTextureScale = new Vector2(1, 1);
}
else
{
if (mKeyframeTexture != null)
{
Material mat = GetComponent<Renderer>().material;
mat.mainTexture = mKeyframeTexture;
mat.mainTextureScale = new Vector2(1, -1);
}
}
// Display the appropriate icon, or disable if not needed
switch (newState)
{
case VideoPlayerHelper.MediaState.READY:
case VideoPlayerHelper.MediaState.REACHED_END:
case VideoPlayerHelper.MediaState.PAUSED:
case VideoPlayerHelper.MediaState.STOPPED:
mIconPlane.GetComponent<Renderer>().material.mainTexture = m_playTexture;
mIconPlaneActive = true;
break;
case VideoPlayerHelper.MediaState.NOT_READY:
case VideoPlayerHelper.MediaState.PLAYING_FULLSCREEN:
mIconPlane.GetComponent<Renderer>().material.mainTexture = m_busyTexture;
mIconPlaneActive = true;
break;
case VideoPlayerHelper.MediaState.ERROR:
mIconPlane.GetComponent<Renderer>().material.mainTexture = m_errorTexture;
mIconPlaneActive = true;
break;
default:
mIconPlaneActive = false;
break;
}
if (newState == VideoPlayerHelper.MediaState.PLAYING_FULLSCREEN)
{
// Switching to full screen, disable VuforiaBehaviour (only applicable for iOS)
VuforiaBehaviour.Instance.enabled = false;
}
else if (mCurrentState == VideoPlayerHelper.MediaState.PLAYING_FULLSCREEN)
{
// Switching away from full screen, enable VuforiaBehaviour (only applicable for iOS)
VuforiaBehaviour.Instance.enabled = true;
}
}
private void ScaleIcon()
{
// Icon should fill 50% of the narrowest side of the video
float videoWidth = Mathf.Abs(transform.localScale.x);
float videoHeight = Mathf.Abs(transform.localScale.z);
float iconWidth, iconHeight;
if (videoWidth > videoHeight)
{
iconWidth = 0.5f * videoHeight / videoWidth;
iconHeight = 0.5f;
}
else
{
iconWidth = 0.5f;
iconHeight = 0.5f * videoWidth / videoHeight;
}
mIconPlane.transform.localScale = new Vector3(-iconWidth, 1.0f, iconHeight);
}
private void CheckIconPlaneVisibility()
{
// If the video object renderer is currently enabled, we might need to toggle the icon plane visibility
if (GetComponent<Renderer>().enabled)
{
// Check if the icon plane renderer has to be disabled explicitly in case it was enabled by another script (e.g. TrackableEventHandler)
Renderer rendererComp = mIconPlane.GetComponent<Renderer>();
if (rendererComp.enabled != mIconPlaneActive)
rendererComp.enabled = mIconPlaneActive;
}
}
#endregion // PRIVATE_METHODS
}
| |
//
// Copyright 2011-2014, 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.Linq;
using System.Linq.Expressions;
using System.Text;
using Android.Provider;
namespace Xamarin
{
internal class ContentQueryTranslator
: ExpressionVisitor
{
public ContentQueryTranslator (IQueryProvider provider, ITableFinder tableFinder)
{
this.provider = provider;
this.tableFinder = tableFinder;
Skip = -1;
Take = -1;
}
public Android.Net.Uri Table
{
get;
private set;
}
public bool IsAny
{
get;
private set;
}
public bool IsCount
{
get;
private set;
}
public Type ReturnType
{
get;
private set;
}
public IEnumerable<ContentResolverColumnMapping> Projections
{
get { return this.projections; }
}
public string QueryString
{
get { return (this.queryBuilder.Length > 0) ? this.queryBuilder.ToString() : null; }
}
public string[] ClauseParameters
{
get { return (this.arguments.Count > 0) ? this.arguments.ToArray() : null; }
}
public string SortString
{
get { return (this.sortBuilder != null) ? this.sortBuilder.ToString() : null; }
}
public int Skip
{
get;
private set;
}
public int Take
{
get;
private set;
}
public Expression Translate (Expression expression)
{
Expression expr = Visit (expression);
if (Table == null)
Table = this.tableFinder.DefaultTable;
return expr;
}
private readonly IQueryProvider provider;
private readonly ITableFinder tableFinder;
private bool fallback = false;
private List<ContentResolverColumnMapping> projections;
private StringBuilder sortBuilder;
private readonly List<string> arguments = new List<string>();
private readonly StringBuilder queryBuilder = new StringBuilder();
protected override Expression VisitMethodCall (MethodCallExpression methodCall)
{
if (methodCall.Arguments.Count == 0 || !(methodCall.Arguments[0] is ConstantExpression || methodCall.Arguments[0] is MethodCallExpression))
{
this.fallback = true;
return methodCall;
}
Expression expression = base.VisitMethodCall (methodCall);
methodCall = expression as MethodCallExpression;
if (methodCall == null)
{
this.fallback = true;
return expression;
}
if (!this.fallback)
{
if (methodCall.Method.Name == "Where")
expression = VisitWhere (methodCall);
else if (methodCall.Method.Name == "Any")
expression = VisitAny (methodCall);
else if (methodCall.Method.Name == "Select")
expression = VisitSelect (methodCall);
else if (methodCall.Method.Name == "SelectMany")
expression = VisitSelectMany (methodCall);
else if (methodCall.Method.Name == "OrderBy" || methodCall.Method.Name == "OrderByDescending")
expression = VisitOrder (methodCall);
else if (methodCall.Method.Name == "Skip")
expression = VisitSkip (methodCall);
else if (methodCall.Method.Name == "Take")
expression = VisitTake (methodCall);
else if (methodCall.Method.Name == "Count")
expression = VisitCount (methodCall);
else if (methodCall.Method.Name == "First" || methodCall.Method.Name == "FirstOrDefault")
expression = VisitFirst (methodCall);
else if (methodCall.Method.Name == "Single" || methodCall.Method.Name == "SingleOrDefault")
expression = VisitSingle (methodCall);
}
return expression;
}
private Expression VisitFirst (MethodCallExpression methodCall)
{
if (methodCall.Arguments.Count > 1)
{
VisitWhere (methodCall);
if (this.fallback)
return methodCall;
}
Take = 1;
return methodCall;
}
private Expression VisitSingle (MethodCallExpression methodCall)
{
if (methodCall.Arguments.Count > 1)
{
VisitWhere (methodCall);
if (this.fallback)
return methodCall;
}
Take = 2;
return methodCall;
}
private Expression VisitCount (MethodCallExpression methodCall)
{
if (methodCall.Arguments.Count > 1)
{
VisitWhere (methodCall);
if (this.fallback)
return methodCall;
}
IsCount = true;
return methodCall.Arguments[0];
}
private Expression VisitTake (MethodCallExpression methodCall)
{
ConstantExpression ce = (ConstantExpression) methodCall.Arguments[1];
Take = (int) ce.Value;
return methodCall.Arguments[0];
}
private Expression VisitSkip (MethodCallExpression methodCall)
{
ConstantExpression ce = (ConstantExpression) methodCall.Arguments[1];
Skip = (int) ce.Value;
return methodCall.Arguments[0];
}
private Expression VisitAny (MethodCallExpression methodCall)
{
if (methodCall.Arguments.Count > 1)
{
VisitWhere (methodCall);
if (this.fallback)
return methodCall;
}
IsAny = true;
return methodCall.Arguments[0];
}
private class WhereEvaluator
: ExpressionVisitor
{
public WhereEvaluator (ITableFinder tableFinder, Android.Net.Uri existingTable)
{
this.tableFinder = tableFinder;
if (existingTable != null)
this.table = new TableFindResult (existingTable, null);
}
public Android.Net.Uri Table
{
get { return this.table.Table; }
}
public string QueryString
{
get { return this.builder.ToString(); }
}
public List<string> Arguments
{
get { return this.arguments; }
}
public bool Fallback
{
get;
private set;
}
public Expression Evaluate (Expression expression)
{
expression = Visit (expression);
if (!Fallback && this.table != null && this.table.MimeType != null) {
this.builder.Insert (0, String.Format ("(({0} = ?) AND ", ContactsContract.DataColumns.Mimetype));
this.builder.Append (")");
this.arguments.Insert (0, this.table.MimeType);
}
return expression;
}
private readonly ITableFinder tableFinder;
private TableFindResult table;
private StringBuilder builder = new StringBuilder();
private readonly List<string> arguments = new List<string>();
private ContentResolverColumnMapping currentMap;
protected override Expression VisitMemberAccess (MemberExpression memberExpression)
{
TableFindResult result = this.tableFinder.Find (memberExpression);
if (this.table == null)
this.table = result;
else if (Table != result.Table || result.MimeType != this.table.MimeType) {
Fallback = true;
return memberExpression;
}
ContentResolverColumnMapping cmap = this.tableFinder.GetColumn (memberExpression.Member);
if (cmap == null || cmap.Columns == null)
{
Fallback = true;
return memberExpression;
}
this.currentMap = cmap;
if (cmap.Columns.Length == 1)
this.builder.Append (cmap.Columns[0]);
else
throw new NotSupportedException();
return base.VisitMemberAccess (memberExpression);
}
protected override Expression VisitConstant (ConstantExpression constant)
{
if (constant.Value is IQueryable)
return constant;
if (constant.Value == null)
this.builder.Append ("NULL");
else
{
object value = constant.Value;
if (this.currentMap != null && this.currentMap.ValueToQueryable != null)
value = this.currentMap.ValueToQueryable (value);
switch (Type.GetTypeCode (value.GetType()))
{
case TypeCode.Object:
Fallback = true;
return constant;
case TypeCode.Boolean:
this.arguments.Add ((bool)value ? "1" : "0");
this.builder.Append ("?");
break;
default:
this.arguments.Add (value.ToString());
this.builder.Append ("?");
break;
}
}
return base.VisitConstant (constant);
}
protected override Expression VisitBinary (BinaryExpression binary)
{
string current = this.builder.ToString();
this.builder = new StringBuilder();
Visit (binary.Left);
if (Fallback)
return binary;
string left = this.builder.ToString();
this.builder = new StringBuilder();
string joiner;
switch (binary.NodeType)
{
case ExpressionType.AndAlso:
joiner = " AND ";
break;
case ExpressionType.OrElse:
joiner = " OR ";
break;
case ExpressionType.Equal:
joiner = " = ";
break;
case ExpressionType.GreaterThan:
joiner = " > ";
break;
case ExpressionType.LessThan:
joiner = " < ";
break;
case ExpressionType.NotEqual:
joiner = " IS NOT ";
break;
default:
Fallback = true;
return binary;
}
Visit (binary.Right);
if (Fallback) {
if (binary.NodeType == ExpressionType.AndAlso) {
Fallback = false;
this.builder = new StringBuilder (current);
this.builder.Append ("(");
this.builder.Append (left);
this.builder.Append (")");
return binary.Right;
} else
return binary;
}
string right = this.builder.ToString();
this.builder = new StringBuilder (current);
this.builder.Append ("(");
this.builder.Append (left);
this.builder.Append (joiner);
this.builder.Append (right);
this.builder.Append (")");
return binary;
}
}
private Expression VisitWhere (MethodCallExpression methodCall)
{
Expression expression = ExpressionEvaluator.Evaluate (methodCall);
var eval = new WhereEvaluator (this.tableFinder, Table);
expression = eval.Evaluate (expression);
if (eval.Fallback || eval.Table == null || (Table != null && eval.Table != Table)) {
this.fallback = true;
return methodCall;
}
if (Table == null)
Table = eval.Table;
this.arguments.AddRange (eval.Arguments);
if (this.queryBuilder.Length > 0)
this.queryBuilder.Append (" AND ");
this.queryBuilder.Append (eval.QueryString);
return methodCall.Arguments[0];
}
private Type GetExpressionArgumentType (Expression expression)
{
switch (expression.NodeType)
{
case ExpressionType.Constant:
return ((ConstantExpression) expression).Value.GetType();
}
return null;
}
private Expression VisitSelect (MethodCallExpression methodCall)
{
MemberExpression me = FindMemberExpression (methodCall.Arguments[1]);
if (!TryGetTable (me))
return methodCall;
ContentResolverColumnMapping column = this.tableFinder.GetColumn (me.Member);
if (column == null || column.Columns == null)
return methodCall;
(this.projections ?? (this.projections = new List<ContentResolverColumnMapping>())).Add (column);
if (column.ReturnType.IsValueType || column.ReturnType == typeof(string))
ReturnType = column.ReturnType;
this.fallback = true;
Type argType = GetExpressionArgumentType (methodCall.Arguments[0]);
if (ReturnType == null || (argType != null && ReturnType.IsAssignableFrom (argType)))
return methodCall.Arguments[0];
return Expression.Constant (Activator.CreateInstance (typeof (Query<>).MakeGenericType (ReturnType), this.provider));
}
// private Expression VisitSelect (MethodCallExpression methodCall)
// {
// List<MemberExpression> mes = MemberExpressionFinder.Find (methodCall.Arguments[1], this.tableFinder);
// if (!TryGetTable (mes))
// return methodCall;
//
// Type returnType = null;
//
// List<Tuple<string, Type>> projs = new List<Tuple<string, Type>>();
// foreach (MemberExpression me in mes)
// {
// Tuple<string, Type> column = this.tableFinder.GetColumn (me.Member);
// if (column == null)
// return methodCall;
//
// if (returnType == null)
// returnType = column.Item2;
// if (returnType != column.Item2)
// return methodCall;
//
// projs.Add (column);
// }
//
// ReturnType = returnType;
// this.fallback = true;
//
// (this.projections ?? (this.projections = new List<Tuple<string, Type>>()))
// .AddRange (projs);
//
// return methodCall.Arguments[0];
// }
private Expression VisitSelectMany (MethodCallExpression methodCall)
{
List<MemberExpression> mes = MemberExpressionFinder.Find (methodCall, this.tableFinder);
if (mes.Count > 1)
{
this.fallback = true;
return methodCall;
}
if (!TryGetTable (mes))
return methodCall;
ContentResolverColumnMapping column = this.tableFinder.GetColumn (mes[0].Member);
if (column == null || column.ReturnType.GetGenericTypeDefinition() != typeof(IEnumerable<>))
{
this.fallback = true;
return methodCall;
}
ReturnType = column.ReturnType.GetGenericArguments()[0];
return Expression.Constant (Activator.CreateInstance (typeof (Query<>).MakeGenericType (ReturnType), this.provider));
//return methodCall.Arguments[0];
}
private Expression VisitOrder (MethodCallExpression methodCall)
{
MemberExpression me = FindMemberExpression (methodCall.Arguments[1]);
if (!TryGetTable (me))
return methodCall;
ContentResolverColumnMapping column = this.tableFinder.GetColumn (me.Member);
if (column != null && column.Columns != null)
{
StringBuilder builder = this.sortBuilder ?? (this.sortBuilder = new StringBuilder());
if (builder.Length > 0)
builder.Append (", ");
if (column.Columns.Length > 1)
throw new NotSupportedException();
builder.Append (column.Columns[0]);
if (methodCall.Method.Name == "OrderByDescending")
builder.Append (" DESC");
return methodCall.Arguments[0];
}
return methodCall;
}
private bool TryGetTable (List<MemberExpression> memberExpressions)
{
if (memberExpressions.Count == 0)
{
this.fallback = true;
return false;
}
Android.Net.Uri existingTable = Table;
TableFindResult presult = null;
foreach (MemberExpression me in memberExpressions)
{
TableFindResult result = this.tableFinder.Find (me);
if (result.Table == null)
{
this.fallback = true;
return false;
}
if (existingTable == null)
{
existingTable = result.Table;
presult = result;
}
else if (existingTable != result.Table)
{
this.fallback = true;
return false;
}
}
if (presult == null)
{
this.fallback = true;
return false;
}
Table = presult.Table;
if (presult.MimeType != null)
this.queryBuilder.Append (String.Format ("({0} = ?)", ContactsContract.DataColumns.Mimetype));
this.arguments.Add (presult.MimeType);
return true;
}
private bool TryGetTable (MemberExpression me)
{
if (me == null)
{
this.fallback = true;
return false;
}
TableFindResult result = this.tableFinder.Find (me);
if (result.MimeType != null)
this.queryBuilder.Append (String.Format ("({0} = ?)", ContactsContract.DataColumns.Mimetype));
this.arguments.Add (result.MimeType);
if (Table == null)
Table = result.Table;
else if (Table != result.Table)
{
this.fallback = true;
return false;
}
return true;
}
private MemberExpression FindMemberExpression (Expression expression)
{
UnaryExpression ue = expression as UnaryExpression;
if (ue != null)
expression = ue.Operand;
LambdaExpression le = expression as LambdaExpression;
if (le != null)
expression = le.Body;
MemberExpression me = expression as MemberExpression;
if (me != null && this.tableFinder.IsSupportedType (me.Member.DeclaringType))
return me;
BinaryExpression be = expression as BinaryExpression;
if (be != null)
{
me = be.Left as MemberExpression;
if (me != null && this.tableFinder.IsSupportedType (me.Member.DeclaringType))
return me;
me = be.Right as MemberExpression;
if (me != null && this.tableFinder.IsSupportedType (me.Member.DeclaringType))
return me;
}
return null;
}
}
}
| |
using System;
using System.Threading.Tasks;
using TheMovieDbNet.Converters;
using TheMovieDbNet.Models.Common;
using TheMovieDbNet.Models.TVs;
namespace TheMovieDbNet.Services
{
/// <summary>
/// Represents a service for accessing movie-related data.
/// </summary>
public class TVService : Service, ITVService
{
private Lazy<TVConverter> _lazyConverter = new Lazy<TVConverter>(() => new TVConverter(), true);
/// <summary>
/// Initializes a new instance of PeopleService.
/// </summary>
/// <param name="apiKey">API key from the movie db developer site</param>
public TVService(string apiKey) : base(apiKey)
{
}
/// <summary>
/// Gets details of a tv.
/// </summary>
/// <param name="id">Tv identifier.</param>
/// <param name="append">Additional info to append to the response (eg: images, videos).</param>
/// <returns>Object of type tv with fields filled with data.</returns>
public async Task<TV> GetDetailsAsync(int id, string append = "")
{
var path = $"/3/tv/{id}?api_key={apiKey}&append_to_response={append}";
return await RequestAndDeserialize<TV>(path, _lazyConverter.Value);
}
/// <summary>
/// Gets details of a tv.
/// </summary>
/// <param name="id">Tv identifier.</param>
/// <param name="settings">Additional info to append to the response (eg: images, videos).</param>
/// <returns>Object of type tv with fields filled with data.</returns>
public async Task<TV> GetDetailsAsync(int id, TVAppendSettings settings)
=> await GetDetailsAsync(id, settings.ToString());
/// <summary>
/// Gets tv identifiers on external sites.
/// </summary>
/// <param name="id">Tv identifier.</param>
/// <param name="language">Language of the result.</param>
/// <returns>External ids for tv.</returns>
public async Task<TVExternals> GetExternalIdsAsync(int id, string language = "")
{
var path = $"/3/tv/{id}/external_ids?api_key={apiKey}";
if (!String.IsNullOrWhiteSpace(language))
path += $"&language={language}";
return await RequestAndDeserialize<TVExternals>(path);
}
/// <summary>
/// Gets the latest added tv.
/// </summary>
/// <param name="language">Language of the result.</param>
/// <returns>TV object with filled details.</returns>
public async Task<TV> GetLatestAsync(string language = "")
{
var path = $"/3/tv/latest?api_key={apiKey}";
if (!String.IsNullOrWhiteSpace(language))
path += $"&language={language}";
return await RequestAndDeserialize<TV>(path, _lazyConverter.Value);
}
/// <summary>
/// Gets the list of tv shows that are airing today.
/// </summary>
/// <param name="page">Page of result.</param>
/// <param name="language">Language of result.</param>
/// <returns>Search results along with page data.</returns>
public async Task<PagedResult<TVSearchItem>> GetAiringTodayAsync(int page = 0, string language = "")
{
var path = $"/3/tv/airing_today?api_key={apiKey}";
if (!String.IsNullOrWhiteSpace(language))
path += $"&language={language}";
if (page > 0)
path += $"&page={page}";
return await RequestAndDeserialize<PagedResult<TVSearchItem>>(path);
}
/// <summary>
/// Gets the list of tv shows that are currently on the air.
/// </summary>
/// <param name="page">Page of result.</param>
/// <param name="language">Language of result.</param>
/// <returns>Search results along with page data.</returns>
public async Task<PagedResult<TVSearchItem>> GetOnTheAirAsync(int page = 0, string language = "")
{
var path = $"/3/tv/on_the_air?api_key={apiKey}";
if (!String.IsNullOrWhiteSpace(language))
path += $"&language={language}";
if (page > 0)
path += $"&page={page}";
return await RequestAndDeserialize<PagedResult<TVSearchItem>>(path);
}
/// <summary>
/// Gets the list of tv shows that are popular.
/// </summary>
/// <param name="page">Page of result.</param>
/// <param name="language">Language of result.</param>
/// <returns>Search results along with page data.</returns>
public async Task<PagedResult<TVSearchItem>> GetPopularAsync(int page = 0, string language = "")
{
var path = $"/3/tv/popular?api_key={apiKey}";
if (!String.IsNullOrWhiteSpace(language))
path += $"&language={language}";
if (page > 0)
path += $"&page={page}";
return await RequestAndDeserialize<PagedResult<TVSearchItem>>(path);
}
/// <summary>
/// Gets the list of tv shows that are top rated.
/// </summary>
/// <param name="page">Page of result.</param>
/// <param name="language">Language of result.</param>
/// <returns>Search results along with page data.</returns>
public async Task<PagedResult<TVSearchItem>> GetTopRatedAsync(int page = 0, string language = "")
{
var path = $"/3/tv/top_rated?api_key={apiKey}";
if (!String.IsNullOrWhiteSpace(language))
path += $"&language={language}";
if (page > 0)
path += $"&page={page}";
return await RequestAndDeserialize<PagedResult<TVSearchItem>>(path);
}
/// <summary>
/// Gets content rating for the tv series.
/// </summary>
/// <param name="id">Tv identifier.</param>
/// <param name="language">Language of rating.</param>
/// <returns>Array of ContentRatings Titles for tv.</returns>
public async Task<ContentRating[]> GetContentRatingsAsync(int id, string language = "")
{
var path = $"/3/tv/{id}/content_ratings?api_key={apiKey}";
if (!String.IsNullOrWhiteSpace(language))
path += $"&language={language}";
return await RequestAndSelect<ContentRating[]>(path, "results");
}
/// <summary>
/// Gets translated titles of the tv.
/// </summary>
/// <param name="id">Tv identifier.</param>
/// <param name="language">Language of translation (eg: es, pt).</param>
/// <returns>Array of Alternative Titles for tv.</returns>
public async Task<AlternativeTitle[]> GetAlternativeTitlesAsync(int id, string language = "")
{
var path = $"/3/tv/{id}/alternative_titles?api_key={apiKey}";
if (!String.IsNullOrWhiteSpace(language))
path += $"&language={language}";
return await RequestAndSelect<AlternativeTitle[]>(path, "results");
}
/// <summary>
/// Gets the cast and crew of the tv.
/// </summary>
/// <param name="id">Tv identifier.</param>
/// <param name="language">Language of translation.</param>
/// <returns>Credits of the tv.</returns>
public async Task<MediaCredits> GetCreditsAsync(int id, string language = "")
{
var path = $"/3/tv/{id}/credits?api_key={apiKey}";
if (!String.IsNullOrWhiteSpace(language))
path += $"&language={language}";
return await RequestAndDeserialize<MediaCredits>(path);
}
/// <summary>
/// Gets the images of the tv.
/// </summary>
/// <param name="id">Tv identifier.</param>
/// <param name="language">Language of the image.</param>
/// <returns>Collection with the images of the tv.</returns>
public async Task<ImageCollection> GetImagesAsync(int id, string language = "")
{
var path = $"/3/tv/{id}/images?api_key={apiKey}";
if (!String.IsNullOrWhiteSpace(language))
path += $"&language={language}";
return await RequestAndDeserialize<ImageCollection>(path);
}
/// <summary>
/// Gets the keywords of the tv.
/// </summary>
/// <param name="id">Tv identifier.</param>
/// <returns>Array of the keywords.</returns>
public async Task<Keyword[]> GetKeywordsAsync(int id)
{
var path = $"/3/tv/{id}/keywords?api_key={apiKey}";
return await RequestAndSelect<Keyword[]>(path, "results");
}
/// <summary>
/// Gets the videos of the tv.
/// </summary>
/// <param name="id">Tv identifier.</param>
/// <param name="language">Video language.</param>
/// <returns>Array of videos.</returns>
public async Task<Video[]> GetVideosAsync(int id, string language = "")
{
var path = $"/3/tv/{id}/videos?api_key={apiKey}";
if (!String.IsNullOrWhiteSpace(language))
path += $"&language={language}";
return await RequestAndSelect<Video[]>(path, "results");
}
/// <summary>
/// Gets the translations of the tv.
/// </summary>
/// <param name="id">Tv identifier.</param>
/// <returns>Array of translations.</returns>
public async Task<Translation[]> GetTranslationsAsync(int id)
{
var path = $"/3/tv/{id}/translations?api_key={apiKey}";
return await RequestAndSelect<Translation[]>(path, "translations");
}
/// <summary>
/// Gets the recommendations for the tv.
/// </summary>
/// <param name="id">Tv identifier.</param>
/// <param name="page">Recommendations page number.</param>
/// <param name="language">Tv language.</param>
/// <returns>Collection of recommendations.</returns>
public async Task<PagedResult<TVSearchItem>> GetRecommendationsAsync(int id, int page = 0, string language = "")
{
var path = $"/3/tv/{id}/recommendations?api_key={apiKey}";
if (page > 0)
path += $"&page={page}";
if (!String.IsNullOrWhiteSpace(language))
path += $"&language={language}";
return await RequestAndDeserialize<PagedResult<TVSearchItem>>(path);
}
/// <summary>
/// Gets the similar tvs.
/// </summary>
/// <param name="id">Tv identifier.</param>
/// <param name="page">Similar tvs page number.</param>
/// <param name="language">tv language.</param>
/// <returns>Collection of similar tvs.</returns>
public async Task<PagedResult<TVSearchItem>> GetSimilarTVsAsync(int id, int page = 0, string language = "")
{
var path = $"/3/tv/{id}/similar?api_key={apiKey}";
if (page > 0)
path += $"&page={page}";
if (!String.IsNullOrWhiteSpace(language))
path += $"&language={language}";
return await RequestAndDeserialize<PagedResult<TVSearchItem>>(path);
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Core.CrossDomainLibWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Collections.Generic
{
using System;
using System.Collections;
using System.Diagnostics;
using System.ServiceModel;
[System.Runtime.InteropServices.ComVisible(false)]
public class SynchronizedCollection<T> : IList<T>, IList
{
List<T> items;
object sync;
public SynchronizedCollection()
{
this.items = new List<T>();
this.sync = new Object();
}
public SynchronizedCollection(object syncRoot)
{
if (syncRoot == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("syncRoot"));
this.items = new List<T>();
this.sync = syncRoot;
}
public SynchronizedCollection(object syncRoot, IEnumerable<T> list)
{
if (syncRoot == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("syncRoot"));
if (list == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("list"));
this.items = new List<T>(list);
this.sync = syncRoot;
}
public SynchronizedCollection(object syncRoot, params T[] list)
{
if (syncRoot == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("syncRoot"));
if (list == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("list"));
this.items = new List<T>(list.Length);
for (int i = 0; i < list.Length; i++)
this.items.Add(list[i]);
this.sync = syncRoot;
}
public int Count
{
get { lock (this.sync) { return this.items.Count; } }
}
protected List<T> Items
{
get { return this.items; }
}
public object SyncRoot
{
get { return this.sync; }
}
public T this[int index]
{
get
{
lock (this.sync)
{
return this.items[index];
}
}
set
{
lock (this.sync)
{
if (index < 0 || index >= this.items.Count)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", index,
SR.GetString(SR.ValueMustBeInRange, 0, this.items.Count - 1)));
this.SetItem(index, value);
}
}
}
public void Add(T item)
{
lock (this.sync)
{
int index = this.items.Count;
this.InsertItem(index, item);
}
}
public void Clear()
{
lock (this.sync)
{
this.ClearItems();
}
}
public void CopyTo(T[] array, int index)
{
lock (this.sync)
{
this.items.CopyTo(array, index);
}
}
public bool Contains(T item)
{
lock (this.sync)
{
return this.items.Contains(item);
}
}
public IEnumerator<T> GetEnumerator()
{
lock (this.sync)
{
return this.items.GetEnumerator();
}
}
public int IndexOf(T item)
{
lock (this.sync)
{
return this.InternalIndexOf(item);
}
}
public void Insert(int index, T item)
{
lock (this.sync)
{
if (index < 0 || index > this.items.Count)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", index,
SR.GetString(SR.ValueMustBeInRange, 0, this.items.Count)));
this.InsertItem(index, item);
}
}
int InternalIndexOf(T item)
{
int count = items.Count;
for (int i = 0; i < count; i++)
{
if (object.Equals(items[i], item))
{
return i;
}
}
return -1;
}
public bool Remove(T item)
{
lock (this.sync)
{
int index = this.InternalIndexOf(item);
if (index < 0)
return false;
this.RemoveItem(index);
return true;
}
}
public void RemoveAt(int index)
{
lock (this.sync)
{
if (index < 0 || index >= this.items.Count)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", index,
SR.GetString(SR.ValueMustBeInRange, 0, this.items.Count - 1)));
this.RemoveItem(index);
}
}
protected virtual void ClearItems()
{
this.items.Clear();
}
protected virtual void InsertItem(int index, T item)
{
this.items.Insert(index, item);
}
protected virtual void RemoveItem(int index)
{
this.items.RemoveAt(index);
}
protected virtual void SetItem(int index, T item)
{
this.items[index] = item;
}
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IList)this.items).GetEnumerator();
}
bool ICollection.IsSynchronized
{
get { return true; }
}
object ICollection.SyncRoot
{
get { return this.sync; }
}
void ICollection.CopyTo(Array array, int index)
{
lock (this.sync)
{
((IList)this.items).CopyTo(array, index);
}
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
VerifyValueType(value);
this[index] = (T)value;
}
}
bool IList.IsReadOnly
{
get { return false; }
}
bool IList.IsFixedSize
{
get { return false; }
}
int IList.Add(object value)
{
VerifyValueType(value);
lock (this.sync)
{
this.Add((T)value);
return this.Count - 1;
}
}
bool IList.Contains(object value)
{
VerifyValueType(value);
return this.Contains((T)value);
}
int IList.IndexOf(object value)
{
VerifyValueType(value);
return this.IndexOf((T)value);
}
void IList.Insert(int index, object value)
{
VerifyValueType(value);
this.Insert(index, (T)value);
}
void IList.Remove(object value)
{
VerifyValueType(value);
this.Remove((T)value);
}
static void VerifyValueType(object value)
{
if (value == null)
{
if (typeof(T).IsValueType)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.SynchronizedCollectionWrongTypeNull)));
}
}
else if (!(value is T))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.SynchronizedCollectionWrongType1, value.GetType().FullName)));
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace Aurora.Modules
{
partial class PhysicsProfilerForm
{
/// <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()
{
this.RegionNameSelector = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.PhysicsTaintBox = new System.Windows.Forms.PictureBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.PhysicsMoveTimeBox = new System.Windows.Forms.PictureBox();
this.label4 = new System.Windows.Forms.Label();
this.CollisionOptimizedTimeBox = new System.Windows.Forms.PictureBox();
this.label5 = new System.Windows.Forms.Label();
this.SendCollisionsTimeBox = new System.Windows.Forms.PictureBox();
this.label6 = new System.Windows.Forms.Label();
this.AvatarUpdatePosAndVelocityBox = new System.Windows.Forms.PictureBox();
this.label7 = new System.Windows.Forms.Label();
this.PrimUpdatePosAndVelocityBox = new System.Windows.Forms.PictureBox();
this.label8 = new System.Windows.Forms.Label();
this.UnlockedTimeBox = new System.Windows.Forms.PictureBox();
this.label9 = new System.Windows.Forms.Label();
this.MaxValBox = new System.Windows.Forms.TextBox();
this.Change = new System.Windows.Forms.Button();
this.Max1 = new System.Windows.Forms.Label();
this.Max2 = new System.Windows.Forms.Label();
this.Max3 = new System.Windows.Forms.Label();
this.Max4 = new System.Windows.Forms.Label();
this.label14 = new System.Windows.Forms.Label();
this.label15 = new System.Windows.Forms.Label();
this.label16 = new System.Windows.Forms.Label();
this.label17 = new System.Windows.Forms.Label();
this.HMax1 = new System.Windows.Forms.Label();
this.HMax2 = new System.Windows.Forms.Label();
this.HMax3 = new System.Windows.Forms.Label();
this.HMax4 = new System.Windows.Forms.Label();
this.HMax5 = new System.Windows.Forms.Label();
this.label23 = new System.Windows.Forms.Label();
this.Max5 = new System.Windows.Forms.Label();
this.HMax6 = new System.Windows.Forms.Label();
this.label26 = new System.Windows.Forms.Label();
this.Max6 = new System.Windows.Forms.Label();
this.HMax7 = new System.Windows.Forms.Label();
this.label29 = new System.Windows.Forms.Label();
this.Max7 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.InstantUpdatesSet = new System.Windows.Forms.Button();
this.TimeBetweenUpdates = new System.Windows.Forms.TextBox();
this.IULabel = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.FindContactsTimeBox = new System.Windows.Forms.PictureBox();
this.label11 = new System.Windows.Forms.Label();
this.label12 = new System.Windows.Forms.Label();
this.label13 = new System.Windows.Forms.Label();
this.label18 = new System.Windows.Forms.Label();
this.label19 = new System.Windows.Forms.Label();
this.label20 = new System.Windows.Forms.Label();
this.label21 = new System.Windows.Forms.Label();
this.ContactLoopTimeBox = new System.Windows.Forms.PictureBox();
this.label22 = new System.Windows.Forms.Label();
this.CollisionAccountingTimeBox = new System.Windows.Forms.PictureBox();
this.label24 = new System.Windows.Forms.Label();
this.label25 = new System.Windows.Forms.Label();
this.label27 = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.PhysicsTaintBox)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PhysicsMoveTimeBox)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CollisionOptimizedTimeBox)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.SendCollisionsTimeBox)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.AvatarUpdatePosAndVelocityBox)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PrimUpdatePosAndVelocityBox)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.UnlockedTimeBox)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.FindContactsTimeBox)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ContactLoopTimeBox)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CollisionAccountingTimeBox)).BeginInit();
this.SuspendLayout();
//
// RegionNameSelector
//
this.RegionNameSelector.FormattingEnabled = true;
this.RegionNameSelector.Location = new System.Drawing.Point(90, 13);
this.RegionNameSelector.Name = "RegionNameSelector";
this.RegionNameSelector.Size = new System.Drawing.Size(121, 21);
this.RegionNameSelector.TabIndex = 0;
this.RegionNameSelector.SelectedIndexChanged += new System.EventHandler(this.RegionNameSelector_SelectedIndexChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 17);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(72, 13);
this.label1.TabIndex = 1;
this.label1.Text = "Region Name";
//
// PhysicsTaintBox
//
this.PhysicsTaintBox.Location = new System.Drawing.Point(35, 75);
this.PhysicsTaintBox.Name = "PhysicsTaintBox";
this.PhysicsTaintBox.Size = new System.Drawing.Size(200, 200);
this.PhysicsTaintBox.TabIndex = 2;
this.PhysicsTaintBox.TabStop = false;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(87, 50);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(96, 13);
this.label2.TabIndex = 3;
this.label2.Text = "Physics Taint Time";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(322, 50);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(99, 13);
this.label3.TabIndex = 5;
this.label3.Text = "Physics Move Time";
//
// PhysicsMoveTimeBox
//
this.PhysicsMoveTimeBox.Location = new System.Drawing.Point(271, 75);
this.PhysicsMoveTimeBox.Name = "PhysicsMoveTimeBox";
this.PhysicsMoveTimeBox.Size = new System.Drawing.Size(200, 200);
this.PhysicsMoveTimeBox.TabIndex = 4;
this.PhysicsMoveTimeBox.TabStop = false;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(548, 50);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(120, 13);
this.label4.TabIndex = 7;
this.label4.Text = "Collision Optimized Time";
//
// CollisionOptimizedTimeBox
//
this.CollisionOptimizedTimeBox.Location = new System.Drawing.Point(508, 75);
this.CollisionOptimizedTimeBox.Name = "CollisionOptimizedTimeBox";
this.CollisionOptimizedTimeBox.Size = new System.Drawing.Size(200, 200);
this.CollisionOptimizedTimeBox.TabIndex = 6;
this.CollisionOptimizedTimeBox.TabStop = false;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(793, 50);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(104, 13);
this.label5.TabIndex = 9;
this.label5.Text = "Send Collisions Time";
//
// SendCollisionsTimeBox
//
this.SendCollisionsTimeBox.Location = new System.Drawing.Point(745, 75);
this.SendCollisionsTimeBox.Name = "SendCollisionsTimeBox";
this.SendCollisionsTimeBox.Size = new System.Drawing.Size(200, 200);
this.SendCollisionsTimeBox.TabIndex = 8;
this.SendCollisionsTimeBox.TabStop = false;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(56, 312);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(159, 13);
this.label6.TabIndex = 11;
this.label6.Text = "Avatar Update Pos And Velocity";
//
// AvatarUpdatePosAndVelocityBox
//
this.AvatarUpdatePosAndVelocityBox.Location = new System.Drawing.Point(35, 338);
this.AvatarUpdatePosAndVelocityBox.Name = "AvatarUpdatePosAndVelocityBox";
this.AvatarUpdatePosAndVelocityBox.Size = new System.Drawing.Size(200, 200);
this.AvatarUpdatePosAndVelocityBox.TabIndex = 10;
this.AvatarUpdatePosAndVelocityBox.TabStop = false;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(297, 312);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(148, 13);
this.label7.TabIndex = 13;
this.label7.Text = "Prim Update Pos And Velocity";
//
// PrimUpdatePosAndVelocityBox
//
this.PrimUpdatePosAndVelocityBox.Location = new System.Drawing.Point(271, 338);
this.PrimUpdatePosAndVelocityBox.Name = "PrimUpdatePosAndVelocityBox";
this.PrimUpdatePosAndVelocityBox.Size = new System.Drawing.Size(200, 200);
this.PrimUpdatePosAndVelocityBox.TabIndex = 12;
this.PrimUpdatePosAndVelocityBox.TabStop = false;
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(568, 312);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(79, 13);
this.label8.TabIndex = 15;
this.label8.Text = "Unlocked Time";
//
// UnlockedTimeBox
//
this.UnlockedTimeBox.Location = new System.Drawing.Point(507, 338);
this.UnlockedTimeBox.Name = "UnlockedTimeBox";
this.UnlockedTimeBox.Size = new System.Drawing.Size(200, 200);
this.UnlockedTimeBox.TabIndex = 14;
this.UnlockedTimeBox.TabStop = false;
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(217, 17);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(97, 13);
this.label9.TabIndex = 16;
this.label9.Text = "Max Value for stats";
//
// MaxValBox
//
this.MaxValBox.Location = new System.Drawing.Point(320, 13);
this.MaxValBox.Name = "MaxValBox";
this.MaxValBox.Size = new System.Drawing.Size(100, 20);
this.MaxValBox.TabIndex = 17;
this.MaxValBox.Text = "200";
//
// Change
//
this.Change.Location = new System.Drawing.Point(426, 12);
this.Change.Name = "Change";
this.Change.Size = new System.Drawing.Size(75, 23);
this.Change.TabIndex = 18;
this.Change.Text = "Set";
this.Change.UseVisualStyleBackColor = true;
this.Change.Click += new System.EventHandler(this.Change_Click);
//
// Max1
//
this.Max1.AutoSize = true;
this.Max1.Location = new System.Drawing.Point(8, 75);
this.Max1.Name = "Max1";
this.Max1.Size = new System.Drawing.Size(25, 13);
this.Max1.TabIndex = 19;
this.Max1.Text = "200";
//
// Max2
//
this.Max2.AutoSize = true;
this.Max2.Location = new System.Drawing.Point(241, 75);
this.Max2.Name = "Max2";
this.Max2.Size = new System.Drawing.Size(25, 13);
this.Max2.TabIndex = 20;
this.Max2.Text = "200";
//
// Max3
//
this.Max3.AutoSize = true;
this.Max3.Location = new System.Drawing.Point(477, 75);
this.Max3.Name = "Max3";
this.Max3.Size = new System.Drawing.Size(25, 13);
this.Max3.TabIndex = 21;
this.Max3.Text = "200";
//
// Max4
//
this.Max4.AutoSize = true;
this.Max4.Location = new System.Drawing.Point(714, 75);
this.Max4.Name = "Max4";
this.Max4.Size = new System.Drawing.Size(25, 13);
this.Max4.TabIndex = 22;
this.Max4.Text = "200";
//
// label14
//
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point(726, 262);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(13, 13);
this.label14.TabIndex = 23;
this.label14.Text = "0";
//
// label15
//
this.label15.AutoSize = true;
this.label15.Location = new System.Drawing.Point(489, 262);
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size(13, 13);
this.label15.TabIndex = 24;
this.label15.Text = "0";
//
// label16
//
this.label16.AutoSize = true;
this.label16.Location = new System.Drawing.Point(253, 262);
this.label16.Name = "label16";
this.label16.Size = new System.Drawing.Size(13, 13);
this.label16.TabIndex = 25;
this.label16.Text = "0";
//
// label17
//
this.label17.AutoSize = true;
this.label17.Location = new System.Drawing.Point(16, 262);
this.label17.Name = "label17";
this.label17.Size = new System.Drawing.Size(13, 13);
this.label17.TabIndex = 26;
this.label17.Text = "0";
//
// HMax1
//
this.HMax1.AutoSize = true;
this.HMax1.Location = new System.Drawing.Point(8, 169);
this.HMax1.Name = "HMax1";
this.HMax1.Size = new System.Drawing.Size(25, 13);
this.HMax1.TabIndex = 27;
this.HMax1.Text = "100";
//
// HMax2
//
this.HMax2.AutoSize = true;
this.HMax2.Location = new System.Drawing.Point(243, 169);
this.HMax2.Name = "HMax2";
this.HMax2.Size = new System.Drawing.Size(25, 13);
this.HMax2.TabIndex = 28;
this.HMax2.Text = "100";
//
// HMax3
//
this.HMax3.AutoSize = true;
this.HMax3.Location = new System.Drawing.Point(477, 169);
this.HMax3.Name = "HMax3";
this.HMax3.Size = new System.Drawing.Size(25, 13);
this.HMax3.TabIndex = 29;
this.HMax3.Text = "100";
//
// HMax4
//
this.HMax4.AutoSize = true;
this.HMax4.Location = new System.Drawing.Point(714, 169);
this.HMax4.Name = "HMax4";
this.HMax4.Size = new System.Drawing.Size(25, 13);
this.HMax4.TabIndex = 30;
this.HMax4.Text = "100";
//
// HMax5
//
this.HMax5.AutoSize = true;
this.HMax5.Location = new System.Drawing.Point(8, 432);
this.HMax5.Name = "HMax5";
this.HMax5.Size = new System.Drawing.Size(25, 13);
this.HMax5.TabIndex = 33;
this.HMax5.Text = "100";
//
// label23
//
this.label23.AutoSize = true;
this.label23.Location = new System.Drawing.Point(16, 525);
this.label23.Name = "label23";
this.label23.Size = new System.Drawing.Size(13, 13);
this.label23.TabIndex = 32;
this.label23.Text = "0";
//
// Max5
//
this.Max5.AutoSize = true;
this.Max5.Location = new System.Drawing.Point(4, 338);
this.Max5.Name = "Max5";
this.Max5.Size = new System.Drawing.Size(25, 13);
this.Max5.TabIndex = 31;
this.Max5.Text = "200";
//
// HMax6
//
this.HMax6.AutoSize = true;
this.HMax6.Location = new System.Drawing.Point(244, 432);
this.HMax6.Name = "HMax6";
this.HMax6.Size = new System.Drawing.Size(25, 13);
this.HMax6.TabIndex = 36;
this.HMax6.Text = "100";
//
// label26
//
this.label26.AutoSize = true;
this.label26.Location = new System.Drawing.Point(252, 525);
this.label26.Name = "label26";
this.label26.Size = new System.Drawing.Size(13, 13);
this.label26.TabIndex = 35;
this.label26.Text = "0";
//
// Max6
//
this.Max6.AutoSize = true;
this.Max6.Location = new System.Drawing.Point(240, 338);
this.Max6.Name = "Max6";
this.Max6.Size = new System.Drawing.Size(25, 13);
this.Max6.TabIndex = 34;
this.Max6.Text = "200";
//
// HMax7
//
this.HMax7.AutoSize = true;
this.HMax7.Location = new System.Drawing.Point(476, 432);
this.HMax7.Name = "HMax7";
this.HMax7.Size = new System.Drawing.Size(25, 13);
this.HMax7.TabIndex = 39;
this.HMax7.Text = "100";
//
// label29
//
this.label29.AutoSize = true;
this.label29.Location = new System.Drawing.Point(484, 525);
this.label29.Name = "label29";
this.label29.Size = new System.Drawing.Size(13, 13);
this.label29.TabIndex = 38;
this.label29.Text = "0";
//
// Max7
//
this.Max7.AutoSize = true;
this.Max7.Location = new System.Drawing.Point(472, 338);
this.Max7.Name = "Max7";
this.Max7.Size = new System.Drawing.Size(25, 13);
this.Max7.TabIndex = 37;
this.Max7.Text = "200";
//
// button1
//
this.button1.Location = new System.Drawing.Point(796, 12);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(152, 23);
this.button1.TabIndex = 40;
this.button1.Text = "Switch to Instant Updating";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// InstantUpdatesSet
//
this.InstantUpdatesSet.Location = new System.Drawing.Point(715, 12);
this.InstantUpdatesSet.Name = "InstantUpdatesSet";
this.InstantUpdatesSet.Size = new System.Drawing.Size(75, 23);
this.InstantUpdatesSet.TabIndex = 43;
this.InstantUpdatesSet.Text = "Set";
this.InstantUpdatesSet.UseVisualStyleBackColor = true;
this.InstantUpdatesSet.Click += new System.EventHandler(this.InstantUpdatesSet_Click);
//
// TimeBetweenUpdates
//
this.TimeBetweenUpdates.Location = new System.Drawing.Point(666, 13);
this.TimeBetweenUpdates.Name = "TimeBetweenUpdates";
this.TimeBetweenUpdates.Size = new System.Drawing.Size(43, 20);
this.TimeBetweenUpdates.TabIndex = 42;
this.TimeBetweenUpdates.Text = "500";
//
// IULabel
//
this.IULabel.AutoSize = true;
this.IULabel.Location = new System.Drawing.Point(507, 17);
this.IULabel.Name = "IULabel";
this.IULabel.Size = new System.Drawing.Size(153, 13);
this.IULabel.TabIndex = 41;
this.IULabel.Text = "Time Between Instant Updates";
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(1033, 50);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(98, 13);
this.label10.TabIndex = 45;
this.label10.Text = "Find Contacts Time";
//
// FindContactsTimeBox
//
this.FindContactsTimeBox.Location = new System.Drawing.Point(982, 75);
this.FindContactsTimeBox.Name = "FindContactsTimeBox";
this.FindContactsTimeBox.Size = new System.Drawing.Size(200, 200);
this.FindContactsTimeBox.TabIndex = 44;
this.FindContactsTimeBox.TabStop = false;
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(951, 169);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(25, 13);
this.label11.TabIndex = 48;
this.label11.Text = "100";
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(963, 262);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(13, 13);
this.label12.TabIndex = 47;
this.label12.Text = "0";
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(951, 75);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(25, 13);
this.label13.TabIndex = 46;
this.label13.Text = "200";
//
// label18
//
this.label18.AutoSize = true;
this.label18.Location = new System.Drawing.Point(714, 432);
this.label18.Name = "label18";
this.label18.Size = new System.Drawing.Size(25, 13);
this.label18.TabIndex = 51;
this.label18.Text = "100";
//
// label19
//
this.label19.AutoSize = true;
this.label19.Location = new System.Drawing.Point(726, 525);
this.label19.Name = "label19";
this.label19.Size = new System.Drawing.Size(13, 13);
this.label19.TabIndex = 50;
this.label19.Text = "0";
//
// label20
//
this.label20.AutoSize = true;
this.label20.Location = new System.Drawing.Point(714, 338);
this.label20.Name = "label20";
this.label20.Size = new System.Drawing.Size(25, 13);
this.label20.TabIndex = 49;
this.label20.Text = "200";
//
// label21
//
this.label21.AutoSize = true;
this.label21.Location = new System.Drawing.Point(797, 312);
this.label21.Name = "label21";
this.label21.Size = new System.Drawing.Size(97, 13);
this.label21.TabIndex = 53;
this.label21.Text = "Contact Loop Time";
//
// ContactLoopTimeBox
//
this.ContactLoopTimeBox.Location = new System.Drawing.Point(745, 338);
this.ContactLoopTimeBox.Name = "ContactLoopTimeBox";
this.ContactLoopTimeBox.Size = new System.Drawing.Size(200, 200);
this.ContactLoopTimeBox.TabIndex = 52;
this.ContactLoopTimeBox.TabStop = false;
//
// label22
//
this.label22.AutoSize = true;
this.label22.Location = new System.Drawing.Point(1018, 312);
this.label22.Name = "label22";
this.label22.Size = new System.Drawing.Size(128, 13);
this.label22.TabIndex = 55;
this.label22.Text = "Collision Accounting Time";
//
// CollisionAccountingTimeBox
//
this.CollisionAccountingTimeBox.Location = new System.Drawing.Point(982, 338);
this.CollisionAccountingTimeBox.Name = "CollisionAccountingTimeBox";
this.CollisionAccountingTimeBox.Size = new System.Drawing.Size(200, 200);
this.CollisionAccountingTimeBox.TabIndex = 54;
this.CollisionAccountingTimeBox.TabStop = false;
//
// label24
//
this.label24.AutoSize = true;
this.label24.Location = new System.Drawing.Point(951, 432);
this.label24.Name = "label24";
this.label24.Size = new System.Drawing.Size(25, 13);
this.label24.TabIndex = 58;
this.label24.Text = "100";
//
// label25
//
this.label25.AutoSize = true;
this.label25.Location = new System.Drawing.Point(963, 525);
this.label25.Name = "label25";
this.label25.Size = new System.Drawing.Size(13, 13);
this.label25.TabIndex = 57;
this.label25.Text = "0";
//
// label27
//
this.label27.AutoSize = true;
this.label27.Location = new System.Drawing.Point(951, 338);
this.label27.Name = "label27";
this.label27.Size = new System.Drawing.Size(25, 13);
this.label27.TabIndex = 56;
this.label27.Text = "200";
//
// PhysicsProfilerForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1201, 550);
this.Controls.Add(this.label24);
this.Controls.Add(this.label25);
this.Controls.Add(this.label27);
this.Controls.Add(this.label22);
this.Controls.Add(this.CollisionAccountingTimeBox);
this.Controls.Add(this.label21);
this.Controls.Add(this.ContactLoopTimeBox);
this.Controls.Add(this.label18);
this.Controls.Add(this.label19);
this.Controls.Add(this.label20);
this.Controls.Add(this.label11);
this.Controls.Add(this.label12);
this.Controls.Add(this.label13);
this.Controls.Add(this.label10);
this.Controls.Add(this.FindContactsTimeBox);
this.Controls.Add(this.InstantUpdatesSet);
this.Controls.Add(this.TimeBetweenUpdates);
this.Controls.Add(this.IULabel);
this.Controls.Add(this.button1);
this.Controls.Add(this.HMax7);
this.Controls.Add(this.label29);
this.Controls.Add(this.Max7);
this.Controls.Add(this.HMax6);
this.Controls.Add(this.label26);
this.Controls.Add(this.Max6);
this.Controls.Add(this.HMax5);
this.Controls.Add(this.label23);
this.Controls.Add(this.Max5);
this.Controls.Add(this.HMax4);
this.Controls.Add(this.HMax3);
this.Controls.Add(this.HMax2);
this.Controls.Add(this.HMax1);
this.Controls.Add(this.label17);
this.Controls.Add(this.label16);
this.Controls.Add(this.label15);
this.Controls.Add(this.label14);
this.Controls.Add(this.Max4);
this.Controls.Add(this.Max3);
this.Controls.Add(this.Max2);
this.Controls.Add(this.Max1);
this.Controls.Add(this.Change);
this.Controls.Add(this.MaxValBox);
this.Controls.Add(this.label9);
this.Controls.Add(this.label8);
this.Controls.Add(this.UnlockedTimeBox);
this.Controls.Add(this.label7);
this.Controls.Add(this.PrimUpdatePosAndVelocityBox);
this.Controls.Add(this.label6);
this.Controls.Add(this.AvatarUpdatePosAndVelocityBox);
this.Controls.Add(this.label5);
this.Controls.Add(this.SendCollisionsTimeBox);
this.Controls.Add(this.label4);
this.Controls.Add(this.CollisionOptimizedTimeBox);
this.Controls.Add(this.label3);
this.Controls.Add(this.PhysicsMoveTimeBox);
this.Controls.Add(this.label2);
this.Controls.Add(this.PhysicsTaintBox);
this.Controls.Add(this.label1);
this.Controls.Add(this.RegionNameSelector);
this.Name = "PhysicsProfilerForm";
this.Text = "PhysicsProfilerForm";
this.Load += new System.EventHandler(this.PhysicsProfilerForm_Load);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.PhysicsProfilerForm_FormClosing);
((System.ComponentModel.ISupportInitialize)(this.PhysicsTaintBox)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PhysicsMoveTimeBox)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CollisionOptimizedTimeBox)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.SendCollisionsTimeBox)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.AvatarUpdatePosAndVelocityBox)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PrimUpdatePosAndVelocityBox)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.UnlockedTimeBox)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.FindContactsTimeBox)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.ContactLoopTimeBox)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CollisionAccountingTimeBox)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ComboBox RegionNameSelector;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.PictureBox PhysicsTaintBox;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.PictureBox PhysicsMoveTimeBox;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.PictureBox CollisionOptimizedTimeBox;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.PictureBox SendCollisionsTimeBox;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.PictureBox AvatarUpdatePosAndVelocityBox;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.PictureBox PrimUpdatePosAndVelocityBox;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.PictureBox UnlockedTimeBox;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.TextBox MaxValBox;
private System.Windows.Forms.Button Change;
private System.Windows.Forms.Label Max1;
private System.Windows.Forms.Label Max2;
private System.Windows.Forms.Label Max3;
private System.Windows.Forms.Label Max4;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.Label label16;
private System.Windows.Forms.Label label17;
private System.Windows.Forms.Label HMax1;
private System.Windows.Forms.Label HMax2;
private System.Windows.Forms.Label HMax3;
private System.Windows.Forms.Label HMax4;
private System.Windows.Forms.Label HMax5;
private System.Windows.Forms.Label label23;
private System.Windows.Forms.Label Max5;
private System.Windows.Forms.Label HMax6;
private System.Windows.Forms.Label label26;
private System.Windows.Forms.Label Max6;
private System.Windows.Forms.Label HMax7;
private System.Windows.Forms.Label label29;
private System.Windows.Forms.Label Max7;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button InstantUpdatesSet;
private System.Windows.Forms.TextBox TimeBetweenUpdates;
private System.Windows.Forms.Label IULabel;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.PictureBox FindContactsTimeBox;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Label label18;
private System.Windows.Forms.Label label19;
private System.Windows.Forms.Label label20;
private System.Windows.Forms.Label label21;
private System.Windows.Forms.PictureBox ContactLoopTimeBox;
private System.Windows.Forms.Label label22;
private System.Windows.Forms.PictureBox CollisionAccountingTimeBox;
private System.Windows.Forms.Label label24;
private System.Windows.Forms.Label label25;
private System.Windows.Forms.Label label27;
}
}
| |
/* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using XenAdmin;
using XenAPI;
using System.Collections;
using XenAdmin.Properties;
using XenAdmin.Actions;
using XenAdmin.Core;
namespace XenAdmin.SettingsPanels
{
public partial class BootOptionsEditPage : UserControl, IEditPage
{
#region Private fields
private VM vm;
private bool bootFromCD;
#endregion
public BootOptionsEditPage()
{
InitializeComponent();
Text = Messages.GENERAL_HEADING_BOOT_OPTIONS;
}
#region IEditPage implementation
public bool ValidToSave { get { return true; } }
/// <summary>
/// Show local validation balloon tooltips
/// </summary>
public void ShowLocalValidationMessages()
{ }
/// <summary>
/// Unregister listeners, dispose balloon tooltips, etc.
/// </summary>
public void Cleanup()
{ }
public bool HasChanged
{
get
{
return (vm.IsHVM && GetOrder() != vm.BootOrder) || (m_textBoxOsParams.Text != vm.PV_args) || (VMPVBootableDVD() != bootFromCD);
}
}
public AsyncAction SaveSettings()
{
vm.BootOrder = GetOrder();
vm.PV_args = m_textBoxOsParams.Text;
return new DelegatedAsyncAction(vm.Connection, "Change VBDs bootable", "Change VBDs bootable", null,
delegate(Session session)
{
if (bootFromCD)
{
foreach (var vbd in vm.Connection.ResolveAll(vm.VBDs))
VBD.set_bootable(session, vbd.opaque_ref, vbd.IsCDROM);
}
else
{
// The lowest numbered disk is the system disk and we should set it to bootable: see CA-47457
List<VBD> vbds = vm.Connection.ResolveAll(vm.VBDs);
vbds.Sort((vbd1, vbd2) =>
{
if (vbd1.userdevice == "xvda")
return -1;
if (vbd2.userdevice == "xvda")
return 1;
return StringUtility.NaturalCompare(vbd1.userdevice,
vbd2.userdevice);
});
bool foundSystemDisk = false;
foreach (var vbd in vbds)
{
bool bootable = (!foundSystemDisk && vbd.type == vbd_type.Disk);
if (bootable)
foundSystemDisk = true;
VBD.set_bootable(session, vbd.opaque_ref, bootable);
}
}
},
true, // supress history
"VBD.set_bootable"
);
}
public void SetXenObjects(IXenObject orig, IXenObject clone)
{
vm = clone as VM;
if (vm == null)
return;
Repopulate();
}
#endregion
#region VerticalTabs.VerticalTab implementation
public String SubText
{
get
{
if (vm == null)
return "";
if (vm.IsHVM)
{
List<String> driveLetters = new List<String>();
foreach (object o in m_checkedListBox.Items)
{
BootDevice device = o as BootDevice;
if (device != null)
driveLetters.Add(device.ToString());
}
string order = String.Join(", ", driveLetters.ToArray());
return String.Format(Messages.BOOTORDER, order);
}
return Messages.NONE_DEFINED;
}
}
public Image Image
{
get
{
return Resources._001_PowerOn_h32bit_16;
}
}
#endregion
private void BootDeviceAndOrderEnabled(bool enabledState)
{
m_checkedListBox.Enabled = enabledState;
m_comboBoxBootDevice.Enabled = enabledState;
}
private void Repopulate()
{
BootDeviceAndOrderEnabled(vm.IsHVM);
if (vm.IsHVM)
{
m_tlpHvm.Visible = true;
m_autoHeightLabelHvm.Visible = true;
m_tlpNonHvm.Visible = false;
m_autoHeightLabelNonHvm.Visible = false;
m_checkedListBox.Items.Clear();
string order = vm.BootOrder.ToUpper();
foreach (char c in order)
m_checkedListBox.Items.Add(new BootDevice(c),true);
// then add any 'missing' entries
foreach (char c in BootDevice.BootOptions)
{
if (!order.Contains(c.ToString()))
m_checkedListBox.Items.Add(new BootDevice(c), false);
}
ToggleUpDownButtonsEnabledState();
}
else
{
m_tlpHvm.Visible = false;
m_autoHeightLabelHvm.Visible = false;
m_tlpNonHvm.Visible = true;
m_autoHeightLabelNonHvm.Visible = true;
m_comboBoxBootDevice.Items.Clear();
m_comboBoxBootDevice.Items.Add(Messages.BOOT_HARD_DISK);
if (vm.HasCD)
{
m_comboBoxBootDevice.Items.Add(Messages.DVD_DRIVE);
m_comboBoxBootDevice.SelectedItem = VMPVBootableDVD() ? Messages.DVD_DRIVE : Messages.BOOT_HARD_DISK;
}
else
m_comboBoxBootDevice.SelectedItem = Messages.BOOT_HARD_DISK;
m_textBoxOsParams.Text = vm.PV_args;
}
}
private bool VMPVBootableDVD()
{
foreach (var vbd in vm.Connection.ResolveAll(vm.VBDs))
{
if (vbd.IsCDROM && vbd.bootable)
return true;
}
return false;
}
private string GetOrder()
{
string bootOrder = "";
foreach (object o in m_checkedListBox.CheckedItems)
{
BootDevice device = o as BootDevice;
if (device != null)
bootOrder += device.GetChar().ToString();
}
return bootOrder;
}
private void ToggleUpDownButtonsEnabledState()
{
m_buttonUp.Enabled = 0 < m_checkedListBox.SelectedIndex && m_checkedListBox.SelectedIndex <= m_checkedListBox.Items.Count - 1;
m_buttonDown.Enabled = 0 <= m_checkedListBox.SelectedIndex && m_checkedListBox.SelectedIndex < m_checkedListBox.Items.Count - 1;
}
/// <param name="up">
/// True moves the item up, false moves it down
/// </param>
private void MoveItem(bool up)
{
int oldIndex = m_checkedListBox.SelectedIndex;
//check selection valid
if (oldIndex < 0 || oldIndex > m_checkedListBox.Items.Count - 1)
return;
//check operation valid
if (up && oldIndex == 0)
return;
if (!up && oldIndex == m_checkedListBox.Items.Count - 1)
return;
int newIndex = up ? oldIndex - 1 : oldIndex + 1;
object item = m_checkedListBox.SelectedItem;
bool isChecked = m_checkedListBox.GetItemChecked(oldIndex);
m_checkedListBox.Items.Remove(item);
m_checkedListBox.Items.Insert(newIndex, item);
m_checkedListBox.SetItemChecked(newIndex, isChecked);
m_checkedListBox.SelectedIndex = newIndex;
ToggleUpDownButtonsEnabledState();
}
#region Control Event Handlers
private void m_checkedListBox_SelectedIndexChanged(object sender, EventArgs e)
{
ToggleUpDownButtonsEnabledState();
}
private void m_buttonUp_Click(object sender, EventArgs e)
{
MoveItem(true);
}
private void m_buttonDown_Click(object sender, EventArgs e)
{
MoveItem(false);
}
private void m_comboBoxBootDevice_SelectedIndexChanged(object sender, EventArgs e)
{
bootFromCD = (string)m_comboBoxBootDevice.SelectedItem == Messages.DVD_DRIVE;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Xml;
namespace Orleans.Runtime.Configuration
{
/// <summary>
/// Orleans application configuration parameters.
/// </summary>
[Serializable]
public class ApplicationConfiguration
{
private readonly Dictionary<string, GrainTypeConfiguration> classSpecific;
private GrainTypeConfiguration defaults;
/// <summary>
/// The default time period used to collect in-active activations.
/// Applies to all grain types.
/// </summary>
public TimeSpan DefaultCollectionAgeLimit
{
get { return defaults.CollectionAgeLimit.HasValue ? defaults.CollectionAgeLimit.Value : GlobalConfiguration.DEFAULT_COLLECTION_AGE_LIMIT; }
}
internal TimeSpan ShortestCollectionAgeLimit
{
get
{
TimeSpan shortest = DefaultCollectionAgeLimit;
foreach (var typeConfig in ClassSpecific)
{
TimeSpan curr = typeConfig.CollectionAgeLimit.Value;
if (curr < shortest)
{
shortest = curr;
}
}
return shortest;
}
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="defaultCollectionAgeLimit">The default time period used to collect in-active activations.</param>
public ApplicationConfiguration(TimeSpan? defaultCollectionAgeLimit = null)
{
classSpecific = new Dictionary<string, GrainTypeConfiguration>();
defaults = new GrainTypeConfiguration(null, defaultCollectionAgeLimit);
}
/// <summary>
/// IEnumerable of all configurations for different grain types.
/// </summary>
public IEnumerable<GrainTypeConfiguration> ClassSpecific { get { return classSpecific.Values; } }
/// <summary>
/// Load this configuratin from xml element.
/// </summary>
/// <param name="xmlElement"></param>
/// <param name="logger"></param>
public void Load(XmlElement xmlElement, Logger logger)
{
bool found = false;
foreach (XmlNode node in xmlElement.ChildNodes)
{
found = true;
var config = GrainTypeConfiguration.Load((XmlElement)node, logger);
if (null == config) continue;
if (config.AreDefaults)
{
defaults = config;
}
else
{
if (classSpecific.ContainsKey(config.FullTypeName))
{
throw new InvalidOperationException(string.Format("duplicate type {0} in configuration", config.FullTypeName));
}
classSpecific.Add(config.FullTypeName, config);
}
}
if (!found)
{
throw new InvalidOperationException("empty GrainTypeConfiguration element");
}
}
/// <summary>
/// Returns the time period used to collect in-active activations of a given type.
/// </summary>
/// <param name="type">Grain type.</param>
/// <returns></returns>
public TimeSpan GetCollectionAgeLimit(Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
return GetCollectionAgeLimit(type.FullName);
}
/// <summary>
/// Returns the time period used to collect in-active activations of a given type.
/// </summary>
/// <param name="type">Grain type full name.</param>
/// <returns></returns>
public TimeSpan GetCollectionAgeLimit(string grainTypeFullName)
{
if (String.IsNullOrEmpty(grainTypeFullName))
{
throw new ArgumentNullException("grainTypeFullName");
}
GrainTypeConfiguration config;
return classSpecific.TryGetValue(grainTypeFullName, out config) && config.CollectionAgeLimit.HasValue ?
config.CollectionAgeLimit.Value : DefaultCollectionAgeLimit;
}
/// <summary>
/// Sets the time period to collect in-active activations for a given type.
/// </summary>
/// <param name="type">Grain type full name.</param>
/// <param name="ageLimit">The age limit to use.</param>
public void SetCollectionAgeLimit(Type type, TimeSpan ageLimit)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
SetCollectionAgeLimit(type.FullName, ageLimit);
}
/// <summary>
/// Sets the time period to collect in-active activations for a given type.
/// </summary>
/// <param name="grainTypeFullName">Grain type full name string.</param>
/// <param name="ageLimit">The age limit to use.</param>
public void SetCollectionAgeLimit(string grainTypeFullName, TimeSpan ageLimit)
{
if (String.IsNullOrEmpty(grainTypeFullName))
{
throw new ArgumentNullException("grainTypeFullName");
}
ThrowIfLessThanZero(ageLimit, "ageLimit");
GrainTypeConfiguration config;
if (!classSpecific.TryGetValue(grainTypeFullName, out config))
{
config = new GrainTypeConfiguration(grainTypeFullName);
classSpecific[grainTypeFullName] = config;
}
config.SetCollectionAgeLimit(ageLimit);
}
/// <summary>
/// Resets the time period to collect in-active activations for a given type to a default value.
/// </summary>
/// <param name="type">Grain type full name.</param>
/// <param name="ageLimit">The age limit to use.</param>
public void ResetCollectionAgeLimitToDefault(Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
ResetCollectionAgeLimitToDefault(type.FullName);
}
/// <summary>
/// Resets the time period to collect in-active activations for a given type to a default value.
/// </summary>
/// <param name="type">Grain type full name string.</param>
/// <param name="ageLimit">The age limit to use.</param>
public void ResetCollectionAgeLimitToDefault(string grainTypeFullName)
{
if (String.IsNullOrEmpty(grainTypeFullName))
{
throw new ArgumentNullException("grainTypeFullName");
}
GrainTypeConfiguration config;
if (!classSpecific.TryGetValue(grainTypeFullName, out config)) return;
config.SetCollectionAgeLimit(null);
}
/// <summary>
/// Sets the default time period to collect in-active activations for all grain type.
/// </summary>
/// <param name="ageLimit">The age limit to use.</param>
public void SetDefaultCollectionAgeLimit(TimeSpan ageLimit)
{
ThrowIfLessThanZero(ageLimit, "ageLimit");
defaults.SetCollectionAgeLimit(ageLimit);
}
private static void ThrowIfLessThanZero(TimeSpan timeSpan, string paramName)
{
if (timeSpan < TimeSpan.Zero) throw new ArgumentOutOfRangeException(paramName);
}
internal void ValidateConfiguration(Logger logger)
{
foreach (GrainTypeConfiguration config in classSpecific.Values)
{
config.ValidateConfiguration(logger);
}
}
/// <summary>
/// Prints the current application configuration.
/// </summary>
/// <returns></returns>
public override string ToString()
{
var result = new StringBuilder();
result.AppendFormat(" Application:").AppendLine();
result.AppendFormat(" Defaults:").AppendLine();
result.AppendFormat(" Deactivate if idle for: {0}", DefaultCollectionAgeLimit)
.AppendLine();
foreach (GrainTypeConfiguration config in classSpecific.Values)
{
if (!config.CollectionAgeLimit.HasValue) continue;
result.AppendFormat(" GrainType Type=\"{0}\":", config.FullTypeName)
.AppendLine();
result.AppendFormat(" Deactivate if idle for: {0} seconds", (long)config.CollectionAgeLimit.Value.TotalSeconds)
.AppendLine();
}
return result.ToString();
}
}
/// <summary>
/// Grain type specific application configuration.
/// </summary>
[Serializable]
public class GrainTypeConfiguration
{
/// <summary>
/// The type of the grain of this configuration.
/// </summary>
public string FullTypeName { get; private set; }
/// <summary>
/// Whether this is a defualt configuration that applies to all grain types.
/// </summary>
public bool AreDefaults { get { return FullTypeName == null; } }
/// <summary>
/// The time period used to collect in-active activations of this type.
/// </summary>
public TimeSpan? CollectionAgeLimit { get { return collectionAgeLimit; } }
private TimeSpan? collectionAgeLimit;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="type">Grain type of this configuration.</param>
public GrainTypeConfiguration(string type)
{
FullTypeName = type;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="type">Grain type of this configuration.</param>
/// <param name="ageLimit">Age limit for this type.</param>
public GrainTypeConfiguration(string type, TimeSpan? ageLimit)
{
FullTypeName = type;
SetCollectionAgeLimit(ageLimit);
}
public void SetCollectionAgeLimit(TimeSpan? ageLimit)
{
if (ageLimit == null)
{
collectionAgeLimit = null;
}
TimeSpan minAgeLimit = GlobalConfiguration.DEFAULT_COLLECTION_QUANTUM;
if (ageLimit < minAgeLimit)
{
if (GlobalConfiguration.ENFORCE_MINIMUM_REQUIREMENT_FOR_AGE_LIMIT)
{
throw new ArgumentException(string.Format("The AgeLimit attribute is required to be at least {0}.", minAgeLimit));
}
}
collectionAgeLimit = ageLimit;
}
/// <summary>
/// Load this configuratin from xml element.
/// </summary>
/// <param name="xmlElement"></param>
/// <param name="logger"></param>
public static GrainTypeConfiguration Load(XmlElement xmlElement, Logger logger)
{
string fullTypeName = null;
bool areDefaults = xmlElement.LocalName == "Defaults";
foreach (XmlAttribute attribute in xmlElement.Attributes)
{
if (!areDefaults && attribute.LocalName == "Type")
{
fullTypeName = attribute.Value.Trim();
}
else
{
throw new InvalidOperationException(string.Format("unrecognized attribute {0}", attribute.LocalName));
}
}
if (!areDefaults)
{
if (fullTypeName == null) throw new InvalidOperationException("Type attribute not specified");
}
bool found = false;
TimeSpan? collectionAgeLimit = null;
foreach (XmlNode node in xmlElement.ChildNodes)
{
var child = (XmlElement)node;
switch (child.LocalName)
{
default:
throw new InvalidOperationException(string.Format("unrecognized XML element {0}", child.LocalName));
case "Deactivation":
found = true;
collectionAgeLimit = ConfigUtilities.ParseCollectionAgeLimit(child);
break;
}
}
if (found) return new GrainTypeConfiguration(fullTypeName, collectionAgeLimit);
throw new InvalidOperationException(string.Format("empty GrainTypeConfiguration for {0}", fullTypeName == null ? "defaults" : fullTypeName));
}
internal void ValidateConfiguration(Logger logger)
{
if (AreDefaults) return;
Type type = null;
try
{
type = TypeUtils.ResolveType(FullTypeName);
}
catch (Exception exception)
{
string errStr = String.Format("Unable to find grain class type {0} specified in configuration; Failing silo startup.", FullTypeName);
logger.Error(ErrorCode.Loader_TypeLoadError, errStr, exception);
throw new OrleansException(errStr, exception);
}
if (type == null)
{
string errStr = String.Format("Unable to find grain class type {0} specified in configuration; Failing silo startup.", FullTypeName);
logger.Error(ErrorCode.Loader_TypeLoadError_2, errStr);
throw new OrleansException(errStr);
}
var typeInfo = type.GetTypeInfo();
// postcondition: returned type must implement IGrain.
if (!typeof(IGrain).IsAssignableFrom(type))
{
string errStr = String.Format("Type {0} must implement IGrain to be used Application configuration context.",type.FullName);
logger.Error(ErrorCode.Loader_TypeLoadError_3, errStr);
throw new OrleansException(errStr);
}
// postcondition: returned type must either be an interface or a class.
if (!typeInfo.IsInterface && !typeInfo.IsClass)
{
string errStr = String.Format("Type {0} must either be an interface or class used Application configuration context.",type.FullName);
logger.Error(ErrorCode.Loader_TypeLoadError_4, errStr);
throw new OrleansException(errStr);
}
}
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
using CodeJam.PerfTests;
using CodeJam.PerfTests.Configs;
using NUnit.Framework;
namespace CodeJam.DesignDecisions.JitOptimized
{
/// <summary>
/// Proofs that JIT eliminates code branches that are under static readonly variable condition
/// Use case:
/// 1. We have a generic class that handles some features depending on the type args.
/// 2. We want to skip feature-related code as fast as it is possible.
/// </summary>
[TestFixture(Category = CompetitionHelpers.PerfTestCategory + ": Design decisions")]
[SuppressMessage("ReSharper", "ConditionIsAlwaysTrueOrFalse")]
[SuppressMessage("ReSharper", "HeuristicUnreachableCode")]
public class DecisionFeatureSwitchPerfTest
{
#region PerfTest helpers
// DONTTOUCH: public and non-static to reproduce the main use case.
public class AnotherClass
{
public static readonly bool FeatureDisabledReadonly = bool.Parse("false"); // calculated at runtime
}
private const bool FeatureDisabledConstValue = false;
private static readonly bool _featureEnabledReadonly = !AnotherClass.FeatureDisabledReadonly;
// ReSharper disable once FieldCanBeMadeReadOnly.Local
private static bool _featureMutableFlag = AnotherClass.FeatureDisabledReadonly;
private static readonly bool _featureDisabledReadonly = AnotherClass.FeatureDisabledReadonly;
private static readonly int _featureInt5Readonly = int.Parse("5"); // calculated at runtime
private static bool AdditionalFeatureCheck(int a) => a > 1;
private static int OnFeatureEnabled(int a) => a * a / a;
private static int DefaultAction(int a) => a + 1;
#endregion
private static readonly int Count = CompetitionRunHelpers.SmallLoopCount;
[Test]
public void RunDecisionFeatureSwitchPerfTest() => Competition.Run(this);
[CompetitionBaseline]
[GcAllocations(0)]
public int NoFeatureHardcoded()
{
var a = 0;
for (var i = 0; i < Count; i++)
{
a = DefaultAction(a);
}
return a;
}
[CompetitionBenchmark(0.85, 1.26)]
[GcAllocations(0)]
public int FeatureDisabledConst()
{
var a = 0;
for (var i = 0; i < Count; i++)
{
#pragma warning disable 162
if (FeatureDisabledConstValue && AdditionalFeatureCheck(a))
a = OnFeatureEnabled(a);
#pragma warning restore 162
a = DefaultAction(a);
}
return a;
}
[CompetitionBenchmark(0.84, 1.19)]
[GcAllocations(0)]
public int FeatureDisabledConstTwoIf()
{
var a = 0;
for (var i = 0; i < Count; i++)
{
#pragma warning disable 162
if (FeatureDisabledConstValue)
if (AdditionalFeatureCheck(a))
a = OnFeatureEnabled(a);
#pragma warning restore 162
a = DefaultAction(a);
}
return a;
}
[CompetitionBenchmark(0.91, 1.14)]
[GcAllocations(0)]
public int FeatureDisabledReadonly()
{
var a = 0;
for (var i = 0; i < Count; i++)
{
if (_featureDisabledReadonly && AdditionalFeatureCheck(a))
a = OnFeatureEnabled(a);
a = DefaultAction(a);
}
return a;
}
[CompetitionBenchmark(0.82, 1.47)]
[GcAllocations(0)]
public int FeatureDisabledReadonlyTwoIf()
{
var a = 0;
for (var i = 0; i < Count; i++)
{
if (_featureDisabledReadonly)
if (AdditionalFeatureCheck(a))
a = OnFeatureEnabled(a);
a = DefaultAction(a);
}
return a;
}
[CompetitionBenchmark(0.85, 1.43)]
[GcAllocations(0)]
public int AnotherClassFeatureDisabledReadonly()
{
var a = 0;
for (var i = 0; i < Count; i++)
{
if (AnotherClass.FeatureDisabledReadonly && AdditionalFeatureCheck(a))
a = OnFeatureEnabled(a);
a = DefaultAction(a);
}
return a;
}
[CompetitionBenchmark(0.78, 1.45)]
[GcAllocations(0)]
public int NotFeatureEnabledReadonly()
{
var a = 0;
for (var i = 0; i < Count; i++)
{
if (!_featureEnabledReadonly && AdditionalFeatureCheck(a))
a = OnFeatureEnabled(a);
a = DefaultAction(a);
}
return a;
}
[CompetitionBenchmark(0.83, 1.53)]
[GcAllocations(0)]
public int FeatureIntGreaterThanReadonly()
{
var a = 0;
for (var i = 0; i < Count; i++)
{
if (_featureInt5Readonly > 10 && AdditionalFeatureCheck(a))
a = OnFeatureEnabled(a);
a = DefaultAction(a);
}
return a;
}
[CompetitionBenchmark(1.49, 2.75)]
[GcAllocations(0)]
public int FeatureMutableFlag()
{
var a = 0;
for (var i = 0; i < Count; i++)
{
if (_featureMutableFlag && AdditionalFeatureCheck(a))
a = OnFeatureEnabled(a);
a = DefaultAction(a);
}
return a;
}
[CompetitionBenchmark(1.43, 2.20)]
[GcAllocations(0)]
public int FeatureMutableFlagTwoIf()
{
var a = 0;
for (var i = 0; i < Count; i++)
{
if (_featureMutableFlag)
if (AdditionalFeatureCheck(a))
a = OnFeatureEnabled(a);
a = DefaultAction(a);
}
return a;
}
[CompetitionBenchmark(13.22, 25.35)]
[GcAllocations(0)]
public int FeatureEnabledReadonly()
{
var a = 0;
for (var i = 0; i < Count; i++)
{
if (_featureEnabledReadonly && AdditionalFeatureCheck(a))
a = OnFeatureEnabled(a);
a = DefaultAction(a);
}
return a;
}
[CompetitionBenchmark(13.23, 25.25)]
[GcAllocations(0)]
public int FeatureEnabledReadonlyTwoIf()
{
var a = 0;
for (var i = 0; i < Count; i++)
{
if (_featureEnabledReadonly)
if (AdditionalFeatureCheck(a))
a = OnFeatureEnabled(a);
a = DefaultAction(a);
}
return a;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
namespace AxiomCoders.PdfTemplateEditor.Controls
{
public partial class ColorPickerCtrl : UserControl
{
Color m_selectedColor = Color.AntiqueWhite;
public Color SelectedColor
{
get { return Color.FromArgb((int)Math.Floor(255f*m_opacity), m_selectedColor);; }
set
{
m_opacity = (float)value.A / 255f;
value = Color.FromArgb(255, value);
m_colorWheel.SelectedColor = value;
if (m_colorTable.ColorExist(value) == false)
m_colorTable.SetCustomColor(value);
m_colorTable.SelectedItem = value;
m_opacitySlider.Percent = m_opacity;
}
}
public ColorPickerCtrl()
{
InitializeComponent();
List<Color> colors = new List<Color>();
float step = 100/8;
for (float x = 0; x <= 100; x += step)
{
float v = 255 * x/100;
colors.Add(Color.FromArgb(255, (int)v, (int)v, (int)v));
}
colors.Add(Color.White);
colors.Add(Color.FromArgb(255, 255, 000, 000));
colors.Add(Color.FromArgb(255, 255, 255, 000));
colors.Add(Color.FromArgb(255, 000, 255, 000));
colors.Add(Color.FromArgb(255, 000, 255, 255));
colors.Add(Color.FromArgb(255, 000, 000, 255));
colors.Add(Color.FromArgb(255, 255, 000, 255));
int cols = 16;
int rows = 3;
float cnt = (rows * cols);
float huestep = 360 / cnt;
float hue = 0;
while (hue < 360)
{
colors.Add(new HSLColor(hue, 1, 0.5).Color);
hue += huestep;
}
hue = 0;
while (hue < 360)
{
colors.Add(new HSLColor(hue, 0.5, 0.5).Color);
hue += huestep;
}
m_colorTable.Colors = colors.ToArray();
m_colorTable.Cols = cols;
m_colorTable.SelectedIndexChanged += new EventHandler(OnColorTableSelectionChanged);
m_colorWheel.SelectedColorChanged += new EventHandler(OnColorWheelSelectionChanged);
m_opacitySlider.SelectedValueChanged += new EventHandler(OnOpacityValueChanged);
m_eyedropColorPicker.SelectedColorChanged += new EventHandler(OnEyeDropperSelectionChanged);
m_colorSample.Paint += new PaintEventHandler(OnColorSamplePaint);
}
void OnEyeDropperSelectionChanged(object sender, EventArgs e)
{
m_colorWheel.SelectedColor = m_eyedropColorPicker.SelectedColor;
}
float m_opacity = 1;
void OnOpacityValueChanged(object sender, EventArgs e)
{
m_opacity = Math.Max(0, m_opacitySlider.Percent);
m_opacity = Math.Min(1, m_opacitySlider.Percent);
m_colorSample.Refresh();
UpdateInfo();
}
void OnColorWheelSelectionChanged(object sender, EventArgs e)
{
Color selcol = m_colorWheel.SelectedColor;
if (selcol != null && selcol != m_selectedColor)
{
m_selectedColor = selcol;
m_colorSample.Refresh();
if (lockColorTable == false && selcol != m_colorTable.SelectedItem)
m_colorTable.SetCustomColor(selcol);
}
UpdateInfo();
}
void UpdateInfo()
{
Color c = Color.FromArgb((int)Math.Floor(255f*m_opacity), m_selectedColor);
string info = string.Format("{0} aRGB({1}, {2}, {3}, {4})", m_colorWheel.SelectedHSLColor.ToString(), c.A, c.R, c.G, c.B);
m_infoLabel.Text = info;
}
void OnColorSamplePaint(object sender, PaintEventArgs e)
{
Rectangle r = m_colorSample.ClientRectangle;
r.Inflate(-4,-4);
int width = r.Width;
r.Width /= 2;
Color c = Color.FromArgb((int)Math.Floor(255f*m_opacity), m_selectedColor);
SolidBrush b = new SolidBrush(c);
e.Graphics.FillRectangle(b, r);
r.X += r.Width;
e.Graphics.FillRectangle(Brushes.White, r);
c = Color.FromArgb(255, m_selectedColor);
b = new SolidBrush(c);
e.Graphics.FillRectangle(b, r);
}
bool lockColorTable = false;
void OnColorTableSelectionChanged(object sender, EventArgs e)
{
Color selcol = (Color)m_colorTable.SelectedItem;
if (selcol != null && selcol != m_selectedColor)
{
lockColorTable = true;
m_colorWheel.SelectedColor = selcol;
lockColorTable = false;
m_colorSample.Invalidate();
}
}
}
public class ColorListBox : ListBox
{
int m_knownColorCount = 0;
public ColorListBox()
{
DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
PropertyInfo[] propinfos = typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static);
foreach (PropertyInfo info in propinfos)
{
if (info.PropertyType == typeof(Color))
{
Color c = (Color)info.GetValue(typeof(Color), null);
if (c.A == 0) // skip transparent
continue;
Items.Add(c);
}
}
m_knownColorCount = Items.Count;
}
int ColorIndex(Color color)
{
// have to search all colors by value;
int argb = color.ToArgb();
for (int index = 0; index < Items.Count; index++)
{
Color c = (Color)Items[index];
if (c.ToArgb() == argb)
return index;
}
return -1;
}
public void SelectColor(Color color)
{
int index = ColorIndex(color);
if (index < 0)
index = SetCustomColor(color);
SelectedItem = Items[index];
}
void RemoveCustomColor()
{
if (Items.Count > m_knownColorCount)
Items.RemoveAt(Items.Count - 1);
}
int SetCustomColor(Color col)
{
RemoveCustomColor();
Items.Add(col);
return Items.Count - 1;
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
if (e.Index > -1)
{
e.DrawBackground();
Rectangle rect = e.Bounds;
rect.Inflate(-2,-2);
rect.Width = 50;
Color textColor = Color.Empty;
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
textColor = SystemColors.HighlightText;
else
textColor = this.ForeColor;
Color color = (Color)Items[e.Index];
using (Brush brush = new SolidBrush(color))
{
e.Graphics.FillRectangle(brush, rect);
}
if ((e.State & DrawItemState.Selected) != DrawItemState.Selected)
{
using (Pen pen = new Pen(e.ForeColor))
{
e.Graphics.DrawRectangle(pen, rect);
}
}
using (Brush brush = new SolidBrush(e.ForeColor))
{
string name = color.Name + string.Format("({0})", e.Index);
if (color.IsKnownColor == false)
name = "<custom>";
StringFormat format = new StringFormat();
format.LineAlignment = StringAlignment.Center;
rect = e.Bounds;
rect.X += 60;
e.Graphics.DrawString(name, Font, brush, rect, format);
}
e.DrawFocusRectangle();
}
}
}
}
| |
// 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 applicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for SubnetsOperations.
/// </summary>
public static partial class SubnetsOperationsExtensions
{
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
public static void Delete(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName)
{
operations.DeleteAsync(resourceGroupName, virtualNetworkName, subnetName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified subnet by virtual network and resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
public static Subnet Get(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, string expand = default(string))
{
return operations.GetAsync(resourceGroupName, virtualNetworkName, subnetName, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified subnet by virtual network and resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Subnet> GetAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
public static Subnet CreateOrUpdate(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Subnet> CreateOrUpdateAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all subnets in a virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
public static IPage<Subnet> List(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName)
{
return operations.ListAsync(resourceGroupName, virtualNetworkName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all subnets in a virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Subnet>> ListAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
public static void BeginDelete(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName)
{
operations.BeginDeleteAsync(resourceGroupName, virtualNetworkName, subnetName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
public static Subnet BeginCreateOrUpdate(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Subnet> BeginCreateOrUpdateAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all subnets in a virtual network.
/// </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<Subnet> ListNext(this ISubnetsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all subnets in a virtual network.
/// </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<Subnet>> ListNextAsync(this ISubnetsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: booking/history/reservation_amendment_summary.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Booking.History {
/// <summary>Holder for reflection information generated from booking/history/reservation_amendment_summary.proto</summary>
public static partial class ReservationAmendmentSummaryReflection {
#region Descriptor
/// <summary>File descriptor for booking/history/reservation_amendment_summary.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ReservationAmendmentSummaryReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjNib29raW5nL2hpc3RvcnkvcmVzZXJ2YXRpb25fYW1lbmRtZW50X3N1bW1h",
"cnkucHJvdG8SG2hvbG1zLnR5cGVzLmJvb2tpbmcuaGlzdG9yeRouYm9va2lu",
"Zy9pbmRpY2F0b3JzL3Jlc2VydmF0aW9uX2luZGljYXRvci5wcm90bxowYm9v",
"a2luZy9wcmljaW5nL3Jlc2VydmF0aW9uX3ByaWNlX2VzdGltYXRlLnByb3Rv",
"GipwcmltaXRpdmUvcGJfaW5jbHVzaXZlX29wc2RhdGVfcmFuZ2UucHJvdG8a",
"IXN1cHBseS9yb29tX3R5cGVzL3Jvb21fdHlwZS5wcm90byLkBQobUmVzZXJ2",
"YXRpb25BbWVuZG1lbnRTdW1tYXJ5EkkKC3Jlc2VydmF0aW9uGAEgASgLMjQu",
"aG9sbXMudHlwZXMuYm9va2luZy5pbmRpY2F0b3JzLlJlc2VydmF0aW9uSW5k",
"aWNhdG9yEhIKCmJvb2tpbmdfaWQYAiABKAkSSAoQZGF0ZV9yYW5nZV9wcmlv",
"chgDIAEoCzIuLmhvbG1zLnR5cGVzLnByaW1pdGl2ZS5QYkluY2x1c2l2ZU9w",
"c2RhdGVSYW5nZRJACg9yb29tX3R5cGVfcHJpb3IYBCABKAsyJy5ob2xtcy50",
"eXBlcy5zdXBwbHkucm9vbV90eXBlcy5Sb29tVHlwZRIbChNudW1iZXJfYWR1",
"bHRzX3ByaW9yGAUgASgNEh0KFW51bWJlcl9jaGlsZHJlbl9wcmlvchgGIAEo",
"DRJTChRwcmljZV9lc3RpbWF0ZV9wcmlvchgIIAEoCzI1LmhvbG1zLnR5cGVz",
"LmJvb2tpbmcucHJpY2luZy5SZXNlcnZhdGlvblByaWNlRXN0aW1hdGUSSQoR",
"ZGF0ZV9yYW5nZV9sYXR0ZXIYCSABKAsyLi5ob2xtcy50eXBlcy5wcmltaXRp",
"dmUuUGJJbmNsdXNpdmVPcHNkYXRlUmFuZ2USQQoQcm9vbV90eXBlX2xhdHRl",
"chgKIAEoCzInLmhvbG1zLnR5cGVzLnN1cHBseS5yb29tX3R5cGVzLlJvb21U",
"eXBlEhwKFG51bWJlcl9hZHVsdHNfbGF0dGVyGAsgASgNEh4KFm51bWJlcl9j",
"aGlsZHJlbl9sYXR0ZXIYDCABKA0SVAoVcHJpY2VfZXN0aW1hdGVfbGF0dGVy",
"GA4gASgLMjUuaG9sbXMudHlwZXMuYm9va2luZy5wcmljaW5nLlJlc2VydmF0",
"aW9uUHJpY2VFc3RpbWF0ZRISCgp0YWdzX3ByaW9yGA8gAygJEhMKC3RhZ3Nf",
"bGF0dGVyGBAgAygJQh6qAhtIT0xNUy5UeXBlcy5Cb29raW5nLkhpc3Rvcnli",
"BnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Pricing.ReservationPriceEstimateReflection.Descriptor, global::HOLMS.Types.Primitive.PbInclusiveOpsdateRangeReflection.Descriptor, global::HOLMS.Types.Supply.RoomTypes.RoomTypeReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.History.ReservationAmendmentSummary), global::HOLMS.Types.Booking.History.ReservationAmendmentSummary.Parser, new[]{ "Reservation", "BookingId", "DateRangePrior", "RoomTypePrior", "NumberAdultsPrior", "NumberChildrenPrior", "PriceEstimatePrior", "DateRangeLatter", "RoomTypeLatter", "NumberAdultsLatter", "NumberChildrenLatter", "PriceEstimateLatter", "TagsPrior", "TagsLatter" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class ReservationAmendmentSummary : pb::IMessage<ReservationAmendmentSummary> {
private static readonly pb::MessageParser<ReservationAmendmentSummary> _parser = new pb::MessageParser<ReservationAmendmentSummary>(() => new ReservationAmendmentSummary());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ReservationAmendmentSummary> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.History.ReservationAmendmentSummaryReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationAmendmentSummary() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationAmendmentSummary(ReservationAmendmentSummary other) : this() {
Reservation = other.reservation_ != null ? other.Reservation.Clone() : null;
bookingId_ = other.bookingId_;
DateRangePrior = other.dateRangePrior_ != null ? other.DateRangePrior.Clone() : null;
RoomTypePrior = other.roomTypePrior_ != null ? other.RoomTypePrior.Clone() : null;
numberAdultsPrior_ = other.numberAdultsPrior_;
numberChildrenPrior_ = other.numberChildrenPrior_;
PriceEstimatePrior = other.priceEstimatePrior_ != null ? other.PriceEstimatePrior.Clone() : null;
DateRangeLatter = other.dateRangeLatter_ != null ? other.DateRangeLatter.Clone() : null;
RoomTypeLatter = other.roomTypeLatter_ != null ? other.RoomTypeLatter.Clone() : null;
numberAdultsLatter_ = other.numberAdultsLatter_;
numberChildrenLatter_ = other.numberChildrenLatter_;
PriceEstimateLatter = other.priceEstimateLatter_ != null ? other.PriceEstimateLatter.Clone() : null;
tagsPrior_ = other.tagsPrior_.Clone();
tagsLatter_ = other.tagsLatter_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationAmendmentSummary Clone() {
return new ReservationAmendmentSummary(this);
}
/// <summary>Field number for the "reservation" field.</summary>
public const int ReservationFieldNumber = 1;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservation_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator Reservation {
get { return reservation_; }
set {
reservation_ = value;
}
}
/// <summary>Field number for the "booking_id" field.</summary>
public const int BookingIdFieldNumber = 2;
private string bookingId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string BookingId {
get { return bookingId_; }
set {
bookingId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "date_range_prior" field.</summary>
public const int DateRangePriorFieldNumber = 3;
private global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange dateRangePrior_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange DateRangePrior {
get { return dateRangePrior_; }
set {
dateRangePrior_ = value;
}
}
/// <summary>Field number for the "room_type_prior" field.</summary>
public const int RoomTypePriorFieldNumber = 4;
private global::HOLMS.Types.Supply.RoomTypes.RoomType roomTypePrior_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Supply.RoomTypes.RoomType RoomTypePrior {
get { return roomTypePrior_; }
set {
roomTypePrior_ = value;
}
}
/// <summary>Field number for the "number_adults_prior" field.</summary>
public const int NumberAdultsPriorFieldNumber = 5;
private uint numberAdultsPrior_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public uint NumberAdultsPrior {
get { return numberAdultsPrior_; }
set {
numberAdultsPrior_ = value;
}
}
/// <summary>Field number for the "number_children_prior" field.</summary>
public const int NumberChildrenPriorFieldNumber = 6;
private uint numberChildrenPrior_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public uint NumberChildrenPrior {
get { return numberChildrenPrior_; }
set {
numberChildrenPrior_ = value;
}
}
/// <summary>Field number for the "price_estimate_prior" field.</summary>
public const int PriceEstimatePriorFieldNumber = 8;
private global::HOLMS.Types.Booking.Pricing.ReservationPriceEstimate priceEstimatePrior_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Pricing.ReservationPriceEstimate PriceEstimatePrior {
get { return priceEstimatePrior_; }
set {
priceEstimatePrior_ = value;
}
}
/// <summary>Field number for the "date_range_latter" field.</summary>
public const int DateRangeLatterFieldNumber = 9;
private global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange dateRangeLatter_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange DateRangeLatter {
get { return dateRangeLatter_; }
set {
dateRangeLatter_ = value;
}
}
/// <summary>Field number for the "room_type_latter" field.</summary>
public const int RoomTypeLatterFieldNumber = 10;
private global::HOLMS.Types.Supply.RoomTypes.RoomType roomTypeLatter_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Supply.RoomTypes.RoomType RoomTypeLatter {
get { return roomTypeLatter_; }
set {
roomTypeLatter_ = value;
}
}
/// <summary>Field number for the "number_adults_latter" field.</summary>
public const int NumberAdultsLatterFieldNumber = 11;
private uint numberAdultsLatter_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public uint NumberAdultsLatter {
get { return numberAdultsLatter_; }
set {
numberAdultsLatter_ = value;
}
}
/// <summary>Field number for the "number_children_latter" field.</summary>
public const int NumberChildrenLatterFieldNumber = 12;
private uint numberChildrenLatter_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public uint NumberChildrenLatter {
get { return numberChildrenLatter_; }
set {
numberChildrenLatter_ = value;
}
}
/// <summary>Field number for the "price_estimate_latter" field.</summary>
public const int PriceEstimateLatterFieldNumber = 14;
private global::HOLMS.Types.Booking.Pricing.ReservationPriceEstimate priceEstimateLatter_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Pricing.ReservationPriceEstimate PriceEstimateLatter {
get { return priceEstimateLatter_; }
set {
priceEstimateLatter_ = value;
}
}
/// <summary>Field number for the "tags_prior" field.</summary>
public const int TagsPriorFieldNumber = 15;
private static readonly pb::FieldCodec<string> _repeated_tagsPrior_codec
= pb::FieldCodec.ForString(122);
private readonly pbc::RepeatedField<string> tagsPrior_ = new pbc::RepeatedField<string>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<string> TagsPrior {
get { return tagsPrior_; }
}
/// <summary>Field number for the "tags_latter" field.</summary>
public const int TagsLatterFieldNumber = 16;
private static readonly pb::FieldCodec<string> _repeated_tagsLatter_codec
= pb::FieldCodec.ForString(130);
private readonly pbc::RepeatedField<string> tagsLatter_ = new pbc::RepeatedField<string>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<string> TagsLatter {
get { return tagsLatter_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ReservationAmendmentSummary);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ReservationAmendmentSummary other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Reservation, other.Reservation)) return false;
if (BookingId != other.BookingId) return false;
if (!object.Equals(DateRangePrior, other.DateRangePrior)) return false;
if (!object.Equals(RoomTypePrior, other.RoomTypePrior)) return false;
if (NumberAdultsPrior != other.NumberAdultsPrior) return false;
if (NumberChildrenPrior != other.NumberChildrenPrior) return false;
if (!object.Equals(PriceEstimatePrior, other.PriceEstimatePrior)) return false;
if (!object.Equals(DateRangeLatter, other.DateRangeLatter)) return false;
if (!object.Equals(RoomTypeLatter, other.RoomTypeLatter)) return false;
if (NumberAdultsLatter != other.NumberAdultsLatter) return false;
if (NumberChildrenLatter != other.NumberChildrenLatter) return false;
if (!object.Equals(PriceEstimateLatter, other.PriceEstimateLatter)) return false;
if(!tagsPrior_.Equals(other.tagsPrior_)) return false;
if(!tagsLatter_.Equals(other.tagsLatter_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (reservation_ != null) hash ^= Reservation.GetHashCode();
if (BookingId.Length != 0) hash ^= BookingId.GetHashCode();
if (dateRangePrior_ != null) hash ^= DateRangePrior.GetHashCode();
if (roomTypePrior_ != null) hash ^= RoomTypePrior.GetHashCode();
if (NumberAdultsPrior != 0) hash ^= NumberAdultsPrior.GetHashCode();
if (NumberChildrenPrior != 0) hash ^= NumberChildrenPrior.GetHashCode();
if (priceEstimatePrior_ != null) hash ^= PriceEstimatePrior.GetHashCode();
if (dateRangeLatter_ != null) hash ^= DateRangeLatter.GetHashCode();
if (roomTypeLatter_ != null) hash ^= RoomTypeLatter.GetHashCode();
if (NumberAdultsLatter != 0) hash ^= NumberAdultsLatter.GetHashCode();
if (NumberChildrenLatter != 0) hash ^= NumberChildrenLatter.GetHashCode();
if (priceEstimateLatter_ != null) hash ^= PriceEstimateLatter.GetHashCode();
hash ^= tagsPrior_.GetHashCode();
hash ^= tagsLatter_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (reservation_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Reservation);
}
if (BookingId.Length != 0) {
output.WriteRawTag(18);
output.WriteString(BookingId);
}
if (dateRangePrior_ != null) {
output.WriteRawTag(26);
output.WriteMessage(DateRangePrior);
}
if (roomTypePrior_ != null) {
output.WriteRawTag(34);
output.WriteMessage(RoomTypePrior);
}
if (NumberAdultsPrior != 0) {
output.WriteRawTag(40);
output.WriteUInt32(NumberAdultsPrior);
}
if (NumberChildrenPrior != 0) {
output.WriteRawTag(48);
output.WriteUInt32(NumberChildrenPrior);
}
if (priceEstimatePrior_ != null) {
output.WriteRawTag(66);
output.WriteMessage(PriceEstimatePrior);
}
if (dateRangeLatter_ != null) {
output.WriteRawTag(74);
output.WriteMessage(DateRangeLatter);
}
if (roomTypeLatter_ != null) {
output.WriteRawTag(82);
output.WriteMessage(RoomTypeLatter);
}
if (NumberAdultsLatter != 0) {
output.WriteRawTag(88);
output.WriteUInt32(NumberAdultsLatter);
}
if (NumberChildrenLatter != 0) {
output.WriteRawTag(96);
output.WriteUInt32(NumberChildrenLatter);
}
if (priceEstimateLatter_ != null) {
output.WriteRawTag(114);
output.WriteMessage(PriceEstimateLatter);
}
tagsPrior_.WriteTo(output, _repeated_tagsPrior_codec);
tagsLatter_.WriteTo(output, _repeated_tagsLatter_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (reservation_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Reservation);
}
if (BookingId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(BookingId);
}
if (dateRangePrior_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(DateRangePrior);
}
if (roomTypePrior_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(RoomTypePrior);
}
if (NumberAdultsPrior != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(NumberAdultsPrior);
}
if (NumberChildrenPrior != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(NumberChildrenPrior);
}
if (priceEstimatePrior_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(PriceEstimatePrior);
}
if (dateRangeLatter_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(DateRangeLatter);
}
if (roomTypeLatter_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(RoomTypeLatter);
}
if (NumberAdultsLatter != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(NumberAdultsLatter);
}
if (NumberChildrenLatter != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(NumberChildrenLatter);
}
if (priceEstimateLatter_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(PriceEstimateLatter);
}
size += tagsPrior_.CalculateSize(_repeated_tagsPrior_codec);
size += tagsLatter_.CalculateSize(_repeated_tagsLatter_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ReservationAmendmentSummary other) {
if (other == null) {
return;
}
if (other.reservation_ != null) {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
Reservation.MergeFrom(other.Reservation);
}
if (other.BookingId.Length != 0) {
BookingId = other.BookingId;
}
if (other.dateRangePrior_ != null) {
if (dateRangePrior_ == null) {
dateRangePrior_ = new global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange();
}
DateRangePrior.MergeFrom(other.DateRangePrior);
}
if (other.roomTypePrior_ != null) {
if (roomTypePrior_ == null) {
roomTypePrior_ = new global::HOLMS.Types.Supply.RoomTypes.RoomType();
}
RoomTypePrior.MergeFrom(other.RoomTypePrior);
}
if (other.NumberAdultsPrior != 0) {
NumberAdultsPrior = other.NumberAdultsPrior;
}
if (other.NumberChildrenPrior != 0) {
NumberChildrenPrior = other.NumberChildrenPrior;
}
if (other.priceEstimatePrior_ != null) {
if (priceEstimatePrior_ == null) {
priceEstimatePrior_ = new global::HOLMS.Types.Booking.Pricing.ReservationPriceEstimate();
}
PriceEstimatePrior.MergeFrom(other.PriceEstimatePrior);
}
if (other.dateRangeLatter_ != null) {
if (dateRangeLatter_ == null) {
dateRangeLatter_ = new global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange();
}
DateRangeLatter.MergeFrom(other.DateRangeLatter);
}
if (other.roomTypeLatter_ != null) {
if (roomTypeLatter_ == null) {
roomTypeLatter_ = new global::HOLMS.Types.Supply.RoomTypes.RoomType();
}
RoomTypeLatter.MergeFrom(other.RoomTypeLatter);
}
if (other.NumberAdultsLatter != 0) {
NumberAdultsLatter = other.NumberAdultsLatter;
}
if (other.NumberChildrenLatter != 0) {
NumberChildrenLatter = other.NumberChildrenLatter;
}
if (other.priceEstimateLatter_ != null) {
if (priceEstimateLatter_ == null) {
priceEstimateLatter_ = new global::HOLMS.Types.Booking.Pricing.ReservationPriceEstimate();
}
PriceEstimateLatter.MergeFrom(other.PriceEstimateLatter);
}
tagsPrior_.Add(other.tagsPrior_);
tagsLatter_.Add(other.tagsLatter_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(reservation_);
break;
}
case 18: {
BookingId = input.ReadString();
break;
}
case 26: {
if (dateRangePrior_ == null) {
dateRangePrior_ = new global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange();
}
input.ReadMessage(dateRangePrior_);
break;
}
case 34: {
if (roomTypePrior_ == null) {
roomTypePrior_ = new global::HOLMS.Types.Supply.RoomTypes.RoomType();
}
input.ReadMessage(roomTypePrior_);
break;
}
case 40: {
NumberAdultsPrior = input.ReadUInt32();
break;
}
case 48: {
NumberChildrenPrior = input.ReadUInt32();
break;
}
case 66: {
if (priceEstimatePrior_ == null) {
priceEstimatePrior_ = new global::HOLMS.Types.Booking.Pricing.ReservationPriceEstimate();
}
input.ReadMessage(priceEstimatePrior_);
break;
}
case 74: {
if (dateRangeLatter_ == null) {
dateRangeLatter_ = new global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange();
}
input.ReadMessage(dateRangeLatter_);
break;
}
case 82: {
if (roomTypeLatter_ == null) {
roomTypeLatter_ = new global::HOLMS.Types.Supply.RoomTypes.RoomType();
}
input.ReadMessage(roomTypeLatter_);
break;
}
case 88: {
NumberAdultsLatter = input.ReadUInt32();
break;
}
case 96: {
NumberChildrenLatter = input.ReadUInt32();
break;
}
case 114: {
if (priceEstimateLatter_ == null) {
priceEstimateLatter_ = new global::HOLMS.Types.Booking.Pricing.ReservationPriceEstimate();
}
input.ReadMessage(priceEstimateLatter_);
break;
}
case 122: {
tagsPrior_.AddEntriesFrom(input, _repeated_tagsPrior_codec);
break;
}
case 130: {
tagsLatter_.AddEntriesFrom(input, _repeated_tagsLatter_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// 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;
public class Utils
{
public static int failures = 0;
public static void Fail(string outputString)
{
failures++;
// Console.WriteLine(outputString + new StackTrace(true).ToString());
Console.WriteLine(outputString);
}
public static void CheckType<U>(U parameterToCheck, Type typeToCheckAgainst)
{
if (!typeToCheckAgainst.Equals(typeof(U)))
{
Fail("Expected typeof generic method Type Parameter for parameter, '" + parameterToCheck + "', to be '" + typeToCheckAgainst + "', but found '" + typeof(U) + "'");
}
if (!typeToCheckAgainst.Equals(parameterToCheck.GetType()))
{
Fail("Expected Type.GetType parameter, '" + parameterToCheck + "', to be '" + typeToCheckAgainst + "', but found '" + parameterToCheck.GetType() + "'");
}
}
public static bool CompareArray<U>(U[] arrayOne, U[] arrayTwo)
{
for (int i = arrayOne.GetUpperBound(0); i >= 0; i--)
{
if (arrayOne[i].Equals(arrayTwo[i]))
{
return false;
}
}
return true;
}
public static string BuildArrayString<U>(U[] arrayToPrint)
{
string stringToReturn = typeof(U) + " {";
int i;
for (i = 0; i <= arrayToPrint.GetUpperBound(0); i++)
{
stringToReturn = stringToReturn + arrayToPrint[i] + ", ";
}
stringToReturn.Remove(stringToReturn.Length - 2, 2);
stringToReturn = stringToReturn + "}";
return stringToReturn;
}
}
public class GenericClass<T>
{
public static Type classParameterType;
public bool usingBaseVirtualProperty;
public static U StaticGenericMethod<U>(U methodParameter, Type methodParameterType)
{
Utils.CheckType<U>(methodParameter, methodParameterType);
return methodParameter;
}
public static int StaticNonGenericMethodInt(int methodParameter, Type methodParameterType)
{
Utils.CheckType<int>(methodParameter, methodParameterType);
return methodParameter;
}
public static string StaticNonGenericMethodString(string methodParameter, Type methodParameterType)
{
Utils.CheckType<string>(methodParameter, methodParameterType);
return methodParameter;
}
public static int[] StaticNonGenericMethodIntArray(int[] methodParameter, Type methodParameterType)
{
Utils.CheckType<int[]>(methodParameter, methodParameterType);
return methodParameter;
}
public static string[] StaticNonGenericMethodStringArray(string[] methodParameter, Type methodParameterType)
{
Utils.CheckType<string[]>(methodParameter, methodParameterType);
return methodParameter;
}
public static U StaticGenericMethodUsesClassTypeParam<U>(T classParameter, U methodParameter, Type methodParameterType)
{
Utils.CheckType<U>(methodParameter, methodParameterType);
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public static int StaticNonGenericMethodIntUsesClassTypeParam(T classParameter, int methodParameter, Type methodParameterType)
{
Utils.CheckType<int>(methodParameter, methodParameterType);
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public static string StaticNonGenericMethodStringUsesClassTypeParam(T classParameter, string methodParameter, Type methodParameterType)
{
Utils.CheckType<string>(methodParameter, methodParameterType);
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public static int[] StaticNonGenericMethodIntArrayUsesClassTypeParam(T classParameter, int[] methodParameter, Type methodParameterType)
{
Utils.CheckType<int[]>(methodParameter, methodParameterType);
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public static string[] StaticNonGenericMethodStringArrayUsesClassTypeParam(T classParameter, string[] methodParameter, Type methodParameterType)
{
Utils.CheckType<string[]>(methodParameter, methodParameterType);
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public U GenericMethod<U>(U methodParameter, Type methodParameterType)
{
Utils.CheckType<U>(methodParameter, methodParameterType);
return methodParameter;
}
public int NonGenericMethodInt(int methodParameter, Type methodParameterType)
{
Utils.CheckType<int>(methodParameter, methodParameterType);
return methodParameter;
}
public string NonGenericMethodString(string methodParameter, Type methodParameterType)
{
Utils.CheckType<string>(methodParameter, methodParameterType);
return methodParameter;
}
public int[] NonGenericMethodIntArray(int[] methodParameter, Type methodParameterType)
{
Utils.CheckType<int[]>(methodParameter, methodParameterType);
return methodParameter;
}
public string[] NonGenericMethodStringArray(string[] methodParameter, Type methodParameterType)
{
Utils.CheckType<string[]>(methodParameter, methodParameterType);
return methodParameter;
}
public U GenericMethodUsesClassTypeParam<U>(T classParameter, U methodParameter, Type methodParameterType)
{
Utils.CheckType<U>(methodParameter, methodParameterType);
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public int NonGenericMethodIntUsesClassTypeParam(T classParameter, int methodParameter, Type methodParameterType)
{
Utils.CheckType<int>(methodParameter, methodParameterType);
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public string NonGenericMethodStringUsesClassTypeParam(T classParameter, string methodParameter, Type methodParameterType)
{
Utils.CheckType<string>(methodParameter, methodParameterType);
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public int[] NonGenericMethodIntArrayUsesClassTypeParam(T classParameter, int[] methodParameter, Type methodParameterType)
{
Utils.CheckType<int[]>(methodParameter, methodParameterType);
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public string[] NonGenericMethodStringArrayUsesClassTypeParam(T classParameter, string[] methodParameter, Type methodParameterType)
{
Utils.CheckType<string[]>(methodParameter, methodParameterType);
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public virtual U VirtualGenericMethod<U>(U methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<U>(methodParameter, methodParameterType);
if (isBase == false) { Utils.Fail("Expected to be true, but found it to be false."); }
return methodParameter;
}
public virtual int VirtualNonGenericMethodInt(int methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<int>(methodParameter, methodParameterType);
if (isBase == false) { Utils.Fail("Expected to be true, but found it to be false."); }
return methodParameter;
}
public virtual string VirtualNonGenericMethodString(string methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<string>(methodParameter, methodParameterType);
if (isBase == false) { Utils.Fail("Expected to be true, but found it to be false."); }
return methodParameter;
}
public virtual int[] VirtualNonGenericMethodIntArray(int[] methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<int[]>(methodParameter, methodParameterType);
if (isBase == false) { Utils.Fail("Expected to be true, but found it to be false."); }
return methodParameter;
}
public virtual string[] VirtualNonGenericMethodStringArray(string[] methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<string[]>(methodParameter, methodParameterType);
if (isBase == false) { Utils.Fail("Expected to be true, but found it to be false."); }
return methodParameter;
}
public virtual U VirtualGenericMethodUsesClassTypeParam<U>(T classParameter, U methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<U>(methodParameter, methodParameterType);
if (isBase == false) { Utils.Fail("Expected to be true, but found it to be false."); }
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public virtual int VirtualNonGenericMethodIntUsesClassTypeParam(T classParameter, int methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<int>(methodParameter, methodParameterType);
if (isBase == false) { Utils.Fail("Expected to be true, but found it to be false."); }
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public virtual string VirtualNonGenericMethodStringUsesClassTypeParam(T classParameter, string methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<string>(methodParameter, methodParameterType);
if (isBase == false) { Utils.Fail("Expected to be true, but found it to be false."); }
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public virtual int[] VirtualNonGenericMethodIntArrayUsesClassTypeParam(T classParameter, int[] methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<int[]>(methodParameter, methodParameterType);
if (isBase == false) { Utils.Fail("Expected to be true, but found it to be false."); }
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public virtual string[] VirtualNonGenericMethodStringArrayUsesClassTypeParam(T classParameter, string[] methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<string[]>(methodParameter, methodParameterType);
if (isBase == false) { Utils.Fail("Expected to be true, but found it to be false."); }
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public T genericField;
public int nongenericIntField;
public string nongenericStringField;
public int[] nongenericIntArrayField;
public string[] nongenericStringArrayField;
public T genericProperty
{
get
{
Utils.CheckType<T>(genericField, classParameterType);
return genericField;
}
set
{
Utils.CheckType<T>(value, classParameterType);
genericField = value;
}
}
public int nongenericIntProperty
{
get
{
return nongenericIntField;
}
set
{
nongenericIntField = value;
}
}
public string nongenericStringProperty
{
get
{
return nongenericStringField;
}
set
{
nongenericStringField = value;
}
}
public int[] nongenericIntArrayProperty
{
get
{
return nongenericIntArrayField;
}
set
{
nongenericIntArrayField = value;
}
}
public string[] nongenericStringArrayProperty
{
get
{
return nongenericStringArrayField;
}
set
{
nongenericStringArrayField = value;
}
}
public virtual T genericVirtualProperty
{
get
{
Utils.CheckType<T>(genericField, classParameterType);
if (usingBaseVirtualProperty == false) { Utils.Fail("Expected usingBaseVirtualProperty to be true, but found it to be false."); }
return genericField;
}
set
{
Utils.CheckType<T>(value, classParameterType);
if (usingBaseVirtualProperty == false) { Utils.Fail("Expected usingBaseVirtualProperty to be true, but found it to be false."); }
genericField = value;
}
}
public virtual int nongenericIntVirtualProperty
{
get
{
if (usingBaseVirtualProperty == false) { Utils.Fail("Expected usingBaseVirtualProperty to be true, but found it to be false."); }
return nongenericIntField;
}
set
{
if (usingBaseVirtualProperty == false) { Utils.Fail("Expected usingBaseVirtualProperty to be true, but found it to be false."); }
nongenericIntField = value;
}
}
public virtual string nongenericStringVirtualProperty
{
get
{
if (usingBaseVirtualProperty == false) { Utils.Fail("Expected usingBaseVirtualProperty to be true, but found it to be false."); }
return nongenericStringField;
}
set
{
if (usingBaseVirtualProperty == false) { Utils.Fail("Expected usingBaseVirtualProperty to be true, but found it to be false."); }
nongenericStringField = value;
}
}
public virtual int[] nongenericIntArrayVirtualProperty
{
get
{
if (usingBaseVirtualProperty == false) { Utils.Fail("Expected usingBaseVirtualProperty to be true, but found it to be false."); }
return nongenericIntArrayField;
}
set
{
if (usingBaseVirtualProperty == false) { Utils.Fail("Expected usingBaseVirtualProperty to be true, but found it to be false."); }
nongenericIntArrayField = value;
}
}
public virtual string[] nongenericStringArrayVirtualProperty
{
get
{
if (usingBaseVirtualProperty == false) { Utils.Fail("Expected usingBaseVirtualProperty to be true, but found it to be false."); }
return nongenericStringArrayField;
}
set
{
if (usingBaseVirtualProperty == false) { Utils.Fail("Expected usingBaseVirtualProperty to be true, but found it to be false."); }
nongenericStringArrayField = value;
}
}
public delegate U genericDelegate<U>(U delegateParameter, Type typeOfDelegateParameter);
public delegate int nongenericDelegateInt(int delegateParameter, Type typeOfDelegateParameter);
public delegate string nongenericDelegateString(string delegateParameter, Type typeOfDelegateParameter);
public delegate int[] nongenericDelegateIntArray(int[] delegateParameter, Type typeOfDelegateParameter);
public delegate string[] nongenericDelegateStringArray(string[] delegateParameter, Type typeOfDelegateParameter);
public delegate U genericDelegateUsesClassTypeParam<U>(T classParameter, U delegateParameter, Type typeOfDelegateParameter);
public delegate int nongenericDelegateIntUsesClassTypeParam(T classParameter, int delegateParameter, Type typeOfDelegateParameter);
public delegate string nongenericDelegateStringUsesClassTypeParam(T classParameter, string delegateParameter, Type typeOfDelegateParameter);
public delegate int[] nongenericDelegateIntArrayUsesClassTypeParam(T classParameter, int[] delegateParameter, Type typeOfDelegateParameter);
public delegate string[] nongenericDelegateStringArrayUsesClassTypeParam(T classParameter, string[] delegateParameter, Type typeOfDelegateParameter);
}
public class GenericClassInheritsFromGenericClass<T> : GenericClass<T>
{
public override U VirtualGenericMethod<U>(U methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<U>(methodParameter, methodParameterType);
if (isBase == true) { Utils.Fail("Expected to be false, but found it to be true."); }
return methodParameter;
}
public override int VirtualNonGenericMethodInt(int methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<int>(methodParameter, methodParameterType);
if (isBase == true) { Utils.Fail("Expected to be false, but found it to be true."); }
return methodParameter;
}
public override string VirtualNonGenericMethodString(string methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<string>(methodParameter, methodParameterType);
if (isBase == true) { Utils.Fail("Expected to be false, but found it to be true."); }
return methodParameter;
}
public override int[] VirtualNonGenericMethodIntArray(int[] methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<int[]>(methodParameter, methodParameterType);
if (isBase == true) { Utils.Fail("Expected to be false, but found it to be true."); }
return methodParameter;
}
public override string[] VirtualNonGenericMethodStringArray(string[] methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<string[]>(methodParameter, methodParameterType);
if (isBase == true) { Utils.Fail("Expected to be false, but found it to be true."); }
return methodParameter;
}
public override U VirtualGenericMethodUsesClassTypeParam<U>(T classParameter, U methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<U>(methodParameter, methodParameterType);
if (isBase == true) { Utils.Fail("Expected to be false, but found it to be true."); }
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public override int VirtualNonGenericMethodIntUsesClassTypeParam(T classParameter, int methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<int>(methodParameter, methodParameterType);
if (isBase == true) { Utils.Fail("Expected to be false, but found it to be true."); }
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public override string VirtualNonGenericMethodStringUsesClassTypeParam(T classParameter, string methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<string>(methodParameter, methodParameterType);
if (isBase == true) { Utils.Fail("Expected to be false, but found it to be true."); }
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public override int[] VirtualNonGenericMethodIntArrayUsesClassTypeParam(T classParameter, int[] methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<int[]>(methodParameter, methodParameterType);
if (isBase == true) { Utils.Fail("Expected to be false, but found it to be true."); }
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public override string[] VirtualNonGenericMethodStringArrayUsesClassTypeParam(T classParameter, string[] methodParameter, Type methodParameterType, bool isBase)
{
Utils.CheckType<string[]>(methodParameter, methodParameterType);
if (isBase == true) { Utils.Fail("Expected to be false, but found it to be true."); }
Utils.CheckType<T>(classParameter, classParameterType);
return methodParameter;
}
public override T genericVirtualProperty
{
get
{
Utils.CheckType<T>(genericField, classParameterType);
if (usingBaseVirtualProperty == true) { Utils.Fail("Expected usingBaseVirtualProperty to be false, but found it to be true."); }
return genericField;
}
set
{
Utils.CheckType<T>(value, classParameterType);
if (usingBaseVirtualProperty == true) { Utils.Fail("Expected usingBaseVirtualProperty to be false, but found it to be true."); }
genericField = value;
}
}
public override int nongenericIntVirtualProperty
{
get
{
if (usingBaseVirtualProperty == true) { Utils.Fail("Expected usingBaseVirtualProperty to be false, but found it to be true."); }
return nongenericIntField;
}
set
{
if (usingBaseVirtualProperty == true) { Utils.Fail("Expected usingBaseVirtualProperty to be false, but found it to be true."); }
nongenericIntField = value;
}
}
public override string nongenericStringVirtualProperty
{
get
{
if (usingBaseVirtualProperty == true) { Utils.Fail("Expected usingBaseVirtualProperty to be false, but found it to be true."); }
return nongenericStringField;
}
set
{
if (usingBaseVirtualProperty == true) { Utils.Fail("Expected usingBaseVirtualProperty to be false, but found it to be true."); }
nongenericStringField = value;
}
}
public override int[] nongenericIntArrayVirtualProperty
{
get
{
if (usingBaseVirtualProperty == true) { Utils.Fail("Expected usingBaseVirtualProperty to be false, but found it to be true."); }
return nongenericIntArrayField;
}
set
{
if (usingBaseVirtualProperty == true) { Utils.Fail("Expected usingBaseVirtualProperty to be false, but found it to be true."); }
nongenericIntArrayField = value;
}
}
public override string[] nongenericStringArrayVirtualProperty
{
get
{
if (usingBaseVirtualProperty == true) { Utils.Fail("Expected usingBaseVirtualProperty to be false, but found it to be true."); }
return nongenericStringArrayField;
}
set
{
if (usingBaseVirtualProperty == true) { Utils.Fail("Expected usingBaseVirtualProperty to be false, but found it to be true."); }
nongenericStringArrayField = value;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Runtime.InteropServices;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Completion;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.SymbolSearch;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options
{
[ComVisible(true)]
public class AutomationObject
{
private readonly Workspace _workspace;
internal AutomationObject(Workspace workspace)
{
_workspace = workspace;
}
/// <summary>
/// Unused. But kept around for back compat. Note this option is not about
/// turning warning into errors. It's about an aspect of 'remove unused using'
/// functionality we don't support anymore. Namely whether or not 'remove unused
/// using' should warn if you have any build errors as that might mean we
/// remove some usings inappropriately.
/// </summary>
public int WarnOnBuildErrors
{
get { return 0; }
set { }
}
public int AutoComment
{
get { return GetBooleanOption(FeatureOnOffOptions.AutoXmlDocCommentGeneration); }
set { SetBooleanOption(FeatureOnOffOptions.AutoXmlDocCommentGeneration, value); }
}
public int AutoInsertAsteriskForNewLinesOfBlockComments
{
get { return GetBooleanOption(FeatureOnOffOptions.AutoInsertBlockCommentStartString); }
set { SetBooleanOption(FeatureOnOffOptions.AutoInsertBlockCommentStartString, value); }
}
public int BringUpOnIdentifier
{
get { return GetBooleanOption(CompletionOptions.TriggerOnTypingLetters); }
set { SetBooleanOption(CompletionOptions.TriggerOnTypingLetters, value); }
}
public int HighlightMatchingPortionsOfCompletionListItems
{
get { return GetBooleanOption(CompletionOptions.HighlightMatchingPortionsOfCompletionListItems); }
set { SetBooleanOption(CompletionOptions.HighlightMatchingPortionsOfCompletionListItems, value); }
}
public int ShowCompletionItemFilters
{
get { return GetBooleanOption(CompletionOptions.ShowCompletionItemFilters); }
set { SetBooleanOption(CompletionOptions.ShowCompletionItemFilters, value); }
}
[Obsolete("This SettingStore option has now been deprecated in favor of CSharpClosedFileDiagnostics")]
public int ClosedFileDiagnostics
{
get { return GetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic); }
set
{
// Even though this option has been deprecated, we want to respect the setting if the user has explicitly turned off closed file diagnostics (which is the non-default value for 'ClosedFileDiagnostics').
// So, we invoke the setter only for value = 0.
if (value == 0)
{
SetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, value);
}
}
}
public int CSharpClosedFileDiagnostics
{
get { return GetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic); }
set { SetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, value); }
}
public int DisplayLineSeparators
{
get { return GetBooleanOption(FeatureOnOffOptions.LineSeparator); }
set { SetBooleanOption(FeatureOnOffOptions.LineSeparator, value); }
}
public int EnableHighlightRelatedKeywords
{
get { return GetBooleanOption(FeatureOnOffOptions.KeywordHighlighting); }
set { SetBooleanOption(FeatureOnOffOptions.KeywordHighlighting, value); }
}
public int EnterOutliningModeOnOpen
{
get { return GetBooleanOption(FeatureOnOffOptions.Outlining); }
set { SetBooleanOption(FeatureOnOffOptions.Outlining, value); }
}
public int ExtractMethod_AllowMovingDeclaration
{
get { return GetBooleanOption(ExtractMethodOptions.AllowMovingDeclaration); }
set { SetBooleanOption(ExtractMethodOptions.AllowMovingDeclaration, value); }
}
public int ExtractMethod_DoNotPutOutOrRefOnStruct
{
get { return GetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct); }
set { SetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, value); }
}
public int Formatting_TriggerOnBlockCompletion
{
get { return GetBooleanOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace); }
set { SetBooleanOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace, value); }
}
public int Formatting_TriggerOnPaste
{
get { return GetBooleanOption(FeatureOnOffOptions.FormatOnPaste); }
set { SetBooleanOption(FeatureOnOffOptions.FormatOnPaste, value); }
}
public int Formatting_TriggerOnStatementCompletion
{
get { return GetBooleanOption(FeatureOnOffOptions.AutoFormattingOnSemicolon); }
set { SetBooleanOption(FeatureOnOffOptions.AutoFormattingOnSemicolon, value); }
}
public int HighlightReferences
{
get { return GetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting); }
set { SetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting, value); }
}
public int Indent_BlockContents
{
get { return GetBooleanOption(CSharpFormattingOptions.IndentBlock); }
set { SetBooleanOption(CSharpFormattingOptions.IndentBlock, value); }
}
public int Indent_Braces
{
get { return GetBooleanOption(CSharpFormattingOptions.IndentBraces); }
set { SetBooleanOption(CSharpFormattingOptions.IndentBraces, value); }
}
public int Indent_CaseContents
{
get { return GetBooleanOption(CSharpFormattingOptions.IndentSwitchCaseSection); }
set { SetBooleanOption(CSharpFormattingOptions.IndentSwitchCaseSection, value); }
}
public int Indent_CaseLabels
{
get { return GetBooleanOption(CSharpFormattingOptions.IndentSwitchSection); }
set { SetBooleanOption(CSharpFormattingOptions.IndentSwitchSection, value); }
}
public int Indent_FlushLabelsLeft
{
get
{
var option = _workspace.Options.GetOption(CSharpFormattingOptions.LabelPositioning);
return option == LabelPositionOptions.LeftMost ? 1 : 0;
}
set
{
_workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.LabelPositioning, value == 1 ? LabelPositionOptions.LeftMost : LabelPositionOptions.NoIndent);
}
}
public int Indent_UnindentLabels
{
get
{
return (int)_workspace.Options.GetOption(CSharpFormattingOptions.LabelPositioning);
}
set
{
_workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.LabelPositioning, value);
}
}
public int InsertNewlineOnEnterWithWholeWord
{
get { return (int)GetOption(CompletionOptions.EnterKeyBehavior); }
set { SetOption(CompletionOptions.EnterKeyBehavior, (EnterKeyRule)value); }
}
public int EnterKeyBehavior
{
get { return (int)GetOption(CompletionOptions.EnterKeyBehavior); }
set { SetOption(CompletionOptions.EnterKeyBehavior, (EnterKeyRule)value); }
}
public int SnippetsBehavior
{
get { return (int)GetOption(CompletionOptions.SnippetsBehavior); }
set { SetOption(CompletionOptions.SnippetsBehavior, (SnippetsRule)value); }
}
public int NewLines_AnonymousTypeInitializer_EachMember
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes); }
set { SetBooleanOption(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes, value); }
}
public int NewLines_Braces_AnonymousMethod
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods, value); }
}
public int NewLines_Braces_AnonymousTypeInitializer
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes, value); }
}
public int NewLines_Braces_ControlFlow
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, value); }
}
public int NewLines_Braces_LambdaExpressionBody
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody, value); }
}
public int NewLines_Braces_Method
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInMethods); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInMethods, value); }
}
public int NewLines_Braces_Property
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInProperties); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInProperties, value); }
}
public int NewLines_Braces_Accessor
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAccessors); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAccessors, value); }
}
public int NewLines_Braces_ObjectInitializer
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, value); }
}
public int NewLines_Braces_Type
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInTypes); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInTypes, value); }
}
public int NewLines_Keywords_Catch
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLineForCatch); }
set { SetBooleanOption(CSharpFormattingOptions.NewLineForCatch, value); }
}
public int NewLines_Keywords_Else
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLineForElse); }
set { SetBooleanOption(CSharpFormattingOptions.NewLineForElse, value); }
}
public int NewLines_Keywords_Finally
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLineForFinally); }
set { SetBooleanOption(CSharpFormattingOptions.NewLineForFinally, value); }
}
public int NewLines_ObjectInitializer_EachMember
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLineForMembersInObjectInit); }
set { SetBooleanOption(CSharpFormattingOptions.NewLineForMembersInObjectInit, value); }
}
public int NewLines_QueryExpression_EachClause
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLineForClausesInQuery); }
set { SetBooleanOption(CSharpFormattingOptions.NewLineForClausesInQuery, value); }
}
public int Refactoring_Verification_Enabled
{
get { return GetBooleanOption(FeatureOnOffOptions.RefactoringVerification); }
set { SetBooleanOption(FeatureOnOffOptions.RefactoringVerification, value); }
}
public int RenameSmartTagEnabled
{
get { return GetBooleanOption(FeatureOnOffOptions.RenameTracking); }
set { SetBooleanOption(FeatureOnOffOptions.RenameTracking, value); }
}
public int RenameTrackingPreview
{
get { return GetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview); }
set { SetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview, value); }
}
public int ShowKeywords
{
get { return 0; }
set { }
}
[Obsolete("Use SnippetsBehavior instead")]
public int ShowSnippets
{
get
{
return GetOption(CompletionOptions.SnippetsBehavior) == SnippetsRule.AlwaysInclude
? 1 : 0;
}
set
{
if (value == 0)
{
SetOption(CompletionOptions.SnippetsBehavior, SnippetsRule.NeverInclude);
}
else
{
SetOption(CompletionOptions.SnippetsBehavior, SnippetsRule.AlwaysInclude);
}
}
}
public int SortUsings_PlaceSystemFirst
{
get { return GetBooleanOption(GenerationOptions.PlaceSystemNamespaceFirst); }
set { SetBooleanOption(GenerationOptions.PlaceSystemNamespaceFirst, value); }
}
public int AddImport_SuggestForTypesInReferenceAssemblies
{
get { return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies); }
set { SetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, value); }
}
public int AddImport_SuggestForTypesInNuGetPackages
{
get { return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages); }
set { SetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, value); }
}
public int Space_AfterBasesColon
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration, value); }
}
public int Space_AfterCast
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterCast); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterCast, value); }
}
public int Space_AfterComma
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterComma); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterComma, value); }
}
public int Space_AfterDot
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterDot); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterDot, value); }
}
public int Space_AfterMethodCallName
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterMethodCallName); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterMethodCallName, value); }
}
public int Space_AfterMethodDeclarationName
{
get { return GetBooleanOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName); }
set { SetBooleanOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName, value); }
}
public int Space_AfterSemicolonsInForStatement
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement, value); }
}
public int Space_AroundBinaryOperator
{
get
{
var option = _workspace.Options.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator);
return option == BinaryOperatorSpacingOptions.Single ? 1 : 0;
}
set
{
var option = value == 1 ? BinaryOperatorSpacingOptions.Single : BinaryOperatorSpacingOptions.Ignore;
_workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, option);
}
}
public int Space_BeforeBasesColon
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration, value); }
}
public int Space_BeforeComma
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeComma); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeComma, value); }
}
public int Space_BeforeDot
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeDot); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeDot, value); }
}
public int Space_BeforeOpenSquare
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket, value); }
}
public int Space_BeforeSemicolonsInForStatement
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement, value); }
}
public int Space_BetweenEmptyMethodCallParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses, value); }
}
public int Space_BetweenEmptyMethodDeclarationParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses, value); }
}
public int Space_BetweenEmptySquares
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets, value); }
}
public int Space_InControlFlowConstruct
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword, value); }
}
public int Space_WithinCastParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinCastParentheses); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinCastParentheses, value); }
}
public int Space_WithinExpressionParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinExpressionParentheses); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinExpressionParentheses, value); }
}
public int Space_WithinMethodCallParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodCallParentheses); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodCallParentheses, value); }
}
public int Space_WithinMethodDeclarationParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis, value); }
}
public int Space_WithinOtherParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinOtherParentheses); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinOtherParentheses, value); }
}
public int Space_WithinSquares
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinSquareBrackets); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinSquareBrackets, value); }
}
public string Style_PreferIntrinsicPredefinedTypeKeywordInDeclaration_CodeStyle
{
get { return GetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration); }
set { SetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, value); }
}
public string Style_PreferIntrinsicPredefinedTypeKeywordInMemberAccess_CodeStyle
{
get { return GetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); }
set { SetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, value); }
}
public string Style_NamingPreferences
{
get
{
return _workspace.Options.GetOption(SimplificationOptions.NamingPreferences, LanguageNames.CSharp).CreateXElement().ToString();
}
set
{
try
{
_workspace.Options = _workspace.Options.WithChangedOption(SimplificationOptions.NamingPreferences, LanguageNames.CSharp, NamingStylePreferences.FromXElement(XElement.Parse(value)));
}
catch (Exception)
{
}
}
}
public string Style_QualifyFieldAccess
{
get { return GetXmlOption(CodeStyleOptions.QualifyFieldAccess); }
set { SetXmlOption(CodeStyleOptions.QualifyFieldAccess, value); }
}
public string Style_QualifyPropertyAccess
{
get { return GetXmlOption(CodeStyleOptions.QualifyPropertyAccess); }
set { SetXmlOption(CodeStyleOptions.QualifyPropertyAccess, value); }
}
public string Style_QualifyMethodAccess
{
get { return GetXmlOption(CodeStyleOptions.QualifyMethodAccess); }
set { SetXmlOption(CodeStyleOptions.QualifyMethodAccess, value); }
}
public string Style_QualifyEventAccess
{
get { return GetXmlOption(CodeStyleOptions.QualifyEventAccess); }
set { SetXmlOption(CodeStyleOptions.QualifyEventAccess, value); }
}
public int Style_UseVarWhenDeclaringLocals
{
get { return GetBooleanOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals); }
set { SetBooleanOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals, value); }
}
public string Style_UseImplicitTypeWherePossible
{
get { return GetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible); }
set { SetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, value); }
}
public string Style_UseImplicitTypeWhereApparent
{
get { return GetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent); }
set { SetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, value); }
}
public string Style_UseImplicitTypeForIntrinsicTypes
{
get { return GetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes); }
set { SetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, value); }
}
public int Wrapping_IgnoreSpacesAroundBinaryOperators
{
get
{
return (int)_workspace.Options.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator);
}
set
{
_workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, value);
}
}
public int Wrapping_IgnoreSpacesAroundVariableDeclaration
{
get { return GetBooleanOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration); }
set { SetBooleanOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration, value); }
}
public int Wrapping_KeepStatementsOnSingleLine
{
get { return GetBooleanOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine); }
set { SetBooleanOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, value); }
}
public int Wrapping_PreserveSingleLine
{
get { return GetBooleanOption(CSharpFormattingOptions.WrappingPreserveSingleLine); }
set { SetBooleanOption(CSharpFormattingOptions.WrappingPreserveSingleLine, value); }
}
private int GetBooleanOption(Option<bool> key)
{
return _workspace.Options.GetOption(key) ? 1 : 0;
}
private int GetBooleanOption(PerLanguageOption<bool> key)
{
return _workspace.Options.GetOption(key, LanguageNames.CSharp) ? 1 : 0;
}
private T GetOption<T>(PerLanguageOption<T> key)
{
return _workspace.Options.GetOption(key, LanguageNames.CSharp);
}
private void SetBooleanOption(Option<bool> key, int value)
{
_workspace.Options = _workspace.Options.WithChangedOption(key, value != 0);
}
private void SetBooleanOption(PerLanguageOption<bool> key, int value)
{
_workspace.Options = _workspace.Options.WithChangedOption(key, LanguageNames.CSharp, value != 0);
}
private void SetOption<T>(PerLanguageOption<T> key, T value)
{
_workspace.Options = _workspace.Options.WithChangedOption(key, LanguageNames.CSharp, value);
}
private int GetBooleanOption(PerLanguageOption<bool?> key)
{
var option = _workspace.Options.GetOption(key, LanguageNames.CSharp);
if (!option.HasValue)
{
return -1;
}
return option.Value ? 1 : 0;
}
private string GetXmlOption(Option<CodeStyleOption<bool>> option)
{
return _workspace.Options.GetOption(option).ToXElement().ToString();
}
private void SetBooleanOption(PerLanguageOption<bool?> key, int value)
{
bool? boolValue = (value < 0) ? (bool?)null : (value > 0);
_workspace.Options = _workspace.Options.WithChangedOption(key, LanguageNames.CSharp, boolValue);
}
private string GetXmlOption(PerLanguageOption<CodeStyleOption<bool>> option)
{
return _workspace.Options.GetOption(option, LanguageNames.CSharp).ToXElement().ToString();
}
private void SetXmlOption(Option<CodeStyleOption<bool>> option, string value)
{
var convertedValue = CodeStyleOption<bool>.FromXElement(XElement.Parse(value));
_workspace.Options = _workspace.Options.WithChangedOption(option, convertedValue);
}
private void SetXmlOption(PerLanguageOption<CodeStyleOption<bool>> option, string value)
{
var convertedValue = CodeStyleOption<bool>.FromXElement(XElement.Parse(value));
_workspace.Options = _workspace.Options.WithChangedOption(option, LanguageNames.CSharp, convertedValue);
}
}
}
| |
// 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.
//
// C# adaptation of C implementation of Livermore Loops Fortran benchmark.
/* Livermore Loops coded in C Latest File Modification 20 Oct 92,
* by Tim Peters, Kendall Square Res. Corp. tim@ksr.com, ksr!tim@uunet.uu.net
* SUBROUTINE KERNEL( TK) replaces the Fortran routine in LFK Test program.
************************************************************************
* *
* KERNEL executes 24 samples of "C" computation *
* *
* TK(1) - total cpu time to execute only the 24 kernels.*
* TK(2) - total Flops executed by the 24 Kernels *
* *
************************************************************************
* *
* L. L. N. L. " C " K E R N E L S: M F L O P S *
* *
* These kernels measure " C " numerical computation *
* rates for a spectrum of cpu-limited computational *
* structures or benchmarks. Mathematical through-put *
* is measured in units of millions of floating-point *
* operations executed per second, called Megaflops/sec. *
* *
* Fonzi's Law: There is not now and there never will be a language *
* in which it is the least bit difficult to write *
* bad programs. *
* F.H.MCMAHON 1972 *
************************************************************************
*Originally from Greg Astfalk, AT&T, P.O.Box 900, Princeton, NJ. 08540*
* by way of Frank McMahon (LLNL). *
* *
* REFERENCE *
* *
* F.H.McMahon, The Livermore Fortran Kernels: *
* A Computer Test Of The Numerical Performance Range, *
* Lawrence Livermore National Laboratory, *
* Livermore, California, UCRL-53745, December 1986. *
* *
* from: National Technical Information Service *
* U.S. Department of Commerce *
* 5285 Port Royal Road *
* Springfield, VA. 22161 *
* *
* Changes made to correct many array subscripting problems, *
* make more readable (added #define's), include the original *
* FORTRAN versions of the runs as comments, and make more *
* portable by Kelly O'Hair (LLNL) and Chuck Rasbold (LLNL). *
* *
************************************************************************
*/
using Microsoft.Xunit.Performance;
using System;
using System.Runtime.CompilerServices;
using Xunit;
[assembly: OptimizeForBenchmarks]
[assembly: MeasureInstructionsRetired]
namespace Benchstone.BenchF
{
public class LLoops
{
#if DEBUG
public const int Iterations = 1;
#else
public const int Iterations = 4000;
#endif
private const double MaxErr = 1.0e-6;
private double[] _x = new double[1002];
private double[] _y = new double[1002];
private double[] _z = new double[1002];
private double[] _u = new double[501];
private double[][] _px;
private double[][] _cx;
private double[][][] _u1;
private double[][][] _u2;
private double[][][] _u3;
private double[][] _b;
private double[] _bnk1 = new double[6];
private double[][] _c;
private double[] _bnk2 = new double[6];
private double[][] _p;
private double[] _bnk3 = new double[6];
private double[][] _h;
private double[] _bnk4 = new double[6];
private double[] _bnk5 = new double[6];
private double[] _ex = new double[68];
private double[] _rh = new double[68];
private double[] _dex = new double[68];
private double[] _vx = new double[151];
private double[] _xx = new double[151];
private double[] _grd = new double[151];
private int[] _e = new int[193];
private int[] _f = new int[193];
private int[] _nrops = { 0, 5, 10, 2, 2, 2, 2, 16, 36, 17, 9, 1, 1, 7, 11 };
private int[] _loops = { 0, 400, 200, 1000, 510, 1000, 1000, 120, 40, 100, 100, 1000, 1000, 128, 150 };
private double[] _checks = {
0, 0.811986948148e+07, 0.356310000000e+03, 0.356310000000e+03, -0.402412007078e+05,
0.136579037764e+06, 0.419716278716e+06,
0.429449847526e+07, 0.314064400000e+06,
0.182709000000e+07, -0.140415250000e+09,
0.374895020500e+09, 0.000000000000e+00,
0.171449024000e+06, -0.510829560800e+07
};
public static volatile object VolatileObject;
[MethodImpl(MethodImplOptions.NoInlining)]
private static void Escape(object obj)
{
VolatileObject = obj;
}
private static T[][] AllocArray<T>(int n1, int n2)
{
T[][] a = new T[n1][];
for (int i = 0; i < n1; ++i)
{
a[i] = new T[n2];
}
return a;
}
private static T[][][] AllocArray<T>(int n1, int n2, int n3)
{
T[][][] a = new T[n1][][];
for (int i = 0; i < n1; ++i)
{
a[i] = new T[n2][];
for (int j = 0; j < n2; j++)
{
a[i][j] = new T[n3];
}
}
return a;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private bool Bench()
{
_px = AllocArray<double>(16, 101);
_cx = AllocArray<double>(16, 101);
_u1 = AllocArray<double>(6, 23, 3);
_u2 = AllocArray<double>(6, 23, 3);
_u3 = AllocArray<double>(6, 23, 3);
_b = AllocArray<double>(65, 9);
_c = AllocArray<double>(65, 9);
_h = AllocArray<double>(65, 9);
_p = AllocArray<double>(5, 513);
for (int i = 0; i < Iterations; i++)
{
Main1(i < Iterations - 1 ? 0 : 1);
}
return true;
}
private static int Clock()
{
return 0;
}
private void Main1(int output)
{
int nt, lw, nl1, nl2;
int i, i1, i2, ip, ir, ix, j, j1, j2, k, kx, ky, l, m;
double[] ts = new double[21];
double[] rt = new double[21];
double[] rpm = new double[21];
double[] cksum = new double[21];
double r, t, a11, a12, a13, sig, a21, a22, a23, a31, a32, a33;
double b28, b27, b26, b25, b24, b23, b22, c0, flx, rx1;
double q, s, scale, uu, du1, du2, du3, ar, br, cr, xi, ri;
int[] mops = new int[20];
for (i = 1; i <= 20; i++)
{
cksum[i] = 0.0;
}
r = 4.86;
t = 276.0;
a11 = 0.5;
a12 = 0.33;
a13 = 0.25;
sig = 0.8;
a21 = 0.20;
a22 = 0.167;
a23 = 0.141;
a31 = 0.125;
a32 = 0.111;
a33 = 0.10;
b28 = 0.1;
b27 = 0.2;
b26 = 0.3;
b25 = 0.4;
b24 = 0.5;
b23 = 0.6;
b22 = 0.7;
c0 = 0.8;
flx = 4.689;
rx1 = 64.0;
/*
* end of initialization -- begin timing
*/
/* loop 1 hydro excerpt */
Init();
ts[1] = (double)Clock();
q = 0.0;
for (k = 1; k <= 400; k++)
{
_x[k] = q + _y[k] * (r * _z[k + 10] + t * _z[k + 11]);
}
ts[1] = (double)Clock() - ts[1];
for (k = 1; k <= 400; k++)
{
cksum[1] += (double)k * _x[k];
}
/* loop 2 mlr, inner product */
Init();
ts[2] = (double)Clock();
q = 0.0;
for (k = 1; k <= 996; k += 5)
{
q += _z[k] * _x[k] + _z[k + 1] * _x[k + 1] + _z[k + 2] * _x[k + 2] + _z[k + 3] * _x[k + 3] + _z[k + 4] * _x[k + 4];
}
ts[2] = (double)Clock() - ts[2];
cksum[2] = q;
/* loop 3 inner prod */
Init();
ts[3] = (double)Clock();
q = 0.0;
for (k = 1; k <= 1000; k++)
{
q += _z[k] * _x[k];
}
ts[3] = (double)Clock() - ts[3];
cksum[3] = q;
/* loop 4 banded linear equarions */
Init();
ts[4] = (double)Clock();
for (l = 7; l <= 107; l += 50)
{
lw = l;
for (j = 30; j <= 870; j += 5)
{
_x[l - 1] -= _x[lw++] * _y[j];
}
_x[l - 1] = _y[5] * _x[l - 1];
}
ts[4] = (double)Clock() - ts[4];
for (l = 7; l <= 107; l += 50)
{
cksum[4] += (double)l * _x[l - 1];
}
/* loop 5 tri-diagonal elimination, below diagonal */
Init();
ts[5] = (double)Clock();
for (i = 2; i <= 998; i += 3)
{
_x[i] = _z[i] * (_y[i] - _x[i - 1]);
_x[i + 1] = _z[i + 1] * (_y[i + 1] - _x[i]);
_x[i + 2] = _z[i + 2] * (_y[i + 2] - _x[i + 1]);
}
ts[5] = (double)Clock() - ts[5];
for (i = 2; i <= 1000; i++)
{
cksum[5] += (double)i * _x[i];
}
/* loop 6 tri-diagonal elimination, above diagonal */
Init();
ts[6] = (double)Clock();
for (j = 3; j <= 999; j += 3)
{
i = 1003 - j;
_x[i] = _x[i] - _z[i] * _x[i + 1];
_x[i - 1] = _x[i - 1] - _z[i - 1] * _x[i];
_x[i - 2] = _x[i - 2] - _z[i - 2] * _x[i - 1];
}
ts[6] = (double)Clock() - ts[6];
for (j = 1; j <= 999; j++)
{
l = 1001 - j;
cksum[6] += (double)j * _x[l];
}
/* loop 7 equation of state excerpt */
Init();
ts[7] = (double)Clock();
for (m = 1; m <= 120; m++)
{
_x[m] = _u[m] + r * (_z[m] + r * _y[m]) + t * (_u[m + 3] + r * (_u[m + 2] + r * _u[m + 1]) + t * (_u[m + 6] + r * (_u[m + 5] + r * _u[m + 4])));
}
ts[7] = (double)Clock() - ts[7];
for (m = 1; m <= 120; m++)
{
cksum[7] += (double)m * _x[m];
}
/* loop 8 p.d.e. integration */
Init();
ts[8] = (double)Clock();
nl1 = 1;
nl2 = 2;
for (kx = 2; kx <= 3; kx++)
{
for (ky = 2; ky <= 21; ky++)
{
du1 = _u1[kx][ky + 1][nl1] - _u1[kx][ky - 1][nl1];
du2 = _u2[kx][ky + 1][nl1] - _u2[kx][ky - 1][nl1];
du3 = _u3[kx][ky + 1][nl1] - _u3[kx][ky - 1][nl1];
_u1[kx][ky][nl2] = _u1[kx][ky][nl1] + a11 * du1 + a12 * du2 + a13 * du3 + sig * (_u1[kx + 1][ky][nl1]
- 2.0 * _u1[kx][ky][nl1] + _u1[kx - 1][ky][nl1]);
_u2[kx][ky][nl2] = _u2[kx][ky][nl1] + a21 * du1 + a22 * du2 + a23 * du3 + sig * (_u2[kx + 1][ky][nl1]
- 2.0 * _u2[kx][ky][nl1] + _u2[kx - 1][ky][nl1]);
_u3[kx][ky][nl2] = _u3[kx][ky][nl1] + a31 * du1 + a32 * du2 + a33 * du3 + sig * (_u3[kx + 1][ky][nl1]
- 2.0 * _u3[kx][ky][nl1] + _u3[kx - 1][ky][nl1]);
}
}
ts[8] = (double)Clock() - ts[8];
for (i = 1; i <= 2; i++)
{
for (kx = 2; kx <= 3; kx++)
{
for (ky = 2; ky <= 21; ky++)
{
cksum[8] += (double)kx * (double)ky * (double)i * (_u1[kx][ky][i] + _u2[kx][ky][i] + _u3[kx][ky][i]);
}
}
}
/* loop 9 integrate predictors */
Init();
ts[9] = (double)Clock();
for (i = 1; i <= 100; i++)
{
_px[1][i] = b28 * _px[13][i] + b27 * _px[12][i] + b26 * _px[11][i] + b25 * _px[10][i] + b24 * _px[9][i] +
b23 * _px[8][i] + b22 * _px[7][i] + c0 * (_px[5][i] + _px[6][i]) + _px[3][i];
}
ts[9] = (double)Clock() - ts[9];
for (i = 1; i <= 100; i++)
{
cksum[9] += (double)i * _px[1][i];
}
/* loop 10 difference predictors */
Init();
ts[10] = (double)Clock();
for (i = 1; i <= 100; i++)
{
ar = _cx[5][i];
br = ar - _px[5][i];
_px[5][i] = ar;
cr = br - _px[6][i];
_px[6][i] = br;
ar = cr - _px[7][i];
_px[7][i] = cr;
br = ar - _px[8][i];
_px[8][i] = ar;
cr = br - _px[9][i];
_px[9][i] = br;
ar = cr - _px[10][i];
_px[10][i] = cr;
br = ar - _px[11][i];
_px[11][i] = ar;
cr = br - _px[12][i];
_px[12][i] = br;
_px[14][i] = cr - _px[13][i];
_px[13][i] = cr;
}
ts[10] = (double)Clock() - ts[10];
for (i = 1; i <= 100; i++)
{
for (k = 5; k <= 14; k++)
{
cksum[10] += (double)k * (double)i * _px[k][i];
}
}
/* loop 11 first sum. */
Init();
ts[11] = (double)Clock();
_x[1] = _y[1];
for (k = 2; k <= 1000; k++)
{
_x[k] = _x[k - 1] + _y[k];
}
ts[11] = (double)Clock() - ts[11];
for (k = 1; k <= 1000; k++)
{
cksum[11] += (double)k * _x[k];
}
/* loop 12 first diff. */
Init();
ts[12] = (double)Clock();
for (k = 1; k <= 999; k++)
{
_x[k] = _y[k + 1] - _y[k];
}
ts[12] = (double)Clock() - ts[12];
for (k = 1; k <= 999; k++)
{
cksum[12] += (double)k * _x[k];
}
/* loop 13 2-d particle pusher */
Init();
ts[13] = (double)Clock();
for (ip = 1; ip <= 128; ip++)
{
i1 = (int)_p[1][ip];
j1 = (int)_p[2][ip];
_p[3][ip] += _b[i1][j1];
_p[4][ip] += _c[i1][j1];
_p[1][ip] += _p[3][ip];
_p[2][ip] += _p[4][ip];
// Each element of m_p, m_b and m_c is initialized to 1.00025 in Init().
// From the assignments above,
// i2 = m_p[1][ip] = m_p[1][ip] + m_p[3][ip] = m_p[1][ip] + m_p[3][ip] + m_b[i1][j1] = 1 + 1 + 1 = 3
// j2 = m_p[2][ip] = m_p[2][ip] + m_p[4][ip] = m_p[2][ip] + m_p[4][ip] + m_c[i1][j1] = 1 + 1 + 1 = 3
i2 = (int)_p[1][ip];
j2 = (int)_p[2][ip];
// Accessing m_y, m_z upto 35
_p[1][ip] += _y[i2 + 32];
_p[2][ip] += _z[j2 + 32];
i2 += _e[i2 + 32];
j2 += _f[j2 + 32];
_h[i2][j2] += 1.0;
}
ts[13] = (double)Clock() - ts[13];
for (ip = 1; ip <= 128; ip++)
{
cksum[13] += (double)ip * (_p[3][ip] + _p[4][ip] + _p[1][ip] + _p[2][ip]);
}
for (k = 1; k <= 64; k++)
{
for (ix = 1; ix <= 8; ix++)
{
cksum[13] += (double)k * (double)ix * _h[k][ix];
}
}
/* loop 14 1-d particle pusher */
Init();
ts[14] = (double)Clock();
for (k = 1; k <= 150; k++)
{
// m_grd[150] = 13.636
// Therefore ix <= 13
ix = (int)_grd[k];
xi = (double)ix;
_vx[k] += _ex[ix] + (_xx[k] - xi) * _dex[ix];
_xx[k] += _vx[k] + flx;
ir = (int)_xx[k];
ri = (double)ir;
rx1 = _xx[k] - ri;
ir = System.Math.Abs(ir % 64);
_xx[k] = ri + rx1;
// ir < 64 since ir = ir % 64
// So m_rh is accessed upto 64
_rh[ir] += 1.0 - rx1;
_rh[ir + 1] += rx1;
}
ts[14] = (double)Clock() - ts[14];
for (k = 1; k <= 150; k++)
{
cksum[14] += (double)k * (_vx[k] + _xx[k]);
}
for (k = 1; k <= 67; k++)
{
cksum[14] += (double)k * _rh[k];
}
/* time the clock call */
ts[15] = (double)Clock();
ts[15] = (double)Clock() - ts[15];
/* scale= set to convert time to micro-seconds */
scale = 1.0;
rt[15] = ts[15] * scale;
nt = 14;
t = s = uu = 0.0;
for (k = 1; k <= nt; k++)
{
rt[k] = (ts[k] - ts[15]) * scale;
t += rt[k];
mops[k] = _nrops[k] * _loops[k];
s += (double)mops[k];
rpm[k] = 0.0;
if (rt[k] != 0.0)
{
rpm[k] = (double)mops[k] / rt[k];
}
uu += rpm[k];
}
uu /= (double)nt;
s /= t;
// Ensure that the array elements are live-out
Escape(ts);
Escape(rt);
Escape(rpm);
Escape(cksum);
Escape(mops);
}
private void Init()
{
int j, k, l;
for (k = 1; k <= 1000; k++)
{
_x[k] = 1.11;
_y[k] = 1.123;
_z[k] = 0.321;
}
for (k = 1; k <= 500; k++)
{
_u[k] = 0.00025;
}
for (k = 1; k <= 15; k++)
{
for (l = 1; l <= 100; l++)
{
_px[k][l] = l;
_cx[k][l] = l;
}
}
for (j = 1; j < 6; j++)
{
for (k = 1; k < 23; k++)
{
for (l = 1; l < 3; l++)
{
_u1[j][k][l] = k;
_u2[j][k][l] = k + k;
_u3[j][k][l] = k + k + k;
}
}
}
for (j = 1; j < 65; j++)
{
for (k = 1; k < 9; k++)
{
_b[j][k] = 1.00025;
_c[j][k] = 1.00025;
_h[j][k] = 1.00025;
}
}
for (j = 1; j < 6; j++)
{
_bnk1[j] = j * 100;
_bnk2[j] = j * 110;
_bnk3[j] = j * 120;
_bnk4[j] = j * 130;
_bnk5[j] = j * 140;
}
for (j = 1; j < 5; j++)
{
for (k = 1; k < 513; k++)
{
_p[j][k] = 1.00025;
}
}
for (j = 1; j < 193; j++)
{
_e[j] = _f[j] = 1;
}
for (j = 1; j < 68; j++)
{
_ex[j] = _rh[j] = _dex[j] = (double)j;
}
for (j = 1; j < 151; j++)
{
_vx[j] = 0.001;
_xx[j] = 0.001;
_grd[j] = (double)(j / 8 + 3);
}
}
[Benchmark]
public static void Test()
{
var lloops = new LLoops();
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
lloops.Bench();
}
}
}
private bool TestBase()
{
bool result = Bench();
return result;
}
public static int Main()
{
var lloops = new LLoops();
bool result = lloops.TestBase();
return (result ? 100 : -1);
}
}
}
| |
using System;
using System.Collections;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Xml;
using System.Xml.Xsl;
using System.IO;
using System.Web;
//using QuickDL.Properties;
using System.Globalization;
namespace QuickDL
{
/// <summary>
/// This class is used to get data from a SQL Server database
/// </summary>
public class SqlUtil
{
string _connStr = ""; // ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
public string ZConnStr
{
get { return _connStr; }
set { _connStr = value; }
}
public class DBContext
{
public SqlConnection Connection { get; set; }
public SqlTransaction Transaction { get; set; }
}
#region Private Constants
private readonly string DB_SCHEMA_NAME = (ConfigurationManager.AppSettings["DB_SCHEMA_NAME"] != null ? ConfigurationManager.AppSettings["DB_SCHEMA_NAME"].ToString() : "{0}");
private readonly int COMMAND_TIMEOUT = (ConfigurationManager.AppSettings["SQL_TIMEOUT"] != null ? int.Parse(ConfigurationManager.AppSettings["SQL_TIMEOUT"].ToString()) : 30);
#endregion
#region Private Variables
SqlConnection _conn = null;
#endregion
#region Public Methods
/// <summary>
/// Executes a non query result
/// </summary>
/// <param name="spName">The SP Name to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
public void ExecSPNonQuery(string spName, Hashtable spParams)
{
try
{
ExecSPNonQuery(spName, spParams, _connStr, DB_SCHEMA_NAME);
}
catch
{
throw;
}
}
/// <summary>
/// Returns a dataset from a SP
/// </summary>
/// <param name="spName">The SP Name to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <returns>dataset returned from SP</returns>
public DataSet ExecSP(string spName, Hashtable spParams)
{
try
{
return (ExecSP(spName, spParams, _connStr, DB_SCHEMA_NAME));
}
catch
{
throw;
}
}
/// <summary>
/// Returns a string from a SP
/// </summary>
/// <param name="spName">The SP Name to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="defaultValue">The default value to return if something fails</param>
/// <returns>string returned from SP or defaultValue if failed</returns>
public string ExecSP(string spName, Hashtable spParams, string defaultValue)
{
try
{
return (ExecSP(spName, spParams, _connStr, DB_SCHEMA_NAME, defaultValue));
}
catch
{
throw;
}
}
/// <summary>
/// Returns a string from a SP
/// </summary>
/// <param name="spName">The SP Name to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="defaultValue">The default value to return if something fails</param>
/// <param name="fieldToReturn">The name of the field to return</param>
/// <returns>byte[] returned from SP or defaultValue if failed</returns>
public byte[] ExecSP(string spName, Hashtable spParams, byte[] defaultValue, string fieldToReturn)
{
try
{
return (ExecSP(spName, spParams, _connStr, DB_SCHEMA_NAME, defaultValue, fieldToReturn));
}
catch
{
throw;
}
}
/// <summary>
/// Returns a string from a SP
/// </summary>
/// <param name="spName">The SP Name to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="defaultValue">The default value to return if something fails</param>
/// <returns>int returned from SP or default value if failed</returns>
public int ExecSP(string spName, Hashtable spParams, int defaultValue)
{
try
{
return (ExecSP(spName, spParams, _connStr, DB_SCHEMA_NAME, defaultValue));
}
catch
{
throw;
}
}
/// <summary>
/// Returns a string from a SP
/// </summary>
/// <param name="spName">The SP Name to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="defaultValue">The default value to return if something fails</param>
/// <returns>int returned from SP or default value if failed</returns>
public bool ExecSP(string spName, Hashtable spParams, bool defaultValue)
{
try
{
return (ExecSP(spName, spParams, _connStr, DB_SCHEMA_NAME, defaultValue));
}
catch
{
throw;
}
}
/// <summary>
/// Returns a string from a SP
/// </summary>
/// <param name="spName">The SP Name to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="defaultValue">The default value to return if something fails</param>
/// <returns>int returned from SP or default value if failed</returns>
public double ExecSP(string spName, Hashtable spParams, double defaultValue)
{
try
{
//string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
return (ExecSP(spName, spParams, _connStr, DB_SCHEMA_NAME, defaultValue));
}
catch
{
throw;
}
}
/// <summary>
/// Returns a XmlDocument from a SP
/// </summary>
/// <param name="spName">The SP Name to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="transformFile">The transform file to use with the XML</param>
/// <returns>byte representing transformed html returned from SP</returns>
public string ExecXMLSP(string spName, Hashtable spParams, string transformFile)
{
try
{
return (ExecXMLSP(spName, spParams, _connStr, DB_SCHEMA_NAME, transformFile));
}
catch
{
throw;
}
}
/// <summary>
/// Returns a XmlDocument from a SP
/// </summary>
/// <param name="sql">The sql to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="transformFile">The transform file to use with the XML</param>
/// <returns>byte representing transformed html returned from SP</returns>
public string ExecXMLSQL(string sql, Hashtable spParams, string transformFile)
{
try
{
return (ExecXMLSQL(sql, spParams, _connStr, transformFile));
}
catch
{
throw;
}
}
/// <summary>
/// Executes a non query result
/// </summary>
/// <param name="spName">The sql to run</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
public void ExecSQLNonQuery(string sql, Hashtable spParams)
{
try
{
ExecSQLNonQuery(sql, spParams, _connStr);
}
catch
{
throw;
}
}
/// <summary>
/// Returns a dataset from SQL
/// </summary>
/// <param name="sql">The sql to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <returns>dataset returned from SP</returns>
public DataSet ExecSQL(string sql, Hashtable spParams)
{
try
{
return (ExecSQLConn(sql, spParams, _connStr));
}
catch
{
throw;
}
}
/// <summary>
/// Returns a string from a SQL
/// </summary>
/// <param name="sql">The SQL to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="defaultValue">The default value to return if something fails</param>
/// <returns>string returned from SQL or defaultValue if failed</returns>
public string ExecSQL(string sql, Hashtable spParams, string defaultValue)
{
try
{
return (ExecSQL(sql, spParams, _connStr, defaultValue));
}
catch
{
throw;
}
}
/// <summary>
/// Returns a string from sql
/// </summary>
/// <param name="sql">The SQL to run</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="defaultValue">The default value to return if something fails</param>
/// <param name="fieldToReturn">The name of the field to return</param>
/// <returns>byte[] returned from SQL or defaultValue if failed</returns>
public byte[] ExecSQL(string sql, Hashtable spParams, byte[] defaultValue, string fieldToReturn)
{
try
{
return (ExecSQL(sql, spParams, _connStr, defaultValue, fieldToReturn));
}
catch
{
throw;
}
}
/// <summary>
/// Returns a string from a SQL
/// </summary>
/// <param name="sql">The SQL to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="defaultValue">The default value to return if something fails</param>
/// <returns>int returned from SQL or default value if failed</returns>
public int ExecSQL(string sql, Hashtable spParams, int defaultValue)
{
try
{
return (ExecSQL(sql, spParams, _connStr, defaultValue));
}
catch
{
throw;
}
}
/// <summary>
/// Returns a string from a SQL
/// </summary>
/// <param name="sql">The SQL to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="defaultValue">The default value to return if something fails</param>
/// <returns>int returned from SQL or default value if failed</returns>
public double ExecSQL(string sql, Hashtable spParams, double defaultValue)
{
try
{
return (ExecSQL(sql, spParams, _connStr, defaultValue));
}
catch
{
throw;
}
}
/// <summary>
/// Executes a non query result
/// </summary>
/// <param name="spName">The SP Name to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="connStr">The connection string</param>
/// <param name="schema">The database schema to use in a formatted string... ex [DatabaseName].[SchemaName].{0}</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
public void ExecSPNonQuery(string spName, Hashtable spParams, string connStr, string schema)
{
try
{
ExecSPTrace(spName, spParams, connStr, schema, null, null);
_conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(String.Format(schema, spName));
cmd.CommandType = CommandType.StoredProcedure;
foreach (DictionaryEntry deParam in spParams)
{
cmd.Parameters.AddWithValue(deParam.Key.ToString(), deParam.Value);
}
cmd.Connection = _conn;
cmd.CommandTimeout = COMMAND_TIMEOUT;
//SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
_conn.Open();
cmd.ExecuteNonQuery();
}
catch
{
throw;
}
}
catch
{
throw;
}
finally
{
if (_conn != null)
{
_conn.Close();
_conn.Dispose();
}
}
}
public int ExecSPReturnIntValue(string spName, Hashtable spParams)
{
try
{
ExecSPTrace(spName, spParams, null, null, null, null);
_conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(String.Format(DB_SCHEMA_NAME, spName));
cmd.CommandType = CommandType.StoredProcedure;
foreach (DictionaryEntry deParam in spParams)
{
cmd.Parameters.AddWithValue(deParam.Key.ToString(), deParam.Value);
}
const string RETURN_VALUE_NAME = "@ReturnValue";
SqlParameter returnValueParam = new SqlParameter(RETURN_VALUE_NAME, SqlDbType.Int);
returnValueParam.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(returnValueParam);
cmd.Connection = _conn;
cmd.CommandTimeout = COMMAND_TIMEOUT;
//SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
_conn.Open();
cmd.ExecuteNonQuery();
object returnValue = cmd.Parameters[RETURN_VALUE_NAME].Value;
return (int)returnValue;
}
catch
{
throw;
}
}
catch
{
throw;
}
finally
{
if (_conn != null)
{
_conn.Close();
_conn.Dispose();
}
}
}
void ExecSPTrace(string spName, Hashtable spParams, string connStr, string schema, string defaultValue, string fieldToReturn)
{
//if (!Settings.Default.SqlTraceEnabled) return;
bool SqlTraceEnabled = false;
if (!SqlTraceEnabled) return;
if (spName == null) spName = "***NULL***";
if (connStr == null) connStr = "***NULL***";
if (schema == null) schema = "***NULL***";
if (defaultValue == null) defaultValue = "***NULL***";
if (fieldToReturn == null) fieldToReturn = "***NULL***";
if (spParams == null) spParams = new Hashtable();
StringBuilder sql = new StringBuilder();
sql.AppendFormat("{0}", spName);
foreach (DictionaryEntry param in spParams)
{
string value;
if (param.Value == null)
{
value = "<NULL>";
}
else
{
string s = param.Value.ToString();
value = s.Length == 0 ? "<BLANK>" : s;
}
sql.AppendFormat(" {0}=[{1}]", param.Key, value);
}
HttpContext context = HttpContext.Current;
if (context != null)
{
context.Trace.Write("DB", sql.ToString());
return;
}
// Quick-and-dirty output to a text file for a non-Web app.
string logFile = Path.Combine(Environment.CurrentDirectory, "core-sql.log");
File.AppendAllText(logFile, sql.ToString() + Environment.NewLine);
}
/// <summary>
/// Returns a dataset from a SP
/// </summary>
/// <param name="spName">The SP Name to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="connStr">The connection string</param>
/// <param name="schema">The database schema to use in a formatted string... ex [DatabaseName].[SchemaName].{0}</param>
/// <returns>dataset returned from SP</returns>
public DataSet ExecSP(string spName, Hashtable spParams, string connStr, string schema)
{
try
{
ExecSPTrace(spName, spParams, connStr, schema, null, null);
_conn = new SqlConnection(connStr);
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(String.Format(schema, spName));
cmd.CommandType = CommandType.StoredProcedure;
foreach (DictionaryEntry deParam in spParams)
{
cmd.Parameters.AddWithValue(deParam.Key.ToString(), deParam.Value);
}
cmd.Connection = _conn;
cmd.CommandTimeout = COMMAND_TIMEOUT;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
return ds;
}
catch
{
throw;
}
finally
{
if (_conn != null)
{
_conn.Close();
_conn.Dispose();
}
}
}
/// <summary>
/// Returns a string from a SP
/// </summary>
/// <param name="spName">The SP Name to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="defaultValue">The default value to return if something fails</param>
/// <param name="connStr">The connection string</param>
/// <param name="schema">The database schema to use in a formatted string... ex [DatabaseName].[SchemaName].{0}</param>
/// <returns>string returned from SP or defaultValue if failed</returns>
public string ExecSP(string spName, Hashtable spParams, string connStr, string schema, string defaultValue)
{
try
{
ExecSPTrace(spName, spParams, connStr, schema, defaultValue, null);
_conn = new SqlConnection(connStr);
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(String.Format(schema, spName));
cmd.CommandType = CommandType.StoredProcedure;
foreach (DictionaryEntry deParam in spParams)
{
cmd.Parameters.AddWithValue(deParam.Key.ToString(), deParam.Value);
}
cmd.Connection = _conn;
cmd.CommandTimeout = COMMAND_TIMEOUT;
//SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
_conn.Open();
object fieldValue = cmd.ExecuteScalar();
if (fieldValue == null) return null;
string strReturn = fieldValue.ToString();
return strReturn;
}
catch
{
//return (defaultValue);
throw;
}
}
catch
{
throw;
}
finally
{
if (_conn != null)
{
_conn.Close();
_conn.Dispose();
}
}
}
/// <summary>
/// Returns a string from a SP
/// </summary>
/// <param name="spName">The SP Name to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="defaultValue">The default value to return if something fails</param>
/// <param name="fieldToReturn">The name of the field to return</param>
/// <param name="connStr">The connection string</param>
/// <param name="schema">The database schema to use in a formatted string... ex [DatabaseName].[SchemaName].{0}</param>
/// <returns>byte[] returned from SP or defaultValue if failed</returns>
public byte[] ExecSP(string spName, Hashtable spParams, string connStr, string schema, byte[] defaultValue, string fieldToReturn)
{
try
{
ExecSPTrace(spName, spParams, connStr, schema, "byte[]", fieldToReturn);
_conn = new SqlConnection(connStr);
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(String.Format(schema, spName));
cmd.CommandType = CommandType.StoredProcedure;
foreach (DictionaryEntry deParam in spParams)
{
cmd.Parameters.AddWithValue(deParam.Key.ToString(), deParam.Value);
}
cmd.Connection = _conn;
cmd.CommandTimeout = COMMAND_TIMEOUT;
//SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
//open the connection
_conn.Open();
//create a reader
SqlDataReader sr = cmd.ExecuteReader();
//read the data
sr.Read();
byte[] objReturn = (byte[])sr[fieldToReturn];
sr.Close();
sr.Dispose();
return objReturn;
}
catch
{
//return (defaultValue);
throw;
}
}
catch
{
throw;
}
finally
{
if (_conn != null)
{
_conn.Close();
_conn.Dispose();
}
}
}
/// <summary>
/// Returns a string from a SP
/// </summary>
/// <param name="spName">The SP Name to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="defaultValue">The default value to return if something fails</param>
/// <param name="connStr">The connection string</param>
/// <param name="schema">The database schema to use in a formatted string... ex [DatabaseName].[SchemaName].{0}</param>
/// <returns>int returned from SP or default value if failed</returns>
public int ExecSP(string spName, Hashtable spParams, string connStr, string schema, int defaultValue)
{
try
{
ExecSPTrace(spName, spParams, connStr, schema,
"int=" + defaultValue == null ? "NULL" : defaultValue.ToString(), null);
_conn = new SqlConnection(connStr);
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(String.Format(schema, spName));
cmd.CommandType = CommandType.StoredProcedure;
foreach (DictionaryEntry deParam in spParams)
{
cmd.Parameters.AddWithValue(deParam.Key.ToString(), deParam.Value);
}
cmd.Connection = _conn;
cmd.CommandTimeout = COMMAND_TIMEOUT;
//SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
_conn.Open();
object obj = cmd.ExecuteScalar();
if (obj == null) return defaultValue;
int strReturn = int.Parse(obj.ToString());
return strReturn;
}
catch
{
//return (defaultValue);
throw;
}
}
catch
{
throw;
}
finally
{
if (_conn != null)
{
_conn.Close();
_conn.Dispose();
}
}
}
/// <summary>
/// Returns a string from a SP
/// </summary>
/// <param name="spName">The SP Name to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="defaultValue">The default value to return if something fails</param>
/// <param name="connStr">The connection string</param>
/// <param name="schema">The database schema to use in a formatted string... ex [DatabaseName].[SchemaName].{0}</param>
/// <returns>int returned from SP or default value if failed</returns>
public bool ExecSP(string spName, Hashtable spParams, string connStr, string schema, bool defaultValue)
{
try
{
ExecSPTrace(spName, spParams, connStr, schema,
"bool=" + defaultValue == null ? "NULL" : defaultValue.ToString(), null);
_conn = new SqlConnection(connStr);
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(String.Format(schema, spName));
cmd.CommandType = CommandType.StoredProcedure;
foreach (DictionaryEntry deParam in spParams)
{
cmd.Parameters.AddWithValue(deParam.Key.ToString(), deParam.Value);
}
cmd.Connection = _conn;
cmd.CommandTimeout = COMMAND_TIMEOUT;
//SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
_conn.Open();
object obj = cmd.ExecuteScalar();
if (obj == null) return defaultValue;
bool value = (bool)obj;
return value;
}
catch
{
//return (defaultValue);
throw;
}
}
catch
{
throw;
}
finally
{
if (_conn != null)
{
_conn.Close();
_conn.Dispose();
}
}
}
/// <summary>
/// Returns a string from a SP
/// </summary>
/// <param name="spName">The SP Name to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="defaultValue">The default value to return if something fails</param>
/// <param name="connStr">The connection string</param>
/// <param name="schema">The database schema to use in a formatted string... ex [DatabaseName].[SchemaName].{0}</param>
/// <returns>int returned from SP or default value if failed</returns>
public double ExecSP(string spName, Hashtable spParams, string connStr, string schema, double defaultValue)
{
try
{
ExecSPTrace(spName, spParams, connStr, schema,
"double=" + defaultValue == null ? "NULL" : defaultValue.ToString(), null);
_conn = new SqlConnection(connStr);
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(String.Format(schema, spName));
cmd.CommandType = CommandType.StoredProcedure;
foreach (DictionaryEntry deParam in spParams)
{
cmd.Parameters.AddWithValue(deParam.Key.ToString(), deParam.Value);
}
cmd.Connection = _conn;
cmd.CommandTimeout = COMMAND_TIMEOUT;
//SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
_conn.Open();
object obj = cmd.ExecuteScalar();
double strReturn = double.Parse(obj.ToString());
return strReturn;
}
catch
{
//return (defaultValue);
throw;
}
}
catch
{
throw;
}
finally
{
if (_conn != null)
{
_conn.Close();
_conn.Dispose();
}
}
}
/// <summary>
/// Returns a XmlDocument from a SP
/// </summary>
/// <param name="spName">The SP Name to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="transformFile">The transform file to use with the XML</param>
/// <param name="connStr">The connection string</param>
/// <param name="schema">The database schema to use in a formatted string... ex [DatabaseName].[SchemaName].{0}</param>
/// <returns>byte representing transformed html returned from SP</returns>
public string ExecXMLSP(string spName, Hashtable spParams, string connStr, string schema, string transformFile)
{
try
{
ExecSPTrace(spName, spParams, connStr, schema, transformFile, null);
_conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(String.Format(schema, spName));
cmd.CommandType = CommandType.StoredProcedure;
foreach (DictionaryEntry deParam in spParams)
{
cmd.Parameters.AddWithValue(deParam.Key.ToString(), deParam.Value);
}
cmd.Connection = _conn;
cmd.CommandTimeout = COMMAND_TIMEOUT;
//declare transform variable
XslCompiledTransform xctrans = new XslCompiledTransform();
//create a memory stream
MemoryStream ms = new MemoryStream();
//create a xmlWrite and attach it to the memorystream
XmlWriter xWriter = new XmlTextWriter(ms, Encoding.Default);
//open the connection
_conn.Open();
//read in the XML to the xReader
XmlReader xReader = cmd.ExecuteXmlReader();
try
{
//check to make sure the transform exists
if (File.Exists(transformFile))
{
//load the transform file
xctrans.Load(transformFile);
//transform the XML from the xReader and output it to the memorystream attached
//to the xWriter
xctrans.Transform(xReader, null, xWriter);
//set the memory streams position back to the beginning of the stream
ms.Position = 0;
//create a streamreader on the memory stream
StreamReader sr = new StreamReader(ms);
try
{
//read the memory stream to the end and output it as a string
return (sr.ReadToEnd());
}
catch
{
throw;
}
finally
{
//close the streamreader
sr.Close();
}
}
else
{
throw (new Exception(String.Concat("XML Loading: File does not exist! - ", transformFile)));
}
}
catch
{
throw;
}
finally
{
//close the rest of the objects (xmlreader,xmlwriter,memorystream)
xReader.Close();
xWriter.Close();
ms.Close();
}
}
catch
{
throw;
}
finally
{
if (_conn != null)
{
_conn.Close();
_conn.Dispose();
}
}
}
/// <summary>
/// Returns a XmlDocument from a SP
/// </summary>
/// <param name="sql">The sql to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="transformFile">The transform file to use with the XML</param>
/// <param name="connStr">The connection string</param>
/// <returns>byte representing transformed html returned from SP</returns>
public string ExecXMLSQL(string sql, Hashtable spParams, string connStr, string transformFile)
{
try
{
ExecSPTrace(sql, spParams, connStr, null, transformFile, null);
_conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(sql);
cmd.CommandType = CommandType.Text;
cmd.Connection = _conn;
cmd.CommandTimeout = COMMAND_TIMEOUT;
foreach (DictionaryEntry deParam in spParams)
{
cmd.Parameters.AddWithValue(deParam.Key.ToString(), deParam.Value);
}
//declare transform variable
XslCompiledTransform xctrans = new XslCompiledTransform();
//create a memory stream
MemoryStream ms = new MemoryStream();
//create a xmlWrite and attach it to the memorystream
XmlWriter xWriter = new XmlTextWriter(ms, Encoding.Default);
//open the connection
_conn.Open();
//read in the XML to the xReader
XmlReader xReader = cmd.ExecuteXmlReader();
try
{
//check to make sure the transform exists
if (File.Exists(transformFile))
{
//load the transform file
xctrans.Load(transformFile);
//transform the XML from the xReader and output it to the memorystream attached
//to the xWriter
xctrans.Transform(xReader, null, xWriter);
//set the memory streams position back to the beginning of the stream
ms.Position = 0;
//create a streamreader on the memory stream
StreamReader sr = new StreamReader(ms);
try
{
//read the memory stream to the end and output it as a string
return (sr.ReadToEnd());
}
catch
{
throw;
}
finally
{
//close the streamreader
sr.Close();
}
}
else
{
throw (new Exception(String.Concat("XML Loading: File does not exist! - ", transformFile)));
}
}
catch
{
throw;
}
finally
{
//close the rest of the objects (xmlreader,xmlwriter,memorystream)
xReader.Close();
xWriter.Close();
ms.Close();
}
}
catch
{
throw;
}
finally
{
if (_conn != null)
{
_conn.Close();
_conn.Dispose();
}
}
}
/// <summary>
/// Executes a non query result
/// </summary>
/// <param name="sql">The sql to run</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="connStr">The connection string</param>
/// <param name="schema">The database schema to use in a formatted string... ex [DatabaseName].[SchemaName].{0}</param>
public void ExecSQLNonQuery(string sql, Hashtable spParams, string connStr)
{
try
{
ExecSPTrace(sql, spParams, connStr, null, null, null);
_conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(sql);
cmd.CommandType = CommandType.Text;
cmd.Connection = _conn;
cmd.CommandTimeout = COMMAND_TIMEOUT;
foreach (DictionaryEntry deParam in spParams)
{
cmd.Parameters.AddWithValue(deParam.Key.ToString(), deParam.Value);
}
//SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
_conn.Open();
cmd.ExecuteNonQuery();
}
catch
{
throw;
}
}
catch
{
throw;
}
finally
{
if (_conn != null)
{
_conn.Close();
_conn.Dispose();
}
}
}
/// <summary>
/// Returns a dataset from SQL
/// </summary>
/// <param name="sql">The sql to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="connStr">The connection string</param>
/// <returns>dataset returned from SP</returns>
public DataSet ExecSQLConn(string sql, Hashtable spParams, string connStr)
{
try
{
ExecSPTrace(sql, spParams, connStr, null, null, null);
_conn = new SqlConnection(connStr);
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(sql);
cmd.CommandType = CommandType.Text;
cmd.Connection = _conn;
cmd.CommandTimeout = COMMAND_TIMEOUT;
foreach (DictionaryEntry deParam in spParams)
{
cmd.Parameters.AddWithValue(deParam.Key.ToString(), deParam.Value);
}
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
return ds;
}
catch
{
throw;
}
finally
{
if (_conn != null)
{
_conn.Close();
_conn.Dispose();
}
}
}
/// <summary>
/// Returns a string from a SQL
/// </summary>
/// <param name="sql">The SQL to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="defaultValue">The default value to return if something fails</param>
/// <param name="connStr">The connection string</param>
/// <returns>string returned from SQL or defaultValue if failed</returns>
public string ExecSQL(string sql, Hashtable spParams, string connStr, string defaultValue)
{
try
{
ExecSPTrace(sql, spParams, connStr, null,
"string=" + defaultValue == null ? "NULL" : defaultValue.ToString(), null);
_conn = new SqlConnection(connStr);
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(sql);
cmd.CommandType = CommandType.Text;
cmd.Connection = _conn;
cmd.CommandTimeout = COMMAND_TIMEOUT;
foreach (DictionaryEntry deParam in spParams)
{
cmd.Parameters.AddWithValue(deParam.Key.ToString(), deParam.Value);
}
//SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
_conn.Open();
string strReturn = cmd.ExecuteScalar().ToString();
return strReturn;
}
catch
{
//return (defaultValue);
throw;
}
}
catch
{
throw;
}
finally
{
if (_conn != null)
{
_conn.Close();
_conn.Dispose();
}
}
}
/// <summary>
/// Returns a string from sql
/// </summary>
/// <param name="sql">The SQL to run</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="defaultValue">The default value to return if something fails</param>
/// <param name="fieldToReturn">The name of the field to return</param>
/// <param name="connStr">The connection string</param>
/// <returns>byte[] returned from SQL or defaultValue if failed</returns>
public byte[] ExecSQL(string sql, Hashtable spParams, string connStr, byte[] defaultValue, string fieldToReturn)
{
try
{
ExecSPTrace(sql, spParams, connStr, null,
defaultValue == null ? "NO" : "YES", fieldToReturn);
_conn = new SqlConnection(connStr);
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(sql);
cmd.CommandType = CommandType.Text;
cmd.Connection = _conn;
cmd.CommandTimeout = COMMAND_TIMEOUT;
foreach (DictionaryEntry deParam in spParams)
{
cmd.Parameters.AddWithValue(deParam.Key.ToString(), deParam.Value);
}
//SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
//open the connection
_conn.Open();
//create a reader
SqlDataReader sr = cmd.ExecuteReader();
//read the data
sr.Read();
byte[] objReturn = (byte[])sr[fieldToReturn];
sr.Close();
sr.Dispose();
return objReturn;
}
catch
{
//return (defaultValue);
throw;
}
}
catch
{
throw;
}
finally
{
if (_conn != null)
{
_conn.Close();
_conn.Dispose();
}
}
}
/// <summary>
/// Returns a string from a SQL
/// </summary>
/// <param name="sql">The SQL to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="defaultValue">The default value to return if something fails</param>
/// <param name="connStr">The connection string</param>
/// <returns>int returned from SQL or default value if failed</returns>
public int ExecSQL(string sql, Hashtable spParams, string connStr, int defaultValue)
{
try
{
ExecSPTrace(sql, spParams, connStr, null,
"int=" + defaultValue == null ? "NULL" : defaultValue.ToString(), null);
_conn = new SqlConnection(connStr);
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(sql);
cmd.CommandType = CommandType.Text;
cmd.Connection = _conn;
cmd.CommandTimeout = COMMAND_TIMEOUT;
foreach (DictionaryEntry deParam in spParams)
{
cmd.Parameters.AddWithValue(deParam.Key.ToString(), deParam.Value);
}
//SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
_conn.Open();
object o = cmd.ExecuteScalar();
if (o == null) return defaultValue;
int i = int.Parse(o.ToString(), CultureInfo.InvariantCulture);
return i;
}
catch
{
//return (defaultValue);
throw;
}
}
catch
{
throw;
}
finally
{
if (_conn != null)
{
_conn.Close();
_conn.Dispose();
}
}
}
/// <summary>
/// Returns a string from a SQL
/// </summary>
/// <param name="sql">The SQL to execute</param>
/// <param name="spParams">The parameters for the sp in the form of a hashtable (key = param name , value=value)</param>
/// <param name="defaultValue">The default value to return if something fails</param>
/// <param name="connStr">The connection string</param>
/// <returns>int returned from SQL or default value if failed</returns>
public double ExecSQL(string sql, Hashtable spParams, string connStr, double defaultValue)
{
try
{
ExecSPTrace(sql, spParams, connStr, null,
"double=" + defaultValue == null ? "NULL" : defaultValue.ToString(), null);
_conn = new SqlConnection(connStr);
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(sql);
cmd.CommandType = CommandType.Text;
cmd.Connection = _conn;
cmd.CommandTimeout = COMMAND_TIMEOUT;
foreach (DictionaryEntry deParam in spParams)
{
cmd.Parameters.AddWithValue(deParam.Key.ToString(), deParam.Value);
}
//SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
_conn.Open();
double strReturn = double.Parse(cmd.ExecuteScalar().ToString());
return strReturn;
}
catch
{
//return (defaultValue);
throw;
}
}
catch
{
throw;
}
finally
{
if (_conn != null)
{
_conn.Close();
_conn.Dispose();
}
}
}
#endregion
#region Connection-Oriented Methods (With Transaction)
public object Connect()
{
return Connect(IsolationLevel.Unspecified);
}
public object Connect(IsolationLevel iso)
{
string connStr = _connStr;
DBContext context = new DBContext();
context.Connection = new SqlConnection(connStr);
context.Connection.Open();
context.Transaction = iso == IsolationLevel.Unspecified ?
context.Connection.BeginTransaction() :
context.Connection.BeginTransaction(iso);
return context;
}
public void Commit(object context)
{
DBContext db = (DBContext)context;
db.Transaction.Commit();
db.Connection.Close();
}
public void Rollback(object context)
{
DBContext db = (DBContext)context;
db.Transaction.Rollback();
db.Connection.Close();
}
public int ExecuteScalar(string sql, object context)
{
ExecSPTrace(sql, null, "***CONTEXT***", null, null, null);
DBContext db = (DBContext)context;
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(sql);
cmd.CommandType = CommandType.Text;
cmd.Transaction = db.Transaction;
cmd.Connection = db.Connection;
cmd.CommandTimeout = COMMAND_TIMEOUT;
//SqlDataAdapter da = new SqlDataAdapter(cmd);
object obj = cmd.ExecuteScalar();
if (obj == null) return -1;
int value = int.Parse(obj.ToString());
return value;
}
public void ExecuteNonQuery(string sql, object context)
{
ExecSPTrace(sql, null, "***CONTEXT***", null, null, null);
DBContext db = (DBContext)context;
SqlCommand cmd = new SqlCommand(sql);
cmd.CommandType = CommandType.Text;
cmd.Transaction = db.Transaction;
cmd.Connection = db.Connection;
cmd.CommandTimeout = COMMAND_TIMEOUT;
//SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
}
public SqlDataReader ExecuteQuery(string sql, object context)
{
ExecSPTrace(sql, null, "***CONTEXT***", null, null, null);
DBContext db = (DBContext)context;
SqlCommand cmd = new SqlCommand(sql);
cmd.CommandType = CommandType.Text;
cmd.Transaction = db.Transaction;
cmd.Connection = db.Connection;
cmd.CommandTimeout = COMMAND_TIMEOUT;
//SqlDataAdapter da = new SqlDataAdapter(cmd);
return cmd.ExecuteReader();
}
#endregion
}
}
| |
// 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
* URL Shortener API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/url-shortener/v1/getting_started'>URL Shortener API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20150519 (138)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/url-shortener/v1/getting_started'>
* https://developers.google.com/url-shortener/v1/getting_started</a>
* <tr><th>Discovery Name<td>urlshortener
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using URL Shortener API can be found at
* <a href='https://developers.google.com/url-shortener/v1/getting_started'>https://developers.google.com/url-shortener/v1/getting_started</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.Urlshortener.v1
{
/// <summary>The Urlshortener Service.</summary>
public class UrlshortenerService : 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 UrlshortenerService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public UrlshortenerService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
url = new UrlResource(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 "urlshortener"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://www.googleapis.com/urlshortener/v1/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return "urlshortener/v1/"; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://www.googleapis.com/batch"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch"; }
}
#endif
/// <summary>Available OAuth 2.0 scopes for use with the URL Shortener API.</summary>
public class Scope
{
/// <summary>Manage your goo.gl short URLs</summary>
public static string Urlshortener = "https://www.googleapis.com/auth/urlshortener";
}
private readonly UrlResource url;
/// <summary>Gets the Url resource.</summary>
public virtual UrlResource Url
{
get { return url; }
}
}
///<summary>A base abstract class for Urlshortener requests.</summary>
public abstract class UrlshortenerBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new UrlshortenerBaseServiceRequest instance.</summary>
protected UrlshortenerBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>Data format for the 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 the response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
}
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [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. Overrides userIp if both are provided.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user
/// limits.</summary>
[Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserIp { get; set; }
/// <summary>Initializes Urlshortener parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userIp", new Google.Apis.Discovery.Parameter
{
Name = "userIp",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "url" collection of methods.</summary>
public class UrlResource
{
private const string Resource = "url";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public UrlResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Expands a short URL or gets creation time and analytics.</summary>
/// <param name="shortUrl">The short URL, including the protocol.</param>
public virtual GetRequest Get(string shortUrl)
{
return new GetRequest(service, shortUrl);
}
/// <summary>Expands a short URL or gets creation time and analytics.</summary>
public class GetRequest : UrlshortenerBaseServiceRequest<Google.Apis.Urlshortener.v1.Data.Url>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string shortUrl)
: base(service)
{
ShortUrl = shortUrl;
InitParameters();
}
/// <summary>The short URL, including the protocol.</summary>
[Google.Apis.Util.RequestParameterAttribute("shortUrl", Google.Apis.Util.RequestParameterType.Query)]
public virtual string ShortUrl { get; private set; }
/// <summary>Additional information to return.</summary>
[Google.Apis.Util.RequestParameterAttribute("projection", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<ProjectionEnum> Projection { get; set; }
/// <summary>Additional information to return.</summary>
public enum ProjectionEnum
{
/// <summary>Returns only click counts.</summary>
[Google.Apis.Util.StringValueAttribute("ANALYTICS_CLICKS")]
ANALYTICSCLICKS,
/// <summary>Returns only top string counts.</summary>
[Google.Apis.Util.StringValueAttribute("ANALYTICS_TOP_STRINGS")]
ANALYTICSTOPSTRINGS,
/// <summary>Returns the creation timestamp and all available analytics.</summary>
[Google.Apis.Util.StringValueAttribute("FULL")]
FULL,
}
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "url"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"shortUrl", new Google.Apis.Discovery.Parameter
{
Name = "shortUrl",
IsRequired = true,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"projection", new Google.Apis.Discovery.Parameter
{
Name = "projection",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Creates a new short URL.</summary>
/// <param name="body">The body of the request.</param>
public virtual InsertRequest Insert(Google.Apis.Urlshortener.v1.Data.Url body)
{
return new InsertRequest(service, body);
}
/// <summary>Creates a new short URL.</summary>
public class InsertRequest : UrlshortenerBaseServiceRequest<Google.Apis.Urlshortener.v1.Data.Url>
{
/// <summary>Constructs a new Insert request.</summary>
public InsertRequest(Google.Apis.Services.IClientService service, Google.Apis.Urlshortener.v1.Data.Url body)
: base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Urlshortener.v1.Data.Url 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 "insert"; }
}
///<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 "url"; }
}
/// <summary>Initializes Insert parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
/// <summary>Retrieves a list of URLs shortened by a user.</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Retrieves a list of URLs shortened by a user.</summary>
public class ListRequest : UrlshortenerBaseServiceRequest<Google.Apis.Urlshortener.v1.Data.UrlHistory>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>Additional information to return.</summary>
[Google.Apis.Util.RequestParameterAttribute("projection", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<ProjectionEnum> Projection { get; set; }
/// <summary>Additional information to return.</summary>
public enum ProjectionEnum
{
/// <summary>Returns short URL click counts.</summary>
[Google.Apis.Util.StringValueAttribute("ANALYTICS_CLICKS")]
ANALYTICSCLICKS,
/// <summary>Returns short URL click counts.</summary>
[Google.Apis.Util.StringValueAttribute("FULL")]
FULL,
}
/// <summary>Token for requesting successive pages of results.</summary>
[Google.Apis.Util.RequestParameterAttribute("start-token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string StartToken { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "url/history"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"projection", new Google.Apis.Discovery.Parameter
{
Name = "projection",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"start-token", new Google.Apis.Discovery.Parameter
{
Name = "start-token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.Urlshortener.v1.Data
{
public class AnalyticsSnapshot : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Top browsers, e.g. "Chrome"; sorted by (descending) click counts. Only present if this data is
/// available.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("browsers")]
public virtual System.Collections.Generic.IList<StringCount> Browsers { get; set; }
/// <summary>Top countries (expressed as country codes), e.g. "US" or "DE"; sorted by (descending) click counts.
/// Only present if this data is available.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("countries")]
public virtual System.Collections.Generic.IList<StringCount> Countries { get; set; }
/// <summary>Number of clicks on all goo.gl short URLs pointing to this long URL.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("longUrlClicks")]
public virtual System.Nullable<long> LongUrlClicks { get; set; }
/// <summary>Top platforms or OSes, e.g. "Windows"; sorted by (descending) click counts. Only present if this
/// data is available.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("platforms")]
public virtual System.Collections.Generic.IList<StringCount> Platforms { get; set; }
/// <summary>Top referring hosts, e.g. "www.google.com"; sorted by (descending) click counts. Only present if
/// this data is available.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("referrers")]
public virtual System.Collections.Generic.IList<StringCount> Referrers { get; set; }
/// <summary>Number of clicks on this short URL.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("shortUrlClicks")]
public virtual System.Nullable<long> ShortUrlClicks { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class AnalyticsSummary : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Click analytics over all time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("allTime")]
public virtual AnalyticsSnapshot AllTime { get; set; }
/// <summary>Click analytics over the last day.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("day")]
public virtual AnalyticsSnapshot Day { get; set; }
/// <summary>Click analytics over the last month.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("month")]
public virtual AnalyticsSnapshot Month { get; set; }
/// <summary>Click analytics over the last two hours.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("twoHours")]
public virtual AnalyticsSnapshot TwoHours { get; set; }
/// <summary>Click analytics over the last week.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("week")]
public virtual AnalyticsSnapshot Week { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class StringCount : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Number of clicks for this top entry, e.g. for this particular country or browser.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("count")]
public virtual System.Nullable<long> Count { get; set; }
/// <summary>Label assigned to this top entry, e.g. "US" or "Chrome".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class Url : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A summary of the click analytics for the short and long URL. Might not be present if not requested
/// or currently unavailable.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("analytics")]
public virtual AnalyticsSummary Analytics { get; set; }
/// <summary>Time the short URL was created; ISO 8601 representation using the yyyy-MM-dd'T'HH:mm:ss.SSSZZ
/// format, e.g. "2010-10-14T19:01:24.944+00:00".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("created")]
public virtual string Created { get; set; }
/// <summary>Short URL, e.g. "http://goo.gl/l6MS".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>The fixed string "urlshortener#url".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Long URL, e.g. "http://www.google.com/". Might not be present if the status is "REMOVED".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("longUrl")]
public virtual string LongUrl { get; set; }
/// <summary>Status of the target URL. Possible values: "OK", "MALWARE", "PHISHING", or "REMOVED". A URL might
/// be marked "REMOVED" if it was flagged as spam, for example.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("status")]
public virtual string Status { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class UrlHistory : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A list of URL resources.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("items")]
public virtual System.Collections.Generic.IList<Url> Items { get; set; }
/// <summary>Number of items returned with each full "page" of results. Note that the last page could have fewer
/// items than the "itemsPerPage" value.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("itemsPerPage")]
public virtual System.Nullable<int> ItemsPerPage { get; set; }
/// <summary>The fixed string "urlshortener#urlHistory".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>A token to provide to get the next page of results.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>Total number of short URLs associated with this user (may be approximate).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("totalItems")]
public virtual System.Nullable<int> TotalItems { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
namespace WebLabDeusto
{
public class SessionId
{
private readonly string id;
public SessionId(string id)
{
this.id = id;
}
public string Id
{
get{
return this.id;
}
}
public override string ToString()
{
return "SessionId(" + this.id + ")";
}
}
public class ReservationId
{
private readonly string id;
public ReservationId(string id)
{
this.id = id;
}
public string Id
{
get{
return this.id;
}
}
public override string ToString()
{
return "ReservationId(" + this.id + ")";
}
}
public abstract class Reservation
{
protected readonly ReservationId reservationId;
public Reservation(string reservationId)
{
this.reservationId = new ReservationId(reservationId);
}
public ReservationId ReservationId
{
get{
return this.reservationId;
}
}
}
public class WaitingConfirmationReservation : Reservation
{
public WaitingConfirmationReservation(string reservationId):base(reservationId)
{ }
public override string ToString()
{
return "WaitingConfirmationReservation(" + this.reservationId + ")";
}
}
public class WaitingReservation : Reservation
{
private readonly int position;
public WaitingReservation(string reservationId, int position):base(reservationId)
{
this.position = position;
}
public int Position
{
get{
return this.position;
}
}
public override string ToString()
{
return "WaitingReservation(" + this.reservationId + ", " + this.position + ")";
}
}
public class WaitingInstancesReservation : Reservation
{
private readonly int position;
public WaitingInstancesReservation(string reservationId, int position) : base(reservationId)
{
this.position = position;
}
public int Position
{
get{
return this.position;
}
}
public override string ToString()
{
return "WaitingInstancesReservation(" + this.reservationId + ", " + this.position + ")";
}
}
public class ConfirmedReservation : Reservation
{
private readonly double time;
private readonly string initialConfiguration;
private readonly string url;
private readonly string remoteReservationId;
public ConfirmedReservation(string reservationId, double time, string initialConfiguration, string url, string remoteReservationId) : base(reservationId)
{
this.time = time;
this.initialConfiguration = initialConfiguration;
this.url = url;
this.remoteReservationId = remoteReservationId;
}
public double Time
{
get{
return this.time;
}
}
public string InitialConfiguration
{
get{
return this.initialConfiguration;
}
}
public string Url
{
get{
return this.url;
}
}
public string RemoteReservationId
{
get{
return this.remoteReservationId;
}
}
public bool IsRemote
{
get{
return this.remoteReservationId == null || this.remoteReservationId == "";
}
}
public bool IsLocal
{
get{
return !IsRemote;
}
}
public override string ToString()
{
return "ConfirmedReservation(" + this.reservationId + ", " + this.time + ", " + this.initialConfiguration + ", " + this.url + ", " + this.remoteReservationId + ")";
}
}
public class PostReservationReservation : Reservation
{
private readonly bool finished;
private readonly string initialData;
private readonly string endData;
public PostReservationReservation(string reservationId, bool finished, string initialData, string endData) : base(reservationId)
{
this.finished = finished;
this.initialData = initialData;
this.endData = endData;
}
public bool IsFinished
{
get{
return this.finished;
}
}
public string InitialData
{
get{
return this.initialData;
}
}
public string EndData
{
get{
return this.endData;
}
}
public override string ToString()
{
return "PostReservationReservation( " + this.reservationId + ", " + this.finished + ", " + this.initialData + ", " + this.endData + ")";
}
}
}
| |
//
// Copyright (c) 2008-2013, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Vhdx
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
/// <summary>
/// Creates new VHD disks by wrapping existing streams.
/// </summary>
/// <remarks>Using this method for creating virtual disks avoids consuming
/// large amounts of memory, or going via the local file system when the aim
/// is simply to present a VHD version of an existing disk.</remarks>
public sealed class DiskBuilder : DiskImageBuilder
{
private long _blockSize = 32 * Sizes.OneMiB;
/// <summary>
/// Gets or sets the type of VHDX file to build.
/// </summary>
public DiskType DiskType { get; set; }
/// <summary>
/// The VHDX block size, or <c>0</c> (indicating default).
/// </summary>
public long BlockSize
{
get
{
return _blockSize;
}
set
{
if (value % Sizes.OneMiB != 0)
{
throw new ArgumentException("BlockSize must be a multiple of 1MB", "value");
}
_blockSize = value;
}
}
/// <summary>
/// Initiates the build process.
/// </summary>
/// <param name="baseName">The base name for the VHDX, for example 'foo' to create 'foo.vhdx'.</param>
/// <returns>A set of one or more logical files that constitute the virtual disk. The first file is
/// the 'primary' file that is normally attached to VMs.</returns>
public override DiskImageFileSpecification[] Build(string baseName)
{
if (string.IsNullOrEmpty(baseName))
{
throw new ArgumentException("Invalid base file name", "baseName");
}
if (Content == null)
{
throw new InvalidOperationException("No content stream specified");
}
DiskImageFileSpecification fileSpec = new DiskImageFileSpecification(baseName + ".vhdx", new DiskStreamBuilder(Content, DiskType, BlockSize));
return new DiskImageFileSpecification[] { fileSpec };
}
private class DiskStreamBuilder : StreamBuilder
{
private SparseStream _content;
private DiskType _diskType;
private long _blockSize;
public DiskStreamBuilder(SparseStream content, DiskType diskType, long blockSize)
{
_content = content;
_diskType = diskType;
_blockSize = blockSize;
}
internal override List<BuilderExtent> FixExtents(out long totalLength)
{
if (_diskType != DiskType.Dynamic)
{
throw new NotSupportedException("Creation of only dynamic disks currently implemented");
}
List<BuilderExtent> extents = new List<BuilderExtent>();
int logicalSectorSize = 512;
int physicalSectorSize = 4096;
long chunkRatio = (0x800000L * logicalSectorSize) / _blockSize;
long dataBlocksCount = Utilities.Ceil(_content.Length, _blockSize);
long sectorBitmapBlocksCount = Utilities.Ceil(dataBlocksCount, chunkRatio);
long totalBatEntriesDynamic = dataBlocksCount + ((dataBlocksCount - 1) / chunkRatio);
FileHeader fileHeader = new FileHeader() { Creator = ".NET DiscUtils" };
long fileEnd = Sizes.OneMiB;
VhdxHeader header1 = new VhdxHeader();
header1.SequenceNumber = 0;
header1.FileWriteGuid = Guid.NewGuid();
header1.DataWriteGuid = Guid.NewGuid();
header1.LogGuid = Guid.Empty;
header1.LogVersion = 0;
header1.Version = 1;
header1.LogLength = (uint)Sizes.OneMiB;
header1.LogOffset = (ulong)fileEnd;
header1.CalcChecksum();
fileEnd += header1.LogLength;
VhdxHeader header2 = new VhdxHeader(header1);
header2.SequenceNumber = 1;
header2.CalcChecksum();
RegionTable regionTable = new RegionTable();
RegionEntry metadataRegion = new RegionEntry();
metadataRegion.Guid = RegionEntry.MetadataRegionGuid;
metadataRegion.FileOffset = fileEnd;
metadataRegion.Length = (uint)Sizes.OneMiB;
metadataRegion.Flags = RegionFlags.Required;
regionTable.Regions.Add(metadataRegion.Guid, metadataRegion);
fileEnd += metadataRegion.Length;
RegionEntry batRegion = new RegionEntry();
batRegion.Guid = RegionEntry.BatGuid;
batRegion.FileOffset = fileEnd;
batRegion.Length = (uint)Utilities.RoundUp(totalBatEntriesDynamic * 8, Sizes.OneMiB);
batRegion.Flags = RegionFlags.Required;
regionTable.Regions.Add(batRegion.Guid, batRegion);
fileEnd += batRegion.Length;
extents.Add(ExtentForStruct(fileHeader, 0));
extents.Add(ExtentForStruct(header1, 64 * Sizes.OneKiB));
extents.Add(ExtentForStruct(header2, 128 * Sizes.OneKiB));
extents.Add(ExtentForStruct(regionTable, 192 * Sizes.OneKiB));
extents.Add(ExtentForStruct(regionTable, 256 * Sizes.OneKiB));
// Metadata
FileParameters fileParams = new FileParameters() { BlockSize = (uint)_blockSize, Flags = FileParametersFlags.None };
ParentLocator parentLocator = new ParentLocator();
byte[] metadataBuffer = new byte[metadataRegion.Length];
MemoryStream metadataStream = new MemoryStream(metadataBuffer);
Metadata.Initialize(metadataStream, fileParams, (ulong)_content.Length, (uint)logicalSectorSize, (uint)physicalSectorSize, null);
extents.Add(new BuilderBufferExtent(metadataRegion.FileOffset, metadataBuffer));
List<Range<long, long>> presentBlocks = new List<Range<long, long>>(StreamExtent.Blocks(_content.Extents, _blockSize));
// BAT
BlockAllocationTableBuilderExtent batExtent = new BlockAllocationTableBuilderExtent(batRegion.FileOffset, batRegion.Length, presentBlocks, fileEnd, _blockSize, chunkRatio);
extents.Add(batExtent);
// Stream contents
foreach (var range in presentBlocks)
{
long substreamStart = range.Offset * _blockSize;
long substreamCount = Math.Min(_content.Length - substreamStart, range.Count * _blockSize);
SubStream dataSubStream = new SubStream(_content, substreamStart, substreamCount);
BuilderSparseStreamExtent dataExtent = new BuilderSparseStreamExtent(fileEnd, dataSubStream);
extents.Add(dataExtent);
fileEnd += range.Count * _blockSize;
}
totalLength = fileEnd;
return extents;
}
private static BuilderExtent ExtentForStruct(IByteArraySerializable structure, long position)
{
byte[] buffer = new byte[structure.Size];
structure.WriteTo(buffer, 0);
return new BuilderBufferExtent(position, buffer);
}
}
private class BlockAllocationTableBuilderExtent : BuilderExtent
{
private List<Range<long, long>> _blocks;
private long _dataStart;
private long _blockSize;
private long _chunkRatio;
private byte[] _batData;
public BlockAllocationTableBuilderExtent(long start, long length, List<Range<long,long>> blocks, long dataStart, long blockSize, long chunkRatio)
: base(start, length)
{
_blocks = blocks;
_dataStart = dataStart;
_blockSize = blockSize;
_chunkRatio = chunkRatio;
}
public override void Dispose()
{
_batData = null;
}
internal override void PrepareForRead()
{
_batData = new byte[Length];
long fileOffset = _dataStart;
BatEntry entry = new BatEntry();
foreach(var range in _blocks)
{
for(long block = range.Offset; block < range.Offset + range.Count; ++block)
{
long chunk = block / _chunkRatio;
long chunkOffset = block % _chunkRatio;
long batIndex = (chunk * (_chunkRatio + 1)) + chunkOffset;
entry.FileOffsetMB = fileOffset / Sizes.OneMiB;
entry.PayloadBlockStatus = PayloadBlockStatus.FullyPresent;
entry.WriteTo(_batData, (int)(batIndex * 8));
fileOffset += _blockSize;
}
}
}
internal override int Read(long diskOffset, byte[] block, int offset, int count)
{
int start = (int)Math.Min(diskOffset - Start, _batData.Length);
int numRead = Math.Min(count, _batData.Length - start);
Array.Copy(_batData, start, block, offset, numRead);
return numRead;
}
internal override void DisposeReadState()
{
_batData = null;
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Diagnostics {
using System.Text;
using System.Threading;
using System;
using System.Security;
using System.Security.Permissions;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
// READ ME:
// Modifying the order or fields of this object may require other changes
// to the unmanaged definition of the StackFrameHelper class, in
// VM\DebugDebugger.h. The binder will catch some of these layout problems.
[Serializable]
internal class StackFrameHelper
{
[NonSerialized]
private Thread targetThread;
private int[] rgiOffset;
private int[] rgiILOffset;
// this field is here only for backwards compatibility of serialization format
private MethodBase[] rgMethodBase;
#pragma warning disable 414 // Field is not used from managed.
// dynamicMethods is an array of System.Resolver objects, used to keep
// DynamicMethodDescs alive for the lifetime of StackFrameHelper.
private Object dynamicMethods;
#pragma warning restore 414
[NonSerialized]
private IntPtr[] rgMethodHandle;
private String[] rgFilename;
private int[] rgiLineNumber;
private int[] rgiColumnNumber;
#if FEATURE_EXCEPTIONDISPATCHINFO
[OptionalField]
private bool[] rgiLastFrameFromForeignExceptionStackTrace;
#endif // FEATURE_EXCEPTIONDISPATCHINFO
private int iFrameCount;
private bool fNeedFileInfo;
public StackFrameHelper(bool fNeedFileLineColInfo, Thread target)
{
targetThread = target;
rgMethodBase = null;
rgMethodHandle = null;
rgiOffset = null;
rgiILOffset = null;
rgFilename = null;
rgiLineNumber = null;
rgiColumnNumber = null;
dynamicMethods = null;
#if FEATURE_EXCEPTIONDISPATCHINFO
rgiLastFrameFromForeignExceptionStackTrace = null;
#endif // FEATURE_EXCEPTIONDISPATCHINFO
// 0 means capture all frames. For StackTraces from an Exception, the EE always
// captures all frames. For other uses of StackTraces, we can abort stack walking after
// some limit if we want to by setting this to a non-zero value. In Whidbey this was
// hard-coded to 512, but some customers complained. There shouldn't be any need to limit
// this as memory/CPU is no longer allocated up front. If there is some reason to provide a
// limit in the future, then we should expose it in the managed API so applications can
// override it.
iFrameCount = 0;
fNeedFileInfo = fNeedFileLineColInfo;
}
[System.Security.SecuritySafeCritical]
public virtual MethodBase GetMethodBase(int i)
{
// There may be a better way to do this.
// we got RuntimeMethodHandles here and we need to go to MethodBase
// but we don't know whether the reflection info has been initialized
// or not. So we call GetMethods and GetConstructors on the type
// and then we fetch the proper MethodBase!!
IntPtr mh = rgMethodHandle[i];
if (mh.IsNull())
return null;
IRuntimeMethodInfo mhReal = RuntimeMethodHandle.GetTypicalMethodDefinition(new RuntimeMethodInfoStub(mh, this));
return RuntimeType.GetMethodBase(mhReal);
}
public virtual int GetOffset(int i) { return rgiOffset[i];}
public virtual int GetILOffset(int i) { return rgiILOffset[i];}
public virtual String GetFilename(int i) { return rgFilename[i];}
public virtual int GetLineNumber(int i) { return rgiLineNumber[i];}
public virtual int GetColumnNumber(int i) { return rgiColumnNumber[i];}
#if FEATURE_EXCEPTIONDISPATCHINFO
public virtual bool IsLastFrameFromForeignExceptionStackTrace(int i)
{
return (rgiLastFrameFromForeignExceptionStackTrace == null)?false:rgiLastFrameFromForeignExceptionStackTrace[i];
}
#endif // FEATURE_EXCEPTIONDISPATCHINFO
public virtual int GetNumberOfFrames() { return iFrameCount;}
public virtual void SetNumberOfFrames(int i) { iFrameCount = i;}
//
// serialization implementation
//
[OnSerializing]
[SecuritySafeCritical]
void OnSerializing(StreamingContext context)
{
// this is called in the process of serializing this object.
// For compatibility with Everett we need to assign the rgMethodBase field as that is the field
// that will be serialized
rgMethodBase = (rgMethodHandle == null) ? null : new MethodBase[rgMethodHandle.Length];
if (rgMethodHandle != null)
{
for (int i = 0; i < rgMethodHandle.Length; i++)
{
if (!rgMethodHandle[i].IsNull())
rgMethodBase[i] = RuntimeType.GetMethodBase(new RuntimeMethodInfoStub(rgMethodHandle[i], this));
}
}
}
[OnSerialized]
void OnSerialized(StreamingContext context)
{
// after we are done serializing null the rgMethodBase field
rgMethodBase = null;
}
[OnDeserialized]
[SecuritySafeCritical]
void OnDeserialized(StreamingContext context)
{
// after we are done deserializing we need to transform the rgMethodBase in rgMethodHandle
rgMethodHandle = (rgMethodBase == null) ? null : new IntPtr[rgMethodBase.Length];
if (rgMethodBase != null)
{
for (int i = 0; i < rgMethodBase.Length; i++)
{
if (rgMethodBase[i] != null)
rgMethodHandle[i] = rgMethodBase[i].MethodHandle.Value;
}
}
rgMethodBase = null;
}
}
// Class which represents a description of a stack trace
// There is no good reason for the methods of this class to be virtual.
// In order to ensure trusted code can trust the data it gets from a
// StackTrace, we use an InheritanceDemand to prevent partially-trusted
// subclasses.
#if !FEATURE_CORECLR
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
#endif
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class StackTrace
{
private StackFrame[] frames;
private int m_iNumOfFrames;
public const int METHODS_TO_SKIP = 0;
private int m_iMethodsToSkip;
// Constructs a stack trace from the current location.
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
public StackTrace()
{
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, false, null, null);
}
// Constructs a stack trace from the current location.
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(bool fNeedFileInfo)
{
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, null);
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(int skipFrames)
{
if (skipFrames < 0)
throw new ArgumentOutOfRangeException("skipFrames",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(skipFrames+METHODS_TO_SKIP, false, null, null);
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(int skipFrames, bool fNeedFileInfo)
{
if (skipFrames < 0)
throw new ArgumentOutOfRangeException("skipFrames",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(skipFrames+METHODS_TO_SKIP, fNeedFileInfo, null, null);
}
// Constructs a stack trace from the current location.
public StackTrace(Exception e)
{
if (e == null)
throw new ArgumentNullException("e");
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, false, null, e);
}
// Constructs a stack trace from the current location.
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(Exception e, bool fNeedFileInfo)
{
if (e == null)
throw new ArgumentNullException("e");
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, e);
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(Exception e, int skipFrames)
{
if (e == null)
throw new ArgumentNullException("e");
if (skipFrames < 0)
throw new ArgumentOutOfRangeException("skipFrames",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(skipFrames+METHODS_TO_SKIP, false, null, e);
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(Exception e, int skipFrames, bool fNeedFileInfo)
{
if (e == null)
throw new ArgumentNullException("e");
if (skipFrames < 0)
throw new ArgumentOutOfRangeException("skipFrames",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(skipFrames+METHODS_TO_SKIP, fNeedFileInfo, null, e);
}
// Constructs a "fake" stack trace, just containing a single frame.
// Does not have the overhead of a full stack trace.
//
public StackTrace(StackFrame frame)
{
frames = new StackFrame[1];
frames[0] = frame;
m_iMethodsToSkip = 0;
m_iNumOfFrames = 1;
}
// Constructs a stack trace for the given thread
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
[Obsolete("This constructor has been deprecated. Please use a constructor that does not require a Thread parameter. http://go.microsoft.com/fwlink/?linkid=14202")]
public StackTrace(Thread targetThread, bool needFileInfo)
{
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, needFileInfo, targetThread, null);
}
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void GetStackFramesInternal(StackFrameHelper sfh, int iSkip, Exception e);
internal static int CalculateFramesToSkip(StackFrameHelper StackF, int iNumFrames)
{
int iRetVal = 0;
String PackageName = "System.Diagnostics";
// Check if this method is part of the System.Diagnostics
// package. If so, increment counter keeping track of
// System.Diagnostics functions
for (int i = 0; i < iNumFrames; i++)
{
MethodBase mb = StackF.GetMethodBase(i);
if (mb != null)
{
Type t = mb.DeclaringType;
if (t == null)
break;
String ns = t.Namespace;
if (ns == null)
break;
if (String.Compare(ns, PackageName, StringComparison.Ordinal) != 0)
break;
}
iRetVal++;
}
return iRetVal;
}
// Retrieves an object with stack trace information encoded.
// It leaves out the first "iSkip" lines of the stacktrace.
//
private void CaptureStackTrace(int iSkip, bool fNeedFileInfo, Thread targetThread,
Exception e)
{
m_iMethodsToSkip += iSkip;
StackFrameHelper StackF = new StackFrameHelper(fNeedFileInfo, targetThread);
GetStackFramesInternal(StackF, 0, e);
m_iNumOfFrames = StackF.GetNumberOfFrames();
if (m_iMethodsToSkip > m_iNumOfFrames)
m_iMethodsToSkip = m_iNumOfFrames;
if (m_iNumOfFrames != 0)
{
frames = new StackFrame[m_iNumOfFrames];
for (int i = 0; i < m_iNumOfFrames; i++)
{
bool fDummy1 = true;
bool fDummy2 = true;
StackFrame sfTemp = new StackFrame(fDummy1, fDummy2);
sfTemp.SetMethodBase(StackF.GetMethodBase(i));
sfTemp.SetOffset(StackF.GetOffset(i));
sfTemp.SetILOffset(StackF.GetILOffset(i));
#if FEATURE_EXCEPTIONDISPATCHINFO
sfTemp.SetIsLastFrameFromForeignExceptionStackTrace(StackF.IsLastFrameFromForeignExceptionStackTrace(i));
#endif // FEATURE_EXCEPTIONDISPATCHINFO
if (fNeedFileInfo)
{
sfTemp.SetFileName(StackF.GetFilename (i));
sfTemp.SetLineNumber(StackF.GetLineNumber(i));
sfTemp.SetColumnNumber(StackF.GetColumnNumber(i));
}
frames[i] = sfTemp;
}
// CalculateFramesToSkip skips all frames in the System.Diagnostics namespace,
// but this is not desired if building a stack trace from an exception.
if (e == null)
m_iMethodsToSkip += CalculateFramesToSkip(StackF, m_iNumOfFrames);
m_iNumOfFrames -= m_iMethodsToSkip;
if (m_iNumOfFrames < 0)
{
m_iNumOfFrames = 0;
}
}
// In case this is the same object being re-used, set frames to null
else
frames = null;
}
// Property to get the number of frames in the stack trace
//
public virtual int FrameCount
{
get { return m_iNumOfFrames;}
}
// Returns a given stack frame. Stack frames are numbered starting at
// zero, which is the last stack frame pushed.
//
public virtual StackFrame GetFrame(int index)
{
if ((frames != null) && (index < m_iNumOfFrames) && (index >= 0))
return frames[index+m_iMethodsToSkip];
return null;
}
// Returns an array of all stack frames for this stacktrace.
// The array is ordered and sized such that GetFrames()[i] == GetFrame(i)
// The nth element of this array is the same as GetFrame(n).
// The length of the array is the same as FrameCount.
//
[ComVisible(false)]
public virtual StackFrame [] GetFrames()
{
if (frames == null || m_iNumOfFrames <= 0)
return null;
// We have to return a subset of the array. Unfortunately this
// means we have to allocate a new array and copy over.
StackFrame [] array = new StackFrame[m_iNumOfFrames];
Array.Copy(frames, m_iMethodsToSkip, array, 0, m_iNumOfFrames);
return array;
}
// Builds a readable representation of the stack trace
//
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
public override String ToString()
{
// Include a trailing newline for backwards compatibility
return ToString(TraceFormat.TrailingNewLine);
}
// TraceFormat is Used to specify options for how the
// string-representation of a StackTrace should be generated.
internal enum TraceFormat
{
Normal,
TrailingNewLine, // include a trailing new line character
NoResourceLookup // to prevent infinite resource recusion
}
// Builds a readable representation of the stack trace, specifying
// the format for backwards compatibility.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal String ToString(TraceFormat traceFormat)
{
bool displayFilenames = true; // we'll try, but demand may fail
String word_At = "at";
String inFileLineNum = "in {0}:line {1}";
if(traceFormat != TraceFormat.NoResourceLookup)
{
word_At = Environment.GetRuntimeResourceString("Word_At");
inFileLineNum = Environment.GetRuntimeResourceString("StackTrace_InFileLineNumber");
}
bool fFirstFrame = true;
StringBuilder sb = new StringBuilder(255);
for (int iFrameIndex = 0; iFrameIndex < m_iNumOfFrames; iFrameIndex++)
{
StackFrame sf = GetFrame(iFrameIndex);
MethodBase mb = sf.GetMethod();
if (mb != null)
{
// We want a newline at the end of every line except for the last
if (fFirstFrame)
fFirstFrame = false;
else
sb.Append(Environment.NewLine);
sb.AppendFormat(CultureInfo.InvariantCulture, " {0} ", word_At);
Type t = mb.DeclaringType;
// if there is a type (non global method) print it
if (t != null)
{
sb.Append(t.FullName.Replace('+', '.'));
sb.Append(".");
}
sb.Append(mb.Name);
// deal with the generic portion of the method
if (mb is MethodInfo && ((MethodInfo)mb).IsGenericMethod)
{
Type[] typars = ((MethodInfo)mb).GetGenericArguments();
sb.Append("[");
int k=0;
bool fFirstTyParam = true;
while (k < typars.Length)
{
if (fFirstTyParam == false)
sb.Append(",");
else
fFirstTyParam = false;
sb.Append(typars[k].Name);
k++;
}
sb.Append("]");
}
// arguments printing
sb.Append("(");
ParameterInfo[] pi = mb.GetParameters();
bool fFirstParam = true;
for (int j = 0; j < pi.Length; j++)
{
if (fFirstParam == false)
sb.Append(", ");
else
fFirstParam = false;
String typeName = "<UnknownType>";
if (pi[j].ParameterType != null)
typeName = pi[j].ParameterType.Name;
sb.Append(typeName + " " + pi[j].Name);
}
sb.Append(")");
// source location printing
if (displayFilenames && (sf.GetILOffset() != -1))
{
// If we don't have a PDB or PDB-reading is disabled for the module,
// then the file name will be null.
String fileName = null;
// Getting the filename from a StackFrame is a privileged operation - we won't want
// to disclose full path names to arbitrarily untrusted code. Rather than just omit
// this we could probably trim to just the filename so it's still mostly usefull.
try
{
fileName = sf.GetFileName();
}
#if FEATURE_CAS_POLICY
catch (NotSupportedException)
{
// Having a deprecated stack modifier on the callstack (such as Deny) will cause
// a NotSupportedException to be thrown. Since we don't know if the app can
// access the file names, we'll conservatively hide them.
displayFilenames = false;
}
#endif // FEATURE_CAS_POLICY
catch (SecurityException)
{
// If the demand for displaying filenames fails, then it won't
// succeed later in the loop. Avoid repeated exceptions by not trying again.
displayFilenames = false;
}
if (fileName != null)
{
// tack on " in c:\tmp\MyFile.cs:line 5"
sb.Append(' ');
sb.AppendFormat(CultureInfo.InvariantCulture, inFileLineNum, fileName, sf.GetFileLineNumber());
}
}
#if FEATURE_EXCEPTIONDISPATCHINFO
if (sf.GetIsLastFrameFromForeignExceptionStackTrace())
{
sb.Append(Environment.NewLine);
sb.Append(Environment.GetRuntimeResourceString("Exception_EndStackTraceFromPreviousThrow"));
}
#endif // FEATURE_EXCEPTIONDISPATCHINFO
}
}
if(traceFormat == TraceFormat.TrailingNewLine)
sb.Append(Environment.NewLine);
return sb.ToString();
}
// This helper is called from within the EE to construct a string representation
// of the current stack trace.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
private static String GetManagedStackTraceStringHelper(bool fNeedFileInfo)
{
// Note all the frames in System.Diagnostics will be skipped when capturing
// a normal stack trace (not from an exception) so we don't need to explicitly
// skip the GetManagedStackTraceStringHelper frame.
StackTrace st = new StackTrace(0, fNeedFileInfo);
return st.ToString();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic;
using System.Dynamic.Utils;
using System.Linq.Expressions;
using System.Threading;
using System.Reflection;
namespace System.Runtime.CompilerServices
{
/// <summary>
/// Class responsible for runtime binding of the dynamic operations on the dynamic call site.
/// </summary>
public abstract class CallSiteBinder
{
private static readonly LabelTarget s_updateLabel = Expression.Label("CallSiteBinder.UpdateLabel");
/// <summary>
/// The Level 2 cache - all rules produced for the same binder.
/// </summary>
internal Dictionary<Type, object> Cache;
/// <summary>
/// Initializes a new instance of the <see cref="CallSiteBinder"/> class.
/// </summary>
protected CallSiteBinder()
{
}
/// <summary>
/// Gets a label that can be used to cause the binding to be updated. It
/// indicates that the expression's binding is no longer valid.
/// This is typically used when the "version" of a dynamic object has
/// changed.
/// </summary>
public static LabelTarget UpdateLabel
{
get { return s_updateLabel; }
}
private sealed class LambdaSignature<T> where T : class
{
private static LambdaSignature<T> s_instance;
internal static LambdaSignature<T> Instance
{
get
{
if (s_instance == null)
{
s_instance = new LambdaSignature<T>();
}
return s_instance;
}
}
internal readonly ReadOnlyCollection<ParameterExpression> Parameters;
internal readonly LabelTarget ReturnLabel;
private LambdaSignature()
{
Type target = typeof(T);
if (!target.IsSubclassOf(typeof(MulticastDelegate)))
{
throw Error.TypeParameterIsNotDelegate(target);
}
MethodInfo invoke = target.GetMethod("Invoke");
ParameterInfo[] pis = invoke.GetParametersCached();
if (pis[0].ParameterType != typeof(CallSite))
{
throw Error.FirstArgumentMustBeCallSite();
}
var @params = new ParameterExpression[pis.Length - 1];
for (int i = 0; i < @params.Length; i++)
{
@params[i] = Expression.Parameter(pis[i + 1].ParameterType, "$arg" + i);
}
Parameters = new TrueReadOnlyCollection<ParameterExpression>(@params);
ReturnLabel = Expression.Label(invoke.GetReturnType());
}
}
/// <summary>
/// Performs the runtime binding of the dynamic operation on a set of arguments.
/// </summary>
/// <param name="args">An array of arguments to the dynamic operation.</param>
/// <param name="parameters">The array of <see cref="ParameterExpression"/> instances that represent the parameters of the call site in the binding process.</param>
/// <param name="returnLabel">A LabelTarget used to return the result of the dynamic binding.</param>
/// <returns>
/// An Expression that performs tests on the dynamic operation arguments, and
/// performs the dynamic operation if hte tests are valid. If the tests fail on
/// subsequent occurrences of the dynamic operation, Bind will be called again
/// to produce a new <see cref="Expression"/> for the new argument types.
/// </returns>
public abstract Expression Bind(object[] args, ReadOnlyCollection<ParameterExpression> parameters, LabelTarget returnLabel);
/// <summary>
/// Provides low-level runtime binding support. Classes can override this and provide a direct
/// delegate for the implementation of rule. This can enable saving rules to disk, having
/// specialized rules available at runtime, or providing a different caching policy.
/// </summary>
/// <typeparam name="T">The target type of the CallSite.</typeparam>
/// <param name="site">The CallSite the bind is being performed for.</param>
/// <param name="args">The arguments for the binder.</param>
/// <returns>A new delegate which replaces the CallSite Target.</returns>
public virtual T BindDelegate<T>(CallSite<T> site, object[] args) where T : class
{
return null;
}
internal T BindCore<T>(CallSite<T> site, object[] args) where T : class
{
//
// Try to find a precompiled delegate, and return it if found.
//
T result = BindDelegate(site, args);
if (result != null)
{
return result;
}
//
// Get the Expression for the binding
//
var signature = LambdaSignature<T>.Instance;
Expression binding = Bind(args, signature.Parameters, signature.ReturnLabel);
//
// Check the produced rule
//
if (binding == null)
{
throw Error.NoOrInvalidRuleProduced();
}
//
// finally produce the new rule if we need to
//
Expression<T> e = Stitch(binding, signature);
T newRule = e.Compile();
CacheTarget(newRule);
return newRule;
}
/// <summary>
/// Adds a target to the cache of known targets. The cached targets will
/// be scanned before calling BindDelegate to produce the new rule.
/// </summary>
/// <typeparam name="T">The type of target being added.</typeparam>
/// <param name="target">The target delegate to be added to the cache.</param>
protected void CacheTarget<T>(T target) where T : class
{
GetRuleCache<T>().AddRule(target);
}
private static Expression<T> Stitch<T>(Expression binding, LambdaSignature<T> signature) where T : class
{
Type siteType = typeof(CallSite<T>);
var body = new ReadOnlyCollectionBuilder<Expression>(3);
body.Add(binding);
var site = Expression.Parameter(typeof(CallSite), "$site");
var @params = signature.Parameters.AddFirst(site);
Expression updLabel = Expression.Label(CallSiteBinder.UpdateLabel);
#if DEBUG
// put the AST into the constant pool for debugging purposes
updLabel = Expression.Block(
Expression.Constant(binding, typeof(Expression)),
updLabel
);
#endif
body.Add(updLabel);
body.Add(
Expression.Label(
signature.ReturnLabel,
Expression.Condition(
Expression.Call(
typeof(CallSiteOps).GetMethod("SetNotMatched"),
@params.First()
),
Expression.Default(signature.ReturnLabel.Type),
Expression.Invoke(
Expression.Property(
Expression.Convert(site, siteType),
typeof(CallSite<T>).GetProperty("Update")
),
new TrueReadOnlyCollection<Expression>(@params)
)
)
)
);
return Expression.Lambda<T>(
Expression.Block(body),
"CallSite.Target",
true, // always compile the rules with tail call optimization
new TrueReadOnlyCollection<ParameterExpression>(@params)
);
}
internal RuleCache<T> GetRuleCache<T>() where T : class
{
// make sure we have cache.
if (Cache == null)
{
Interlocked.CompareExchange(ref Cache, new Dictionary<Type, object>(), null);
}
object ruleCache;
var cache = Cache;
lock (cache)
{
if (!cache.TryGetValue(typeof(T), out ruleCache))
{
cache[typeof(T)] = ruleCache = new RuleCache<T>();
}
}
RuleCache<T> result = ruleCache as RuleCache<T>;
Debug.Assert(result != null);
return result;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Pathfinding;
using Pathfinding.Util;
using Pathfinding.Serialization.JsonFx;
namespace Pathfinding.RVO {}
namespace Pathfinding {
/** A class for holding a user placed connection */
public class UserConnection {
public Vector3 p1;
public Vector3 p2;
public ConnectionType type;
//Connection
[JsonName("doOverCost")]
public bool doOverrideCost = false;
[JsonName("overCost")]
public int overrideCost = 0;
public bool oneWay = false;
public bool enable = true;
public float width = 0;
//Modify Node
[JsonName("doOverWalkable")]
public bool doOverrideWalkability = true;
[JsonName("doOverCost")]
public bool doOverridePenalty = false;
[JsonName("overPenalty")]
public uint overridePenalty = 0;
}
[System.Serializable]
/** Stores editor colors */
public class AstarColor {
public Color _NodeConnection;
public Color _UnwalkableNode;
public Color _BoundsHandles;
public Color _ConnectionLowLerp;
public Color _ConnectionHighLerp;
public Color _MeshEdgeColor;
public Color _MeshColor;
/** Holds user set area colors.
* Use GetAreaColor to get an area color */
public Color[] _AreaColors;
public static Color NodeConnection = new Color (1,1,1,0.9F);
public static Color UnwalkableNode = new Color (1,0,0,0.5F);
public static Color BoundsHandles = new Color (0.29F,0.454F,0.741F,0.9F);
public static Color ConnectionLowLerp = new Color (0,1,0,0.5F);
public static Color ConnectionHighLerp = new Color (1,0,0,0.5F);
public static Color MeshEdgeColor = new Color (0,0,0,0.5F);
public static Color MeshColor = new Color (0,0,0,0.5F);
/** Holds user set area colors.
* Use GetAreaColor to get an area color */
private static Color[] AreaColors;
/** Returns an color for an area, uses both user set ones and calculated.
* If the user has set a color for the area, it is used, but otherwise the color is calculated using Mathfx.IntToColor
* \see #AreaColors */
public static Color GetAreaColor (uint area) {
if (AreaColors == null || area >= AreaColors.Length) {
return AstarMath.IntToColor ((int)area,1F);
}
return AreaColors[(int)area];
}
/** Pushes all local variables out to static ones */
public void OnEnable () {
NodeConnection = _NodeConnection;
UnwalkableNode = _UnwalkableNode;
BoundsHandles = _BoundsHandles;
ConnectionLowLerp = _ConnectionLowLerp;
ConnectionHighLerp = _ConnectionHighLerp;
MeshEdgeColor = _MeshEdgeColor;
MeshColor = _MeshColor;
AreaColors = _AreaColors;
}
public AstarColor () {
_NodeConnection = new Color (1,1,1,0.9F);
_UnwalkableNode = new Color (1,0,0,0.5F);
_BoundsHandles = new Color (0.29F,0.454F,0.741F,0.9F);
_ConnectionLowLerp = new Color (0,1,0,0.5F);
_ConnectionHighLerp = new Color (1,0,0,0.5F);
_MeshEdgeColor = new Color (0,0,0,0.5F);
_MeshColor = new Color (0.125F, 0.686F, 0, 0.19F);
}
//new Color (0.909F,0.937F,0.243F,0.6F);
}
/** Returned by graph ray- or linecasts containing info about the hit. This will only be set up if something was hit. */
public struct GraphHitInfo {
/** Start of the line/ray */
public Vector3 origin;
/** Hit point */
public Vector3 point;
/** Node which contained the edge which was hit */
public GraphNode node;
/** Where the tangent starts. tangentOrigin and tangent together actually describes the edge which was hit */
public Vector3 tangentOrigin;
/** Tangent of the edge which was hit */
public Vector3 tangent;
public float distance {
get {
return (point-origin).magnitude;
}
}
public GraphHitInfo (Vector3 point) {
tangentOrigin = Vector3.zero;
origin = Vector3.zero;
this.point = point;
node = null;
tangent = Vector3.zero;
//this.distance = distance;
}
}
/** Nearest node constraint. Constrains which nodes will be returned by the GetNearest function */
public class NNConstraint {
/** Graphs treated as valid to search on.
* This is a bitmask meaning that bit 0 specifies whether or not the first graph in the graphs list should be able to be included in the search,
* bit 1 specifies whether or not the second graph should be included and so on.
* \code
* //Enables the first and third graphs to be included, but not the rest
* myNNConstraint.graphMask = (1 << 0) | (1 << 2);
* \endcode
* \note This does only affect which nodes are returned from a GetNearest call, if an invalid graph is linked to from a valid graph, it might be searched anyway.
*
* \see AstarPath.GetNearest */
public int graphMask = -1;
public bool constrainArea = false; /**< Only treat nodes in the area #area as suitable. Does not affect anything if #area is less than 0 (zero) */
public int area = -1; /**< Area ID to constrain to. Will not affect anything if less than 0 (zero) or if #constrainArea is false */
public bool constrainWalkability = true; /**< Only treat nodes with the walkable flag set to the same as #walkable as suitable */
public bool walkable = true; /**< What must the walkable flag on a node be for it to be suitable. Does not affect anything if #constrainWalkability if false */
public bool distanceXZ = false; /**< if available, do an XZ check instead of checking on all axes. The RecastGraph supports this */
public bool constrainTags = true; /**< Sets if tags should be constrained */
public int tags = -1; /**< Nodes which have any of these tags set are suitable. This is a bitmask, i.e bit 0 indicates that tag 0 is good, bit 3 indicates tag 3 is good etc. */
/** Constrain distance to node.
* Uses distance from AstarPath.maxNearestNodeDistance.
* If this is false, it will completely ignore the distance limit.
* \note This value is not used in this class, it is used by the AstarPath.GetNearest function.
*/
public bool constrainDistance = true;
/** Returns whether or not the graph conforms to this NNConstraint's rules.
*/
public virtual bool SuitableGraph (int graphIndex, NavGraph graph) {
return ((graphMask >> graphIndex) & 1) != 0;
}
/** Returns whether or not the node conforms to this NNConstraint's rules */
public virtual bool Suitable (GraphNode node) {
if (constrainWalkability && node.Walkable != walkable) return false;
if (constrainArea && area >= 0 && node.Area != area) return false;
#if ConfigureTagsAsMultiple
if (constrainTags && (tags & node.Tag) == 0) return false;
#else
if (constrainTags && (tags >> (int)node.Tag & 0x1) == 0) return false;
#endif
return true;
}
/** The default NNConstraint.
* Equivalent to new NNConstraint ().
* This NNConstraint has settings which works for most, it only finds walkable nodes
* and it constrains distance set by A* Inspector -> Settings -> Max Nearest Node Distance */
public static NNConstraint Default {
get {
return new NNConstraint ();
}
}
/** Returns a constraint which will not filter the results */
public static NNConstraint None {
get {
NNConstraint n = new NNConstraint ();
n.constrainWalkability = false;
n.constrainArea = false;
n.constrainTags = false;
n.constrainDistance = false;
n.graphMask = -1;
return n;
}
}
/** Default constructor. Equals to the property #Default */
public NNConstraint () {
}
}
/** A special NNConstraint which can use different logic for the start node and end node in a path.
* A PathNNConstraint can be assigned to the Path.nnConstraint field, the path will first search for the start node, then it will call #SetStart and proceed with searching for the end node (nodes in the case of a MultiTargetPath).\n
* The default PathNNConstraint will constrain the end point to lie inside the same area as the start point.
*/
public class PathNNConstraint : NNConstraint {
public static new PathNNConstraint Default {
get {
PathNNConstraint n = new PathNNConstraint ();
n.constrainArea = true;
return n;
}
}
/** Called after the start node has been found. This is used to get different search logic for the start and end nodes in a path */
public virtual void SetStart (GraphNode node) {
if (node != null) {
area = (int)node.Area;
} else {
constrainArea = false;
}
}
}
public struct NNInfo {
/** Closest node found.
* This node is not necessarily accepted by any NNConstraint passed.
* \see constrainedNode
*/
public GraphNode node;
/** Optional to be filled in.
* If the search will be able to find the constrained node without any extra effort it can fill it in. */
public GraphNode constrainedNode;
/** The position clamped to the closest point on the #node.
*/
public Vector3 clampedPosition;
/** Clamped position for the optional constrainedNode */
public Vector3 constClampedPosition;
public NNInfo (GraphNode node) {
this.node = node;
constrainedNode = null;
constClampedPosition = Vector3.zero;
if (node != null) {
clampedPosition = (Vector3)node.position;
} else {
clampedPosition = Vector3.zero;
}
}
/** Sets the constrained node */
public void SetConstrained (GraphNode constrainedNode, Vector3 clampedPosition) {
this.constrainedNode = constrainedNode;
constClampedPosition = clampedPosition;
}
/** Updates #clampedPosition and #constClampedPosition from node positions */
public void UpdateInfo () {
if (node != null) {
clampedPosition = (Vector3)node.position;
} else {
clampedPosition = Vector3.zero;
}
if (constrainedNode != null) {
constClampedPosition = (Vector3)constrainedNode.position;
} else {
constClampedPosition = Vector3.zero;
}
}
public static explicit operator Vector3 (NNInfo ob) {
return ob.clampedPosition;
}
public static explicit operator GraphNode (NNInfo ob) {
return ob.node;
}
public static explicit operator NNInfo (GraphNode ob) {
return new NNInfo (ob);
}
}
/** Progress info for e.g a progressbar.
* Used by the scan functions in the project
* \see AstarPath.ScanLoop
*/
public struct Progress {
public float progress;
public string description;
public Progress (float p, string d) {
progress = p;
description = d;
}
}
/** Graphs which can be updated during runtime */
public interface IUpdatableGraph {
/** Updates an area using the specified GraphUpdateObject.
*
* Notes to implementators.
* This function should (in order):
* -# Call o.WillUpdateNode on the GUO for every node it will update, it is important that this is called BEFORE any changes are made to the nodes.
* -# Update walkabilty using special settings such as the usePhysics flag used with the GridGraph.
* -# Call Apply on the GUO for every node which should be updated with the GUO.
* -# Update eventual connectivity info if appropriate (GridGraphs updates connectivity, but most other graphs don't since then the connectivity cannot be recovered later).
*/
void UpdateArea (GraphUpdateObject o);
void UpdateAreaInit (GraphUpdateObject o);
GraphUpdateThreading CanUpdateAsync (GraphUpdateObject o);
}
[System.Serializable]
/** Holds a tagmask.
* This is used to store which tags to change and what to set them to in a Pathfinding.GraphUpdateObject.
* All variables are bitmasks.\n
* I wanted to make it a struct, but due to technical limitations when working with Unity's GenericMenu, I couldn't.
* So be wary of this when passing it as it will be passed by reference, not by value as e.g LayerMask.
*/
public class TagMask {
public int tagsChange;
public int tagsSet;
public TagMask () {}
public TagMask (int change, int set) {
tagsChange = change;
tagsSet = set;
}
public void SetValues (System.Object boxedTagMask) {
TagMask o = (TagMask)boxedTagMask;
tagsChange = o.tagsChange;
tagsSet = o.tagsSet;
//Debug.Log ("Set tags to "+tagsChange +" "+tagsSet+" "+someVar);
}
public override string ToString () {
return ""+System.Convert.ToString (tagsChange,2)+"\n"+System.Convert.ToString (tagsSet,2);
}
}
/** Represents a collection of settings used to update nodes in a specific area of a graph.
* \see AstarPath.UpdateGraphs
*/
public class GraphUpdateObject {
/** The bounds to update nodes within */
public Bounds bounds;
/** Performance boost.
* This controlls if a flood fill will be carried out after this GUO has been applied.\n
* If you are sure that a GUO will not modify walkability or connections. You can set this to false.
* For example when only updating penalty values it can save processing power when setting this to false. Especially on large graphs.
* \note If you set this to false, even though it does change e.g walkability, it can lead to paths returning that they failed even though there is a path,
* or the try to search the whole graph for a path even though there is none, and will in the processes use wast amounts of processing power.
*
* If using the basic GraphUpdateObject (not a derived class), a quick way to check if it is going to need a flood fill is to check if #modifyWalkability is true or #updatePhysics is true.
*
*/
public bool requiresFloodFill = true;
/** Use physics checks to update nodes.
* When updating a grid graph and this is true, the nodes' position and walkability will be updated using physics checks
* with settings from "Collision Testing" and "Height Testing".
*
* When updating a PointGraph, setting this to true will make it re-evaluate all connections in the graph which passes through the #bounds.
* This has no effect when updating GridGraphs if #modifyWalkability is turned on.
*
* On RecastGraphs, having this enabled will trigger a complete recalculation of all tiles intersecting the bounds.
* This is quite slow (but powerful). If you only want to update e.g penalty on existing nodes, leave it disabled.
*/
public bool updatePhysics = true;
/** When #updatePhysics is true, GridGraphs will normally reset penalties, with this option you can override it.
* Good to use when you want to keep old penalties even when you update the graph.
*
* The images below shows two overlapping graph update objects, the right one happened to be applied before the left one. They both have updatePhysics = true and are
* set to increase the penalty of the nodes by some amount.
*
* The first image shows the result when resetPenaltyOnPhysics is false. Both penalties are added correctly.
* \shadowimage{resetPenaltyOnPhysics_False.png}
*
* This second image shows when resetPenaltyOnPhysics is set to true. The first GUO is applied correctly, but then the second one (the left one) is applied
* and during its updating, it resets the penalties first and then adds penalty to the nodes. The result is that the penalties from both GUOs are not added together.
* The green patch in at the border is there because physics recalculation (recalculation of the position of the node, checking for obstacles etc.) affects a slightly larger
* area than the original GUO bounds because of the Grid Graph -> Collision Testing -> Diameter setting (it is enlarged by that value). So some extra nodes have their penalties reset.
*
* \shadowimage{resetPenaltyOnPhysics_True.png}
*/
public bool resetPenaltyOnPhysics = true;
/** Update Erosion for GridGraphs.
* When enabled, erosion will be recalculated for grid graphs
* after the GUO has been applied.
*
* In the below image you can see the different effects you can get with the different values.\n
* The first image shows the graph when no GUO has been applied. The blue box is not identified as an obstacle by the graph, the reason
* there are unwalkable nodes around it is because there is a height difference (nodes are placed on top of the box) so erosion will be applied (an erosion value of 2 is used in this graph).
* The orange box is identified as an obstacle, so the area of unwalkable nodes around it is a bit larger since both erosion and collision has made
* nodes unwalkable.\n
* The GUO used simply sets walkability to true, i.e making all nodes walkable.
*
* \shadowimage{updateErosion.png}
*
* When updateErosion=True, the reason the blue box still has unwalkable nodes around it is because there is still a height difference
* so erosion will still be applied. The orange box on the other hand has no height difference and all nodes are set to walkable.\n
* \n
* When updateErosion=False, all nodes walkability are simply set to be walkable in this example.
*
* \see Pathfinding.GridGraph
*/
public bool updateErosion = true;
/** NNConstraint to use.
* The Pathfinding.NNConstraint.SuitableGraph function will be called on the NNConstraint to enable filtering of which graphs to update.\n
* \note As the Pathfinding.NNConstraint.SuitableGraph function is A* Pathfinding Project Pro only, this variable doesn't really affect anything in the free version.
*
*
* \astarpro */
public NNConstraint nnConstraint = NNConstraint.None;
/** Penalty to add to the nodes */
public int addPenalty = 0;
public bool modifyWalkability = false; /**< If true, all nodes \a walkable variables will be set to #setWalkability */
public bool setWalkability = false; /**< If #modifyWalkability is true, the nodes' \a walkable variable will be set to this */
#if ConfigureTagsAsMultiple
public TagMask tags;
#else
public bool modifyTag = false;
public int setTag = 0;
#endif
/** Track which nodes are changed and save backup data.
* Used internally to revert changes if needed.
*/
public bool trackChangedNodes = false;
private List<GraphNode> changedNodes;
private List<ulong> backupData;
private List<Int3> backupPositionData;
public GraphUpdateShape shape = null;
/** Should be called on every node which is updated with this GUO before it is updated.
* \param node The node to save fields for. If null, nothing will be done
* \see #trackChangedNodes
*/
public virtual void WillUpdateNode (GraphNode node) {
if (trackChangedNodes && node != null) {
if (changedNodes == null) { changedNodes = ListPool<GraphNode>.Claim(); backupData = ListPool<ulong>.Claim(); backupPositionData = ListPool<Int3>.Claim(); }
changedNodes.Add (node);
backupPositionData.Add (node.position);
backupData.Add ((ulong)node.Penalty<<32 | (ulong)node.Flags);
}
}
/** Reverts penalties and flags (which includes walkability) on every node which was updated using this GUO.
* Data for reversion is only saved if #trackChangedNodes is true */
public virtual void RevertFromBackup () {
if (trackChangedNodes) {
if (changedNodes == null) return;
throw new System.NotSupportedException ("Positions not supported yet");
/*for (int i=0;i<changedNodes.Count;i++) {
changedNodes[i].Penalty = (uint)(backupData[i]>>32);
changedNodes[i].Flags = (uint)(backupData[i] & 0xFFFFFFFF);
ListPool<GraphNode>.Release (changedNodes);
ListPool<ulong>.Release(backupData);
ListPool<Int3>.Release(backupPositionData);
//changedNodes[i].Position = backupPositionData[i];
}*/
} else {
throw new System.InvalidOperationException ("Changed nodes have not been tracked, cannot revert from backup");
}
}
/** Updates the specified node using this GUO's settings */
public virtual void Apply (GraphNode node) {
if (shape == null || shape.Contains (node)) {
//Update penalty and walkability
node.Penalty = (uint)(node.Penalty+addPenalty);
if (modifyWalkability) {
node.Walkable = setWalkability;
}
//Update tags
#if ConfigureTagsAsMultiple
node.Tag = (node.Tag & ~tags.tagsChange) | (tags.tagsSet & tags.tagsChange);
#else
if (modifyTag) node.Tag = (uint)setTag;
#endif
}
}
public GraphUpdateObject () {
}
/** Creates a new GUO with the specified bounds */
public GraphUpdateObject (Bounds b) {
bounds = b;
}
}
public interface IRaycastableGraph {
bool Linecast (Vector3 start, Vector3 end);
bool Linecast (Vector3 start, Vector3 end, GraphNode hint);
bool Linecast (Vector3 start, Vector3 end, GraphNode hint, out GraphHitInfo hit);
bool Linecast (Vector3 start, Vector3 end, GraphNode hint, out GraphHitInfo hit, List<GraphNode> trace);
}
/** Holds info about one pathfinding thread.
* Mainly used to send information about how the thread should execute when starting it
*/
public struct PathThreadInfo {
public int threadIndex;
public AstarPath astar;
public PathHandler runData;
private System.Object _lock;
public System.Object Lock { get {return _lock; }}
public PathThreadInfo (int index, AstarPath astar, PathHandler runData) {
this.threadIndex = index;
this.astar = astar;
this.runData = runData;
_lock = new object();
}
}
/** Integer Rectangle.
* Works almost like UnityEngine.Rect but with integer coordinates
*/
public struct IntRect {
public int xmin, ymin, xmax, ymax;
public IntRect (int xmin, int ymin, int xmax, int ymax) {
this.xmin = xmin;
this.xmax = xmax;
this.ymin = ymin;
this.ymax = ymax;
}
public bool Contains (int x, int y) {
return !(x < xmin || y < ymin || x > xmax || y > ymax);
}
public int Width {
get {
return xmax-xmin+1;
}
}
public int Height {
get {
return ymax-ymin+1;
}
}
/** Returns if this rectangle is valid.
* An invalid rect could have e.g xmin > xmax.
* Rectamgles with a zero area area invalid.
*/
public bool IsValid () {
return xmin <= xmax && ymin <= ymax;
}
public static bool operator == (IntRect a, IntRect b) {
return a.xmin == b.xmin && a.xmax == b.xmax && a.ymin == b.ymin && a.ymax == b.ymax;
}
public static bool operator != (IntRect a, IntRect b) {
return a.xmin != b.xmin || a.xmax != b.xmax || a.ymin != b.ymin || a.ymax != b.ymax;
}
public override bool Equals (System.Object _b) {
IntRect b = (IntRect)_b;
return xmin == b.xmin && xmax == b.xmax && ymin == b.ymin && ymax == b.ymax;
}
public override int GetHashCode () {
return xmin*131071 ^ xmax*3571 ^ ymin*3109 ^ ymax*7;
}
/** Returns the intersection rect between the two rects.
* The intersection rect is the area which is inside both rects.
* If the rects do not have an intersection, an invalid rect is returned.
* \see IsValid
*/
public static IntRect Intersection (IntRect a, IntRect b) {
IntRect r = new IntRect(
System.Math.Max(a.xmin,b.xmin),
System.Math.Max(a.ymin,b.ymin),
System.Math.Min(a.xmax,b.xmax),
System.Math.Min(a.ymax,b.ymax)
);
return r;
}
/** Returns if the two rectangles intersect each other
*/
public static bool Intersects (IntRect a, IntRect b) {
return !(a.xmin > b.xmax || a.ymin > b.ymax || a.xmax < b.xmin || a.ymax < b.ymin);
}
/** Returns a new rect which contains both input rects.
* This rectangle may contain areas outside both input rects as well in some cases.
*/
public static IntRect Union (IntRect a, IntRect b) {
IntRect r = new IntRect(
System.Math.Min(a.xmin,b.xmin),
System.Math.Min(a.ymin,b.ymin),
System.Math.Max(a.xmax,b.xmax),
System.Math.Max(a.ymax,b.ymax)
);
return r;
}
/** Returns a new IntRect which is expanded to contain the point */
public IntRect ExpandToContain (int x, int y) {
IntRect r = new IntRect(
System.Math.Min(xmin,x),
System.Math.Min(ymin,y),
System.Math.Max(xmax,x),
System.Math.Max(ymax,y)
);
return r;
}
/** Returns a new rect which is expanded by \a range in all directions.
* \param range How far to expand. Negative values are permitted.
*/
public IntRect Expand (int range) {
return new IntRect(xmin-range,
ymin-range,
xmax+range,
ymax+range
);
}
/** Matrices for rotation.
* Each group of 4 elements is a 2x2 matrix.
* The XZ position is multiplied by this.
* So
* \code
* //A rotation by 90 degrees clockwise, second matrix in the array
* (5,2) * ((0, 1), (-1, 0)) = (2,-5)
* \endcode
*/
private static readonly int[] Rotations = {
1, 0, //Identity matrix
0, 1,
0, 1,
-1, 0,
-1, 0,
0,-1,
0,-1,
1, 0
};
/** Returns a new rect rotated around the origin 90*r degrees.
* Ensures that a valid rect is returned.
*/
public IntRect Rotate ( int r ) {
int mx1 = Rotations[r*4+0];
int mx2 = Rotations[r*4+1];
int my1 = Rotations[r*4+2];
int my2 = Rotations[r*4+3];
int p1x = mx1*xmin + mx2*ymin;
int p1y = my1*xmin + my2*ymin;
int p2x = mx1*xmax + mx2*ymax;
int p2y = my1*xmax + my2*ymax;
return new IntRect (
System.Math.Min ( p1x, p2x ),
System.Math.Min ( p1y, p2y ),
System.Math.Max ( p1x, p2x ),
System.Math.Max ( p1y, p2y )
);
}
/** Returns a new rect which is offset by the specified amount.
*/
public IntRect Offset ( Int2 offset ) {
return new IntRect ( xmin+offset.x, ymin + offset.y, xmax + offset.x, ymax + offset.y );
}
/** Returns a new rect which is offset by the specified amount.
*/
public IntRect Offset ( int x, int y ) {
return new IntRect ( xmin+x, ymin + y, xmax + x, ymax + y );
}
public override string ToString () {
return "[x: "+xmin+"..."+xmax+", y: " + ymin +"..."+ymax+"]";
}
/** Draws some debug lines representing the rect */
public void DebugDraw (Matrix4x4 matrix, Color col) {
Vector3 p1 = matrix.MultiplyPoint3x4 (new Vector3(xmin,0,ymin));
Vector3 p2 = matrix.MultiplyPoint3x4 (new Vector3(xmin,0,ymax));
Vector3 p3 = matrix.MultiplyPoint3x4 (new Vector3(xmax,0,ymax));
Vector3 p4 = matrix.MultiplyPoint3x4 (new Vector3(xmax,0,ymin));
Debug.DrawLine (p1,p2,col);
Debug.DrawLine (p2,p3,col);
Debug.DrawLine (p3,p4,col);
Debug.DrawLine (p4,p1,col);
}
}
}
#region Delegates
/* Delegate with on Path object as parameter.
* This is used for callbacks when a path has finished calculation.\n
* Example function:
* \code
public void Start () {
//Assumes a Seeker component is attached to the GameObject
Seeker seeker = GetComponent<Seeker>();
//seeker.pathCallback is a OnPathDelegate, we add the function OnPathComplete to it so it will be called whenever a path has finished calculating on that seeker
seeker.pathCallback += OnPathComplete;
}
public void OnPathComplete (Path p) {
Debug.Log ("This is called when a path is completed on the seeker attached to this GameObject");
}\endcode
*/
public delegate void OnPathDelegate (Path p);
public delegate Vector3[] GetNextTargetDelegate (Path p, Vector3 currentPosition);
public delegate void NodeDelegate (GraphNode node);
public delegate void OnGraphDelegate (NavGraph graph);
public delegate void OnScanDelegate (AstarPath script);
public delegate void OnVoidDelegate ();
public delegate void OnScanStatus (Progress progress);
#endregion
#region Enums
public enum GraphUpdateThreading {
UnityThread,
SeparateThread,
SeparateAndUnityInit
}
/** How path results are logged by the system */
public enum PathLog {
None, /**< Does not log anything */
Normal, /**< Logs basic info about the paths */
Heavy, /**< Includes additional info */
InGame, /**< Same as heavy, but displays the info in-game using GUI */
OnlyErrors /**< Same as normal, but logs only paths which returned an error */
}
/** Heuristic to use. Heuristic is the estimated cost from the current node to the target */
public enum Heuristic {
Manhattan,
DiagonalManhattan,
Euclidean,
None
}
/** What data to draw the graph debugging with */
public enum GraphDebugMode {
Areas,
G,
H,
F,
Penalty,
Connections,
Tags
}
/** Type of connection for a user placed link */
public enum ConnectionType {
Connection,
ModifyNode
}
public enum ThreadCount {
AutomaticLowLoad = -1,
AutomaticHighLoad = -2,
None = 0,
One = 1,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight
}
public enum PathState {
Created = 0,
PathQueue = 1,
Processing = 2,
ReturnQueue = 3,
Returned = 4
}
public enum PathCompleteState {
NotCalculated = 0,
Error = 1,
Complete = 2,
Partial = 3
}
#endregion
| |
using System;
using FluentAssertions.Primitives;
#if !OLD_MSTEST
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
namespace FluentAssertions.Specs
{
[TestClass]
public class NullableNumericAssertionSpecs
{
[TestMethod]
public void Should_succeed_when_asserting_nullable_numeric_value_with_value_to_have_a_value()
{
int? nullableInteger = 1;
nullableInteger.Should().HaveValue();
}
[TestMethod]
public void Should_fail_when_asserting_nullable_numeric_value_without_a_value_to_have_a_value()
{
int? nullableInteger = null;
Action act = () => nullableInteger.Should().HaveValue();
act.ShouldThrow<AssertFailedException>();
}
[TestMethod]
public void Should_fail_with_descriptive_message_when_asserting_nullable_numeric_value_without_a_value_to_have_a_value()
{
int? nullableInteger = null;
var assertions = nullableInteger.Should();
assertions.Invoking(x => x.HaveValue("because we want to test the failure {0}", "message"))
.ShouldThrow<AssertFailedException>()
.WithMessage("Expected a value because we want to test the failure message.");
}
[TestMethod]
public void Should_succeed_when_asserting_nullable_numeric_value_without_a_value_to_be_null()
{
int? nullableInteger = null;
nullableInteger.Should().NotHaveValue();
}
[TestMethod]
public void Should_fail_when_asserting_nullable_numeric_value_with_a_value_to_be_null()
{
int? nullableInteger = 1;
Action act = () => nullableInteger.Should().NotHaveValue();
act.ShouldThrow<AssertFailedException>();
}
[TestMethod]
public void When_nullable_value_with_unexpected_value_is_found_it_should_throw_with_message()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
int? nullableInteger = 1;
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action action = () => nullableInteger.Should().NotHaveValue("it was {0} expected", "not");
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
action
.ShouldThrow<AssertFailedException>()
.WithMessage("Did not expect a value because it was not expected, but found 1.");
}
[TestMethod]
public void Should_succeed_when_asserting_nullable_numeric_value_equals_an_equal_value()
{
int? nullableIntegerA = 1;
int? nullableIntegerB = 1;
nullableIntegerA.Should().Be(nullableIntegerB);
}
[TestMethod]
public void Should_succeed_when_asserting_nullable_numeric_null_value_equals_null()
{
int? nullableIntegerA = null;
int? nullableIntegerB = null;
nullableIntegerA.Should().Be(nullableIntegerB);
}
[TestMethod]
public void Should_fail_when_asserting_nullable_numeric_value_equals_a_different_value()
{
int? nullableIntegerA = 1;
int? nullableIntegerB = 2;
Action act = () => nullableIntegerA.Should().Be(nullableIntegerB);
act.ShouldThrow<AssertFailedException>();
}
[TestMethod]
public void Should_fail_with_descriptive_message_when_asserting_nullable_numeric_value_equals_a_different_value()
{
int? nullableIntegerA = 1;
int? nullableIntegerB = 2;
var assertions = nullableIntegerA.Should();
assertions.Invoking(x => x.Be(nullableIntegerB, "because we want to test the failure {0}", "message"))
.ShouldThrow<AssertFailedException>()
.WithMessage("Expected*2 because we want to test the failure message, but found 1.");
}
#region Be Approximately
[TestMethod]
public void When_nullable_double_is_indeed_approximating_a_value_it_should_not_throw()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
double? value = 3.1415927;
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => value.Should().BeApproximately(3.14, 0.1);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_nullable_double_has_no_value_it_should_throw()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
double? value = null;
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => value.Should().BeApproximately(3.14, 0.001);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>().WithMessage(string.Format(
"Expected value to approximate {0} +/- {1}, but it was <null>.", 3.14, 0.001));
}
[TestMethod]
public void When_nullable_double_is_not_approximating_a_value_it_should_throw()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
double? value = 3.1415927F;
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => value.Should().BeApproximately(1.0, 0.1);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act
.ShouldThrow<AssertFailedException>()
.WithMessage(string.Format(
"Expected value*to approximate {0} +/- {1}, but it differed by*", 1, 0.1));
}
[TestMethod]
public void When_nullable_float_is_indeed_approximating_a_value_it_should_not_throw()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
float? value = 3.1415927F;
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => value.Should().BeApproximately(3.14F, 0.1F);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_nullable_float_is_not_approximating_a_value_it_should_throw()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
float? value = 3.1415927F;
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => value.Should().BeApproximately(1.0F, 0.1F);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act
.ShouldThrow<AssertFailedException>()
.WithMessage(string.Format(
"Expected value*to approximate {0} +/- {1}, but it differed by*", 1, 0.1));
}
[TestMethod]
public void When_nullable_decimal_is_indeed_approximating_a_value_it_should_not_throw()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
decimal? value = 3.1415927m;
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => value.Should().BeApproximately(3.14m, 0.1m);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_nullable_decimal_has_no_value_it_should_throw()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
decimal? value = null;
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => value.Should().BeApproximately(3.14m, 0.001m);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>().WithMessage(string.Format(
"Expected value to approximate {0} +/- {1}, but it was <null>.", 3.14m, 0.001m));
}
[TestMethod]
public void When_nullable_decimal_is_not_approximating_a_value_it_should_throw()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
decimal? value = 3.1415927m;
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => value.Should().BeApproximately(1.0m, 0.1m);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act
.ShouldThrow<AssertFailedException>()
.WithMessage(string.Format(
"Expected value*to approximate {0} +/- {1}, but it differed by*", 1.0m, 0.1m));
}
#endregion
[TestMethod]
public void Should_support_chaining_constraints_with_and()
{
int? nullableInteger = 1;
nullableInteger.Should()
.HaveValue()
.And
.BePositive();
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Classification.ApplicationBinding", Namespace="urn:iControl")]
public partial class ClassificationApplication : iControlInterface {
public ClassificationApplication() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Classification/Application",
RequestNamespace="urn:iControl:Classification/Application", ResponseNamespace="urn:iControl:Classification/Application")]
public void create(
string [] applications,
string [] categories,
long [] ids
) {
this.Invoke("create", new object [] {
applications,
categories,
ids});
}
public System.IAsyncResult Begincreate(string [] applications,string [] categories,long [] ids, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
applications,
categories,
ids}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_applications
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Classification/Application",
RequestNamespace="urn:iControl:Classification/Application", ResponseNamespace="urn:iControl:Classification/Application")]
public void delete_all_applications(
) {
this.Invoke("delete_all_applications", new object [0]);
}
public System.IAsyncResult Begindelete_all_applications(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_applications", new object[0], callback, asyncState);
}
public void Enddelete_all_applications(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_application
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Classification/Application",
RequestNamespace="urn:iControl:Classification/Application", ResponseNamespace="urn:iControl:Classification/Application")]
public void delete_application(
string [] applications
) {
this.Invoke("delete_application", new object [] {
applications});
}
public System.IAsyncResult Begindelete_application(string [] applications, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_application", new object[] {
applications}, callback, asyncState);
}
public void Enddelete_application(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_category
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Classification/Application",
RequestNamespace="urn:iControl:Classification/Application", ResponseNamespace="urn:iControl:Classification/Application")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_category(
string [] applications
) {
object [] results = this.Invoke("get_category", new object [] {
applications});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_category(string [] applications, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_category", new object[] {
applications}, callback, asyncState);
}
public string [] Endget_category(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Classification/Application",
RequestNamespace="urn:iControl:Classification/Application", ResponseNamespace="urn:iControl:Classification/Application")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] applications
) {
object [] results = this.Invoke("get_description", new object [] {
applications});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] applications, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
applications}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Classification/Application",
RequestNamespace="urn:iControl:Classification/Application", ResponseNamespace="urn:iControl:Classification/Application")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_enabled_state(
string [] applications
) {
object [] results = this.Invoke("get_enabled_state", new object [] {
applications});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_enabled_state(string [] applications, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_enabled_state", new object[] {
applications}, callback, asyncState);
}
public CommonEnabledState [] Endget_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Classification/Application",
RequestNamespace="urn:iControl:Classification/Application", ResponseNamespace="urn:iControl:Classification/Application")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_id(
string [] applications
) {
object [] results = this.Invoke("get_id", new object [] {
applications});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_id(string [] applications, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_id", new object[] {
applications}, callback, asyncState);
}
public long [] Endget_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Classification/Application",
RequestNamespace="urn:iControl:Classification/Application", ResponseNamespace="urn:iControl:Classification/Application")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Classification/Application",
RequestNamespace="urn:iControl:Classification/Application", ResponseNamespace="urn:iControl:Classification/Application")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// set_category
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Classification/Application",
RequestNamespace="urn:iControl:Classification/Application", ResponseNamespace="urn:iControl:Classification/Application")]
public void set_category(
string [] applications,
string [] categories
) {
this.Invoke("set_category", new object [] {
applications,
categories});
}
public System.IAsyncResult Beginset_category(string [] applications,string [] categories, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_category", new object[] {
applications,
categories}, callback, asyncState);
}
public void Endset_category(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Classification/Application",
RequestNamespace="urn:iControl:Classification/Application", ResponseNamespace="urn:iControl:Classification/Application")]
public void set_description(
string [] applications,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
applications,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] applications,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
applications,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Classification/Application",
RequestNamespace="urn:iControl:Classification/Application", ResponseNamespace="urn:iControl:Classification/Application")]
public void set_enabled_state(
string [] applications,
CommonEnabledState [] states
) {
this.Invoke("set_enabled_state", new object [] {
applications,
states});
}
public System.IAsyncResult Beginset_enabled_state(string [] applications,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_enabled_state", new object[] {
applications,
states}, callback, asyncState);
}
public void Endset_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using AllReady.Areas.Admin.Features.Events;
using AllReady.Areas.Admin.Features.Campaigns;
using AllReady.Areas.Admin.Features.Requests;
using AllReady.Extensions;
using AllReady.Models;
using AllReady.Security;
using AllReady.Services;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using AllReady.Areas.Admin.ViewModels.Event;
using AllReady.Areas.Admin.ViewModels.Validators;
using AllReady.Areas.Admin.ViewModels.Request;
using AllReady.Constants;
using DeleteQuery = AllReady.Areas.Admin.Features.Events.DeleteQuery;
namespace AllReady.Areas.Admin.Controllers
{
[Area(AreaNames.Admin)]
[Authorize]
public class EventController : Controller
{
public Func<DateTime> DateTimeTodayDate = () => DateTime.Today.Date;
private readonly IImageService _imageService;
private readonly IMediator _mediator;
private readonly IValidateEventEditViewModels _eventEditViewModelValidator;
private readonly IUserAuthorizationService _userAuthorizationService;
public EventController(IImageService imageService, IMediator mediator, IValidateEventEditViewModels eventEditViewModelValidator, IUserAuthorizationService userAuthorizationService)
{
_imageService = imageService;
_mediator = mediator;
_eventEditViewModelValidator = eventEditViewModelValidator;
_userAuthorizationService = userAuthorizationService;
}
[HttpGet]
[Route("Admin/Event/ListAll")]
public async Task<IActionResult> Lister()
{
var viewModel = await _mediator.SendAsync(new EventListerQuery { UserId = _userAuthorizationService.AssociatedUserId });
return View(viewModel);
}
[HttpGet]
[Route("Admin/Event/Details/{id}")]
public async Task<IActionResult> Details(int id)
{
var viewModel = await _mediator.SendAsync(new EventDetailQuery { EventId = id });
if (viewModel == null)
{
return NotFound();
}
var authorizableEvent = await _mediator.SendAsync(new AuthorizableEventQuery(viewModel.Id, viewModel.CampaignId, viewModel.OrganizationId));
if (!await authorizableEvent.UserCanView())
{
return new ForbidResult();
}
// todo - check if the user can duplicate (e.g. create events) against the campaign as well - depends on having an authorizable campaign class first
if (await authorizableEvent.UserCanDelete())
{
viewModel.ShowDeleteButton = true;
}
if (await authorizableEvent.UserCanManageChildObjects())
{
viewModel.ShowCreateChildObjectButtons = true;
}
return View(viewModel);
}
[HttpGet]
[Route("Admin/Event/Create/{campaignId}")]
public async Task<IActionResult> Create(int campaignId)
{
var campaign = await _mediator.SendAsync(new CampaignSummaryQuery { CampaignId = campaignId });
var authorizableCampaign = await _mediator.SendAsync(new AuthorizableCampaignQuery(campaign.Id, campaign.OrganizationId));
if (!await authorizableCampaign.UserCanManageChildObjects())
{
return new ForbidResult();
}
var viewModel = new EventEditViewModel
{
CampaignId = campaign.Id,
CampaignName = campaign.Name,
TimeZoneId = campaign.TimeZoneId,
OrganizationId = campaign.OrganizationId,
OrganizationName = campaign.OrganizationName,
StartDateTime = DateTimeTodayDate(),
EndDateTime = DateTimeTodayDate()
};
return View("Edit", viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
[Route("Admin/Event/Create/{campaignId}")]
public async Task<IActionResult> Create(int campaignId, EventEditViewModel eventEditViewModel, IFormFile fileUpload)
{
var campaign = await _mediator.SendAsync(new CampaignSummaryQuery { CampaignId = campaignId });
var authorizableCampaign = await _mediator.SendAsync(new AuthorizableCampaignQuery(campaign.Id, campaign.OrganizationId));
if (!await authorizableCampaign.UserCanManageChildObjects())
{
return new ForbidResult();
}
var errors = _eventEditViewModelValidator.Validate(eventEditViewModel, campaign);
errors.ToList().ForEach(e => ModelState.AddModelError(e.Key, e.Value));
ModelState.Remove("NewItinerary");
//TryValidateModel is called explictly because of MVC 6 behavior that supresses model state validation during model binding when binding to an IFormFile.
//See #619.
if (ModelState.IsValid && TryValidateModel(eventEditViewModel))
{
if (fileUpload != null)
{
if (!fileUpload.IsAcceptableImageContentType())
{
ModelState.AddModelError(nameof(eventEditViewModel.ImageUrl), "You must upload a valid image file for the logo (.jpg, .png, .gif)");
return View("Edit", eventEditViewModel);
}
}
eventEditViewModel.OrganizationId = campaign.OrganizationId;
var id = await _mediator.SendAsync(new EditEventCommand { Event = eventEditViewModel });
if (fileUpload != null)
{
// resave now that event has the ImageUrl
eventEditViewModel.Id = id;
eventEditViewModel.ImageUrl = await _imageService.UploadEventImageAsync(campaign.OrganizationId, id, fileUpload);
await _mediator.SendAsync(new EditEventCommand { Event = eventEditViewModel });
}
return RedirectToAction(nameof(Details), new { area = AreaNames.Admin, id = id });
}
return View("Edit", eventEditViewModel);
}
[HttpGet]
public async Task<IActionResult> Edit(int id)
{
var campaignEvent = await _mediator.SendAsync(new EventEditQuery { EventId = id });
if (campaignEvent == null)
{
return NotFound();
}
var authorizableEvent = await _mediator.SendAsync(new AuthorizableEventQuery(id, campaignEvent.CampaignId, campaignEvent.OrganizationId));
if (!await authorizableEvent.UserCanEdit())
{
return new ForbidResult();
}
return View(campaignEvent);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(EventEditViewModel eventEditViewModel, IFormFile fileUpload)
{
if (eventEditViewModel == null)
{
return BadRequest();
}
var authorizableEvent = await _mediator.SendAsync(new AuthorizableEventQuery(eventEditViewModel.Id));
if (!await authorizableEvent.UserCanEdit())
{
return new ForbidResult();
}
var campaign = await _mediator.SendAsync(new CampaignSummaryQuery { CampaignId = eventEditViewModel.CampaignId });
var errors = _eventEditViewModelValidator.Validate(eventEditViewModel, campaign);
errors.ForEach(e => ModelState.AddModelError(e.Key, e.Value));
if (ModelState.IsValid)
{
if (fileUpload != null)
{
if (fileUpload.IsAcceptableImageContentType())
{
var existingImageUrl = eventEditViewModel.ImageUrl;
var newImageUrl = await _imageService.UploadEventImageAsync(campaign.OrganizationId, eventEditViewModel.Id, fileUpload);
if (!string.IsNullOrEmpty(newImageUrl))
{
eventEditViewModel.ImageUrl = newImageUrl;
if (existingImageUrl != null && existingImageUrl != newImageUrl)
{
await _imageService.DeleteImageAsync(existingImageUrl);
}
}
}
else
{
ModelState.AddModelError(nameof(eventEditViewModel.ImageUrl), "You must upload a valid image file for the logo (.jpg, .png, .gif)");
return View(eventEditViewModel);
}
}
var id = await _mediator.SendAsync(new EditEventCommand { Event = eventEditViewModel });
return RedirectToAction(nameof(Details), new { area = AreaNames.Admin, id = id });
}
return View(eventEditViewModel);
}
// GET: Event/Duplicate/5
[HttpGet]
public async Task<IActionResult> Duplicate(int id)
{
var viewModel = await _mediator.SendAsync(new DuplicateEventQuery { EventId = id });
if (viewModel == null)
{
return NotFound();
}
if (!User.IsOrganizationAdmin(viewModel.OrganizationId))
{
return Unauthorized();
}
viewModel.UserIsOrgAdmin = true;
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Duplicate(DuplicateEventViewModel viewModel)
{
if (viewModel == null)
{
return BadRequest();
}
if (!viewModel.UserIsOrgAdmin)
{
return Unauthorized();
}
var existingEvent = await _mediator.SendAsync(new EventEditQuery { EventId = viewModel.Id });
var campaign = await _mediator.SendAsync(new CampaignSummaryQuery { CampaignId = existingEvent.CampaignId });
var newEvent = BuildNewEventDetailsModel(existingEvent, viewModel);
//mgmccarthy: why are we validating here? We don't need to validate as the event that is being duplicated was already validated before it was created
var errors = _eventEditViewModelValidator.Validate(newEvent, campaign);
errors.ForEach(e => ModelState.AddModelError(e.Key, e.Value));
if (ModelState.IsValid)
{
var id = await _mediator.SendAsync(new DuplicateEventCommand { DuplicateEventModel = viewModel });
return RedirectToAction(nameof(Details), new { area = AreaNames.Admin, id });
}
return View(viewModel);
}
[HttpGet]
public async Task<IActionResult> Delete(int id)
{
var viewModel = await _mediator.SendAsync(new DeleteQuery { EventId = id });
if (viewModel == null)
{
return NotFound();
}
var authorizableEvent = await _mediator.SendAsync(new AuthorizableEventQuery(viewModel.Id, viewModel.CampaignId, viewModel.OrganizationId));
if (!await authorizableEvent.UserCanDelete())
{
return new ForbidResult();
}
ViewData["Title"] = $"Delete event {viewModel.Name}";
return View(viewModel);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var authorizableEvent = await _mediator.SendAsync(new AuthorizableEventQuery(id));
if (!await authorizableEvent.UserCanDelete())
{
return new ForbidResult();
}
await _mediator.SendAsync(new DeleteEventCommand { EventId = id });
return RedirectToAction(nameof(CampaignController.Details), "Campaign", new { area = AreaNames.Admin, id = authorizableEvent.CampaignId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<JsonResult> DeleteEventImage(int eventId)
{
var campaignEvent = await _mediator.SendAsync(new EventEditQuery { EventId = eventId });
if (campaignEvent == null)
{
return Json(new { status = "NotFound" });
}
var authorizableEvent = await _mediator.SendAsync(new AuthorizableEventQuery(campaignEvent.Id, campaignEvent.CampaignId, campaignEvent.OrganizationId));
if (!await authorizableEvent.UserCanEdit())
{
return Json(new { status = "Unauthorized" });
}
if (campaignEvent.ImageUrl != null)
{
await _imageService.DeleteImageAsync(campaignEvent.ImageUrl);
campaignEvent.ImageUrl = null;
await _mediator.SendAsync(new EditEventCommand { Event = campaignEvent });
return Json(new { status = "Success" });
}
return Json(new { status = "NothingToDelete" });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> MessageAllVolunteers(MessageEventVolunteersViewModel viewModel)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var authorizableEvent = await _mediator.SendAsync(new AuthorizableEventQuery(viewModel.EventId));
if (!await authorizableEvent.UserCanEdit())
{
return new ForbidResult();
}
await _mediator.SendAsync(new MessageEventVolunteersCommand { ViewModel = viewModel });
return Ok();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> PostEventFile(int id, IFormFile file)
{
var organizationId = await _mediator.SendAsync(new OrganizationIdByEventIdQuery { EventId = id });
var imageUrl = await _imageService.UploadEventImageAsync(organizationId, id, file);
await _mediator.SendAsync(new UpdateEventImageUrl { EventId = id, ImageUrl = imageUrl });
return RedirectToRoute(new { controller = "Event", area = AreaNames.Admin, action = nameof(Edit), id });
}
[HttpGet]
[Route("Admin/Event/[action]/{id}/{status?}")]
public async Task<IActionResult> Requests(int id, string status)
{
var authorizableEvent = await _mediator.SendAsync(new AuthorizableEventQuery(id));
if (!await authorizableEvent.UserCanView())
{
return new ForbidResult();
}
var criteria = new RequestSearchCriteria { EventId = id };
var pageTitle = "All Requests";
var currentPage = "All";
if (!string.IsNullOrEmpty(status))
{
RequestStatus requestStatus;
if (Enum.TryParse(status, out requestStatus))
{
criteria.Status = requestStatus;
pageTitle = $"{status} Requests";
currentPage = status;
}
else
{
return RedirectToAction(nameof(Requests), new { id });
}
}
var viewModel = await _mediator.SendAsync(new EventRequestsQuery { EventId = id });
viewModel.PageTitle = pageTitle;
viewModel.CurrentPage = currentPage;
viewModel.Requests = await _mediator.SendAsync(new RequestListItemsQuery { Criteria = criteria });
return View(viewModel);
}
private static EventEditViewModel BuildNewEventDetailsModel(EventEditViewModel existingEvent, DuplicateEventViewModel newEventDetails)
{
existingEvent.Id = 0;
existingEvent.Name = newEventDetails.Name;
existingEvent.Description = newEventDetails.Description;
existingEvent.StartDateTime = newEventDetails.StartDateTime;
existingEvent.EndDateTime = newEventDetails.EndDateTime;
return existingEvent;
}
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.ServiceModel.Activities.Description
{
using System.Collections;
using System.Collections.Generic;
using System.Activities;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.Runtime.DurableInstancing;
using System.ServiceModel.Activities.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
using System.Transactions;
class WorkflowOperationBehavior : IOperationBehavior
{
Bookmark bookmark;
public WorkflowOperationBehavior(Bookmark bookmark, bool canCreateInstance)
: this(canCreateInstance)
{
Fx.Assert(bookmark != null, "bookmark must not be null!");
this.bookmark = bookmark;
}
protected WorkflowOperationBehavior(bool canCreateInstance)
{
this.CanCreateInstance = canCreateInstance;
}
internal bool CanCreateInstance
{
get;
set;
}
public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
{
}
public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
{
if (operationDescription == null)
{
throw FxTrace.Exception.ArgumentNull("operationDescription");
}
if (dispatchOperation == null)
{
throw FxTrace.Exception.ArgumentNull("dispatchOperation");
}
if (dispatchOperation.Parent == null
|| dispatchOperation.Parent.ChannelDispatcher == null
|| dispatchOperation.Parent.ChannelDispatcher.Host == null
|| dispatchOperation.Parent.ChannelDispatcher.Host.Description == null
|| dispatchOperation.Parent.ChannelDispatcher.Host.Description.Behaviors == null)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.DispatchOperationInInvalidState));
}
ServiceHostBase serviceHost = dispatchOperation.Parent.ChannelDispatcher.Host;
if (!(serviceHost is WorkflowServiceHost))
{
throw FxTrace.Exception.AsError(
new InvalidOperationException(SR.WorkflowBehaviorWithNonWorkflowHost(typeof(WorkflowOperationBehavior).Name)));
}
CorrelationKeyCalculator correlationKeyCalculator = null;
ServiceEndpoint endpoint = null;
foreach (ServiceEndpoint endpointToMatch in serviceHost.Description.Endpoints)
{
if (endpointToMatch.Id == dispatchOperation.Parent.EndpointDispatcher.Id)
{
endpoint = endpointToMatch;
break;
}
}
if (endpoint != null)
{
CorrelationQueryBehavior queryBehavior = endpoint.Behaviors.Find<CorrelationQueryBehavior>();
if (queryBehavior != null)
{
correlationKeyCalculator = queryBehavior.GetKeyCalculator();
}
}
dispatchOperation.Invoker = new WorkflowOperationInvoker(operationDescription,
endpoint, correlationKeyCalculator, this, serviceHost, dispatchOperation.Invoker);
}
public void Validate(OperationDescription operationDescription)
{
}
protected internal virtual Bookmark OnResolveBookmark(WorkflowOperationContext context, out BookmarkScope bookmarkScope, out object value)
{
Fx.Assert(this.bookmark != null, "bookmark must not be null!");
CorrelationMessageProperty correlationMessageProperty;
if (CorrelationMessageProperty.TryGet(context.OperationContext.IncomingMessageProperties, out correlationMessageProperty))
{
bookmarkScope = new BookmarkScope(correlationMessageProperty.CorrelationKey.Value);
}
else
{
bookmarkScope = BookmarkScope.Default;
}
value = context;
return this.bookmark;
}
//Invoker for workflowbased application endpoint operation
class WorkflowOperationInvoker : ControlOperationInvoker, IInstanceTransaction
{
bool performanceCountersEnabled;
bool propagateActivity;
bool isHostingEndpoint;
IOperationInvoker innerInvoker;
WorkflowOperationBehavior behavior;
bool isFirstReceiveOfTransactedReceiveScopeTree;
public WorkflowOperationInvoker(OperationDescription operationDescription, ServiceEndpoint endpoint,
CorrelationKeyCalculator keyCalculator, WorkflowOperationBehavior behavior, ServiceHostBase host, IOperationInvoker innerInvoker)
: base(operationDescription, endpoint, keyCalculator, host)
{
Fx.Assert(operationDescription != null, "Null OperationDescription");
Fx.Assert(behavior != null, "Null WorkflowOperationBehavior");
this.StaticBookmarkName = behavior.bookmark == null ? null : behavior.bookmark.Name;
this.behavior = behavior;
this.CanCreateInstance = behavior.CanCreateInstance;
this.performanceCountersEnabled = PerformanceCounters.PerformanceCountersEnabled;
this.propagateActivity = TraceUtility.ShouldPropagateActivity;
this.isHostingEndpoint = endpoint is WorkflowHostingEndpoint;
this.innerInvoker = innerInvoker;
this.isFirstReceiveOfTransactedReceiveScopeTree = operationDescription.IsFirstReceiveOfTransactedReceiveScopeTree;
}
public override object[] AllocateInputs()
{
if (this.isHostingEndpoint)
{
return this.innerInvoker.AllocateInputs();
}
// InternalReceiveMessage & InternalSendMessage is always MessageIn - MessageOut.
// Therefore we always need an array of size 1.
// DispatchOperationRuntime saves the request into this array in this case ( i.e., when DeserializeRequest is false)
return new object[1];
}
protected override IAsyncResult OnBeginServiceOperation(WorkflowServiceInstance workflowInstance, OperationContext operationContext,
object[] inputs, Transaction currentTransaction, IInvokeReceivedNotification notification, TimeSpan timeout, AsyncCallback callback, object state)
{
Fx.Assert(workflowInstance != null, "caller must verify");
Fx.Assert(inputs != null, "caller must verify");
return WorkflowOperationContext.BeginProcessRequest(workflowInstance, operationContext, this.OperationName, inputs,
this.performanceCountersEnabled, this.propagateActivity, currentTransaction, notification, this.behavior, this.endpoint, timeout, callback, state);
}
protected override object OnEndServiceOperation(WorkflowServiceInstance durableInstance, out object[] outputs, IAsyncResult result)
{
// InternalSendMessage always redirects the replyMessage into the returnValue
object returnValue = WorkflowOperationContext.EndProcessRequest(result, out outputs);
//we will just assert that outputs is always an empty array
Fx.Assert(this.isHostingEndpoint || outputs == null || outputs.Length == 0, "Workflow returned a non-empty out-arg");
return returnValue;
}
public Transaction GetTransactionForInstance(OperationContext operationContext)
{
Transaction tx = null;
// We are only going to go ask the PPD for the transaction if we are NOT the first
// Receive in a TransactedReceiveScope;
if (!this.isFirstReceiveOfTransactedReceiveScopeTree)
{
// We need to get the InstanceKey.
InstanceKey instanceKey;
ICollection<InstanceKey> additionalKeys;
this.GetInstanceKeys(operationContext, out instanceKey, out additionalKeys);
Fx.Assert((instanceKey != null) && (instanceKey.IsValid), "InstanceKey is null or invalid in GetInstanceTransaction");
tx = this.InstanceManager.PersistenceProviderDirectory.GetTransactionForInstance(instanceKey);
}
return tx;
}
}
}
}
| |
using System;
using System.Text;
using NUnit.Framework;
using XmlRpcLight.Attributes;
using XmlRpcLight.DataTypes;
using XmlRpcLight.Enums;
namespace XmlRpcLight.Test {
[TestFixture]
public class OptionalSerializeTest {
private struct ChildStruct {
public readonly int x;
public ChildStruct(int num) {
x = num;
}
}
private struct Struct0 {
public XmlRpcInt xi;
public XmlRpcBoolean xb;
public XmlRpcDouble xd;
public XmlRpcDateTime xdt;
#if !FX1_0
public int? nxi;
public bool? nxb;
public double? nxd;
public DateTime? nxdt;
public ChildStruct? nxstr;
#endif
}
private struct Struct1 {
public int mi;
public string ms;
public bool mb;
public double md;
public DateTime mdt;
public byte[] mb64;
public int[] ma;
public XmlRpcInt xi;
public XmlRpcBoolean xb;
public XmlRpcDouble xd;
public XmlRpcDateTime xdt;
public XmlRpcStruct xstr;
#if !FX1_0
public int? nxi;
public bool? nxb;
public double? nxd;
public DateTime? nxdt;
public ChildStruct? nxstr;
#endif
}
[XmlRpcMissingMapping(MappingAction.Error)]
private struct Struct2 {
public int mi;
public string ms;
public bool mb;
public double md;
public DateTime mdt;
public byte[] mb64;
public int[] ma;
public XmlRpcInt xi;
public XmlRpcBoolean xb;
public XmlRpcDouble xd;
public XmlRpcDateTime xdt;
public XmlRpcStruct xstr;
#if !FX1_0
public int? nxi;
public bool? nxb;
public double? nxd;
public DateTime? nxdt;
public ChildStruct? nxstr;
#endif
}
private struct Struct3 {
[XmlRpcMissingMapping(MappingAction.Error)] public int mi;
[XmlRpcMissingMapping(MappingAction.Error)] public string ms;
[XmlRpcMissingMapping(MappingAction.Error)] public bool mb;
[XmlRpcMissingMapping(MappingAction.Error)] public double md;
[XmlRpcMissingMapping(MappingAction.Error)] public DateTime mdt;
[XmlRpcMissingMapping(MappingAction.Error)] public byte[] mb64;
[XmlRpcMissingMapping(MappingAction.Error)] public int[] ma;
[XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcInt xi;
[XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcBoolean xb;
[XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcDouble xd;
[XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcDateTime xdt;
[XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcStruct xstr;
#if !FX1_0
[XmlRpcMissingMapping(MappingAction.Error)] public int? nxi;
[XmlRpcMissingMapping(MappingAction.Error)] public bool? nxb;
[XmlRpcMissingMapping(MappingAction.Error)] public double? nxd;
[XmlRpcMissingMapping(MappingAction.Error)] public DateTime? nxdt;
[XmlRpcMissingMapping(MappingAction.Error)] public ChildStruct? nxstr;
#endif
}
[XmlRpcMissingMapping(MappingAction.Ignore)]
private struct Struct4 {
[XmlRpcMissingMapping(MappingAction.Error)] public int mi;
[XmlRpcMissingMapping(MappingAction.Error)] public string ms;
[XmlRpcMissingMapping(MappingAction.Error)] public bool mb;
[XmlRpcMissingMapping(MappingAction.Error)] public double md;
[XmlRpcMissingMapping(MappingAction.Error)] public DateTime mdt;
[XmlRpcMissingMapping(MappingAction.Error)] public byte[] mb64;
[XmlRpcMissingMapping(MappingAction.Error)] public int[] ma;
[XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcInt xi;
[XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcBoolean xb;
[XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcDouble xd;
[XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcDateTime xdt;
[XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcStruct xstr;
#if !FX1_0
[XmlRpcMissingMapping(MappingAction.Error)] public int? nxi;
[XmlRpcMissingMapping(MappingAction.Error)] public bool? nxb;
[XmlRpcMissingMapping(MappingAction.Error)] public double? nxd;
[XmlRpcMissingMapping(MappingAction.Error)] public DateTime? nxdt;
[XmlRpcMissingMapping(MappingAction.Error)] public ChildStruct? nxstr;
#endif
}
[XmlRpcMissingMapping(MappingAction.Ignore)]
private struct Struct5 {
public int mi;
public string ms;
public bool mb;
public double md;
public DateTime mdt;
public byte[] mb64;
public int[] ma;
public XmlRpcInt xi;
public XmlRpcBoolean xb;
public XmlRpcDouble xd;
public XmlRpcDateTime xdt;
public XmlRpcStruct xstr;
#if !FX1_0
public int? nxi;
public bool? nxb;
public double? nxd;
public DateTime? nxdt;
public ChildStruct? nxstr;
#endif
}
private struct Struct6 {
[XmlRpcMissingMapping(MappingAction.Ignore)] public int mi;
[XmlRpcMissingMapping(MappingAction.Ignore)] public string ms;
[XmlRpcMissingMapping(MappingAction.Ignore)] public bool mb;
[XmlRpcMissingMapping(MappingAction.Ignore)] public double md;
[XmlRpcMissingMapping(MappingAction.Ignore)] public DateTime mdt;
[XmlRpcMissingMapping(MappingAction.Ignore)] public byte[] mb64;
[XmlRpcMissingMapping(MappingAction.Ignore)] public int[] ma;
[XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcInt xi;
[XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcBoolean xb;
[XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcDouble xd;
[XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcDateTime xdt;
[XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcStruct xstr;
#if !FX1_0
[XmlRpcMissingMapping(MappingAction.Ignore)] public int? nxi;
[XmlRpcMissingMapping(MappingAction.Ignore)] public bool? nxb;
[XmlRpcMissingMapping(MappingAction.Ignore)] public double? nxd;
[XmlRpcMissingMapping(MappingAction.Ignore)] public DateTime? nxdt;
[XmlRpcMissingMapping(MappingAction.Ignore)] public ChildStruct? nxstr;
#endif
}
[XmlRpcMissingMapping(MappingAction.Error)]
private struct Struct7 {
[XmlRpcMissingMapping(MappingAction.Ignore)] public int mi;
[XmlRpcMissingMapping(MappingAction.Ignore)] public string ms;
[XmlRpcMissingMapping(MappingAction.Ignore)] public bool mb;
[XmlRpcMissingMapping(MappingAction.Ignore)] public double md;
[XmlRpcMissingMapping(MappingAction.Ignore)] public DateTime mdt;
[XmlRpcMissingMapping(MappingAction.Ignore)] public byte[] mb64;
[XmlRpcMissingMapping(MappingAction.Ignore)] public int[] ma;
[XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcInt xi;
[XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcBoolean xb;
[XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcDouble xd;
[XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcDateTime xdt;
[XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcStruct xstr;
#if !FX1_0
[XmlRpcMissingMapping(MappingAction.Ignore)] public int? nxi;
[XmlRpcMissingMapping(MappingAction.Ignore)] public bool? nxb;
[XmlRpcMissingMapping(MappingAction.Ignore)] public double? nxd;
[XmlRpcMissingMapping(MappingAction.Ignore)] public DateTime? nxdt;
[XmlRpcMissingMapping(MappingAction.Ignore)] public ChildStruct? nxstr;
#endif
}
//-------------------------------------------------------------------------/
[Test]
public void Struct0_AllExist() {
var strout = new Struct0();
strout.xi = 1234;
strout.xb = true;
strout.xd = 1234.567;
strout.xdt = new DateTime(2006, 8, 9, 10, 11, 13);
#if !FX1_0
strout.nxi = 5678;
strout.nxb = true;
strout.nxd = 2345.678;
strout.nxdt = new DateTime(2007, 9, 10, 11, 12, 14);
strout.nxstr = new ChildStruct(567);
#endif
var xdoc = Utils.Serialize("Struct0_AllExist",
strout, Encoding.UTF8, MappingAction.Error);
Type parsedType, parsedArrayType;
var obj = Utils.Parse(xdoc, typeof (Struct0), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.IsInstanceOfType(typeof (Struct0), obj);
var strin = (Struct0) obj;
Assert.AreEqual(strout.xi, strin.xi);
Assert.AreEqual(strout.xb, strin.xb);
Assert.AreEqual(strout.xd, strin.xd);
Assert.AreEqual(strout.xdt, strin.xdt);
#if !FX1_0
Assert.AreEqual(strout.nxi, strin.nxi);
Assert.AreEqual(strout.nxb, strin.nxb);
Assert.AreEqual(strout.nxd, strin.nxd);
Assert.AreEqual(strout.nxdt, strin.nxdt);
Assert.AreEqual(((ChildStruct) strout.nxstr).x, ((ChildStruct) strin.nxstr).x);
#endif
}
//-------------------------------------------------------------------------/
[Test]
[ExpectedException(typeof (XmlRpcMappingSerializeException))]
public void Struct1_AllMissing_ErrorDefault() {
var xdoc = Utils.Serialize("Struct1_AllMissing_ErrorDefault",
new Struct1(),
Encoding.UTF8, MappingAction.Error);
}
[Test]
public void Struct1_AllMissing_IgnoreDefault() {
var xdoc = Utils.Serialize("Struct1_AllMissing_IgnoreDefault",
new Struct1(),
Encoding.UTF8, MappingAction.Ignore);
}
//-------------------------------------------------------------------------/
[Test]
[ExpectedException(typeof (XmlRpcMappingSerializeException))]
public void Struct2_AllMissing_ErrorError() {
var xdoc = Utils.Serialize(
"Struct2_AllMissing_ErrorError",
new Struct2(),
Encoding.UTF8, MappingAction.Error);
}
[Test]
[ExpectedException(typeof (XmlRpcMappingSerializeException))]
public void Struct2_AllMissing_IgnoreError() {
var xdoc = Utils.Serialize(
"Struct2_AllMissing_IgnoreError",
new Struct2(),
Encoding.UTF8, MappingAction.Ignore);
}
//-------------------------------------------------------------------------/
[Test]
[ExpectedException(typeof (XmlRpcMappingSerializeException))]
public void Struct3_AllMissing_ErrorDefaultError() {
var xdoc = Utils.Serialize(
"Struct3_AllMissing_ErrorDefaultError",
new Struct3(),
Encoding.UTF8, MappingAction.Error);
}
[Test]
[ExpectedException(typeof (XmlRpcMappingSerializeException))]
public void Struct3_AllMissing_IgnoreDefaultError() {
var xdoc = Utils.Serialize(
"Struct3_AllMissing_IgnoreDefaultError",
new Struct3(),
Encoding.UTF8, MappingAction.Ignore);
}
//-------------------------------------------------------------------------/
[Test]
[ExpectedException(typeof (XmlRpcMappingSerializeException))]
public void Struct4_AllMissing_ErrorIgnoreError() {
var xdoc = Utils.Serialize(
"Struct4_AllMissing_ErrorIgnoreError",
new Struct4(),
Encoding.UTF8, MappingAction.Error);
}
[Test]
[ExpectedException(typeof (XmlRpcMappingSerializeException))]
public void Struct4_AllMissing_IgnoreIgnoreError() {
var xdoc = Utils.Serialize(
"Struct4_AllMissing_IgnoreIgnoreError",
new Struct4(),
Encoding.UTF8, MappingAction.Ignore);
}
//-------------------------------------------------------------------------/
[Test]
public void Struct5_AllMissing_ErrorIgnoreDefault() {
var xdoc = Utils.Serialize(
"Struct5_AllMissing_ErrorIgnoreDefault",
new Struct5(),
Encoding.UTF8, MappingAction.Error);
}
[Test]
public void Struct5_AllMissing_IgnoreIgnoreDefault() {
var xdoc = Utils.Serialize(
"Struct5_AllMissing_IgnoreIgnoreDefault",
new Struct5(),
Encoding.UTF8, MappingAction.Ignore);
}
//-------------------------------------------------------------------------/
[Test]
public void Struct6_AllMissing_ErrorDefaultIgnore() {
var xdoc = Utils.Serialize(
"Struct6_AllMissing_ErrorDefaultIgnore",
new Struct6(),
Encoding.UTF8, MappingAction.Error);
}
[Test]
public void Struct6_AllMissing_IgnoreDefaultIgnore() {
var xdoc = Utils.Serialize(
"Struct6_AllMissing_IgnoreDefaultIgnore",
new Struct6(),
Encoding.UTF8, MappingAction.Ignore);
}
//-------------------------------------------------------------------------/
[Test]
public void Struct7_AllMissing_ErrorErrorIgnore() {
var xdoc = Utils.Serialize(
"Struct7_AllMissing_ErrorErrorIgnore",
new Struct7(),
Encoding.UTF8, MappingAction.Error);
}
[Test]
public void Struct7_AllMissing_IgnoreErrorIgnore() {
var xdoc = Utils.Serialize(
"Struct7_AllMissing_IgnoreErrorIgnore",
new Struct7(),
Encoding.UTF8, MappingAction.Ignore);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.InteropServices;
namespace System.Numerics.Matrices
{
/// <summary>
/// Represents a matrix of double precision floating-point values defined by its number of columns and rows
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct Matrix2x2: IEquatable<Matrix2x2>, IMatrix
{
public const int ColumnCount = 2;
public const int RowCount = 2;
static Matrix2x2()
{
Zero = new Matrix2x2(0);
Identity = new Matrix2x2(1, 0,
0, 1);
}
/// <summary>
/// Constant Matrix2x2 with value intialized to the identity of a 2 x 2 matrix
/// </summary>
public static readonly Matrix2x2 Identity;
/// <summary>
/// Gets the smallest value used to determine equality
/// </summary>
public double Epsilon { get { return MatrixHelper.Epsilon; } }
/// <summary>
/// Constant Matrix2x2 with all values initialized to zero
/// </summary>
public static readonly Matrix2x2 Zero;
/// <summary>
/// Initializes a Matrix2x2 with all of it values specifically set
/// </summary>
/// <param name="m11">The column 1, row 1 value</param>
/// <param name="m21">The column 2, row 1 value</param>
/// <param name="m12">The column 1, row 2 value</param>
/// <param name="m22">The column 2, row 2 value</param>
public Matrix2x2(double m11, double m21,
double m12, double m22)
{
M11 = m11; M21 = m21;
M12 = m12; M22 = m22;
}
/// <summary>
/// Initialized a Matrix2x2 with all values set to the same value
/// </summary>
/// <param name="value">The value to set all values to</param>
public Matrix2x2(double value)
{
M11 = M21 =
M12 = M22 = value;
}
public double M11;
public double M21;
public double M12;
public double M22;
public unsafe double this[int col, int row]
{
get
{
if (col < 0 || col >= ColumnCount)
throw new ArgumentOutOfRangeException("col", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", ColumnCount, col));
if (row < 0 || row >= RowCount)
throw new ArgumentOutOfRangeException("row", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", RowCount, row));
fixed (Matrix2x2* p = &this)
{
double* d = (double*)p;
return d[row * ColumnCount + col];
}
}
set
{
if (col < 0 || col >= ColumnCount)
throw new ArgumentOutOfRangeException("col", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", ColumnCount, col));
if (row < 0 || row >= RowCount)
throw new ArgumentOutOfRangeException("row", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", RowCount, row));
fixed (Matrix2x2* p = &this)
{
double* d = (double*)p;
d[row * ColumnCount + col] = value;
}
}
}
/// <summary>
/// Gets the number of columns in the matrix
/// </summary>
public int Columns { get { return ColumnCount; } }
/// <summary>
/// Get the number of rows in the matrix
/// </summary>
public int Rows { get { return RowCount; } }
/// <summary>
/// Gets a new Matrix1x2 containing the values of column 1
/// </summary>
public Matrix1x2 Column1 { get { return new Matrix1x2(M11, M12); } }
/// <summary>
/// Gets a new Matrix1x2 containing the values of column 2
/// </summary>
public Matrix1x2 Column2 { get { return new Matrix1x2(M21, M22); } }
/// <summary>
/// Gets a new Matrix2x1 containing the values of column 1
/// </summary>
public Matrix2x1 Row1 { get { return new Matrix2x1(M11, M21); } }
/// <summary>
/// Gets a new Matrix2x1 containing the values of column 2
/// </summary>
public Matrix2x1 Row2 { get { return new Matrix2x1(M12, M22); } }
public override bool Equals(object obj)
{
if (obj is Matrix2x2)
return this == (Matrix2x2)obj;
return false;
}
public bool Equals(Matrix2x2 other)
{
return this == other;
}
public unsafe override int GetHashCode()
{
fixed (Matrix2x2* p = &this)
{
int* x = (int*)p;
unchecked
{
return 0xFFE1
+ 7 * ((((x[00] ^ x[01]) << 0) + ((x[02] ^ x[03]) << 1)) << 0)
+ 7 * ((((x[02] ^ x[03]) << 0) + ((x[04] ^ x[05]) << 1)) << 1);
}
}
}
public override string ToString()
{
return "Matrix2x2: "
+ String.Format("{{|{0:00}|{1:00}|}}", M11, M21)
+ String.Format("{{|{0:00}|{1:00}|}}", M12, M22);
}
/// <summary>
/// Creates and returns a transposed matrix
/// </summary>
/// <returns>Matrix with transposed values</returns>
public Matrix2x2 Transpose()
{
return new Matrix2x2(M11, M12,
M21, M22);
}
public static bool operator ==(Matrix2x2 matrix1, Matrix2x2 matrix2)
{
return MatrixHelper.AreEqual(matrix1.M11, matrix2.M11)
&& MatrixHelper.AreEqual(matrix1.M21, matrix2.M21)
&& MatrixHelper.AreEqual(matrix1.M12, matrix2.M12)
&& MatrixHelper.AreEqual(matrix1.M22, matrix2.M22);
}
public static bool operator !=(Matrix2x2 matrix1, Matrix2x2 matrix2)
{
return MatrixHelper.NotEqual(matrix1.M11, matrix2.M11)
|| MatrixHelper.NotEqual(matrix1.M21, matrix2.M21)
|| MatrixHelper.NotEqual(matrix1.M12, matrix2.M12)
|| MatrixHelper.NotEqual(matrix1.M22, matrix2.M22);
}
public static Matrix2x2 operator +(Matrix2x2 matrix1, Matrix2x2 matrix2)
{
double m11 = matrix1.M11 + matrix2.M11;
double m21 = matrix1.M21 + matrix2.M21;
double m12 = matrix1.M12 + matrix2.M12;
double m22 = matrix1.M22 + matrix2.M22;
return new Matrix2x2(m11, m21,
m12, m22);
}
public static Matrix2x2 operator -(Matrix2x2 matrix1, Matrix2x2 matrix2)
{
double m11 = matrix1.M11 - matrix2.M11;
double m21 = matrix1.M21 - matrix2.M21;
double m12 = matrix1.M12 - matrix2.M12;
double m22 = matrix1.M22 - matrix2.M22;
return new Matrix2x2(m11, m21,
m12, m22);
}
public static Matrix2x2 operator *(Matrix2x2 matrix, double scalar)
{
double m11 = matrix.M11 * scalar;
double m21 = matrix.M21 * scalar;
double m12 = matrix.M12 * scalar;
double m22 = matrix.M22 * scalar;
return new Matrix2x2(m11, m21,
m12, m22);
}
public static Matrix2x2 operator *(double scalar, Matrix2x2 matrix)
{
double m11 = scalar * matrix.M11;
double m21 = scalar * matrix.M21;
double m12 = scalar * matrix.M12;
double m22 = scalar * matrix.M22;
return new Matrix2x2(m11, m21,
m12, m22);
}
public static Matrix1x2 operator *(Matrix2x2 matrix1, Matrix1x2 matrix2)
{
double m11 = matrix1.M11 * matrix2.M11 + matrix1.M21 * matrix2.M12;
double m12 = matrix1.M12 * matrix2.M11 + matrix1.M22 * matrix2.M12;
return new Matrix1x2(m11,
m12);
}
public static Matrix2x2 operator *(Matrix2x2 matrix1, Matrix2x2 matrix2)
{
double m11 = matrix1.M11 * matrix2.M11 + matrix1.M21 * matrix2.M12;
double m21 = matrix1.M11 * matrix2.M21 + matrix1.M21 * matrix2.M22;
double m12 = matrix1.M12 * matrix2.M11 + matrix1.M22 * matrix2.M12;
double m22 = matrix1.M12 * matrix2.M21 + matrix1.M22 * matrix2.M22;
return new Matrix2x2(m11, m21,
m12, m22);
}
public static Matrix3x2 operator *(Matrix2x2 matrix1, Matrix3x2 matrix2)
{
double m11 = matrix1.M11 * matrix2.M11 + matrix1.M21 * matrix2.M12;
double m21 = matrix1.M11 * matrix2.M21 + matrix1.M21 * matrix2.M22;
double m31 = matrix1.M11 * matrix2.M31 + matrix1.M21 * matrix2.M32;
double m12 = matrix1.M12 * matrix2.M11 + matrix1.M22 * matrix2.M12;
double m22 = matrix1.M12 * matrix2.M21 + matrix1.M22 * matrix2.M22;
double m32 = matrix1.M12 * matrix2.M31 + matrix1.M22 * matrix2.M32;
return new Matrix3x2(m11, m21, m31,
m12, m22, m32);
}
public static Matrix4x2 operator *(Matrix2x2 matrix1, Matrix4x2 matrix2)
{
double m11 = matrix1.M11 * matrix2.M11 + matrix1.M21 * matrix2.M12;
double m21 = matrix1.M11 * matrix2.M21 + matrix1.M21 * matrix2.M22;
double m31 = matrix1.M11 * matrix2.M31 + matrix1.M21 * matrix2.M32;
double m41 = matrix1.M11 * matrix2.M41 + matrix1.M21 * matrix2.M42;
double m12 = matrix1.M12 * matrix2.M11 + matrix1.M22 * matrix2.M12;
double m22 = matrix1.M12 * matrix2.M21 + matrix1.M22 * matrix2.M22;
double m32 = matrix1.M12 * matrix2.M31 + matrix1.M22 * matrix2.M32;
double m42 = matrix1.M12 * matrix2.M41 + matrix1.M22 * matrix2.M42;
return new Matrix4x2(m11, m21, m31, m41,
m12, m22, m32, m42);
}
}
}
| |
using System.Collections.Generic;
using Xunit;
using Shouldly;
using System;
namespace AutoMapper.UnitTests
{
public class When_overriding_global_ignore : AutoMapperSpecBase
{
Destination _destination;
public class Source
{
public int ShouldBeMapped { get; set; }
}
public class Destination
{
public int ShouldBeMapped { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.AddGlobalIgnore("ShouldBeMapped");
cfg.CreateMap<Source, Destination>().ForMember(d => d.ShouldBeMapped, o => o.MapFrom(src => 12));
});
protected override void Because_of()
{
_destination = Mapper.Map<Destination>(new Source());
}
[Fact]
public void Should_not_ignore()
{
_destination.ShouldBeMapped.ShouldBe(12);
}
}
public class IgnoreAllTests
{
public class Source
{
public string ShouldBeMapped { get; set; }
}
public class Destination
{
public string ShouldBeMapped { get; set; }
public string StartingWith_ShouldNotBeMapped { get; set; }
public List<string> StartingWith_ShouldBeNullAfterwards { get; set; }
public string AnotherString_ShouldBeNullAfterwards { get; set; }
}
public class DestinationWrongType
{
public Destination ShouldBeMapped { get; set; }
}
public class FooProfile : Profile
{
public FooProfile()
{
CreateMap<Source, Destination>()
.ForMember(dest => dest.AnotherString_ShouldBeNullAfterwards, opt => opt.Ignore());
}
}
[Fact]
public void GlobalIgnore_ignores_all_properties_beginning_with_string()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddGlobalIgnore("StartingWith");
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.AnotherString_ShouldBeNullAfterwards, opt => opt.Ignore());
});
config.CreateMapper().Map<Source, Destination>(new Source{ShouldBeMapped = "true"});
config.AssertConfigurationIsValid();
}
[Fact]
public void GlobalIgnore_ignores_all_properties_beginning_with_string_in_profiles()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddGlobalIgnore("StartingWith");
cfg.AddProfile<FooProfile>();
});
config.CreateMapper().Map<Source, Destination>(new Source{ShouldBeMapped = "true"});
config.AssertConfigurationIsValid();
}
[Fact]
public void GlobalIgnore_ignores_properties_with_names_matching_but_different_types()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddGlobalIgnore("ShouldBeMapped");
cfg.CreateMap<Source, DestinationWrongType>();
});
config.CreateMapper().Map<Source, DestinationWrongType>(new Source { ShouldBeMapped = "true" });
config.AssertConfigurationIsValid();
}
[Fact]
public void Ignored_properties_should_be_default_value()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddGlobalIgnore("StartingWith");
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.AnotherString_ShouldBeNullAfterwards, opt => opt.Ignore());
});
Destination destination = config.CreateMapper().Map<Source, Destination>(new Source { ShouldBeMapped = "true" });
destination.StartingWith_ShouldBeNullAfterwards.ShouldBe(null);
destination.StartingWith_ShouldNotBeMapped.ShouldBe(null);
}
[Fact]
public void Ignore_supports_two_different_values()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddGlobalIgnore("StartingWith");
cfg.AddGlobalIgnore("AnotherString");
cfg.CreateMap<Source, Destination>();
});
Destination destination = config.CreateMapper().Map<Source, Destination>(new Source { ShouldBeMapped = "true" });
destination.AnotherString_ShouldBeNullAfterwards.ShouldBe(null);
destination.StartingWith_ShouldNotBeMapped.ShouldBe(null);
}
}
public class IgnoreAttributeTests
{
public class Source
{
public string ShouldBeMapped { get; set; }
public string ShouldNotBeMapped { get; set; }
}
public class Destination
{
public string ShouldBeMapped { get; set; }
[IgnoreMap]
public string ShouldNotBeMapped { get; set; }
}
[Fact]
public void Ignore_On_Source_Field()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddIgnoreMapAttribute();
cfg.CreateMap<Source, Destination>();
});
config.AssertConfigurationIsValid();
Source source = new Source
{
ShouldBeMapped = "Value1",
ShouldNotBeMapped = "Value2"
};
Destination destination = config.CreateMapper().Map<Source, Destination>(source);
destination.ShouldNotBeMapped.ShouldBe(null);
}
}
public class ReverseMapIgnoreAttributeTests
{
public class Source
{
public string ShouldBeMapped { get; set; }
public string ShouldNotBeMapped { get; set; }
}
public class Destination
{
public string ShouldBeMapped { get; set; }
[IgnoreMap]
public string ShouldNotBeMapped { get; set; }
}
[Fact]
public void Ignore_On_Source_Field()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddIgnoreMapAttribute();
cfg.CreateMap<Source, Destination>().ReverseMap();
});
config.AssertConfigurationIsValid();
Destination source = new Destination
{
ShouldBeMapped = "Value1",
ShouldNotBeMapped = "Value2"
};
Source destination = config.CreateMapper().Map<Destination, Source>(source);
destination.ShouldNotBeMapped.ShouldBe(null);
}
public class Source2
{
}
public class Destination2
{
[IgnoreMap]
public string ShouldNotThrowExceptionOnReverseMapping { get; set; }
}
[Fact]
public void Sould_not_throw_exception_when_reverse_property_does_not_exist()
{
typeof(ArgumentOutOfRangeException).ShouldNotBeThrownBy(() => new MapperConfiguration(cfg => cfg.CreateMap<Source2, Destination2>()
.ReverseMap()));
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Elasticsearch.Net.Connection.Configuration;
using Elasticsearch.Net.Connection.Thrift.Protocol;
using Elasticsearch.Net.Connection.Thrift.Transport;
namespace Elasticsearch.Net.Connection.Thrift
{
public class ThriftConnection : IConnection, IDisposable
{
private readonly ConcurrentDictionary<Uri, ConcurrentQueue<Rest.Client>> _clients =
new ConcurrentDictionary<Uri, ConcurrentQueue<Rest.Client>>();
private readonly Semaphore _resourceLock;
private readonly int _timeout;
private readonly int _poolSize;
private bool _disposed;
private readonly IConnectionConfigurationValues _connectionSettings;
public ThriftConnection(IConnectionConfigurationValues connectionSettings)
{
this._connectionSettings = connectionSettings;
this._timeout = connectionSettings.Timeout;
var connectionPool = this._connectionSettings.ConnectionPool;
var maximumConnections = Math.Max(1, connectionSettings.MaximumAsyncConnections);
var maximumUrls = connectionPool.MaxRetries + 1;
this._poolSize = maximumConnections;
this._resourceLock = new Semaphore(_poolSize, _poolSize);
int seed; int initialSeed = 0; bool shouldPingHint;
for (var i = 0; i < maximumUrls; i++)
{
var uri = connectionPool.GetNext(initialSeed, out seed, out shouldPingHint);
var queue = new ConcurrentQueue<Rest.Client>();
for (var c = 0; c < maximumConnections; c++)
{
var host = uri.Host;
var port = uri.Port;
var tsocket = new TSocket(host, port);
var transport = new TBufferedTransport(tsocket, 1024);
var protocol = new TBinaryProtocol(transport);
var client = new Rest.Client(protocol);
tsocket.Timeout = this._connectionSettings.Timeout;
tsocket.TcpClient.SendTimeout = this._connectionSettings.Timeout;
tsocket.TcpClient.ReceiveTimeout = this._connectionSettings.Timeout;
//tsocket.TcpClient.NoDelay = true;
queue.Enqueue(client);
initialSeed = seed;
}
_clients.TryAdd(uri, queue);
}
}
#region IConnection Members
public Task<ElasticsearchResponse<Stream>> Get(Uri uri, IRequestConfiguration requestConfiguration = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.GET;
restRequest.Uri = uri;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() =>
{
return this.Execute(restRequest, requestConfiguration);
});
}
public Task<ElasticsearchResponse<Stream>> Head(Uri uri, IRequestConfiguration requestConfiguration = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.HEAD;
restRequest.Uri = uri;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() =>
{
return this.Execute(restRequest, requestConfiguration);
});
}
public ElasticsearchResponse<Stream> GetSync(Uri uri, IRequestConfiguration requestConfiguration = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.GET;
restRequest.Uri = uri;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return this.Execute(restRequest, requestConfiguration);
}
public ElasticsearchResponse<Stream> HeadSync(Uri uri, IRequestConfiguration requestConfiguration = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.HEAD;
restRequest.Uri = uri;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return this.Execute(restRequest, requestConfiguration);
}
public Task<ElasticsearchResponse<Stream>> Post(Uri uri, byte[] data, IRequestConfiguration requestConfiguration = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.POST;
restRequest.Uri = uri;
restRequest.Body = data;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() =>
{
return this.Execute(restRequest, requestConfiguration);
});
}
public Task<ElasticsearchResponse<Stream>> Put(Uri uri, byte[] data, IRequestConfiguration requestConfiguration = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.PUT;
restRequest.Uri = uri;
restRequest.Body = data;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() =>
{
return this.Execute(restRequest, requestConfiguration);
});
}
public Task<ElasticsearchResponse<Stream>> Delete(Uri uri, byte[] data, IRequestConfiguration requestConfiguration = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.DELETE;
restRequest.Uri = uri;
restRequest.Body = data;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() =>
{
return this.Execute(restRequest, requestConfiguration);
});
}
public ElasticsearchResponse<Stream> PostSync(Uri uri, byte[] data, IRequestConfiguration requestConfiguration = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.POST;
restRequest.Uri = uri;
restRequest.Body = data;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return this.Execute(restRequest, requestConfiguration);
}
public ElasticsearchResponse<Stream> PutSync(Uri uri, byte[] data, IRequestConfiguration requestConfiguration = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.PUT;
restRequest.Uri = uri;
restRequest.Body = data;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return this.Execute(restRequest, requestConfiguration);
}
public Task<ElasticsearchResponse<Stream>> Delete(Uri uri, IRequestConfiguration requestConfiguration = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.DELETE;
restRequest.Uri = uri;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() =>
{
return this.Execute(restRequest, requestConfiguration);
});
}
public ElasticsearchResponse<Stream> DeleteSync(Uri uri, IRequestConfiguration requestConfiguration = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.DELETE;
restRequest.Uri = uri;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return this.Execute(restRequest, requestConfiguration);
}
public ElasticsearchResponse<Stream> DeleteSync(Uri uri, byte[] data, IRequestConfiguration requestConfiguration = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.DELETE;
restRequest.Uri = uri;
restRequest.Body = data;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return this.Execute(restRequest, requestConfiguration);
}
#endregion
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
}
#endregion
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
foreach (var c in this._clients.SelectMany(c=>c.Value))
{
if (c != null
&& c.InputProtocol != null
&& c.InputProtocol.Transport != null
&& c.InputProtocol.Transport.IsOpen)
c.InputProtocol.Transport.Close();
}
_disposed = true;
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the
/// <see cref="HttpConnection"/> is reclaimed by garbage collection.
/// </summary>
~ThriftConnection()
{
Dispose(false);
}
private ElasticsearchResponse<Stream> Execute(RestRequest restRequest, object requestConfiguration)
{
//RestResponse result = GetClient().execute(restRequest);
//
var method = Enum.GetName(typeof(Method), restRequest.Method);
var uri = restRequest.Uri;
var path = uri.ToString();
var baseUri = new Uri(string.Format("{0}://{1}:{2}", uri.Scheme, uri.Host, uri.Port));
var requestData = restRequest.Body;
if (!this._resourceLock.WaitOne(this._timeout))
{
var m = "Could not start the thrift operation before the timeout of " + this._timeout + "ms completed while waiting for the semaphore";
return ElasticsearchResponse<Stream>.CreateError(this._connectionSettings, new TimeoutException(m), method, path, requestData);
}
try
{
ConcurrentQueue<Rest.Client> queue;
if (!this._clients.TryGetValue(baseUri,out queue))
{
var m = string.Format("Could dequeue a thrift client from internal socket pool of size {0}", this._poolSize);
var status = ElasticsearchResponse<Stream>.CreateError(this._connectionSettings, new Exception(m), method, path, requestData);
return status;
}
Rest.Client client;
if (!queue.TryDequeue(out client))
{
var m = string.Format("Could dequeue a thrift client from internal socket pool of size {0}", this._poolSize);
var status = ElasticsearchResponse<Stream>.CreateError(this._connectionSettings, new Exception(m), method, path, requestData);
return status;
}
try
{
if (!client.InputProtocol.Transport.IsOpen)
client.InputProtocol.Transport.Open();
var result = client.execute(restRequest);
if (result.Status == Status.OK || result.Status == Status.CREATED || result.Status == Status.ACCEPTED)
{
var response = ElasticsearchResponse<Stream>.Create(
this._connectionSettings, (int)result.Status, method, path, requestData, new MemoryStream(result.Body ?? new byte[0]));
return response;
}
else
{
var response = ElasticsearchResponse<Stream>.Create(
this._connectionSettings, (int)result.Status, method, path, requestData, new MemoryStream(result.Body ?? new byte[0]));
return response;
}
}
catch (SocketException)
{
client.InputProtocol.Transport.Close();
throw;
}
catch (IOException)
{
client.InputProtocol.Transport.Close();
throw;
}
catch (TTransportException)
{
client.InputProtocol.Transport.Close();
throw;
}
finally
{
//make sure we make the client available again.
if (queue != null && client != null)
queue.Enqueue(client);
}
}
catch (Exception e)
{
return ElasticsearchResponse<Stream>.CreateError(this._connectionSettings, e, method, path, requestData);
}
finally
{
this._resourceLock.Release();
}
}
public string DecodeStr(byte[] bytes)
{
if (bytes != null && bytes.Length > 0)
{
return Encoding.UTF8.GetString(bytes);
}
return string.Empty;
}
}
}
| |
//#define FBV6_API_ENABLED
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
#if FBV6_API_ENABLED
using Facebook;
#endif
public class SP_FB_API_v6 : SP_FB_API {
public void Init() {
#if FBV6_API_ENABLED
FB.Init(OnInitComplete, OnHideUnity);
#endif
}
public void Login(params string[] scopes) {
#if FBV6_API_ENABLED
string scopesList = string.Empty;
foreach(string s in scopes) {
if (!scopesList.Equals(string.Empty)) {
scopesList += ",";
}
scopesList += s;
}
FB.Login(scopesList, LoginCallback);
#endif
}
public void Logout() {
#if FBV6_API_ENABLED
FB.Logout();
#endif
}
public void API(string query, FB_HttpMethod method, SPFacebook.FB_Delegate callback) {
#if FBV6_API_ENABLED
new FB_GrapRequest_V6(query, ConvertHttpMethod(method), callback);
#endif
}
public void API(string query, FB_HttpMethod method, SPFacebook.FB_Delegate callback, WWWForm form) {
#if FBV6_API_ENABLED
new FB_GrapRequest_V6(query, ConvertHttpMethod(method), callback, form);
#endif
}
public void AppRequest(string message, FB_RequestActionType actionType, string objectId, string[] to, string data = "", string title = "") {
#if FBV6_API_ENABLED
FB.AppRequest(message, ConvertActionType(actionType), objectId, to, data, title, AppRequestCallback);
#endif
}
public void AppRequest(string message, FB_RequestActionType actionType, string objectId, List<object> filters = null, string[] excludeIds = null, int? maxRecipients = null, string data = "", string title = "") {
#if FBV6_API_ENABLED
FB.AppRequest(message, ConvertActionType(actionType), objectId, filters, excludeIds, maxRecipients, data, title, AppRequestCallback);
#endif
}
public void AppRequest(string message, string[] to = null, List<object> filters = null, string[] excludeIds = null, int? maxRecipients = null, string data = "", string title = "") {
#if FBV6_API_ENABLED
FB.AppRequest(message, to, filters, excludeIds, maxRecipients, data, title, AppRequestCallback);
#endif
}
public void FeedShare (string toId = "", string link = "", string linkName = "", string linkCaption = "", string linkDescription = "", string picture = "", string actionName = "", string actionLink = "", string reference = "") {
#if FBV6_API_ENABLED
FB.Feed(
toId: toId,
link: link,
linkName: linkName,
linkCaption: linkCaption,
linkDescription: linkDescription,
picture: picture,
actionName: actionName,
actionLink: actionLink,
reference: reference,
callback: PostCallback
);
#endif
}
public void AppInvite(string appLinkUrl, string previewImageUrl)
{
//Nothing to do here. This API is NOT available in Facebook SDK v6
}
//--------------------------------------
// Get / Set
//--------------------------------------
public bool IsLoggedIn {
get {
#if FBV6_API_ENABLED
return FB.IsLoggedIn;
#else
return false;
#endif
}
}
public string UserId {
get {
#if FBV6_API_ENABLED
return FB.UserId;
#else
return "";
#endif
}
}
public string AccessToken {
get {
#if FBV6_API_ENABLED
return FB.AccessToken;
#else
return "";
#endif
}
}
public string AppId {
get {
#if FBV6_API_ENABLED
return FB.AppId;
#else
return "";
#endif
}
}
public static bool IsAPIEnabled {
get {
#if FBV6_API_ENABLED
return true;
#else
return false;
#endif
}
}
//--------------------------------------
// Handlers
//--------------------------------------
#if FBV6_API_ENABLED
private void AppRequestCallback(FBResult result) {
FB_AppRequestResult res = new FB_AppRequestResult(result.Text, result.Error);
SPFacebook.Instance.AppRequestCallback(res);
}
private void LoginCallback(FBResult result) {
bool IsCancelled = false;
if(result.Error == null && !IsLoggedIn) {
IsCancelled = true;
}
FB_LoginResult res = new FB_LoginResult(result.Text, result.Error, IsCancelled);
res.SetCredential(UserId, AccessToken);
SPFacebook.Instance.LoginCallback(res);
}
private void OnInitComplete() {
SPFacebook.Instance.OnInitComplete();
}
private void OnHideUnity(bool isGameShown) {
SPFacebook.Instance.OnHideUnity(isGameShown);
}
private void PostCallback(FBResult result) {
FB_PostResult res = new FB_PostResult(result.Text, result.Error);
SPFacebook.Instance.PostCallback(res);
}
//--------------------------------------
// Utils
//--------------------------------------
private HttpMethod ConvertHttpMethod(FB_HttpMethod method) {
switch(method) {
case FB_HttpMethod.GET:
return HttpMethod.GET;
case FB_HttpMethod.POST:
return HttpMethod.POST;
case FB_HttpMethod.DELETE:
return HttpMethod.POST;
}
return HttpMethod.GET;
}
private OGActionType ConvertActionType(FB_RequestActionType actionType) {
switch(actionType) {
case FB_RequestActionType.AskFor:
return OGActionType.AskFor;
case FB_RequestActionType.Send:
return OGActionType.Send;
}
return OGActionType.AskFor;
}
#endif
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public class IntersectTests
{
private const int DuplicateFactor = 4;
public static IEnumerable<object[]> IntersectUnorderedData(int[] leftCounts, int[] rightCounts)
{
foreach (object[] parms in UnorderedSources.BinaryRanges(leftCounts.Cast<int>(), (l, r) => 0 - r / 2, rightCounts.Cast<int>()))
{
parms[4] = Math.Min((int)parms[1], ((int)parms[3] + 1) / 2);
yield return parms;
}
}
public static IEnumerable<object[]> IntersectData(int[] leftCounts, int[] rightCounts)
{
foreach (object[] parms in IntersectUnorderedData(leftCounts, rightCounts))
{
parms[0] = ((Labeled<ParallelQuery<int>>)parms[0]).Order();
yield return parms;
}
}
public static IEnumerable<object[]> IntersectSourceMultipleData(int[] counts)
{
foreach (int leftCount in counts.Cast<int>())
{
ParallelQuery<int> left = Enumerable.Range(0, leftCount * DuplicateFactor).Select(x => x % leftCount).ToArray().AsParallel().AsOrdered();
foreach (int rightCount in new int[] { 0, 1, Math.Max(DuplicateFactor * 2, leftCount), 2 * Math.Max(DuplicateFactor, leftCount * 2) })
{
int rightStart = 0 - rightCount / 2;
yield return new object[] { left, leftCount,
ParallelEnumerable.Range(rightStart, rightCount), rightCount, Math.Min(leftCount, (rightCount + 1) / 2) };
}
}
}
//
// Intersect
//
[Theory]
[MemberData(nameof(IntersectUnorderedData), new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_Unordered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
foreach (int i in leftQuery.Intersect(rightQuery))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectUnorderedData), new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Unordered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_Unordered(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData(nameof(IntersectData), new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
foreach (int i in leftQuery.Intersect(rightQuery))
{
Assert.Equal(seen++, i);
}
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectData), new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData(nameof(IntersectUnorderedData), new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_Unordered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(leftQuery.Intersect(rightQuery).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectUnorderedData), new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_Unordered_NotPipelined(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData(nameof(IntersectData), new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
Assert.All(leftQuery.Intersect(rightQuery).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectData), new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_NotPipelined(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData(nameof(IntersectUnorderedData), new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_Unordered_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(leftCount, rightCount));
foreach (int i in leftQuery.Intersect(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)))
{
seen.Add(i % (DuplicateFactor * 2));
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectUnorderedData), new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Unordered_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_Unordered_Distinct(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData(nameof(IntersectData), new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
int seen = 0;
foreach (int i in leftQuery.Intersect(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)))
{
Assert.Equal(seen++, i);
}
Assert.Equal(Math.Min(leftCount, rightCount), seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectData), new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_Distinct(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData(nameof(IntersectUnorderedData), new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_Unordered_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(leftCount, rightCount));
Assert.All(leftQuery.Intersect(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)).ToList(), x => seen.Add(x % (DuplicateFactor * 2)));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectUnorderedData), new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Unordered_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_Unordered_Distinct_NotPipelined(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData(nameof(IntersectData), new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
int seen = 0;
Assert.All(leftQuery.Intersect(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(Math.Min(leftCount, rightCount), seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectData), new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_Distinct_NotPipelined(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData(nameof(IntersectSourceMultipleData), (object)(new int[] { 0, 1, 2, 16 }))]
public static void Intersect_Unordered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
// The difference between this test and the previous, is that it's not possible to
// get non-unique results from ParallelEnumerable.Range()...
// Those tests either need modification of source (via .Select(x => x /DuplicateFactor) or similar,
// or via a comparator that considers some elements equal.
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(leftQuery.AsUnordered().Intersect(rightQuery), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectSourceMultipleData), (object)(new int[] { 512, 1024 * 16 }))]
public static void Intersect_Unordered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
Intersect_Unordered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count);
}
[Theory]
[MemberData(nameof(IntersectSourceMultipleData), (object)(new int[] { 0, 1, 2, 16 }))]
public static void Intersect_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
int seen = 0;
Assert.All(leftQuery.Intersect(rightQuery), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectSourceMultipleData), (object)(new int[] { 512, 1024 * 16 }))]
public static void Intersect_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
Intersect_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count);
}
[Fact]
public static void Intersect_NotSupportedException()
{
#pragma warning disable 618
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Intersect(Enumerable.Range(0, 1)));
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Intersect(Enumerable.Range(0, 1), null));
#pragma warning restore 618
}
[Fact]
// Should not get the same setting from both operands.
public static void Intersect_NoDuplicateSettings()
{
CancellationToken t = new CancellationTokenSource().Token;
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).Intersect(ParallelEnumerable.Range(0, 1).WithCancellation(t)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).Intersect(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).Intersect(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).Intersect(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default)));
}
[Fact]
public static void Intersect_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Intersect(ParallelEnumerable.Range(0, 1)));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Intersect(null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Intersect(ParallelEnumerable.Range(0, 1), EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Intersect(null, EqualityComparer<int>.Default));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.Globalization
{
public static class __HijriCalendar
{
public static IObservable<System.DateTime> AddMonths(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue, IObservable<System.DateTime> time,
IObservable<System.Int32> months)
{
return Observable.Zip(HijriCalendarValue, time, months,
(HijriCalendarValueLambda, timeLambda, monthsLambda) =>
HijriCalendarValueLambda.AddMonths(timeLambda, monthsLambda));
}
public static IObservable<System.DateTime> AddYears(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue, IObservable<System.DateTime> time,
IObservable<System.Int32> years)
{
return Observable.Zip(HijriCalendarValue, time, years,
(HijriCalendarValueLambda, timeLambda, yearsLambda) =>
HijriCalendarValueLambda.AddYears(timeLambda, yearsLambda));
}
public static IObservable<System.Int32> GetDayOfMonth(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue, IObservable<System.DateTime> time)
{
return Observable.Zip(HijriCalendarValue, time,
(HijriCalendarValueLambda, timeLambda) => HijriCalendarValueLambda.GetDayOfMonth(timeLambda));
}
public static IObservable<System.DayOfWeek> GetDayOfWeek(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue, IObservable<System.DateTime> time)
{
return Observable.Zip(HijriCalendarValue, time,
(HijriCalendarValueLambda, timeLambda) => HijriCalendarValueLambda.GetDayOfWeek(timeLambda));
}
public static IObservable<System.Int32> GetDayOfYear(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue, IObservable<System.DateTime> time)
{
return Observable.Zip(HijriCalendarValue, time,
(HijriCalendarValueLambda, timeLambda) => HijriCalendarValueLambda.GetDayOfYear(timeLambda));
}
public static IObservable<System.Int32> GetDaysInMonth(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue, IObservable<System.Int32> year,
IObservable<System.Int32> month, IObservable<System.Int32> era)
{
return Observable.Zip(HijriCalendarValue, year, month, era,
(HijriCalendarValueLambda, yearLambda, monthLambda, eraLambda) =>
HijriCalendarValueLambda.GetDaysInMonth(yearLambda, monthLambda, eraLambda));
}
public static IObservable<System.Int32> GetDaysInYear(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue, IObservable<System.Int32> year,
IObservable<System.Int32> era)
{
return Observable.Zip(HijriCalendarValue, year, era,
(HijriCalendarValueLambda, yearLambda, eraLambda) =>
HijriCalendarValueLambda.GetDaysInYear(yearLambda, eraLambda));
}
public static IObservable<System.Int32> GetEra(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue, IObservable<System.DateTime> time)
{
return Observable.Zip(HijriCalendarValue, time,
(HijriCalendarValueLambda, timeLambda) => HijriCalendarValueLambda.GetEra(timeLambda));
}
public static IObservable<System.Int32> GetMonth(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue, IObservable<System.DateTime> time)
{
return Observable.Zip(HijriCalendarValue, time,
(HijriCalendarValueLambda, timeLambda) => HijriCalendarValueLambda.GetMonth(timeLambda));
}
public static IObservable<System.Int32> GetMonthsInYear(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue, IObservable<System.Int32> year,
IObservable<System.Int32> era)
{
return Observable.Zip(HijriCalendarValue, year, era,
(HijriCalendarValueLambda, yearLambda, eraLambda) =>
HijriCalendarValueLambda.GetMonthsInYear(yearLambda, eraLambda));
}
public static IObservable<System.Int32> GetYear(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue, IObservable<System.DateTime> time)
{
return Observable.Zip(HijriCalendarValue, time,
(HijriCalendarValueLambda, timeLambda) => HijriCalendarValueLambda.GetYear(timeLambda));
}
public static IObservable<System.Boolean> IsLeapDay(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue, IObservable<System.Int32> year,
IObservable<System.Int32> month, IObservable<System.Int32> day, IObservable<System.Int32> era)
{
return Observable.Zip(HijriCalendarValue, year, month, day, era,
(HijriCalendarValueLambda, yearLambda, monthLambda, dayLambda, eraLambda) =>
HijriCalendarValueLambda.IsLeapDay(yearLambda, monthLambda, dayLambda, eraLambda));
}
public static IObservable<System.Int32> GetLeapMonth(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue, IObservable<System.Int32> year,
IObservable<System.Int32> era)
{
return Observable.Zip(HijriCalendarValue, year, era,
(HijriCalendarValueLambda, yearLambda, eraLambda) =>
HijriCalendarValueLambda.GetLeapMonth(yearLambda, eraLambda));
}
public static IObservable<System.Boolean> IsLeapMonth(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue, IObservable<System.Int32> year,
IObservable<System.Int32> month, IObservable<System.Int32> era)
{
return Observable.Zip(HijriCalendarValue, year, month, era,
(HijriCalendarValueLambda, yearLambda, monthLambda, eraLambda) =>
HijriCalendarValueLambda.IsLeapMonth(yearLambda, monthLambda, eraLambda));
}
public static IObservable<System.Boolean> IsLeapYear(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue, IObservable<System.Int32> year,
IObservable<System.Int32> era)
{
return Observable.Zip(HijriCalendarValue, year, era,
(HijriCalendarValueLambda, yearLambda, eraLambda) =>
HijriCalendarValueLambda.IsLeapYear(yearLambda, eraLambda));
}
public static IObservable<System.DateTime> ToDateTime(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue, IObservable<System.Int32> year,
IObservable<System.Int32> month, IObservable<System.Int32> day, IObservable<System.Int32> hour,
IObservable<System.Int32> minute, IObservable<System.Int32> second, IObservable<System.Int32> millisecond,
IObservable<System.Int32> era)
{
return Observable.Zip(HijriCalendarValue, year, month, day, hour, minute, second, millisecond, era,
(HijriCalendarValueLambda, yearLambda, monthLambda, dayLambda, hourLambda, minuteLambda, secondLambda,
millisecondLambda, eraLambda) =>
HijriCalendarValueLambda.ToDateTime(yearLambda, monthLambda, dayLambda, hourLambda, minuteLambda,
secondLambda, millisecondLambda, eraLambda));
}
public static IObservable<System.Int32> ToFourDigitYear(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue, IObservable<System.Int32> year)
{
return Observable.Zip(HijriCalendarValue, year,
(HijriCalendarValueLambda, yearLambda) => HijriCalendarValueLambda.ToFourDigitYear(yearLambda));
}
public static IObservable<System.DateTime> get_MinSupportedDateTime(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue)
{
return Observable.Select(HijriCalendarValue,
(HijriCalendarValueLambda) => HijriCalendarValueLambda.MinSupportedDateTime);
}
public static IObservable<System.DateTime> get_MaxSupportedDateTime(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue)
{
return Observable.Select(HijriCalendarValue,
(HijriCalendarValueLambda) => HijriCalendarValueLambda.MaxSupportedDateTime);
}
public static IObservable<System.Globalization.CalendarAlgorithmType> get_AlgorithmType(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue)
{
return Observable.Select(HijriCalendarValue,
(HijriCalendarValueLambda) => HijriCalendarValueLambda.AlgorithmType);
}
public static IObservable<System.Int32> get_HijriAdjustment(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue)
{
return Observable.Select(HijriCalendarValue,
(HijriCalendarValueLambda) => HijriCalendarValueLambda.HijriAdjustment);
}
public static IObservable<System.Int32[]> get_Eras(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue)
{
return Observable.Select(HijriCalendarValue, (HijriCalendarValueLambda) => HijriCalendarValueLambda.Eras);
}
public static IObservable<System.Int32> get_TwoDigitYearMax(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue)
{
return Observable.Select(HijriCalendarValue,
(HijriCalendarValueLambda) => HijriCalendarValueLambda.TwoDigitYearMax);
}
public static IObservable<System.Reactive.Unit> set_HijriAdjustment(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue, IObservable<System.Int32> value)
{
return ObservableExt.ZipExecute(HijriCalendarValue, value,
(HijriCalendarValueLambda, valueLambda) => HijriCalendarValueLambda.HijriAdjustment = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_TwoDigitYearMax(
this IObservable<System.Globalization.HijriCalendar> HijriCalendarValue, IObservable<System.Int32> value)
{
return ObservableExt.ZipExecute(HijriCalendarValue, value,
(HijriCalendarValueLambda, valueLambda) => HijriCalendarValueLambda.TwoDigitYearMax = valueLambda);
}
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using NLog.Common;
using NLog.Internal;
using NLog.Layouts;
using NLog.MessageTemplates;
using NLog.Time;
/// <summary>
/// Represents the logging event.
/// </summary>
public class LogEventInfo
{
/// <summary>
/// Gets the date of the first log event created.
/// </summary>
public static readonly DateTime ZeroDate = DateTime.UtcNow;
internal static readonly LogMessageFormatter StringFormatMessageFormatter = GetStringFormatMessageFormatter;
internal static LogMessageFormatter DefaultMessageFormatter { get; set; } = LogMessageTemplateFormatter.DefaultAuto.MessageFormatter;
private static int globalSequenceId;
/// <summary>
/// The formatted log message.
/// </summary>
private string _formattedMessage;
/// <summary>
/// The log message including any parameter placeholders
/// </summary>
private string _message;
private object[] _parameters;
private IFormatProvider _formatProvider;
private LogMessageFormatter _messageFormatter = DefaultMessageFormatter;
private IDictionary<Layout, string> _layoutCache;
private PropertiesDictionary _properties;
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
public LogEventInfo()
{
TimeStamp = TimeSource.Current.Time;
SequenceID = Interlocked.Increment(ref globalSequenceId);
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="message">Log message including parameter placeholders.</param>
public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message)
: this(level, loggerName, null, message, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="message">Log message including parameter placeholders.</param>
/// <param name="messageTemplateParameters">Log message including parameter placeholders.</param>
public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message, IList<MessageTemplateParameter> messageTemplateParameters)
: this(level, loggerName, null, message, null, null)
{
if (messageTemplateParameters != null && messageTemplateParameters.Count > 0)
{
_properties = new PropertiesDictionary(messageTemplateParameters);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">Log message including parameter placeholders.</param>
/// <param name="parameters">Parameter array.</param>
public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters)
: this(level, loggerName, formatProvider, message, parameters, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">Log message including parameter placeholders.</param>
/// <param name="parameters">Parameter array.</param>
/// <param name="exception">Exception information.</param>
public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters, Exception exception): this()
{
Level = level;
LoggerName = loggerName;
Message = message;
Parameters = parameters;
FormatProvider = formatProvider;
Exception = exception;
if (NeedToPreformatMessage(parameters))
{
CalcFormattedMessage();
}
}
/// <summary>
/// Gets the unique identifier of log event which is automatically generated
/// and monotonously increasing.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID", Justification = "Backwards compatibility")]
// ReSharper disable once InconsistentNaming
public int SequenceID { get; private set; }
/// <summary>
/// Gets or sets the timestamp of the logging event.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TimeStamp", Justification = "Backwards compatibility.")]
public DateTime TimeStamp { get; set; }
/// <summary>
/// Gets or sets the level of the logging event.
/// </summary>
public LogLevel Level { get; set; }
internal CallSiteInformation CallSiteInformation { get; private set; }
internal CallSiteInformation GetCallSiteInformationInternal() { return CallSiteInformation ?? (CallSiteInformation = new CallSiteInformation()); }
/// <summary>
/// Gets a value indicating whether stack trace has been set for this event.
/// </summary>
public bool HasStackTrace => CallSiteInformation?.StackTrace != null;
/// <summary>
/// Gets the stack frame of the method that did the logging.
/// </summary>
public StackFrame UserStackFrame => CallSiteInformation?.UserStackFrame;
/// <summary>
/// Gets the number index of the stack frame that represents the user
/// code (not the NLog code).
/// </summary>
public int UserStackFrameNumber => CallSiteInformation?.UserStackFrameNumberLegacy ?? CallSiteInformation?.UserStackFrameNumber ?? 0;
/// <summary>
/// Gets the entire stack trace.
/// </summary>
public StackTrace StackTrace => CallSiteInformation?.StackTrace;
/// <summary>
/// Gets the callsite class name
/// </summary>
public string CallerClassName => CallSiteInformation?.CallerClassName;
/// <summary>
/// Gets the callsite member function name
/// </summary>
public string CallerMemberName => CallSiteInformation?.GetCallerMemberName(null, false, true, true);
/// <summary>
/// Gets the callsite source file path
/// </summary>
public string CallerFilePath => CallSiteInformation?.CallerFilePath;
/// <summary>
/// Gets the callsite source file line number
/// </summary>
public int CallerLineNumber => CallSiteInformation?.CallerLineNumber ?? 0;
/// <summary>
/// Gets or sets the exception information.
/// </summary>
public Exception Exception { get; set; }
/// <summary>
/// Gets or sets the logger name.
/// </summary>
public string LoggerName { get; set; }
/// <summary>
/// Gets the logger short name.
/// </summary>
/// <remarks>This property was marked as obsolete on NLog 2.0 and it may be removed in a future release.</remarks>
[Obsolete("This property should not be used. Marked obsolete on NLog 2.0")]
public string LoggerShortName
{
// NOTE: This property is not referenced by NLog code anymore.
get
{
int lastDot = LoggerName.LastIndexOf('.');
if (lastDot >= 0)
{
return LoggerName.Substring(lastDot + 1);
}
return LoggerName;
}
}
/// <summary>
/// Gets or sets the log message including any parameter placeholders.
/// </summary>
public string Message
{
get => _message;
set
{
bool rebuildMessageTemplateParameters = ResetMessageTemplateParameters();
_message = value;
ResetFormattedMessage(rebuildMessageTemplateParameters);
}
}
/// <summary>
/// Gets or sets the parameter values or null if no parameters have been specified.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "For backwards compatibility.")]
public object[] Parameters
{
get => _parameters;
set
{
bool rebuildMessageTemplateParameters = ResetMessageTemplateParameters();
_parameters = value;
ResetFormattedMessage(rebuildMessageTemplateParameters);
}
}
/// <summary>
/// Gets or sets the format provider that was provided while logging or <see langword="null" />
/// when no formatProvider was specified.
/// </summary>
public IFormatProvider FormatProvider
{
get => _formatProvider;
set
{
if (_formatProvider != value)
{
_formatProvider = value;
ResetFormattedMessage(false);
}
}
}
/// <summary>
/// Gets or sets the message formatter for generating <see cref="LogEventInfo.FormattedMessage"/>
/// Uses string.Format(...) when nothing else has been configured.
/// </summary>
public LogMessageFormatter MessageFormatter
{
get => _messageFormatter;
set
{
_messageFormatter = value ?? StringFormatMessageFormatter;
ResetFormattedMessage(false);
}
}
/// <summary>
/// Gets the formatted message.
/// </summary>
public string FormattedMessage
{
get
{
if (_formattedMessage == null)
{
CalcFormattedMessage();
}
return _formattedMessage;
}
}
/// <summary>
/// Checks if any per-event context properties (Without allocation)
/// </summary>
public bool HasProperties
{
get
{
if (_properties != null)
{
return _properties.Count > 0;
}
else
{
return HasMessageTemplateParameters;
}
}
}
internal PropertiesDictionary PropertiesDictionary { get => _properties; set => _properties = value; }
/// <summary>
/// Gets the dictionary of per-event context properties.
/// </summary>
public IDictionary<object, object> Properties => GetPropertiesInternal();
/// <summary>
/// Gets the dictionary of per-event context properties.
/// Internal helper for the PropertiesDictionary type.
/// </summary>
/// <returns></returns>
private PropertiesDictionary GetPropertiesInternal()
{
if (_properties == null)
{
Interlocked.CompareExchange(ref _properties, new PropertiesDictionary(), null);
if (HasMessageTemplateParameters)
{
CalcFormattedMessage();
// MessageTemplateParameters have probably been created
}
}
return _properties;
}
internal bool HasMessageTemplateParameters
{
get
{
var logMessageFormatter = _messageFormatter?.Target as ILogMessageFormatter;
return logMessageFormatter?.HasProperties(this) ?? false;
}
}
/// <summary>
/// Gets the named parameters extracted from parsing <see cref="Message"/> as MessageTemplate
/// </summary>
public IMessageTemplateParameters MessageTemplateParameters
{
get
{
if (_properties != null && _properties.MessageProperties.Count > 0)
{
return new MessageTemplateParameters(_properties.MessageProperties);
}
else
{
return new MessageTemplateParameters(_message, _parameters);
}
}
}
/// <summary>
/// Gets the dictionary of per-event context properties.
/// </summary>
/// <remarks>This property was marked as obsolete on NLog 2.0 and it may be removed in a future release.</remarks>
[Obsolete("Use LogEventInfo.Properties instead. Marked obsolete on NLog 2.0", true)]
public IDictionary Context => GetPropertiesInternal().EventContext;
/// <summary>
/// Creates the null event.
/// </summary>
/// <returns>Null log event.</returns>
public static LogEventInfo CreateNullEvent()
{
return new LogEventInfo(LogLevel.Off, string.Empty, string.Empty);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="message">The message.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, [Localizable(false)] string message)
{
return new LogEventInfo(logLevel, loggerName, null, message, null);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters)
{
return new LogEventInfo(logLevel, loggerName, formatProvider, message, parameters);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, object message)
{
return new LogEventInfo(logLevel, loggerName, formatProvider, "{0}", new[] { message });
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
/// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks>
[Obsolete("use Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, string message) instead. Marked obsolete before v4.3.11")]
public static LogEventInfo Create(LogLevel logLevel, string loggerName, [Localizable(false)] string message, Exception exception)
{
return new LogEventInfo(logLevel, loggerName, null, message, null, exception);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="exception">The exception.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message)
{
return Create(logLevel, loggerName, exception, formatProvider, message, null);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="exception">The exception.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters)
{
return new LogEventInfo(logLevel, loggerName,formatProvider, message, parameters, exception);
}
/// <summary>
/// Creates <see cref="AsyncLogEventInfo"/> from this <see cref="LogEventInfo"/> by attaching the specified asynchronous continuation.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <returns>Instance of <see cref="AsyncLogEventInfo"/> with attached continuation.</returns>
public AsyncLogEventInfo WithContinuation(AsyncContinuation asyncContinuation)
{
return new AsyncLogEventInfo(this, asyncContinuation);
}
/// <summary>
/// Returns a string representation of this log event.
/// </summary>
/// <returns>String representation of the log event.</returns>
public override string ToString()
{
return $"Log Event: Logger='{LoggerName}' Level={Level} Message='{FormattedMessage}' SequenceID={SequenceID}";
}
/// <summary>
/// Sets the stack trace for the event info.
/// </summary>
/// <param name="stackTrace">The stack trace.</param>
/// <param name="userStackFrame">Index of the first user stack frame within the stack trace.</param>
public void SetStackTrace(StackTrace stackTrace, int userStackFrame)
{
GetCallSiteInformationInternal().SetStackTrace(stackTrace, userStackFrame, null);
}
/// <summary>
/// Sets the details retrieved from the Caller Information Attributes
/// </summary>
/// <param name="callerClassName"></param>
/// <param name="callerMemberName"></param>
/// <param name="callerFilePath"></param>
/// <param name="callerLineNumber"></param>
public void SetCallerInfo(string callerClassName, string callerMemberName, string callerFilePath, int callerLineNumber)
{
GetCallSiteInformationInternal().SetCallerInfo(callerClassName, callerMemberName, callerFilePath, callerLineNumber);
}
internal string AddCachedLayoutValue(Layout layout, string value)
{
if (_layoutCache == null)
{
Interlocked.CompareExchange(ref _layoutCache, new Dictionary<Layout, string>(), null);
}
lock (_layoutCache)
{
_layoutCache[layout] = value;
}
return value;
}
internal bool TryGetCachedLayoutValue(Layout layout, out string value)
{
if (_layoutCache == null)
{
// We don't need lock to see if dictionary has been created
value = null;
return false;
}
lock (_layoutCache)
{
if (_layoutCache.Count == 0)
{
value = null;
return false;
}
return _layoutCache.TryGetValue(layout, out value);
}
}
private static bool NeedToPreformatMessage(object[] parameters)
{
// we need to preformat message if it contains any parameters which could possibly
// do logging in their ToString()
if (parameters == null || parameters.Length == 0)
{
return false;
}
if (parameters.Length > 3)
{
// too many parameters, too costly to check
return true;
}
if (!IsSafeToDeferFormatting(parameters[0]))
{
return true;
}
if (parameters.Length >= 2 && !IsSafeToDeferFormatting(parameters[1]))
{
return true;
}
if (parameters.Length >= 3 && !IsSafeToDeferFormatting(parameters[2]))
{
return true;
}
return false;
}
private static bool IsSafeToDeferFormatting(object value)
{
if (value == null)
{
return true;
}
return value.GetType().IsPrimitive() || (value is string);
}
private static string GetStringFormatMessageFormatter(LogEventInfo logEvent)
{
if (logEvent.Parameters == null || logEvent.Parameters.Length == 0)
{
return logEvent.Message;
}
else
{
return string.Format(logEvent.FormatProvider ?? CultureInfo.CurrentCulture, logEvent.Message, logEvent.Parameters);
}
}
private void CalcFormattedMessage()
{
try
{
_formattedMessage = _messageFormatter(this);
}
catch (Exception exception)
{
_formattedMessage = Message;
InternalLogger.Warn(exception, "Error when formatting a message.");
if (exception.MustBeRethrown())
{
throw;
}
}
}
private void ResetFormattedMessage(bool rebuildMessageTemplateParameters)
{
_formattedMessage = null;
if (rebuildMessageTemplateParameters && HasMessageTemplateParameters)
{
CalcFormattedMessage();
}
}
private bool ResetMessageTemplateParameters()
{
if (_properties != null && HasMessageTemplateParameters)
{
_properties.MessageProperties = null;
return true;
}
return false;
}
/// <summary>
/// Set the <see cref="DefaultMessageFormatter"/>
/// </summary>
/// <param name="mode">true = Always, false = Never, null = Auto Detect</param>
internal static void SetDefaultMessageFormatter(bool? mode)
{
if (mode == true)
{
InternalLogger.Info("Message Template Format always enabled");
DefaultMessageFormatter = LogMessageTemplateFormatter.Default.MessageFormatter;
}
else if (mode == false)
{
InternalLogger.Info("Message Template String Format always enabled");
DefaultMessageFormatter = StringFormatMessageFormatter;
}
else
{
//null = auto
InternalLogger.Info("Message Template Auto Format enabled");
DefaultMessageFormatter = LogMessageTemplateFormatter.DefaultAuto.MessageFormatter;
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.XWPF.UserModel
{
using System;
using NPOI.OpenXmlFormats.Wordprocessing;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using NPOI.Util;
using NPOI.OpenXmlFormats.Dml;
using System.Xml.Serialization;
using NPOI.OpenXmlFormats.Dml.WordProcessing;
using NPOI.WP.UserModel;
/**
* @see <a href="http://msdn.microsoft.com/en-us/library/ff533743(v=office.12).aspx">[MS-OI29500] Run Fonts</a>
*/
public enum FontCharRange
{
None,
Ascii /* char 0-127 */,
CS /* complex symbol */,
EastAsia /* east asia */,
HAnsi /* high ansi */
};
/**
* XWPFrun.object defines a region of text with a common Set of properties
*
* @author Yegor Kozlov
* @author Gregg Morris (gregg dot morris at gmail dot com) - added getColor(), setColor()
*/
public class XWPFRun : ISDTContents, IRunElement, ICharacterRun
{
private CT_R run;
private String pictureText;
//private XWPFParagraph paragraph;
private IRunBody parent;
private List<XWPFPicture> pictures;
/**
* @param r the CT_R bean which holds the run.attributes
* @param p the parent paragraph
*/
public XWPFRun(CT_R r, IRunBody p)
{
this.run = r;
this.parent = p;
/**
* reserve already occupied Drawing ids, so reserving new ids later will
* not corrupt the document
*/
IList<CT_Drawing> drawingList = r.GetDrawingList();
foreach (CT_Drawing ctDrawing in drawingList)
{
List<CT_Anchor> anchorList = ctDrawing.GetAnchorList();
foreach (CT_Anchor anchor in anchorList)
{
if (anchor.docPr != null)
{
this.Document.DrawingIdManager.Reserve(anchor.docPr.id);
}
}
List<CT_Inline> inlineList = ctDrawing.GetInlineList();
foreach (CT_Inline inline in inlineList)
{
if (inline.docPr != null)
{
this.Document.DrawingIdManager.Reserve(inline.docPr.id);
}
}
}
//// Look for any text in any of our pictures or Drawings
StringBuilder text = new StringBuilder();
List<object> pictTextObjs = new List<object>();
foreach (CT_Picture pic in r.GetPictList())
pictTextObjs.Add(pic);
foreach (CT_Drawing draw in drawingList)
pictTextObjs.Add(draw);
//foreach (object o in pictTextObjs)
//{
//todo:: imlement this
//XmlObject[] t = o.SelectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:t");
//for (int m = 0; m < t.Length; m++)
//{
// NodeList kids = t[m].DomNode.ChildNodes;
// for (int n = 0; n < kids.Length; n++)
// {
// if (kids.Item(n) is Text)
// {
// if (text.Length > 0)
// text.Append("\n");
// text.Append(kids.Item(n).NodeValue);
// }
// }
//}
//}
pictureText = text.ToString();
// Do we have any embedded pictures?
// (They're a different CT_Picture, under the Drawingml namespace)
pictures = new List<XWPFPicture>();
foreach (object o in pictTextObjs)
{
foreach (OpenXmlFormats.Dml.Picture.CT_Picture pict in GetCTPictures(o))
{
XWPFPicture picture = new XWPFPicture(pict, this);
pictures.Add(picture);
}
}
}
/**
* @deprecated Use {@link XWPFRun#XWPFRun(CTR, IRunBody)}
*/
[Obsolete("Use XWPFRun(CTR, IRunBody)")]
public XWPFRun(CT_R r, XWPFParagraph p)
: this(r, (IRunBody)p)
{
}
private List<NPOI.OpenXmlFormats.Dml.Picture.CT_Picture> GetCTPictures(object o)
{
List<NPOI.OpenXmlFormats.Dml.Picture.CT_Picture> pictures = new List<NPOI.OpenXmlFormats.Dml.Picture.CT_Picture>();
//XmlObject[] picts = o.SelectPath("declare namespace pic='"+CT_Picture.type.Name.NamespaceURI+"' .//pic:pic");
//XmlElement[] picts = o.Any;
//foreach (XmlElement pict in picts)
//{
//if(pict is XmlAnyTypeImpl) {
// // Pesky XmlBeans bug - see Bugzilla #49934
// try {
// pict = CT_Picture.Factory.Parse( pict.ToString() );
// } catch(XmlException e) {
// throw new POIXMLException(e);
// }
//}
//if (pict is NPOI.OpenXmlFormats.Dml.CT_Picture)
//{
// pictures.Add((NPOI.OpenXmlFormats.Dml.CT_Picture)pict);
//}
//}
if (o is CT_Drawing)
{
CT_Drawing drawing = o as CT_Drawing;
if (drawing.inline != null)
{
foreach (CT_Inline inline in drawing.inline)
{
GetPictures(inline.graphic.graphicData, pictures);
}
}
}
else if (o is CT_GraphicalObjectData)
{
GetPictures(o as CT_GraphicalObjectData, pictures);
}
return pictures;
}
private void GetPictures(CT_GraphicalObjectData god, List<NPOI.OpenXmlFormats.Dml.Picture.CT_Picture> pictures)
{
XmlSerializer xmlse = new XmlSerializer(typeof(NPOI.OpenXmlFormats.Dml.Picture.CT_Picture));
foreach (string el in god.Any)
{
System.IO.StringReader stringReader = new System.IO.StringReader(el);
NPOI.OpenXmlFormats.Dml.Picture.CT_Picture pict =
xmlse.Deserialize(System.Xml.XmlReader.Create(stringReader)) as NPOI.OpenXmlFormats.Dml.Picture.CT_Picture;
pictures.Add(pict);
}
}
/**
* Get the currently used CT_R object
* @return CT_R object
*/
public CT_R GetCTR()
{
return run;
}
/**
* Get the currently referenced paragraph/SDT object
* @return current parent
*/
public IRunBody Parent
{
get
{
return parent;
}
}
/**
* Get the currently referenced paragraph, or null if a SDT object
* @deprecated use {@link XWPFRun#getParent()} instead
*/
public XWPFParagraph Paragraph
{
get
{
if (parent is XWPFParagraph)
return (XWPFParagraph)parent;
return null;
}
}
/**
* @return The {@link XWPFDocument} instance, this run.belongs to, or
* <code>null</code> if parent structure (paragraph > document) is not properly Set.
*/
public XWPFDocument Document
{
get
{
if (parent != null)
{
return parent.Document;
}
return null;
}
}
/**
* For isBold, isItalic etc
*/
private bool IsCTOnOff(CT_OnOff onoff)
{
if (!onoff.IsSetVal())
return true;
//CT_OnOff.val is a boolean field, and parse "1","-1","true","on" valus as true.
//see CT_OnOff.Parse(XmlNode, XmlNamespaceManager)
return onoff.val;
}
/**
* Whether the bold property shall be applied to all non-complex script
* characters in the contents of this run.when displayed in a document.
* <p>
* This formatting property is a toggle property, which specifies that its
* behavior differs between its use within a style defInition and its use as
* direct formatting. When used as part of a style defInition, Setting this
* property shall toggle the current state of that property as specified up
* to this point in the hierarchy (i.e. applied to not applied, and vice
* versa). Setting it to <code>false</code> (or an equivalent) shall
* result in the current Setting remaining unChanged. However, when used as
* direct formatting, Setting this property to true or false shall Set the
* absolute state of the resulting property.
* </p>
* <p>
* If this element is not present, the default value is to leave the
* formatting applied at previous level in the style hierarchy. If this
* element is never applied in the style hierarchy, then bold shall not be
* applied to non-complex script characters.
* </p>
*
* @param value <code>true</code> if the bold property is applied to
* this run
*/
public bool IsBold
{
get
{
CT_RPr pr = run.rPr;
if (pr == null || !pr.IsSetB())
{
return false;
}
return IsCTOnOff(pr.b);
}
set
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_OnOff bold = pr.IsSetB() ? pr.b : pr.AddNewB();
bold.val = value;
}
}
/**
* Get text color. The returned value is a string in the hex form "RRGGBB".
*/
public String GetColor()
{
String color = null;
if (run.IsSetRPr())
{
CT_RPr pr = run.rPr;
if (pr.IsSetColor())
{
NPOI.OpenXmlFormats.Wordprocessing.CT_Color clr = pr.color;
color = clr.val; //clr.xgetVal().getStringValue();
}
}
return color;
}
/**
* Set text color.
* @param rgbStr - the desired color, in the hex form "RRGGBB".
*/
public void SetColor(String rgbStr)
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
NPOI.OpenXmlFormats.Wordprocessing.CT_Color color = pr.IsSetColor() ? pr.color : pr.AddNewColor();
color.val = (rgbStr);
}
/**
* Return the string content of this text run
*
* @return the text of this text run.or <code>null</code> if not Set
*/
public String GetText(int pos)
{
return run.SizeOfTArray() == 0 ? null : run.GetTArray(pos).Value;
}
/**
* Returns text embedded in pictures
*/
public String PictureText
{
get
{
return pictureText;
}
}
public void ReplaceText(string oldText, string newText)
{
string text = this.Text.Replace(oldText, newText);
this.SetText(text);
}
/// <summary>
///Sets the text of this text run
/// </summary>
/// <param name="value">the literal text which shall be displayed in the document</param>
public void SetText(String value)
{
SetText(value, 0);
}
public void AppendText(String value)
{
SetText(value, run.GetTList().Count);
}
/// <summary>
/// Sets the text of this text run.in the
/// </summary>
/// <param name="value">the literal text which shall be displayed in the document</param>
/// <param name="pos">position in the text array (NB: 0 based)</param>
public void SetText(String value, int pos)
{
int length = run.SizeOfTArray();
if (pos > length) throw new IndexOutOfRangeException("Value too large for the parameter position");
CT_Text t = (pos < length && pos >= 0) ? run.GetTArray(pos): run.AddNewT();
t.Value = (value);
preserveSpaces(t);
}
/**
* Whether the italic property should be applied to all non-complex script
* characters in the contents of this run.when displayed in a document.
*
* @return <code>true</code> if the italic property is applied
*/
public bool IsItalic
{
get
{
CT_RPr pr = run.rPr;
if (pr == null || !pr.IsSetI())
return false;
return IsCTOnOff(pr.i);
}
set
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_OnOff italic = pr.IsSetI() ? pr.i : pr.AddNewI();
italic.val = value;
}
}
/**
* Specifies that the contents of this run.should be displayed along with an
* underline appearing directly below the character heigh
*
* @return the Underline pattern Applyed to this run
* @see UnderlinePatterns
*/
public UnderlinePatterns Underline
{
get
{
CT_RPr pr = run.rPr;
return (pr != null && pr.IsSetU() && pr.u.val != null) ?
EnumConverter.ValueOf<UnderlinePatterns, ST_Underline>(pr.u.val) : UnderlinePatterns.None;
}
}
internal void InsertText(CT_Text text, int textIndex)
{
run.GetTList().Insert(textIndex, text);
}
/// <summary>
/// insert text at start index in the run
/// </summary>
/// <param name="text">insert text</param>
/// <param name="startIndex">start index of the insertion in the run text</param>
public void InsertText(string text, int startIndex)
{
List<CT_Text> texts = run.GetTList();
int endPos = 0;
int startPos = 0;
for (int i = 0; i < texts.Count; i++)
{
startPos = endPos;
endPos += texts[i].Value.Length;
if (endPos > startIndex)
{
texts[i].Value = texts[i].Value.Insert(startIndex - startPos, text);
break;
}
}
}
public string Text
{
get
{
StringBuilder text = new StringBuilder();
for (int i = 0; i < run.Items.Count; i++)
{
object o = run.Items[i];
if (o is CT_Text)
{
if (!(run.ItemsElementName[i] == RunItemsChoiceType.instrText))
{
text.Append(((CT_Text)o).Value);
}
}
// Complex type evaluation (currently only for extraction of check boxes)
if (o is CT_FldChar)
{
CT_FldChar ctfldChar = ((CT_FldChar)o);
if (ctfldChar.fldCharType == ST_FldCharType.begin)
{
if (ctfldChar.ffData != null)
{
foreach (CT_FFCheckBox checkBox in ctfldChar.ffData.GetCheckBoxList())
{
if (checkBox.@default.val == true)
{
text.Append("|X|");
}
else
{
text.Append("|_|");
}
}
}
}
}
if (o is CT_PTab)
{
text.Append("\t");
}
if (o is CT_Br)
{
text.Append("\n");
}
if (o is CT_Empty)
{
// Some inline text elements Get returned not as
// themselves, but as CTEmpty, owing to some odd
// defInitions around line 5642 of the XSDs
// This bit works around it, and replicates the above
// rules for that case
if (run.ItemsElementName[i] == RunItemsChoiceType.tab)
{
text.Append("\t");
}
if (run.ItemsElementName[i] == RunItemsChoiceType.br)
{
text.Append("\n");
}
if (run.ItemsElementName[i] == RunItemsChoiceType.cr)
{
text.Append("\n");
}
}
if (o is CT_FtnEdnRef)
{
CT_FtnEdnRef ftn = (CT_FtnEdnRef)o;
String footnoteRef = ftn.DomNode.LocalName.Equals("footnoteReference") ?
"[footnoteRef:" + ftn.id + "]" : "[endnoteRef:" + ftn.id + "]";
text.Append(footnoteRef);
}
}
// Any picture text?
if (pictureText != null && pictureText.Length > 0)
{
text.Append("\n").Append(pictureText);
}
return text.ToString();
}
}
/**
* Specifies that the contents of this run.should be displayed along with an
* underline appearing directly below the character heigh
* If this element is not present, the default value is to leave the
* formatting applied at previous level in the style hierarchy. If this
* element is never applied in the style hierarchy, then an underline shall
* not be applied to the contents of this run.
*
* @param value -
* underline type
* @see UnderlinePatterns : all possible patterns that could be applied
*/
public void SetUnderline(UnderlinePatterns value)
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_Underline underline = (pr.u == null) ? pr.AddNewU() : pr.u;
underline.val = EnumConverter.ValueOf<ST_Underline, UnderlinePatterns>(value);
}
/**
* Specifies that the contents of this run.shall be displayed with a single
* horizontal line through the center of the line.
*
* @return <code>true</code> if the strike property is applied
*/
public bool IsStrikeThrough
{
get
{
CT_RPr pr = run.rPr;
if (pr == null || !pr.IsSetStrike())
return false;
return IsCTOnOff(pr.strike);
}
set
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_OnOff strike = pr.IsSetStrike() ? pr.strike : pr.AddNewStrike();
strike.val = value;//(value ? ST_OnOff.True : ST_OnOff.False);
}
}
/**
* Specifies that the contents of this run.shall be displayed with a single
* horizontal line through the center of the line.
* <p>
* This formatting property is a toggle property, which specifies that its
* behavior differs between its use within a style defInition and its use as
* direct formatting. When used as part of a style defInition, Setting this
* property shall toggle the current state of that property as specified up
* to this point in the hierarchy (i.e. applied to not applied, and vice
* versa). Setting it to false (or an equivalent) shall result in the
* current Setting remaining unChanged. However, when used as direct
* formatting, Setting this property to true or false shall Set the absolute
* state of the resulting property.
* </p>
* <p>
* If this element is not present, the default value is to leave the
* formatting applied at previous level in the style hierarchy. If this
* element is never applied in the style hierarchy, then strikethrough shall
* not be applied to the contents of this run.
* </p>
*
* @param value <code>true</code> if the strike property is applied to
* this run
*/
[Obsolete]
public bool IsStrike
{
get
{
return IsStrikeThrough;
}
set
{
IsStrikeThrough = value;
}
}
/**
* Specifies that the contents of this run shall be displayed with a double
* horizontal line through the center of the line.
*
* @return <code>true</code> if the double strike property is applied
*/
public bool IsDoubleStrikeThrough
{
get
{
CT_RPr pr = run.rPr;
if (pr == null || !pr.IsSetDstrike())
return false;
return IsCTOnOff(pr.dstrike);
}
set
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_OnOff dstrike = pr.IsSetDstrike() ? pr.dstrike : pr.AddNewDstrike();
dstrike.val = value;//(value ? STOnOff.TRUE : STOnOff.FALSE);
}
}
public bool IsSmallCaps
{
get
{
CT_RPr pr = run.rPr;
if (pr == null || !pr.IsSetSmallCaps())
return false;
return IsCTOnOff(pr.smallCaps);
}
set
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_OnOff caps = pr.IsSetSmallCaps() ? pr.smallCaps : pr.AddNewSmallCaps();
caps.val = value;//(value ? ST_OnOff.True : ST_OnOff.False);
}
}
public bool IsCapitalized
{
get
{
CT_RPr pr = run.rPr;
if (pr == null || !pr.IsSetCaps())
return false;
return IsCTOnOff(pr.caps);
}
set
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_OnOff caps = pr.IsSetCaps() ? pr.caps : pr.AddNewCaps();
caps.val = value;//(value ? ST_OnOff.True : ST_OnOff.False);
}
}
public bool IsShadowed
{
get
{
CT_RPr pr = run.rPr;
if (pr == null || !pr.IsSetShadow())
return false;
return IsCTOnOff(pr.shadow);
}
set
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_OnOff shadow = pr.IsSetShadow() ? pr.shadow : pr.AddNewShadow();
shadow.val = value;//(value ? ST_OnOff.True : ST_OnOff.False);
}
}
public bool IsImprinted
{
get
{
CT_RPr pr = run.rPr;
if (pr == null || !pr.IsSetImprint())
return false;
return IsCTOnOff(pr.imprint);
}
set
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_OnOff imprinted = pr.IsSetImprint() ? pr.imprint : pr.AddNewImprint();
imprinted.val = value;//(value ? ST_OnOff.True : ST_OnOff.False);
}
}
public bool IsEmbossed
{
get
{
CT_RPr pr = run.rPr;
if (pr == null || !pr.IsSetEmboss())
return false;
return IsCTOnOff(pr.emboss);
}
set
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_OnOff emboss = pr.IsSetEmboss() ? pr.emboss : pr.AddNewEmboss();
emboss.val = value;//(value ? ST_OnOff.True : ST_OnOff.False);
}
}
[Obsolete]
public void SetStrike(bool value)
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_OnOff strike = pr.IsSetStrike() ? pr.strike : pr.AddNewStrike();
strike.val = value;
}
/**
* Specifies the alignment which shall be applied to the contents of this
* run.in relation to the default appearance of the run.s text.
* This allows the text to be repositioned as subscript or superscript without
* altering the font size of the run.properties.
*
* @return VerticalAlign
* @see VerticalAlign all possible value that could be Applyed to this run
*/
public VerticalAlign Subscript
{
get
{
CT_RPr pr = run.rPr;
return (pr != null && pr.IsSetVertAlign()) ?
EnumConverter.ValueOf<VerticalAlign, ST_VerticalAlignRun>(pr.vertAlign.val) : VerticalAlign.BASELINE;
}
set
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_VerticalAlignRun ctValign = pr.IsSetVertAlign() ? pr.vertAlign : pr.AddNewVertAlign();
ctValign.val = EnumConverter.ValueOf<ST_VerticalAlignRun, VerticalAlign>(value);
}
}
public int Kerning
{
get
{
CT_RPr pr = run.rPr;
if (pr == null || !pr.IsSetKern())
return 0;
return (int)pr.kern.val;
}
set
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_HpsMeasure kernmes = pr.IsSetKern() ? pr.kern : pr.AddNewKern();
kernmes.val = (ulong)value;
}
}
public bool IsHighlighted
{
get
{
CT_RPr pr = run.rPr;
if (pr == null || !pr.IsSetHighlight())
return false;
if (pr.highlight.val == ST_HighlightColor.none)
return false;
return true;
}
}
// TODO Provide a wrapper round STHighlightColor, then expose getter/setter
// for the highlight colour. Ideally also then add to CharacterRun interface
public int CharacterSpacing
{
get
{
CT_RPr pr = run.rPr;
if (pr == null || !pr.IsSetSpacing())
return 0;
return int.Parse(pr.spacing.val);
}
set
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_SignedTwipsMeasure spc = pr.IsSetSpacing() ? pr.spacing : pr.AddNewSpacing();
spc.val = value.ToString();
}
}
/**
* Specifies the fonts which shall be used to display the text contents of
* this run. Specifies a font which shall be used to format all characters
* in the ASCII range (0 - 127) within the parent run
*
* @return a string representing the font family
*/
public String FontFamily
{
get
{
return GetFontFamily(FontCharRange.None);
}
set
{
SetFontFamily(value, FontCharRange.None);
}
}
public string FontName
{
get { return FontFamily; }
}
/**
* Gets the font family for the specified font char range.
* If fcr is null, the font char range "ascii" is used
*
* @param fcr the font char range, defaults to "ansi"
* @return a string representing the font famil
*/
public String GetFontFamily(FontCharRange fcr)
{
CT_RPr pr = run.rPr;
if (pr == null || !pr.IsSetRFonts()) return null;
CT_Fonts fonts = pr.rFonts;
switch (fcr == FontCharRange.None ? FontCharRange.Ascii : fcr)
{
default:
case FontCharRange.Ascii:
return fonts.ascii;
case FontCharRange.CS:
return fonts.cs;
case FontCharRange.EastAsia:
return fonts.eastAsia;
case FontCharRange.HAnsi:
return fonts.hAnsi;
}
}
/**
* Specifies the fonts which shall be used to display the text contents of
* this run. The default handling for fcr == null is to overwrite the
* ascii font char range with the given font family and also set all not
* specified font ranges
*
* @param fontFamily
* @param fcr FontCharRange or null for default handling
*/
public void SetFontFamily(String fontFamily, FontCharRange fcr)
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_Fonts fonts = pr.IsSetRFonts() ? pr.rFonts : pr.AddNewRFonts();
if (fcr == FontCharRange.None)
{
fonts.ascii = (fontFamily);
if (!fonts.IsSetHAnsi())
{
fonts.hAnsi = (fontFamily);
}
if (!fonts.IsSetCs())
{
fonts.cs = (fontFamily);
}
if (!fonts.IsSetEastAsia())
{
fonts.eastAsia = (fontFamily);
}
}
else
{
switch (fcr)
{
case FontCharRange.Ascii:
fonts.ascii = (fontFamily);
break;
case FontCharRange.CS:
fonts.cs = (fontFamily);
break;
case FontCharRange.EastAsia:
fonts.eastAsia = (fontFamily);
break;
case FontCharRange.HAnsi:
fonts.hAnsi = (fontFamily);
break;
}
}
}
/**
* Specifies the font size which shall be applied to all non complex script
* characters in the contents of this run.when displayed.
*
* @return value representing the font size
*/
public int FontSize
{
get
{
CT_RPr pr = run.rPr;
return (pr != null && pr.IsSetSz()) ? (int)(pr.sz.val / 2) : -1;
}
set
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_HpsMeasure ctSize = pr.IsSetSz() ? pr.sz : pr.AddNewSz();
ctSize.val = (ulong)value * 2;
}
}
/**
* This element specifies the amount by which text shall be raised or
* lowered for this run.in relation to the default baseline of the
* surrounding non-positioned text. This allows the text to be repositioned
* without altering the font size of the contents.
*
* If the val attribute is positive, then the parent run.shall be raised
* above the baseline of the surrounding text by the specified number of
* half-points. If the val attribute is negative, then the parent run.shall
* be lowered below the baseline of the surrounding text by the specified
* number of half-points.
* *
* If this element is not present, the default value is to leave the
* formatting applied at previous level in the style hierarchy. If this
* element is never applied in the style hierarchy, then the text shall not
* be raised or lowered relative to the default baseline location for the
* contents of this run.
*
* @return a big integer representing the amount of text shall be "moved"
*/
public int TextPosition
{
get
{
CT_RPr pr = run.rPr;
return (pr != null && pr.IsSetPosition()) ? int.Parse(pr.position.val)
: -1;
}
set
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_SignedHpsMeasure position = pr.IsSetPosition() ? pr.position : pr.AddNewPosition();
position.val = (value.ToString());
}
}
/**
*
*/
public void RemoveBreak()
{
// TODO
}
/**
* Specifies that a break shall be placed at the current location in the run
* content.
* A break is a special character which is used to override the
* normal line breaking that would be performed based on the normal layout
* of the document's contents.
* @see #AddCarriageReturn()
*/
public void AddBreak()
{
run.AddNewBr();
}
/**
* Specifies that a break shall be placed at the current location in the run
* content.
* A break is a special character which is used to override the
* normal line breaking that would be performed based on the normal layout
* of the document's contents.
* <p>
* The behavior of this break character (the
* location where text shall be restarted After this break) shall be
* determined by its type values.
* </p>
* @see BreakType
*/
public void AddBreak(BreakType type)
{
CT_Br br = run.AddNewBr();
br.type = EnumConverter.ValueOf<ST_BrType, BreakType>(type);
}
/**
* Specifies that a break shall be placed at the current location in the run
* content. A break is a special character which is used to override the
* normal line breaking that would be performed based on the normal layout
* of the document's contents.
* <p>
* The behavior of this break character (the
* location where text shall be restarted After this break) shall be
* determined by its type (in this case is BreakType.TEXT_WRAPPING as default) and clear attribute values.
* </p>
* @see BreakClear
*/
public void AddBreak(BreakClear Clear)
{
CT_Br br = run.AddNewBr();
br.type = EnumConverter.ValueOf<ST_BrType, BreakType>(BreakType.TEXTWRAPPING);
br.clear = EnumConverter.ValueOf<ST_BrClear, BreakClear>(Clear);
}
/**
* Specifies that a tab shall be placed at the current location in
* the run content.
*/
public void AddTab()
{
run.AddNewTab();
}
public void RemoveTab()
{
//TODO
}
/**
* Specifies that a carriage return shall be placed at the
* current location in the run.content.
* A carriage return is used to end the current line of text in
* WordProcess.
* The behavior of a carriage return in run.content shall be
* identical to a break character with null type and clear attributes, which
* shall end the current line and find the next available line on which to
* continue.
* The carriage return character forced the following text to be
* restarted on the next available line in the document.
*/
public void AddCarriageReturn()
{
run.AddNewCr();
}
public void RemoveCarriageReturn(int i)
{
throw new NotImplementedException();
}
XWPFPicture AddPicture(Stream pictureData, int pictureType, String filename, int width, int height, Action<XWPFDocument, CT_Blip> extAct)
{
// Add the picture + relationship
String relationId;
XWPFPictureData picData;
XWPFDocument doc=null;
// Work out what to add the picture to, then add both the
// picture and the relationship for it
// TODO Should we have an interface for this sort of thing?
if (parent.Part is XWPFHeaderFooter)
{
XWPFHeaderFooter headerFooter = (XWPFHeaderFooter)parent.Part;
relationId = headerFooter.AddPictureData(pictureData, pictureType);
picData = (XWPFPictureData)headerFooter.GetRelationById(relationId);
}
else
{
doc = parent.Document;
relationId = doc.AddPictureData(pictureData, pictureType);
picData = (XWPFPictureData)doc.GetRelationById(relationId);
}
try
{
// Create the Drawing entry for it
CT_Drawing Drawing = run.AddNewDrawing();
CT_Inline inline = Drawing.AddNewInline();
// Do the fiddly namespace bits on the inline
// (We need full control of what goes where and as what)
//CT_GraphicalObject tmp = new CT_GraphicalObject();
//String xml =
// "<a:graphic xmlns:a=\"" + "http://schemas.openxmlformats.org/drawingml/2006/main" + "\">" +
// "<a:graphicData uri=\"" + "http://schemas.openxmlformats.org/drawingml/2006/picture" + "\">" +
// "<pic:pic xmlns:pic=\"" + "http://schemas.openxmlformats.org/drawingml/2006/picture" + "\" />" +
// "</a:graphicData>" +
// "</a:graphic>";
//InputSource is = new InputSource(new StringReader(xml));
//org.w3c.dom.Document doc = DocumentHelper.readDocument(is);
//inline.set(XmlToken.Factory.parse(doc.getDocumentElement(), DEFAULT_XML_OPTIONS));
inline.graphic = new CT_GraphicalObject();
inline.graphic.graphicData = new CT_GraphicalObjectData();
inline.graphic.graphicData.uri = "http://schemas.openxmlformats.org/drawingml/2006/picture";
// Setup the inline
inline.distT = (0);
inline.distR = (0);
inline.distB = (0);
inline.distL = (0);
NPOI.OpenXmlFormats.Dml.WordProcessing.CT_NonVisualDrawingProps docPr = inline.AddNewDocPr();
long id = parent.Document.DrawingIdManager.ReserveNew();
docPr.id = (uint)(id);
/* This name is not visible in Word 2010 anywhere. */
docPr.name = ("Drawing " + id);
docPr.descr = (filename);
NPOI.OpenXmlFormats.Dml.WordProcessing.CT_PositiveSize2D extent = inline.AddNewExtent();
extent.cx = (width);
extent.cy = (height);
// Grab the picture object
NPOI.OpenXmlFormats.Dml.Picture.CT_Picture pic = new OpenXmlFormats.Dml.Picture.CT_Picture();
// Set it up
NPOI.OpenXmlFormats.Dml.Picture.CT_PictureNonVisual nvPicPr = pic.AddNewNvPicPr();
NPOI.OpenXmlFormats.Dml.CT_NonVisualDrawingProps cNvPr = nvPicPr.AddNewCNvPr();
/* use "0" for the id. See ECM-576, 20.2.2.3 */
cNvPr.id = (0);
/* This name is not visible in Word 2010 anywhere */
cNvPr.name = ("Picture " + id);
cNvPr.descr = (filename);
CT_NonVisualPictureProperties cNvPicPr = nvPicPr.AddNewCNvPicPr();
cNvPicPr.AddNewPicLocks().noChangeAspect = true;
CT_BlipFillProperties blipFill = pic.AddNewBlipFill();
CT_Blip blip = blipFill.AddNewBlip();
blip.embed = (picData.GetPackageRelationship().Id);
if (doc != null)
{
extAct(doc, blip);
}
blipFill.AddNewStretch().AddNewFillRect();
CT_ShapeProperties spPr = pic.AddNewSpPr();
CT_Transform2D xfrm = spPr.AddNewXfrm();
CT_Point2D off = xfrm.AddNewOff();
off.x = (0);
off.y = (0);
NPOI.OpenXmlFormats.Dml.CT_PositiveSize2D ext = xfrm.AddNewExt();
ext.cx = (width);
ext.cy = (height);
CT_PresetGeometry2D prstGeom = spPr.AddNewPrstGeom();
prstGeom.prst = (ST_ShapeType.rect);
prstGeom.AddNewAvLst();
using (var ms = new MemoryStream())
{
StreamWriter sw = new StreamWriter(ms);
pic.Write(sw, "pic:pic");
sw.Flush();
ms.Position = 0;
var sr = new StreamReader(ms);
var picXml = sr.ReadToEnd();
inline.graphic.graphicData.AddPicElement(picXml);
}
// Finish up
XWPFPicture xwpfPicture = new XWPFPicture(pic, this);
pictures.Add(xwpfPicture);
return xwpfPicture;
}
catch(XmlException e)
{
throw new InvalidOperationException("XWPFRun.Addpicture error", e);
}
}
public XWPFPicture AddSvg(Stream svgData, Stream altPictureData, int altPictureType, String filename, int width, int height)
{
return AddPicture(altPictureData, altPictureType, filename, width, height, (doc, blip) =>
{
String relationId = doc.AddPictureData(svgData, (int)PictureType.SVG);
XWPFPictureData picData = (XWPFPictureData)doc.GetRelationById(relationId);
var extLst = new CT_OfficeArtExtensionList();
var extItem = new CT_OfficeArtExtension();
extItem.uri = "{96DAC541-7B7A-43D3-8B79-37D633B846F1}";
extItem.Any = "<asvg:svgBlip xmlns:asvg=\"http://schemas.microsoft.com/office/drawing/2016/SVG/main\" r:embed=\"" + picData.GetPackageRelationship().Id + "\"/>";
extLst.ext.Add(extItem);
blip.extLst = extLst;
});
}
/**
* Adds a picture to the run. This method handles
* attaching the picture data to the overall file.
*
* @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_EMF
* @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_WMF
* @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_PICT
* @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_JPEG
* @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_PNG
* @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_DIB
*
* @param pictureData The raw picture data
* @param pictureType The type of the picture, eg {@link Document#PICTURE_TYPE_JPEG}
* @param width width in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}
* @param height height in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}
* @throws NPOI.Openxml4j.exceptions.InvalidFormatException
* @throws IOException
*/
public XWPFPicture AddPicture(Stream pictureData, int pictureType, String filename, int width, int height)
{
return AddPicture(pictureData, pictureType, filename, width, height, (doc, blip) => { });
}
/**
* Returns the embedded pictures of the run. These
* are pictures which reference an external,
* embedded picture image such as a .png or .jpg
*/
public List<XWPFPicture> GetEmbeddedPictures()
{
return pictures;
}
/**
* Add the xml:spaces="preserve" attribute if the string has leading or trailing white spaces
*
* @param xs the string to check
*/
static void preserveSpaces(CT_Text xs)
{
String text = xs.Value;
if (text != null && (text.StartsWith(" ") || text.EndsWith(" ")))
{
// XmlCursor c = xs.NewCursor();
// c.ToNextToken();
// c.InsertAttributeWithValue(new QName("http://www.w3.org/XML/1998/namespace", "space"), "preserve");
// c.Dispose();
xs.space = "preserve";
}
}
/**
* Returns the string version of the text, with tabs and
* carriage returns in place of their xml equivalents.
*/
public override String ToString()
{
return Text;
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// ScreenManager.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using System.Text;
#endregion
namespace RolePlaying
{
/// <summary>
/// The screen manager is a component which manages one or more GameScreen
/// instances. It maintains a stack of screens, calls their Update and Draw
/// methods at the appropriate times, and automatically routes input to the
/// topmost active screen.
/// </summary>
/// <remarks>
/// Similar to a class found in the Game State Management sample on the
/// XNA Creators Club Online website (http://creators.xna.com).
/// </remarks>
public class ScreenManager : DrawableGameComponent
{
#region Fields
List<GameScreen> screens = new List<GameScreen>();
List<GameScreen> screensToUpdate = new List<GameScreen>();
SpriteBatch spriteBatch;
bool isInitialized;
#endregion
#region Properties
/// <summary>
/// A default SpriteBatch shared by all the screens. This saves
/// each screen having to bother creating their own local instance.
/// </summary>
public SpriteBatch SpriteBatch
{
get { return spriteBatch; }
}
#endregion
#region Initialization
/// <summary>
/// Constructs a new screen manager component.
/// </summary>
public ScreenManager(Game game)
: base(game)
{
}
/// <summary>
/// Initializes the screen manager component.
/// </summary>
public override void Initialize()
{
base.Initialize();
isInitialized = true;
}
/// <summary>
/// Load your graphics content.
/// </summary>
protected override void LoadContent()
{
// Load content belonging to the screen manager.
ContentManager content = Game.Content;
spriteBatch = new SpriteBatch(GraphicsDevice);
// Tell each of the screens to load their content.
foreach (GameScreen screen in screens)
{
screen.LoadContent();
}
}
/// <summary>
/// Unload your graphics content.
/// </summary>
protected override void UnloadContent()
{
// Tell each of the screens to unload their content.
foreach (GameScreen screen in screens)
{
screen.UnloadContent();
}
}
#endregion
#region Update and Draw
/// <summary>
/// Allows each screen to run logic.
/// </summary>
public override void Update(GameTime gameTime)
{
// Make a copy of the master screen list, to avoid confusion if
// the process of updating one screen adds or removes others.
screensToUpdate.Clear();
foreach (GameScreen screen in screens)
screensToUpdate.Add(screen);
bool otherScreenHasFocus = !Game.IsActive;
bool coveredByOtherScreen = false;
// Loop as long as there are screens waiting to be updated.
while (screensToUpdate.Count > 0)
{
// Pop the topmost screen off the waiting list.
GameScreen screen = screensToUpdate[screensToUpdate.Count - 1];
screensToUpdate.RemoveAt(screensToUpdate.Count - 1);
// Update the screen.
screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
if (screen.ScreenState == ScreenState.TransitionOn ||
screen.ScreenState == ScreenState.Active)
{
// If this is the first active screen we came across,
// give it a chance to handle input.
if (!otherScreenHasFocus)
{
screen.HandleInput();
otherScreenHasFocus = true;
}
// If this is an active non-popup, inform any subsequent
// screens that they are covered by it.
if (!screen.IsPopup)
coveredByOtherScreen = true;
}
}
}
/// <summary>
/// Tells each screen to draw itself.
/// </summary>
public override void Draw(GameTime gameTime)
{
foreach (GameScreen screen in screens)
{
if (screen.ScreenState == ScreenState.Hidden)
continue;
screen.Draw(gameTime);
}
}
#endregion
#region Public Methods
/// <summary>
/// Adds a new screen to the screen manager.
/// </summary>
public void AddScreen(GameScreen screen)
{
screen.ScreenManager = this;
screen.IsExiting = false;
// If we have a graphics device, tell the screen to load content.
if (isInitialized)
{
screen.LoadContent();
}
screens.Add(screen);
}
/// <summary>
/// Removes a screen from the screen manager. You should normally
/// use GameScreen.ExitScreen instead of calling this directly, so
/// the screen can gradually transition off rather than just being
/// instantly removed.
/// </summary>
public void RemoveScreen(GameScreen screen)
{
// If we have a graphics device, tell the screen to unload content.
if (isInitialized)
{
screen.UnloadContent();
}
screens.Remove(screen);
screensToUpdate.Remove(screen);
}
/// <summary>
/// Expose an array holding all the screens. We return a copy rather
/// than the real master list, because screens should only ever be added
/// or removed using the AddScreen and RemoveScreen methods.
/// </summary>
public GameScreen[] GetScreens()
{
return screens.ToArray();
}
#endregion
}
}
| |
using J2N.Collections.Generic.Extensions;
using J2N.Numerics;
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.IO;
namespace Lucene.Net.Store
{
/*
* 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 CodecUtil = Lucene.Net.Codecs.CodecUtil;
using CorruptIndexException = Lucene.Net.Index.CorruptIndexException;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IOUtils = Lucene.Net.Util.IOUtils;
/// <summary>
/// Class for accessing a compound stream.
/// This class implements a directory, but is limited to only read operations.
/// Directory methods that would normally modify data throw an exception.
/// <para/>
/// All files belonging to a segment have the same name with varying extensions.
/// The extensions correspond to the different file formats used by the <see cref="Codecs.Codec"/>.
/// When using the Compound File format these files are collapsed into a
/// single <c>.cfs</c> file (except for the <see cref="Codecs.LiveDocsFormat"/>, with a
/// corresponding <c>.cfe</c> file indexing its sub-files.
/// <para/>
/// Files:
/// <list type="bullet">
/// <item><description><c>.cfs</c>: An optional "virtual" file consisting of all the other
/// index files for systems that frequently run out of file handles.</description></item>
/// <item><description><c>.cfe</c>: The "virtual" compound file's entry table holding all
/// entries in the corresponding .cfs file.</description></item>
/// </list>
/// <para>Description:</para>
/// <list type="bullet">
/// <item><description>Compound (.cfs) --> Header, FileData <sup>FileCount</sup></description></item>
/// <item><description>Compound Entry Table (.cfe) --> Header, FileCount, <FileName,
/// DataOffset, DataLength> <sup>FileCount</sup>, Footer</description></item>
/// <item><description>Header --> <see cref="CodecUtil.WriteHeader"/></description></item>
/// <item><description>FileCount --> <see cref="DataOutput.WriteVInt32"/></description></item>
/// <item><description>DataOffset,DataLength --> <see cref="DataOutput.WriteInt64"/></description></item>
/// <item><description>FileName --> <see cref="DataOutput.WriteString"/></description></item>
/// <item><description>FileData --> raw file data</description></item>
/// <item><description>Footer --> <see cref="CodecUtil.WriteFooter"/></description></item>
/// </list>
/// <para>Notes:</para>
/// <list type="bullet">
/// <item><description>FileCount indicates how many files are contained in this compound file.
/// The entry table that follows has that many entries.</description></item>
/// <item><description>Each directory entry contains a long pointer to the start of this file's data
/// section, the files length, and a <see cref="string"/> with that file's name.</description></item>
/// </list>
/// <para/>
/// @lucene.experimental
/// </summary>
public sealed class CompoundFileDirectory : BaseDirectory
{
/// <summary>
/// Offset/Length for a slice inside of a compound file </summary>
public sealed class FileEntry
{
internal long Offset { get; set; }
internal long Length { get; set; }
}
private readonly Directory directory;
private readonly string fileName;
private readonly int readBufferSize;
private readonly IDictionary<string, FileEntry> entries;
private readonly bool openForWrite;
private static readonly IDictionary<string, FileEntry> SENTINEL = Collections.EmptyMap<string, FileEntry>();
private readonly CompoundFileWriter writer;
private readonly IndexInputSlicer handle;
/// <summary>
/// Create a new <see cref="CompoundFileDirectory"/>.
/// </summary>
public CompoundFileDirectory(Directory directory, string fileName, IOContext context, bool openForWrite)
{
this.directory = directory;
this.fileName = fileName;
this.readBufferSize = BufferedIndexInput.GetBufferSize(context);
this.IsOpen = false;
this.openForWrite = openForWrite;
if (!openForWrite)
{
bool success = false;
handle = directory.CreateSlicer(fileName, context);
try
{
this.entries = ReadEntries(handle, directory, fileName);
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(handle);
}
}
this.IsOpen = true;
writer = null;
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(!(directory is CompoundFileDirectory), () => "compound file inside of compound file: " + fileName);
this.entries = SENTINEL;
this.IsOpen = true;
writer = new CompoundFileWriter(directory, fileName);
handle = null;
}
}
// LUCENENET NOTE: These MUST be sbyte because they can be negative
private static readonly sbyte CODEC_MAGIC_BYTE1 = (sbyte)CodecUtil.CODEC_MAGIC.TripleShift(24);
private static readonly sbyte CODEC_MAGIC_BYTE2 = (sbyte)CodecUtil.CODEC_MAGIC.TripleShift(16);
private static readonly sbyte CODEC_MAGIC_BYTE3 = (sbyte)CodecUtil.CODEC_MAGIC.TripleShift(8);
private static readonly sbyte CODEC_MAGIC_BYTE4 = (sbyte)CodecUtil.CODEC_MAGIC;
/// <summary>
/// Helper method that reads CFS entries from an input stream </summary>
private static IDictionary<string, FileEntry> ReadEntries(IndexInputSlicer handle, Directory dir, string name)
{
IOException priorE = null;
IndexInput stream = null;
ChecksumIndexInput entriesStream = null;
// read the first VInt. If it is negative, it's the version number
// otherwise it's the count (pre-3.1 indexes)
try
{
IDictionary<string, FileEntry> mapping;
#pragma warning disable 612, 618
stream = handle.OpenFullSlice();
#pragma warning restore 612, 618
int firstInt = stream.ReadVInt32();
// impossible for 3.0 to have 63 files in a .cfs, CFS writer was not visible
// and separate norms/etc are outside of cfs.
if (firstInt == CODEC_MAGIC_BYTE1)
{
sbyte secondByte = (sbyte)stream.ReadByte();
sbyte thirdByte = (sbyte)stream.ReadByte();
sbyte fourthByte = (sbyte)stream.ReadByte();
if (secondByte != CODEC_MAGIC_BYTE2 || thirdByte != CODEC_MAGIC_BYTE3 || fourthByte != CODEC_MAGIC_BYTE4)
{
throw new CorruptIndexException("Illegal/impossible header for CFS file: " + secondByte + "," + thirdByte + "," + fourthByte);
}
int version = CodecUtil.CheckHeaderNoMagic(stream, CompoundFileWriter.DATA_CODEC, CompoundFileWriter.VERSION_START, CompoundFileWriter.VERSION_CURRENT);
string entriesFileName = IndexFileNames.SegmentFileName(
IndexFileNames.StripExtension(name), "",
IndexFileNames.COMPOUND_FILE_ENTRIES_EXTENSION);
entriesStream = dir.OpenChecksumInput(entriesFileName, IOContext.READ_ONCE);
CodecUtil.CheckHeader(entriesStream, CompoundFileWriter.ENTRY_CODEC, CompoundFileWriter.VERSION_START, CompoundFileWriter.VERSION_CURRENT);
int numEntries = entriesStream.ReadVInt32();
mapping = new Dictionary<string, FileEntry>(numEntries);
for (int i = 0; i < numEntries; i++)
{
FileEntry fileEntry = new FileEntry();
string id = entriesStream.ReadString();
FileEntry previous = mapping.Put(id, fileEntry);
if (previous != null)
{
throw new CorruptIndexException("Duplicate cfs entry id=" + id + " in CFS: " + entriesStream);
}
fileEntry.Offset = entriesStream.ReadInt64();
fileEntry.Length = entriesStream.ReadInt64();
}
if (version >= CompoundFileWriter.VERSION_CHECKSUM)
{
CodecUtil.CheckFooter(entriesStream);
}
else
{
#pragma warning disable 612, 618
CodecUtil.CheckEOF(entriesStream);
#pragma warning restore 612, 618
}
}
else
{
// TODO remove once 3.x is not supported anymore
mapping = ReadLegacyEntries(stream, firstInt);
}
return mapping;
}
catch (IOException ioe)
{
priorE = ioe;
}
finally
{
IOUtils.DisposeWhileHandlingException(priorE, stream, entriesStream);
}
// this is needed until Java 7's real try-with-resources:
throw new InvalidOperationException("impossible to get here");
}
private static IDictionary<string, FileEntry> ReadLegacyEntries(IndexInput stream, int firstInt)
{
IDictionary<string, FileEntry> entries = new Dictionary<string, FileEntry>();
int count;
bool stripSegmentName;
if (firstInt < CompoundFileWriter.FORMAT_PRE_VERSION)
{
if (firstInt < CompoundFileWriter.FORMAT_NO_SEGMENT_PREFIX)
{
throw new CorruptIndexException("Incompatible format version: "
+ firstInt + " expected >= " + CompoundFileWriter.FORMAT_NO_SEGMENT_PREFIX + " (resource: " + stream + ")");
}
// It's a post-3.1 index, read the count.
count = stream.ReadVInt32();
stripSegmentName = false;
}
else
{
count = firstInt;
stripSegmentName = true;
}
// read the directory and init files
long streamLength = stream.Length;
FileEntry entry = null;
for (int i = 0; i < count; i++)
{
long offset = stream.ReadInt64();
if (offset < 0 || offset > streamLength)
{
throw new CorruptIndexException("Invalid CFS entry offset: " + offset + " (resource: " + stream + ")");
}
string id = stream.ReadString();
if (stripSegmentName)
{
// Fix the id to not include the segment names. this is relevant for
// pre-3.1 indexes.
id = IndexFileNames.StripSegmentName(id);
}
if (entry != null)
{
// set length of the previous entry
entry.Length = offset - entry.Offset;
}
entry = new FileEntry();
entry.Offset = offset;
FileEntry previous = entries.Put(id, entry);
if (previous != null)
{
throw new CorruptIndexException("Duplicate cfs entry id=" + id + " in CFS: " + stream);
}
}
// set the length of the final entry
if (entry != null)
{
entry.Length = streamLength - entry.Offset;
}
return entries;
}
public Directory Directory => directory;
public string Name => fileName;
protected override void Dispose(bool disposing)
{
lock (this)
{
if (disposing)
{
if (!IsOpen)
{
// allow double close - usually to be consistent with other closeables
return; // already closed
}
IsOpen = false;
if (writer != null)
{
if (Debugging.AssertsEnabled) Debugging.Assert(openForWrite);
writer.Dispose();
}
else
{
IOUtils.Dispose(handle);
}
}
}
}
public override IndexInput OpenInput(string name, IOContext context)
{
lock (this)
{
EnsureOpen();
if (Debugging.AssertsEnabled) Debugging.Assert(!openForWrite);
string id = IndexFileNames.StripSegmentName(name);
if (!entries.TryGetValue(id, out FileEntry entry) || entry == null)
{
throw new FileNotFoundException("No sub-file with id " + id +
" found (fileName=" + name + " files: " +
string.Format(J2N.Text.StringFormatter.InvariantCulture, "{0}", entries.Keys) + ")");
}
return handle.OpenSlice(name, entry.Offset, entry.Length);
}
}
/// <summary>
/// Returns an array of strings, one for each file in the directory. </summary>
public override string[] ListAll()
{
EnsureOpen();
string[] res;
if (writer != null)
{
res = writer.ListAll();
}
else
{
res = entries.Keys.ToArray();
// Add the segment name
string seg = IndexFileNames.ParseSegmentName(fileName);
for (int i = 0; i < res.Length; i++)
{
res[i] = seg + res[i];
}
}
return res;
}
/// <summary>
/// Returns true iff a file with the given name exists. </summary>
[Obsolete("this method will be removed in 5.0")]
public override bool FileExists(string name)
{
EnsureOpen();
if (this.writer != null)
{
return writer.FileExists(name);
}
return entries.ContainsKey(IndexFileNames.StripSegmentName(name));
}
/// <summary>
/// Not implemented </summary>
/// <exception cref="NotSupportedException"> always: not supported by CFS </exception>
public override void DeleteFile(string name)
{
throw new NotSupportedException();
}
/// <summary>
/// Not implemented </summary>
/// <exception cref="NotSupportedException"> always: not supported by CFS </exception>
public void RenameFile(string from, string to)
{
throw new NotSupportedException();
}
/// <summary>
/// Returns the length of a file in the directory. </summary>
/// <exception cref="IOException"> if the file does not exist </exception>
public override long FileLength(string name)
{
EnsureOpen();
if (this.writer != null)
{
return writer.FileLength(name);
}
FileEntry e = entries[IndexFileNames.StripSegmentName(name)];
if (e == null)
{
throw new FileNotFoundException(name);
}
return e.Length;
}
public override IndexOutput CreateOutput(string name, IOContext context)
{
EnsureOpen();
return writer.CreateOutput(name, context);
}
public override void Sync(ICollection<string> names)
{
throw new NotSupportedException();
}
/// <summary>
/// Not implemented </summary>
/// <exception cref="NotSupportedException"> always: not supported by CFS </exception>
public override Lock MakeLock(string name)
{
throw new NotSupportedException();
}
public override IndexInputSlicer CreateSlicer(string name, IOContext context)
{
EnsureOpen();
if (Debugging.AssertsEnabled) Debugging.Assert(!openForWrite);
string id = IndexFileNames.StripSegmentName(name);
if (!entries.TryGetValue(id, out FileEntry entry) || entry == null)
{
throw new FileNotFoundException("No sub-file with id " + id +
" found (fileName=" + name + " files: " +
string.Format(J2N.Text.StringFormatter.InvariantCulture, "{0}", entries.Keys) + ")");
}
return new IndexInputSlicerAnonymousInnerClassHelper(this, entry);
}
private class IndexInputSlicerAnonymousInnerClassHelper : IndexInputSlicer
{
private readonly CompoundFileDirectory outerInstance;
private FileEntry entry;
public IndexInputSlicerAnonymousInnerClassHelper(CompoundFileDirectory outerInstance, FileEntry entry)
{
this.outerInstance = outerInstance;
this.entry = entry;
}
protected override void Dispose(bool disposing)
{
}
public override IndexInput OpenSlice(string sliceDescription, long offset, long length)
{
return outerInstance.handle.OpenSlice(sliceDescription, entry.Offset + offset, length);
}
[Obsolete("Only for reading CFS files from 3.x indexes.")]
public override IndexInput OpenFullSlice()
{
return OpenSlice("full-slice", 0, entry.Length);
}
}
public override string ToString()
{
return "CompoundFileDirectory(file=\"" + fileName + "\" in dir=" + directory + ")";
}
}
}
| |
//This file has been modified.
//Josh: Most switch statements evaluating an Enum have been replaced with
// Enum.Parse
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email info@fyireporting.com |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* 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.Xml;
using System.IO;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace Reporting.Rdl
{
///<summary>
/// StyleInfo (borders, fonts, background, padding, ...)
///</summary>
public class StyleInfo: ICloneable
{
// note: all sizes are expressed as points
// _BorderColor
/// <summary>
/// Color of the left border
/// </summary>
public Color BColorLeft; // (Color) Color of the left border
/// <summary>
/// Color of the right border
/// </summary>
public Color BColorRight; // (Color) Color of the right border
/// <summary>
/// Color of the top border
/// </summary>
public Color BColorTop; // (Color) Color of the top border
/// <summary>
/// Color of the bottom border
/// </summary>
public Color BColorBottom; // (Color) Color of the bottom border
// _BorderStyle
/// <summary>
/// Style of the left border
/// </summary>
public BorderStyleEnum BStyleLeft; // (Enum BorderStyle) Style of the left border
/// <summary>
/// Style of the left border
/// </summary>
public BorderStyleEnum BStyleRight; // (Enum BorderStyle) Style of the left border
/// <summary>
/// Style of the top border
/// </summary>
public BorderStyleEnum BStyleTop; // (Enum BorderStyle) Style of the top border
/// <summary>
/// Style of the bottom border
/// </summary>
public BorderStyleEnum BStyleBottom; // (Enum BorderStyle) Style of the bottom border
// _BorderWdith
/// <summary>
/// Width of the left border. Max: 20 pt Min: 0.25 pt
/// </summary>
public float BWidthLeft; //(Size) Width of the left border. Max: 20 pt Min: 0.25 pt
/// <summary>
/// Width of the right border. Max: 20 pt Min: 0.25 pt
/// </summary>
public float BWidthRight; //(Size) Width of the right border. Max: 20 pt Min: 0.25 pt
/// <summary>
/// Width of the right border. Max: 20 pt Min: 0.25 pt
/// </summary>
public float BWidthTop; //(Size) Width of the right border. Max: 20 pt Min: 0.25 pt
/// <summary>
/// Width of the bottom border. Max: 20 pt Min: 0.25 pt
/// </summary>
public float BWidthBottom; //(Size) Width of the bottom border. Max: 20 pt Min: 0.25 pt
/// <summary>
/// Color of the background
/// </summary>
public Color BackgroundColor; //(Color) Color of the background
public string BackgroundColorText; //(Textual Color) Color of the background
/// <summary>
/// The type of background gradient
/// </summary>
public BackgroundGradientTypeEnum BackgroundGradientType; // The type of background gradient
/// <summary>
/// End color for the background gradient.
/// </summary>
/// <summary>
/// The type of background pattern
/// </summary>
public patternTypeEnum PatternType;
public Color BackgroundGradientEndColor; //(Color) End color for the background gradient.
/// <summary>
/// A background image for the report item.
/// </summary>
public PageImage BackgroundImage; // A background image for the report item.
/// <summary>
/// Font style Default: Normal
/// </summary>
public FontStyleEnum FontStyle; // (Enum FontStyle) Font style Default: Normal
/// <summary>
/// Name of the font family Default: Arial
/// </summary>
private string _FontFamily; //(string)Name of the font family Default: Arial -- allow comma separated value?
/// <summary>
/// Point size of the font
/// </summary>
public float FontSize; //(Size) Point size of the font
/// <summary>
/// Thickness of the font
/// </summary>
public FontWeightEnum FontWeight; //(Enum FontWeight) Thickness of the font
/// <summary>
/// Cell format in Excel07 Default: General
/// </summary>
public string _Format; //WRP 28102008 Cell format string
/// <summary>
/// Special text formatting Default: none
/// </summary>
public TextDecorationEnum TextDecoration; // (Enum TextDecoration) Special text formatting Default: none
/// <summary>
/// Horizontal alignment of the text Default: General
/// </summary>
public TextAlignEnum TextAlign; // (Enum TextAlign) Horizontal alignment of the text Default: General
/// <summary>
/// Vertical alignment of the text Default: Top
/// </summary>
public VerticalAlignEnum VerticalAlign; // (Enum VerticalAlign) Vertical alignment of the text Default: Top
/// <summary>
/// The foreground color Default: Black
/// </summary>
public Color Color; // (Color) The foreground color Default: Black
public string ColorText; // (Color-text)
/// <summary>
/// Padding between the left edge of the report item.
/// </summary>
public float PaddingLeft; // (Size)Padding between the left edge of the report item.
/// <summary>
/// Padding between the right edge of the report item.
/// </summary>
public float PaddingRight; // (Size) Padding between the right edge of the report item.
/// <summary>
/// Padding between the top edge of the report item.
/// </summary>
public float PaddingTop; // (Size) Padding between the top edge of the report item.
/// <summary>
/// Padding between the bottom edge of the report item.
/// </summary>
public float PaddingBottom; // (Size) Padding between the bottom edge of the report item.
/// <summary>
/// Height of a line of text.
/// </summary>
public float LineHeight; // (Size) Height of a line of text
/// <summary>
/// Indicates whether text is written left-to-right (default)
/// </summary>
public DirectionEnum Direction; // (Enum Direction) Indicates whether text is written left-to-right (default)
/// <summary>
/// Indicates the writing mode; e.g. left right top bottom or top bottom left right.
/// </summary>
public WritingModeEnum WritingMode; // (Enum WritingMode) Indicates whether text is written
/// <summary>
/// The primary language of the text.
/// </summary>
public string Language; // (Language) The primary language of the text.
/// <summary>
/// Unused.
/// </summary>
public UnicodeBiDirectionalEnum UnicodeBiDirectional; // (Enum UnicodeBiDirection)
/// <summary>
/// Calendar to use.
/// </summary>
public CalendarEnum Calendar; // (Enum Calendar)
/// <summary>
/// The digit format to use.
/// </summary>
public string NumeralLanguage; // (Language) The digit format to use as described by its
/// <summary>
/// The variant of the digit format to use.
/// </summary>
public int NumeralVariant; //(Integer) The variant of the digit format to use.
/// <summary>
/// Constructor using all defaults for the style.
/// </summary>
[System.Diagnostics.DebuggerStepThrough]
public StyleInfo()
{
BColorLeft = BColorRight = BColorTop = BColorBottom = System.Drawing.Color.Black; // (Color) Color of the bottom border
BStyleLeft = BStyleRight = BStyleTop = BStyleBottom = BorderStyleEnum.None;
// _BorderWdith
BWidthLeft = BWidthRight = BWidthTop = BWidthBottom = 1;
BackgroundColor = System.Drawing.Color.Empty;
BackgroundColorText = string.Empty;
BackgroundGradientType = BackgroundGradientTypeEnum.None;
BackgroundGradientEndColor = System.Drawing.Color.Empty;
BackgroundImage = null;
FontStyle = FontStyleEnum.Normal;
_FontFamily = "Arial";
//WRP 291008 numFmtId should be 0 (Zero) for General format - will be interpreted as a string
//It has default values in Excel07 as per ECMA-376 standard (SEction 3.8.30) for Office Open XML Excel07
_Format = "General";
FontSize = 10;
FontWeight = FontWeightEnum.Normal;
PatternType = patternTypeEnum.None;
TextDecoration = TextDecorationEnum.None;
TextAlign = TextAlignEnum.General;
VerticalAlign = VerticalAlignEnum.Top;
Color = System.Drawing.Color.Black;
ColorText = "Black";
PaddingLeft = PaddingRight = PaddingTop = PaddingBottom = 0;
LineHeight = 0;
Direction = DirectionEnum.LTR;
WritingMode = WritingModeEnum.lr_tb;
Language = "en-US";
UnicodeBiDirectional = UnicodeBiDirectionalEnum.Normal;
Calendar = CalendarEnum.Gregorian;
NumeralLanguage = Language;
NumeralVariant=1;
}
/// <summary>
/// Name of the font family Default: Arial
/// </summary>
public string FontFamily
{
[System.Diagnostics.DebuggerStepThrough]
get
{
int i = _FontFamily.IndexOf(",");
return i > 0? _FontFamily.Substring(0, i): _FontFamily;
}
[System.Diagnostics.DebuggerStepThrough]
set { _FontFamily = value; }
}
/// <summary>
/// Name of the font family Default: Arial. Support list of families separated by ','.
/// </summary>
public string FontFamilyFull
{
[System.Diagnostics.DebuggerStepThrough]
get {return _FontFamily;}
}
/// <summary>
/// Gets the FontFamily instance using the FontFamily string. This supports lists of fonts.
/// </summary>
/// <returns></returns>
[System.Diagnostics.DebuggerStepThrough]
public FontFamily GetFontFamily()
{
return GetFontFamily(_FontFamily);
}
/// <summary>
/// Gets the FontFamily instance using the passed face name. This supports lists of fonts.
/// </summary>
/// <returns></returns>
static public FontFamily GetFontFamily(string fface)
{
string[] choices = fface.Split(',');
FontFamily ff=null;
foreach (string val in choices)
{
try
{
string font=null;
// TODO: should be better way than to hard code; could put in config file??
switch (val.Trim().ToLower())
{
case "serif":
font = "Times New Roman";
break;
case "sans-serif":
font = "Arial";
break;
case "cursive":
font = "Comic Sans MS";
break;
case "fantasy":
font = "Impact";
break;
case "monospace":
case "courier":
font = "Courier New";
break;
default:
font = val;
break;
}
ff = new FontFamily(font);
if (ff != null)
break;
}
catch {} // if font doesn't exist we will go to the next
}
if (ff == null)
ff = new FontFamily("Arial");
return ff;
}
/// <summary>
/// True if font is bold.
/// </summary>
/// <returns></returns>
[System.Diagnostics.DebuggerStepThrough]
public bool IsFontBold()
{
switch(FontWeight)
{
case FontWeightEnum.Bold:
case FontWeightEnum.Bolder:
case FontWeightEnum.W500:
case FontWeightEnum.W600:
case FontWeightEnum.W700:
case FontWeightEnum.W800:
case FontWeightEnum.W900:
return true;
default:
return false;
}
}
/// <summary>
/// Gets the enumerated font weight.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
[System.Diagnostics.DebuggerStepThrough]
static public FontWeightEnum GetFontWeight(string v, FontWeightEnum def) //Josh: Changed to Enum.Parse instead of switch
{
FontWeightEnum fw;
try
{
fw = (FontWeightEnum)Enum.Parse(typeof(FontWeightEnum), v);
}
catch
{
fw = def;
}
//switch(v.ToLower())
//{
// case "Lighter":
// fw = FontWeightEnum.Lighter;
// break;
// case "Normal":
// fw = FontWeightEnum.Normal;
// break;
// case "bold":
// fw = FontWeightEnum.Bold;
// break;
// case "bolder":
// fw = FontWeightEnum.Bolder;
// break;
// case "500":
// fw = FontWeightEnum.W500;
// break;
// case "600":
// fw = FontWeightEnum.W600;
// break;
// case "700":
// fw = FontWeightEnum.W700;
// break;
// case "800":
// fw = FontWeightEnum.W800;
// break;
// case "900":
// fw = FontWeightEnum.W900;
// break;
// default:
// fw = def;
// break;
//}
return fw;
}
/// <summary>
/// Returns the font style (normal or italic).
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
[System.Diagnostics.DebuggerStepThrough]
public static FontStyleEnum GetFontStyle(string v, FontStyleEnum def)//Josh: Changed to Enum.Parse instead of switch
{
FontStyleEnum f;
try
{
f = (FontStyleEnum)Enum.Parse(typeof(FontStyleEnum), v);
}
catch
{
f = def;
}
//switch (v.ToLower())
//{
// case "normal":
// f = FontStyleEnum.Normal;
// break;
// case "italic":
// f = FontStyleEnum.Italic;
// break;
// default:
// f = def;
// break;
//}
return f;
}
/// <summary>
/// Gets the background gradient type.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
[System.Diagnostics.DebuggerStepThrough]
static public BackgroundGradientTypeEnum GetBackgroundGradientType(string v, BackgroundGradientTypeEnum def)//Josh: Changed to Enum.Parse instead of switch
{
BackgroundGradientTypeEnum gt;
try
{
gt = (BackgroundGradientTypeEnum)Enum.Parse(typeof(BackgroundGradientTypeEnum), v);
}
catch
{
gt = def;
}
//switch(v.ToLower())
//{
// case "none":
// gt = BackgroundGradientTypeEnum.None;
// break;
// case "leftright":
// gt = BackgroundGradientTypeEnum.LeftRight;
// break;
// case "topbottom":
// gt = BackgroundGradientTypeEnum.TopBottom;
// break;
// case "center":
// gt = BackgroundGradientTypeEnum.Center;
// break;
// case "diagonalleft":
// gt = BackgroundGradientTypeEnum.DiagonalLeft;
// break;
// case "diagonalright":
// gt = BackgroundGradientTypeEnum.DiagonalRight;
// break;
// case "horizontalcenter":
// gt = BackgroundGradientTypeEnum.HorizontalCenter;
// break;
// case "verticalcenter":
// gt = BackgroundGradientTypeEnum.VerticalCenter;
// break;
// default:
// gt = def;
// break;
//}
return gt;
}
/// <summary>
/// Gets the text decoration.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
[System.Diagnostics.DebuggerStepThrough]
public static TextDecorationEnum GetTextDecoration(string v, TextDecorationEnum def)//Josh: Changed to Enum.Parse instead of switch
{
TextDecorationEnum td;
try
{
td = (TextDecorationEnum)Enum.Parse(typeof(TextDecorationEnum), v);
}
catch
{
td = def;
}
//switch (v.ToLower())
//{
// case "underline":
// td = TextDecorationEnum.Underline;
// break;
// case "overline":
// td = TextDecorationEnum.Overline;
// break;
// case "linethrough":
// td = TextDecorationEnum.LineThrough;
// break;
// case "none":
// td = TextDecorationEnum.None;
// break;
// default:
// td = def;
// break;
//}
return td;
}
/// <summary>
/// Gets the text alignment.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
[System.Diagnostics.DebuggerStepThrough]
public static TextAlignEnum GetTextAlign(string v, TextAlignEnum def)//Josh: Changed to Enum.Parse instead of switch
{
TextAlignEnum ta;
try
{
ta = (TextAlignEnum)Enum.Parse(typeof(TextAlignEnum), v);
}
catch
{
ta = def;
}
//switch(v.ToLower())
//{
// case "left":
// ta = TextAlignEnum.Left;
// break;
// case "right":
// ta = TextAlignEnum.Right;
// break;
// case "center":
// ta = TextAlignEnum.Center;
// break;
// case "general":
// ta = TextAlignEnum.General;
// break;
// default:
// ta = def;
// break;
//}
return ta;
}
/// <summary>
/// Gets the vertical alignment.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
[System.Diagnostics.DebuggerStepThrough]
public static VerticalAlignEnum GetVerticalAlign(string v, VerticalAlignEnum def)//Josh: Changed to Enum.Parse instead of switch
{
VerticalAlignEnum va;
try
{
va = (VerticalAlignEnum)Enum.Parse(typeof(VerticalAlignEnum), v);
}
catch
{
va = def;
}
//switch (v.ToLower())
//{
// case "top":
// va = VerticalAlignEnum.Top;
// break;
// case "middle":
// va = VerticalAlignEnum.Middle;
// break;
// case "bottom":
// va = VerticalAlignEnum.Bottom;
// break;
// default:
// va = def;
// break;
//}
return va;
}
/// <summary>
/// Gets the direction of the text.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
[System.Diagnostics.DebuggerStepThrough]
public static DirectionEnum GetDirection(string v, DirectionEnum def)//Josh: Changed to Enum.Parse instead of switch
{
DirectionEnum d;
try
{
d = (DirectionEnum)Enum.Parse(typeof(DirectionEnum), v);
}
catch
{
d = def;
}
//switch(v.ToLower())
//{
// case "ltr":
// d = DirectionEnum.LTR;
// break;
// case "rtl":
// d = DirectionEnum.RTL;
// break;
// default:
// d = def;
// break;
//}
return d;
}
/// <summary>
/// Gets the writing mode; e.g. left right top bottom or top bottom left right.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
[System.Diagnostics.DebuggerStepThrough]
public static WritingModeEnum GetWritingMode(string v, WritingModeEnum def)//Josh: Changed to Enum.Parse instead of switch
{
WritingModeEnum w;
try
{
w = (WritingModeEnum)Enum.Parse(typeof(WritingModeEnum), v);
}
catch
{
w = def;
}
//switch(v.ToLower())
//{
// case "lr-tb":
// w = WritingModeEnum.lr_tb;
// break;
// case "tb-rl":
// w = WritingModeEnum.tb_rl;
// break;
// default:
// w = def;
// break;
//}
return w;
}
/// <summary>
/// Gets the unicode BiDirectional.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
[System.Diagnostics.DebuggerStepThrough]
public static UnicodeBiDirectionalEnum GetUnicodeBiDirectional(string v, UnicodeBiDirectionalEnum def)//Josh: Changed to Enum.Parse instead of switch
{
UnicodeBiDirectionalEnum u;
try
{
u = (UnicodeBiDirectionalEnum)Enum.Parse(typeof(UnicodeBiDirectionalEnum), v);
}
catch
{
u = def;
}
//switch (v.ToLower())
//{
// case "normal":
// u = UnicodeBiDirectionalEnum.Normal;
// break;
// case "embed":
// u = UnicodeBiDirectionalEnum.Embed;
// break;
// case "bidi-override":
// u = UnicodeBiDirectionalEnum.BiDi_Override;
// break;
// default:
// u = def;
// break;
//}
return u;
}
/// <summary>
/// Gets the calendar (e.g. Gregorian, GregorianArabic, and so on)
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
[System.Diagnostics.DebuggerStepThrough]
public static CalendarEnum GetCalendar(string v, CalendarEnum def)//Josh: Changed to Enum.Parse instead of switch
{
CalendarEnum c;
try
{
c = (CalendarEnum)Enum.Parse(typeof(CalendarEnum), v);
}
catch
{
c = def;
}
//switch (v.ToLower())
//{
// case "gregorian":
// c = CalendarEnum.Gregorian;
// break;
// case "gregorianarabic":
// c = CalendarEnum.GregorianArabic;
// break;
// case "gregorianmiddleeastfrench":
// c = CalendarEnum.GregorianMiddleEastFrench;
// break;
// case "gregoriantransliteratedenglish":
// c = CalendarEnum.GregorianTransliteratedEnglish;
// break;
// case "gregoriantransliteratedfrench":
// c = CalendarEnum.GregorianTransliteratedFrench;
// break;
// case "gregorianusenglish":
// c = CalendarEnum.GregorianUSEnglish;
// break;
// case "hebrew":
// c = CalendarEnum.Hebrew;
// break;
// case "hijri":
// c = CalendarEnum.Hijri;
// break;
// case "japanese":
// c = CalendarEnum.Japanese;
// break;
// case "korea":
// c = CalendarEnum.Korea;
// break;
// case "taiwan":
// c = CalendarEnum.Taiwan;
// break;
// case "thaibuddhist":
// c = CalendarEnum.ThaiBuddhist;
// break;
// default:
// c = def;
// break;
//}
return c;
}
// WRP 301008 return Excel07 format code as defined in section 3.8.30 of the ECMA-376 standard for Office Open XML Excel07 file formats
public static int GetFormatCode (string val)
{
switch (val)
{
case "General":
return 0;
case "0":
return 1;
case "0.00":
return 2;
case "#,##0":
return 3;
case "#,##0.00":
return 4;
case "0%":
return 9;
case "0.00%":
return 10;
case "0.00E+00":
return 11;
case "# ?/?":
return 12;
case " # ??/??":
return 13;
case "mm-dd-yy":
return 14;
case "d-mmm-yy":
return 15;
case "d-mmm":
return 16;
case "mmm-yy":
return 17;
case "h:mm AM/PM":
return 18;
case "h:mm:ss AM/PM":
return 19;
case "h:mm":
return 20;
case "h:mm:ss":
return 21;
case "m/d/yy h:mm":
return 22;
case "#,##0 ;(#,##0)":
return 37;
case "#,##0 ;[Red](#,##0)":
return 38;
case "#,##0.00;(#,##0.00)":
return 39;
case "#,##0.00;[Red](#,##0.00)":
return 40;
case "mm:ss":
return 45;
case "[h]:mm:ss":
return 46;
case "mmss.0":
return 47;
case "##0.0E+0":
return 48;
case "@":
return 49;
default:
return 999;
}
}
public static patternTypeEnum GetPatternType(System.Drawing.Drawing2D.HatchStyle hs)
{
switch (hs)
{
case HatchStyle.BackwardDiagonal:
return patternTypeEnum.BackwardDiagonal;
case HatchStyle.Cross:
return patternTypeEnum.Cross;
case HatchStyle.DarkDownwardDiagonal:
return patternTypeEnum.DarkDownwardDiagonal;
case HatchStyle.DarkHorizontal:
return patternTypeEnum.DarkHorizontal;
case HatchStyle.Vertical:
return patternTypeEnum.Vertical;
case HatchStyle.LargeConfetti:
return patternTypeEnum.LargeConfetti;
case HatchStyle.OutlinedDiamond:
return patternTypeEnum.OutlinedDiamond;
case HatchStyle.SmallConfetti:
return patternTypeEnum.SmallConfetti;
case HatchStyle.HorizontalBrick:
return patternTypeEnum.HorizontalBrick;
case HatchStyle.LargeCheckerBoard:
return patternTypeEnum.CheckerBoard;
case HatchStyle.SolidDiamond:
return patternTypeEnum.SolidDiamond;
case HatchStyle.DiagonalBrick:
return patternTypeEnum.DiagonalBrick;
default:
return patternTypeEnum.None;
}
}
#region ICloneable Members
public object Clone()
{
return this.MemberwiseClone();
}
#endregion
}
/// <summary>
/// The types of patterns supported.
/// </summary>
public enum patternTypeEnum
{
None,
LargeConfetti,
Cross,
DarkDownwardDiagonal,
OutlinedDiamond,
DarkHorizontal,
SmallConfetti,
HorizontalBrick,
CheckerBoard,
Vertical,
SolidDiamond,
DiagonalBrick,
BackwardDiagonal
}
/// <summary>
/// The types of background gradients supported.
/// </summary>
public enum BackgroundGradientTypeEnum
{
/// <summary>
/// No gradient
/// </summary>
None,
/// <summary>
/// Left Right gradient
/// </summary>
LeftRight,
/// <summary>
/// Top Bottom gradient
/// </summary>
TopBottom,
/// <summary>
/// Center gradient
/// </summary>
Center,
/// <summary>
/// Diagonal Left gradient
/// </summary>
DiagonalLeft,
/// <summary>
/// Diagonal Right gradient
/// </summary>
DiagonalRight,
/// <summary>
/// Horizontal Center gradient
/// </summary>
HorizontalCenter,
/// <summary>
/// Vertical Center
/// </summary>
VerticalCenter
}
/// <summary>
/// Font styles supported
/// </summary>
public enum FontStyleEnum
{
/// <summary>
/// Normal font
/// </summary>
Normal,
/// <summary>
/// Italic font
/// </summary>
Italic
}
/// <summary>
/// Potential font weights
/// </summary>
public enum FontWeightEnum
{
/// <summary>
/// Lighter font
/// </summary>
Lighter,
/// <summary>
/// Normal font
/// </summary>
Normal,
/// <summary>
/// Bold font
/// </summary>
Bold,
/// <summary>
/// Bolder font
/// </summary>
Bolder,
/// <summary>
/// W100 font
/// </summary>
W100,
/// <summary>
/// W200 font
/// </summary>
W200,
/// <summary>
/// W300 font
/// </summary>
W300,
/// <summary>
/// W400 font
/// </summary>
W400,
/// <summary>
/// W500 font
/// </summary>
W500,
/// <summary>
/// W600 font
/// </summary>
W600,
/// <summary>
/// W700 font
/// </summary>
W700,
/// <summary>
/// W800 font
/// </summary>
W800,
/// <summary>
/// W900 font
/// </summary>
W900
}
public enum TextDecorationEnum
{
Underline,
Overline,
LineThrough,
None
}
public enum TextAlignEnum
{
Left,
Center,
Right,
General,
Justified
}
public enum VerticalAlignEnum
{
Top,
Middle,
Bottom
}
public enum DirectionEnum
{
LTR, // left to right
RTL // right to left
}
public enum WritingModeEnum
{
lr_tb, // left right - top bottom
tb_rl // top bottom - right left
}
public enum UnicodeBiDirectionalEnum
{
Normal,
Embed,
BiDi_Override
}
public enum CalendarEnum
{
Gregorian,
GregorianArabic,
GregorianMiddleEastFrench,
GregorianTransliteratedEnglish,
GregorianTransliteratedFrench,
GregorianUSEnglish,
Hebrew,
Hijri,
Japanese,
Korea,
Taiwan,
ThaiBuddhist
}
}
| |
namespace System.Web.Mvc.Test {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.TestUtil;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
[TestClass]
public class ReflectedActionDescriptorTest {
private static readonly MethodInfo _int32EqualsIntMethod = typeof(int).GetMethod("Equals", new Type[] { typeof(int) });
[TestMethod]
public void ConstructorSetsActionNameProperty() {
// Arrange
string name = "someName";
// Act
ReflectedActionDescriptor ad = new ReflectedActionDescriptor(new Mock<MethodInfo>().Object, "someName", new Mock<ControllerDescriptor>().Object, false /* validateMethod */);
// Assert
Assert.AreEqual(name, ad.ActionName);
}
[TestMethod]
public void ConstructorSetsControllerDescriptorProperty() {
// Arrange
ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;
// Act
ReflectedActionDescriptor ad = new ReflectedActionDescriptor(new Mock<MethodInfo>().Object, "someName", cd, false /* validateMethod */);
// Assert
Assert.AreSame(cd, ad.ControllerDescriptor);
}
[TestMethod]
public void ConstructorSetsMethodInfoProperty() {
// Arrange
MethodInfo methodInfo = new Mock<MethodInfo>().Object;
// Act
ReflectedActionDescriptor ad = new ReflectedActionDescriptor(methodInfo, "someName", new Mock<ControllerDescriptor>().Object, false /* validateMethod */);
// Assert
Assert.AreSame(methodInfo, ad.MethodInfo);
}
[TestMethod]
public void ConstructorThrowsIfActionNameIsEmpty() {
// Act & assert
ExceptionHelper.ExpectArgumentExceptionNullOrEmpty(
delegate {
new ReflectedActionDescriptor(new Mock<MethodInfo>().Object, "", new Mock<ControllerDescriptor>().Object);
}, "actionName");
}
[TestMethod]
public void ConstructorThrowsIfActionNameIsNull() {
// Act & assert
ExceptionHelper.ExpectArgumentExceptionNullOrEmpty(
delegate {
new ReflectedActionDescriptor(new Mock<MethodInfo>().Object, null, new Mock<ControllerDescriptor>().Object);
}, "actionName");
}
[TestMethod]
public void ConstructorThrowsIfControllerDescriptorIsNull() {
// Act & assert
ExceptionHelper.ExpectArgumentNullException(
delegate {
new ReflectedActionDescriptor(new Mock<MethodInfo>().Object, "someName", null);
}, "controllerDescriptor");
}
[TestMethod]
public void ConstructorThrowsIfMethodInfoHasRefParameters() {
// Arrange
MethodInfo methodInfo = typeof(MyController).GetMethod("MethodHasRefParameter");
// Act & assert
ExceptionHelper.ExpectArgumentException(
delegate {
new ReflectedActionDescriptor(methodInfo, "someName", new Mock<ControllerDescriptor>().Object);
},
@"Cannot call action method 'Void MethodHasRefParameter(Int32 ByRef)' on controller 'System.Web.Mvc.Test.ReflectedActionDescriptorTest+MyController' since the parameter 'Int32& i' is passed by reference.
Parameter name: methodInfo");
}
[TestMethod]
public void ConstructorThrowsIfMethodInfoHasOutParameters() {
// Arrange
MethodInfo methodInfo = typeof(MyController).GetMethod("MethodHasOutParameter");
// Act & assert
ExceptionHelper.ExpectArgumentException(
delegate {
new ReflectedActionDescriptor(methodInfo, "someName", new Mock<ControllerDescriptor>().Object);
},
@"Cannot call action method 'Void MethodHasOutParameter(Int32 ByRef)' on controller 'System.Web.Mvc.Test.ReflectedActionDescriptorTest+MyController' since the parameter 'Int32& i' is passed by reference.
Parameter name: methodInfo");
}
[TestMethod]
public void ConstructorThrowsIfMethodInfoIsInstanceMethodOnNonControllerBaseType() {
// Arrange
MethodInfo methodInfo = typeof(string).GetMethod("Clone");
// Act & assert
ExceptionHelper.ExpectArgumentException(
delegate {
new ReflectedActionDescriptor(methodInfo, "someName", new Mock<ControllerDescriptor>().Object);
},
@"Cannot create a descriptor for instance method 'System.Object Clone()' on type 'System.String' since the type does not subclass ControllerBase.
Parameter name: methodInfo");
}
[TestMethod]
public void ConstructorThrowsIfMethodInfoIsNull() {
// Act & assert
ExceptionHelper.ExpectArgumentNullException(
delegate {
new ReflectedActionDescriptor(null, "someName", new Mock<ControllerDescriptor>().Object);
}, "methodInfo");
}
[TestMethod]
public void ConstructorThrowsIfMethodInfoIsOpenGenericType() {
// Arrange
MethodInfo methodInfo = typeof(MyController).GetMethod("OpenGenericMethod");
// Act & assert
ExceptionHelper.ExpectArgumentException(
delegate {
new ReflectedActionDescriptor(methodInfo, "someName", new Mock<ControllerDescriptor>().Object);
},
@"Cannot call action method 'Void OpenGenericMethod[T]()' on controller 'System.Web.Mvc.Test.ReflectedActionDescriptorTest+MyController' since it is a generic method.
Parameter name: methodInfo");
}
[TestMethod]
public void ExecuteCallsMethodInfoOnSuccess() {
// Arrange
Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Expect(c => c.Controller).Returns(new ConcatController());
Dictionary<string, object> parameters = new Dictionary<string, object>(){
{ "a", "hello " },
{ "b", "world" }
};
ReflectedActionDescriptor ad = GetActionDescriptor(typeof(ConcatController).GetMethod("Concat"));
// Act
object result = ad.Execute(mockControllerContext.Object, parameters);
// Assert
Assert.AreEqual("hello world", result);
}
[TestMethod]
public void ExecuteThrowsIfControllerContextIsNull() {
// Arrange
ReflectedActionDescriptor ad = GetActionDescriptor();
// Act & assert
ExceptionHelper.ExpectArgumentNullException(
delegate {
ad.Execute(null, new Dictionary<string, object>());
}, "controllerContext");
}
[TestMethod]
public void ExecuteThrowsIfParametersContainsNullForNonNullableParameter() {
// Arrange
ReflectedActionDescriptor ad = GetActionDescriptor(_int32EqualsIntMethod);
Dictionary<string, object> parameters = new Dictionary<string, object>() { { "obj", null } };
// Act & assert
ExceptionHelper.ExpectArgumentException(
delegate {
ad.Execute(new Mock<ControllerContext>().Object, parameters);
},
@"The parameters dictionary contains a null entry for parameter 'obj' of non-nullable type 'System.Int32' for method 'Boolean Equals(Int32)' in 'System.Int32'. To make a parameter optional its type should be either a reference type or a Nullable type.
Parameter name: parameters");
}
[TestMethod]
public void ExecuteThrowsIfParametersContainsValueOfWrongTypeForParameter() {
// Arrange
ReflectedActionDescriptor ad = GetActionDescriptor(_int32EqualsIntMethod);
Dictionary<string, object> parameters = new Dictionary<string, object>() { { "obj", "notAnInteger" } };
// Act & assert
ExceptionHelper.ExpectArgumentException(
delegate {
ad.Execute(new Mock<ControllerContext>().Object, parameters);
},
@"The parameters dictionary contains an invalid entry for parameter 'obj' for method 'Boolean Equals(Int32)' in 'System.Int32'. The dictionary contains a value of type 'System.String', but the parameter requires a value of type 'System.Int32'.
Parameter name: parameters");
}
[TestMethod]
public void ExecuteThrowsIfParametersIsMissingAValue() {
// Arrange
ReflectedActionDescriptor ad = GetActionDescriptor(_int32EqualsIntMethod);
Dictionary<string, object> parameters = new Dictionary<string, object>();
// Act & assert
ExceptionHelper.ExpectArgumentException(
delegate {
ad.Execute(new Mock<ControllerContext>().Object, parameters);
},
@"The parameters dictionary does not contain an entry for parameter 'obj' of type 'System.Int32' for method 'Boolean Equals(Int32)' in 'System.Int32'. The dictionary must contain an entry for each parameter, even parameters with null values.
Parameter name: parameters");
}
[TestMethod]
public void ExecuteThrowsIfParametersIsNull() {
// Arrange
ReflectedActionDescriptor ad = GetActionDescriptor();
// Act & assert
ExceptionHelper.ExpectArgumentNullException(
delegate {
ad.Execute(new Mock<ControllerContext>().Object, null);
}, "parameters");
}
[TestMethod]
public void GetCustomAttributesCallsMethodInfoGetCustomAttributes() {
// Arrange
object[] expected = new object[0];
Mock<MethodInfo> mockMethod = new Mock<MethodInfo>();
mockMethod.Expect(mi => mi.GetCustomAttributes(true)).Returns(expected);
ReflectedActionDescriptor ad = GetActionDescriptor(mockMethod.Object);
// Act
object[] returned = ad.GetCustomAttributes(true);
// Assert
Assert.AreSame(expected, returned);
}
[TestMethod]
public void GetCustomAttributesWithAttributeTypeCallsMethodInfoGetCustomAttributes() {
// Arrange
object[] expected = new object[0];
Mock<MethodInfo> mockMethod = new Mock<MethodInfo>();
mockMethod.Expect(mi => mi.GetCustomAttributes(typeof(ObsoleteAttribute), true)).Returns(expected);
ReflectedActionDescriptor ad = GetActionDescriptor(mockMethod.Object);
// Act
object[] returned = ad.GetCustomAttributes(typeof(ObsoleteAttribute), true);
// Assert
Assert.AreSame(expected, returned);
}
[TestMethod]
public void GetFilters() {
// Arrange
ControllerBase controller = new GetMemberChainSubderivedController();
ControllerContext context = new Mock<ControllerContext>().Object;
MethodInfo methodInfo = typeof(GetMemberChainSubderivedController).GetMethod("SomeVirtual");
ReflectedActionDescriptor ad = GetActionDescriptor(methodInfo);
// Act
FilterInfo filters = ad.GetFilters();
// Assert
Assert.AreEqual(2, filters.AuthorizationFilters.Count, "Wrong number of authorization filters.");
Assert.AreEqual("BaseClass", ((KeyedFilterAttribute)filters.AuthorizationFilters[0]).Key);
Assert.AreEqual("BaseMethod", ((KeyedFilterAttribute)filters.AuthorizationFilters[1]).Key);
Assert.AreEqual(5, filters.ActionFilters.Count, "Wrong number of action filters.");
Assert.AreEqual("BaseClass", ((KeyedFilterAttribute)filters.ActionFilters[0]).Key);
Assert.AreEqual("BaseMethod", ((KeyedFilterAttribute)filters.ActionFilters[1]).Key);
Assert.AreEqual("DerivedClass", ((KeyedFilterAttribute)filters.ActionFilters[2]).Key);
Assert.AreEqual("SubderivedClass", ((KeyedFilterAttribute)filters.ActionFilters[3]).Key);
Assert.AreEqual("SubderivedMethod", ((KeyedFilterAttribute)filters.ActionFilters[4]).Key);
Assert.AreEqual(5, filters.ResultFilters.Count, "Wrong number of result filters.");
Assert.AreEqual("BaseClass", ((KeyedFilterAttribute)filters.ResultFilters[0]).Key);
Assert.AreEqual("BaseMethod", ((KeyedFilterAttribute)filters.ResultFilters[1]).Key);
Assert.AreEqual("DerivedClass", ((KeyedFilterAttribute)filters.ResultFilters[2]).Key);
Assert.AreEqual("SubderivedClass", ((KeyedFilterAttribute)filters.ResultFilters[3]).Key);
Assert.AreEqual("SubderivedMethod", ((KeyedFilterAttribute)filters.ResultFilters[4]).Key);
Assert.AreEqual(1, filters.ExceptionFilters.Count, "Wrong number of exception filters.");
Assert.AreEqual("BaseClass", ((KeyedFilterAttribute)filters.ExceptionFilters[0]).Key);
}
[TestMethod]
public void GetFiltersUsesMethodReflectedTypeRatherThanMethodDeclaringType() {
// DevDiv 208062: Action filters specified on derived class won't run if the action method is on a base class
// Arrange
ControllerBase controller = new GetMemberChainDerivedController();
ControllerContext context = new Mock<ControllerContext>().Object;
MethodInfo methodInfo = typeof(GetMemberChainDerivedController).GetMethod("SomeVirtual");
ReflectedActionDescriptor ad = GetActionDescriptor(methodInfo);
// Act
FilterInfo filters = ad.GetFilters();
// Assert
Assert.AreEqual(2, filters.AuthorizationFilters.Count, "Wrong number of authorization filters.");
Assert.AreEqual("BaseClass", ((KeyedFilterAttribute)filters.AuthorizationFilters[0]).Key);
Assert.AreEqual("BaseMethod", ((KeyedFilterAttribute)filters.AuthorizationFilters[1]).Key);
Assert.AreEqual(3, filters.ActionFilters.Count, "Wrong number of action filters.");
Assert.AreEqual("BaseClass", ((KeyedFilterAttribute)filters.ActionFilters[0]).Key);
Assert.AreEqual("BaseMethod", ((KeyedFilterAttribute)filters.ActionFilters[1]).Key);
Assert.AreEqual("DerivedClass", ((KeyedFilterAttribute)filters.ActionFilters[2]).Key);
Assert.AreEqual(3, filters.ResultFilters.Count, "Wrong number of result filters.");
Assert.AreEqual("BaseClass", ((KeyedFilterAttribute)filters.ResultFilters[0]).Key);
Assert.AreEqual("BaseMethod", ((KeyedFilterAttribute)filters.ResultFilters[1]).Key);
Assert.AreEqual("DerivedClass", ((KeyedFilterAttribute)filters.ResultFilters[2]).Key);
Assert.AreEqual(1, filters.ExceptionFilters.Count, "Wrong number of exception filters.");
Assert.AreEqual("BaseClass", ((KeyedFilterAttribute)filters.ExceptionFilters[0]).Key);
}
[TestMethod]
public void GetParametersWrapsParameterInfos() {
// Arrange
ParameterInfo pInfo0 = typeof(ConcatController).GetMethod("Concat").GetParameters()[0];
ParameterInfo pInfo1 = typeof(ConcatController).GetMethod("Concat").GetParameters()[1];
ReflectedActionDescriptor ad = GetActionDescriptor(typeof(ConcatController).GetMethod("Concat"));
// Act
ParameterDescriptor[] pDescsFirstCall = ad.GetParameters();
ParameterDescriptor[] pDescsSecondCall = ad.GetParameters();
// Assert
Assert.AreNotSame(pDescsFirstCall, pDescsSecondCall, "GetParameters() should return a new array on each invocation.");
Assert.IsTrue(pDescsFirstCall.SequenceEqual(pDescsSecondCall), "Array elements were not equal.");
Assert.AreEqual(2, pDescsFirstCall.Length);
ReflectedParameterDescriptor pDesc0 = pDescsFirstCall[0] as ReflectedParameterDescriptor;
ReflectedParameterDescriptor pDesc1 = pDescsFirstCall[1] as ReflectedParameterDescriptor;
Assert.IsNotNull(pDesc0, "Parameter 0 should have been of type ReflectedParameterDescriptor.");
Assert.AreSame(ad, pDesc0.ActionDescriptor, "Parameter 0 Action did not match.");
Assert.AreSame(pInfo0, pDesc0.ParameterInfo, "Parameter 0 ParameterInfo did not match.");
Assert.IsNotNull(pDesc1, "Parameter 1 should have been of type ReflectedParameterDescriptor.");
Assert.AreSame(ad, pDesc1.ActionDescriptor, "Parameter 1 Action did not match.");
Assert.AreSame(pInfo1, pDesc1.ParameterInfo, "Parameter 1 ParameterInfo did not match.");
}
[TestMethod]
public void GetSelectorsWrapsSelectorAttributes() {
// Arrange
ControllerContext controllerContext = new Mock<ControllerContext>().Object;
Mock<MethodInfo> mockMethod = new Mock<MethodInfo>();
Mock<ActionMethodSelectorAttribute> mockAttr = new Mock<ActionMethodSelectorAttribute>();
mockAttr.Expect(attr => attr.IsValidForRequest(controllerContext, mockMethod.Object)).Returns(true).Verifiable();
mockMethod.Expect(m => m.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true)).Returns(new ActionMethodSelectorAttribute[] { mockAttr.Object });
ReflectedActionDescriptor ad = GetActionDescriptor(mockMethod.Object);
// Act
ICollection<ActionSelector> selectors = ad.GetSelectors();
bool executedSuccessfully = selectors.All(s => s(controllerContext));
// Assert
Assert.AreEqual(1, selectors.Count);
Assert.IsTrue(executedSuccessfully);
mockAttr.Verify();
}
[TestMethod]
public void IsDefinedCallsMethodInfoIsDefined() {
// Arrange
Mock<MethodInfo> mockMethod = new Mock<MethodInfo>();
mockMethod.Expect(mi => mi.IsDefined(typeof(ObsoleteAttribute), true)).Returns(true);
ReflectedActionDescriptor ad = GetActionDescriptor(mockMethod.Object);
// Act
bool isDefined = ad.IsDefined(typeof(ObsoleteAttribute), true);
// Assert
Assert.IsTrue(isDefined);
}
[TestMethod]
public void TryCreateDescriptorReturnsDescriptorOnSuccess() {
// Arrange
MethodInfo methodInfo = typeof(MyController).GetMethod("StaticMethod");
ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;
// Act
ReflectedActionDescriptor ad = ReflectedActionDescriptor.TryCreateDescriptor(methodInfo, "someName", cd);
// Assert
Assert.IsNotNull(ad, "Descriptor should have been created successfully.");
Assert.AreSame(methodInfo, ad.MethodInfo);
Assert.AreEqual("someName", ad.ActionName);
Assert.AreSame(cd, ad.ControllerDescriptor);
}
[TestMethod]
public void TryCreateDescriptorReturnsNullOnFailure() {
// Arrange
MethodInfo methodInfo = typeof(MyController).GetMethod("OpenGenericMethod");
ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;
// Act
ReflectedActionDescriptor ad = ReflectedActionDescriptor.TryCreateDescriptor(methodInfo, "someName", cd);
// Assert
Assert.IsNull(ad, "Descriptor should not have been returned.");
}
private static ReflectedActionDescriptor GetActionDescriptor() {
return GetActionDescriptor(new Mock<MethodInfo>().Object);
}
private static ReflectedActionDescriptor GetActionDescriptor(MethodInfo methodInfo) {
return new ReflectedActionDescriptor(methodInfo, "someName", new Mock<ControllerDescriptor>().Object, false /* validateMethod */) {
DispatcherCache = new ActionMethodDispatcherCache()
};
}
private class ConcatController : Controller {
public string Concat(string a, string b) {
return a + b;
}
}
[KeyedActionFilter(Key = "BaseClass", Order = 0)]
[KeyedAuthorizationFilter(Key = "BaseClass", Order = 0)]
[KeyedExceptionFilter(Key = "BaseClass", Order = 0)]
private class GetMemberChainController : Controller {
[KeyedActionFilter(Key = "BaseMethod", Order = 0)]
[KeyedAuthorizationFilter(Key = "BaseMethod", Order = 0)]
public virtual void SomeVirtual() {
}
}
[KeyedActionFilter(Key = "DerivedClass", Order = 1)]
private class GetMemberChainDerivedController : GetMemberChainController {
}
[KeyedActionFilter(Key = "SubderivedClass", Order = 2)]
private class GetMemberChainSubderivedController : GetMemberChainDerivedController {
[KeyedActionFilter(Key = "SubderivedMethod", Order = 2)]
public override void SomeVirtual() {
}
}
private abstract class KeyedFilterAttribute : FilterAttribute {
public string Key {
get;
set;
}
}
private class KeyedAuthorizationFilterAttribute : KeyedFilterAttribute, IAuthorizationFilter {
public void OnAuthorization(AuthorizationContext filterContext) {
throw new NotImplementedException();
}
}
private class KeyedExceptionFilterAttribute : KeyedFilterAttribute, IExceptionFilter {
public void OnException(ExceptionContext filterContext) {
throw new NotImplementedException();
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
private class KeyedActionFilterAttribute : KeyedFilterAttribute, IActionFilter, IResultFilter {
public void OnActionExecuting(ActionExecutingContext filterContext) {
throw new NotImplementedException();
}
public void OnActionExecuted(ActionExecutedContext filterContext) {
throw new NotImplementedException();
}
public void OnResultExecuting(ResultExecutingContext filterContext) {
throw new NotImplementedException();
}
public void OnResultExecuted(ResultExecutedContext filterContext) {
throw new NotImplementedException();
}
}
private class MyController : Controller {
public static void StaticMethod() {
}
public void OpenGenericMethod<T>() {
}
public void MethodHasOutParameter(out int i) {
i = 0;
}
public void MethodHasRefParameter(ref int i) {
}
}
}
}
| |
#region License
// Copyright (c) K2 Workflow (SourceCode Technology Holdings Inc.). All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
#endregion
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
namespace SourceCode.Chasm
{
/// <summary>
/// Represents a <see cref="Sha1"/> value.
/// </summary>
/// <seealso cref="SHA1" />
/// <seealso cref="System.IEquatable{T}" />
/// <seealso cref="System.IComparable{T}" />
[DebuggerDisplay("{ToString(\"D\"),nq,ac}")]
public struct Sha1 : IEquatable<Sha1>, IComparable<Sha1>
{
#region Constants
// Use a thread-local instance of the underlying crypto algorithm.
private static readonly ThreadLocal<SHA1> _sha1 = new ThreadLocal<SHA1>(SHA1.Create);
/// <summary>
/// The fixed byte length of a <see cref="Sha1"/> value.
/// </summary>
public const byte ByteLen = 20;
/// <summary>
/// The number of hex characters required to represent a <see cref="Sha1"/> value.
/// </summary>
public const byte CharLen = ByteLen * 2;
/// <summary>
/// A singleton representing an <see cref="Sha1"/> value that is all zeroes.
/// </summary>
/// <value>
/// The zeroes <see cref="Sha1"/>.
/// </value>
public static Sha1 Zero { get; }
#endregion
#region Properties
// We choose to use value types for primary storage so that we can live on the stack
// Using byte[] or String means a dereference to the heap (& fixed byte would require unsafe)
public ulong Blit0 { get; }
public ulong Blit1 { get; }
public uint Blit2 { get; }
/// <summary>
/// Returns a <see cref="Memory{T}"/> from the <see cref="Sha1"/>.
/// </summary>
public Memory<byte> Memory
{
get
{
var buffer = new byte[ByteLen];
unsafe
{
fixed (byte* ptr = buffer)
{
// Code is valid per BitConverter.ToInt32|64 (see #1 elsewhere in this class)
*(ulong*)(&ptr[0 + 0]) = Blit0;
*(ulong*)(&ptr[0 + 8]) = Blit1;
*(uint*)(&ptr[0 + 16]) = Blit2;
}
}
var mem = new Memory<byte>(buffer);
return mem;
}
}
#endregion
#region De/Constructors
/// <summary>
/// Deserializes a <see cref="Sha1"/> value from the provided blits.
/// </summary>
/// <param name="blit0">The blit0.</param>
/// <param name="blit1">The blit1.</param>
/// <param name="blit2">The blit2.</param>
public Sha1(ulong blit0, ulong blit1, uint blit2)
{
Blit0 = blit0;
Blit1 = blit1;
Blit2 = blit2;
}
/// <summary>
/// Deserializes a <see cref="Sha1"/> value from the provided <see cref="Byte[]"/> starting at the specified position.
/// </summary>
/// <param name="buffer">The buffer.</param>
/// <param name="offset">The offset.</param>
/// <exception cref="ArgumentNullException">buffer</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// buffer - buffer
/// or
/// offset - buffer
/// </exception>
[SecuritySafeCritical]
public Sha1(byte[] buffer, int offset)
{
if (buffer == null) throw new ArgumentNullException(nameof(buffer));
if (buffer.Length < ByteLen)
throw new ArgumentOutOfRangeException(nameof(buffer), $"{nameof(buffer)} must have length at least {ByteLen}");
if (offset < 0 || offset + ByteLen > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset), $"{nameof(buffer)} must have length at least {ByteLen}");
unsafe
{
fixed (byte* ptr = buffer)
{
// Code is valid per BitConverter.ToInt32|64 (see #1 elsewhere in this class)
Blit0 = *(ulong*)(&ptr[offset + 0]);
Blit1 = *(ulong*)(&ptr[offset + 8]);
Blit2 = *(uint*)(&ptr[offset + 16]);
}
}
}
/// <summary>
/// Deserializes a <see cref="Sha1"/> value from the provided <see cref="ReadOnlyMemory{T}"/>.
/// </summary>
/// <param name="span">The buffer.</param>
/// <exception cref="ArgumentOutOfRangeException">buffer - buffer</exception>
[SecuritySafeCritical]
public Sha1(ReadOnlySpan<byte> span)
{
if (span.IsEmpty || span.Length < ByteLen)
throw new ArgumentOutOfRangeException(nameof(span), $"{nameof(span)} must have length at least {ByteLen}");
unsafe
{
fixed (byte* ptr = &span.DangerousGetPinnableReference())
{
// Code is valid per BitConverter.ToInt32|64 (see #1 elsewhere in this class)
Blit0 = *(ulong*)(&ptr[0]);
Blit1 = *(ulong*)(&ptr[8]);
Blit2 = *(uint*)(&ptr[16]);
}
}
}
/// <summary>
/// Deconstructs the specified <see cref="Sha1"/>.
/// </summary>
/// <param name="blit0">The blit0.</param>
/// <param name="blit1">The blit1.</param>
/// <param name="blit2">The blit2.</param>
public void Deconstruct(out ulong blit0, out ulong blit1, out uint blit2)
{
blit0 = Blit0;
blit1 = Blit1;
blit2 = Blit2;
}
#endregion
#region Factory
/// <summary>
/// Hashes the specified value using utf8 encoding.
/// </summary>
/// <param name="value">The string to hash.</param>
/// <returns></returns>
public static Sha1 Hash(string value)
{
if (value == null) return Zero;
// Note that length=0 should not short-circuit
// Rent buffer
var maxLen = Encoding.UTF8.GetMaxByteCount(value.Length); // Utf8 is 1-4 bpc
var rented = ArrayPool<byte>.Shared.Rent(maxLen);
var count = Encoding.UTF8.GetBytes(value, 0, value.Length, rented, 0);
var hash = _sha1.Value.ComputeHash(rented, 0, count);
var sha1 = new Sha1(hash);
// Return buffer
ArrayPool<byte>.Shared.Return(rented);
return sha1;
}
/// <summary>
/// Hashes the specified bytes.
/// </summary>
/// <param name="bytes">The bytes to hash.</param>
/// <returns></returns>
public static Sha1 Hash(byte[] bytes)
{
if (bytes == null) return Zero;
// Note that length=0 should not short-circuit
var hash = _sha1.Value.ComputeHash(bytes);
var sha1 = new Sha1(hash);
return sha1;
}
/// <summary>
/// Hashes the specified bytes, starting at the specified offset and count.
/// </summary>
/// <param name="bytes">The bytes to hash.</param>
/// <param name="offset">The offset.</param>
/// <param name="count">The count.</param>
/// <returns></returns>
public static Sha1 Hash(byte[] bytes, int offset, int count)
{
if (bytes == null) return Zero;
// Note that length=0 should not short-circuit
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (offset < 0 || offset + count > bytes.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
var hash = _sha1.Value.ComputeHash(bytes, offset, count);
var sha1 = new Sha1(hash);
return sha1;
}
/// <summary>
/// Hashes the specified bytes.
/// </summary>
/// <param name="bytes">The bytes to hash.</param>
/// <returns></returns>
public static Sha1 Hash(ArraySegment<byte> bytes)
{
if (bytes.Array == null) return Zero;
// Note that length=0 should not short-circuit
var hash = _sha1.Value.ComputeHash(bytes.Array, bytes.Offset, bytes.Count);
var sha1 = new Sha1(hash);
return sha1;
}
/// <summary>
/// Hashes the specified stream.
/// </summary>
/// <param name="stream">The stream to hash.</param>
/// <returns></returns>
public static Sha1 Hash(Stream stream)
{
if (stream == null) return Zero;
// Note that length=0 should not short-circuit
var hash = _sha1.Value.ComputeHash(stream);
var sha1 = new Sha1(hash);
return sha1;
}
#endregion
#region Methods
/// <summary>
/// Copies the <see cref="Sha1"/> value to the provided buffer.
/// </summary>
/// <param name="buffer">The buffer to copy to.</param>
/// <param name="offset">The offset.</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">buffer</exception>
/// <exception cref="ArgumentOutOfRangeException">offset - buffer</exception>
[SecuritySafeCritical]
public int CopyTo(byte[] buffer, int offset)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0 || checked(offset + ByteLen) > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset), $"{nameof(buffer)} must have length at least {ByteLen}");
unsafe
{
fixed (byte* ptr = buffer)
{
// Code is valid per BitConverter.ToInt32|64 (see #1 elsewhere in this class)
*(ulong*)(&ptr[offset + 0]) = Blit0;
*(ulong*)(&ptr[offset + 8]) = Blit1;
*(uint*)(&ptr[offset + 16]) = Blit2;
}
}
return ByteLen;
}
#endregion
#region ToString
private const char FormatN = (char)0;
[SecuritySafeCritical]
private char[] ToChars(char separator)
{
Debug.Assert(separator == FormatN || separator == '-' || separator == ' ');
var sep = 0;
char[] chars;
// Text is treated as 5 groups of 8 chars (4 bytes); 4 separators optional
if (separator == FormatN)
{
chars = new char[CharLen];
}
else
{
sep = 8;
chars = new char[CharLen + 4];
}
unsafe
{
var bytes = stackalloc byte[ByteLen]; // TODO: https://github.com/dotnet/corefx/pull/24212
{
// Code is valid per BitConverter.ToInt32|64 (see #1 elsewhere in this class)
*(ulong*)(&bytes[0]) = Blit0;
*(ulong*)(&bytes[8]) = Blit1;
*(uint*)(&bytes[16]) = Blit2;
}
var pos = 0;
for (var i = 0; i < ByteLen; i++) // 20
{
// Each byte is two hexits (convention is lowercase)
var b = bytes[i] >> 4; // == b / 16
chars[pos++] = (char)(b < 10 ? b + '0' : b - 10 + 'a');
b = bytes[i] - (b << 4); // == b % 16
chars[pos++] = (char)(b < 10 ? b + '0' : b - 10 + 'a');
// Append a separator if required
if (pos == sep) // pos >= 2, sep = 0|N
{
chars[pos++] = separator;
sep = pos + 8;
if (sep >= chars.Length)
sep = 0;
}
}
}
return chars;
}
/// <summary>
/// Returns a string representation of the <see cref="Sha1"/> instance using the 'N' format.
/// </summary>
/// <returns></returns>
public override string ToString()
{
var chars = ToChars(FormatN);
return new string(chars);
}
/// <summary>
/// Returns a string representation of the <see cref="Sha1"/> instance.
/// N: a9993e364706816aba3e25717850c26c9cd0d89d,
/// D: a9993e36-4706816a-ba3e2571-7850c26c-9cd0d89d,
/// S: a9993e36 4706816a ba3e2571 7850c26c 9cd0d89d
/// </summary>
/// <param name="format"></param>
/// <returns></returns>
public string ToString(string format)
{
if (string.IsNullOrWhiteSpace(format))
throw new FormatException($"Empty format specification");
if (format.Length != 1)
throw new FormatException($"Invalid format specification length {format.Length}");
switch (format[0])
{
// a9993e364706816aba3e25717850c26c9cd0d89d
case 'n':
case 'N':
{
var chars = ToChars(FormatN);
return new string(chars);
}
// a9993e36-4706816a-ba3e2571-7850c26c-9cd0d89d
case 'd':
case 'D':
{
var chars = ToChars('-');
return new string(chars);
}
// a9993e36 4706816a ba3e2571 7850c26c 9cd0d89d
case 's':
case 'S':
{
var chars = ToChars(' ');
return new string(chars);
}
}
throw new FormatException($"Invalid format specification '{format}'");
}
/// <summary>
/// Converts the <see cref="Sha1"/> instance to a string using the 'N' format,
/// and returns the value split into two tokens.
/// </summary>
/// <param name="prefixLength">The length of the first token.</param>
/// <returns></returns>
public KeyValuePair<string, string> Split(int prefixLength)
{
var chars = ToChars(FormatN);
if (prefixLength <= 0)
return new KeyValuePair<string, string>(string.Empty, new string(chars));
if (prefixLength >= CharLen)
return new KeyValuePair<string, string>(new string(chars), string.Empty);
var key = new string(chars, 0, prefixLength);
var val = new string(chars, prefixLength, chars.Length - prefixLength);
var kvp = new KeyValuePair<string, string>(key, val);
return kvp;
}
#endregion
#region Parse
// Sentinel value for n/a (128)
private const byte __ = 0b1000_0000;
// '0'=48, '9'=57
// 'A'=65, 'F'=70
// 'a'=97, 'f'=102
private static readonly byte[] Hexits = new byte['f' - '0' + 1] // 102 - 48 + 1 = 55
{
00, 01, 02, 03, 04, 05, 06, 07, 08, 09, // [00-09] = 48..57 = '0'..'9'
__, __, __, __, __, __, __, 10, 11, 12, // [10-16,17-19] = 65..67 = 'A'..'C'
13, 14, 15, __, __, __, __, __, __, __, // [20-22,23-29] = 68..70 = 'D'..'F'
__, __, __, __, __, __, __, __, __, __, // [30-39]
__, __, __, __, __, __, __, __, __, 10, // [40-48,49] = 97..97 = 'a'
11, 12, 13, 14, 15 // [50-54] = 98..102= 'b'..'f'
};
[SecuritySafeCritical]
private static bool TryParseImpl(string hex, int startIndex, out Sha1 value)
{
Debug.Assert(hex != null);
Debug.Assert(startIndex >= 0);
Debug.Assert(hex.Length >= CharLen + startIndex);
value = Zero;
unsafe
{
var bytes = stackalloc byte[ByteLen]; // TODO: https://github.com/dotnet/corefx/pull/24212
// Text is treated as 5 groups of 8 chars (4 bytes); 4 separators optional
// "34aa973c-d4c4daa4-f61eeb2b-dbad2731-6534016f"
var pos = startIndex;
for (var i = 0; i < 5; i++)
{
for (var j = 0; j < 4; j++)
{
// Two hexits per byte: aaaa bbbb
if (!TryParseHexit(hex[pos++], out var h1)
|| !TryParseHexit(hex[pos++], out var h2))
return false;
bytes[i * 4 + j] = (byte)((h1 << 4) | h2);
}
if (pos < CharLen && (hex[pos] == '-' || hex[pos] == ' '))
pos++;
}
// If the string is not fully consumed, it had an invalid length
if (pos != hex.Length)
return false;
// Code is valid per BitConverter.ToInt32|64 (see #1 elsewhere in this class)
var blit0 = *(ulong*)(&bytes[0]);
var blit1 = *(ulong*)(&bytes[8]);
var blit2 = *(uint*)(&bytes[16]);
value = new Sha1(blit0, blit1, blit2);
return true;
}
// Local functions
bool TryParseHexit(char c, out byte b)
{
b = 0;
if (c < '0' || c > 'f')
return false;
var bex = Hexits[c - '0'];
if (bex == __) // Sentinel value for n/a (128)
return false;
b = bex;
return true;
}
}
/// <summary>
/// Parses the specified hexadecimal.
/// </summary>
/// <param name="hex">The hexadecimal.</param>
/// <returns></returns>
/// <exception cref="FormatException">Sha1</exception>
public static Sha1 Parse(string hex)
{
if (!TryParse(hex, out var sha1))
throw new FormatException($"String was not recognized as a valid {nameof(Sha1)}");
return sha1;
}
/// <summary>
/// Tries to parse the specified hexadecimal.
/// </summary>
/// <param name="hex">The hexadecimal.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public static bool TryParse(string hex, out Sha1 value)
{
value = Zero;
// Length must be at least 40
if (hex == null || hex.Length < CharLen)
return false;
var startIndex = 0;
// Check if the hex specifier '0x' is present
if (hex[0] == '0' && (hex[1] == 'x' || hex[1] == 'X'))
{
// Length must be at least 42
if (hex.Length < 2 + CharLen)
return false;
// Skip '0x'
startIndex = 2;
}
if (!TryParseImpl(hex, startIndex, out var sha1))
return false;
value = sha1;
return true;
}
#endregion
#region IEquatable
public bool Equals(Sha1 other) => Sha1Comparer.Default.Equals(this, other);
public override bool Equals(object obj)
=> obj is Sha1 sha1
&& Sha1Comparer.Default.Equals(this, sha1);
public override int GetHashCode() => Sha1Comparer.Default.GetHashCode(this);
#endregion
#region IComparable
public int CompareTo(Sha1 other) => Sha1Comparer.Default.Compare(this, other);
#endregion
#region Operators
public static bool operator ==(Sha1 x, Sha1 y) => Sha1Comparer.Default.Equals(x, y);
public static bool operator !=(Sha1 x, Sha1 y) => !(x == y);
public static bool operator >=(Sha1 x, Sha1 y) => Sha1Comparer.Default.Compare(x, y) >= 0;
public static bool operator >(Sha1 x, Sha1 y) => Sha1Comparer.Default.Compare(x, y) > 0;
public static bool operator <=(Sha1 x, Sha1 y) => Sha1Comparer.Default.Compare(x, y) <= 0;
public static bool operator <(Sha1 x, Sha1 y) => Sha1Comparer.Default.Compare(x, y) < 0;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using NUnit.Framework;
using ServiceStack.Common;
using ServiceStack.Common.Utils;
using ServiceStack.Html;
using ServiceStack.Markdown;
using ServiceStack.ServiceInterface.Testing;
using ServiceStack.Text;
using ServiceStack.VirtualPath;
using ServiceStack.WebHost.Endpoints.Formats;
using ServiceStack.WebHost.Endpoints.Support.Markdown;
namespace ServiceStack.ServiceHost.Tests.Formats
{
[TestFixture]
public class TemplateTests
{
string staticTemplatePath;
string staticTemplateContent;
string dynamicPagePath;
string dynamicPageContent;
string dynamicListPagePath;
string dynamicListPageContent;
private MarkdownFormat markdownFormat;
Dictionary<string, object> templateArgs;
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
staticTemplatePath = "~/Views/Shared/_Layout.shtml".MapProjectPath();
staticTemplateContent = File.ReadAllText(staticTemplatePath);
dynamicPagePath = "~/Views/Template/DynamicTpl.md".MapProjectPath();
dynamicPageContent = File.ReadAllText(dynamicPagePath);
dynamicListPagePath = "~/Views/Template/DynamicListTpl.md".MapProjectPath();
dynamicListPageContent = File.ReadAllText(dynamicListPagePath);
}
[SetUp]
public void OnBeforeEachTest()
{
markdownFormat = new MarkdownFormat {
VirtualPathProvider = new InMemoryVirtualPathProvider(new BasicAppHost())
};
templateArgs = new Dictionary<string, object> { { MarkdownPage.ModelName, person } };
}
[Test]
public void Can_Render_MarkdownTemplate()
{
var template = new MarkdownTemplate(staticTemplatePath, "default", staticTemplateContent);
template.Prepare();
Assert.That(template.TextBlocks.Length, Is.EqualTo(2));
const string mockResponse = "[Replaced with Template]";
var expectedHtml = staticTemplateContent.ReplaceFirst(MarkdownFormat.TemplatePlaceHolder, mockResponse);
var mockArgs = new Dictionary<string, object> { { MarkdownTemplate.BodyPlaceHolder, mockResponse } };
var templateOutput = template.RenderToString(mockArgs);
Console.WriteLine("Template Output: " + templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Link> Links { get; set; }
}
public class Link
{
public Link()
{
this.Labels = new List<string>();
}
public string Name { get; set; }
public string Href { get; set; }
public List<string> Labels { get; set; }
}
Person person = new Person {
FirstName = "Demis",
LastName = "Bellot",
Links = new List<Link>
{
new Link { Name = "ServiceStack", Href = "http://www.servicestack.net", Labels = {"REST","JSON","XML"} },
new Link { Name = "AjaxStack", Href = "http://www.ajaxstack.com", Labels = {"HTML5", "AJAX", "SPA"} },
},
};
[Test]
public void Can_Render_MarkdownPage()
{
var dynamicPage = new MarkdownPage(markdownFormat, dynamicPageContent, "DynamicTpl", dynamicPageContent);
dynamicPage.Compile();
Assert.That(dynamicPage.HtmlBlocks.Length, Is.EqualTo(9));
var expectedHtml = markdownFormat.Transform(dynamicPageContent)
.Replace("@Model.FirstName", person.FirstName)
.Replace("@Model.LastName", person.LastName);
var templateOutput = dynamicPage.RenderToHtml(templateArgs);
Console.WriteLine("Template Output: " + templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_MarkdownPage_with_foreach()
{
var dynamicPage = new MarkdownPage(markdownFormat,
dynamicListPagePath, "DynamicListTpl", dynamicListPageContent);
dynamicPage.Compile();
Assert.That(dynamicPage.HtmlBlocks.Length, Is.EqualTo(11));
var expectedMarkdown = dynamicListPageContent
.Replace("@Model.FirstName", person.FirstName)
.Replace("@Model.LastName", person.LastName);
var foreachLinks = " - ServiceStack - http://www.servicestack.net\r\n"
+ " - AjaxStack - http://www.ajaxstack.com\r\n";
expectedMarkdown = expectedMarkdown.ReplaceForeach(foreachLinks);
var expectedHtml = markdownFormat.Transform(expectedMarkdown);
Console.WriteLine("ExpectedHtml: " + expectedHtml);
var templateOutput = dynamicPage.RenderToHtml(templateArgs);
Console.WriteLine("Template Output: " + templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_MarkdownPage_with_IF_statement()
{
var template = @"# Dynamic If Markdown Template
Hello @Model.FirstName,
@if (Model.FirstName == ""Bellot"") {
* @Model.FirstName
}
@if (Model.LastName == ""Bellot"") {
* @Model.LastName
}
### heading 3";
var expected = @"# Dynamic If Markdown Template
Hello Demis,
* Bellot
### heading 3";
var expectedHtml = markdownFormat.Transform(expected);
var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicIfTpl", template);
dynamicPage.Compile();
var templateOutput = dynamicPage.RenderToHtml(templateArgs);
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_Markdown_with_Nested_Statements()
{
var template = @"# @Model.FirstName Dynamic Nested Markdown Template
# heading 1
@foreach (var link in Model.Links) {
@if (link.Name == ""AjaxStack"") {
- @link.Name - @link.Href
}
}
@if (Model.Links.Count == 2) {
## Haz 2 links
@foreach (var link in Model.Links) {
- @link.Name - @link.Href
@foreach (var label in link.Labels) {
- @label
}
}
}
### heading 3".NormalizeNewLines();
var expected = @"# Demis Dynamic Nested Markdown Template
# heading 1
- AjaxStack - http://www.ajaxstack.com
## Haz 2 links
- ServiceStack - http://www.servicestack.net
- REST
- JSON
- XML
- AjaxStack - http://www.ajaxstack.com
- HTML5
- AJAX
- SPA
### heading 3".NormalizeNewLines();
var expectedHtml = markdownFormat.Transform(expected);
var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicNestedTpl", template);
dynamicPage.Compile();
var templateOutput = dynamicPage.RenderToHtml(templateArgs);
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
public class CustomMarkdownViewBase<T> : MarkdownViewBase<T>
{
public MvcHtmlString Table(Person model)
{
return new CustomMarkdownViewBase().Table(model);
}
}
public class CustomMarkdownViewBase : MarkdownViewBase
{
public MvcHtmlString Table(Person model)
{
var sb = new StringBuilder();
sb.AppendFormat("<table><caption>{0}'s Links</caption>", model.FirstName);
sb.AppendLine("<thead><tr><th>Name</th><th>Link</th></tr></thead>");
sb.AppendLine("<tbody>");
foreach (var link in model.Links)
{
sb.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>", link.Name, link.Href);
}
sb.AppendLine("</tbody>");
sb.AppendLine("</table>");
return MvcHtmlString.Create(sb.ToString());
}
private static string[] MenuItems = new[] { "About Us", "Blog", "Links", "Contact" };
public void Menu(string selectedId)
{
var sb = new StringBuilder();
sb.Append("<ul>\n");
foreach (var menuItem in MenuItems)
{
var cls = menuItem == selectedId ? " class='selected'" : "";
sb.AppendFormat("<li><a href='{0}'{1}>{0}</a></li>\n", menuItem, cls);
}
sb.Append("</ul>\n");
ScopeArgs.Add("Menu", MvcHtmlString.Create(sb.ToString()));
}
}
public class CustomMarkdownHelper
{
public static CustomMarkdownHelper Instance = new CustomMarkdownHelper();
public MvcHtmlString InlineBlock(string content, string id)
{
return MvcHtmlString.Create(
"<div id=\"" + id + "\"><div class=\"inner inline-block\">" + content + "</div></div>");
}
}
[Test]
public void Can_Render_Markdown_with_StaticMethods()
{
var headerTemplate = @"## Header Links!
- [Google](http://google.com)
- [Bing](http://bing.com)";
var template = @"## Welcome to Razor!
@Html.Partial(""HeaderLinks"", Model)
Hello @Upper(Model.LastName), @Model.FirstName
### Breadcrumbs
@Combine("" / "", Model.FirstName, Model.LastName)
### Menus
@foreach (var link in Model.Links) {
- @link.Name - @link.Href
@foreach (var label in link.Labels) {
- @label
}
}
### HTML Table
@Table(Model)
".NormalizeNewLines();
var expectedHtml = @"<h2>Welcome to Razor!</h2>
<h2>Header Links!</h2>
<ul>
<li><a href=""http://google.com"">Google</a></li>
<li><a href=""http://bing.com"">Bing</a></li>
</ul>
<p>Hello BELLOT, Demis</p>
<h3>Breadcrumbs</h3>
Demis / Bellot<h3>Menus</h3>
<ul>
<li>
ServiceStack - http://www.servicestack.net
<ul>
<li>REST</li>
<li>JSON</li>
<li>XML</li>
</ul>
</li>
<li>
AjaxStack - http://www.ajaxstack.com
<ul>
<li>HTML5</li>
<li>AJAX</li>
<li>SPA</li>
</ul>
</li>
</ul>
<h3>HTML Table</h3>
<table><caption>Demis's Links</caption><thead><tr><th>Name</th><th>Link</th></tr></thead>
<tbody>
<tr><td>ServiceStack</td><td>http://www.servicestack.net</td></tr><tr><td>AjaxStack</td><td>http://www.ajaxstack.com</td></tr></tbody>
</table>
".NormalizeNewLines();
markdownFormat.MarkdownBaseType = typeof(CustomMarkdownViewBase);
markdownFormat.MarkdownGlobalHelpers = new Dictionary<string, Type>
{
{"Ext", typeof(CustomMarkdownHelper)}
};
markdownFormat.RegisterMarkdownPage(new MarkdownPage(markdownFormat,
"/path/to/page", "HeaderLinks", headerTemplate));
var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicIfTpl", template);
dynamicPage.Compile();
var templateOutput = dynamicPage.RenderToHtml(templateArgs);
templateOutput = templateOutput.Replace("\r\n", "\n");
templateOutput.Print();
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_inherit_from_Generic_view_page_from_model_directive()
{
var template = @"@model ServiceStack.ServiceHost.Tests.Formats.TemplateTests+Person
# Generic View Page
## Form fields
@Html.LabelFor(m => m.FirstName) @Html.TextBoxFor(m => m.FirstName)
";
var expectedHtml = @"<h1>Generic View Page</h1>
<h2>Form fields</h2>
<label for=""FirstName"">FirstName</label> <input id=""FirstName"" name=""FirstName"" type=""text"" value=""Demis"" />".NormalizeNewLines();
var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicModelTpl", template);
dynamicPage.Compile();
var templateOutput = dynamicPage.RenderToHtml(templateArgs);
templateOutput = templateOutput.Replace("\r\n", "\n");
Assert.That(dynamicPage.ExecutionContext.BaseType, Is.EqualTo(typeof(MarkdownViewBase<>)));
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_inherit_from_CustomViewPage_using_inherits_directive()
{
var template = @"@inherits ServiceStack.ServiceHost.Tests.Formats.TemplateTests+CustomMarkdownViewBase<ServiceStack.ServiceHost.Tests.Formats.TemplateTests+Person>
# Generic View Page
## Form fields
@Html.LabelFor(m => m.FirstName) @Html.TextBoxFor(m => m.FirstName)
## Person Table
@Table(Model)
";
var expectedHtml = @"<h1>Generic View Page</h1>
<h2>Form fields</h2>
<label for=""FirstName"">FirstName</label> <input id=""FirstName"" name=""FirstName"" type=""text"" value=""Demis"" /><h2>Person Table</h2>
<table><caption>Demis's Links</caption><thead><tr><th>Name</th><th>Link</th></tr></thead>
<tbody>
<tr><td>ServiceStack</td><td>http://www.servicestack.net</td></tr><tr><td>AjaxStack</td><td>http://www.ajaxstack.com</td></tr></tbody>
</table>
".NormalizeNewLines();
var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicModelTpl", template);
dynamicPage.Compile();
var templateOutput = dynamicPage.RenderToHtml(templateArgs);
templateOutput = templateOutput.Replace("\r\n", "\n");
Assert.That(dynamicPage.ExecutionContext.BaseType, Is.EqualTo(typeof(CustomMarkdownViewBase<>)));
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_MarkdownPage_with_external_helper()
{
var template = @"# View Page with Custom Helper
## External Helper

@Ext.InlineBlock(Model.FirstName, ""first-name"")
";
var expectedHtml = @"<h1>View Page with Custom Helper</h1>
<h2>External Helper</h2>
<p><img src=""path/to/img"" alt=""inline-img"" />
<div id=""first-name""><div class=""inner inline-block"">Demis</div></div>".NormalizeNewLines();
markdownFormat.MarkdownGlobalHelpers.Add("Ext", typeof(CustomMarkdownHelper));
var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicModelTpl", template);
dynamicPage.Compile();
var templateOutput = dynamicPage.RenderToHtml(templateArgs);
templateOutput = templateOutput.Replace("\r\n", "\n");
Assert.That(dynamicPage.ExecutionContext.BaseType, Is.EqualTo(typeof(MarkdownViewBase)));
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_MarkdownPage_with_external_helper_using_helper_directive()
{
var template = @"@helper Ext: ServiceStack.ServiceHost.Tests.Formats.TemplateTests+CustomMarkdownHelper
# View Page with Custom Helper
## External Helper

@Ext.InlineBlock(Model.FirstName, ""first-name"")
";
var expectedHtml = @"<h1>View Page with Custom Helper</h1>
<h2>External Helper</h2>
<p><img src=""path/to/img"" alt=""inline-img"" />
<div id=""first-name""><div class=""inner inline-block"">Demis</div></div>".NormalizeNewLines();
var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicModelTpl", template);
dynamicPage.Compile();
var templateOutput = dynamicPage.RenderToHtml(templateArgs);
templateOutput = templateOutput.Replace("\r\n", "\n");
Assert.That(dynamicPage.ExecutionContext.BaseType, Is.EqualTo(typeof(MarkdownViewBase)));
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_page_to_Markdown_only()
{
var headerTemplate = @"## Header Links!
- [Google](http://google.com)
- [Bing](http://bing.com)
";
var template = @"## Welcome to Razor!
@Html.Partial(""HeaderLinks"", Model)
Hello @Upper(Model.LastName), @Model.FirstName
### Breadcrumbs
@Combine("" / "", Model.FirstName, Model.LastName)
### Menus
@foreach (var link in Model.Links) {
- @link.Name - @link.Href
@foreach (var label in link.Labels) {
- @label
}
}".NormalizeNewLines();
var expectedHtml = @"## Welcome to Razor!
## Header Links!
- [Google](http://google.com)
- [Bing](http://bing.com)
Hello BELLOT, Demis
### Breadcrumbs
Demis / Bellot
### Menus
- ServiceStack - http://www.servicestack.net
- REST
- JSON
- XML
- AjaxStack - http://www.ajaxstack.com
- HTML5
- AJAX
- SPA
".NormalizeNewLines();
markdownFormat.RegisterMarkdownPage(new MarkdownPage(markdownFormat,
"/path/to/page", "HeaderLinks", headerTemplate));
var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicModelTpl", template);
dynamicPage.Compile();
var templateOutput = dynamicPage.RenderToMarkdown(templateArgs);
templateOutput = templateOutput.Replace("\r\n", "\n");
Assert.That(dynamicPage.ExecutionContext.BaseType, Is.EqualTo(typeof(MarkdownViewBase)));
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_Markdown_with_variable_statements()
{
var template = @"## Welcome to Razor!
@var lastName = Model.LastName;
Hello @Upper(lastName), @Model.FirstName
### Breadcrumbs
@Combine("" / "", Model.FirstName, lastName)
@var links = Model.Links
### Menus
@foreach (var link in links) {
- @link.Name - @link.Href
@var labels = link.Labels
@foreach (var label in labels) {
- @label
}
}".NormalizeNewLines();
var expectedHtml = @"## Welcome to Razor!
Hello BELLOT, Demis
### Breadcrumbs
Demis / Bellot
### Menus
- ServiceStack - http://www.servicestack.net
- REST
- JSON
- XML
- AjaxStack - http://www.ajaxstack.com
- HTML5
- AJAX
- SPA
".NormalizeNewLines();
var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicModelTpl", template);
dynamicPage.Compile();
var templateOutput = dynamicPage.RenderToMarkdown(templateArgs);
templateOutput = templateOutput.Replace("\r\n", "\n");
Assert.That(dynamicPage.ExecutionContext.BaseType, Is.EqualTo(typeof(MarkdownViewBase)));
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_MarkdownPage_with_comments()
{
var template = @"# Dynamic If Markdown Template
Hello @Model.FirstName,
@if (Model.FirstName == ""Bellot"") {
* @Model.FirstName
}
@*
@if (Model.LastName == ""Bellot"") {
* @Model.LastName
}
*@
@*
Plain text in a comment
*@
### heading 3";
var expectedHtml = @"<h1>Dynamic If Markdown Template</h1>
<p>Hello Demis,</p>
<h3>heading 3</h3>
".NormalizeNewLines();
var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicIfTpl", template);
dynamicPage.Compile();
var templateOutput = dynamicPage.RenderToHtml(templateArgs);
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_MarkdownPage_with_unmatching_escaped_braces()
{
var template = @"# Dynamic If Markdown Template
Hello @Model.FirstName, { -- unmatched, leave unescaped outside statement
{ -- inside matching braces, outside statement -- }
@if (Model.LastName == ""Bellot"") {
* @Model.LastName
{{ -- inside matching braces, escape inside statement -- }}
{{ -- unmatched
}
### heading 3";
var expectedHtml = @"<h1>Dynamic If Markdown Template</h1>
<p>Hello Demis, { -- unmatched, leave unescaped outside statement</p>
<p>{ -- inside matching braces, outside statement -- }</p>
<ul>
<li>Bellot</li>
</ul>
<p>{ -- inside matching braces, escape inside statement -- }</p>
<p>{ -- unmatched</p>
<h3>heading 3</h3>
".NormalizeNewLines();
var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicIfTpl", template);
dynamicPage.Compile();
var templateOutput = dynamicPage.RenderToHtml(templateArgs);
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_capture_Section_statements_and_store_them_in_scopeargs()
{
var template = @"## Welcome to Razor!
@var lastName = Model.LastName;
@section Salutations {
Hello @Upper(lastName), @Model.FirstName
}
@section Breadcrumbs {
### Breadcrumbs
@Combine("" / "", Model.FirstName, lastName)
}
@var links = Model.Links
@section Menus {
### Menus
@foreach (var link in links) {
- @link.Name - @link.Href
@var labels = link.Labels
@foreach (var label in labels) {
- @label
}
}
}
## Captured Sections
<div id='breadcrumbs'>@Breadcrumbs</div>
@Menus
## Salutations
@Salutations".NormalizeNewLines();
var expectedHtml = @"<h2>Welcome to Razor!</h2>
<h2>Captured Sections</h2>
<div id='breadcrumbs'><h3>Breadcrumbs</h3>
<p>Demis / Bellot</p>
</div>
<p><h3>Menus</h3>
<ul>
<li>
ServiceStack - http://www.servicestack.net
<ul>
<li>REST</li>
<li>JSON</li>
<li>XML</li>
</ul>
</li>
<li>
AjaxStack - http://www.ajaxstack.com
<ul>
<li>HTML5</li>
<li>AJAX</li>
<li>SPA</li>
</ul>
</li>
</ul>
</p>
<h2>Salutations</h2>
<p><p>Hello BELLOT, Demis</p>
</p>
".NormalizeNewLines();
var dynamicPage = new MarkdownPage(markdownFormat, "/path/to/tpl", "DynamicModelTpl", template);
dynamicPage.Compile();
var templateOutput = dynamicPage.RenderToHtml(templateArgs);
templateOutput = templateOutput.Replace("\r\n", "\n");
Assert.That(dynamicPage.ExecutionContext.BaseType, Is.EqualTo(typeof(MarkdownViewBase)));
Console.WriteLine(templateOutput);
Assert.That(templateArgs["Salutations"].ToString(), Is.EqualTo("<p>Hello BELLOT, Demis</p>\n"));
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_Template_with_section_and_variable_placeholders()
{
var template = @"## Welcome to Razor!
@var lastName = Model.LastName;
Hello @Upper(lastName), @Model.FirstName,
@section Breadcrumbs {
### Breadcrumbs
@Combine("" / "", Model.FirstName, lastName)
}
@section Menus {
### Menus
@foreach (var link in Model.Links) {
- @link.Name - @link.Href
@var labels = link.Labels
@foreach (var label in labels) {
- @label
}
}
}".NormalizeNewLines();
var websiteTemplate = @"<!doctype html>
<html lang=""en-us"">
<head>
<title><!--@lastName--> page</title>
</head>
<body>
<header>
<!--@Menus-->
</header>
<h1>Website Template</h1>
<div id=""content""><!--@Body--></div>
<footer>
<!--@Breadcrumbs-->
</footer>
</body>
</html>".NormalizeNewLines();
var expectedHtml = @"<!doctype html>
<html lang=""en-us"">
<head>
<title>Bellot page</title>
</head>
<body>
<header>
<h3>Menus</h3>
<ul>
<li>
ServiceStack - http://www.servicestack.net
<ul>
<li>REST</li>
<li>JSON</li>
<li>XML</li>
</ul>
</li>
<li>
AjaxStack - http://www.ajaxstack.com
<ul>
<li>HTML5</li>
<li>AJAX</li>
<li>SPA</li>
</ul>
</li>
</ul>
</header>
<h1>Website Template</h1>
<div id=""content""><h2>Welcome to Razor!</h2>
<p>Hello BELLOT, Demis,</p>
</div>
<footer>
<h3>Breadcrumbs</h3>
<p>Demis / Bellot</p>
</footer>
</body>
</html>".NormalizeNewLines();
markdownFormat.AddFileAndTemplate("websiteTemplate", websiteTemplate);
markdownFormat.AddPage(
new MarkdownPage(markdownFormat, "/path/to/page-tpl", "DynamicModelTpl", template) {
Template = "websiteTemplate"
});
var templateOutput = markdownFormat.RenderDynamicPageHtml("DynamicModelTpl", person);
templateOutput = templateOutput.Replace("\r\n", "\n");
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_Static_ContentPage_that_populates_variable_and_displayed_on_website_template()
{
var websiteTemplate = @"<!doctype html>
<html lang=""en-us"">
<head>
<title>Static page</title>
</head>
<body>
<header>
<!--@Header-->
</header>
<div id='menus'>
<!--@Menu-->
</div>
<h1>Website Template</h1>
<div id=""content""><!--@Body--></div>
</body>
</html>".NormalizeNewLines();
var template = @"# Static Markdown Template
@Menu(""Links"")
@section Header {
### Static Page Title
}
### heading 3
paragraph";
var expectedHtml = @"<!doctype html>
<html lang=""en-us"">
<head>
<title>Static page</title>
</head>
<body>
<header>
<h3>Static Page Title</h3>
</header>
<div id='menus'>
<ul>
<li><a href='About Us'>About Us</a></li>
<li><a href='Blog'>Blog</a></li>
<li><a href='Links' class='selected'>Links</a></li>
<li><a href='Contact'>Contact</a></li>
</ul>
</div>
<h1>Website Template</h1>
<div id=""content""><h1>Static Markdown Template</h1>
<h3>heading 3</h3>
<p>paragraph</p>
</div>
</body>
</html>".NormalizeNewLines();
markdownFormat.MarkdownBaseType = typeof(CustomMarkdownViewBase);
markdownFormat.AddFileAndTemplate("websiteTemplate", websiteTemplate);
markdownFormat.RegisterMarkdownPage(
new MarkdownPage(markdownFormat, "pagetpl", "StaticTpl", template, MarkdownPageType.ContentPage) {
Template = "websiteTemplate"
});
var templateOutput = markdownFormat.RenderStaticPage("pagetpl", true);
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
namespace UMA.Editors
{
[CustomEditor(typeof(OverlayLibrary))]
[CanEditMultipleObjects]
public class OverlayLibraryEditor : Editor
{
private SerializedObject m_Object;
private OverlayLibrary overlayLibrary;
private SerializedProperty m_OverlayDataCount;
private const string kArraySizePath = "overlayElementList.Array.size";
private const string kArrayData = "overlayElementList.Array.data[{0}]";
private bool canUpdate;
private bool isDirty;
public SerializedProperty scaleAdjust;
public SerializedProperty readWrite;
public SerializedProperty compress;
public void OnEnable(){
m_Object = new SerializedObject(target);
overlayLibrary = m_Object.targetObject as OverlayLibrary;
m_OverlayDataCount = m_Object.FindProperty(kArraySizePath);
scaleAdjust = serializedObject.FindProperty ("scaleAdjust");
readWrite = serializedObject.FindProperty ("readWrite");
compress = serializedObject.FindProperty ("compress");
}
private OverlayDataAsset[] GetOverlayDataArray()
{
int arrayCount = m_OverlayDataCount.intValue;
OverlayDataAsset[] OverlayDataArray = new OverlayDataAsset[arrayCount];
for(int i = 0; i < arrayCount; i++){
OverlayDataArray[i] = m_Object.FindProperty(string.Format(kArrayData,i)).objectReferenceValue as OverlayDataAsset;
}
return OverlayDataArray;
}
private void SetOverlayData(int index, OverlayDataAsset overlayElement)
{
m_Object.FindProperty(string.Format(kArrayData,index)).objectReferenceValue = overlayElement;
isDirty = true;
}
private OverlayDataAsset GetOverlayDataAtIndex(int index)
{
return m_Object.FindProperty(string.Format(kArrayData, index)).objectReferenceValue as OverlayDataAsset;
}
private void AddOverlayData(OverlayDataAsset overlayElement)
{
m_OverlayDataCount.intValue ++;
SetOverlayData(m_OverlayDataCount.intValue - 1, overlayElement);
}
private void RemoveOverlayDataAtIndex(int index){
for(int i = index; i < m_OverlayDataCount.intValue - 1; i++){
SetOverlayData(i, GetOverlayDataAtIndex(i + 1));
}
m_OverlayDataCount.intValue --;
}
private void ScaleDownTextures(){
OverlayDataAsset[] overlayElementList = GetOverlayDataArray();
string path;
for(int i = 0; i < overlayElementList.Length; i++){
if(overlayElementList[i] != null){
Rect tempRect = overlayElementList[i].rect;
overlayElementList[i].rect = new Rect(tempRect.x*0.5f,tempRect.y*0.5f,tempRect.width*0.5f,tempRect.height*0.5f);
EditorUtility.SetDirty(overlayElementList[i]);
for(int textureID = 0; textureID < overlayElementList[i].textureList.Length; textureID++){
if(overlayElementList[i].textureList[textureID]){
path = AssetDatabase.GetAssetPath(overlayElementList[i].textureList[textureID]);
TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
textureImporter.maxTextureSize = (int)(textureImporter.maxTextureSize*0.5f);
AssetDatabase.WriteImportSettingsIfDirty (path);
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
}
}
}
}
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
private void ScaleUpTextures(){
OverlayDataAsset[] overlayElementList = GetOverlayDataArray();
string path;
for(int i = 0; i < overlayElementList.Length; i++){
if(overlayElementList[i] != null){
Rect tempRect = overlayElementList[i].rect;
overlayElementList[i].rect = new Rect(tempRect.x*2,tempRect.y*2,tempRect.width*2,tempRect.height*2);
EditorUtility.SetDirty(overlayElementList[i]);
for(int textureID = 0; textureID < overlayElementList[i].textureList.Length; textureID++){
if(overlayElementList[i].textureList[textureID]){
path = AssetDatabase.GetAssetPath(overlayElementList[i].textureList[textureID]);
TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
textureImporter.maxTextureSize = (int)(textureImporter.maxTextureSize*2);
AssetDatabase.WriteImportSettingsIfDirty (path);
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
}
}
}
}
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
private void ConfigureTextures(){
OverlayDataAsset[] overlayElementList = GetOverlayDataArray();
string path;
for(int i = 0; i < overlayElementList.Length; i++){
if(overlayElementList[i] != null){
for(int textureID = 0; textureID < overlayElementList[i].textureList.Length; textureID++){
if(overlayElementList[i].textureList[textureID]){
path = AssetDatabase.GetAssetPath(overlayElementList[i].textureList[textureID]);
TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
textureImporter.isReadable = readWrite.boolValue;
if(compress.boolValue){
textureImporter.textureCompression = TextureImporterCompression.CompressedHQ;
textureImporter.compressionQuality = 100;
}else{
textureImporter.textureCompression = TextureImporterCompression.Uncompressed;
}
AssetDatabase.WriteImportSettingsIfDirty (path);
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
Debug.Log(overlayElementList[i].textureList[textureID].name + " isReadable set to " + readWrite.boolValue + " and compression set to " + compress.boolValue);
}
}
}
}
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
private void DropAreaGUI(Rect dropArea){
var evt = Event.current;
if(evt.type == EventType.DragUpdated){
if(dropArea.Contains(evt.mousePosition)){
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
}
}
if(evt.type == EventType.DragPerform){
if(dropArea.Contains(evt.mousePosition)){
DragAndDrop.AcceptDrag();
UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences;
for(int i = 0; i < draggedObjects.Length; i++){
if (draggedObjects[i])
{
OverlayDataAsset tempOverlayData = draggedObjects[i] as OverlayDataAsset;
if (tempOverlayData)
{
AddOverlayData(tempOverlayData);
continue;
}
var path = AssetDatabase.GetAssetPath(draggedObjects[i]);
if (System.IO.Directory.Exists(path))
{
RecursiveScanFoldersForAssets(path);
}
}
}
}
}
}
private void RecursiveScanFoldersForAssets(string path)
{
var assetFiles = System.IO.Directory.GetFiles(path, "*.asset");
foreach (var assetFile in assetFiles)
{
var tempOverlayData = AssetDatabase.LoadAssetAtPath(assetFile, typeof(OverlayDataAsset)) as OverlayDataAsset;
if (tempOverlayData)
{
AddOverlayData(tempOverlayData);
}
}
foreach (var subFolder in System.IO.Directory.GetDirectories(path))
{
RecursiveScanFoldersForAssets(subFolder.Replace('\\', '/'));
}
}
public override void OnInspectorGUI(){
m_Object.Update();
serializedObject.Update();
GUILayout.Label ("overlayList", EditorStyles.boldLabel);
OverlayDataAsset[] overlayElementList = GetOverlayDataArray();
GUILayout.Space(30);
GUILayout.Label ("Overlays reduced " + scaleAdjust.intValue +" time(s)");
GUILayout.BeginHorizontal();
if(scaleAdjust.intValue > 0){
if(GUILayout.Button("Resolution +")){
ScaleUpTextures();
isDirty = true;
canUpdate = false;
scaleAdjust.intValue --;
}
}
if(GUILayout.Button("Resolution -")){
ScaleDownTextures();
isDirty = true;
canUpdate = false;
scaleAdjust.intValue ++;
}
GUILayout.EndHorizontal();
GUILayout.Space(20);
GUILayout.BeginHorizontal();
compress.boolValue = GUILayout.Toggle (compress.boolValue ? true : false," Compress Textures");
readWrite.boolValue = GUILayout.Toggle (readWrite.boolValue ? true : false," Read/Write");
if(GUILayout.Button(" Apply")){
ConfigureTextures();
isDirty = true;
canUpdate = false;
}
GUILayout.EndHorizontal();
GUILayout.Space(20);
GUILayout.BeginHorizontal();
if(GUILayout.Button("Order by Name")){
canUpdate = false;
List<OverlayDataAsset> OverlayDataTemp = new List<OverlayDataAsset>();
OverlayDataTemp.AddRange(overlayElementList);
//Make sure there's no invalid data
for(int i = 0; i < OverlayDataTemp.Count; i++){
if(OverlayDataTemp[i] == null){
OverlayDataTemp.RemoveAt(i);
i--;
}
}
OverlayDataTemp.Sort((x,y) => x.name.CompareTo(y.name));
for(int i = 0; i < OverlayDataTemp.Count; i++){
SetOverlayData(i,OverlayDataTemp[i]);
}
}
if(GUILayout.Button("Update List")){
isDirty = true;
canUpdate = false;
}
if (GUILayout.Button("Remove Duplicates"))
{
HashSet<OverlayDataAsset> Overlays = new HashSet<OverlayDataAsset>();
foreach(OverlayDataAsset oda in overlayElementList)
{
Overlays.Add(oda);
}
m_OverlayDataCount.intValue = Overlays.Count;
List<OverlayDataAsset> od = new List<OverlayDataAsset>();
od.AddRange(Overlays);
for(int i=0;i<od.Count;i++)
{
SetOverlayData(i,od[i]);
}
isDirty = true;
canUpdate = false;
}
GUILayout.EndHorizontal();
GUILayout.Space(20);
Rect dropArea = GUILayoutUtility.GetRect(0.0f,50.0f, GUILayout.ExpandWidth(true));
GUI.Box(dropArea,"Drag Overlays here");
GUILayout.Space(20);
for(int i = 0; i < m_OverlayDataCount.intValue; i ++){
GUILayout.BeginHorizontal();
var result = EditorGUILayout.ObjectField(overlayElementList[i], typeof(OverlayDataAsset), true) as OverlayDataAsset;
if(GUI.changed && canUpdate){
SetOverlayData(i,result);
}
if(GUILayout.Button("-", GUILayout.Width(20.0f))){
canUpdate = false;
RemoveOverlayDataAtIndex(i);
}
GUILayout.EndHorizontal();
if(i == m_OverlayDataCount.intValue -1){
canUpdate = true;
if(isDirty){
overlayLibrary.UpdateDictionary();
isDirty = false;
}
}
}
DropAreaGUI(dropArea);
if(GUILayout.Button("Add OverlayData")){
AddOverlayData(null);
}
if(GUILayout.Button("Clear List")){
m_OverlayDataCount.intValue = 0;
}
m_Object.ApplyModifiedProperties();
serializedObject.ApplyModifiedProperties();
}
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace Octokit
{
/// <summary>
/// A client for GitHub's Repositories API.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/">Repositories API documentation</a> for more details.
/// </remarks>
public interface IRepositoriesClient
{
/// <summary>
/// Client for managing pull requests.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/pulls/">Pull Requests API documentation</a> for more details
/// </remarks>
IPullRequestsClient PullRequest { get; }
/// <summary>
/// Client for managing branches in a repository.
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/">Branches API documentation</a> for more details
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
IRepositoryBranchesClient Branch { get; }
/// <summary>
/// Client for managing commit comments in a repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/comments/">Repository Comments API documentation</a> for more information.
/// </remarks>
IRepositoryCommentsClient Comment { get; }
/// <summary>
/// Client for managing deploy keys in a repository.
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/keys/">Repository Deploy Keys API documentation</a> for more information.
/// </remarks>
IRepositoryDeployKeysClient DeployKeys { get; }
/// <summary>
/// Client for managing the contents of a repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/contents/">Repository Contents API documentation</a> for more information.
/// </remarks>
IRepositoryContentsClient Content { get; }
/// <summary>
/// Creates a new repository for the current user.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information.
/// </remarks>
/// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="Repository"/> instance for the created repository.</returns>
Task<Repository> Create(NewRepository newRepository);
/// <summary>
/// Creates a new repository in the specified organization.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information.
/// </remarks>
/// <param name="organizationLogin">Login of the organization in which to create the repository</param>
/// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="Repository"/> instance for the created repository</returns>
Task<Repository> Create(string organizationLogin, NewRepository newRepository);
/// <summary>
/// Deletes the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#delete-a-repository">API documentation</a> for more information.
/// Deleting a repository requires admin access. If OAuth is used, the `delete_repo` scope is required.
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
Task Delete(string owner, string name);
/// <summary>
/// Deletes the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#delete-a-repository">API documentation</a> for more information.
/// Deleting a repository requires admin access. If OAuth is used, the `delete_repo` scope is required.
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
Task Delete(long repositoryId);
/// <summary>
/// Transfers the ownership of the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/#transfer-a-repository">API documentation</a> for more information.
/// </remarks>
/// <param name="owner">The current owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="repositoryTransfer">Repository transfer information</param>
/// <returns>A <see cref="Repository"/></returns>
Task<Repository> Transfer(string owner, string name, RepositoryTransfer repositoryTransfer);
/// <summary>
/// Transfers the ownership of the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/#transfer-a-repository">API documentation</a> for more information.
/// </remarks>
/// <param name="repositoryId">The id of the repository</param>
/// <param name="repositoryTransfer">Repository transfer information</param>
/// <returns>A <see cref="Repository"/></returns>
Task<Repository> Transfer(long repositoryId, RepositoryTransfer repositoryTransfer);
/// <summary>
/// Gets the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#get">API documentation</a> for more information.
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="Repository"/></returns>
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")]
Task<Repository> Get(string owner, string name);
/// <summary>
/// Gets the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#get">API documentation</a> for more information.
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="Repository"/></returns>
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")]
Task<Repository> Get(long repositoryId);
/// <summary>
/// Gets all public repositories.
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/#list-all-public-repositories">API documentation</a> for more information.
/// The default page size on GitHub.com is 30.
/// </remarks>
/// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
Justification = "Makes a network request")]
[ExcludeFromPaginationApiOptionsConventionTest("This API call uses the PublicRepositoryRequest.Since parameter for pagination")]
Task<IReadOnlyList<Repository>> GetAllPublic();
/// <summary>
/// Gets all public repositories since the integer Id of the last Repository that you've seen.
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/#list-all-public-repositories">API documentation</a> for more information.
/// The default page size on GitHub.com is 30.
/// </remarks>
/// <param name="request">Search parameters of the last repository seen</param>
/// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns>
[ExcludeFromPaginationApiOptionsConventionTest("This API call uses the PublicRepositoryRequest.Since parameter for pagination")]
Task<IReadOnlyList<Repository>> GetAllPublic(PublicRepositoryRequest request);
/// <summary>
/// Gets all repositories owned by the current user.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information.
/// The default page size on GitHub.com is 30.
/// </remarks>
/// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
Justification = "Makes a network request")]
Task<IReadOnlyList<Repository>> GetAllForCurrent();
/// <summary>
/// Gets all repositories owned by the current user.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information.
/// </remarks>
/// <param name="options">Options for changing the API response</param>
/// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns>
Task<IReadOnlyList<Repository>> GetAllForCurrent(ApiOptions options);
/// <summary>
/// Gets all repositories owned by the current user.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information.
/// The default page size on GitHub.com is 30.
/// </remarks>
/// <param name="request">Search parameters to filter results on</param>
/// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns>
Task<IReadOnlyList<Repository>> GetAllForCurrent(RepositoryRequest request);
/// <summary>
/// Gets all repositories owned by the current user.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information.
/// </remarks>
/// <param name="request">Search parameters to filter results on</param>
/// <param name="options">Options for changing the API response</param>
/// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns>
Task<IReadOnlyList<Repository>> GetAllForCurrent(RepositoryRequest request, ApiOptions options);
/// <summary>
/// Gets all repositories owned by the specified user.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-user-repositories">API documentation</a> for more information.
/// The default page size on GitHub.com is 30.
/// </remarks>
/// <param name="login">The account name to search for</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns>
Task<IReadOnlyList<Repository>> GetAllForUser(string login);
/// <summary>
/// Gets all repositories owned by the specified user.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-user-repositories">API documentation</a> for more information.
/// </remarks>
/// <param name="login">The account name to search for</param>
/// <param name="options">Options for changing the API response</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns>
Task<IReadOnlyList<Repository>> GetAllForUser(string login, ApiOptions options);
/// <summary>
/// Gets all repositories owned by the specified organization.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-organization-repositories">API documentation</a> for more information.
/// The default page size on GitHub.com is 30.
/// </remarks>
/// <param name="organization">The organization name to search for</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns>
Task<IReadOnlyList<Repository>> GetAllForOrg(string organization);
/// <summary>
/// Gets all repositories owned by the specified organization.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-organization-repositories">API documentation</a> for more information.
/// </remarks>
/// <param name="organization">The organization name to search for</param>
/// <param name="options">Options for changing the API response</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns>
Task<IReadOnlyList<Repository>> GetAllForOrg(string organization, ApiOptions options);
/// <summary>
/// A client for GitHub's Commit Status API.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/statuses/">Commit Status API documentation</a> for more
/// details. Also check out the <a href="https://github.com/blog/1227-commit-status-api">blog post</a>
/// that announced this feature.
/// </remarks>
ICommitStatusClient Status { get; }
/// <summary>
/// A client for GitHub's Repository Hooks API.
/// </summary>
/// <remarks>See <a href="http://developer.github.com/v3/repos/hooks/">Hooks API documentation</a> for more information.</remarks>
IRepositoryHooksClient Hooks { get; }
/// <summary>
/// A client for GitHub's Repository Forks API.
/// </summary>
/// <remarks>See <a href="http://developer.github.com/v3/repos/forks/">Forks API documentation</a> for more information.</remarks>
IRepositoryForksClient Forks { get; }
/// <summary>
/// A client for GitHub's Repo Collaborators.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/">Collaborators API documentation</a> for more details
/// </remarks>
IRepoCollaboratorsClient Collaborator { get; }
/// <summary>
/// Client for GitHub's Repository Deployments API
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/deployments/">Deployments API documentation</a> for more details
/// </remarks>
IDeploymentsClient Deployment { get; }
/// <summary>
/// Client for GitHub's Repository Statistics API.
/// Note that the GitHub API uses caching on these endpoints,
/// see <a href="https://developer.github.com/v3/repos/statistics/#a-word-about-caching">a word about caching</a> for more details.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/statistics/">Statistics API documentation</a> for more details
///</remarks>
IStatisticsClient Statistics { get; }
/// <summary>
/// Client for GitHub's Repository Commits API
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/commits/">Commits API documentation</a> for more details
///</remarks>
IRepositoryCommitsClient Commit { get; }
/// <summary>
/// Access GitHub's Releases API.
/// </summary>
/// <remarks>
/// Refer to the API documentation for more information: https://developer.github.com/v3/repos/releases/
/// </remarks>
IReleasesClient Release { get; }
/// <summary>
/// Client for GitHub's Repository Merging API
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/merging/">Merging API documentation</a> for more details
///</remarks>
IMergingClient Merging { get; }
/// <summary>
/// Gets all contributors for the specified repository. Does not include anonymous contributors.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <returns>All contributors of the repository.</returns>
Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name);
/// <summary>
/// Gets all contributors for the specified repository. Does not include anonymous contributors.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <returns>All contributors of the repository.</returns>
Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(long repositoryId);
/// <summary>
/// Gets all contributors for the specified repository. Does not include anonymous contributors.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="options">Options for changing the API response</param>
/// <returns>All contributors of the repository.</returns>
Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name, ApiOptions options);
/// <summary>
/// Gets all contributors for the specified repository. Does not include anonymous contributors.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="options">Options for changing the API response</param>
/// <returns>All contributors of the repository.</returns>
Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(long repositoryId, ApiOptions options);
/// <summary>
/// Gets all contributors for the specified repository. With the option to include anonymous contributors.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param>
/// <returns>All contributors of the repository.</returns>
Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name, bool includeAnonymous);
/// <summary>
/// Gets all contributors for the specified repository. With the option to include anonymous contributors.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param>
/// <returns>All contributors of the repository.</returns>
Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(long repositoryId, bool includeAnonymous);
/// <summary>
/// Gets all contributors for the specified repository. With the option to include anonymous contributors.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param>
/// <param name="options">Options for changing the API response</param>
/// <returns>All contributors of the repository.</returns>
Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name, bool includeAnonymous, ApiOptions options);
/// <summary>
/// Gets all contributors for the specified repository. With the option to include anonymous contributors.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param>
/// <param name="options">Options for changing the API response</param>
/// <returns>All contributors of the repository.</returns>
Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(long repositoryId, bool includeAnonymous, ApiOptions options);
/// <summary>
/// Gets all languages for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-languages">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <returns>All languages used in the repository and the number of bytes of each language.</returns>
[ExcludeFromPaginationApiOptionsConventionTest("Pagination not supported by GitHub API (tested 29/08/2017)")]
Task<IReadOnlyList<RepositoryLanguage>> GetAllLanguages(string owner, string name);
/// <summary>
/// Gets all languages for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-languages">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <returns>All languages used in the repository and the number of bytes of each language.</returns>
[ExcludeFromPaginationApiOptionsConventionTest("Pagination not supported by GitHub API (tested 29/08/2017)")]
Task<IReadOnlyList<RepositoryLanguage>> GetAllLanguages(long repositoryId);
/// <summary>
/// Gets all teams for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns>
Task<IReadOnlyList<Team>> GetAllTeams(string owner, string name);
/// <summary>
/// Gets all teams for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns>
Task<IReadOnlyList<Team>> GetAllTeams(long repositoryId);
/// <summary>
/// Gets all teams for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="options">Options for changing the API response</param>
/// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns>
Task<IReadOnlyList<Team>> GetAllTeams(string owner, string name, ApiOptions options);
/// <summary>
/// Gets all teams for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="options">Options for changing the API response</param>
/// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns>
Task<IReadOnlyList<Team>> GetAllTeams(long repositoryId, ApiOptions options);
/// <summary>
/// Gets all tags for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <returns>All of the repositories tags.</returns>
Task<IReadOnlyList<RepositoryTag>> GetAllTags(string owner, string name);
/// <summary>
/// Gets all tags for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <returns>All of the repositories tags.</returns>
Task<IReadOnlyList<RepositoryTag>> GetAllTags(long repositoryId);
/// <summary>
/// Gets all tags for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="options">Options for changing the API response</param>
/// <returns>All of the repositories tags.</returns>
Task<IReadOnlyList<RepositoryTag>> GetAllTags(string owner, string name, ApiOptions options);
/// <summary>
/// Gets all tags for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="options">Options for changing the API response</param>
/// <returns>All of the repositories tags.</returns>
Task<IReadOnlyList<RepositoryTag>> GetAllTags(long repositoryId, ApiOptions options);
/// <summary>
/// Get the contents of a repository's license
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/licenses/#get-the-contents-of-a-repositorys-license">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <returns>Returns the contents of the repository's license file, if one is detected.</returns>
Task<RepositoryContentLicense> GetLicenseContents(string owner, string name);
/// <summary>
/// Get the contents of a repository's license
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/licenses/#get-the-contents-of-a-repositorys-license">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <returns>Returns the contents of the repository's license file, if one is detected.</returns>
Task<RepositoryContentLicense> GetLicenseContents(long repositoryId);
/// <summary>
/// Updates the specified repository with the values given in <paramref name="update"/>
/// </summary>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="update">New values to update the repository with</param>
/// <returns>The updated <see cref="T:Octokit.Repository"/></returns>
Task<Repository> Edit(string owner, string name, RepositoryUpdate update);
/// <summary>
/// Updates the specified repository with the values given in <paramref name="update"/>
/// </summary>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="update">New values to update the repository with</param>
/// <returns>The updated <see cref="T:Octokit.Repository"/></returns>
Task<Repository> Edit(long repositoryId, RepositoryUpdate update);
/// <summary>
/// A client for GitHub's Repository Pages API.
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/pages/">Repository Pages API documentation</a> for more information.
/// </remarks>
IRepositoryPagesClient Page { get; }
/// <summary>
/// A client for GitHub's Repository Invitations API.
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/invitations/">Repository Invitations API documentation</a> for more information.
/// </remarks>
IRepositoryInvitationsClient Invitation { get; }
/// <summary>
/// Access GitHub's Repository Traffic API
/// </summary>
/// <remarks>
/// Refer to the API documentation for more information: https://developer.github.com/v3/repos/traffic/
/// </remarks>
IRepositoryTrafficClient Traffic { get; }
/// <summary>
/// Access GitHub's Repository Projects API
/// </summary>
/// <remarks>
/// Refer to the API documentation for more information: https://developer.github.com/v3/repos/projects/
/// </remarks>
IProjectsClient Project { get; }
/// <summary>
/// Gets all topics for the specified owner and repository name.
/// </summary>
/// <remarks>
/// See the <a href="https://docs.github.com/en/rest/reference/repos#get-all-repository-topics">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="options">Options for changing the API response</param>
/// <returns>All topics associated with the repository.</returns>
Task<RepositoryTopics> GetAllTopics(string owner, string name, ApiOptions options);
/// <summary>
/// Gets all topics for the specified owner and repository name.
/// </summary>
/// <remarks>
/// See the <a href="https://docs.github.com/en/rest/reference/repos#get-all-repository-topics">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <returns>All topics associated with the repository.</returns>
Task<RepositoryTopics> GetAllTopics(string owner, string name);
/// <summary>
/// Gets all topics for the specified repository ID.
/// </summary>
/// <remarks>
/// See the <a href="https://docs.github.com/en/rest/reference/repos#get-all-repository-topics">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The ID of the repository</param>
/// <param name="options">Options for changing the API response</param>
/// <returns>All topics associated with the repository.</returns>
Task<RepositoryTopics> GetAllTopics(long repositoryId, ApiOptions options);
/// <summary>
/// Gets all topics for the specified repository ID.
/// </summary>
/// <remarks>
/// See the <a href="https://docs.github.com/en/rest/reference/repos#get-all-repository-topics">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The ID of the repository</param>
/// <returns>All topics associated with the repository.</returns>
Task<RepositoryTopics> GetAllTopics(long repositoryId);
/// <summary>
/// Replaces all topics for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="https://docs.github.com/en/rest/reference/repos#replace-all-repository-topics">API documentation</a> for more details
///
/// This is a replacement operation; it is not additive. To clear repository topics, for example, you could specify an empty list of topics here.
/// </remarks>
/// <param name="repositoryId">The ID of the repository</param>
/// <param name="topics">The list of topics to associate with the repository</param>
/// <returns>All topics now associated with the repository.</returns>
Task<RepositoryTopics> ReplaceAllTopics(long repositoryId, RepositoryTopics topics);
/// <summary>
/// Replaces all topics for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="https://docs.github.com/en/rest/reference/repos#replace-all-repository-topics">API documentation</a> for more details
///
/// This is a replacement operation; it is not additive. To clear repository topics, for example, you could specify an empty list of topics here.
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="topics">The list of topics to associate with the repository</param>
/// <returns>All topics now associated with the repository.</returns>
Task<RepositoryTopics> ReplaceAllTopics(string owner, string name, RepositoryTopics topics);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http
{
/// <summary>
/// Static class containing the WinHttp global callback and associated routines.
/// </summary>
internal static class WinHttpRequestCallback
{
public static Interop.WinHttp.WINHTTP_STATUS_CALLBACK StaticCallbackDelegate =
new Interop.WinHttp.WINHTTP_STATUS_CALLBACK(WinHttpCallback);
public static void WinHttpCallback(
IntPtr handle,
IntPtr context,
uint internetStatus,
IntPtr statusInformation,
uint statusInformationLength)
{
bool invokeCallback = false;
if (Environment.HasShutdownStarted)
{
return;
}
if (context == IntPtr.Zero)
{
return;
}
WinHttpRequestState state = WinHttpRequestState.FromIntPtr(context);
if (state != null &&
state.RequestHandle != null &&
!state.RequestHandle.IsInvalid &&
state.RequestHandle.DangerousGetHandle() == handle)
{
invokeCallback = true;
}
WinHttpTraceHelper.TraceCallbackStatus("WinHttpCallback", handle, invokeCallback, internetStatus);
if (invokeCallback)
{
RequestCallback(handle, state, internetStatus, statusInformation, statusInformationLength);
}
}
private static void RequestCallback(
IntPtr handle,
WinHttpRequestState state,
uint internetStatus,
IntPtr statusInformation,
uint statusInformationLength)
{
try
{
switch (internetStatus)
{
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE:
OnRequestSendRequestComplete(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
OnRequestReadComplete(state, statusInformationLength);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE:
OnRequestWriteComplete(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE:
OnRequestReceiveResponseHeadersComplete(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REDIRECT:
string redirectUriString = Marshal.PtrToStringUni(statusInformation);
var redirectUri = new Uri(redirectUriString);
OnRequestRedirect(state, redirectUri);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDING_REQUEST:
OnRequestSendingRequest(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
Debug.Assert(
statusInformationLength == Marshal.SizeOf<Interop.WinHttp.WINHTTP_ASYNC_RESULT>(),
"RequestCallback: statusInformationLength=" + statusInformationLength +
" must be sizeof(WINHTTP_ASYNC_RESULT)=" + Marshal.SizeOf<Interop.WinHttp.WINHTTP_ASYNC_RESULT>());
var asyncResult = Marshal.PtrToStructure<Interop.WinHttp.WINHTTP_ASYNC_RESULT>(statusInformation);
OnRequestError(state, asyncResult);
return;
default:
return;
}
}
catch (Exception ex)
{
Interop.WinHttp.WinHttpCloseHandle(handle);
state.SavedException = ex;
}
}
private static void OnRequestSendRequestComplete(WinHttpRequestState state)
{
Debug.Assert(state != null, "OnRequestSendRequestComplete: state is null");
Debug.Assert(state.TcsSendRequest != null, "OnRequestSendRequestComplete: TcsSendRequest is null");
Debug.Assert(!state.TcsSendRequest.Task.IsCompleted, "OnRequestSendRequestComplete: TcsSendRequest.Task is completed");
state.TcsSendRequest.TrySetResult(true);
}
private static void OnRequestReadComplete(WinHttpRequestState state, uint bytesRead)
{
Debug.Assert(state != null, "OnRequestReadComplete: state is null");
Debug.Assert(state.TcsReadFromResponseStream != null, "TcsReadFromResponseStream is null");
Debug.Assert(!state.TcsReadFromResponseStream.Task.IsCompleted, "TcsReadFromResponseStream.Task is completed");
state.TcsReadFromResponseStream.TrySetResult((int)bytesRead);
}
private static void OnRequestWriteComplete(WinHttpRequestState state)
{
Debug.Assert(state != null, "OnRequestWriteComplete: state is null");
Debug.Assert(state.TcsInternalWriteDataToRequestStream != null, "TcsInternalWriteDataToRequestStream is null");
Debug.Assert(!state.TcsInternalWriteDataToRequestStream.Task.IsCompleted, "TcsInternalWriteDataToRequestStream.Task is completed");
state.TcsInternalWriteDataToRequestStream.TrySetResult(true);
}
private static void OnRequestReceiveResponseHeadersComplete(WinHttpRequestState state)
{
Debug.Assert(state != null, "OnRequestReceiveResponseHeadersComplete: state is null");
Debug.Assert(state.TcsReceiveResponseHeaders != null, "TcsReceiveResponseHeaders is null");
Debug.Assert(!state.TcsReceiveResponseHeaders.Task.IsCompleted, "TcsReceiveResponseHeaders.Task is completed");
state.TcsReceiveResponseHeaders.TrySetResult(true);
}
private static void OnRequestRedirect(WinHttpRequestState state, Uri redirectUri)
{
const string EmptyCookieHeader = "Cookie:";
Debug.Assert(state != null, "OnRequestRedirect: state is null");
Debug.Assert(redirectUri != null, "OnRequestRedirect: redirectUri is null");
Debug.Assert(state.TcsReceiveResponseHeaders != null, "TcsReceiveResponseHeaders is null");
Debug.Assert(!state.TcsReceiveResponseHeaders.Task.IsCompleted, "TcsReceiveResponseHeaders.Task is completed");
// If we're manually handling cookies, we need to reset them based on the new URI.
if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer)
{
// Clear cookies.
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
state.RequestHandle,
EmptyCookieHeader,
(uint)EmptyCookieHeader.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_REPLACE))
{
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND)
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
// Re-add cookies. The GetCookieHeader() method will return the correct set of
// cookies based on the redirectUri.
string cookieHeader = WinHttpHandler.GetCookieHeader(redirectUri, state.Handler.CookieContainer);
if (!string.IsNullOrEmpty(cookieHeader))
{
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
state.RequestHandle,
cookieHeader,
(uint)cookieHeader.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
}
state.RequestMessage.RequestUri = redirectUri;
// Redirection to a new uri may require a new connection through a potentially different proxy.
// If so, we will need to respond to additional 407 proxy auth demands and re-attach any
// proxy credentials. The ProcessResponse() method looks at the state.LastStatusCode
// before attaching proxy credentials and marking the HTTP request to be re-submitted.
// So we need to reset the LastStatusCode remembered. Otherwise, it will see additional 407
// responses as an indication that proxy auth failed and won't retry the HTTP request.
if (state.LastStatusCode == HttpStatusCode.ProxyAuthenticationRequired)
{
state.LastStatusCode = 0;
}
// For security reasons, we drop the server credential if it is a
// NetworkCredential. But we allow credentials in a CredentialCache
// since they are specifically tied to URI's.
if (!(state.ServerCredentials is CredentialCache))
{
state.ServerCredentials = null;
}
}
private static void OnRequestSendingRequest(WinHttpRequestState state)
{
Debug.Assert(state != null, "OnRequestSendingRequest: state is null");
if (state.RequestMessage.RequestUri.Scheme != UriScheme.Https)
{
// Not SSL/TLS.
return;
}
// Grab the channel binding token (CBT) information from the request handle and put it into
// the TransportContext object.
state.TransportContext.SetChannelBinding(state.RequestHandle);
if (state.ServerCertificateValidationCallback != null)
{
IntPtr certHandle = IntPtr.Zero;
uint certHandleSize = (uint)IntPtr.Size;
if (!Interop.WinHttp.WinHttpQueryOption(
state.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_SERVER_CERT_CONTEXT,
ref certHandle,
ref certHandleSize))
{
int lastError = Marshal.GetLastWin32Error();
throw WinHttpException.CreateExceptionUsingError(lastError);
}
// Create a managed wrapper around the certificate handle. Since this results in duplicating
// the handle, we will close the original handle after creating the wrapper.
var serverCertificate = new X509Certificate2(certHandle);
Interop.Crypt32.CertFreeCertificateContext(certHandle);
X509Chain chain = null;
SslPolicyErrors sslPolicyErrors;
try
{
WinHttpCertificateHelper.BuildChain(
serverCertificate,
state.RequestMessage.RequestUri.Host,
state.CheckCertificateRevocationList,
out chain,
out sslPolicyErrors);
bool result = state.ServerCertificateValidationCallback(
state.RequestMessage,
serverCertificate,
chain,
sslPolicyErrors);
if (!result)
{
throw WinHttpException.CreateExceptionUsingError(
(int)Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE);
}
}
finally
{
if (chain != null)
{
chain.Dispose();
}
}
}
}
private static void OnRequestError(WinHttpRequestState state, Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult)
{
WinHttpTraceHelper.TraceAsyncError("OnRequestError", asyncResult);
Debug.Assert(state != null, "OnRequestError: state is null");
var innerException = WinHttpException.CreateExceptionUsingError((int)asyncResult.dwError);
switch ((uint)asyncResult.dwResult.ToInt32())
{
case Interop.WinHttp.API_SEND_REQUEST:
state.TcsSendRequest.TrySetException(innerException);
break;
case Interop.WinHttp.API_RECEIVE_RESPONSE:
if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_RESEND_REQUEST)
{
state.RetryRequest = true;
state.TcsReceiveResponseHeaders.TrySetResult(false);
}
else if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED)
{
// WinHttp will automatically drop any client SSL certificates that we
// have pre-set into the request handle including the NULL certificate
// (which means we have no certs to send). For security reasons, we don't
// allow the certificate to be re-applied. But we need to tell WinHttp
// explicitly that we don't have any certificate to send.
WinHttpHandler.SetNoClientCertificate(state.RequestHandle);
state.RetryRequest = true;
state.TcsReceiveResponseHeaders.TrySetResult(false);
}
else if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED)
{
state.TcsReceiveResponseHeaders.TrySetCanceled(state.CancellationToken);
}
else
{
state.TcsReceiveResponseHeaders.TrySetException(innerException);
}
break;
case Interop.WinHttp.API_READ_DATA:
if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED)
{
// TODO: Issue #2165. We need to pass in the cancellation token from the
// user's ReadAsync() call into the TrySetCanceled().
Debug.WriteLine("RequestCallback: API_READ_DATA - ERROR_WINHTTP_OPERATION_CANCELLED");
state.TcsReadFromResponseStream.TrySetCanceled();
}
else
{
state.TcsReadFromResponseStream.TrySetException(
new IOException(SR.net_http_io_read, innerException));
}
break;
case Interop.WinHttp.API_WRITE_DATA:
if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED)
{
// TODO: Issue #2165. We need to pass in the cancellation token from the
// user's WriteAsync() call into the TrySetCanceled().
Debug.WriteLine("RequestCallback: API_WRITE_DATA - ERROR_WINHTTP_OPERATION_CANCELLED");
state.TcsInternalWriteDataToRequestStream.TrySetCanceled();
}
else
{
state.TcsInternalWriteDataToRequestStream.TrySetException(
new IOException(SR.net_http_io_write, innerException));
}
break;
default:
Debug.Fail(
"OnRequestError: Result (" + asyncResult.dwResult + ") is not expected.",
"Error code: " + asyncResult.dwError + " (" + innerException.Message + ")");
break;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Drawing.ColorTranslator.cs
//
// Authors:
// Dennis Hayes (dennish@raytek.com)
// Ravindra (rkumar@novell.com)
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2001 Ximian, Inc. http://www.ximian.com
// Copyright (C) 2004,2006-2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.ComponentModel;
using System.Globalization;
namespace System.Drawing
{
public sealed class ColorTranslator
{
private ColorTranslator()
{
}
public static Color FromHtml(string htmlColor)
{
if (string.IsNullOrEmpty(htmlColor))
return Color.Empty;
switch (htmlColor.ToLowerInvariant())
{
case "buttonface":
case "threedface":
return SystemColors.Control;
case "buttonhighlight":
case "threedlightshadow":
return SystemColors.ControlLightLight;
case "buttonshadow":
return SystemColors.ControlDark;
case "captiontext":
return SystemColors.ActiveCaptionText;
case "threeddarkshadow":
return SystemColors.ControlDarkDark;
case "threedhighlight":
return SystemColors.ControlLight;
case "background":
return SystemColors.Desktop;
case "buttontext":
return SystemColors.ControlText;
case "infobackground":
return SystemColors.Info;
// special case for Color.LightGray versus html's LightGrey (#340917)
case "lightgrey":
return Color.LightGray;
}
if (htmlColor[0] == '#' && htmlColor.Length == 4)
{
char r = htmlColor[1], g = htmlColor[2], b = htmlColor[3];
htmlColor = new string(new char[] { '#', r, r, g, g, b, b });
}
#if NETCORE
return ColorConverterCommon.ConvertFromString(htmlColor, CultureInfo.CurrentCulture);
#else
TypeConverter converter = TypeDescriptor.GetConverter (typeof (Color));
return (Color) converter.ConvertFromString (htmlColor);
#endif
}
internal static Color FromBGR(int bgr)
{
Color result = Color.FromArgb(0xFF, (bgr & 0xFF), ((bgr >> 8) & 0xFF), ((bgr >> 16) & 0xFF));
Color known = KnownColors.FindColorMatch(result);
return (known.IsEmpty) ? result : known;
}
public static Color FromOle(int oleColor)
{
// OleColor format is BGR
return FromBGR(oleColor);
}
public static Color FromWin32(int win32Color)
{
// Win32Color format is BGR
return FromBGR(win32Color);
}
public static string ToHtml(Color c)
{
if (c.IsEmpty)
return String.Empty;
if (ColorUtil.IsSystemColor(c))
{
KnownColor kc = c.ToKnownColor();
switch (kc)
{
case KnownColor.ActiveBorder:
case KnownColor.ActiveCaption:
case KnownColor.AppWorkspace:
case KnownColor.GrayText:
case KnownColor.Highlight:
case KnownColor.HighlightText:
case KnownColor.InactiveBorder:
case KnownColor.InactiveCaption:
case KnownColor.InactiveCaptionText:
case KnownColor.InfoText:
case KnownColor.Menu:
case KnownColor.MenuText:
case KnownColor.ScrollBar:
case KnownColor.Window:
case KnownColor.WindowFrame:
case KnownColor.WindowText:
return KnownColors.GetName(kc).ToLowerInvariant();
case KnownColor.ActiveCaptionText:
return "captiontext";
case KnownColor.Control:
return "buttonface";
case KnownColor.ControlDark:
return "buttonshadow";
case KnownColor.ControlDarkDark:
return "threeddarkshadow";
case KnownColor.ControlLight:
return "buttonface";
case KnownColor.ControlLightLight:
return "buttonhighlight";
case KnownColor.ControlText:
return "buttontext";
case KnownColor.Desktop:
return "background";
case KnownColor.HotTrack:
return "highlight";
case KnownColor.Info:
return "infobackground";
default:
return String.Empty;
}
}
if (c.IsNamedColor)
{
if (c == Color.LightGray)
return "LightGrey";
else
return c.Name;
}
return FormatHtml(c.R, c.G, c.B);
}
static char GetHexNumber(int b)
{
return (char)(b > 9 ? 55 + b : 48 + b);
}
static string FormatHtml(int r, int g, int b)
{
char[] htmlColor = new char[7];
htmlColor[0] = '#';
htmlColor[1] = GetHexNumber((r >> 4) & 15);
htmlColor[2] = GetHexNumber(r & 15);
htmlColor[3] = GetHexNumber((g >> 4) & 15);
htmlColor[4] = GetHexNumber(g & 15);
htmlColor[5] = GetHexNumber((b >> 4) & 15);
htmlColor[6] = GetHexNumber(b & 15);
return new string(htmlColor);
}
public static int ToOle(Color c)
{
// OleColor format is BGR, same as Win32
return ((c.B << 16) | (c.G << 8) | c.R);
}
public static int ToWin32(Color c)
{
// Win32Color format is BGR, Same as OleColor
return ((c.B << 16) | (c.G << 8) | c.R);
}
}
}
| |
// 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 Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ArrayOperations operations.
/// </summary>
internal partial class ArrayOperations : IServiceOperations<AzureCompositeModel>, IArrayOperations
{
/// <summary>
/// Initializes a new instance of the ArrayOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ArrayOperations(AzureCompositeModel client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModel
/// </summary>
public AzureCompositeModel Client { get; private set; }
/// <summary>
/// Get complex types with array property
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ArrayWrapper>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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<ArrayWrapper>();
_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 = SafeJsonConvert.DeserializeObject<ArrayWrapper>(_responseContent, this.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>
/// Put complex types with array property
/// </summary>
/// <param name='array'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutValidWithHttpMessagesAsync(IList<string> array = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
ArrayWrapper complexBody = new ArrayWrapper();
if (array != null)
{
complexBody.Array = array;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get complex types with array property which is empty
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ArrayWrapper>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/empty").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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<ArrayWrapper>();
_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 = SafeJsonConvert.DeserializeObject<ArrayWrapper>(_responseContent, this.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>
/// Put complex types with array property which is empty
/// </summary>
/// <param name='array'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutEmptyWithHttpMessagesAsync(IList<string> array = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
ArrayWrapper complexBody = new ArrayWrapper();
if (array != null)
{
complexBody.Array = array;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/empty").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get complex types with array property while server doesn't provide a
/// response payload
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ArrayWrapper>> GetNotProvidedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/notprovided").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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<ArrayWrapper>();
_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 = SafeJsonConvert.DeserializeObject<ArrayWrapper>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
using Internal.Runtime.CompilerServices;
namespace System
{
/// <summary>
/// Represents a contiguous region of memory, similar to <see cref="ReadOnlySpan{T}"/>.
/// Unlike <see cref="ReadOnlySpan{T}"/>, it is not a byref-like type.
/// </summary>
[DebuggerTypeProxy(typeof(MemoryDebugView<>))]
[DebuggerDisplay("{ToString(),raw}")]
public readonly struct ReadOnlyMemory<T>
{
// NOTE: With the current implementation, Memory<T> and ReadOnlyMemory<T> must have the same layout,
// as code uses Unsafe.As to cast between them.
// The highest order bit of _index is used to discern whether _object is an array/string or an owned memory
// if (_index >> 31) == 1, _object is an MemoryManager<T>
// else, _object is a T[] or string.
// if (_length >> 31) == 1, _object is a pre-pinned array, so Pin() will not allocate a new GCHandle
// else, Pin() needs to allocate a new GCHandle to pin the object.
private readonly object _object;
private readonly int _index;
private readonly int _length;
internal const int RemoveFlagsBitMask = 0x7FFFFFFF;
/// <summary>
/// Creates a new memory over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory(T[] array)
{
if (array == null)
{
this = default;
return; // returns default
}
_object = array;
_index = 0;
_length = array.Length;
}
/// <summary>
/// Creates a new memory over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory(T[] array, int start, int length)
{
if (array == null)
{
if (start != 0 || length != 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
this = default;
return; // returns default
}
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
_object = array;
_index = start;
_length = length;
}
/// <summary>Creates a new memory over the existing object, start, and length. No validation is performed.</summary>
/// <param name="obj">The target object.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ReadOnlyMemory(object obj, int start, int length)
{
// No validation performed; caller must provide any necessary validation.
_object = obj;
_index = start;
_length = length;
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(T[] array) => new ReadOnlyMemory<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> segment) => new ReadOnlyMemory<T>(segment.Array, segment.Offset, segment.Count);
/// <summary>
/// Returns an empty <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static ReadOnlyMemory<T> Empty => default;
/// <summary>
/// The number of items in the memory.
/// </summary>
public int Length => _length & RemoveFlagsBitMask;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => (_length & RemoveFlagsBitMask) == 0;
/// <summary>
/// For <see cref="ReadOnlyMemory{Char}"/>, returns a new instance of string that represents the characters pointed to by the memory.
/// Otherwise, returns a <see cref="string"/> with the name of the type and the number of elements.
/// </summary>
public override string ToString()
{
if (typeof(T) == typeof(char))
{
return (_object is string str) ? str.Substring(_index, _length & RemoveFlagsBitMask) : Span.ToString();
}
return string.Format("System.ReadOnlyMemory<{0}>[{1}]", typeof(T).Name, _length & RemoveFlagsBitMask);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory<T> Slice(int start)
{
// Used to maintain the high-bit which indicates whether the Memory has been pre-pinned or not.
int capturedLength = _length;
int actualLength = capturedLength & RemoveFlagsBitMask;
if ((uint)start > (uint)actualLength)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
}
// It is expected for (capturedLength - start) to be negative if the memory is already pre-pinned.
return new ReadOnlyMemory<T>(_object, _index + start, capturedLength - start);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory<T> Slice(int start, int length)
{
// Used to maintain the high-bit which indicates whether the Memory has been pre-pinned or not.
int capturedLength = _length;
int actualLength = _length & RemoveFlagsBitMask;
if ((uint)start > (uint)actualLength || (uint)length > (uint)(actualLength - start))
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
}
// Set the high-bit to match the this._length high bit (1 for pre-pinned, 0 for unpinned).
return new ReadOnlyMemory<T>(_object, _index + start, length | (capturedLength & ~RemoveFlagsBitMask));
}
/// <summary>
/// Returns a span from the memory.
/// </summary>
public ReadOnlySpan<T> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (_index < 0)
{
Debug.Assert(_length >= 0);
Debug.Assert(_object != null);
return ((MemoryManager<T>)_object).GetSpan().Slice(_index & RemoveFlagsBitMask, _length);
}
else if (typeof(T) == typeof(char) && _object is string s)
{
Debug.Assert(_length >= 0);
return new ReadOnlySpan<T>(ref Unsafe.As<char, T>(ref s.GetRawStringData()), s.Length).Slice(_index, _length);
}
else if (_object != null)
{
return new ReadOnlySpan<T>((T[])_object, _index, _length & RemoveFlagsBitMask);
}
else
{
return default;
}
}
}
/// <summary>
/// Copies the contents of the read-only memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <param name="destination">The Memory to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination is shorter than the source.
/// </exception>
/// </summary>
public void CopyTo(Memory<T> destination) => Span.CopyTo(destination.Span);
/// <summary>
/// Copies the contents of the readonly-only memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <returns>If the destination is shorter than the source, this method
/// return false and no data is written to the destination.</returns>
/// </summary>
/// <param name="destination">The span to copy items into.</param>
public bool TryCopyTo(Memory<T> destination) => Span.TryCopyTo(destination.Span);
/// <summary>
/// Creates a handle for the memory.
/// The GC will not move the memory until the returned <see cref="MemoryHandle"/>
/// is disposed, enabling taking and using the memory's address.
/// <exception cref="System.ArgumentException">
/// An instance with nonprimitive (non-blittable) members cannot be pinned.
/// </exception>
/// </summary>
public unsafe MemoryHandle Pin()
{
if (_index < 0)
{
Debug.Assert(_object != null);
return ((MemoryManager<T>)_object).Pin((_index & RemoveFlagsBitMask));
}
else if (typeof(T) == typeof(char) && _object is string s)
{
GCHandle handle = GCHandle.Alloc(s, GCHandleType.Pinned);
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref s.GetRawStringData()), _index);
return new MemoryHandle(pointer, handle);
}
else if (_object is T[] array)
{
// Array is already pre-pinned
if (_length < 0)
{
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref array.GetRawSzArrayData()), _index);
return new MemoryHandle(pointer);
}
else
{
GCHandle handle = GCHandle.Alloc(array, GCHandleType.Pinned);
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref array.GetRawSzArrayData()), _index);
return new MemoryHandle(pointer, handle);
}
}
return default;
}
/// <summary>
/// Copies the contents from the memory into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray() => Span.ToArray();
/// <summary>Determines whether the specified object is equal to the current object.</summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
if (obj is ReadOnlyMemory<T> readOnlyMemory)
{
return Equals(readOnlyMemory);
}
else if (obj is Memory<T> memory)
{
return Equals(memory);
}
else
{
return false;
}
}
/// <summary>
/// Returns true if the memory points to the same array and has the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public bool Equals(ReadOnlyMemory<T> other)
{
return
_object == other._object &&
_index == other._index &&
_length == other._length;
}
/// <summary>Returns the hash code for this <see cref="ReadOnlyMemory{T}"/></summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
return _object != null ? CombineHashCodes(_object.GetHashCode(), _index.GetHashCode(), _length.GetHashCode()) : 0;
}
private static int CombineHashCodes(int left, int right)
{
return ((left << 5) + left) ^ right;
}
private static int CombineHashCodes(int h1, int h2, int h3)
{
return CombineHashCodes(CombineHashCodes(h1, h2), h3);
}
/// <summary>Gets the state of the memory as individual fields.</summary>
/// <param name="start">The offset.</param>
/// <param name="length">The count.</param>
/// <returns>The object.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal object GetObjectStartLength(out int start, out int length)
{
start = _index;
length = _length;
return _object;
}
}
}
| |
// 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.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Platform;
using osu.Framework.Testing;
using osuTK;
using osuTK.Graphics;
namespace osu.Framework.Tests.Exceptions
{
[TestFixture]
public class TestLoadExceptions
{
[Test]
public void TestLoadIntoInvalidTarget()
{
var loadable = new DelayedTestBoxAsync();
var loadTarget = new LoadTarget(loadable);
Assert.Throws<InvalidOperationException>(() => loadTarget.PerformAsyncLoad());
}
[Test]
public void TestSingleSyncAdd()
{
var loadable = new DelayedTestBoxAsync();
Assert.DoesNotThrow(() =>
{
runGameWithLogic(g =>
{
g.Add(loadable);
Assert.IsTrue(loadable.LoadState == LoadState.Ready);
Assert.AreEqual(loadable.Parent, g);
g.Exit();
});
});
}
[Test]
public void TestSingleAsyncAdd()
{
var loadable = new DelayedTestBoxAsync();
var loadTarget = new LoadTarget(loadable);
Assert.DoesNotThrow(() =>
{
runGameWithLogic(g =>
{
g.Add(loadTarget);
loadTarget.PerformAsyncLoad();
}, g => loadable.Parent == loadTarget);
});
}
[Test]
public void TestDoubleAsyncLoad()
{
var loadable = new DelayedTestBoxAsync();
var loadTarget = new LoadTarget(loadable);
Assert.DoesNotThrow(() =>
{
runGameWithLogic(g =>
{
g.Add(loadTarget);
loadTarget.PerformAsyncLoad();
loadTarget.PerformAsyncLoad(false);
}, g => loadable.Parent == loadTarget);
});
}
[Test]
public void TestDoubleAsyncAddFails()
{
Assert.Throws<InvalidOperationException>(() =>
{
runGameWithLogic(g =>
{
var loadable = new DelayedTestBoxAsync();
var loadTarget = new LoadTarget(loadable);
g.Add(loadTarget);
loadTarget.PerformAsyncLoad();
loadTarget.PerformAsyncLoad();
});
});
}
[Test]
public void TestTargetDisposedDuringAsyncLoad()
{
Assert.Throws<ObjectDisposedException>(() =>
{
runGameWithLogic(g =>
{
var loadable = new DelayedTestBoxAsync();
var loadTarget = new LoadTarget(loadable);
g.Add(loadTarget);
loadTarget.PerformAsyncLoad();
while (loadable.LoadState < LoadState.Loading)
Thread.Sleep(1);
g.Dispose();
});
});
}
[Test]
public void TestLoadableDisposedDuringAsyncLoad()
{
Assert.Throws<ObjectDisposedException>(() =>
{
runGameWithLogic(g =>
{
var loadable = new DelayedTestBoxAsync();
var loadTarget = new LoadTarget(loadable);
g.Add(loadTarget);
loadTarget.PerformAsyncLoad();
while (loadable.LoadState < LoadState.Loading)
Thread.Sleep(1);
loadable.Dispose();
});
});
}
/// <summary>
/// The async load completion callback is scheduled on the <see cref="Game"/>. The callback is generally used to add the child to the container,
/// however it is possible for the container to be disposed when this occurs due to being scheduled on the <see cref="Game"/>. If this occurs,
/// the cancellation is invoked and the completion task should not be run.
///
/// This is a very timing-dependent test which performs the following sequence:
/// LoadAsync -> schedule Callback -> dispose parent -> invoke scheduled callback
/// </summary>
[Test]
public void TestDisposeAfterLoad()
{
Assert.DoesNotThrow(() =>
{
var loadTarget = new LoadTarget(new DelayedTestBoxAsync());
bool allowDispose = false;
bool disposeTriggered = false;
bool updatedAfterDispose = false;
runGameWithLogic(g =>
{
g.Add(loadTarget);
loadTarget.PerformAsyncLoad().ContinueWith(t => allowDispose = true);
}, g =>
{
// The following code is done here for a very specific reason, but can occur naturally in normal use
// This delegate is essentially the first item in the game's scheduler, so it will always run PRIOR to the async callback
if (disposeTriggered)
updatedAfterDispose = true;
if (allowDispose)
{
// Async load has complete, the callback has been scheduled but NOT run yet
// Dispose the parent container - this is done by clearing the game
g.Clear(true);
disposeTriggered = true;
}
// After disposing the parent, one update loop is required
return updatedAfterDispose;
});
});
}
[Test]
public void TestSyncLoadException()
{
Assert.Throws<AsyncTestException>(() => runGameWithLogic(g => g.Add(new DelayedTestBoxAsync(true))));
}
[SuppressMessage("ReSharper", "AccessToDisposedClosure")]
private void runGameWithLogic(Action<Game> logic, Func<Game, bool> exitCondition = null)
{
Storage storage = null;
try
{
using (var host = new TestRunHeadlessGameHost($"{GetType().Name}-{Guid.NewGuid()}", new HostOptions()))
{
using (var game = new TestGame())
{
game.Schedule(() =>
{
storage = host.Storage;
host.UpdateThread.Scheduler.AddDelayed(() =>
{
if (exitCondition?.Invoke(game) == true)
host.Exit();
}, 0, true);
logic(game);
});
host.Run(game);
}
}
}
finally
{
try
{
storage?.DeleteDirectory(string.Empty);
}
catch
{
// May fail due to the file handles still being open on Windows, but this isn't a big problem for us
}
}
}
private class LoadTarget : Container
{
private readonly Drawable loadable;
public LoadTarget(Drawable loadable)
{
this.loadable = loadable;
}
public Task PerformAsyncLoad(bool withAdd = true) => LoadComponentAsync(loadable, _ =>
{
if (withAdd) Add(loadable);
});
}
public class DelayedTestBoxAsync : Box
{
private readonly bool throws;
public DelayedTestBoxAsync(bool throws = false)
{
this.throws = throws;
Size = new Vector2(50);
Colour = Color4.Green;
}
[BackgroundDependencyLoader]
private void load()
{
Task.Delay((int)(1000 / Clock.Rate)).WaitSafely();
if (throws)
throw new AsyncTestException();
}
}
private class AsyncTestException : Exception
{
}
}
}
| |
//-----------------------------------------------------------------------
// Copyright (c) Microsoft Open Technologies, Inc.
// All Rights Reserved
// Apache License 2.0
//
// 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 Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Configuration;
using System.IdentityModel.Configuration;
using System.IdentityModel.Tokens;
using System.Security.Cryptography.X509Certificates;
namespace System.IdentityModel.Test
{
[TestClass]
public class NamedKeyIssuerTokenResolverDefaultConfigTest : ConfigurationTest
{
/// <summary>
/// Test Context Wrapper instance on top of TestContext. Provides better accessor functions
/// </summary>
protected TestContextProvider _testContextProvider;
[ClassInitialize]
public static void ClassSetup( TestContext testContext )
{
}
[TestInitialize]
public void Initialize()
{
_testContextProvider = new TestContextProvider( TestContext );
}
/// <summary>
/// The test context that is set by Visual Studio and TAEF - need to keep this exact signature
/// </summary>
public TestContext TestContext { get; set; }
public NamedKeyIssuerTokenResolverDefaultConfigTest()
{
}
protected override string GetConfiguration( string testVariation )
{
return @"<system.identityModel>
<identityConfiguration>
<issuerTokenResolver type='" + typeof( NamedKeyIssuerTokenResolver ).AssemblyQualifiedName + @"' />
</identityConfiguration>
</system.identityModel>";
}
protected override void ValidateTestCase( string testVariation )
{
IdentityConfiguration identityConfig = new IdentityConfiguration( IdentityConfiguration.DefaultServiceName );
Assert.IsNotNull( identityConfig.IssuerTokenResolver );
Assert.IsFalse( identityConfig.IssuerTokenResolver.GetType() != typeof( NamedKeyIssuerTokenResolver ) , string.Format( "Expected identityConfiguration.IsuerTokenResolver.GetType() == typeof( NamedKeyIssuerTokenResolver ), was: '{0}'", identityConfig.IssuerTokenResolver.GetType() ) );
NamedKeyIssuerTokenResolver resolver = identityConfig.IssuerTokenResolver as NamedKeyIssuerTokenResolver;
Assert.IsTrue( resolver.SecurityKeys.Count == 0 );
Assert.IsTrue( IssuerTokenResolver.DefaultStoreName == StoreName.TrustedPeople );
Assert.IsTrue( IssuerTokenResolver.DefaultStoreLocation == StoreLocation.LocalMachine );
// Should not find key
SecurityKey key = null;
NamedKeySecurityKeyIdentifierClause clause = new NamedKeySecurityKeyIdentifierClause( "keyName", "KeyingMaterial.SymmetricKeyBytes_256" );
Assert.IsFalse( resolver.TryResolveSecurityKey( clause, out key ) );
Assert.IsNull( key );
// Should not find token
SecurityToken token = null;
Assert.IsFalse( resolver.TryResolveToken( clause, out token ) );
Assert.IsNull( token );
}
[TestMethod]
[TestProperty( "TestCaseID", "5BD621E8-9427-499D-A9D3-941BD2672752" )]
[Description( "Default NamedKeyIssuerTokenResolver" )]
public void LoadNamedKeyIssuerTokenResolver()
{
RunTestCase( string.Empty );
}
}
[TestClass]
public class NamedKeyIssuerTokenResolverMultipleKeysConfigTest : ConfigurationTest
{
/// <summary>
/// Test Context Wrapper instance on top of TestContext. Provides better accessor functions
/// </summary>
protected TestContextProvider _testContextProvider;
[ClassInitialize]
public static void ClassSetup( TestContext testContext )
{
}
public NamedKeyIssuerTokenResolverMultipleKeysConfigTest()
{}
protected override string GetConfiguration( string testVariation )
{
return @"
<system.identityModel>
<identityConfiguration>
<issuerTokenResolver type='System.IdentityModel.Tokens.NamedKeyIssuerTokenResolver, System.IdentityModel.Tokens.JWT'>
<securityKey symmetricKey='jWo8qtxA05mPwwjMPhIS7w==' name='LocalSTS' />
<securityKey symmetricKey='Vbxq2mlbGJw8XH+ZoYBnUHmHga8/o/IduvU/Tht70iE=' name='LiveId' />
<securityKey symmetricKey='Vbxq2mlbGJw8XH+ZoYBnUHmHga8/o/IduvU/Tht70iE=' name='LocalSTS' />
</issuerTokenResolver>
</identityConfiguration>
</system.identityModel>";
}
protected override void ValidateTestCase( string testCase )
{
IdentityConfiguration identityConfig = new IdentityConfiguration( IdentityConfiguration.DefaultServiceName );
Assert.IsNotNull( identityConfig.IssuerTokenResolver );
Assert.IsFalse( identityConfig.IssuerTokenResolver.GetType() != typeof( NamedKeyIssuerTokenResolver ) , string.Format( "Expected identityConfiguration.IsuerTokenResolver.GetType() == typeof( NamedKeyIssuerTokenResolver ), was: '{0}'", identityConfig.IssuerTokenResolver.GetType() ) );
NamedKeyIssuerTokenResolver resolver = identityConfig.IssuerTokenResolver as NamedKeyIssuerTokenResolver;
Assert.IsTrue( resolver.SecurityKeys.Count == 2 );
Assert.IsTrue( IssuerTokenResolver.DefaultStoreName == StoreName.TrustedPeople );
Assert.IsTrue( IssuerTokenResolver.DefaultStoreLocation == StoreLocation.LocalMachine );
// Should find key
SecurityKey key = KeyingMaterial.SymmetricSecurityKey_256;
NamedKeySecurityKeyIdentifierClause clause = new NamedKeySecurityKeyIdentifierClause( "LiveId", "key" );
Assert.IsTrue( resolver.TryResolveSecurityKey( clause, out key ) );
Assert.IsNotNull( key );
// Should not find token
SecurityToken token = null;
Assert.IsTrue( resolver.TryResolveToken( clause, out token ) );
Assert.IsNotNull( token );
}
[TestMethod]
[TestProperty( "TestCaseID", "1E62250E-9208-4917-8677-0C82EFE6823E" )]
[Description( "MultiKey NamedKeyIssuerTokenResolver" )]
public void MultiKeyNamedKeyIssuerTokenResolver()
{
RunTestCase( string.Empty );
}
}
[TestClass]
public class NamedKeyIssuerTokenResolverInvalidConfig : ConfigurationTest
{
static Dictionary<string, string> _testCases = new Dictionary<string, string>();
/// <summary>
/// Test Context Wrapper instance on top of TestContext. Provides better accessor functions
/// </summary>
protected TestContextProvider _testContextProvider;
public NamedKeyIssuerTokenResolverInvalidConfig()
{
}
[ClassInitialize]
public static void ClassSetup( TestContext testContext )
{
_testCases.Add( "AsymmetricKey",
@"<issuerTokenResolver type='System.IdentityModel.Tokens.NamedKeyIssuerTokenResolver, System.IdentityModel.Tokens.JWT'>
<securityKey asymmetricKey='jWo8qtxA05mPwwjMPhIS7w==' name='LocalSTS' />
</issuerTokenResolver>" );
_testCases.Add( "MissingSymmetricKey",
@"<issuerTokenResolver type='System.IdentityModel.Tokens.NamedKeyIssuerTokenResolver, System.IdentityModel.Tokens.JWT'>
<securityKey name='LocalSTS' />
</issuerTokenResolver>" );
_testCases.Add( "NameMissing",
@"<issuerTokenResolver type='System.IdentityModel.Tokens.NamedKeyIssuerTokenResolver, System.IdentityModel.Tokens.JWT'>
<securityKey symmetricKey = 'jWo8qtxA05mPwwjMPhIS7w==' />
</issuerTokenResolver>" );
_testCases.Add( "EncodingWrong",
@"<issuerTokenResolver type='System.IdentityModel.Tokens.NamedKeyIssuerTokenResolver, System.IdentityModel.Tokens.JWT'>
<securityKey symmetricKey = 'jWo8qtxA05mPwwjMPhIS7w==' EncodingType = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64' />
</issuerTokenResolver>" );
_testCases.Add( "KeyDoesNotParse",
@"<issuerTokenResolver type='System.IdentityModel.Tokens.NamedKeyIssuerTokenResolver, System.IdentityModel.Tokens.JWT'>
<securityKey symmetricKey = '000==' />
</issuerTokenResolver>" );
_testCases.Add( "EncodingRight",
@"<issuerTokenResolver type='System.IdentityModel.Tokens.NamedKeyIssuerTokenResolver, System.IdentityModel.Tokens.JWT'>
<securityKey symmetricKey = 'jWo8qtxA05mPwwjMPhIS7w==' EncodingType = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary' />
</issuerTokenResolver>" );
}
[TestInitialize]
public void Initialize()
{
_testContextProvider = new TestContextProvider( TestContext );
}
/// <summary>
/// The test context that is set by Visual Studio and TAEF - need to keep this exact signature
/// </summary>
public TestContext TestContext { get; set; }
protected override string GetConfiguration( string testVariation )
{
string caseToRun = _testCases[testVariation];
return @"<system.identityModel><identityConfiguration>" + caseToRun + @"</identityConfiguration></system.identityModel>";
}
protected override void ValidateTestCase( string testCase )
{
try
{
IdentityConfiguration identityConfig = new IdentityConfiguration( IdentityConfiguration.DefaultServiceName );
Assert.Fail( string.Format( "Expected Exception of type '{0}'", typeof( ConfigurationErrorsException ) ) );
}
catch ( Exception ex )
{
Assert.IsTrue( ex.GetType() == typeof( ConfigurationErrorsException ) );
}
}
[TestMethod]
[TestProperty( "TestCaseID", "1E62250E-9208-4917-8677-0C82EFE6823E" )]
[Description( "NamedKeyIssuerTokenResolver BadConfig" )]
public void Case()
{
RunTestCase("AsymmetricKey");
RunTestCase("MissingSymmetricKey");
RunTestCase("NameMissing");
RunTestCase("EncodingWrong");
RunTestCase("KeyDoesNotParse");
RunTestCase("EncodingRight");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
// Note: This class has an OS Limitation where the inotify API can miss events if a directory is created and immediately has
// changes underneath. This is due to the inotify* APIs not being recursive and needing to call inotify_add_watch on
// each subdirectory, causing a race between adding the watch and file system events happening.
public partial class FileSystemWatcher
{
/// <summary>Starts a new watch operation if one is not currently running.</summary>
private void StartRaisingEvents()
{
// If we're called when "Initializing" is true, set enabled to true
if (IsSuspended())
{
_enabled = true;
return;
}
// If we already have a cancellation object, we're already running.
if (_cancellation != null)
{
return;
}
// Open an inotify file descriptor.
SafeFileHandle handle = Interop.Sys.INotifyInit();
if (handle.IsInvalid)
{
Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo();
switch (error.Error)
{
case Interop.Error.EMFILE:
string maxValue = ReadMaxUserLimit(MaxUserInstancesPath);
string message = !string.IsNullOrEmpty(maxValue) ?
SR.Format(SR.IOException_INotifyInstanceUserLimitExceeded_Value, maxValue) :
SR.IOException_INotifyInstanceUserLimitExceeded;
throw new IOException(message, error.RawErrno);
case Interop.Error.ENFILE:
throw new IOException(SR.IOException_INotifyInstanceSystemLimitExceeded, error.RawErrno);
default:
throw Interop.GetExceptionForIoErrno(error);
}
}
try
{
// Create the cancellation object that will be used by this FileSystemWatcher to cancel the new watch operation
CancellationTokenSource cancellation = new CancellationTokenSource();
// Start running. All state associated with the watch operation is stored in a separate object; this is done
// to avoid race conditions that could result if the users quickly starts/stops/starts/stops/etc. causing multiple
// active operations to all be outstanding at the same time.
var runner = new RunningInstance(
this, handle, _directory,
IncludeSubdirectories, NotifyFilter, cancellation.Token);
// Now that we've created the runner, store the cancellation object and mark the instance
// as running. We wait to do this so that if there was a failure, StartRaisingEvents
// may be called to try again without first having to call StopRaisingEvents.
_cancellation = cancellation;
_enabled = true;
// Start the runner
runner.Start();
}
catch
{
// If we fail to actually start the watching even though we've opened the
// inotify handle, close the inotify handle proactively rather than waiting for it
// to be finalized.
handle.Dispose();
throw;
}
}
/// <summary>Cancels the currently running watch operation if there is one.</summary>
private void StopRaisingEvents()
{
_enabled = false;
if (IsSuspended())
return;
// If there's an active cancellation token, cancel and release it.
// The cancellation token and the processing task respond to cancellation
// to handle all other cleanup.
var cts = _cancellation;
if (cts != null)
{
_cancellation = null;
cts.Cancel();
}
}
/// <summary>Called when FileSystemWatcher is finalized.</summary>
private void FinalizeDispose()
{
// The RunningInstance remains rooted and holds open the SafeFileHandle until it's explicitly
// torn down. FileSystemWatcher.Dispose will call StopRaisingEvents, but not on finalization;
// thus we need to explicitly call it here.
StopRaisingEvents();
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>Path to the procfs file that contains the maximum number of inotify instances an individual user may create.</summary>
private const string MaxUserInstancesPath = "/proc/sys/fs/inotify/max_user_instances";
/// <summary>Path to the procfs file that contains the maximum number of inotify watches an individual user may create.</summary>
private const string MaxUserWatchesPath = "/proc/sys/fs/inotify/max_user_watches";
/// <summary>
/// Cancellation for the currently running watch operation.
/// This is non-null if an operation has been started and null if stopped.
/// </summary>
private CancellationTokenSource _cancellation;
/// <summary>Reads the value of a max user limit path from procfs.</summary>
/// <param name="path">The path to read.</param>
/// <returns>The value read, or "0" if a failure occurred.</returns>
private static string ReadMaxUserLimit(string path)
{
try { return File.ReadAllText(path).Trim(); }
catch { return null; }
}
/// <summary>
/// Maps the FileSystemWatcher's NotifyFilters enumeration to the
/// corresponding Interop.Sys.NotifyEvents values.
/// </summary>
/// <param name="filters">The filters provided the by user.</param>
/// <returns>The corresponding NotifyEvents values to use with inotify.</returns>
private static Interop.Sys.NotifyEvents TranslateFilters(NotifyFilters filters)
{
Interop.Sys.NotifyEvents result = 0;
// We always include a few special inotify watch values that configure
// the watch's behavior.
result |=
Interop.Sys.NotifyEvents.IN_ONLYDIR | // we only allow watches on directories
Interop.Sys.NotifyEvents.IN_EXCL_UNLINK; // we want to stop monitoring unlinked files
// For the Created and Deleted events, we need to always
// register for the created/deleted inotify events, regardless
// of the supplied filters values. We explicitly don't include IN_DELETE_SELF.
// The Windows implementation doesn't include notifications for the root directory,
// and having this for subdirectories results in duplicate notifications, one from
// the parent and one from self.
result |=
Interop.Sys.NotifyEvents.IN_CREATE |
Interop.Sys.NotifyEvents.IN_DELETE;
// For the Changed event, which inotify events we subscribe to
// are based on the NotifyFilters supplied.
const NotifyFilters filtersForAccess =
NotifyFilters.LastAccess;
const NotifyFilters filtersForModify =
NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.Security |
NotifyFilters.Size;
const NotifyFilters filtersForAttrib =
NotifyFilters.Attributes |
NotifyFilters.CreationTime |
NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.Security |
NotifyFilters.Size;
if ((filters & filtersForAccess) != 0)
{
result |= Interop.Sys.NotifyEvents.IN_ACCESS;
}
if ((filters & filtersForModify) != 0)
{
result |= Interop.Sys.NotifyEvents.IN_MODIFY;
}
if ((filters & filtersForAttrib) != 0)
{
result |= Interop.Sys.NotifyEvents.IN_ATTRIB;
}
// For the Rename event, we'll register for the corresponding move inotify events if the
// caller's NotifyFilters asks for notifications related to names.
const NotifyFilters filtersForMoved =
NotifyFilters.FileName |
NotifyFilters.DirectoryName;
if ((filters & filtersForMoved) != 0)
{
result |=
Interop.Sys.NotifyEvents.IN_MOVED_FROM |
Interop.Sys.NotifyEvents.IN_MOVED_TO;
}
return result;
}
/// <summary>
/// State and processing associated with an active watch operation. This state is kept separate from FileSystemWatcher to avoid
/// race conditions when a user starts/stops/starts/stops/etc. in quick succession, resulting in the potential for multiple
/// active operations. It also helps with avoiding rooted cycles and enabling proper finalization.
/// </summary>
private sealed class RunningInstance
{
/// <summary>
/// The size of the native struct inotify_event. 4 32-bit integer values, the last of which is a length
/// that indicates how many bytes follow to form the string name.
/// </summary>
private const int c_INotifyEventSize = 16;
/// <summary>
/// Weak reference to the associated watcher. A weak reference is used so that the FileSystemWatcher may be collected and finalized,
/// causing an active operation to be torn down. With a strong reference, a blocking read on the inotify handle will keep alive this
/// instance which will keep alive the FileSystemWatcher which will not be finalizable and thus which will never signal to the blocking
/// read to wake up in the event that the user neglects to stop raising events.
/// </summary>
private readonly WeakReference<FileSystemWatcher> _weakWatcher;
/// <summary>
/// The path for the primary watched directory.
/// </summary>
private readonly string _directoryPath;
/// <summary>
/// The inotify handle / file descriptor
/// </summary>
private readonly SafeFileHandle _inotifyHandle;
/// <summary>
/// Buffer used to store raw bytes read from the inotify handle.
/// </summary>
private readonly byte[] _buffer;
/// <summary>
/// The number of bytes read into the _buffer.
/// </summary>
private int _bufferAvailable;
/// <summary>
/// The next position in _buffer from which an event should be read.
/// </summary>
private int _bufferPos;
/// <summary>
/// Filters to use when adding a watch on directories.
/// </summary>
private readonly NotifyFilters _notifyFilters;
private readonly Interop.Sys.NotifyEvents _watchFilters;
/// <summary>
/// Whether to monitor subdirectories. Unlike Win32, inotify does not implicitly monitor subdirectories;
/// watches must be explicitly added for those subdirectories.
/// </summary>
private readonly bool _includeSubdirectories;
/// <summary>
/// Token to monitor for cancellation requests, upon which processing is stopped and all
/// state is cleaned up.
/// </summary>
private readonly CancellationToken _cancellationToken;
/// <summary>
/// Mapping from watch descriptor (as returned by inotify_add_watch) to state for
/// the associated directory being watched. Events from inotify include only relative
/// names, so the watch descriptor in an event must be used to look up the associated
/// directory path in order to convert the relative filename into a full path.
/// </summary>
private readonly Dictionary<int, WatchedDirectory> _wdToPathMap = new Dictionary<int, WatchedDirectory>();
/// <summary>
/// Maximum length of a name returned from inotify event.
/// </summary>
private const int NAME_MAX = 255; // from limits.h
/// <summary>Initializes the instance with all state necessary to operate a watch.</summary>
internal RunningInstance(
FileSystemWatcher watcher, SafeFileHandle inotifyHandle, string directoryPath,
bool includeSubdirectories, NotifyFilters notifyFilters, CancellationToken cancellationToken)
{
Debug.Assert(watcher != null);
Debug.Assert(inotifyHandle != null && !inotifyHandle.IsInvalid && !inotifyHandle.IsClosed);
Debug.Assert(directoryPath != null);
_weakWatcher = new WeakReference<FileSystemWatcher>(watcher);
_inotifyHandle = inotifyHandle;
_directoryPath = directoryPath;
_buffer = watcher.AllocateBuffer();
Debug.Assert(_buffer != null && _buffer.Length > (c_INotifyEventSize + NAME_MAX + 1));
_includeSubdirectories = includeSubdirectories;
_notifyFilters = notifyFilters;
_watchFilters = TranslateFilters(notifyFilters);
_cancellationToken = cancellationToken;
// Add a watch for this starting directory. We keep track of the watch descriptor => directory information
// mapping in a dictionary; this is needed in order to be able to determine the containing directory
// for all notifications so that we can reconstruct the full path.
AddDirectoryWatchUnlocked(null, directoryPath);
}
internal void Start()
{
// Schedule a task to read from the inotify queue and process the events.
Task.Factory.StartNew(obj => ((RunningInstance)obj).ProcessEvents(),
this, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
// PERF: As needed, we can look into making this use async I/O rather than burning
// a thread that blocks in the read syscall.
}
/// <summary>Object to use for synchronizing access to state when necessary.</summary>
private object SyncObj { get { return _wdToPathMap; } }
/// <summary>Adds a watch on a directory to the existing inotify handle.</summary>
/// <param name="parent">The parent directory entry.</param>
/// <param name="directoryName">The new directory path to monitor, relative to the root.</param>
private void AddDirectoryWatch(WatchedDirectory parent, string directoryName)
{
lock (SyncObj)
{
// The read syscall on the file descriptor will block until either close is called or until
// all previously added watches are removed. We don't want to rely on close, as a) that could
// lead to race conditions where we inadvertently read from a recycled file descriptor, and b)
// the SafeFileHandle that wraps the file descriptor can't be disposed (thus closing
// the underlying file descriptor and allowing read to wake up) while there's an active ref count
// against the handle, so we'd deadlock if we relied on that approach. Instead, we want to follow
// the approach of removing all watches when we're done, which means we also don't want to
// add any new watches once the count hits zero.
if (parent == null || _wdToPathMap.Count > 0)
{
Debug.Assert(parent != null || _wdToPathMap.Count == 0);
AddDirectoryWatchUnlocked(parent, directoryName);
}
}
}
/// <summary>Adds a watch on a directory to the existing inotify handle.</summary>
/// <param name="parent">The parent directory entry.</param>
/// <param name="directoryName">The new directory path to monitor, relative to the root.</param>
private void AddDirectoryWatchUnlocked(WatchedDirectory parent, string directoryName)
{
string fullPath = parent != null ? parent.GetPath(false, directoryName) : directoryName;
// inotify_add_watch will fail if this is a symlink, so check that we didn't get a symlink
Interop.Sys.FileStatus status = default(Interop.Sys.FileStatus);
if ((Interop.Sys.LStat(fullPath, out status) == 0) &&
((status.Mode & (uint)Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFLNK))
{
return;
}
// Add a watch for the full path. If the path is already being watched, this will return
// the existing descriptor. This works even in the case of a rename. We also add the DONT_FOLLOW
// and EXCL_UNLINK flags to keep parity with Windows where we don't pickup symlinks or unlinked
// files (which don't exist in Windows)
int wd = Interop.Sys.INotifyAddWatch(_inotifyHandle, fullPath, (uint)(this._watchFilters | Interop.Sys.NotifyEvents.IN_DONT_FOLLOW | Interop.Sys.NotifyEvents.IN_EXCL_UNLINK));
if (wd == -1)
{
// If we get an error when trying to add the watch, don't let that tear down processing. Instead,
// raise the Error event with the exception and let the user decide how to handle it.
Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo();
Exception exc;
if (error.Error == Interop.Error.ENOSPC)
{
string maxValue = ReadMaxUserLimit(MaxUserWatchesPath);
string message = !string.IsNullOrEmpty(maxValue) ?
SR.Format(SR.IOException_INotifyWatchesUserLimitExceeded_Value, maxValue) :
SR.IOException_INotifyWatchesUserLimitExceeded;
exc = new IOException(message, error.RawErrno);
}
else
{
exc = Interop.GetExceptionForIoErrno(error, fullPath);
}
FileSystemWatcher watcher;
if (_weakWatcher.TryGetTarget(out watcher))
{
watcher.OnError(new ErrorEventArgs(exc));
}
return;
}
// Then store the path information into our map.
WatchedDirectory directoryEntry;
bool isNewDirectory = false;
if (_wdToPathMap.TryGetValue(wd, out directoryEntry))
{
// The watch descriptor was already in the map. Hard links on directories
// aren't possible, and symlinks aren't annotated as IN_ISDIR,
// so this is a rename. (In extremely remote cases, this could be
// a recycled watch descriptor if many, many events were lost
// such that our dictionary got very inconsistent with the state
// of the world, but there's little that can be done about that.)
if (directoryEntry.Parent != parent)
{
if (directoryEntry.Parent != null)
{
directoryEntry.Parent.Children.Remove (directoryEntry);
}
directoryEntry.Parent = parent;
if (parent != null)
{
parent.InitializedChildren.Add (directoryEntry);
}
}
directoryEntry.Name = directoryName;
}
else
{
// The watch descriptor wasn't in the map. This is a creation.
directoryEntry = new WatchedDirectory
{
Parent = parent,
WatchDescriptor = wd,
Name = directoryName
};
if (parent != null)
{
parent.InitializedChildren.Add (directoryEntry);
}
_wdToPathMap.Add(wd, directoryEntry);
isNewDirectory = true;
}
// Since inotify doesn't handle nesting implicitly, explicitly
// add a watch for each child directory if the developer has
// asked for subdirectories to be included.
if (isNewDirectory && _includeSubdirectories)
{
// This method is recursive. If we expect to see hierarchies
// so deep that it would cause us to overflow the stack, we could
// consider using an explicit stack object rather than recursion.
// This is unlikely, however, given typical directory names
// and max path limits.
foreach (string subDir in Directory.EnumerateDirectories(fullPath))
{
AddDirectoryWatchUnlocked(directoryEntry, System.IO.Path.GetFileName(subDir));
// AddDirectoryWatchUnlocked will add the new directory to
// this.Children, so we don't have to / shouldn't also do it here.
}
}
}
/// <summary>Removes the watched directory from our state, and optionally removes the inotify watch itself.</summary>
/// <param name="directoryEntry">The directory entry to remove.</param>
/// <param name="removeInotify">true to remove the inotify watch; otherwise, false. The default is true.</param>
private void RemoveWatchedDirectory(WatchedDirectory directoryEntry, bool removeInotify = true)
{
Debug.Assert (_includeSubdirectories);
lock (SyncObj)
{
if (directoryEntry.Parent != null)
{
directoryEntry.Parent.Children.Remove (directoryEntry);
}
RemoveWatchedDirectoryUnlocked (directoryEntry, removeInotify);
}
}
/// <summary>Removes the watched directory from our state, and optionally removes the inotify watch itself.</summary>
/// <param name="directoryEntry">The directory entry to remove.</param>
/// <param name="removeInotify">true to remove the inotify watch; otherwise, false. The default is true.</param>
private void RemoveWatchedDirectoryUnlocked(WatchedDirectory directoryEntry, bool removeInotify)
{
// If the directory has children, recursively remove them (see comments on recursion in AddDirectoryWatch).
if (directoryEntry.Children != null)
{
foreach (WatchedDirectory child in directoryEntry.Children)
{
RemoveWatchedDirectoryUnlocked (child, removeInotify);
}
directoryEntry.Children = null;
}
// Then remove the directory itself.
_wdToPathMap.Remove(directoryEntry.WatchDescriptor);
// And if the caller has requested, remove the associated inotify watch.
if (removeInotify)
{
// Remove the inotify watch. This could fail if our state has become inconsistent
// with the state of the world (e.g. due to lost events). So we don't want failures
// to throw exceptions, but we do assert to detect coding problems during debugging.
int result = Interop.Sys.INotifyRemoveWatch(_inotifyHandle, directoryEntry.WatchDescriptor);
Debug.Assert(result >= 0);
}
}
/// <summary>
/// Callback invoked when cancellation is requested. Removes all watches,
/// which will cause the active processing loop to shutdown.
/// </summary>
private void CancellationCallback()
{
lock (SyncObj)
{
// Remove all watches (inotiy_rm_watch) and clear out the map.
// No additional watches will be added after this point.
foreach (int wd in this._wdToPathMap.Keys)
{
int result = Interop.Sys.INotifyRemoveWatch(_inotifyHandle, wd);
Debug.Assert(result >= 0); // ignore errors; they're non-fatal, but they also shouldn't happen
}
_wdToPathMap.Clear();
}
}
/// <summary>
/// Main processing loop. This is currently implemented as a synchronous operation that continually
/// reads events and processes them... in the future, this could be changed to use asynchronous processing
/// if the impact of using a thread-per-FileSystemWatcher is too high.
/// </summary>
private void ProcessEvents()
{
// When cancellation is requested, clear out all watches. This should force any active or future reads
// on the inotify handle to return 0 bytes read immediately, allowing us to wake up from the blocking call
// and exit the processing loop and clean up.
var ctr = _cancellationToken.UnsafeRegister(obj => ((RunningInstance)obj).CancellationCallback(), this);
try
{
// Previous event information
ReadOnlySpan<char> previousEventName = ReadOnlySpan<char>.Empty;
WatchedDirectory previousEventParent = null;
uint previousEventCookie = 0;
// Process events as long as we're not canceled and there are more to read...
NotifyEvent nextEvent;
while (!_cancellationToken.IsCancellationRequested && TryReadEvent(out nextEvent))
{
// Try to get the actual watcher from our weak reference. We maintain a weak reference most of the time
// so as to avoid a rooted cycle that would prevent our processing loop from ever ending
// if the watcher is dropped by the user without being disposed. If we can't get the watcher,
// there's nothing more to do (we can't raise events), so bail.
FileSystemWatcher watcher;
if (!_weakWatcher.TryGetTarget(out watcher))
{
break;
}
uint mask = nextEvent.mask;
ReadOnlySpan<char> expandedName = ReadOnlySpan<char>.Empty;
WatchedDirectory associatedDirectoryEntry = null;
// An overflow event means that we can't trust our state without restarting since we missed events and
// some of those events could be a directory create, meaning we wouldn't have added the directory to the
// watch and would not provide correct data to the caller.
if ((mask & (uint)Interop.Sys.NotifyEvents.IN_Q_OVERFLOW) != 0)
{
// Notify the caller of the error and, if the includeSubdirectories flag is set, restart to pick up any
// potential directories we missed due to the overflow.
watcher.NotifyInternalBufferOverflowEvent();
if (_includeSubdirectories)
{
watcher.Restart();
}
break;
}
else
{
// Look up the directory information for the supplied wd
lock (SyncObj)
{
if (!_wdToPathMap.TryGetValue(nextEvent.wd, out associatedDirectoryEntry))
{
// The watch descriptor could be missing from our dictionary if it was removed
// due to cancellation, or if we already removed it and this is a related event
// like IN_IGNORED. In any case, just ignore it... even if for some reason we
// should have the value, there's little we can do about it at this point,
// and there's no more processing of this event we can do without it.
continue;
}
}
expandedName = associatedDirectoryEntry.GetPath(true, nextEvent.name);
}
// To match Windows, ignore all changes that happen on the root folder itself
if (expandedName.IsEmpty)
{
watcher = null;
continue;
}
// Determine whether the affected object is a directory (rather than a file).
// If it is, we may need to do special processing, such as adding a watch for new
// directories if IncludeSubdirectories is enabled. Since we're only watching
// directories, any IN_IGNORED event is also for a directory.
bool isDir = (mask & (uint)(Interop.Sys.NotifyEvents.IN_ISDIR | Interop.Sys.NotifyEvents.IN_IGNORED)) != 0;
// Renames come in the form of two events: IN_MOVED_FROM and IN_MOVED_TO.
// In general, these should come as a sequence, one immediately after the other.
// So, we delay raising an event for IN_MOVED_FROM until we see what comes next.
if (!previousEventName.IsEmpty && ((mask & (uint)Interop.Sys.NotifyEvents.IN_MOVED_TO) == 0 || previousEventCookie != nextEvent.cookie))
{
// IN_MOVED_FROM without an immediately-following corresponding IN_MOVED_TO.
// We have to assume that it was moved outside of our root watch path, which
// should be considered a deletion to match Win32 behavior.
// But since we explicitly added watches on directories, if it's a directory it'll
// still be watched, so we need to explicitly remove the watch.
if (previousEventParent != null && previousEventParent.Children != null)
{
// previousEventParent will be non-null iff the IN_MOVED_FROM
// was for a directory, in which case previousEventParent is that directory's
// parent and previousEventName is the name of the directory to be removed.
foreach (WatchedDirectory child in previousEventParent.Children)
{
if (previousEventName.Equals(child.Name, StringComparison.Ordinal))
{
RemoveWatchedDirectory(child);
break;
}
}
}
// Then fire the deletion event, even though the event was IN_MOVED_FROM.
watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Deleted, previousEventName);
previousEventName = null;
previousEventParent = null;
previousEventCookie = 0;
}
// If the event signaled that there's a new subdirectory and if we're monitoring subdirectories,
// add a watch for it.
const Interop.Sys.NotifyEvents AddMaskFilters = Interop.Sys.NotifyEvents.IN_CREATE | Interop.Sys.NotifyEvents.IN_MOVED_TO;
bool addWatch = ((mask & (uint)AddMaskFilters) != 0);
if (addWatch && isDir && _includeSubdirectories)
{
AddDirectoryWatch(associatedDirectoryEntry, nextEvent.name);
}
// Check if the event should have been filtered but was unable because of inotify's inability
// to filter files vs directories.
const Interop.Sys.NotifyEvents fileDirEvents = Interop.Sys.NotifyEvents.IN_CREATE |
Interop.Sys.NotifyEvents.IN_DELETE |
Interop.Sys.NotifyEvents.IN_MOVED_FROM |
Interop.Sys.NotifyEvents.IN_MOVED_TO;
if ((((uint)fileDirEvents & mask) > 0) &&
(isDir && ((_notifyFilters & NotifyFilters.DirectoryName) == 0) ||
(!isDir && ((_notifyFilters & NotifyFilters.FileName) == 0))))
{
continue;
}
const Interop.Sys.NotifyEvents switchMask = fileDirEvents | Interop.Sys.NotifyEvents.IN_IGNORED |
Interop.Sys.NotifyEvents.IN_ACCESS | Interop.Sys.NotifyEvents.IN_MODIFY | Interop.Sys.NotifyEvents.IN_ATTRIB;
switch ((Interop.Sys.NotifyEvents)(mask & (uint)switchMask))
{
case Interop.Sys.NotifyEvents.IN_CREATE:
watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Created, expandedName);
break;
case Interop.Sys.NotifyEvents.IN_IGNORED:
// We're getting an IN_IGNORED because a directory watch was removed.
// and we're getting this far in our code because we still have an entry for it
// in our dictionary. So we want to clean up the relevant state, but not clean
// attempt to call back to inotify to remove the watches.
RemoveWatchedDirectory(associatedDirectoryEntry, removeInotify:false);
break;
case Interop.Sys.NotifyEvents.IN_DELETE:
watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Deleted, expandedName);
// We don't explicitly RemoveWatchedDirectory here, as that'll be handled
// by IN_IGNORED processing if this is a directory.
break;
case Interop.Sys.NotifyEvents.IN_ACCESS:
case Interop.Sys.NotifyEvents.IN_MODIFY:
case Interop.Sys.NotifyEvents.IN_ATTRIB:
watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Changed, expandedName);
break;
case Interop.Sys.NotifyEvents.IN_MOVED_FROM:
// We need to check if this MOVED_FROM event is standalone - meaning the item was moved out
// of scope. We do this by checking if we are at the end of our buffer (meaning no more events)
// and if there is data to be read by polling the fd. If there aren't any more events, fire the
// deleted event; if there are more events, handle it via next pass. This adds an additional
// edge case where we get the MOVED_FROM event and the MOVED_TO event hasn't been generated yet
// so we will send a DELETE for this event and a CREATE when the MOVED_TO is eventually processed.
if (_bufferPos == _bufferAvailable)
{
// Do the poll with a small timeout value. Community research showed that a few milliseconds
// was enough to allow the vast majority of MOVED_TO events that were going to show
// up to actually arrive. This doesn't need to be perfect; there's always the chance
// that a MOVED_TO could show up after whatever timeout is specified, in which case
// it'll just result in a delete + create instead of a rename. We need the value to be
// small so that we don't significantly delay the delivery of the deleted event in case
// that's actually what's needed (otherwise it'd be fine to block indefinitely waiting
// for the next event to arrive).
const int MillisecondsTimeout = 2;
Interop.Sys.PollEvents events;
Interop.Sys.Poll(_inotifyHandle, Interop.Sys.PollEvents.POLLIN, MillisecondsTimeout, out events);
// If we error or don't have any signaled handles, send the deleted event
if (events == Interop.Sys.PollEvents.POLLNONE)
{
// There isn't any more data in the queue so this is a deleted event
watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Deleted, expandedName);
break;
}
}
// We will set these values if the buffer has more data OR if the poll call tells us that more data is available.
previousEventName = expandedName;
previousEventParent = isDir ? associatedDirectoryEntry : null;
previousEventCookie = nextEvent.cookie;
break;
case Interop.Sys.NotifyEvents.IN_MOVED_TO:
if (previousEventName != null)
{
// If the previous name from IN_MOVED_FROM is non-null, then this is a rename.
watcher.NotifyRenameEventArgs(WatcherChangeTypes.Renamed, expandedName, previousEventName);
}
else
{
// If it is null, then we didn't get an IN_MOVED_FROM (or we got it a long time
// ago and treated it as a deletion), in which case this is considered a creation.
watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Created, expandedName);
}
previousEventName = ReadOnlySpan<char>.Empty;
previousEventParent = null;
previousEventCookie = 0;
break;
}
// Drop our strong reference to the watcher now that we're potentially going to block again for another read
watcher = null;
}
}
catch (Exception exc)
{
FileSystemWatcher watcher;
if (_weakWatcher.TryGetTarget(out watcher))
{
watcher.OnError(new ErrorEventArgs(exc));
}
}
finally
{
ctr.Dispose();
_inotifyHandle.Dispose();
}
}
/// <summary>Read event from the inotify handle into the supplied event object.</summary>
/// <param name="notifyEvent">The event object to be populated.</param>
/// <returns><see langword="true"/> if event was read successfully, <see langword="false"/> otherwise.</returns>
private bool TryReadEvent(out NotifyEvent notifyEvent)
{
Debug.Assert(_buffer != null);
Debug.Assert(_buffer.Length > 0);
Debug.Assert(_bufferAvailable >= 0 && _bufferAvailable <= _buffer.Length);
Debug.Assert(_bufferPos >= 0 && _bufferPos <= _bufferAvailable);
// Read more data into our buffer if we need it
if (_bufferAvailable == 0 || _bufferPos == _bufferAvailable)
{
// Read from the handle. This will block until either data is available
// or all watches have been removed, in which case zero bytes are read.
unsafe
{
try
{
fixed (byte* buf = &_buffer[0])
{
_bufferAvailable = Interop.CheckIo(Interop.Sys.Read(_inotifyHandle, buf, this._buffer.Length),
isDirectory: true);
Debug.Assert(_bufferAvailable <= this._buffer.Length);
}
}
catch (ArgumentException)
{
_bufferAvailable = 0;
Debug.Fail("Buffer provided to read was too small");
}
Debug.Assert(_bufferAvailable >= 0);
}
if (_bufferAvailable == 0)
{
notifyEvent = default(NotifyEvent);
return false;
}
Debug.Assert(_bufferAvailable >= c_INotifyEventSize);
_bufferPos = 0;
}
// Parse each event:
// struct inotify_event {
// int wd;
// uint32_t mask;
// uint32_t cookie;
// uint32_t len;
// char name[]; // length determined by len; at least 1 for required null termination
// };
Debug.Assert(_bufferPos + c_INotifyEventSize <= _bufferAvailable);
NotifyEvent readEvent;
readEvent.wd = BitConverter.ToInt32(_buffer, _bufferPos);
readEvent.mask = BitConverter.ToUInt32(_buffer, _bufferPos + 4); // +4 to get past wd
readEvent.cookie = BitConverter.ToUInt32(_buffer, _bufferPos + 8); // +8 to get past wd, mask
int nameLength = (int)BitConverter.ToUInt32(_buffer, _bufferPos + 12); // +12 to get past wd, mask, cookie
readEvent.name = ReadName(_bufferPos + c_INotifyEventSize, nameLength); // +16 to get past wd, mask, cookie, len
_bufferPos += c_INotifyEventSize + nameLength;
notifyEvent = readEvent;
return true;
}
/// <summary>
/// Reads a UTF8 string from _buffer starting at the specified position and up to
/// the specified length. Null termination is trimmed off (the length may include
/// many null bytes, not just one, or it may include none).
/// </summary>
/// <param name="position"></param>
/// <param name="nameLength"></param>
/// <returns></returns>
private string ReadName(int position, int nameLength)
{
Debug.Assert(position > 0);
Debug.Assert(nameLength >= 0 && (position + nameLength) <= _buffer.Length);
int lengthWithoutNullTerm = nameLength;
for (int i = 0; i < nameLength; i++)
{
if (_buffer[position + i] == '\0')
{
lengthWithoutNullTerm = i;
break;
}
}
Debug.Assert(lengthWithoutNullTerm <= nameLength); // should be null terminated or empty
return lengthWithoutNullTerm > 0 ?
Encoding.UTF8.GetString(_buffer, position, lengthWithoutNullTerm) :
string.Empty;
}
/// <summary>An event read and translated from the inotify handle.</summary>
/// <remarks>
/// Unlike it's native counterpart, this struct stores a string name rather than
/// an integer length and a char[]. It is not directly marshalable.
/// </remarks>
private struct NotifyEvent
{
internal int wd;
internal uint mask;
internal uint cookie;
internal string name;
}
/// <summary>State associated with a watched directory.</summary>
private sealed class WatchedDirectory
{
/// <summary>A StringBuilder cached on the current thread to avoid allocations when possible.</summary>
[ThreadStatic]
private static StringBuilder t_builder;
/// <summary>The parent directory.</summary>
internal WatchedDirectory Parent;
/// <summary>The watch descriptor associated with this directory.</summary>
internal int WatchDescriptor;
/// <summary>The filename of this directory.</summary>
internal string Name;
/// <summary>Child directories of this directory for which we added explicit watches.</summary>
internal List<WatchedDirectory> Children;
/// <summary>Child directories of this directory for which we added explicit watches. This is the same as Children, but ensured to be initialized as non-null.</summary>
internal List<WatchedDirectory> InitializedChildren
{
get
{
if (Children == null)
{
Children = new List<WatchedDirectory> ();
}
return Children;
}
}
// PERF: Work is being done here proportionate to depth of watch directories.
// If this becomes a bottleneck, we'll need to come up with another mechanism
// for obtaining and keeping paths up to date, for example storing the full path
// in each WatchedDirectory node and recursively updating all children on a move,
// which we can do given that we store all children. For now we're not doing that
// because it's not a clear win: either you update all children recursively when
// a directory moves / is added, or you compute each name when an event occurs.
// The former is better if there are going to be lots of events causing lots
// of traversals to compute names, and the latter is better for big directory
// structures that incur fewer file events.
/// <summary>Gets the path of this directory.</summary>
/// <param name="relativeToRoot">Whether to get a path relative to the root directory being watched, or a full path.</param>
/// <param name="additionalName">An additional name to include in the path, relative to this directory.</param>
/// <returns>The computed path.</returns>
internal string GetPath(bool relativeToRoot, string additionalName = null)
{
// Use our cached builder
StringBuilder builder = t_builder;
if (builder == null)
{
t_builder = builder = new StringBuilder();
}
builder.Clear();
// Write the directory's path. Then if an additional filename was supplied, append it
Write(builder, relativeToRoot);
if (additionalName != null)
{
AppendSeparatorIfNeeded(builder);
builder.Append(additionalName);
}
return builder.ToString();
}
/// <summary>Write's this directory's path to the builder.</summary>
/// <param name="builder">The builder to which to write.</param>
/// <param name="relativeToRoot">
/// true if the path should be relative to the root directory being watched.
/// false if the path should be a full file system path, including that of
/// the root directory being watched.
/// </param>
private void Write(StringBuilder builder, bool relativeToRoot)
{
// This method is recursive. If we expect to see hierarchies
// so deep that it would cause us to overflow the stack, we could
// consider using an explicit stack object rather than recursion.
// This is unlikely, however, given typical directory names
// and max path limits.
// First append the parent's path
if (Parent != null)
{
Parent.Write(builder, relativeToRoot);
AppendSeparatorIfNeeded(builder);
}
// Then append ours. In the case of the root directory
// being watched, we only append its name if the caller
// has asked for a full path.
if (Parent != null || !relativeToRoot)
{
builder.Append(Name);
}
}
/// <summary>Adds a directory path separator to the end of the builder if one isn't there.</summary>
/// <param name="builder">The builder.</param>
private static void AppendSeparatorIfNeeded(StringBuilder builder)
{
if (builder.Length > 0)
{
char c = builder[builder.Length - 1];
if (c != System.IO.Path.DirectorySeparatorChar && c != System.IO.Path.AltDirectorySeparatorChar)
{
builder.Append(System.IO.Path.DirectorySeparatorChar);
}
}
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Microsoft.Practices.Prism.Properties;
namespace Microsoft.Practices.Prism.Modularity
{
/// <summary>
/// Represents a group of <see cref="ModuleInfo"/> instances that are usually deployed together. <see cref="ModuleInfoGroup"/>s
/// are also used by the <see cref="ModuleCatalog"/> to prevent common deployment problems such as having a module that's required
/// at startup that depends on modules that will only be downloaded on demand.
///
/// The group also forwards <see cref="Ref"/> and <see cref="InitializationMode"/> values to the <see cref="ModuleInfo"/>s that it
/// contains.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
public class ModuleInfoGroup : IModuleCatalogItem, IList<ModuleInfo>, IList // IList must be supported in Silverlight 2 to be able to add items from XAML
{
private readonly Collection<ModuleInfo> modules = new Collection<ModuleInfo>();
/// <summary>
/// Gets or sets the <see cref="ModuleInfo.InitializationMode"/> for the whole group. Any <see cref="ModuleInfo"/> classes that are
/// added after setting this value will also get this <see cref="InitializationMode"/>.
/// </summary>
/// <see cref="ModuleInfo.InitializationMode"/>
/// <value>The initialization mode.</value>
public InitializationMode InitializationMode { get; set; }
/// <summary>
/// Gets or sets the <see cref="ModuleInfo.Ref"/> value for the whole group. Any <see cref="ModuleInfo"/> classes that are
/// added after setting this value will also get this <see cref="Ref"/>.
///
/// The ref value will also be used by the <see cref="IModuleManager"/> to determine which <see cref="IModuleTypeLoader"/> to use.
/// For example, using an "file://" prefix with a valid URL will cause the FileModuleTypeLoader to be used
/// (Only available in the desktop version of CAL).
/// </summary>
/// <see cref="ModuleInfo.Ref"/>
/// <value>The ref value that will be used.</value>
public string Ref { get; set; }
/// <summary>
/// Adds an <see cref="ModuleInfo"/> moduleInfo to the <see cref="ModuleInfoGroup"/>.
/// </summary>
/// <param name="item">The <see cref="ModuleInfo"/> to the <see cref="ModuleInfoGroup"/>.</param>
public void Add(ModuleInfo item)
{
this.ForwardValues(item);
this.modules.Add(item);
}
/// <summary>
/// Forwards <see cref="InitializationMode"/> and <see cref="Ref"/> properties from this <see cref="ModuleInfoGroup"/>
/// to <paramref name="moduleInfo"/>.
/// </summary>
/// <param name="moduleInfo">The module info to forward values to.</param>
/// <exception cref="ArgumentNullException">An <see cref="ArgumentNullException"/> is thrown if <paramref name="moduleInfo"/> is <see langword="null"/>.</exception>
protected void ForwardValues(ModuleInfo moduleInfo)
{
if (moduleInfo == null) throw new System.ArgumentNullException("moduleInfo");
if (moduleInfo.Ref == null)
{
moduleInfo.Ref = this.Ref;
}
if (moduleInfo.InitializationMode == InitializationMode.WhenAvailable && this.InitializationMode != InitializationMode.WhenAvailable)
{
moduleInfo.InitializationMode = this.InitializationMode;
}
}
/// <summary>
/// Removes all <see cref="ModuleInfo"/>s from the <see cref="ModuleInfoGroup"/>.
/// </summary>
public void Clear()
{
this.modules.Clear();
}
/// <summary>
/// Determines whether the <see cref="ModuleInfoGroup"/> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="ModuleInfoGroup"/>.</param>
/// <returns>
/// true if <paramref name="item"/> is found in the <see cref="ModuleInfoGroup"/>; otherwise, false.
/// </returns>
public bool Contains(ModuleInfo item)
{
return this.modules.Contains(item);
}
/// <summary>
/// Copies the elements of the <see cref="ModuleInfoGroup"/> 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 <see cref="ModuleInfoGroup"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="array"/> is null.
/// </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="arrayIndex"/> is less than 0.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="array"/> is multidimensional.
/// -or-
/// <paramref name="arrayIndex"/> is equal to or greater than the length of <paramref name="array"/>.
/// -or-
/// The number of elements in the source <see cref="ModuleInfoGroup"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.
/// </exception>
public void CopyTo(ModuleInfo[] array, int arrayIndex)
{
this.modules.CopyTo(array, arrayIndex);
}
/// <summary>
/// Gets the number of elements contained in the <see cref="ModuleInfoGroup"/>.
/// </summary>
/// <value></value>
/// <returns>
/// The number of elements contained in the <see cref="ModuleInfoGroup"/>.
/// </returns>
public int Count
{
get { return this.modules.Count; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="ModuleInfoGroup"/> is read-only.
/// </summary>
/// <value></value>
/// <returns>false, because the <see cref="ModuleInfoGroup"/> is not Read-Only.
/// </returns>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="ModuleInfoGroup"/>.
/// </summary>
/// <param name="item">The object to remove from the <see cref="ModuleInfoGroup"/>.</param>
/// <returns>
/// true if <paramref name="item"/> was successfully removed from the <see cref="ModuleInfoGroup"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="ModuleInfoGroup"/>.
/// </returns>
public bool Remove(ModuleInfo item)
{
return this.modules.Remove(item);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<ModuleInfo> GetEnumerator()
{
return this.modules.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Adds an item to the <see cref="ModuleInfoGroup"/>.
/// </summary>
/// <param name="value">
/// The <see cref="T:System.Object"/> to add to the <see cref="ModuleInfoGroup"/>.
/// Must be of type <see cref="ModuleInfo"/>
/// </param>
/// <returns>
/// The position into which the new element was inserted.
/// </returns>
int IList.Add(object value)
{
this.Add((ModuleInfo)value);
return 1;
}
/// <summary>
/// Determines whether the <see cref="ModuleInfoGroup"/> contains a specific value.
/// </summary>
/// <param name="value">
/// The <see cref="T:System.Object"/> to locate in the <see cref="ModuleInfoGroup"/>.
/// Must be of type <see cref="ModuleInfo"/>
/// </param>
/// <returns>
/// true if the <see cref="T:System.Object"/> is found in the <see cref="ModuleInfoGroup"/>; otherwise, false.
/// </returns>
bool IList.Contains(object value)
{
if (value == null) throw new ArgumentNullException("value");
ModuleInfo moduleInfo = value as ModuleInfo;
if (moduleInfo == null)
throw new ArgumentException(Resources.ValueMustBeOfTypeModuleInfo, "value");
return this.Contains(moduleInfo);
}
/// <summary>
/// Determines the index of a specific item in the <see cref="ModuleInfoGroup"/>.
/// </summary>
/// <param name="value">
/// The <see cref="T:System.Object"/> to locate in the <see cref="ModuleInfoGroup"/>.
/// Must be of type <see cref="ModuleInfo"/>
/// </param>
/// <returns>
/// The index of <paramref name="value"/> if found in the list; otherwise, -1.
/// </returns>
public int IndexOf(object value)
{
return this.modules.IndexOf((ModuleInfo)value);
}
/// <summary>
/// Inserts an item to the <see cref="ModuleInfoGroup"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="value"/> should be inserted.</param>
/// <param name="value">
/// The <see cref="T:System.Object"/> to insert into the <see cref="ModuleInfoGroup"/>.
/// Must be of type <see cref="ModuleInfo"/>
/// </param>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index"/> is not a valid index in the <see cref="ModuleInfoGroup"/>.
/// </exception>
/// <exception cref="ArgumentNullException">
/// If <paramref name="value"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If <paramref name="value"/> is not of type <see cref="ModuleInfo"/>
/// </exception>
public void Insert(int index, object value)
{
if (value == null)
throw new ArgumentNullException("value");
ModuleInfo moduleInfo = value as ModuleInfo;
if (moduleInfo == null)
throw new ArgumentException(Resources.ValueMustBeOfTypeModuleInfo, "value");
this.modules.Insert(index, moduleInfo);
}
/// <summary>
/// Gets a value indicating whether the <see cref="ModuleInfoGroup"/> has a fixed size.
/// </summary>
/// <returns>false, because the <see cref="ModuleInfoGroup"/> does not have a fixed length.
/// </returns>
public bool IsFixedSize
{
get { return false; }
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="ModuleInfoGroup"/>.
/// </summary>
/// <param name="value">
/// The <see cref="T:System.Object"/> to remove from the <see cref="ModuleInfoGroup"/>.
/// Must be of type <see cref="ModuleInfo"/>
/// </param>
void IList.Remove(object value)
{
this.Remove((ModuleInfo)value);
}
/// <summary>
/// Removes the <see cref="T:System.Collections.Generic.IList`1"/> item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.
/// </exception>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.
/// </exception>
public void RemoveAt(int index)
{
this.modules.RemoveAt(index);
}
/// <summary>
/// Gets or sets the <see cref="System.Object"/> at the specified index.
/// </summary>
/// <value></value>
object IList.this[int index]
{
get { return this[index]; }
set { this[index] = (ModuleInfo)value; }
}
/// <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 <see cref="T:System.Collections.ICollection"/>. 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="T:System.ArgumentNullException">
/// <paramref name="array"/> is null.
/// </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index"/> is less than zero.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="array"/> is multidimensional.
/// -or-
/// <paramref name="index"/> is equal to or greater than the length of <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"/>.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// 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)
{
((ICollection)this.modules).CopyTo(array, index);
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe).
/// </summary>
/// <value></value>
/// <returns>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe); otherwise, false.
/// </returns>
public bool IsSynchronized
{
get { return ((ICollection)this.modules).IsSynchronized; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>.
/// </summary>
/// <value></value>
/// <returns>
/// An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>.
/// </returns>
public object SyncRoot
{
get { return ((ICollection)this.modules).SyncRoot; }
}
/// <summary>
/// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1"/>.
/// </summary>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1"/>.</param>
/// <returns>
/// The index of <paramref name="item"/> if found in the list; otherwise, -1.
/// </returns>
public int IndexOf(ModuleInfo item)
{
return this.modules.IndexOf(item);
}
/// <summary>
/// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
/// <param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1"/>.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.
/// </exception>
public void Insert(int index, ModuleInfo item)
{
this.modules.Insert(index, item);
}
/// <summary>
/// Gets or sets the <see cref="ModuleInfo"/> at the specified index.
/// </summary>
/// <value>The <see cref="ModuleInfo"/> at the specified index </value>
public ModuleInfo this[int index]
{
get { return this.modules[index]; }
set { this.modules[index] = value; }
}
}
}
| |
/*
Copyright (c) 2010-2015 by Genstein and Jason Lautzenheiser.
This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace Trizbort.Export
{
internal class Inform6Exporter : CodeExporter
{
private const char SINGLE_QUOTE = '\'';
private const char DOUBLE_QUOTE = '"';
public override string FileDialogTitle => "Export Inform 6 Source Code";
public override List<KeyValuePair<string, string>> FileDialogFilters => new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("Inform 6 Source Files", ".inf"),
new KeyValuePair<string, string>("Text Files", ".txt")
};
protected override IEnumerable<string> ReservedWords => new[] {"Constant", "Story", "Headline", "Include", "Object", "with", "has", "hasnt", "not", "and", "or", "n_to", "s_to", "e_to", "w_to", "nw_to", "ne_to", "sw_to", "se_to", "u_to", "d_to", "in_to", "out_to", "before", "after", "if", "else", "print", "player", "location", "description"};
protected override Encoding Encoding => Encoding.ASCII;
protected override void ExportHeader(TextWriter writer, string title, string author, string description, string history)
{
writer.WriteLine("Constant Story {0};", toI6String(title, DOUBLE_QUOTE));
writer.WriteLine("Constant Headline {0};", toI6String($"^By {author}^{description}^^", DOUBLE_QUOTE));
writer.WriteLine();
writer.WriteLine("Include \"Parser\";");
writer.WriteLine("Include \"VerbLib\";");
writer.WriteLine();
}
protected override void ExportContent(TextWriter writer)
{
foreach (var location in LocationsInExportOrder)
{
writer.WriteLine("Object {0} {1}", location.ExportName, toI6String(location.Room.Name, DOUBLE_QUOTE));
writer.WriteLine(" with description");
writer.WriteLine(" {0},", toI6String(location.Room.PrimaryDescription, DOUBLE_QUOTE));
foreach (var direction in AllDirections)
{
var exit = location.GetBestExit(direction);
if (exit != null)
{
writer.WriteLine(" {0} {1},", toI6PropertyName(direction), exit.Target.ExportName);
}
}
writer.WriteLine(" has {0}light;", location.Room.IsDark ? "~" : string.Empty);
writer.WriteLine();
ExportThings(writer, location.Things, null, 1);
}
writer.WriteLine("[ Initialise;");
if (LocationsInExportOrder.Count > 0)
{
writer.WriteLine(" location = {0};", LocationsInExportOrder[0].ExportName);
}
else
{
writer.WriteLine(" ! location = ...;");
}
writer.WriteLine(" ! \"^^Your opening paragraph here...^^\";");
writer.WriteLine("];");
writer.WriteLine();
writer.WriteLine("Include \"Grammar\";");
writer.WriteLine();
}
private void ExportThings(TextWriter writer, List<Thing> things, Thing container, int indent)
{
foreach (var thing in things)
{
if (thing.Container != container)
{
// match only the container we're given, or lack thereof
continue;
}
writer.WriteLine("Object {0} {1} {2}", repeat("-> ", indent), thing.ExportName, toI6String(stripOddCharacters(thing.DisplayName, ' ', '-').Trim(), DOUBLE_QUOTE));
writer.Write(" with name {0}", toI6Words(stripOddCharacters(thing.DisplayName, ' ', '-')));
if (thing.Contents.Count > 0)
{
writer.WriteLine(",");
writer.WriteLine(" has open container;");
}
else
{
writer.WriteLine(";");
}
writer.WriteLine();
ExportThings(writer, thing.Contents, thing, indent + 1);
}
}
private static string toI6Words(string text)
{
var words = text.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
if (words.Length == 0)
{
return toI6String("thing", SINGLE_QUOTE);
}
var output = string.Empty;
foreach (var word in words)
{
if (output.Length > 0)
{
output += ' ';
}
output += toI6String(word, SINGLE_QUOTE);
}
return output;
}
private static string repeat(string s, int times)
{
var text = string.Empty;
for (var index = 0; index < times; ++index)
{
text += s;
}
return text;
}
private static string toI6String(string text, char quote)
{
if (text == null)
{
text = string.Empty;
}
return string.Format("{1}{0}{1}", text.Replace('\"', '~').Replace("\r", string.Empty).Replace('\n', '^'), quote);
}
private static string toI6PropertyName(AutomapDirection direction)
{
switch (direction)
{
case AutomapDirection.North:
return "n_to";
case AutomapDirection.South:
return "s_to";
case AutomapDirection.East:
return "e_to";
case AutomapDirection.West:
return "w_to";
case AutomapDirection.NorthEast:
return "ne_to";
case AutomapDirection.NorthWest:
return "nw_to";
case AutomapDirection.SouthEast:
return "se_to";
case AutomapDirection.SouthWest:
return "sw_to";
case AutomapDirection.Up:
return "u_to";
case AutomapDirection.Down:
return "d_to";
case AutomapDirection.In:
return "in_to";
case AutomapDirection.Out:
return "out_to";
default:
Debug.Assert(false, "Unrecognised automap direction.");
return "north";
}
}
protected override string GetExportName(Room room, int? suffix)
{
var name = stripOddCharacters(room.Name);
if (string.IsNullOrEmpty(name))
{
name = "room";
}
if (suffix != null)
{
name = $"{name}{suffix}";
}
return name;
}
protected override string GetExportName(string displayName, int? suffix)
{
var name = stripOddCharacters(displayName);
if (string.IsNullOrEmpty(name))
{
name = "item";
}
if (suffix != null)
{
name = $"{name}{suffix}";
}
return name;
}
private static string stripOddCharacters(string text, params char[] exclude)
{
var exclusions = new List<char>(exclude);
if (string.IsNullOrEmpty(text))
{
return string.Empty;
}
var result = string.Empty;
foreach (var c in text)
{
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' || exclusions.Contains(c))
{
result += c;
}
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace PH_App
{
public class Matrix3
{
public float[,] M = new float[4, 4];
public Matrix3()
{
Identity3();
}
public Matrix3(float m00, float m01, float m02, float m03,
float m10, float m11, float m12, float m13,
float m20, float m21, float m22, float m23,
float m30, float m31, float m32, float m33)
{
M[0, 0] = m00;
M[0, 1] = m01;
M[0, 2] = m02;
M[0, 3] = m03;
M[1, 0] = m10;
M[1, 1] = m11;
M[1, 2] = m12;
M[1, 3] = m13;
M[2, 0] = m20;
M[2, 1] = m21;
M[2, 2] = m22;
M[2, 3] = m23;
M[3, 0] = m30;
M[3, 1] = m31;
M[3, 2] = m32;
M[3, 3] = m33;
}
// Define a Identity matrix:
public void Identity3()
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (i == j)
{
M[i, j] = 1;
}
else
{
M[i, j] = 0;
}
}
}
}
// Multiply two matrices together:
public static Matrix3 operator *(Matrix3 m1, Matrix3 m2)
{
Matrix3 result = new Matrix3();
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
float element = 0;
for (int k = 0; k < 4; k++)
{
element += m1.M[i, k] * m2.M[k, j];
}
result.M[i, j] = element;
}
}
return result;
}
// Apply a transformation to a vector (point):
public float[] VectorMultiply(float[] vector)
{
float[] result = new float[4];
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
result[i] += M[i, j] * vector[j];
}
}
return result;
}
// Create a scaling matrix:
public static Matrix3 Scale3(float sx, float sy, float sz)
{
Matrix3 result = new Matrix3();
result.M[0, 0] = sx;
result.M[1, 1] = sy;
result.M[2, 2] = sz;
return result;
}
// Create a translation matrix
public static Matrix3 Translate3(float dx, float dy, float dz)
{
Matrix3 result = new Matrix3();
result.M[0, 3] = dx;
result.M[1, 3] = dy;
result.M[2, 3] = dz;
return result;
}
// Create a rotation matrix around the x axis:
public static Matrix3 Rotate3X(float theta)
{
theta = theta * (float)Math.PI / 180.0f;
float sn = (float)Math.Sin(theta);
float cn = (float)Math.Cos(theta);
Matrix3 result = new Matrix3();
result.M[1, 1] = cn;
result.M[1, 2] = -sn;
result.M[2, 1] = sn;
result.M[2, 2] = cn;
return result;
}
// Create a rotation matrix around the y axis:
public static Matrix3 Rotate3Y(float theta)
{
theta = theta * (float)Math.PI / 180.0f;
float sn = (float)Math.Sin(theta);
float cn = (float)Math.Cos(theta);
Matrix3 result = new Matrix3();
result.M[0, 0] = cn;
result.M[0, 2] = sn;
result.M[2, 0] = -sn;
result.M[2, 2] = cn;
return result;
}
// Create a rotation matrix around the z axis:
public static Matrix3 Rotate3Z(float theta)
{
theta = theta * (float)Math.PI / 180.0f;
float sn = (float)Math.Sin(theta);
float cn = (float)Math.Cos(theta);
Matrix3 result = new Matrix3();
result.M[0, 0] = cn;
result.M[0, 1] = -sn;
result.M[1, 0] = sn;
result.M[1, 1] = cn;
return result;
}
// Front view projection matrix:
public static Matrix3 FrontView()
{
Matrix3 result = new Matrix3();
result.M[2, 2] = 0;
return result;
}
// Side view projection matrix:
public static Matrix3 SideView()
{
Matrix3 result = new Matrix3();
result.M[0, 0] = 0;
result.M[2, 2] = 0;
result.M[0, 2] = -1;
return result;
}
// Top view projection matrix:
public static Matrix3 TopView()
{
Matrix3 result = new Matrix3();
result.M[1, 1] = 0;
result.M[2, 2] = 0;
result.M[1, 2] = -1;
return result;
}
// Axonometric projection matrix:
public static Matrix3 Axonometric(float alpha, float beta)
{
Matrix3 result = new Matrix3();
float sna = (float)Math.Sin(alpha * Math.PI / 180);
float cna = (float)Math.Cos(alpha * Math.PI / 180);
float snb = (float)Math.Sin(beta * Math.PI / 180);
float cnb = (float)Math.Cos(beta * Math.PI / 180);
result.M[0, 0] = cnb;
result.M[0, 2] = snb;
result.M[1, 0] = sna * snb;
result.M[1, 1] = cna;
result.M[1, 2] = -sna * cnb;
result.M[2, 2] = 0;
return result;
}
// Oblique projection matrix:
public static Matrix3 Oblique(float alpha, float theta)
{
Matrix3 result = new Matrix3();
float ta = (float)Math.Tan(alpha * Math.PI / 180);
float snt = (float)Math.Sin(theta * Math.PI / 180);
float cnt = (float)Math.Cos(theta * Math.PI / 180);
result.M[0, 2] = -cnt / ta;
result.M[1, 2] = -snt / ta;
result.M[2, 2] = 0;
return result;
}
// Perspective projection matrix:
public static Matrix3 Perspective(float d)
{
Matrix3 result = new Matrix3();
result.M[3, 2] = -1 / d;
return result;
}
public Point3 Cylindrical(float r, float theta, float y)
{
Point3 pt = new Point3();
float sn = (float)Math.Sin(theta * Math.PI / 180);
float cn = (float)Math.Cos(theta * Math.PI / 180);
pt.X = r * cn;
pt.Y = y;
pt.Z = -r * sn;
pt.W = 1;
return pt;
}
public Point3 Spherical(float r, float theta, float phi)
{
Point3 pt = new Point3();
float snt = (float)Math.Sin(theta * Math.PI / 180);
float cnt = (float)Math.Cos(theta * Math.PI / 180);
float snp = (float)Math.Sin(phi * Math.PI / 180);
float cnp = (float)Math.Cos(phi * Math.PI / 180);
pt.X = r * snt * cnp;
pt.Y = r * cnt;
pt.Z = -r * snt * snp;
pt.W = 1;
return pt;
}
public static Matrix3 Euler(float alpha, float beta, float gamma)
{
Matrix3 result = new Matrix3();
alpha = alpha * (float)Math.PI / 180.0f;
float sna = (float)Math.Sin(alpha);
float cna = (float)Math.Cos(alpha);
beta = beta * (float)Math.PI / 180.0f;
float snb = (float)Math.Sin(beta);
float cnb = (float)Math.Cos(beta);
gamma = gamma * (float)Math.PI / 180.0f;
float sng = (float)Math.Sin(gamma);
float cng = (float)Math.Cos(gamma);
result.M[0, 0] = cna * cng - sna * snb * sng;
result.M[0, 1] = -snb * sng;
result.M[0, 2] = sna * cng - cna * cnb * sng;
result.M[1, 0] = -sna * snb;
result.M[1, 1] = cnb;
result.M[1, 2] = cna * snb;
result.M[2, 0] = -cna * sng - sna * cnb * cng;
result.M[2, 1] = -snb * cng;
result.M[2, 2] = cna * cnb * cng - sna * snb;
return result;
}
public static Matrix3 AzimuthElevation(float elevation, float azimuth)
{
Matrix3 result = new Matrix3();
// make sure elevation in the range of [-90, 90]:
if (elevation > 90)
elevation = 90;
else if (elevation < -90)
elevation = -90;
// Make sure azimuth in the range of [-180, 180]:
if (azimuth > 180)
azimuth = 180;
else if (azimuth < -180)
azimuth = -180;
elevation = elevation * (float)Math.PI / 180.0f;
float sne = (float)Math.Sin(elevation);
float cne = (float)Math.Cos(elevation);
azimuth = azimuth * (float)Math.PI / 180.0f;
float sna = (float)Math.Sin(azimuth);
float cna = (float)Math.Cos(azimuth);
result.M[0, 0] = cna;
result.M[0, 1] = sna;
result.M[0, 2] = 0;
result.M[1, 0] = -sne * sna;
result.M[1, 1] = sne * cna;
result.M[1, 2] = cne;
result.M[2, 0] = cne * sna;
result.M[2, 1] = -cne * cna;
result.M[2, 2] = sne;
return result;
}
}
}
| |
//
// ExceptionInfo.cs
//
// Author:
// Lluis Sanchez Gual <lluis@novell.com>
//
// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Text;
namespace Mono.Debugging.Client
{
[Serializable]
public class ExceptionInfo
{
ObjectValue exception;
ObjectValue messageObject;
[NonSerialized]
ExceptionStackFrame[] frames;
[NonSerialized]
ExceptionInfo innerException;
[NonSerialized]
ObjectValue instance;
/// <summary>
/// The provided value can have the following members:
/// Type of the object: type of the exception
/// Message: Message of the exception
/// Instance: Raw instance of the exception
/// StackTrace: an array of frames. Each frame must have:
/// Value of the object: display text of the frame
/// File: name of the file
/// Line: line
/// Column: column
/// InnerException: inner exception, following the same format described above.
/// </summary>
public ExceptionInfo (ObjectValue exception)
{
this.exception = exception;
if (exception.IsEvaluating || exception.IsEvaluatingGroup)
exception.ValueChanged += HandleExceptionValueChanged;
}
void LoadMessage ()
{
if (messageObject == null) {
messageObject = exception.GetChild ("Message");
if (messageObject != null && messageObject.IsEvaluating)
messageObject.ValueChanged += HandleMessageValueChanged;
}
}
void HandleMessageValueChanged (object sender, EventArgs e)
{
frames = null;
NotifyChanged ();
}
void HandleExceptionValueChanged (object sender, EventArgs e)
{
frames = null;
if (exception.IsEvaluatingGroup)
exception = exception.GetArrayItem (0);
LoadMessage ();
NotifyChanged ();
}
void NotifyChanged ()
{
EventHandler evnt = Changed;
if (evnt != null)
evnt (this, EventArgs.Empty);
}
public string Type {
get { return exception.TypeName; }
}
public string Message {
get {
LoadMessage ();
if (messageObject != null && messageObject.IsEvaluating)
return "Loading...";
return messageObject != null ? messageObject.Value : null;
}
}
ObjectValue helpLinkObject;
public string HelpLink {
get {
if (helpLinkObject == null) {
helpLinkObject = exception.GetChild ("HelpLink");
if (helpLinkObject != null && helpLinkObject.IsEvaluating) {
helpLinkObject.ValueChanged += delegate {
NotifyChanged ();
};
}
}
return helpLinkObject != null ? helpLinkObject.Value : null;
}
}
public ObjectValue Instance {
get {
if (instance == null)
instance = exception.GetChild ("Instance");
if (instance == null)
return exception;
return instance;
}
}
public bool IsEvaluating {
get { return exception.IsEvaluating || exception.IsEvaluatingGroup; }
}
public bool StackIsEvaluating {
get {
ObjectValue stackTrace = exception.GetChild ("StackTrace");
if (stackTrace != null)
return stackTrace.IsEvaluating;
return false;
}
}
public ExceptionStackFrame[] StackTrace {
get {
if (frames != null)
return frames;
var stackTrace = exception.GetChild ("StackTrace");
if (stackTrace == null || stackTrace.IsNull)
return frames = new ExceptionStackFrame [0];
if (stackTrace.IsEvaluating) {
frames = new ExceptionStackFrame [0];
stackTrace.ValueChanged += HandleExceptionValueChanged;
return frames;
}
if (stackTrace.TypeName == "string") {
stackTrace = Debugging.Evaluation.ExceptionInfoSource.GetStackTrace (stackTrace.Value);
}
if (!stackTrace.IsArray) {
return frames = new ExceptionStackFrame [0];
}
var list = new List<ExceptionStackFrame> ();
for (int i = 0; i < stackTrace.ArrayCount; i++)
list.Add (new ExceptionStackFrame (stackTrace.GetArrayItem (i, EvaluationOptions.DefaultOptions)));
frames = list.ToArray ();
return frames;
}
}
public ExceptionInfo InnerException {
get {
if (innerException == null) {
ObjectValue innerVal = exception.GetChild ("InnerException");
if (innerVal == null || innerVal.IsNull || innerVal.IsError || innerVal.IsUnknown)
return null;
if (innerVal.IsEvaluating) {
innerVal.ValueChanged += delegate { NotifyChanged (); };
return null;
}
innerException = new ExceptionInfo (innerVal);
innerException.Changed += delegate {
NotifyChanged ();
};
}
return innerException;
}
}
List<ExceptionInfo> innerExceptions;
public List<ExceptionInfo> InnerExceptions {
get {
if (innerExceptions == null) {
ObjectValue innerVal = exception.GetChild ("InnerExceptions");
if (innerVal == null || innerVal.IsError || innerVal.IsUnknown)
return null;
if (innerVal.IsEvaluating) {
innerVal.ValueChanged += delegate { NotifyChanged (); };
return null;
}
innerExceptions = new List<ExceptionInfo> ();
foreach (var inner in innerVal.GetAllChildren ()) {
var innerObj = new ExceptionInfo (inner);
innerObj.Changed += delegate {
NotifyChanged ();
};
innerExceptions.Add (innerObj);
}
}
return innerExceptions;
}
}
public event EventHandler Changed;
internal void ConnectCallback (StackFrame parentFrame)
{
ObjectValue.ConnectCallbacks (parentFrame, exception);
}
public override string ToString ()
{
var sb = new StringBuilder ();
var chain = new List<ExceptionInfo> ();
var e = this;
while (e != null) {
chain.Insert (0, e);
if (sb.Length > 0)
sb.Append (" ---> ");
sb.Append (e.Type).Append (": ").Append (e.Message);
e = e.InnerException;
}
sb.AppendLine ();
foreach (var ex in chain) {
if (ex != chain[0])
sb.AppendLine (" --- End of inner exception stack trace ---");
foreach (var frame in ex.StackTrace) {
sb.Append (" at ").Append (frame.DisplayText);
if (!string.IsNullOrEmpty (frame.File)) {
sb.Append (" in ").Append (frame.File).Append (':').Append (frame.Line);
if (frame.Column != 0)
sb.Append (',').Append (frame.Column);
}
sb.AppendLine ();
}
}
return sb.ToString ();
}
}
public class ExceptionStackFrame
{
readonly ObjectValue frame;
/// <summary>
/// The provided value must have a specific structure.
/// The Value property is the display text.
/// A child "File" member must be the name of the file.
/// A child "Line" member must be the line.
/// A child "Column" member must be the column.
/// </summary>
public ExceptionStackFrame (ObjectValue value)
{
frame = value;
}
public string File {
get {
var file = frame.GetChild ("File", EvaluationOptions.DefaultOptions);
if (file != null)
return file.Value;
return null;
}
}
public int Line {
get {
var val = frame.GetChild ("Line", EvaluationOptions.DefaultOptions);
if (val != null)
return int.Parse (val.Value);
return 0;
}
}
public int Column {
get {
var val = frame.GetChild ("Column", EvaluationOptions.DefaultOptions);
if (val != null)
return int.Parse (val.Value);
return 0;
}
}
public string DisplayText {
get { return frame.Value; }
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.