context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Diagnostics;
using System.Windows.Forms;
using FileHelpers;
namespace FileHelpersSamples
{
/// <summary>
/// Menu of available sample forms.
/// Allows a new user to walk through the facilities of
/// the engine.
/// </summary>
/// <remarks>
/// This sample code will test whether the sample is the
/// latest available version.
/// </remarks>
public class frmSamples : frmFather
{
private Button cmdEasy;
private Button cmdDataLink;
private Button button1;
private Button cmdEasy2;
private Button cmdLibrary;
private System.Windows.Forms.Button cmdProgress;
private System.Windows.Forms.Button cmdSort;
private System.Windows.Forms.Button cmdAsync;
private System.Windows.Forms.Button cmdMasterDetail;
private System.Windows.Forms.PictureBox pictureBox7;
private System.Windows.Forms.PictureBox picCurrent;
private System.Windows.Forms.PictureBox picNewVersion;
private System.Windows.Forms.Button cmdMultipleDeli;
private System.Windows.Forms.Button cmdMultiTimming;
private System.Windows.Forms.PictureBox pictureBox5;
private System.Windows.Forms.PictureBox pictureBox6;
private System.Windows.Forms.PictureBox pictureBox4;
private System.Windows.Forms.ToolTip tip;
private System.Windows.Forms.Label lblVersion2;
private System.Windows.Forms.PictureBox pictureBox8;
private System.Windows.Forms.Button cmdReadAsDatatable;
private System.Windows.Forms.PictureBox pictureBox9;
private System.Windows.Forms.PictureBox pictureBox10;
private System.Windows.Forms.PictureBox pictureBox11;
private System.Windows.Forms.Button cmdRecordConditions;
private System.ComponentModel.IContainer components;
public frmSamples()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing) {
if (components != null)
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof (frmSamples));
this.cmdEasy = new System.Windows.Forms.Button();
this.cmdDataLink = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.cmdEasy2 = new System.Windows.Forms.Button();
this.cmdLibrary = new System.Windows.Forms.Button();
this.cmdProgress = new System.Windows.Forms.Button();
this.cmdMultiTimming = new System.Windows.Forms.Button();
this.cmdSort = new System.Windows.Forms.Button();
this.cmdMultipleDeli = new System.Windows.Forms.Button();
this.cmdAsync = new System.Windows.Forms.Button();
this.cmdMasterDetail = new System.Windows.Forms.Button();
this.pictureBox7 = new System.Windows.Forms.PictureBox();
this.picCurrent = new System.Windows.Forms.PictureBox();
this.picNewVersion = new System.Windows.Forms.PictureBox();
this.pictureBox5 = new System.Windows.Forms.PictureBox();
this.pictureBox6 = new System.Windows.Forms.PictureBox();
this.pictureBox4 = new System.Windows.Forms.PictureBox();
this.tip = new System.Windows.Forms.ToolTip(this.components);
this.pictureBox11 = new System.Windows.Forms.PictureBox();
this.pictureBox8 = new System.Windows.Forms.PictureBox();
this.lblVersion2 = new System.Windows.Forms.Label();
this.cmdReadAsDatatable = new System.Windows.Forms.Button();
this.pictureBox9 = new System.Windows.Forms.PictureBox();
this.cmdRecordConditions = new System.Windows.Forms.Button();
this.pictureBox10 = new System.Windows.Forms.PictureBox();
this.SuspendLayout();
//
// cmdEasy
//
this.cmdEasy.BackColor = System.Drawing.Color.FromArgb(((System.Byte) (0)),
((System.Byte) (0)),
((System.Byte) (110)));
this.cmdEasy.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cmdEasy.Font = new System.Drawing.Font("Tahoma",
11.25F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.cmdEasy.ForeColor = System.Drawing.Color.Gainsboro;
this.cmdEasy.Image = ((System.Drawing.Image) (resources.GetObject("cmdEasy.Image")));
this.cmdEasy.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
this.cmdEasy.Location = new System.Drawing.Point(11, 64);
this.cmdEasy.Name = "cmdEasy";
this.cmdEasy.Size = new System.Drawing.Size(216, 40);
this.cmdEasy.TabIndex = 0;
this.cmdEasy.Text = "Easy Delimited";
this.cmdEasy.Click += new System.EventHandler(this.cmdEasy_Click);
//
// cmdDataLink
//
this.cmdDataLink.BackColor = System.Drawing.Color.FromArgb(((System.Byte) (0)),
((System.Byte) (0)),
((System.Byte) (110)));
this.cmdDataLink.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cmdDataLink.Font = new System.Drawing.Font("Tahoma",
11.25F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.cmdDataLink.ForeColor = System.Drawing.Color.Gainsboro;
this.cmdDataLink.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
this.cmdDataLink.Location = new System.Drawing.Point(424, 208);
this.cmdDataLink.Name = "cmdDataLink";
this.cmdDataLink.Size = new System.Drawing.Size(216, 40);
this.cmdDataLink.TabIndex = 2;
this.cmdDataLink.Text = "Access DataLink";
this.cmdDataLink.Click += new System.EventHandler(this.cmdDataLink_Click);
//
// button1
//
this.button1.BackColor = System.Drawing.Color.FromArgb(((System.Byte) (0)),
((System.Byte) (0)),
((System.Byte) (110)));
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button1.Font = new System.Drawing.Font("Tahoma",
12F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.button1.ForeColor = System.Drawing.Color.Gainsboro;
this.button1.Location = new System.Drawing.Point(231, 357);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(192, 40);
this.button1.TabIndex = 4;
this.button1.Text = "Exit";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// cmdEasy2
//
this.cmdEasy2.BackColor = System.Drawing.Color.FromArgb(((System.Byte) (0)),
((System.Byte) (0)),
((System.Byte) (110)));
this.cmdEasy2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cmdEasy2.Font = new System.Drawing.Font("Tahoma",
11.25F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.cmdEasy2.ForeColor = System.Drawing.Color.Gainsboro;
this.cmdEasy2.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
this.cmdEasy2.Location = new System.Drawing.Point(11, 112);
this.cmdEasy2.Name = "cmdEasy2";
this.cmdEasy2.Size = new System.Drawing.Size(216, 40);
this.cmdEasy2.TabIndex = 1;
this.cmdEasy2.Text = "Easy Fixed";
this.cmdEasy2.Click += new System.EventHandler(this.cmdEasy2_Click);
//
// cmdLibrary
//
this.cmdLibrary.BackColor = System.Drawing.Color.FromArgb(((System.Byte) (0)),
((System.Byte) (0)),
((System.Byte) (110)));
this.cmdLibrary.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cmdLibrary.Font = new System.Drawing.Font("Tahoma",
11.25F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.cmdLibrary.ForeColor = System.Drawing.Color.Gainsboro;
this.cmdLibrary.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
this.cmdLibrary.Location = new System.Drawing.Point(424, 256);
this.cmdLibrary.Name = "cmdLibrary";
this.cmdLibrary.Size = new System.Drawing.Size(216, 40);
this.cmdLibrary.TabIndex = 3;
this.cmdLibrary.Text = "Time Testing";
this.cmdLibrary.Click += new System.EventHandler(this.cmdLibrary_Click);
//
// cmdProgress
//
this.cmdProgress.BackColor = System.Drawing.Color.FromArgb(((System.Byte) (0)),
((System.Byte) (0)),
((System.Byte) (110)));
this.cmdProgress.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cmdProgress.Font = new System.Drawing.Font("Tahoma",
11.25F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.cmdProgress.ForeColor = System.Drawing.Color.Gainsboro;
this.cmdProgress.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
this.cmdProgress.Location = new System.Drawing.Point(424, 160);
this.cmdProgress.Name = "cmdProgress";
this.cmdProgress.Size = new System.Drawing.Size(216, 40);
this.cmdProgress.TabIndex = 5;
this.cmdProgress.Text = "Progress Notification";
this.cmdProgress.Click += new System.EventHandler(this.cmdProgress_Click);
//
// cmdMultiTimming
//
this.cmdMultiTimming.BackColor = System.Drawing.Color.FromArgb(((System.Byte) (0)),
((System.Byte) (0)),
((System.Byte) (110)));
this.cmdMultiTimming.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cmdMultiTimming.Font = new System.Drawing.Font("Tahoma",
11.25F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.cmdMultiTimming.ForeColor = System.Drawing.Color.Gainsboro;
this.cmdMultiTimming.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
this.cmdMultiTimming.Location = new System.Drawing.Point(424, 304);
this.cmdMultiTimming.Name = "cmdMultiTimming";
this.cmdMultiTimming.Size = new System.Drawing.Size(216, 40);
this.cmdMultiTimming.TabIndex = 7;
this.cmdMultiTimming.Text = "Mult Time Testing";
this.cmdMultiTimming.Click += new System.EventHandler(this.button2_Click);
//
// cmdSort
//
this.cmdSort.BackColor = System.Drawing.Color.FromArgb(((System.Byte) (0)),
((System.Byte) (0)),
((System.Byte) (110)));
this.cmdSort.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cmdSort.Font = new System.Drawing.Font("Tahoma",
11.25F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.cmdSort.ForeColor = System.Drawing.Color.Gainsboro;
this.cmdSort.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
this.cmdSort.Location = new System.Drawing.Point(424, 112);
this.cmdSort.Name = "cmdSort";
this.cmdSort.Size = new System.Drawing.Size(216, 40);
this.cmdSort.TabIndex = 9;
this.cmdSort.Text = "Sorting";
this.cmdSort.Click += new System.EventHandler(this.cmdSort_Click);
//
// cmdMultipleDeli
//
this.cmdMultipleDeli.BackColor = System.Drawing.Color.FromArgb(((System.Byte) (0)),
((System.Byte) (0)),
((System.Byte) (110)));
this.cmdMultipleDeli.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cmdMultipleDeli.Font = new System.Drawing.Font("Tahoma",
11.25F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.cmdMultipleDeli.ForeColor = System.Drawing.Color.Gainsboro;
this.cmdMultipleDeli.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
this.cmdMultipleDeli.Location = new System.Drawing.Point(424, 64);
this.cmdMultipleDeli.Name = "cmdMultipleDeli";
this.cmdMultipleDeli.Size = new System.Drawing.Size(216, 40);
this.cmdMultipleDeli.TabIndex = 11;
this.cmdMultipleDeli.Text = "Changing Delimiters";
this.cmdMultipleDeli.Click += new System.EventHandler(this.cmdMiltipleDeli_Click);
//
// cmdAsync
//
this.cmdAsync.BackColor = System.Drawing.Color.FromArgb(((System.Byte) (0)),
((System.Byte) (0)),
((System.Byte) (110)));
this.cmdAsync.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cmdAsync.Font = new System.Drawing.Font("Tahoma",
11.25F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.cmdAsync.ForeColor = System.Drawing.Color.Gainsboro;
this.cmdAsync.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
this.cmdAsync.Location = new System.Drawing.Point(11, 160);
this.cmdAsync.Name = "cmdAsync";
this.cmdAsync.Size = new System.Drawing.Size(216, 40);
this.cmdAsync.TabIndex = 12;
this.cmdAsync.Text = "Record by Record";
this.cmdAsync.Click += new System.EventHandler(this.cmdAsync_Click);
//
// cmdMasterDetail
//
this.cmdMasterDetail.BackColor = System.Drawing.Color.FromArgb(((System.Byte) (0)),
((System.Byte) (0)),
((System.Byte) (110)));
this.cmdMasterDetail.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cmdMasterDetail.Font = new System.Drawing.Font("Tahoma",
11.25F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.cmdMasterDetail.ForeColor = System.Drawing.Color.Gainsboro;
this.cmdMasterDetail.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
this.cmdMasterDetail.Location = new System.Drawing.Point(11, 256);
this.cmdMasterDetail.Name = "cmdMasterDetail";
this.cmdMasterDetail.Size = new System.Drawing.Size(216, 40);
this.cmdMasterDetail.TabIndex = 15;
this.cmdMasterDetail.Text = "Master Detail";
this.cmdMasterDetail.Click += new System.EventHandler(this.cmdMasterDetail_Click);
//
// pictureBox7
//
this.pictureBox7.BackColor = System.Drawing.Color.Transparent;
this.pictureBox7.Image = ((System.Drawing.Image) (resources.GetObject("pictureBox7.Image")));
this.pictureBox7.Location = new System.Drawing.Point(224, 264);
this.pictureBox7.Name = "pictureBox7";
this.pictureBox7.Size = new System.Drawing.Size(48, 30);
this.pictureBox7.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox7.TabIndex = 16;
this.pictureBox7.TabStop = false;
//
// picCurrent
//
this.picCurrent.Anchor =
((System.Windows.Forms.AnchorStyles)
((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.picCurrent.BackColor = System.Drawing.Color.Transparent;
this.picCurrent.Image = ((System.Drawing.Image) (resources.GetObject("picCurrent.Image")));
this.picCurrent.Location = new System.Drawing.Point(545, 352);
this.picCurrent.Name = "picCurrent";
this.picCurrent.Size = new System.Drawing.Size(146, 53);
this.picCurrent.TabIndex = 17;
this.picCurrent.TabStop = false;
this.picCurrent.Visible = false;
//
// picNewVersion
//
this.picNewVersion.Anchor =
((System.Windows.Forms.AnchorStyles)
((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.picNewVersion.BackColor = System.Drawing.Color.Transparent;
this.picNewVersion.Cursor = System.Windows.Forms.Cursors.Hand;
this.picNewVersion.Image = ((System.Drawing.Image) (resources.GetObject("picNewVersion.Image")));
this.picNewVersion.Location = new System.Drawing.Point(545, 352);
this.picNewVersion.Name = "picNewVersion";
this.picNewVersion.Size = new System.Drawing.Size(146, 53);
this.picNewVersion.TabIndex = 18;
this.picNewVersion.TabStop = false;
this.picNewVersion.Visible = false;
this.picNewVersion.Click += new System.EventHandler(this.picNewVersion_Click);
//
// pictureBox5
//
this.pictureBox5.BackColor = System.Drawing.Color.Transparent;
this.pictureBox5.Image = ((System.Drawing.Image) (resources.GetObject("pictureBox5.Image")));
this.pictureBox5.Location = new System.Drawing.Point(224, 168);
this.pictureBox5.Name = "pictureBox5";
this.pictureBox5.Size = new System.Drawing.Size(48, 30);
this.pictureBox5.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox5.TabIndex = 19;
this.pictureBox5.TabStop = false;
//
// pictureBox6
//
this.pictureBox6.BackColor = System.Drawing.Color.Transparent;
this.pictureBox6.Image = ((System.Drawing.Image) (resources.GetObject("pictureBox6.Image")));
this.pictureBox6.Location = new System.Drawing.Point(224, 216);
this.pictureBox6.Name = "pictureBox6";
this.pictureBox6.Size = new System.Drawing.Size(48, 30);
this.pictureBox6.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox6.TabIndex = 20;
this.pictureBox6.TabStop = false;
//
// pictureBox4
//
this.pictureBox4.BackColor = System.Drawing.Color.Transparent;
this.pictureBox4.Image = ((System.Drawing.Image) (resources.GetObject("pictureBox4.Image")));
this.pictureBox4.Location = new System.Drawing.Point(640, 312);
this.pictureBox4.Name = "pictureBox4";
this.pictureBox4.Size = new System.Drawing.Size(48, 30);
this.pictureBox4.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox4.TabIndex = 21;
this.pictureBox4.TabStop = false;
//
// tip
//
this.tip.AutomaticDelay = 200;
this.tip.AutoPopDelay = 20000;
this.tip.InitialDelay = 200;
this.tip.ReshowDelay = 0;
this.tip.ShowAlways = true;
//
// pictureBox11
//
this.pictureBox11.BackColor = System.Drawing.Color.Transparent;
this.pictureBox11.Cursor = System.Windows.Forms.Cursors.Hand;
this.pictureBox11.Image = ((System.Drawing.Image) (resources.GetObject("pictureBox11.Image")));
this.pictureBox11.Location = new System.Drawing.Point(302, 244);
this.pictureBox11.Name = "pictureBox11";
this.pictureBox11.Size = new System.Drawing.Size(80, 98);
this.pictureBox11.TabIndex = 28;
this.pictureBox11.TabStop = false;
this.tip.SetToolTip(this.pictureBox11, "--> Devoo Software Home");
this.pictureBox11.Click += new System.EventHandler(this.pictureBox11_Click);
//
// pictureBox8
//
this.pictureBox8.BackColor = System.Drawing.Color.Transparent;
this.pictureBox8.Cursor = System.Windows.Forms.Cursors.Hand;
this.pictureBox8.Image = ((System.Drawing.Image) (resources.GetObject("pictureBox8.Image")));
this.pictureBox8.Location = new System.Drawing.Point(280, 80);
this.pictureBox8.Name = "pictureBox8";
this.pictureBox8.Size = new System.Drawing.Size(128, 152);
this.pictureBox8.TabIndex = 23;
this.pictureBox8.TabStop = false;
this.tip.SetToolTip(this.pictureBox8, "--> FileHelpers Home");
this.pictureBox8.Click += new System.EventHandler(this.pictureBox8_Click);
//
// lblVersion2
//
this.lblVersion2.BackColor = System.Drawing.Color.Transparent;
this.lblVersion2.Font = new System.Drawing.Font("Tahoma",
9F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.lblVersion2.ForeColor = System.Drawing.Color.FromArgb(((System.Byte) (224)),
((System.Byte) (224)),
((System.Byte) (224)));
this.lblVersion2.Location = new System.Drawing.Point(0, 386);
this.lblVersion2.Name = "lblVersion2";
this.lblVersion2.Size = new System.Drawing.Size(100, 18);
this.lblVersion2.TabIndex = 22;
this.lblVersion2.Text = "Version: ";
//
// cmdReadAsDatatable
//
this.cmdReadAsDatatable.BackColor = System.Drawing.Color.FromArgb(((System.Byte) (0)),
((System.Byte) (0)),
((System.Byte) (110)));
this.cmdReadAsDatatable.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cmdReadAsDatatable.Font = new System.Drawing.Font("Tahoma",
11.25F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.cmdReadAsDatatable.ForeColor = System.Drawing.Color.Gainsboro;
this.cmdReadAsDatatable.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
this.cmdReadAsDatatable.Location = new System.Drawing.Point(11, 208);
this.cmdReadAsDatatable.Name = "cmdReadAsDatatable";
this.cmdReadAsDatatable.Size = new System.Drawing.Size(216, 40);
this.cmdReadAsDatatable.TabIndex = 24;
this.cmdReadAsDatatable.Text = "Read as DataTable";
this.cmdReadAsDatatable.Click += new System.EventHandler(this.cmdReadAsDatatable_Click);
//
// pictureBox9
//
this.pictureBox9.BackColor = System.Drawing.Color.Transparent;
this.pictureBox9.Image = ((System.Drawing.Image) (resources.GetObject("pictureBox9.Image")));
this.pictureBox9.Location = new System.Drawing.Point(640, 72);
this.pictureBox9.Name = "pictureBox9";
this.pictureBox9.Size = new System.Drawing.Size(48, 30);
this.pictureBox9.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox9.TabIndex = 25;
this.pictureBox9.TabStop = false;
//
// cmdRecordConditions
//
this.cmdRecordConditions.BackColor = System.Drawing.Color.FromArgb(((System.Byte) (0)),
((System.Byte) (0)),
((System.Byte) (110)));
this.cmdRecordConditions.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cmdRecordConditions.Font = new System.Drawing.Font("Tahoma",
11.25F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.cmdRecordConditions.ForeColor = System.Drawing.Color.Gainsboro;
this.cmdRecordConditions.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
this.cmdRecordConditions.Location = new System.Drawing.Point(11, 304);
this.cmdRecordConditions.Name = "cmdRecordConditions";
this.cmdRecordConditions.Size = new System.Drawing.Size(216, 40);
this.cmdRecordConditions.TabIndex = 26;
this.cmdRecordConditions.Text = "Record Conditions";
this.cmdRecordConditions.Click += new System.EventHandler(this.cmdRecordConditions_Click);
//
// pictureBox10
//
this.pictureBox10.BackColor = System.Drawing.Color.Transparent;
this.pictureBox10.Image = ((System.Drawing.Image) (resources.GetObject("pictureBox10.Image")));
this.pictureBox10.Location = new System.Drawing.Point(224, 312);
this.pictureBox10.Name = "pictureBox10";
this.pictureBox10.Size = new System.Drawing.Size(48, 30);
this.pictureBox10.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox10.TabIndex = 27;
this.pictureBox10.TabStop = false;
//
// frmSamples
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.ClientSize = new System.Drawing.Size(690, 429);
this.Controls.Add(this.pictureBox11);
this.Controls.Add(this.cmdRecordConditions);
this.Controls.Add(this.pictureBox9);
this.Controls.Add(this.cmdReadAsDatatable);
this.Controls.Add(this.pictureBox8);
this.Controls.Add(this.lblVersion2);
this.Controls.Add(this.cmdMasterDetail);
this.Controls.Add(this.cmdMultipleDeli);
this.Controls.Add(this.cmdSort);
this.Controls.Add(this.cmdMultiTimming);
this.Controls.Add(this.cmdProgress);
this.Controls.Add(this.cmdLibrary);
this.Controls.Add(this.cmdEasy2);
this.Controls.Add(this.button1);
this.Controls.Add(this.cmdDataLink);
this.Controls.Add(this.cmdEasy);
this.Controls.Add(this.pictureBox4);
this.Controls.Add(this.pictureBox6);
this.Controls.Add(this.pictureBox7);
this.Controls.Add(this.cmdAsync);
this.Controls.Add(this.pictureBox5);
this.Controls.Add(this.pictureBox10);
this.Controls.Add(this.picCurrent);
this.Controls.Add(this.picNewVersion);
this.ExitOnEsc = false;
this.Name = "frmSamples";
this.Text = "FileHelpers Library - Samples ";
this.Load += new System.EventHandler(this.frmSamples_Load);
this.Activated += new System.EventHandler(this.frmSamples_Activated);
this.Controls.SetChildIndex(this.picNewVersion, 0);
this.Controls.SetChildIndex(this.picCurrent, 0);
this.Controls.SetChildIndex(this.pictureBox10, 0);
this.Controls.SetChildIndex(this.pictureBox5, 0);
this.Controls.SetChildIndex(this.cmdAsync, 0);
this.Controls.SetChildIndex(this.pictureBox7, 0);
this.Controls.SetChildIndex(this.pictureBox6, 0);
this.Controls.SetChildIndex(this.pictureBox4, 0);
this.Controls.SetChildIndex(this.cmdEasy, 0);
this.Controls.SetChildIndex(this.cmdDataLink, 0);
this.Controls.SetChildIndex(this.button1, 0);
this.Controls.SetChildIndex(this.cmdEasy2, 0);
this.Controls.SetChildIndex(this.cmdLibrary, 0);
this.Controls.SetChildIndex(this.cmdProgress, 0);
this.Controls.SetChildIndex(this.cmdMultiTimming, 0);
this.Controls.SetChildIndex(this.cmdSort, 0);
this.Controls.SetChildIndex(this.cmdMultipleDeli, 0);
this.Controls.SetChildIndex(this.cmdMasterDetail, 0);
this.Controls.SetChildIndex(this.lblVersion2, 0);
this.Controls.SetChildIndex(this.pictureBox8, 0);
this.Controls.SetChildIndex(this.cmdReadAsDatatable, 0);
this.Controls.SetChildIndex(this.pictureBox9, 0);
this.Controls.SetChildIndex(this.cmdRecordConditions, 0);
this.Controls.SetChildIndex(this.pictureBox11, 0);
this.ResumeLayout(false);
}
#endregion
private void cmdEasy_Click(object sender, EventArgs e)
{
frmEasySampleDelimited frm = new frmEasySampleDelimited();
frm.ShowDialog();
frm.Dispose();
}
private void cmdDataLink_Click(object sender, EventArgs e)
{
frmDataLinkSample frm = new frmDataLinkSample();
frm.ShowDialog();
frm.Dispose();
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void cmdEasy2_Click(object sender, EventArgs e)
{
frmEasySampleFixed frm = new frmEasySampleFixed();
frm.ShowDialog();
frm.Dispose();
}
private void cmdLibrary_Click(object sender, EventArgs e)
{
frmTimming frm = new frmTimming();
frm.ShowDialog();
frm.Dispose();
}
private void cmdProgress_Click(object sender, System.EventArgs e)
{
frmProgressSample frm = new frmProgressSample();
frm.ShowDialog();
frm.Dispose();
}
private void button2_Click(object sender, System.EventArgs e)
{
frmTimmingAdvanced frm = new frmTimmingAdvanced();
frm.ShowDialog();
frm.Dispose();
}
private void cmdSort_Click(object sender, System.EventArgs e)
{
frmSort frm = new frmSort();
frm.ShowDialog();
frm.Dispose();
}
private void cmdMiltipleDeli_Click(object sender, System.EventArgs e)
{
frmEasyMulti frm = new frmEasyMulti();
frm.ShowDialog();
frm.Dispose();
}
private void cmdAsync_Click(object sender, System.EventArgs e)
{
frmEasySampleAsync frm = new frmEasySampleAsync();
frm.ShowDialog();
frm.Dispose();
}
private void cmdMasterDetail_Click(object sender, System.EventArgs e)
{
frmMasterDetail frm = new frmMasterDetail();
frm.ShowDialog();
frm.Dispose();
}
private void frmSamples_Load(object sender, System.EventArgs e)
{
lblVersion2.Text += typeof (FileHelperEngine).Assembly.GetName().Version.ToString(3);
cmdEasy2.Image = cmdEasy.Image;
cmdAsync.Image = cmdEasy.Image;
cmdMultipleDeli.Image = cmdEasy.Image;
cmdMasterDetail.Image = cmdEasy.Image;
cmdProgress.Image = cmdEasy.Image;
cmdDataLink.Image = cmdEasy.Image;
cmdSort.Image = cmdEasy.Image;
cmdLibrary.Image = cmdEasy.Image;
cmdMultiTimming.Image = cmdEasy.Image;
cmdRecordConditions.Image = cmdEasy.Image;
cmdReadAsDatatable.Image = cmdEasy.Image;
}
private bool mFirstTime = true;
private void frmSamples_Activated(object sender, System.EventArgs e)
{
if (mFirstTime == false)
return;
mFirstTime = false;
// check versions with internet ones in background
System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(BuscarVersion));
}
/// <summary>
/// Version details from the Internet
/// </summary>
private VersionData mLastVersion;
/// <summary>
/// Load the current version details from the Internet
/// Then check the version of the engine against it.
/// </summary>
private void BuscarVersion(object target)
{
try {
mLastVersion = VersionData.GetLastVersion();
picNewVersion.Invoke(new SimpleHandler(MostrarVersion));
}
catch {}
}
/// <summary>
/// Confirm the working version against the latest one on the web
/// </summary>
/// <remarks>
/// Displays a 'current version' image or another image to encourage an update.
/// </remarks>
private void MostrarVersion()
{
if (mLastVersion == null)
return;
string ver = typeof (FileHelperEngine).Assembly.GetName().Version.ToString(3);
if (VersionData.CompararVersiones(ver, mLastVersion.Version) >= 0)
picCurrent.Visible = true;
else {
picNewVersion.Visible = true;
picNewVersion.Tag = mLastVersion;
tip.SetToolTip(picNewVersion,
"Version: " + mLastVersion.Version + Environment.NewLine + mLastVersion.Description);
}
}
private delegate void SimpleHandler();
private void picNewVersion_Click(object sender, System.EventArgs e)
{
frmLastVersion frm = new frmLastVersion((VersionData) picNewVersion.Tag);
frm.ShowDialog();
frm.Dispose();
}
private void cmdReadAsDatatable_Click(object sender, System.EventArgs e)
{
frmEasyToDataTable frm = new frmEasyToDataTable();
frm.ShowDialog();
frm.Dispose();
}
private void pictureBox11_Click(object sender, System.EventArgs e)
{
ProcessStartInfo info = new ProcessStartInfo("explorer", "\"http://www.devoo.net\"");
Process.Start(info);
}
private void pictureBox8_Click(object sender, System.EventArgs e)
{
ProcessStartInfo info = new ProcessStartInfo("explorer", "\"http://www.filehelpers.net\"");
Process.Start(info);
}
private void cmdRecordConditions_Click(object sender, System.EventArgs e)
{
frmRecordConditions frm = new frmRecordConditions();
frm.ShowDialog();
frm.Dispose();
}
}
}
| |
// 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.IotHub
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
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>
/// API for using the IoT Hub Features.
/// </summary>
public partial class IotHubClient : ServiceClient<IotHubClient>, IIotHubClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Gets Azure subscription credentials.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// The subscription identifier.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Version of the Api.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IIotHubResourceOperations.
/// </summary>
public virtual IIotHubResourceOperations IotHubResource { get; private set; }
/// <summary>
/// Initializes a new instance of the IotHubClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected IotHubClient(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the IotHubClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected IotHubClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the IotHubClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected IotHubClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the IotHubClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected IotHubClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the IotHubClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public IotHubClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the IotHubClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public IotHubClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the IotHubClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public IotHubClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the IotHubClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public IotHubClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.IotHubResource = new IotHubResourceOperations(this);
this.BaseUri = new Uri("https://management.azure.com");
this.ApiVersion = "2016-02-03";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
/*
* 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.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Lifetime;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Xml;
using OpenMetaverse;
using log4net;
using Nini.Config;
using Amib.Threading;
using OpenSim.Framework;
using OpenSim.Region.CoreModules;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.Api.Runtime;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Region.ScriptEngine.Shared.CodeTools;
using OpenSim.Region.ScriptEngine.Interfaces;
namespace OpenSim.Region.ScriptEngine.Shared.Instance
{
public class ScriptInstance : MarshalByRefObject, IScriptInstance
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// The current work item if an event for this script is running or waiting to run,
/// </summary>
/// <remarks>
/// Null if there is no running or waiting to run event. Must be changed only under an EventQueue lock.
/// </remarks>
private IScriptWorkItem m_CurrentWorkItem;
private IScript m_Script;
private DetectParams[] m_DetectParams;
private bool m_TimerQueued;
private DateTime m_EventStart;
private bool m_InEvent;
private string m_Assembly;
private string m_CurrentEvent = String.Empty;
private bool m_InSelfDelete;
private int m_MaxScriptQueue;
private bool m_SaveState = true;
private int m_ControlEventsInQueue;
private int m_LastControlLevel;
private bool m_CollisionInQueue;
// The following is for setting a minimum delay between events
private double m_minEventDelay;
private long m_eventDelayTicks;
private long m_nextEventTimeTicks;
private bool m_startOnInit = true;
private UUID m_AttachedAvatar;
private StateSource m_stateSource;
private bool m_postOnRez;
private bool m_startedFromSavedState;
private UUID m_CurrentStateHash;
private UUID m_RegionID;
public int DebugLevel { get; set; }
public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> LineMap { get; set; }
private Dictionary<string,IScriptApi> m_Apis = new Dictionary<string,IScriptApi>();
public Object[] PluginData = new Object[0];
/// <summary>
/// Used by llMinEventDelay to suppress events happening any faster than this speed.
/// This currently restricts all events in one go. Not sure if each event type has
/// its own check so take the simple route first.
/// </summary>
public double MinEventDelay
{
get { return m_minEventDelay; }
set
{
if (value > 0.001)
m_minEventDelay = value;
else
m_minEventDelay = 0.0;
m_eventDelayTicks = (long)(m_minEventDelay * 10000000L);
m_nextEventTimeTicks = DateTime.Now.Ticks;
}
}
public bool Running { get; set; }
public bool Suspended
{
get { return m_Suspended; }
set
{
// Need to do this inside a lock in order to avoid races with EventProcessor()
lock (m_Script)
{
bool wasSuspended = m_Suspended;
m_Suspended = value;
if (wasSuspended && !m_Suspended)
{
lock (EventQueue)
{
// Need to place ourselves back in a work item if there are events to process
if (EventQueue.Count > 0 && Running && !ShuttingDown)
m_CurrentWorkItem = Engine.QueueEventHandler(this);
}
}
}
}
}
private bool m_Suspended;
public bool ShuttingDown { get; set; }
public string State { get; set; }
public IScriptEngine Engine { get; private set; }
public UUID AppDomain { get; set; }
public SceneObjectPart Part { get; private set; }
public string PrimName { get; private set; }
public string ScriptName { get; private set; }
public UUID ItemID { get; private set; }
public UUID ObjectID { get { return Part.UUID; } }
public uint LocalID { get { return Part.LocalId; } }
public UUID RootObjectID { get { return Part.ParentGroup.UUID; } }
public uint RootLocalID { get { return Part.ParentGroup.LocalId; } }
public UUID AssetID { get; private set; }
public Queue EventQueue { get; private set; }
public long EventsQueued
{
get
{
lock (EventQueue)
return EventQueue.Count;
}
}
public long EventsProcessed { get; private set; }
public int StartParam { get; set; }
public TaskInventoryItem ScriptTask { get; private set; }
public DateTime TimeStarted { get; private set; }
public long MeasurementPeriodTickStart { get; private set; }
public long MeasurementPeriodExecutionTime { get; private set; }
public static readonly long MaxMeasurementPeriod = 30 * TimeSpan.TicksPerMinute;
private bool m_coopTermination;
private EventWaitHandle m_coopSleepHandle;
public void ClearQueue()
{
m_TimerQueued = false;
EventQueue.Clear();
}
public ScriptInstance(
IScriptEngine engine, SceneObjectPart part, TaskInventoryItem item,
int startParam, bool postOnRez,
int maxScriptQueue)
{
State = "default";
EventQueue = new Queue(32);
Engine = engine;
Part = part;
ScriptTask = item;
// This is currently only here to allow regression tests to get away without specifying any inventory
// item when they are testing script logic that doesn't require an item.
if (ScriptTask != null)
{
ScriptName = ScriptTask.Name;
ItemID = ScriptTask.ItemID;
AssetID = ScriptTask.AssetID;
}
PrimName = part.ParentGroup.Name;
StartParam = startParam;
m_MaxScriptQueue = maxScriptQueue;
m_postOnRez = postOnRez;
m_AttachedAvatar = Part.ParentGroup.AttachedAvatar;
m_RegionID = Part.ParentGroup.Scene.RegionInfo.RegionID;
if (Engine.Config.GetString("ScriptStopStrategy", "abort") == "co-op")
{
m_coopTermination = true;
m_coopSleepHandle = new XEngineEventWaitHandle(false, EventResetMode.AutoReset);
}
}
/// <summary>
/// Load the script from an assembly into an AppDomain.
/// </summary>
/// <param name='dom'></param>
/// <param name='assembly'></param>
/// <param name='stateSource'></param>
/// <returns>false if load failed, true if suceeded</returns>
public bool Load(AppDomain dom, string assembly, StateSource stateSource)
{
m_Assembly = assembly;
m_stateSource = stateSource;
ApiManager am = new ApiManager();
foreach (string api in am.GetApis())
{
m_Apis[api] = am.CreateApi(api);
m_Apis[api].Initialize(Engine, Part, ScriptTask, m_coopSleepHandle);
}
try
{
object[] constructorParams;
Assembly scriptAssembly = dom.Load(Path.GetFileNameWithoutExtension(assembly));
Type scriptType = scriptAssembly.GetType("SecondLife.XEngineScript");
if (scriptType != null)
{
constructorParams = new object[] { m_coopSleepHandle };
}
else if (!m_coopTermination)
{
scriptType = scriptAssembly.GetType("SecondLife.Script");
constructorParams = null;
}
else
{
m_log.ErrorFormat(
"[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. You must remove all existing {6}* script DLL files before using enabling co-op termination"
+ ", either by setting DeleteScriptsOnStartup = true in [XEngine] for one run"
+ " or by deleting these files manually.",
ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, assembly);
return false;
}
// m_log.DebugFormat(
// "[SCRIPT INSTANCE]: Looking to load {0} from assembly {1} in {2}",
// scriptType.FullName, Path.GetFileNameWithoutExtension(assembly), Engine.World.Name);
if (dom != System.AppDomain.CurrentDomain)
m_Script
= (IScript)dom.CreateInstanceAndUnwrap(
Path.GetFileNameWithoutExtension(assembly),
scriptType.FullName,
false,
BindingFlags.Default,
null,
constructorParams,
null,
null,
null);
else
m_Script
= (IScript)scriptAssembly.CreateInstance(
scriptType.FullName,
false,
BindingFlags.Default,
null,
constructorParams,
null,
null);
//ILease lease = (ILease)RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass);
//RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass);
// lease.Register(this);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Error loading assembly {6}. Exception {7}{8}",
ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, assembly, e.Message, e.StackTrace);
return false;
}
try
{
foreach (KeyValuePair<string,IScriptApi> kv in m_Apis)
{
m_Script.InitApi(kv.Key, kv.Value);
}
// // m_log.Debug("[Script] Script instance created");
Part.SetScriptEvents(ItemID,
(int)m_Script.GetStateEventFlags(State));
}
catch (Exception e)
{
m_log.ErrorFormat(
"[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Error initializing script instance. Exception {6}{7}",
ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, e.Message, e.StackTrace);
return false;
}
m_SaveState = true;
string savedState = Path.Combine(Path.GetDirectoryName(assembly),
ItemID.ToString() + ".state");
if (File.Exists(savedState))
{
string xml = String.Empty;
try
{
FileInfo fi = new FileInfo(savedState);
int size = (int)fi.Length;
if (size < 512000)
{
using (FileStream fs = File.Open(savedState,
FileMode.Open, FileAccess.Read, FileShare.None))
{
Byte[] data = new Byte[size];
fs.Read(data, 0, size);
xml = Encoding.UTF8.GetString(data);
ScriptSerializer.Deserialize(xml, this);
AsyncCommandManager.CreateFromData(Engine,
LocalID, ItemID, ObjectID,
PluginData);
// m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", PrimName, m_ScriptName);
Part.SetScriptEvents(ItemID,
(int)m_Script.GetStateEventFlags(State));
if (!Running)
m_startOnInit = false;
Running = false;
// we get new rez events on sim restart, too
// but if there is state, then we fire the change
// event
// We loaded state, don't force a re-save
m_SaveState = false;
m_startedFromSavedState = true;
}
}
else
{
m_log.WarnFormat(
"[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Unable to load script state file {6}. Memory limit exceeded.",
ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState);
}
}
catch (Exception e)
{
m_log.ErrorFormat(
"[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Unable to load script state file {6}. XML is {7}. Exception {8}{9}",
ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState, xml, e.Message, e.StackTrace);
}
}
// else
// {
// ScenePresence presence = Engine.World.GetScenePresence(part.OwnerID);
// if (presence != null && (!postOnRez))
// presence.ControllingClient.SendAgentAlertMessage("Compile successful", false);
// }
return true;
}
public void Init()
{
if (ShuttingDown)
return;
if (m_startedFromSavedState)
{
if (m_startOnInit)
Start();
if (m_postOnRez)
{
PostEvent(new EventParams("on_rez",
new Object[] {new LSL_Types.LSLInteger(StartParam)}, new DetectParams[0]));
}
if (m_stateSource == StateSource.AttachedRez)
{
PostEvent(new EventParams("attach",
new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0]));
}
else if (m_stateSource == StateSource.RegionStart)
{
//m_log.Debug("[Script] Posted changed(CHANGED_REGION_RESTART) to script");
PostEvent(new EventParams("changed",
new Object[] { new LSL_Types.LSLInteger((int)Changed.REGION_RESTART) }, new DetectParams[0]));
}
else if (m_stateSource == StateSource.PrimCrossing || m_stateSource == StateSource.Teleporting)
{
// CHANGED_REGION
PostEvent(new EventParams("changed",
new Object[] { new LSL_Types.LSLInteger((int)Changed.REGION) }, new DetectParams[0]));
// CHANGED_TELEPORT
if (m_stateSource == StateSource.Teleporting)
PostEvent(new EventParams("changed",
new Object[] { new LSL_Types.LSLInteger((int)Changed.TELEPORT) }, new DetectParams[0]));
}
}
else
{
if (m_startOnInit)
Start();
PostEvent(new EventParams("state_entry",
new Object[0], new DetectParams[0]));
if (m_postOnRez)
{
PostEvent(new EventParams("on_rez",
new Object[] {new LSL_Types.LSLInteger(StartParam)}, new DetectParams[0]));
}
if (m_stateSource == StateSource.AttachedRez)
{
PostEvent(new EventParams("attach",
new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0]));
}
}
}
private void ReleaseControls()
{
int permsMask;
UUID permsGranter;
lock (Part.TaskInventory)
{
if (!Part.TaskInventory.ContainsKey(ItemID))
return;
permsGranter = Part.TaskInventory[ItemID].PermsGranter;
permsMask = Part.TaskInventory[ItemID].PermsMask;
}
if ((permsMask & ScriptBaseClass.PERMISSION_TAKE_CONTROLS) != 0)
{
ScenePresence presence = Engine.World.GetScenePresence(permsGranter);
if (presence != null)
presence.UnRegisterControlEventsToScript(LocalID, ItemID);
}
}
public void DestroyScriptInstance()
{
ReleaseControls();
AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID);
}
public void RemoveState()
{
string savedState = Path.Combine(Path.GetDirectoryName(m_Assembly),
ItemID.ToString() + ".state");
try
{
File.Delete(savedState);
}
catch (Exception e)
{
m_log.Warn(
string.Format(
"[SCRIPT INSTANCE]: Could not delete script state {0} for script {1} (id {2}) in part {3} (id {4}) in object {5} in {6}. Exception ",
savedState, ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name),
e);
}
}
public void VarDump(Dictionary<string, object> vars)
{
// m_log.Info("Variable dump for script "+ ItemID.ToString());
// foreach (KeyValuePair<string, object> v in vars)
// {
// m_log.Info("Variable: "+v.Key+" = "+v.Value.ToString());
// }
}
public void Start()
{
lock (EventQueue)
{
if (Running)
return;
Running = true;
TimeStarted = DateTime.Now;
MeasurementPeriodTickStart = Util.EnvironmentTickCount();
MeasurementPeriodExecutionTime = 0;
if (EventQueue.Count > 0)
{
if (m_CurrentWorkItem == null)
m_CurrentWorkItem = Engine.QueueEventHandler(this);
// else
// m_log.Error("[Script] Tried to start a script that was already queued");
}
}
}
public bool Stop(int timeout)
{
if (DebugLevel >= 1)
m_log.DebugFormat(
"[SCRIPT INSTANCE]: Stopping script {0} {1} in {2} {3} with timeout {4} {5} {6}",
ScriptName, ItemID, PrimName, ObjectID, timeout, m_InSelfDelete, DateTime.Now.Ticks);
IScriptWorkItem workItem;
lock (EventQueue)
{
if (!Running)
return true;
// If we're not running or waiting to run an event then we can safely stop.
if (m_CurrentWorkItem == null)
{
Running = false;
return true;
}
// If we are waiting to run an event then we can try to cancel it.
if (m_CurrentWorkItem.Cancel())
{
m_CurrentWorkItem = null;
Running = false;
return true;
}
workItem = m_CurrentWorkItem;
Running = false;
}
// Wait for the current event to complete.
if (!m_InSelfDelete)
{
if (!m_coopTermination)
{
// If we're not co-operative terminating then try and wait for the event to complete before stopping
if (workItem.Wait(timeout))
return true;
}
else
{
if (DebugLevel >= 1)
m_log.DebugFormat(
"[SCRIPT INSTANCE]: Co-operatively stopping script {0} {1} in {2} {3}",
ScriptName, ItemID, PrimName, ObjectID);
// This will terminate the event on next handle check by the script.
m_coopSleepHandle.Set();
// For now, we will wait forever since the event should always cleanly terminate once LSL loop
// checking is implemented. May want to allow a shorter timeout option later.
if (workItem.Wait(Timeout.Infinite))
{
if (DebugLevel >= 1)
m_log.DebugFormat(
"[SCRIPT INSTANCE]: Co-operatively stopped script {0} {1} in {2} {3}",
ScriptName, ItemID, PrimName, ObjectID);
return true;
}
}
}
lock (EventQueue)
{
workItem = m_CurrentWorkItem;
}
if (workItem == null)
return true;
// If the event still hasn't stopped and we the stop isn't the result of script or object removal, then
// forcibly abort the work item (this aborts the underlying thread).
// Co-operative termination should never reach this point.
if (!m_InSelfDelete)
{
m_log.DebugFormat(
"[SCRIPT INSTANCE]: Aborting unstopped script {0} {1} in prim {2}, localID {3}, timeout was {4} ms",
ScriptName, ItemID, PrimName, LocalID, timeout);
workItem.Abort();
}
lock (EventQueue)
{
m_CurrentWorkItem = null;
}
return true;
}
public void SetState(string state)
{
if (state == State)
return;
PostEvent(new EventParams("state_exit", new Object[0],
new DetectParams[0]));
PostEvent(new EventParams("state", new Object[] { state },
new DetectParams[0]));
PostEvent(new EventParams("state_entry", new Object[0],
new DetectParams[0]));
throw new EventAbortException();
}
/// <summary>
/// Post an event to this script instance.
/// </summary>
/// <remarks>
/// The request to run the event is sent
/// </remarks>
/// <param name="data"></param>
public void PostEvent(EventParams data)
{
// m_log.DebugFormat("[Script] Posted event {2} in state {3} to {0}.{1}",
// PrimName, ScriptName, data.EventName, State);
if (!Running)
return;
// If min event delay is set then ignore any events untill the time has expired
// This currently only allows 1 event of any type in the given time period.
// This may need extending to allow for a time for each individual event type.
if (m_eventDelayTicks != 0)
{
if (DateTime.Now.Ticks < m_nextEventTimeTicks)
return;
m_nextEventTimeTicks = DateTime.Now.Ticks + m_eventDelayTicks;
}
lock (EventQueue)
{
if (EventQueue.Count >= m_MaxScriptQueue)
return;
if (data.EventName == "timer")
{
if (m_TimerQueued)
return;
m_TimerQueued = true;
}
if (data.EventName == "control")
{
int held = ((LSL_Types.LSLInteger)data.Params[1]).value;
// int changed = ((LSL_Types.LSLInteger)data.Params[2]).value;
// If the last message was a 0 (nothing held)
// and this one is also nothing held, drop it
//
if (m_LastControlLevel == held && held == 0)
return;
// If there is one or more queued, then queue
// only changed ones, else queue unconditionally
//
if (m_ControlEventsInQueue > 0)
{
if (m_LastControlLevel == held)
return;
}
m_LastControlLevel = held;
m_ControlEventsInQueue++;
}
if (data.EventName == "collision")
{
if (m_CollisionInQueue)
return;
if (data.DetectParams == null)
return;
m_CollisionInQueue = true;
}
EventQueue.Enqueue(data);
if (m_CurrentWorkItem == null)
{
m_CurrentWorkItem = Engine.QueueEventHandler(this);
}
}
}
/// <summary>
/// Process the next event queued for this script
/// </summary>
/// <returns></returns>
public object EventProcessor()
{
// We check here as the thread stopping this instance from running may itself hold the m_Script lock.
if (!Running)
return 0;
lock (m_Script)
{
// m_log.DebugFormat("[XEngine]: EventProcessor() invoked for {0}.{1}", PrimName, ScriptName);
if (Suspended)
return 0;
EventParams data = null;
lock (EventQueue)
{
data = (EventParams)EventQueue.Dequeue();
if (data == null) // Shouldn't happen
{
if (EventQueue.Count > 0 && Running && !ShuttingDown)
{
m_CurrentWorkItem = Engine.QueueEventHandler(this);
}
else
{
m_CurrentWorkItem = null;
}
return 0;
}
if (data.EventName == "timer")
m_TimerQueued = false;
if (data.EventName == "control")
{
if (m_ControlEventsInQueue > 0)
m_ControlEventsInQueue--;
}
if (data.EventName == "collision")
m_CollisionInQueue = false;
}
if (DebugLevel >= 2)
m_log.DebugFormat(
"[SCRIPT INSTANCE]: Processing event {0} for {1}/{2}({3})/{4}({5}) @ {6}/{7}",
data.EventName,
ScriptName,
Part.Name,
Part.LocalId,
Part.ParentGroup.Name,
Part.ParentGroup.UUID,
Part.AbsolutePosition,
Part.ParentGroup.Scene.Name);
m_DetectParams = data.DetectParams;
if (data.EventName == "state") // Hardcoded state change
{
State = data.Params[0].ToString();
if (DebugLevel >= 1)
m_log.DebugFormat(
"[SCRIPT INSTANCE]: Changing state to {0} for {1}/{2}({3})/{4}({5}) @ {6}/{7}",
State,
ScriptName,
Part.Name,
Part.LocalId,
Part.ParentGroup.Name,
Part.ParentGroup.UUID,
Part.AbsolutePosition,
Part.ParentGroup.Scene.Name);
AsyncCommandManager.StateChange(Engine,
LocalID, ItemID);
Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State));
}
else
{
if (Engine.World.PipeEventsForScript(LocalID) ||
data.EventName == "control") // Don't freeze avies!
{
// m_log.DebugFormat("[Script] Delivered event {2} in state {3} to {0}.{1}",
// PrimName, ScriptName, data.EventName, State);
try
{
m_CurrentEvent = data.EventName;
m_EventStart = DateTime.Now;
m_InEvent = true;
int start = Util.EnvironmentTickCount();
// Reset the measurement period when we reach the end of the current one.
if (start - MeasurementPeriodTickStart > MaxMeasurementPeriod)
MeasurementPeriodTickStart = start;
m_Script.ExecuteEvent(State, data.EventName, data.Params);
MeasurementPeriodExecutionTime += Util.EnvironmentTickCount() - start;
m_InEvent = false;
m_CurrentEvent = String.Empty;
if (m_SaveState)
{
// This will be the very first event we deliver
// (state_entry) in default state
//
SaveState(m_Assembly);
m_SaveState = false;
}
}
catch (Exception e)
{
// m_log.DebugFormat(
// "[SCRIPT] Exception in script {0} {1}: {2}{3}",
// ScriptName, ItemID, e.Message, e.StackTrace);
m_InEvent = false;
m_CurrentEvent = String.Empty;
if ((!(e is TargetInvocationException)
|| (!(e.InnerException is SelfDeleteException)
&& !(e.InnerException is ScriptDeleteException)
&& !(e.InnerException is ScriptCoopStopException)))
&& !(e is ThreadAbortException))
{
try
{
// DISPLAY ERROR INWORLD
string text = FormatException(e);
if (text.Length > 1000)
text = text.Substring(0, 1000);
Engine.World.SimChat(Utils.StringToBytes(text),
ChatTypeEnum.DebugChannel, 2147483647,
Part.AbsolutePosition,
Part.Name, Part.UUID, false);
m_log.Debug(string.Format(
"[SCRIPT INSTANCE]: Runtime error in script {0}, part {1} {2} at {3} in {4} ",
ScriptName,
PrimName,
Part.UUID,
Part.AbsolutePosition,
Part.ParentGroup.Scene.Name),
e);
}
catch (Exception)
{
}
// catch (Exception e2) // LEGIT: User Scripting
// {
// m_log.Error("[SCRIPT]: "+
// "Error displaying error in-world: " +
// e2.ToString());
// m_log.Error("[SCRIPT]: " +
// "Errormessage: Error compiling script:\r\n" +
// e.ToString());
// }
}
else if ((e is TargetInvocationException) && (e.InnerException is SelfDeleteException))
{
m_InSelfDelete = true;
Engine.World.DeleteSceneObject(Part.ParentGroup, false);
}
else if ((e is TargetInvocationException) && (e.InnerException is ScriptDeleteException))
{
m_InSelfDelete = true;
Part.Inventory.RemoveInventoryItem(ItemID);
}
else if ((e is TargetInvocationException) && (e.InnerException is ScriptCoopStopException))
{
if (DebugLevel >= 1)
m_log.DebugFormat(
"[SCRIPT INSTANCE]: Script {0}.{1} in event {2}, state {3} stopped co-operatively.",
PrimName, ScriptName, data.EventName, State);
}
}
}
}
// If there are more events and we are currently running and not shutting down, then ask the
// script engine to run the next event.
lock (EventQueue)
{
EventsProcessed++;
if (EventQueue.Count > 0 && Running && !ShuttingDown)
{
m_CurrentWorkItem = Engine.QueueEventHandler(this);
}
else
{
m_CurrentWorkItem = null;
}
}
m_DetectParams = null;
return 0;
}
}
public int EventTime()
{
if (!m_InEvent)
return 0;
return (DateTime.Now - m_EventStart).Seconds;
}
public void ResetScript(int timeout)
{
if (m_Script == null)
return;
bool running = Running;
RemoveState();
ReleaseControls();
Stop(timeout);
Part.Inventory.GetInventoryItem(ItemID).PermsMask = 0;
Part.Inventory.GetInventoryItem(ItemID).PermsGranter = UUID.Zero;
AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID);
EventQueue.Clear();
m_Script.ResetVars();
State = "default";
Part.SetScriptEvents(ItemID,
(int)m_Script.GetStateEventFlags(State));
if (running)
Start();
m_SaveState = true;
PostEvent(new EventParams("state_entry",
new Object[0], new DetectParams[0]));
}
public void ApiResetScript()
{
// bool running = Running;
RemoveState();
ReleaseControls();
m_Script.ResetVars();
Part.Inventory.GetInventoryItem(ItemID).PermsMask = 0;
Part.Inventory.GetInventoryItem(ItemID).PermsGranter = UUID.Zero;
AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID);
EventQueue.Clear();
m_Script.ResetVars();
State = "default";
Part.SetScriptEvents(ItemID,
(int)m_Script.GetStateEventFlags(State));
if (m_CurrentEvent != "state_entry")
{
m_SaveState = true;
PostEvent(new EventParams("state_entry",
new Object[0], new DetectParams[0]));
throw new EventAbortException();
}
}
public Dictionary<string, object> GetVars()
{
if (m_Script != null)
return m_Script.GetVars();
else
return new Dictionary<string, object>();
}
public void SetVars(Dictionary<string, object> vars)
{
m_Script.SetVars(vars);
}
public DetectParams GetDetectParams(int idx)
{
if (m_DetectParams == null)
return null;
if (idx < 0 || idx >= m_DetectParams.Length)
return null;
return m_DetectParams[idx];
}
public UUID GetDetectID(int idx)
{
if (m_DetectParams == null)
return UUID.Zero;
if (idx < 0 || idx >= m_DetectParams.Length)
return UUID.Zero;
return m_DetectParams[idx].Key;
}
public void SaveState(string assembly)
{
// If we're currently in an event, just tell it to save upon return
//
if (m_InEvent)
{
m_SaveState = true;
return;
}
PluginData = AsyncCommandManager.GetSerializationData(Engine, ItemID);
string xml = ScriptSerializer.Serialize(this);
// Compare hash of the state we just just created with the state last written to disk
// If the state is different, update the disk file.
UUID hash = UUID.Parse(Utils.MD5String(xml));
if (hash != m_CurrentStateHash)
{
try
{
FileStream fs = File.Create(Path.Combine(Path.GetDirectoryName(assembly), ItemID.ToString() + ".state"));
Byte[] buf = Util.UTF8NoBomEncoding.GetBytes(xml);
fs.Write(buf, 0, buf.Length);
fs.Close();
}
catch(Exception)
{
// m_log.Error("Unable to save xml\n"+e.ToString());
}
//if (!File.Exists(Path.Combine(Path.GetDirectoryName(assembly), ItemID.ToString() + ".state")))
//{
// throw new Exception("Completed persistence save, but no file was created");
//}
m_CurrentStateHash = hash;
}
}
public IScriptApi GetApi(string name)
{
if (m_Apis.ContainsKey(name))
{
// m_log.DebugFormat("[SCRIPT INSTANCE]: Found api {0} in {1}@{2}", name, ScriptName, PrimName);
return m_Apis[name];
}
// m_log.DebugFormat("[SCRIPT INSTANCE]: Did not find api {0} in {1}@{2}", name, ScriptName, PrimName);
return null;
}
public override string ToString()
{
return String.Format("{0} {1} on {2}", ScriptName, ItemID, PrimName);
}
string FormatException(Exception e)
{
if (e.InnerException == null) // Not a normal runtime error
return e.ToString();
string message = "Runtime error:\n" + e.InnerException.StackTrace;
string[] lines = message.Split(new char[] {'\n'});
foreach (string line in lines)
{
if (line.Contains("SecondLife.Script"))
{
int idx = line.IndexOf(':');
if (idx != -1)
{
string val = line.Substring(idx+1);
int lineNum = 0;
if (int.TryParse(val, out lineNum))
{
KeyValuePair<int, int> pos =
Compiler.FindErrorPosition(
lineNum, 0, LineMap);
int scriptLine = pos.Key;
int col = pos.Value;
if (scriptLine == 0)
scriptLine++;
if (col == 0)
col++;
message = string.Format("Runtime error:\n" +
"({0}): {1}", scriptLine - 1,
e.InnerException.Message);
return message;
}
}
}
}
// m_log.ErrorFormat("Scripting exception:");
// m_log.ErrorFormat(e.ToString());
return e.ToString();
}
public string GetAssemblyName()
{
return m_Assembly;
}
public string GetXMLState()
{
bool run = Running;
Stop(100);
Running = run;
// We should not be doing this, but since we are about to
// dispose this, it really doesn't make a difference
// This is meant to work around a Windows only race
//
m_InEvent = false;
// Force an update of the in-memory plugin data
//
PluginData = AsyncCommandManager.GetSerializationData(Engine, ItemID);
return ScriptSerializer.Serialize(this);
}
public UUID RegionID
{
get { return m_RegionID; }
}
public void Suspend()
{
Suspended = true;
}
public void Resume()
{
Suspended = false;
}
}
/// <summary>
/// Xengine event wait handle.
/// </summary>
/// <remarks>
/// This class exists becase XEngineScriptBase gets a reference to this wait handle. We need to make sure that
/// when scripts are running in different AppDomains the lease does not expire.
/// FIXME: Like LSL_Api, etc., this effectively leaks memory since the GC will never collect it. To avoid this,
/// proper remoting sponsorship needs to be implemented across the board.
/// </remarks>
public class XEngineEventWaitHandle : EventWaitHandle
{
public XEngineEventWaitHandle(bool initialState, EventResetMode mode) : base(initialState, mode) {}
public override Object InitializeLifetimeService()
{
return null;
}
}
}
| |
using System;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor.Graphing.Util;
using UnityEditor.ShaderGraph;
using UnityEditor.ShaderGraph.Drawing;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEditor.Experimental.Rendering.HDPipeline;
using UnityEngine.Experimental.Rendering.HDPipeline;
namespace UnityEditor.Experimental.Rendering.HDPipeline.Drawing
{
class HDUnlitSettingsView : VisualElement
{
HDUnlitMasterNode m_Node;
IntegerField m_SortPiorityField;
Label CreateLabel(string text, int indentLevel)
{
string label = "";
for (var i = 0; i < indentLevel; i++)
{
label += " ";
}
return new Label(label + text);
}
public HDUnlitSettingsView(HDUnlitMasterNode node)
{
m_Node = node;
PropertySheet ps = new PropertySheet();
int indentLevel = 0;
ps.Add(new PropertyRow(CreateLabel("Surface Type", indentLevel)), (row) =>
{
row.Add(new EnumField(SurfaceType.Opaque), (field) =>
{
field.value = m_Node.surfaceType;
field.RegisterValueChangedCallback(ChangeSurfaceType);
});
});
++indentLevel;
switch (m_Node.surfaceType)
{
case SurfaceType.Opaque:
ps.Add(new PropertyRow(CreateLabel("Rendering Pass", indentLevel)), (row) =>
{
var valueList = HDSubShaderUtilities.GetRenderingPassList(true, true);
row.Add(new PopupField<HDRenderQueue.RenderQueueType>(valueList, HDRenderQueue.RenderQueueType.Opaque, HDSubShaderUtilities.RenderQueueName, HDSubShaderUtilities.RenderQueueName), (field) =>
{
field.value = HDRenderQueue.GetOpaqueEquivalent(m_Node.renderingPass);
field.RegisterValueChangedCallback(ChangeRenderingPass);
});
});
break;
case SurfaceType.Transparent:
ps.Add(new PropertyRow(CreateLabel("Rendering Pass", indentLevel)), (row) =>
{
Enum defaultValue;
switch (m_Node.renderingPass) // Migration
{
default: //when deserializing without issue, we still need to init the default to something even if not used.
case HDRenderQueue.RenderQueueType.Transparent:
defaultValue = HDRenderQueue.TransparentRenderQueue.Default;
break;
case HDRenderQueue.RenderQueueType.PreRefraction:
defaultValue = HDRenderQueue.TransparentRenderQueue.BeforeRefraction;
break;
}
var valueList = HDSubShaderUtilities.GetRenderingPassList(false, true);
row.Add(new PopupField<HDRenderQueue.RenderQueueType>(valueList, HDRenderQueue.RenderQueueType.Transparent, HDSubShaderUtilities.RenderQueueName, HDSubShaderUtilities.RenderQueueName), (field) =>
{
field.value = HDRenderQueue.GetTransparentEquivalent(m_Node.renderingPass);
field.RegisterValueChangedCallback(ChangeRenderingPass);
});
});
break;
default:
throw new ArgumentException("Unknown SurfaceType");
}
--indentLevel;
if (m_Node.surfaceType == SurfaceType.Transparent)
{
++indentLevel;
ps.Add(new PropertyRow(CreateLabel("Blending Mode", indentLevel)), (row) =>
{
row.Add(new EnumField(HDUnlitMasterNode.AlphaModeLit.Additive), (field) =>
{
field.value = GetAlphaModeLit(m_Node.alphaMode);
field.RegisterValueChangedCallback(ChangeBlendMode);
});
});
m_SortPiorityField = new IntegerField();
ps.Add(new PropertyRow(CreateLabel("Sorting Priority", indentLevel)), (row) =>
{
row.Add(m_SortPiorityField, (field) =>
{
field.value = m_Node.sortPriority;
field.RegisterValueChangedCallback(ChangeSortPriority);
});
});
ps.Add(new PropertyRow(CreateLabel("Receive Fog", indentLevel)), (row) =>
{
row.Add(new Toggle(), (toggle) =>
{
toggle.value = m_Node.transparencyFog.isOn;
toggle.OnToggleChanged(ChangeTransparencyFog);
});
});
ps.Add(new PropertyRow(CreateLabel("Distortion", indentLevel)), (row) =>
{
row.Add(new Toggle(), (toggle) =>
{
toggle.value = m_Node.distortion.isOn;
toggle.OnToggleChanged(ChangeDistortion);
});
});
if (m_Node.distortion.isOn)
{
++indentLevel;
ps.Add(new PropertyRow(CreateLabel("Mode", indentLevel)), (row) =>
{
row.Add(new EnumField(DistortionMode.Add), (field) =>
{
field.value = m_Node.distortionMode;
field.RegisterValueChangedCallback(ChangeDistortionMode);
});
});
ps.Add(new PropertyRow(CreateLabel("Distortion Only", indentLevel)), (row) =>
{
row.Add(new Toggle(), (toggle) =>
{
toggle.value = m_Node.distortionOnly.isOn;
toggle.OnToggleChanged(ChangeDistortionOnly);
});
});
ps.Add(new PropertyRow(CreateLabel("Depth Test", indentLevel)), (row) =>
{
row.Add(new Toggle(), (toggle) =>
{
toggle.value = m_Node.distortionDepthTest.isOn;
toggle.OnToggleChanged(ChangeDistortionDepthTest);
});
});
--indentLevel;
}
--indentLevel;
}
ps.Add(new PropertyRow(new Label("Double-Sided")), (row) =>
{
row.Add(new Toggle(), (toggle) =>
{
toggle.value = m_Node.doubleSided.isOn;
toggle.OnToggleChanged(ChangeDoubleSided);
});
});
ps.Add(new PropertyRow(CreateLabel("Alpha Clipping", indentLevel)), (row) =>
{
row.Add(new Toggle(), (toggle) =>
{
toggle.value = m_Node.alphaTest.isOn;
toggle.OnToggleChanged(ChangeAlphaTest);
});
});
Add(ps);
}
void ChangeSurfaceType(ChangeEvent<Enum> evt)
{
if (Equals(m_Node.surfaceType, evt.newValue))
return;
m_Node.owner.owner.RegisterCompleteObjectUndo("Surface Type Change");
m_Node.surfaceType = (SurfaceType)evt.newValue;
UpdateRenderingPassValue(m_Node.renderingPass);
}
void ChangeDoubleSided(ChangeEvent<bool> evt)
{
m_Node.owner.owner.RegisterCompleteObjectUndo("Double-Sided Change");
ToggleData td = m_Node.doubleSided;
td.isOn = evt.newValue;
m_Node.doubleSided = td;
}
void ChangeBlendMode(ChangeEvent<Enum> evt)
{
// Make sure the mapping is correct by handling each case.
AlphaMode alphaMode = GetAlphaMode((HDUnlitMasterNode.AlphaModeLit)evt.newValue);
if (Equals(m_Node.alphaMode, alphaMode))
return;
m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Mode Change");
m_Node.alphaMode = alphaMode;
}
void ChangeTransparencyFog(ChangeEvent<bool> evt)
{
m_Node.owner.owner.RegisterCompleteObjectUndo("Transparency Fog Change");
ToggleData td = m_Node.transparencyFog;
td.isOn = evt.newValue;
m_Node.transparencyFog = td;
}
void ChangeRenderingPass(ChangeEvent<HDRenderQueue.RenderQueueType> evt)
{
switch (evt.newValue)
{
case HDRenderQueue.RenderQueueType.Overlay:
case HDRenderQueue.RenderQueueType.Unknown:
case HDRenderQueue.RenderQueueType.Background:
throw new ArgumentException("Unexpected kind of RenderQueue, was " + evt.newValue);
default:
break;
};
UpdateRenderingPassValue(evt.newValue);
}
void UpdateRenderingPassValue(HDRenderQueue.RenderQueueType newValue)
{
HDRenderQueue.RenderQueueType renderingPass;
switch (m_Node.surfaceType)
{
case SurfaceType.Opaque:
renderingPass = HDRenderQueue.GetOpaqueEquivalent(newValue);
break;
case SurfaceType.Transparent:
renderingPass = HDRenderQueue.GetTransparentEquivalent(newValue);
break;
default:
throw new ArgumentException("Unknown SurfaceType");
}
if (Equals(m_Node.renderingPass, renderingPass))
return;
m_Node.owner.owner.RegisterCompleteObjectUndo("Rendering Pass Change");
m_Node.renderingPass = renderingPass;
}
void ChangeDistortion(ChangeEvent<bool> evt)
{
m_Node.owner.owner.RegisterCompleteObjectUndo("Distortion Change");
ToggleData td = m_Node.distortion;
td.isOn = evt.newValue;
m_Node.distortion = td;
}
void ChangeDistortionMode(ChangeEvent<Enum> evt)
{
if (Equals(m_Node.distortionMode, evt.newValue))
return;
m_Node.owner.owner.RegisterCompleteObjectUndo("Distortion Mode Change");
m_Node.distortionMode = (DistortionMode)evt.newValue;
}
void ChangeDistortionOnly(ChangeEvent<bool> evt)
{
m_Node.owner.owner.RegisterCompleteObjectUndo("Distortion Only Change");
ToggleData td = m_Node.distortionOnly;
td.isOn = evt.newValue;
m_Node.distortionDepthTest = td;
}
void ChangeDistortionDepthTest(ChangeEvent<bool> evt)
{
m_Node.owner.owner.RegisterCompleteObjectUndo("Distortion Depth Test Change");
ToggleData td = m_Node.distortionDepthTest;
td.isOn = evt.newValue;
m_Node.distortionDepthTest = td;
}
void ChangeSortPriority(ChangeEvent<int> evt)
{
m_Node.sortPriority = HDRenderQueue.ClampsTransparentRangePriority(evt.newValue);
// Force the text to match.
m_SortPiorityField.value = m_Node.sortPriority;
if (Equals(m_Node.sortPriority, evt.newValue))
return;
m_Node.owner.owner.RegisterCompleteObjectUndo("Sort Priority Change");
}
void ChangeAlphaTest(ChangeEvent<bool> evt)
{
m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Change");
ToggleData td = m_Node.alphaTest;
td.isOn = evt.newValue;
m_Node.alphaTest = td;
}
public AlphaMode GetAlphaMode(HDUnlitMasterNode.AlphaModeLit alphaModeLit)
{
switch (alphaModeLit)
{
case HDUnlitMasterNode.AlphaModeLit.Alpha:
return AlphaMode.Alpha;
case HDUnlitMasterNode.AlphaModeLit.Premultiply:
return AlphaMode.Premultiply;
case HDUnlitMasterNode.AlphaModeLit.Additive:
return AlphaMode.Additive;
default:
{
Debug.LogWarning("Not supported: " + alphaModeLit);
return AlphaMode.Alpha;
}
}
}
public HDUnlitMasterNode.AlphaModeLit GetAlphaModeLit(AlphaMode alphaMode)
{
switch (alphaMode)
{
case AlphaMode.Alpha:
return HDUnlitMasterNode.AlphaModeLit.Alpha;
case AlphaMode.Premultiply:
return HDUnlitMasterNode.AlphaModeLit.Premultiply;
case AlphaMode.Additive:
return HDUnlitMasterNode.AlphaModeLit.Additive;
default:
{
Debug.LogWarning("Not supported: " + alphaMode);
return HDUnlitMasterNode.AlphaModeLit.Alpha;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.Serialization;
namespace System.Collections.Generic
{
public partial class SortedSet<T>
{
/// <summary>
/// This class represents a subset view into the tree. Any changes to this view
/// are reflected in the actual tree. It uses the comparer of the underlying tree.
/// </summary>
internal sealed class TreeSubSet : SortedSet<T>, ISerializable, IDeserializationCallback
{
private SortedSet<T> _underlying;
private T _min, _max;
// keeps track of whether the count variable is up to date
// up to date -> _countVersion = _underlying.version
// not up to date -> _countVersion < _underlying.version
private int _countVersion;
// these exist for unbounded collections
// for instance, you could allow this subset to be defined for i > 10. The set will throw if
// anything <= 10 is added, but there is no upper bound. These features Head(), Tail(), were punted
// in the spec, and are not available, but the framework is there to make them available at some point.
private bool _lBoundActive, _uBoundActive;
// used to see if the count is out of date
#if DEBUG
internal override bool versionUpToDate()
{
return (version == _underlying.version);
}
#endif
public TreeSubSet(SortedSet<T> Underlying, T Min, T Max, bool lowerBoundActive, bool upperBoundActive)
: base(Underlying.Comparer)
{
_underlying = Underlying;
_min = Min;
_max = Max;
_lBoundActive = lowerBoundActive;
_uBoundActive = upperBoundActive;
root = _underlying.FindRange(_min, _max, _lBoundActive, _uBoundActive); // root is first element within range
count = 0;
version = -1;
_countVersion = -1;
}
internal override bool AddIfNotPresent(T item)
{
if (!IsWithinRange(item))
{
throw new ArgumentOutOfRangeException(nameof(item));
}
bool ret = _underlying.AddIfNotPresent(item);
VersionCheck();
#if DEBUG
Debug.Assert(this.versionUpToDate() && root == _underlying.FindRange(_min, _max));
#endif
return ret;
}
public override bool Contains(T item)
{
VersionCheck();
#if DEBUG
Debug.Assert(versionUpToDate() && root == _underlying.FindRange(_min, _max));
#endif
return base.Contains(item);
}
internal override bool DoRemove(T item)
{
if (!IsWithinRange(item))
{
return false;
}
bool ret = _underlying.Remove(item);
VersionCheck();
#if DEBUG
Debug.Assert(versionUpToDate() && root == _underlying.FindRange(_min, _max));
#endif
return ret;
}
public override void Clear()
{
if (Count == 0)
{
return;
}
List<T> toRemove = new List<T>();
BreadthFirstTreeWalk(n => { toRemove.Add(n.Item); return true; });
while (toRemove.Count != 0)
{
_underlying.Remove(toRemove[toRemove.Count - 1]);
toRemove.RemoveAt(toRemove.Count - 1);
}
root = null;
count = 0;
version = _underlying.version;
}
internal override bool IsWithinRange(T item)
{
int comp = _lBoundActive ? Comparer.Compare(_min, item) : -1;
if (comp > 0)
{
return false;
}
comp = _uBoundActive ? Comparer.Compare(_max, item) : 1;
return comp >= 0;
}
internal override T MinInternal
{
get
{
Node? current = root;
T result = default(T)!;
while (current != null)
{
int comp = _lBoundActive ? Comparer.Compare(_min, current.Item) : -1;
if (comp == 1)
{
current = current.Right;
}
else
{
result = current.Item;
if (comp == 0)
{
break;
}
current = current.Left;
}
}
return result;
}
}
internal override T MaxInternal
{
get
{
Node? current = root;
T result = default(T)!;
while (current != null)
{
int comp = _uBoundActive ? Comparer.Compare(_max, current.Item) : 1;
if (comp == -1)
{
current = current.Left;
}
else
{
result = current.Item;
if (comp == 0)
{
break;
}
current = current.Right;
}
}
return result;
}
}
internal override bool InOrderTreeWalk(TreeWalkPredicate<T> action)
{
VersionCheck();
if (root == null)
{
return true;
}
// The maximum height of a red-black tree is 2*lg(n+1).
// See page 264 of "Introduction to algorithms" by Thomas H. Cormen
Stack<Node> stack = new Stack<Node>(2 * (int)SortedSet<T>.Log2(count + 1)); // this is not exactly right if count is out of date, but the stack can grow
Node? current = root;
while (current != null)
{
if (IsWithinRange(current.Item))
{
stack.Push(current);
current = current.Left;
}
else if (_lBoundActive && Comparer.Compare(_min, current.Item) > 0)
{
current = current.Right;
}
else
{
current = current.Left;
}
}
while (stack.Count != 0)
{
current = stack.Pop();
if (!action(current))
{
return false;
}
Node? node = current.Right;
while (node != null)
{
if (IsWithinRange(node.Item))
{
stack.Push(node);
node = node.Left;
}
else if (_lBoundActive && Comparer.Compare(_min, node.Item) > 0)
{
node = node.Right;
}
else
{
node = node.Left;
}
}
}
return true;
}
internal override bool BreadthFirstTreeWalk(TreeWalkPredicate<T> action)
{
VersionCheck();
if (root == null)
{
return true;
}
Queue<Node> processQueue = new Queue<Node>();
processQueue.Enqueue(root);
Node current;
while (processQueue.Count != 0)
{
current = processQueue.Dequeue();
if (IsWithinRange(current.Item) && !action(current))
{
return false;
}
if (current.Left != null && (!_lBoundActive || Comparer.Compare(_min, current.Item) < 0))
{
processQueue.Enqueue(current.Left);
}
if (current.Right != null && (!_uBoundActive || Comparer.Compare(_max, current.Item) > 0))
{
processQueue.Enqueue(current.Right);
}
}
return true;
}
internal override SortedSet<T>.Node? FindNode(T item)
{
if (!IsWithinRange(item))
{
return null;
}
VersionCheck();
#if DEBUG
Debug.Assert(this.versionUpToDate() && root == _underlying.FindRange(_min, _max));
#endif
return base.FindNode(item);
}
// this does indexing in an inefficient way compared to the actual sortedset, but it saves a
// lot of space
internal override int InternalIndexOf(T item)
{
int count = -1;
foreach (T i in this)
{
count++;
if (Comparer.Compare(item, i) == 0)
return count;
}
#if DEBUG
Debug.Assert(this.versionUpToDate() && root == _underlying.FindRange(_min, _max));
#endif
return -1;
}
/// <summary>
/// Checks whether this subset is out of date, and updates it if necessary.
/// <param name="updateCount">Updates the count variable if necessary.</param>
/// </summary>
internal override void VersionCheck(bool updateCount = false) => VersionCheckImpl(updateCount);
private void VersionCheckImpl(bool updateCount)
{
Debug.Assert(_underlying != null);
if (version != _underlying.version)
{
root = _underlying.FindRange(_min, _max, _lBoundActive, _uBoundActive);
version = _underlying.version;
}
if (updateCount && _countVersion != _underlying.version)
{
count = 0;
InOrderTreeWalk(n => { count++; return true; });
_countVersion = _underlying.version;
}
}
/// <summary>
/// Returns the number of elements <c>count</c> of the parent set.
/// </summary>
internal override int TotalCount()
{
Debug.Assert(_underlying != null);
return _underlying.Count;
}
// This passes functionality down to the underlying tree, clipping edges if necessary
// There's nothing gained by having a nested subset. May as well draw it from the base
// Cannot increase the bounds of the subset, can only decrease it
public override SortedSet<T> GetViewBetween(T lowerValue, T upperValue)
{
if (_lBoundActive && Comparer.Compare(_min, lowerValue) > 0)
{
throw new ArgumentOutOfRangeException(nameof(lowerValue));
}
if (_uBoundActive && Comparer.Compare(_max, upperValue) < 0)
{
throw new ArgumentOutOfRangeException(nameof(upperValue));
}
return (TreeSubSet)_underlying.GetViewBetween(lowerValue, upperValue);
}
#if DEBUG
internal override void IntersectWithEnumerable(IEnumerable<T> other)
{
base.IntersectWithEnumerable(other);
Debug.Assert(versionUpToDate() && root == _underlying.FindRange(_min, _max));
}
#endif
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) => GetObjectData(info, context);
protected override void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
void IDeserializationCallback.OnDeserialization(object? sender)
{
throw new PlatformNotSupportedException();
}
protected override void OnDeserialization(object? sender) => throw new PlatformNotSupportedException();
}
}
}
| |
// 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.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Utilities;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal static class AnalyzerHelper
{
private const string CSharpCompilerAnalyzerTypeName = "Microsoft.CodeAnalysis.Diagnostics.CSharp.CSharpCompilerDiagnosticAnalyzer";
private const string VisualBasicCompilerAnalyzerTypeName = "Microsoft.CodeAnalysis.Diagnostics.VisualBasic.VisualBasicCompilerDiagnosticAnalyzer";
// These are the error codes of the compiler warnings.
// Keep the ids the same so that de-duplication against compiler errors
// works in the error list (after a build).
internal const string WRN_AnalyzerCannotBeCreatedIdCS = "CS8032";
internal const string WRN_AnalyzerCannotBeCreatedIdVB = "BC42376";
internal const string WRN_NoAnalyzerInAssemblyIdCS = "CS8033";
internal const string WRN_NoAnalyzerInAssemblyIdVB = "BC42377";
internal const string WRN_UnableToLoadAnalyzerIdCS = "CS8034";
internal const string WRN_UnableToLoadAnalyzerIdVB = "BC42378";
// Shared with Compiler
internal const string AnalyzerExceptionDiagnosticId = "AD0001";
internal const string AnalyzerDriverExceptionDiagnosticId = "AD0002";
// IDE only errors
internal const string WRN_AnalyzerCannotBeCreatedId = "AD1000";
internal const string WRN_NoAnalyzerInAssemblyId = "AD1001";
internal const string WRN_UnableToLoadAnalyzerId = "AD1002";
private const string AnalyzerExceptionDiagnosticCategory = "Intellisense";
public static bool IsWorkspaceDiagnosticAnalyzer(this DiagnosticAnalyzer analyzer)
{
return analyzer is DocumentDiagnosticAnalyzer || analyzer is ProjectDiagnosticAnalyzer;
}
public static bool IsBuiltInAnalyzer(this DiagnosticAnalyzer analyzer)
{
return analyzer is IBuiltInAnalyzer || analyzer.IsWorkspaceDiagnosticAnalyzer() || analyzer.IsCompilerAnalyzer();
}
public static bool IsOpenFileOnly(this DiagnosticAnalyzer analyzer, Workspace workspace)
{
var builtInAnalyzer = analyzer as IBuiltInAnalyzer;
if (builtInAnalyzer != null)
{
return builtInAnalyzer.OpenFileOnly(workspace);
}
return false;
}
public static bool ContainsOpenFileOnlyAnalyzers(this CompilationWithAnalyzers analyzerDriverOpt, Workspace workspace)
{
if (analyzerDriverOpt == null)
{
// not Roslyn. no open file only analyzers
return false;
}
foreach (var analyzer in analyzerDriverOpt.Analyzers)
{
if (analyzer.IsOpenFileOnly(workspace))
{
return true;
}
}
return false;
}
public static bool HasNonHiddenDescriptor(this DiagnosticAnalyzerService service, DiagnosticAnalyzer analyzer, Project project)
{
// most of analyzers, number of descriptor is quite small, so this should be cheap.
return service.GetDiagnosticDescriptors(analyzer).Any(d => d.GetEffectiveSeverity(project.CompilationOptions) != ReportDiagnostic.Hidden);
}
public static ReportDiagnostic GetEffectiveSeverity(this DiagnosticDescriptor descriptor, CompilationOptions options)
{
return options == null
? descriptor.DefaultSeverity.MapSeverityToReport()
: descriptor.GetEffectiveSeverity(options);
}
public static ReportDiagnostic MapSeverityToReport(this DiagnosticSeverity severity)
{
switch (severity)
{
case DiagnosticSeverity.Hidden:
return ReportDiagnostic.Hidden;
case DiagnosticSeverity.Info:
return ReportDiagnostic.Info;
case DiagnosticSeverity.Warning:
return ReportDiagnostic.Warn;
case DiagnosticSeverity.Error:
return ReportDiagnostic.Error;
default:
throw ExceptionUtilities.UnexpectedValue(severity);
}
}
public static bool IsCompilerAnalyzer(this DiagnosticAnalyzer analyzer)
{
// TODO: find better way.
var typeString = analyzer.GetType().ToString();
if (typeString == CSharpCompilerAnalyzerTypeName)
{
return true;
}
if (typeString == VisualBasicCompilerAnalyzerTypeName)
{
return true;
}
return false;
}
public static ValueTuple<string, VersionStamp> GetAnalyzerIdAndVersion(this DiagnosticAnalyzer analyzer)
{
// Get the unique ID for given diagnostic analyzer.
// note that we also put version stamp so that we can detect changed analyzer.
var typeInfo = analyzer.GetType().GetTypeInfo();
return ValueTuple.Create(analyzer.GetAnalyzerId(), GetAnalyzerVersion(CorLightup.Desktop.GetAssemblyLocation(typeInfo.Assembly)));
}
public static string GetAnalyzerAssemblyName(this DiagnosticAnalyzer analyzer)
{
var typeInfo = analyzer.GetType().GetTypeInfo();
return typeInfo.Assembly.GetName().Name;
}
public static Task<OptionSet> GetDocumentOptionSetAsync(this AnalyzerOptions analyzerOptions, SyntaxTree syntaxTree, CancellationToken cancellationToken)
{
var workspaceAnalyzerOptions = analyzerOptions as WorkspaceAnalyzerOptions;
if (workspaceAnalyzerOptions == null)
{
return SpecializedTasks.Default<OptionSet>();
}
return workspaceAnalyzerOptions.GetDocumentOptionSetAsync(syntaxTree, cancellationToken);
}
internal static void OnAnalyzerException_NoTelemetryLogging(
Exception ex,
DiagnosticAnalyzer analyzer,
Diagnostic diagnostic,
AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource,
ProjectId projectIdOpt)
{
if (diagnostic != null)
{
hostDiagnosticUpdateSource?.ReportAnalyzerDiagnostic(analyzer, diagnostic, hostDiagnosticUpdateSource?.Workspace, projectIdOpt);
}
if (IsBuiltInAnalyzer(analyzer))
{
FatalError.ReportWithoutCrashUnlessCanceled(ex);
}
}
internal static void OnAnalyzerExceptionForSupportedDiagnostics(DiagnosticAnalyzer analyzer, Exception exception, AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource)
{
if (exception is OperationCanceledException)
{
return;
}
var diagnostic = CreateAnalyzerExceptionDiagnostic(analyzer, exception);
OnAnalyzerException_NoTelemetryLogging(exception, analyzer, diagnostic, hostDiagnosticUpdateSource, projectIdOpt: null);
}
/// <summary>
/// Create a diagnostic for exception thrown by the given analyzer.
/// </summary>
/// <remarks>
/// Keep this method in sync with "AnalyzerExecutor.CreateAnalyzerExceptionDiagnostic".
/// </remarks>
internal static Diagnostic CreateAnalyzerExceptionDiagnostic(DiagnosticAnalyzer analyzer, Exception e)
{
var analyzerName = analyzer.ToString();
// TODO: It is not ideal to create a new descriptor per analyzer exception diagnostic instance.
// However, until we add a LongMessage field to the Diagnostic, we are forced to park the instance specific description onto the Descriptor's Description field.
// This requires us to create a new DiagnosticDescriptor instance per diagnostic instance.
var descriptor = new DiagnosticDescriptor(AnalyzerExceptionDiagnosticId,
title: FeaturesResources.User_Diagnostic_Analyzer_Failure,
messageFormat: FeaturesResources.Analyzer_0_threw_an_exception_of_type_1_with_message_2,
description: string.Format(FeaturesResources.Analyzer_0_threw_the_following_exception_colon_1, analyzerName, e.CreateDiagnosticDescription()),
category: AnalyzerExceptionDiagnosticCategory,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
customTags: WellKnownDiagnosticTags.AnalyzerException);
return Diagnostic.Create(descriptor, Location.None, analyzerName, e.GetType(), e.Message);
}
private static VersionStamp GetAnalyzerVersion(string path)
{
if (path == null || !File.Exists(path))
{
return VersionStamp.Default;
}
return VersionStamp.Create(File.GetLastWriteTimeUtc(path));
}
public static DiagnosticData CreateAnalyzerLoadFailureDiagnostic(string fullPath, AnalyzerLoadFailureEventArgs e)
{
return CreateAnalyzerLoadFailureDiagnostic(null, null, null, fullPath, e);
}
public static DiagnosticData CreateAnalyzerLoadFailureDiagnostic(
Workspace workspace, ProjectId projectId, string language, string fullPath, AnalyzerLoadFailureEventArgs e)
{
if (!TryGetErrorMessage(language, fullPath, e, out var id, out var message, out var messageFormat, out var description))
{
return null;
}
return new DiagnosticData(
id,
FeaturesResources.Roslyn_HostError,
message,
messageFormat,
severity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: description,
warningLevel: 0,
workspace: workspace,
projectId: projectId);
}
private static bool TryGetErrorMessage(
string language, string fullPath, AnalyzerLoadFailureEventArgs e,
out string id, out string message, out string messageFormat, out string description)
{
switch (e.ErrorCode)
{
case AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToLoadAnalyzer:
id = Choose(language, WRN_UnableToLoadAnalyzerId, WRN_UnableToLoadAnalyzerIdCS, WRN_UnableToLoadAnalyzerIdVB);
messageFormat = FeaturesResources.Unable_to_load_Analyzer_assembly_0_colon_1;
message = string.Format(FeaturesResources.Unable_to_load_Analyzer_assembly_0_colon_1, fullPath, e.Message);
description = e.Exception.CreateDiagnosticDescription();
break;
case AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer:
id = Choose(language, WRN_AnalyzerCannotBeCreatedId, WRN_AnalyzerCannotBeCreatedIdCS, WRN_AnalyzerCannotBeCreatedIdVB);
messageFormat = FeaturesResources.An_instance_of_analyzer_0_cannot_be_created_from_1_colon_2;
message = string.Format(FeaturesResources.An_instance_of_analyzer_0_cannot_be_created_from_1_colon_2, e.TypeName, fullPath, e.Message);
description = e.Exception.CreateDiagnosticDescription();
break;
case AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers:
id = Choose(language, WRN_NoAnalyzerInAssemblyId, WRN_NoAnalyzerInAssemblyIdCS, WRN_NoAnalyzerInAssemblyIdVB);
messageFormat = FeaturesResources.The_assembly_0_does_not_contain_any_analyzers;
message = string.Format(FeaturesResources.The_assembly_0_does_not_contain_any_analyzers, fullPath);
description = e.Exception.CreateDiagnosticDescription();
break;
case AnalyzerLoadFailureEventArgs.FailureErrorCode.None:
default:
id = string.Empty;
message = string.Empty;
messageFormat = string.Empty;
description = string.Empty;
return false;
}
return true;
}
private static string Choose(string language, string noLanguageMessage, string csharpMessage, string vbMessage)
{
if (language == null)
{
return noLanguageMessage;
}
return language == LanguageNames.CSharp ? csharpMessage : vbMessage;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using NodaTime;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Util;
namespace QuantConnect.Algorithm
{
public partial class QCAlgorithm
{
/// <summary>
/// Gets or sets the history provider for the algorithm
/// </summary>
public IHistoryProvider HistoryProvider
{
get;
set;
}
/// <summary>
/// Gets whether or not this algorithm is still warming up
/// </summary>
public bool IsWarmingUp
{
get;
private set;
}
/// <summary>
/// Sets the warm up period to the specified value
/// </summary>
/// <param name="timeSpan">The amount of time to warm up, this does not take into account market hours/weekends</param>
public void SetWarmup(TimeSpan timeSpan)
{
_warmupBarCount = null;
_warmupTimeSpan = timeSpan;
}
/// <summary>
/// Sets the warm up period to the specified value
/// </summary>
/// <param name="timeSpan">The amount of time to warm up, this does not take into account market hours/weekends</param>
public void SetWarmUp(TimeSpan timeSpan)
{
SetWarmup(timeSpan);
}
/// <summary>
/// Sets the warm up period by resolving a start date that would send that amount of data into
/// the algorithm. The highest (smallest) resolution in the securities collection will be used.
/// For example, if an algorithm has minute and daily data and 200 bars are requested, that would
/// use 200 minute bars.
/// </summary>
/// <param name="barCount">The number of data points requested for warm up</param>
public void SetWarmup(int barCount)
{
_warmupTimeSpan = null;
_warmupBarCount = barCount;
}
/// <summary>
/// Sets the warm up period by resolving a start date that would send that amount of data into
/// the algorithm. The highest (smallest) resolution in the securities collection will be used.
/// For example, if an algorithm has minute and daily data and 200 bars are requested, that would
/// use 200 minute bars.
/// </summary>
/// <param name="barCount">The number of data points requested for warm up</param>
public void SetWarmUp(int barCount)
{
SetWarmup(barCount);
}
/// <summary>
/// Sets <see cref="IAlgorithm.IsWarmingUp"/> to false to indicate this algorithm has finished its warm up
/// </summary>
public void SetFinishedWarmingUp()
{
IsWarmingUp = false;
}
/// <summary>
/// Gets the history requests required for provide warm up data for the algorithm
/// </summary>
/// <returns></returns>
public IEnumerable<HistoryRequest> GetWarmupHistoryRequests()
{
if (_warmupBarCount.HasValue)
{
return CreateBarCountHistoryRequests(Securities.Keys, _warmupBarCount.Value);
}
if (_warmupTimeSpan.HasValue)
{
var end = UtcTime.ConvertFromUtc(TimeZone);
return CreateDateRangeHistoryRequests(Securities.Keys, end - _warmupTimeSpan.Value, end);
}
// if not warmup requested return nothing
return Enumerable.Empty<HistoryRequest>();
}
/// <summary>
/// Get the history for all configured securities over the requested span.
/// This will use the resolution and other subscription settings for each security.
/// The symbols must exist in the Securities collection.
/// </summary>
/// <param name="span">The span over which to request data. This is a calendar span, so take into consideration weekends and such</param>
/// <param name="resolution">The resolution to request</param>
/// <returns>An enumerable of slice containing data over the most recent span for all configured securities</returns>
public IEnumerable<Slice> History(TimeSpan span, Resolution? resolution = null)
{
return History(Securities.Keys, Time - span, Time, resolution).Memoize();
}
/// <summary>
/// Get the history for all configured securities over the requested span.
/// This will use the resolution and other subscription settings for each security.
/// The symbols must exist in the Securities collection.
/// </summary>
/// <param name="periods">The number of bars to request</param>
/// <param name="resolution">The resolution to request</param>
/// <returns>An enumerable of slice containing data over the most recent span for all configured securities</returns>
public IEnumerable<Slice> History(int periods, Resolution? resolution = null)
{
return History(Securities.Keys, periods, resolution).Memoize();
}
/// <summary>
/// Gets the historical data for all symbols of the requested type over the requested span.
/// The symbol's configured values for resolution and fill forward behavior will be used
/// The symbols must exist in the Securities collection.
/// </summary>
/// <param name="span">The span over which to retrieve recent historical data</param>
/// <param name="resolution">The resolution to request</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
public IEnumerable<DataDictionary<T>> History<T>(TimeSpan span, Resolution? resolution = null)
where T : IBaseData
{
return History<T>(Securities.Keys, span, resolution).Memoize();
}
/// <summary>
/// Gets the historical data for the specified symbols over the requested span.
/// The symbols must exist in the Securities collection.
/// </summary>
/// <typeparam name="T">The data type of the symbols</typeparam>
/// <param name="symbols">The symbols to retrieve historical data for</param>
/// <param name="span">The span over which to retrieve recent historical data</param>
/// <param name="resolution">The resolution to request</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
public IEnumerable<DataDictionary<T>> History<T>(IEnumerable<Symbol> symbols, TimeSpan span, Resolution? resolution = null)
where T : IBaseData
{
return History<T>(symbols, Time - span, Time, resolution).Memoize();
}
/// <summary>
/// Gets the historical data for the specified symbols. The exact number of bars will be returned for
/// each symbol. This may result in some data start earlier/later than others due to when various
/// exchanges are open. The symbols must exist in the Securities collection.
/// </summary>
/// <typeparam name="T">The data type of the symbols</typeparam>
/// <param name="symbols">The symbols to retrieve historical data for</param>
/// <param name="periods">The number of bars to request</param>
/// <param name="resolution">The resolution to request</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
public IEnumerable<DataDictionary<T>> History<T>(IEnumerable<Symbol> symbols, int periods, Resolution? resolution = null)
where T : IBaseData
{
var requests = symbols.Select(x =>
{
var security = Securities[x];
var config = GetMatchingSubscription(security, typeof(T));
if (config == null) return null;
Resolution? res = resolution ?? security.Resolution;
var start = GetStartTimeAlgoTz(x, periods, resolution).ConvertToUtc(TimeZone);
return CreateHistoryRequest(security, config, start, UtcTime.RoundDown(res.Value.ToTimeSpan()), resolution);
});
return History(requests.Where(x => x != null)).Get<T>().Memoize();
}
/// <summary>
/// Gets the historical data for the specified symbols between the specified dates. The symbols must exist in the Securities collection.
/// </summary>
/// <typeparam name="T">The data type of the symbols</typeparam>
/// <param name="symbols">The symbols to retrieve historical data for</param>
/// <param name="start">The start time in the algorithm's time zone</param>
/// <param name="end">The end time in the algorithm's time zone</param>
/// <param name="resolution">The resolution to request</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
public IEnumerable<DataDictionary<T>> History<T>(IEnumerable<Symbol> symbols, DateTime start, DateTime end, Resolution? resolution = null)
where T : IBaseData
{
var requests = symbols.Select(x =>
{
var security = Securities[x];
var config = GetMatchingSubscription(security, typeof(T));
if (config == null) return null;
return CreateHistoryRequest(security, config, start, end, resolution);
});
return History(requests.Where(x => x != null)).Get<T>().Memoize();
}
/// <summary>
/// Gets the historical data for the specified symbol over the request span. The symbol must exist in the Securities collection.
/// </summary>
/// <typeparam name="T">The data type of the symbol</typeparam>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="span">The span over which to retrieve recent historical data</param>
/// <param name="resolution">The resolution to request</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
public IEnumerable<T> History<T>(Symbol symbol, TimeSpan span, Resolution? resolution = null)
where T : IBaseData
{
return History<T>(symbol, Time - span, Time, resolution).Memoize();
}
/// <summary>
/// Gets the historical data for the specified symbol. The exact number of bars will be returned.
/// The symbol must exist in the Securities collection.
/// </summary>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="periods">The number of bars to request</param>
/// <param name="resolution">The resolution to request</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
public IEnumerable<TradeBar> History(Symbol symbol, int periods, Resolution? resolution = null)
{
var security = Securities[symbol];
var start = GetStartTimeAlgoTz(symbol, periods, resolution);
var securityType = symbol.ID.SecurityType;
if (securityType == SecurityType.Forex || securityType == SecurityType.Cfd)
{
Error("Calling this method on a Forex or CFD security will return an empty result. Please use the generic version with QuoteBar type parameter.");
}
return History(new[] {symbol}, start, Time.RoundDown((resolution ?? security.Resolution).ToTimeSpan()), resolution).Get(symbol).Memoize();
}
/// <summary>
/// Gets the historical data for the specified symbol. The exact number of bars will be returned.
/// The symbol must exist in the Securities collection.
/// </summary>
/// <typeparam name="T">The data type of the symbol</typeparam>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="periods">The number of bars to request</param>
/// <param name="resolution">The resolution to request</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
public IEnumerable<T> History<T>(Symbol symbol, int periods, Resolution? resolution = null)
where T : IBaseData
{
if (resolution == Resolution.Tick) throw new ArgumentException("History functions that accept a 'periods' parameter can not be used with Resolution.Tick");
var security = Securities[symbol];
// verify the types match
var requestedType = typeof(T);
var config = GetMatchingSubscription(security, requestedType);
if (config == null)
{
var actualType = security.Subscriptions.Select(x => x.Type.Name).DefaultIfEmpty("[None]").FirstOrDefault();
throw new ArgumentException("The specified security is not of the requested type. Symbol: " + symbol.ToString() + " Requested Type: " + requestedType.Name + " Actual Type: " + actualType);
}
var start = GetStartTimeAlgoTz(symbol, periods, resolution);
return History<T>(symbol, start, Time.RoundDown((resolution ?? security.Resolution).ToTimeSpan()), resolution).Memoize();
}
/// <summary>
/// Gets the historical data for the specified symbol between the specified dates. The symbol must exist in the Securities collection.
/// </summary>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="start">The start time in the algorithm's time zone</param>
/// <param name="end">The end time in the algorithm's time zone</param>
/// <param name="resolution">The resolution to request</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
public IEnumerable<T> History<T>(Symbol symbol, DateTime start, DateTime end, Resolution? resolution = null)
where T : IBaseData
{
var security = Securities[symbol];
// verify the types match
var requestedType = typeof(T);
var config = GetMatchingSubscription(security, requestedType);
if (config == null)
{
var actualType = security.Subscriptions.Select(x => x.Type.Name).DefaultIfEmpty("[None]").FirstOrDefault();
throw new ArgumentException("The specified security is not of the requested type. Symbol: " + symbol.ToString() + " Requested Type: " + requestedType.Name + " Actual Type: " + actualType);
}
var request = CreateHistoryRequest(security, config, start, end, resolution);
return History(request).Get<T>(symbol).Memoize();
}
/// <summary>
/// Gets the historical data for the specified symbol over the request span. The symbol must exist in the Securities collection.
/// </summary>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="span">The span over which to retrieve recent historical data</param>
/// <param name="resolution">The resolution to request</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
public IEnumerable<TradeBar> History(Symbol symbol, TimeSpan span, Resolution? resolution = null)
{
var securityType = symbol.ID.SecurityType;
if (securityType == SecurityType.Forex || securityType == SecurityType.Cfd)
{
Error("Calling this method on a Forex or CFD security will return an empty result. Please use the generic version with QuoteBar type parameter.");
}
return History(new[] {symbol}, span, resolution).Get(symbol).Memoize();
}
/// <summary>
/// Gets the historical data for the specified symbol over the request span. The symbol must exist in the Securities collection.
/// </summary>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="start">The start time in the algorithm's time zone</param>
/// <param name="end">The end time in the algorithm's time zone</param>
/// <param name="resolution">The resolution to request</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
public IEnumerable<TradeBar> History(Symbol symbol, DateTime start, DateTime end, Resolution? resolution = null)
{
var securityType = symbol.ID.SecurityType;
if (securityType == SecurityType.Forex || securityType == SecurityType.Cfd)
{
Error("Calling this method on a Forex or CFD security will return an empty result. Please use the generic version with QuoteBar type parameter.");
}
return History(new[] {symbol}, start, end, resolution).Get(symbol).Memoize();
}
/// <summary>
/// Gets the historical data for the specified symbols over the requested span.
/// The symbol's configured values for resolution and fill forward behavior will be used
/// The symbols must exist in the Securities collection.
/// </summary>
/// <param name="symbols">The symbols to retrieve historical data for</param>
/// <param name="span">The span over which to retrieve recent historical data</param>
/// <param name="resolution">The resolution to request</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
public IEnumerable<Slice> History(IEnumerable<Symbol> symbols, TimeSpan span, Resolution? resolution = null)
{
return History(symbols, Time - span, Time, resolution).Memoize();
}
/// <summary>
/// Gets the historical data for the specified symbols. The exact number of bars will be returned for
/// each symbol. This may result in some data start earlier/later than others due to when various
/// exchanges are open. The symbols must exist in the Securities collection.
/// </summary>
/// <param name="symbols">The symbols to retrieve historical data for</param>
/// <param name="periods">The number of bars to request</param>
/// <param name="resolution">The resolution to request</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
public IEnumerable<Slice> History(IEnumerable<Symbol> symbols, int periods, Resolution? resolution = null)
{
if (resolution == Resolution.Tick) throw new ArgumentException("History functions that accept a 'periods' parameter can not be used with Resolution.Tick");
return History(CreateBarCountHistoryRequests(symbols, periods, resolution)).Memoize();
}
/// <summary>
/// Gets the historical data for the specified symbols between the specified dates. The symbols must exist in the Securities collection.
/// </summary>
/// <param name="symbols">The symbols to retrieve historical data for</param>
/// <param name="start">The start time in the algorithm's time zone</param>
/// <param name="end">The end time in the algorithm's time zone</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="fillForward">True to fill forward missing data, false otherwise</param>
/// <param name="extendedMarket">True to include extended market hours data, false otherwise</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
public IEnumerable<Slice> History(IEnumerable<Symbol> symbols, DateTime start, DateTime end, Resolution? resolution = null, bool? fillForward = null, bool? extendedMarket = null)
{
return History(CreateDateRangeHistoryRequests(symbols, start, end, resolution, fillForward, extendedMarket)).Memoize();
}
/// <summary>
/// Gets the start time required for the specified bar count in terms of the algorithm's time zone
/// </summary>
private DateTime GetStartTimeAlgoTz(Symbol symbol, int periods, Resolution? resolution = null)
{
var security = Securities[symbol];
var timeSpan = (resolution ?? security.Resolution).ToTimeSpan();
// make this a minimum of one second
timeSpan = timeSpan < QuantConnect.Time.OneSecond ? QuantConnect.Time.OneSecond : timeSpan;
var localStartTime = QuantConnect.Time.GetStartTimeForTradeBars(security.Exchange.Hours, UtcTime.ConvertFromUtc(security.Exchange.TimeZone), timeSpan, periods, security.IsExtendedMarketHours);
return localStartTime.ConvertTo(security.Exchange.TimeZone, TimeZone);
}
/// <summary>
/// Executes the specified history request
/// </summary>
/// <param name="request">the history request to execute</param>
/// <returns>An enumerable of slice satisfying the specified history request</returns>
public IEnumerable<Slice> History(HistoryRequest request)
{
return History(new[] {request}).Memoize();
}
/// <summary>
/// Executes the specified history requests
/// </summary>
/// <param name="requests">the history requests to execute</param>
/// <returns>An enumerable of slice satisfying the specified history request</returns>
public IEnumerable<Slice> History(IEnumerable<HistoryRequest> requests)
{
return History(requests, TimeZone).Memoize();
}
/// <summary>
/// Get the last known price using the history provider.
/// Useful for seeding securities with the correct price
/// </summary>
/// <param name="security"><see cref="Security"/> object for which to retrieve historical data</param>
/// <returns>A single <see cref="BaseData"/> object with the last known price</returns>
public BaseData GetLastKnownPrice(Security security)
{
if (security.Symbol.IsCanonical())
{
return null;
}
// For speed and memory usage, use Resolution.Minute as the minimum resolution
var resolution = (Resolution)Math.Max((int)Resolution.Minute, (int)security.Resolution);
var startTime = GetStartTimeAlgoTzForSecurity(security, 1, resolution);
var endTime = Time.RoundDown(resolution.ToTimeSpan());
// Get the config with the largest resolution
var subscriptionDataConfig = GetMatchingSubscription(security, typeof(BaseData));
var request = new HistoryRequest
{
StartTimeUtc = startTime.ConvertToUtc(_localTimeKeeper.TimeZone),
EndTimeUtc = endTime.ConvertToUtc(_localTimeKeeper.TimeZone),
DataType = subscriptionDataConfig != null ? subscriptionDataConfig.Type : typeof(TradeBar),
Resolution = resolution,
FillForwardResolution = resolution,
Symbol = security.Symbol,
ExchangeHours = security.Exchange.Hours
};
var history = History(new List<HistoryRequest> { request });
if (history.Any() && history.First().Values.Any())
{
return history.First().Values.First();
}
return null;
}
/// <summary>
/// Gets the start time required for the specified bar count for a security in terms of the algorithm's time zone
/// Used when the security has not yet been subscribed to
/// </summary>
private DateTime GetStartTimeAlgoTzForSecurity(Security security, int periods, Resolution? resolution = null)
{
var timeSpan = (resolution ?? security.Resolution).ToTimeSpan();
// make this a minimum of one second
timeSpan = timeSpan < QuantConnect.Time.OneSecond ? QuantConnect.Time.OneSecond : timeSpan;
var localStartTime = QuantConnect.Time.GetStartTimeForTradeBars(security.Exchange.Hours, UtcTime.ConvertFromUtc(security.Exchange.TimeZone), timeSpan, periods, security.IsExtendedMarketHours);
return localStartTime.ConvertTo(security.Exchange.TimeZone, TimeZone);
}
private IEnumerable<Slice> History(IEnumerable<HistoryRequest> requests, DateTimeZone timeZone)
{
var sentMessage = false;
var reqs = requests.ToList();
foreach (var request in reqs)
{
// prevent future requests
if (request.EndTimeUtc > UtcTime)
{
request.EndTimeUtc = UtcTime;
if (request.StartTimeUtc > request.EndTimeUtc)
{
request.StartTimeUtc = request.EndTimeUtc;
}
if (!sentMessage)
{
sentMessage = true;
Debug("Request for future history modified to end now.");
}
}
}
// filter out future data to prevent look ahead bias
return ((IAlgorithm) this).HistoryProvider.GetHistory(reqs, timeZone);
}
/// <summary>
/// Helper method to create history requests from a date range
/// </summary>
private IEnumerable<HistoryRequest> CreateDateRangeHistoryRequests(IEnumerable<Symbol> symbols, DateTime startAlgoTz, DateTime endAlgoTz, Resolution? resolution = null, bool? fillForward = null, bool? extendedMarket = null)
{
return symbols.Where(x => !x.IsCanonical()).Select(x =>
{
var security = Securities[x];
var config = GetMatchingSubscription(security, typeof (BaseData));
var request = CreateHistoryRequest(security, config, startAlgoTz, endAlgoTz, resolution);
// apply overrides
Resolution? res = resolution ?? security.Resolution;
if (fillForward.HasValue) request.FillForwardResolution = fillForward.Value ? res : null;
if (extendedMarket.HasValue) request.IncludeExtendedMarketHours = extendedMarket.Value;
return request;
});
}
/// <summary>
/// Helper methods to create a history request for the specified symbols and bar count
/// </summary>
private IEnumerable<HistoryRequest> CreateBarCountHistoryRequests(IEnumerable<Symbol> symbols, int periods, Resolution? resolution = null)
{
return symbols.Where(x => !x.IsCanonical()).Select(x =>
{
var security = Securities[x];
Resolution? res = resolution ?? security.Resolution;
var start = GetStartTimeAlgoTz(x, periods, res);
var config = GetMatchingSubscription(security, typeof(BaseData));
return CreateHistoryRequest(security, config, start, Time.RoundDown(res.Value.ToTimeSpan()), resolution);
});
}
private HistoryRequest CreateHistoryRequest(Security security, SubscriptionDataConfig subscription, DateTime startAlgoTz, DateTime endAlgoTz, Resolution? resolution)
{
resolution = resolution ?? security.Resolution;
// find the correct data type for the history request
var dataType = subscription.IsCustomData ? subscription.Type : LeanData.GetDataType(resolution.Value, subscription.TickType);
var request = new HistoryRequest(subscription, security.Exchange.Hours, startAlgoTz.ConvertToUtc(TimeZone), endAlgoTz.ConvertToUtc(TimeZone))
{
DataType = dataType,
Resolution = resolution.Value,
FillForwardResolution = subscription.FillDataForward ? resolution : null
};
return request;
}
private static SubscriptionDataConfig GetMatchingSubscription(Security security, Type type)
{
// find a subscription matchin the requested type with a higher resolution than requested
return (from sub in security.Subscriptions.OrderByDescending(s => s.Resolution)
where type.IsAssignableFrom(sub.Type)
select sub).FirstOrDefault();
}
}
}
| |
// 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 Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.NodejsTools.Project
{
/// <summary>
/// Merges the NTVS IVsCfg object with the Venus IVsCfg implementation redirecting
/// things appropriately to either one.
/// </summary>
internal class NodejsProjectConfig :
IVsCfg,
IVsProjectCfg,
IVsProjectCfg2,
IVsProjectFlavorCfg,
IVsDebuggableProjectCfg,
ISpecifyPropertyPages,
IVsSpecifyProjectDesignerPages,
IVsCfgBrowseObject
{
private readonly IVsCfg _innerNodeCfg;
private readonly IVsProjectFlavorCfg _webCfg;
public NodejsProjectConfig(IVsCfg pythonCfg, IVsProjectFlavorCfg webConfig)
{
this._innerNodeCfg = pythonCfg;
this._webCfg = webConfig;
}
#region IVsCfg Members
public int get_DisplayName(out string pbstrDisplayName)
{
return this._innerNodeCfg.get_DisplayName(out pbstrDisplayName);
}
public int get_IsDebugOnly(out int pfIsDebugOnly)
{
return this._innerNodeCfg.get_IsDebugOnly(out pfIsDebugOnly);
}
public int get_IsReleaseOnly(out int pfIsReleaseOnly)
{
return this._innerNodeCfg.get_IsReleaseOnly(out pfIsReleaseOnly);
}
#endregion
#region IVsProjectCfg Members
public int EnumOutputs(out IVsEnumOutputs ppIVsEnumOutputs)
{
if (this._webCfg is IVsProjectCfg projCfg)
{
return projCfg.EnumOutputs(out ppIVsEnumOutputs);
}
ppIVsEnumOutputs = null;
return VSConstants.E_NOTIMPL;
}
public int OpenOutput(string szOutputCanonicalName, out IVsOutput ppIVsOutput)
{
if (this._webCfg is IVsProjectCfg projCfg)
{
return projCfg.OpenOutput(szOutputCanonicalName, out ppIVsOutput);
}
ppIVsOutput = null;
return VSConstants.E_NOTIMPL;
}
public int get_BuildableProjectCfg(out IVsBuildableProjectCfg ppIVsBuildableProjectCfg)
{
if (this._webCfg is IVsProjectCfg projCfg)
{
return projCfg.get_BuildableProjectCfg(out ppIVsBuildableProjectCfg);
}
ppIVsBuildableProjectCfg = null;
return VSConstants.E_NOTIMPL;
}
public int get_CanonicalName(out string pbstrCanonicalName)
{
if (this._webCfg is IVsProjectCfg projCfg)
{
return projCfg.get_CanonicalName(out pbstrCanonicalName);
}
pbstrCanonicalName = null;
return VSConstants.E_NOTIMPL;
}
public int get_IsPackaged(out int pfIsPackaged)
{
if (this._webCfg is IVsProjectCfg projCfg)
{
return projCfg.get_IsPackaged(out pfIsPackaged);
}
pfIsPackaged = 0;
return VSConstants.E_NOTIMPL;
}
public int get_IsSpecifyingOutputSupported(out int pfIsSpecifyingOutputSupported)
{
if (this._webCfg is IVsProjectCfg projCfg)
{
return projCfg.get_IsSpecifyingOutputSupported(out pfIsSpecifyingOutputSupported);
}
pfIsSpecifyingOutputSupported = 0;
return VSConstants.E_NOTIMPL;
}
public int get_Platform(out Guid pguidPlatform)
{
if (this._webCfg is IVsProjectCfg projCfg)
{
return projCfg.get_Platform(out pguidPlatform);
}
pguidPlatform = Guid.Empty;
return VSConstants.E_NOTIMPL;
}
public int get_ProjectCfgProvider(out IVsProjectCfgProvider ppIVsProjectCfgProvider)
{
if (this._webCfg is IVsProjectCfg projCfg)
{
return projCfg.get_ProjectCfgProvider(out ppIVsProjectCfgProvider);
}
ppIVsProjectCfgProvider = null;
return VSConstants.E_NOTIMPL;
}
public int get_RootURL(out string pbstrRootURL)
{
if (this._webCfg is IVsProjectCfg projCfg)
{
return projCfg.get_RootURL(out pbstrRootURL);
}
pbstrRootURL = null;
return VSConstants.E_NOTIMPL;
}
public int get_TargetCodePage(out uint puiTargetCodePage)
{
if (this._webCfg is IVsProjectCfg projCfg)
{
return projCfg.get_TargetCodePage(out puiTargetCodePage);
}
puiTargetCodePage = 0;
return VSConstants.E_NOTIMPL;
}
public int get_UpdateSequenceNumber(ULARGE_INTEGER[] puliUSN)
{
if (this._webCfg is IVsProjectCfg projCfg)
{
return projCfg.get_UpdateSequenceNumber(puliUSN);
}
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsProjectCfg2 Members
public int OpenOutputGroup(string szCanonicalName, out IVsOutputGroup ppIVsOutputGroup)
{
if (this._innerNodeCfg is IVsProjectCfg2 projCfg)
{
return projCfg.OpenOutputGroup(szCanonicalName, out ppIVsOutputGroup);
}
ppIVsOutputGroup = null;
return VSConstants.E_NOTIMPL;
}
public int OutputsRequireAppRoot(out int pfRequiresAppRoot)
{
if (this._innerNodeCfg is IVsProjectCfg2 projCfg)
{
return projCfg.OutputsRequireAppRoot(out pfRequiresAppRoot);
}
pfRequiresAppRoot = 1;
return VSConstants.E_NOTIMPL;
}
public int get_CfgType(ref Guid iidCfg, out IntPtr ppCfg)
{
if (iidCfg == typeof(IVsDebuggableProjectCfg).GUID)
{
if (this._innerNodeCfg is IVsProjectFlavorCfg pyCfg)
{
return pyCfg.get_CfgType(ref iidCfg, out ppCfg);
}
}
if (this._webCfg is IVsProjectFlavorCfg projCfg)
{
return projCfg.get_CfgType(ref iidCfg, out ppCfg);
}
ppCfg = IntPtr.Zero;
return VSConstants.E_NOTIMPL;
}
public int get_IsPrivate(out int pfPrivate)
{
if (this._innerNodeCfg is IVsProjectCfg2 projCfg)
{
return projCfg.get_IsPrivate(out pfPrivate);
}
pfPrivate = 0;
return VSConstants.E_NOTIMPL;
}
public int get_OutputGroups(uint celt, IVsOutputGroup[] rgpcfg, uint[] pcActual = null)
{
if (this._innerNodeCfg is IVsProjectCfg2 projCfg)
{
return projCfg.get_OutputGroups(celt, rgpcfg, pcActual);
}
return VSConstants.E_NOTIMPL;
}
public int get_VirtualRoot(out string pbstrVRoot)
{
if (this._innerNodeCfg is IVsProjectCfg2 projCfg)
{
return projCfg.get_VirtualRoot(out pbstrVRoot);
}
pbstrVRoot = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsProjectFlavorCfg Members
public int Close()
{
if (this._webCfg is IVsProjectFlavorCfg cfg)
{
return cfg.Close();
}
return VSConstants.S_OK;
}
#endregion
#region IVsDebuggableProjectCfg Members
public int DebugLaunch(uint grfLaunch)
{
if (this._innerNodeCfg is IVsDebuggableProjectCfg cfg)
{
return cfg.DebugLaunch(grfLaunch);
}
return VSConstants.E_NOTIMPL;
}
public int QueryDebugLaunch(uint grfLaunch, out int pfCanLaunch)
{
if (this._innerNodeCfg is IVsDebuggableProjectCfg cfg)
{
return cfg.QueryDebugLaunch(grfLaunch, out pfCanLaunch);
}
pfCanLaunch = 0;
return VSConstants.E_NOTIMPL;
}
#endregion
#region ISpecifyPropertyPages Members
public void GetPages(CAUUID[] pPages)
{
if (this._innerNodeCfg is ISpecifyPropertyPages cfg)
{
cfg.GetPages(pPages);
}
}
#endregion
#region IVsSpecifyProjectDesignerPages Members
public int GetProjectDesignerPages(CAUUID[] pPages)
{
if (this._innerNodeCfg is IVsSpecifyProjectDesignerPages cfg)
{
return cfg.GetProjectDesignerPages(pPages);
}
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsCfgBrowseObject Members
public int GetCfg(out IVsCfg ppCfg)
{
ppCfg = this;
return VSConstants.S_OK;
}
public int GetProjectItem(out IVsHierarchy pHier, out uint pItemid)
{
if (this._innerNodeCfg is IVsCfgBrowseObject cfg)
{
return cfg.GetProjectItem(out pHier, out pItemid);
}
pHier = null;
pItemid = 0;
return VSConstants.E_NOTIMPL;
}
#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.IO;
using System.Net;
using System.Text;
using HttpServer;
namespace OpenSim.Framework.Servers.HttpServer
{
/// <summary>
/// OSHttpResponse is the OpenSim representation of an HTTP
/// response.
/// </summary>
public class OSHttpResponse : IOSHttpResponse
{
/// <summary>
/// Content type property.
/// </summary>
/// <remarks>
/// Setting this property will also set IsContentTypeSet to
/// true.
/// </remarks>
public virtual string ContentType
{
get
{
return _httpResponse.ContentType;
}
set
{
_httpResponse.ContentType = value;
}
}
/// <summary>
/// Boolean property indicating whether the content type
/// property actively has been set.
/// </summary>
/// <remarks>
/// IsContentTypeSet will go away together with .NET base.
/// </remarks>
// public bool IsContentTypeSet
// {
// get { return _contentTypeSet; }
// }
// private bool _contentTypeSet;
/// <summary>
/// Length of the body content; 0 if there is no body.
/// </summary>
public long ContentLength
{
get
{
return _httpResponse.ContentLength;
}
set
{
_httpResponse.ContentLength = value;
}
}
/// <summary>
/// Alias for ContentLength.
/// </summary>
public long ContentLength64
{
get { return ContentLength; }
set { ContentLength = value; }
}
/// <summary>
/// Encoding of the body content.
/// </summary>
public Encoding ContentEncoding
{
get
{
return _httpResponse.Encoding;
}
set
{
_httpResponse.Encoding = value;
}
}
public bool KeepAlive
{
get
{
return _httpResponse.Connection == ConnectionType.KeepAlive;
}
set
{
if (value)
_httpResponse.Connection = ConnectionType.KeepAlive;
else
_httpResponse.Connection = ConnectionType.Close;
}
}
/// <summary>
/// Get or set the keep alive timeout property (default is
/// 20). Setting this to 0 also disables KeepAlive. Setting
/// this to something else but 0 also enable KeepAlive.
/// </summary>
public int KeepAliveTimeout
{
get
{
return _httpResponse.KeepAlive;
}
set
{
if (value == 0)
{
_httpResponse.Connection = ConnectionType.Close;
_httpResponse.KeepAlive = 0;
}
else
{
_httpResponse.Connection = ConnectionType.KeepAlive;
_httpResponse.KeepAlive = value;
}
}
}
/// <summary>
/// Return the output stream feeding the body.
/// </summary>
/// <remarks>
/// On its way out...
/// </remarks>
public Stream OutputStream
{
get
{
return _httpResponse.Body;
}
}
public string ProtocolVersion
{
get
{
return _httpResponse.ProtocolVersion;
}
set
{
_httpResponse.ProtocolVersion = value;
}
}
/// <summary>
/// Return the output stream feeding the body.
/// </summary>
public Stream Body
{
get
{
return _httpResponse.Body;
}
}
/// <summary>
/// Set a redirct location.
/// </summary>
public string RedirectLocation
{
// get { return _redirectLocation; }
set
{
_httpResponse.Redirect(value);
}
}
/// <summary>
/// Chunk transfers.
/// </summary>
public bool SendChunked
{
get
{
return _httpResponse.Chunked;
}
set
{
_httpResponse.Chunked = value;
}
}
/// <summary>
/// HTTP status code.
/// </summary>
public virtual int StatusCode
{
get
{
return (int)_httpResponse.Status;
}
set
{
_httpResponse.Status = (HttpStatusCode)value;
}
}
/// <summary>
/// HTTP status description.
/// </summary>
public string StatusDescription
{
get
{
return _httpResponse.Reason;
}
set
{
_httpResponse.Reason = value;
}
}
public bool ReuseContext
{
get
{
if (_httpClientContext != null)
{
return !_httpClientContext.EndWhenDone;
}
return true;
}
set
{
if (_httpClientContext != null)
{
_httpClientContext.EndWhenDone = !value;
}
}
}
protected IHttpResponse _httpResponse;
private IHttpClientContext _httpClientContext;
public OSHttpResponse() {}
public OSHttpResponse(IHttpResponse resp)
{
_httpResponse = resp;
}
/// <summary>
/// Instantiate an OSHttpResponse object from an OSHttpRequest
/// object.
/// </summary
/// <param name="req">Incoming OSHttpRequest to which we are
/// replying</param>
public OSHttpResponse(OSHttpRequest req)
{
_httpResponse = new HttpResponse(req.IHttpClientContext, req.IHttpRequest);
_httpClientContext = req.IHttpClientContext;
}
public OSHttpResponse(HttpResponse resp, IHttpClientContext clientContext)
{
_httpResponse = resp;
_httpClientContext = clientContext;
}
/// <summary>
/// Add a header field and content to the response.
/// </summary>
/// <param name="key">string containing the header field
/// name</param>
/// <param name="value">string containing the header field
/// value</param>
public void AddHeader(string key, string value)
{
_httpResponse.AddHeader(key, value);
}
/// <summary>
/// Send the response back to the remote client
/// </summary>
public void Send()
{
_httpResponse.Body.Flush();
// disable this till they are safe to use
_httpResponse.Connection = ConnectionType.Close;
_httpResponse.Chunked = false;
_httpResponse.Send();
}
public void FreeContext()
{
if (_httpClientContext != null)
_httpClientContext.Close();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Xunit;
namespace Microsoft.AspNetCore.Razor.Runtime.TagHelpers
{
public class TagHelperScopeManagerTest
{
[Fact]
public void Begin_DoesNotRequireParentExecutionContext()
{
// Arrange & Act
var scopeManager = CreateDefaultScopeManager();
// Act
var executionContext = BeginDefaultScope(scopeManager, tagName: "p");
executionContext.Items["test-entry"] = 1234;
// Assert
var executionContextItem = Assert.Single(executionContext.Items);
Assert.Equal("test-entry", (string)executionContextItem.Key, StringComparer.Ordinal);
Assert.Equal(1234, executionContextItem.Value);
}
[Fact]
public void Begin_ReturnedExecutionContext_ItemsAreRetrievedFromParentExecutionContext()
{
// Arrange
var scopeManager = CreateDefaultScopeManager();
var parentExecutionContext = BeginDefaultScope(scopeManager, tagName: "p");
parentExecutionContext.Items["test-entry"] = 1234;
// Act
var executionContext = BeginDefaultScope(scopeManager, tagName: "p");
// Assert
var executionContextItem = Assert.Single(executionContext.Items);
Assert.Equal("test-entry", (string)executionContextItem.Key, StringComparer.Ordinal);
Assert.Equal(1234, executionContextItem.Value);
}
[Fact]
public void Begin_DoesShallowCopyOfParentItems()
{
// Arrange
var scopeManager = CreateDefaultScopeManager();
var parentComplexObject = new Dictionary<string, int>(StringComparer.Ordinal);
var parentExecutionContext = BeginDefaultScope(scopeManager, tagName: "p");
parentExecutionContext.Items["test-entry"] = parentComplexObject;
var executionContext = BeginDefaultScope(scopeManager, tagName: "p");
// Act
((Dictionary<string, int>)executionContext.Items["test-entry"]).Add("from-child", 1234);
// Assert
var executionContextItem = Assert.Single(executionContext.Items);
Assert.Equal("test-entry", (string)executionContextItem.Key, StringComparer.Ordinal);
Assert.Same(parentComplexObject, executionContextItem.Value);
var parentEntry = Assert.Single(parentComplexObject);
Assert.Equal("from-child", parentEntry.Key, StringComparer.Ordinal);
Assert.Equal(1234, parentEntry.Value);
}
[Fact]
public void Begin_ReturnedExecutionContext_ItemsModificationDoesNotAffectParent()
{
// Arrange
var scopeManager = CreateDefaultScopeManager();
var parentExecutionContext = BeginDefaultScope(scopeManager, tagName: "p");
parentExecutionContext.Items["test-entry"] = 1234;
var executionContext = BeginDefaultScope(scopeManager, tagName: "p");
// Act
executionContext.Items["test-entry"] = 2222;
// Assert
var executionContextItem = Assert.Single(executionContext.Items);
Assert.Equal("test-entry", (string)executionContextItem.Key, StringComparer.Ordinal);
Assert.Equal(2222, executionContextItem.Value);
var parentExecutionContextItem = Assert.Single(parentExecutionContext.Items);
Assert.Equal("test-entry", (string)parentExecutionContextItem.Key, StringComparer.Ordinal);
Assert.Equal(1234, parentExecutionContextItem.Value);
}
[Fact]
public void Begin_ReturnedExecutionContext_ItemsInsertionDoesNotAffectParent()
{
// Arrange
var scopeManager = CreateDefaultScopeManager();
var parentExecutionContext = BeginDefaultScope(scopeManager, tagName: "p");
var executionContext = BeginDefaultScope(scopeManager, tagName: "p");
// Act
executionContext.Items["new-entry"] = 2222;
// Assert
var executionContextItem = Assert.Single(executionContext.Items);
Assert.Equal("new-entry", (string)executionContextItem.Key, StringComparer.Ordinal);
Assert.Equal(2222, executionContextItem.Value);
Assert.Empty(parentExecutionContext.Items);
}
[Fact]
public void Begin_ReturnedExecutionContext_ItemsRemovalDoesNotAffectParent()
{
// Arrange
var scopeManager = CreateDefaultScopeManager();
var parentExecutionContext = BeginDefaultScope(scopeManager, tagName: "p");
parentExecutionContext.Items["test-entry"] = 1234;
var executionContext = BeginDefaultScope(scopeManager, tagName: "p");
// Act
executionContext.Items.Remove("test-entry");
// Assert
Assert.Empty(executionContext.Items);
var parentExecutionContextItem = Assert.Single(parentExecutionContext.Items);
Assert.Equal("test-entry", (string)parentExecutionContextItem.Key, StringComparer.Ordinal);
Assert.Equal(1234, parentExecutionContextItem.Value);
}
[Fact]
public void Begin_CreatesContexts_TagHelperOutput_WithAppropriateTagName()
{
// Arrange
var scopeManager = CreateDefaultScopeManager();
// Act
var executionContext = BeginDefaultScope(scopeManager, tagName: "p");
var output = executionContext.Output;
// Assert
Assert.Equal("p", output.TagName);
}
[Fact]
public void Begin_CanNest()
{
// Arrange
var scopeManager = CreateDefaultScopeManager();
// Act
var executionContext = BeginDefaultScope(scopeManager, tagName: "p");
executionContext = BeginDefaultScope(scopeManager, tagName: "div");
var output = executionContext.Output;
// Assert
Assert.Equal("div", output.TagName);
}
[Theory]
[InlineData(TagMode.SelfClosing)]
[InlineData(TagMode.StartTagAndEndTag)]
[InlineData(TagMode.StartTagOnly)]
public void Begin_SetsExecutionContexts_TagHelperOutputTagMode(TagMode tagMode)
{
// Arrange
var scopeManager = CreateDefaultScopeManager();
// Act
var executionContext = BeginDefaultScope(scopeManager, "p", tagMode);
var output = executionContext.Output;
// Assert
Assert.Equal(tagMode, output.TagMode);
}
[Fact]
public void End_ReturnsParentExecutionContext()
{
// Arrange
var scopeManager = CreateDefaultScopeManager();
// Act
var executionContext = BeginDefaultScope(scopeManager, tagName: "p");
executionContext = BeginDefaultScope(scopeManager, tagName: "div");
executionContext = scopeManager.End();
var output = executionContext.Output;
// Assert
Assert.Equal("p", output.TagName);
}
[Fact]
public void End_ReturnsNullIfNoNestedContext()
{
// Arrange
var scopeManager = CreateDefaultScopeManager();
// Act
var executionContext = BeginDefaultScope(scopeManager, tagName: "p");
executionContext = BeginDefaultScope(scopeManager, tagName: "div");
executionContext = scopeManager.End();
executionContext = scopeManager.End();
// Assert
Assert.Null(executionContext);
}
[Fact]
public void End_ThrowsIfNoScope()
{
// Arrange
var scopeManager = CreateDefaultScopeManager();
var expectedError = string.Format(
CultureInfo.CurrentCulture,
"Must call '{2}.{1}' before calling '{2}.{0}'.",
nameof(TagHelperScopeManager.End),
nameof(TagHelperScopeManager.Begin),
nameof(TagHelperScopeManager));
// Act & Assert
var ex = Assert.Throws<InvalidOperationException>(() =>
{
scopeManager.End();
});
Assert.Equal(expectedError, ex.Message);
}
private static TagHelperScopeManager CreateDefaultScopeManager()
{
return new TagHelperScopeManager(
startTagHelperWritingScope: _ => { },
endTagHelperWritingScope: () => new DefaultTagHelperContent());
}
private static TagHelperExecutionContext BeginDefaultScope(
TagHelperScopeManager scopeManager,
string tagName,
TagMode tagMode = TagMode.StartTagAndEndTag)
{
return scopeManager.Begin(
tagName,
tagMode,
uniqueId: string.Empty,
executeChildContentAsync: async () => await Task.FromResult(result: true));
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Tasks;
using Microsoft.Build.Utilities;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Build.UnitTests.GetSDKReferenceFiles_Tests
{
public class FakeSdkStructure : IDisposable
{
private readonly string _fakeSDKStructureRoot;
public string SdkDirectory { get; }
public string SdkDirectory2 { get; }
public FakeSdkStructure()
{
string sdkDirectory;
_fakeSDKStructureRoot = CreateFakeSDKReferenceAssemblyDirectory1(out sdkDirectory);
SdkDirectory = sdkDirectory;
string sdkDirectory2;
CreateFakeSDKReferenceAssemblyDirectory2(out sdkDirectory2);
SdkDirectory2 = sdkDirectory2;
}
public void Dispose()
{
if (FileUtilities.DirectoryExistsNoThrow(_fakeSDKStructureRoot))
{
FileUtilities.DeleteDirectoryNoThrow(_fakeSDKStructureRoot, true);
}
}
/// <summary>
/// Create a fake sdk structure on disk
/// </summary>
private static string CreateFakeSDKReferenceAssemblyDirectory1(out string sdkDirectory)
{
string testDirectoryRoot = Path.Combine(Path.GetTempPath(), "FakeSDKForReferenceAssemblies");
sdkDirectory = Path.Combine(testDirectoryRoot, "MyPlatform\\8.0\\ExtensionSDKs\\SDkWithManifest\\2.0\\");
string referenceAssemblyDirectoryConfigx86 = Path.Combine(sdkDirectory, "References\\Retail\\X86");
string referenceAssemblyDirectoryConfigx64 = Path.Combine(sdkDirectory, "References\\Retail\\X64");
string referenceAssemblyDirectoryConfigNeutral = Path.Combine(sdkDirectory, "References\\Retail\\Neutral");
string referenceAssemblyDirectoryCommonConfigNeutral = Path.Combine(sdkDirectory, "References\\CommonConfiguration\\Neutral");
string referenceAssemblyDirectoryCommonConfigX86 = Path.Combine(sdkDirectory, "References\\CommonConfiguration\\X86");
string referenceAssemblyDirectoryCommonConfigX64 = Path.Combine(sdkDirectory, "References\\CommonConfiguration\\X64");
string redistDirectoryConfigx86 = Path.Combine(sdkDirectory, "Redist\\Retail\\X86");
string redistDirectoryConfigx64 = Path.Combine(sdkDirectory, "Redist\\Retail\\X64");
string redistDirectoryConfigNeutral = Path.Combine(sdkDirectory, "Redist\\Retail\\Neutral");
string redistDirectoryCommonConfigNeutral = Path.Combine(sdkDirectory, "Redist\\CommonConfiguration\\Neutral");
string redistDirectoryCommonConfigX86 = Path.Combine(sdkDirectory, "Redist\\CommonConfiguration\\X86");
string redistDirectoryCommonConfigX64 = Path.Combine(sdkDirectory, "Redist\\CommonConfiguration\\X64");
string designTimeDirectoryConfigx86 = Path.Combine(sdkDirectory, "DesignTime\\Retail\\X86");
string designTimeDirectoryConfigNeutral = Path.Combine(sdkDirectory, "DesignTime\\Retail\\Neutral");
string designTimeDirectoryCommonConfigNeutral = Path.Combine(sdkDirectory, "DesignTime\\CommonConfiguration\\Neutral");
string designTimeDirectoryCommonConfigX86 = Path.Combine(sdkDirectory, "DesignTime\\CommonConfiguration\\X86");
Directory.CreateDirectory(testDirectoryRoot);
Directory.CreateDirectory(sdkDirectory);
Directory.CreateDirectory(referenceAssemblyDirectoryConfigx86);
Directory.CreateDirectory(referenceAssemblyDirectoryConfigx64);
Directory.CreateDirectory(referenceAssemblyDirectoryConfigNeutral);
Directory.CreateDirectory(referenceAssemblyDirectoryCommonConfigNeutral);
Directory.CreateDirectory(referenceAssemblyDirectoryCommonConfigX86);
Directory.CreateDirectory(referenceAssemblyDirectoryCommonConfigX64);
Directory.CreateDirectory(redistDirectoryConfigx86);
Directory.CreateDirectory(redistDirectoryConfigx64);
Directory.CreateDirectory(redistDirectoryConfigNeutral);
Directory.CreateDirectory(Path.Combine(redistDirectoryConfigNeutral, "ASubDirectory\\TwoDeep"));
Directory.CreateDirectory(redistDirectoryCommonConfigNeutral);
Directory.CreateDirectory(redistDirectoryCommonConfigX86);
Directory.CreateDirectory(redistDirectoryCommonConfigX64);
Directory.CreateDirectory(designTimeDirectoryConfigx86);
Directory.CreateDirectory(designTimeDirectoryConfigNeutral);
Directory.CreateDirectory(designTimeDirectoryCommonConfigNeutral);
Directory.CreateDirectory(designTimeDirectoryCommonConfigX86);
string testWinMD = Path.Combine(referenceAssemblyDirectoryConfigx86, "A.winmd");
string testWinMD64 = Path.Combine(referenceAssemblyDirectoryConfigx64, "A.winmd");
string testWinMDNeutral = Path.Combine(referenceAssemblyDirectoryConfigNeutral, "B.winmd");
string testWinMDNeutralWinXML = Path.Combine(referenceAssemblyDirectoryConfigNeutral, "B.xml");
string testWinMDCommonConfigurationx86 = Path.Combine(referenceAssemblyDirectoryCommonConfigX86, "C.winmd");
string testWinMDCommonConfigurationx64 = Path.Combine(referenceAssemblyDirectoryCommonConfigX64, "C.winmd");
string testWinMDCommonConfigurationNeutral = Path.Combine(referenceAssemblyDirectoryCommonConfigNeutral, "D.winmd");
string testWinMDCommonConfigurationNeutralDupe = Path.Combine(referenceAssemblyDirectoryCommonConfigNeutral, "A.winmd");
string testRA = Path.Combine(referenceAssemblyDirectoryConfigx86, "E.dll");
string testRA64 = Path.Combine(referenceAssemblyDirectoryConfigx64, "E.dll");
string testRANeutral = Path.Combine(referenceAssemblyDirectoryConfigNeutral, "F.dll");
string testRACommonConfigurationx86 = Path.Combine(referenceAssemblyDirectoryCommonConfigX86, "G.dll");
string testRACommonConfigurationx64 = Path.Combine(referenceAssemblyDirectoryCommonConfigX64, "G.dll");
string testRACommonConfigurationNeutral = Path.Combine(referenceAssemblyDirectoryCommonConfigNeutral, "H.dll");
// Make duplicate of winmd but change to dll extension so that we can make sure that we eliminate duplicate file names.
string testRACommonConfigurationNeutralDupe = Path.Combine(referenceAssemblyDirectoryCommonConfigNeutral, "A.dll");
string redist = Path.Combine(redistDirectoryConfigx86, "A.dll");
string redist64 = Path.Combine(redistDirectoryConfigx64, "A.dll");
string redistNeutral = Path.Combine(redistDirectoryConfigNeutral, "ASubDirectory\\TwoDeep\\B.dll");
string redistNeutralPri = Path.Combine(redistDirectoryConfigNeutral, "B.pri");
string redistCommonConfigurationx86 = Path.Combine(redistDirectoryCommonConfigX86, "C.dll");
string redistCommonConfigurationx64 = Path.Combine(redistDirectoryCommonConfigX64, "C.dll");
string redistCommonConfigurationNeutral = Path.Combine(redistDirectoryCommonConfigNeutral, "D.dll");
string redistCommonConfigurationNeutralDupe = Path.Combine(redistDirectoryCommonConfigNeutral, "A.dll");
File.WriteAllText(testWinMDNeutralWinXML, "TestXml");
File.WriteAllText(testWinMD, "TestWinmd");
File.WriteAllText(testWinMD64, "TestWinmd");
File.WriteAllText(testWinMDNeutral, "TestWinmd");
File.WriteAllText(testWinMDCommonConfigurationNeutral, "TestWinmd");
File.WriteAllText(testWinMDCommonConfigurationx86, "TestWinmd");
File.WriteAllText(testWinMDCommonConfigurationx64, "TestWinmd");
File.WriteAllText(testWinMDCommonConfigurationNeutralDupe, "TestWinmd");
File.WriteAllText(testRA, "TestWinmd");
File.WriteAllText(testRA64, "TestWinmd");
File.WriteAllText(testRANeutral, "TestWinmd");
File.WriteAllText(testRACommonConfigurationNeutral, "TestWinmd");
File.WriteAllText(testRACommonConfigurationx86, "TestWinmd");
File.WriteAllText(testRACommonConfigurationx64, "TestWinmd");
File.WriteAllText(testRACommonConfigurationNeutralDupe, "TestWinmd");
File.WriteAllText(redist, "TestWinmd");
File.WriteAllText(redist64, "TestWinmd");
File.WriteAllText(redistNeutral, "TestWinmd");
File.WriteAllText(redistNeutralPri, "TestWinmd");
File.WriteAllText(redistCommonConfigurationNeutral, "TestWinmd");
File.WriteAllText(redistCommonConfigurationx86, "TestWinmd");
File.WriteAllText(redistCommonConfigurationx64, "TestWinmd");
File.WriteAllText(redistCommonConfigurationNeutralDupe, "TestWinmd");
return testDirectoryRoot;
}
/// <summary>
/// Create a fake sdk structure on disk
/// </summary>
private static string CreateFakeSDKReferenceAssemblyDirectory2(out string sdkDirectory)
{
string testDirectoryRoot = Path.Combine(Path.GetTempPath(), "FakeSDKForReferenceAssemblies");
sdkDirectory = Path.Combine(testDirectoryRoot, "MyPlatform\\8.0\\ExtensionSDKs\\AnotherSDK\\2.0\\");
string referenceAssemblyDirectoryConfigx86 = Path.Combine(sdkDirectory, "References\\Retail\\X86");
string redistDirectoryConfigx86 = Path.Combine(sdkDirectory, "Redist\\Retail\\X86");
Directory.CreateDirectory(testDirectoryRoot);
Directory.CreateDirectory(sdkDirectory);
Directory.CreateDirectory(referenceAssemblyDirectoryConfigx86);
Directory.CreateDirectory(redistDirectoryConfigx86);
string testWinMD = Path.Combine(referenceAssemblyDirectoryConfigx86, "B.winmd");
string redist = Path.Combine(redistDirectoryConfigx86, "B.pri");
string redist2 = Path.Combine(redistDirectoryConfigx86, "B.dll");
File.WriteAllText(testWinMD, "TestWinmd");
File.WriteAllText(redist, "TestWinmd");
File.WriteAllText(redist2, "TestWinmd");
return testDirectoryRoot;
}
}
/// <summary>
/// Test the expansion of sdk reference assemblies.
/// </summary>
public class GetSDKReferenceFilesTestFixture : IDisposable, IClassFixture<FakeSdkStructure>
{
private readonly ITestOutputHelper _output;
private readonly string _sdkDirectory;
private readonly string _sdkDirectory2;
private readonly MockEngine.GetStringDelegate _resourceDelegate;
private readonly GetAssemblyName _getAssemblyName = GetAssemblyName;
private readonly GetAssemblyRuntimeVersion _getAssemblyRuntimeVersion = GetImageRuntimeVersion;
private readonly string _cacheDirectory = Path.Combine(Path.GetTempPath(), "GetSDKReferenceFiles");
public GetSDKReferenceFilesTestFixture(FakeSdkStructure fakeSdkStructure, ITestOutputHelper output)
{
_output = output;
_sdkDirectory = fakeSdkStructure.SdkDirectory;
_sdkDirectory2 = fakeSdkStructure.SdkDirectory2;
_resourceDelegate = AssemblyResources.GetString;
if (FileUtilities.DirectoryExistsNoThrow(_cacheDirectory))
{
_output.WriteLine($"Found existing cache directory {_cacheDirectory}; deleting it.");
FileUtilities.DeleteDirectoryNoThrow(_cacheDirectory, true);
}
Directory.CreateDirectory(_cacheDirectory);
_output.WriteLine($"Created cache directory {_cacheDirectory}.");
}
public void Dispose()
{
if (FileUtilities.DirectoryExistsNoThrow(_cacheDirectory))
{
_output.WriteLine($"Deleting cache directory {_cacheDirectory}.");
FileUtilities.DeleteDirectoryNoThrow(_cacheDirectory, true);
}
}
/// <summary>
/// Make sure there are no outputs if no resolved sdk files are passed in.
/// </summary>
[Fact]
public void PassReferenceWithNoReferenceDirectory()
{
var engine = new MockEngine(_output);
ITaskItem item = new TaskItem("C:\\SDKDoesNotExist");
item.SetMetadata("ExpandReferenceAssemblies", "true");
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x86");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
var t = new GetSDKReferenceFiles
{
BuildEngine = engine,
ResolvedSDKReferences = new ITaskItem[] { item },
CacheFileFolderPath = _cacheDirectory,
};
t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true).ShouldBeTrue();
t.CopyLocalFiles.ShouldBeEmpty();
t.References.ShouldBeEmpty();
t.RedistFiles.ShouldBeEmpty();
}
private delegate IList<string> GetSDKFolders(string sdkRoot);
private delegate IList<string> GetSDKFolders2(string sdkRoot, string configuration, string architecture);
/// <summary>
/// Make sure we get the correct folder list when asking for it.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void GetSDKReferenceFolders()
{
var getReferenceFolders = new GetSDKFolders(ToolLocationHelper.GetSDKReferenceFolders);
var getReferenceFolders2 = new GetSDKFolders2(ToolLocationHelper.GetSDKReferenceFolders);
VerifySDKFolders(getReferenceFolders, getReferenceFolders2, "References", _sdkDirectory);
}
[Fact]
public void VerifyGetSdkReferenceTranslator()
{
Dictionary<string, GetSDKReferenceFiles.SdkReferenceInfo> pathToReferenceMetadata = new();
pathToReferenceMetadata.Add("first", new("dat", "dat2", true, false));
pathToReferenceMetadata.Add("second", new("inf", "inf2", false, false));
Dictionary<string, List<string>> directoryToFileList = new();
directoryToFileList.Add("third", new List<string>() { "a", "b", "c" });
directoryToFileList.Add("fourth", new List<string>() { "1", "2", "3" });
GetSDKReferenceFiles.SDKInfo writeInfo = new(pathToReferenceMetadata, directoryToFileList, 47);
GetSDKReferenceFiles.SaveContext contextWriter = new("d", "n", writeInfo);
GetSDKReferenceFiles.SDKInfo readInfo = null;
using (TestEnvironment env = TestEnvironment.Create())
{
TransientTestFolder folder = env.CreateFolder();
GetSDKReferenceFiles.SDKFilesCache cache = new(null, folder.Path, null, null, null);
cache.SaveAssemblyListToCacheFile(contextWriter);
GetSDKReferenceFiles.SDKFilesCache cache2 = new(null, folder.Path, null, null, null);
readInfo = cache2.LoadAssemblyListFromCacheFile("d", "n");
}
readInfo.DirectoryToFileList.Count.ShouldBe(2);
readInfo.DirectoryToFileList["fourth"].Count.ShouldBe(3);
readInfo.DirectoryToFileList["fourth"][1].ShouldBe("2");
readInfo.DirectoryToFileList["third"][0].ShouldBe("a");
readInfo.Hash.ShouldBe(47);
readInfo.PathToReferenceMetadata.Count.ShouldBe(2);
readInfo.PathToReferenceMetadata["first"].FusionName.ShouldBe("dat");
readInfo.PathToReferenceMetadata["first"].IsManagedWinmd.ShouldBeFalse();
readInfo.PathToReferenceMetadata["first"].IsWinMD.ShouldBeTrue();
readInfo.PathToReferenceMetadata["second"].ImageRuntime.ShouldBe("inf2");
}
private static void VerifySDKFolders(GetSDKFolders singleParamDelegate, GetSDKFolders2 multiParamDelegate, string folderName, string sdkDirectory)
{
IList<string> sdkFolders = singleParamDelegate(sdkDirectory);
Assert.Equal(2, sdkFolders.Count);
Assert.Equal(Path.Combine(sdkDirectory, folderName + "\\Retail\\Neutral\\"), sdkFolders[0]);
Assert.Equal(Path.Combine(sdkDirectory, folderName + "\\CommonConfiguration\\Neutral\\"), sdkFolders[1]);
sdkFolders = multiParamDelegate(sdkDirectory, "Retail", "Neutral");
Assert.Equal(2, sdkFolders.Count);
Assert.Equal(Path.Combine(sdkDirectory, folderName + "\\Retail\\Neutral\\"), sdkFolders[0]);
Assert.Equal(Path.Combine(sdkDirectory, folderName + "\\CommonConfiguration\\Neutral\\"), sdkFolders[1]);
sdkFolders = multiParamDelegate(sdkDirectory, "Retail", "X86");
Assert.Equal(4, sdkFolders.Count);
Assert.Equal(Path.Combine(sdkDirectory, folderName + "\\Retail\\X86\\"), sdkFolders[0]);
Assert.Equal(Path.Combine(sdkDirectory, folderName + "\\Retail\\Neutral\\"), sdkFolders[1]);
Assert.Equal(Path.Combine(sdkDirectory, folderName + "\\CommonConfiguration\\X86\\"), sdkFolders[2]);
Assert.Equal(Path.Combine(sdkDirectory, folderName + "\\CommonConfiguration\\Neutral\\"), sdkFolders[3]);
}
/// <summary>
/// Make sure we get the correct folder list when asking for it.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void GetSDKRedistFolders()
{
var getRedistFolders = new GetSDKFolders(ToolLocationHelper.GetSDKRedistFolders);
var getRedistFolders2 = new GetSDKFolders2(ToolLocationHelper.GetSDKRedistFolders);
VerifySDKFolders(getRedistFolders, getRedistFolders2, "Redist", _sdkDirectory);
}
/// <summary>
/// Make sure we get the correct folder list when asking for it.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void GetSDKDesignTimeFolders()
{
var getDesignTimeFolders = new GetSDKFolders(ToolLocationHelper.GetSDKDesignTimeFolders);
var getDesignTimeFolders2 = new GetSDKFolders2(ToolLocationHelper.GetSDKDesignTimeFolders);
VerifySDKFolders(getDesignTimeFolders, getDesignTimeFolders2, "DesignTime", _sdkDirectory);
}
/// <summary>
/// Make sure there are no outputs if an sdk which does not exist is passed in.
/// </summary>
[Fact]
public void PassNoSDKReferences()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Empty(t.CopyLocalFiles);
Assert.Empty(t.References);
Assert.Empty(t.RedistFiles);
}
/// <summary>
/// Make sure there are no outputs if expand sdks is not true.
/// </summary>
[Fact]
public void PassReferenceWithExpandFalse()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "false");
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x86");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Empty(t.CopyLocalFiles);
Assert.Empty(t.References);
Assert.Empty(t.RedistFiles);
}
/// <summary>
/// Make sure there are no redist outputs if CopyRedist is false
/// </summary>
[Fact]
public void PassReferenceWithCopyRedistFalse()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x86");
item.SetMetadata("ExpandReferenceAssemblies", "false");
item.SetMetadata("CopyRedist", "false");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Empty(t.CopyLocalFiles);
Assert.Empty(t.References);
Assert.Empty(t.RedistFiles);
}
/// <summary>
/// Verify we get the correct set of reference assemblies and copy local files when the CopyLocal flag is true
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void GetReferenceAssembliesWhenExpandTrueCopyLocalTrue()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "true");
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x86");
item.SetMetadata("CopyLocalExpandedReferenceAssemblies", "true");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Equal(9, t.CopyLocalFiles.Length);
Assert.Equal(8, t.References.Length);
string winmd = Path.Combine(_sdkDirectory, "References\\Retail\\X86\\A.winmd");
Assert.Equal(winmd, t.References[0].ItemSpec, true);
Assert.Equal("A.winmd", Path.GetFileName(t.References[0].ItemSpec), true);
Assert.Equal("WindowsRuntime 1.0;CLR V2.0.50727", t.References[0].GetMetadata("ImageRuntime"), true);
Assert.Equal("A, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=null", t.References[0].GetMetadata("FusionName"), true);
Assert.Equal("true", t.References[0].GetMetadata("WinMDFile"), true);
Assert.Equal("Managed", t.References[0].GetMetadata("WinMDFileType"), true);
Assert.Equal("true", t.References[0].GetMetadata("CopyLocal"), true);
Assert.Equal("SDkWithManifest, Version=2.0", t.References[0].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.References[0].GetMetadata("ResolvedFrom"), true);
Assert.Equal("E.dll", Path.GetFileName(t.References[4].ItemSpec), true);
Assert.Equal("CLR V2.0.50727", t.References[4].GetMetadata("ImageRuntime"), true);
Assert.Equal("E, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=null", t.References[4].GetMetadata("FusionName"), true);
Assert.Equal("false", t.References[4].GetMetadata("WinMDFile"), true);
Assert.Empty(t.References[4].GetMetadata("WinMDFileType"));
Assert.Equal("true", t.References[4].GetMetadata("CopyLocal"), true);
Assert.Equal("SDkWithManifest, Version=2.0", t.References[4].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.References[4].GetMetadata("ResolvedFrom"), true);
Assert.Equal("A.winmd", Path.GetFileName(t.CopyLocalFiles[0].ItemSpec), true);
Assert.Equal("WindowsRuntime 1.0;CLR V2.0.50727", t.CopyLocalFiles[0].GetMetadata("ImageRuntime"), true);
Assert.Equal("A, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=null", t.CopyLocalFiles[0].GetMetadata("FusionName"), true);
Assert.Equal("true", t.CopyLocalFiles[0].GetMetadata("WinMDFile"), true);
Assert.Equal("Managed", t.CopyLocalFiles[0].GetMetadata("WinMDFileType"), true);
Assert.Equal("true", t.CopyLocalFiles[0].GetMetadata("CopyLocal"), true);
Assert.Equal("SDkWithManifest, Version=2.0", t.CopyLocalFiles[0].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.CopyLocalFiles[0].GetMetadata("ResolvedFrom"), true);
Assert.Equal("E.dll", Path.GetFileName(t.CopyLocalFiles[5].ItemSpec), true);
Assert.Equal("CLR V2.0.50727", t.CopyLocalFiles[5].GetMetadata("ImageRuntime"), true);
Assert.Equal("E, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=null", t.CopyLocalFiles[5].GetMetadata("FusionName"), true);
Assert.Equal("false", t.CopyLocalFiles[5].GetMetadata("WinMDFile"), true);
Assert.Empty(t.CopyLocalFiles[5].GetMetadata("WinMDFileType"));
Assert.Equal("true", t.CopyLocalFiles[5].GetMetadata("CopyLocal"), true);
Assert.Equal("SDkWithManifest, Version=2.0", t.CopyLocalFiles[5].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.CopyLocalFiles[5].GetMetadata("ResolvedFrom"), true);
Assert.Equal("B.xml", Path.GetFileName(t.CopyLocalFiles[2].ItemSpec));
}
/// <summary>
/// Verify reference is not processed by GetSDKReferenceFiles when "ReferenceOnly" metadata is set.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void VerifyNoCopyWhenReferenceOnlyIsTrue()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item1 = new TaskItem(_sdkDirectory);
item1.SetMetadata("ExpandReferenceAssemblies", "true");
item1.SetMetadata("TargetedSDKConfiguration", "Retail");
item1.SetMetadata("TargetedSDKArchitecture", "x86");
item1.SetMetadata("CopyLocalExpandedReferenceAssemblies", "false");
item1.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
ITaskItem item2 = new TaskItem(_sdkDirectory);
item2.SetMetadata("ExpandReferenceAssemblies", "true");
item2.SetMetadata("TargetedSDKConfiguration", "Retail");
item2.SetMetadata("TargetedSDKArchitecture", "x86");
item2.SetMetadata("CopyLocalExpandedReferenceAssemblies", "false");
item2.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
item2.SetMetadata("RuntimeReferenceOnly", "true");
// Process both regular and runtime-only references
t.ResolvedSDKReferences = new ITaskItem[] { item1, item2 };
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Equal(8, t.References.Length);
// Process regular references
t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
t.ResolvedSDKReferences = new ITaskItem[] { item1 };
success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Equal(8, t.References.Length);
// Process runtime-only references
t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
t.ResolvedSDKReferences = new ITaskItem[] { item2 };
success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Empty(t.References);
}
/// <summary>
/// Verify we get the correct set of reference assemblies and copy local files when the CopyLocal flag is false
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
[Trait("Category", "mono-windows-failing")]
public void GetReferenceAssembliesWhenExpandTrueCopyLocalFalse()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles
{
BuildEngine = engine,
CacheFileFolderPath = _cacheDirectory
};
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "true");
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x86");
item.SetMetadata("CopyLocalExpandedReferenceAssemblies", "false");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Empty(t.CopyLocalFiles);
Assert.Equal(8, t.References.Length);
Assert.Equal("A.winmd", Path.GetFileName(t.References[0].ItemSpec), true);
Assert.Equal("WindowsRuntime 1.0;CLR V2.0.50727", t.References[0].GetMetadata("ImageRuntime"), true);
Assert.Equal("A, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=null", t.References[0].GetMetadata("FusionName"), true);
Assert.Equal("true", t.References[0].GetMetadata("WinMDFile"), true);
Assert.Equal("Managed", t.References[0].GetMetadata("WinMDFileType"), true);
Assert.Equal("false", t.References[0].GetMetadata("CopyLocal"), true);
Assert.Equal("SDkWithManifest, Version=2.0", t.References[0].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.References[0].GetMetadata("ResolvedFrom"), true);
Assert.Equal("B.winmd", Path.GetFileName(t.References[1].ItemSpec), true);
Assert.Equal("WindowsRuntime 1.0", t.References[1].GetMetadata("ImageRuntime"), true);
Assert.Equal("B, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=null", t.References[1].GetMetadata("FusionName"), true);
Assert.Equal("true", t.References[1].GetMetadata("WinMDFile"), true);
Assert.Equal("Native", t.References[1].GetMetadata("WinMDFileType"), true);
Assert.Equal("false", t.References[1].GetMetadata("CopyLocal"), true);
Assert.Equal("SDkWithManifest, Version=2.0", t.References[1].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.References[1].GetMetadata("ResolvedFrom"), true);
Assert.Equal("E.dll", Path.GetFileName(t.References[4].ItemSpec), true);
Assert.Equal("CLR V2.0.50727", t.References[4].GetMetadata("ImageRuntime"), true);
Assert.Equal("E, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=null", t.References[4].GetMetadata("FusionName"), true);
Assert.Equal("false", t.References[4].GetMetadata("WinMDFile"), true);
Assert.Empty(t.References[4].GetMetadata("WinMDFileType"));
Assert.Equal("false", t.References[4].GetMetadata("CopyLocal"), true);
Assert.Equal("SDkWithManifest, Version=2.0", t.References[4].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.References[4].GetMetadata("ResolvedFrom"), true);
}
/// <summary>
/// Verify that different cache files are created and used correctly for assemblies with the same identity but with files in different directories
/// Also verifies that when
/// </summary>
[Fact]
public void VerifyCacheFileNames()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "true");
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x86");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
ITaskItem[] references1 = t.References;
// Verify the task created a cache file
string sdkIdentity = item.GetMetadata("OriginalItemSpec");
string sdkRoot = item.ItemSpec;
string cacheFile = sdkIdentity + ",Set=" + FileUtilities.GetHexHash(sdkIdentity) + "-" + FileUtilities.GetHexHash(sdkRoot) + ",Hash=*.dat";
Thread.Sleep(100);
string[] existingCacheFiles = Directory.GetFiles(_cacheDirectory, cacheFile);
Assert.Single(existingCacheFiles);
GetSDKReferenceFiles t2 = new GetSDKReferenceFiles();
t2.BuildEngine = engine;
t2.CacheFileFolderPath = _cacheDirectory;
// Same SDK with different path
ITaskItem item2 = new TaskItem(_sdkDirectory2);
item2.SetMetadata("ExpandReferenceAssemblies", "true");
item2.SetMetadata("TargetedSDKConfiguration", "Retail");
item2.SetMetadata("TargetedSDKArchitecture", "x86");
item2.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t2.ResolvedSDKReferences = new ITaskItem[] { item2 };
bool success2 = t2.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
ITaskItem[] references2 = t2.References;
Assert.True(success2);
// References from the two builds should not overlap, otherwise the cache files are being misused
foreach (var ref2 in references2)
{
Assert.Empty(references1.Where(i => i.ItemSpec.Equals(ref2.ItemSpec, StringComparison.InvariantCultureIgnoreCase)));
}
Thread.Sleep(100);
string sdkIdentity2 = item.GetMetadata("OriginalItemSpec");
string sdkRoot2 = item.ItemSpec;
string cacheFile2 = sdkIdentity2 + ",Set=" + FileUtilities.GetHexHash(sdkIdentity2) + "-" + FileUtilities.GetHexHash(sdkRoot2) + ",Hash=*.dat";
string[] existingCacheFiles2 = Directory.GetFiles(_cacheDirectory, cacheFile);
Assert.Single(existingCacheFiles2);
// There should have two cache files with the same prefix and first hash
Thread.Sleep(100);
string[] allCacheFiles = Directory.GetFiles(_cacheDirectory, sdkIdentity2 + ",Set=" + FileUtilities.GetHexHash(sdkIdentity2) + "*");
Assert.Equal(2, allCacheFiles.Length);
}
/// <summary>
/// Verify the correct reference files are found and that by default we do log the reference files
/// added.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void VerifyReferencesLogged()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "true");
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x86");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Empty(t.CopyLocalFiles);
Assert.Equal(8, t.References.Length);
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[0].ItemSpec.Replace(t.References[0].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[1].ItemSpec.Replace(t.References[1].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[2].ItemSpec.Replace(t.References[2].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[3].ItemSpec.Replace(t.References[3].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[4].ItemSpec.Replace(t.References[4].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[5].ItemSpec.Replace(t.References[5].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[6].ItemSpec.Replace(t.References[6].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[7].ItemSpec.Replace(t.References[7].GetMetadata("SDKRootPath"), String.Empty));
Assert.Equal("A.winmd", Path.GetFileName(t.References[0].ItemSpec));
Assert.Equal("true", t.References[0].GetMetadata("WinMDFile"));
Assert.Equal("Managed", t.References[0].GetMetadata("WinMDFileType"));
Assert.Equal("false", t.References[0].GetMetadata("CopyLocal"));
Assert.Equal("SDkWithManifest, Version=2.0", t.References[0].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.References[0].GetMetadata("ResolvedFrom"), true);
Assert.Equal("E.dll", Path.GetFileName(t.References[4].ItemSpec));
Assert.Equal("false", t.References[4].GetMetadata("WinMDFile"));
Assert.Empty(t.References[4].GetMetadata("WinMDFileType"));
Assert.Equal("false", t.References[4].GetMetadata("CopyLocal"));
Assert.Equal("SDkWithManifest, Version=2.0", t.References[4].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.References[4].GetMetadata("ResolvedFrom"), true);
}
/// <summary>
/// Verify the correct reference files are found and that by default we do log the reference files
/// added.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void VerifyReferencesLoggedFilterOutWinmd()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "true");
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x86");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
t.ReferenceExtensions = new string[] { ".dll" };
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Empty(t.CopyLocalFiles);
Assert.Equal(5, t.References.Length);
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[0].ItemSpec.Replace(t.References[0].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[1].ItemSpec.Replace(t.References[1].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[2].ItemSpec.Replace(t.References[2].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[3].ItemSpec.Replace(t.References[3].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[4].ItemSpec.Replace(t.References[4].GetMetadata("SDKRootPath"), String.Empty));
Assert.Equal("A.dll", Path.GetFileName(t.References[0].ItemSpec), true);
Assert.Equal("false", t.References[0].GetMetadata("WinMDFile"), true);
Assert.Empty(t.References[0].GetMetadata("WinMDFileType"));
Assert.Equal("false", t.References[0].GetMetadata("CopyLocal"), true);
Assert.Equal("SDkWithManifest, Version=2.0", t.References[0].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.References[0].GetMetadata("ResolvedFrom"), true);
Assert.Equal("h.dll", Path.GetFileName(t.References[4].ItemSpec), true);
Assert.Equal("false", t.References[4].GetMetadata("WinMDFile"), true);
Assert.Empty(t.References[4].GetMetadata("WinMDFileType"));
Assert.Equal("false", t.References[4].GetMetadata("CopyLocal"), true);
Assert.Equal("SDkWithManifest, Version=2.0", t.References[4].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.References[4].GetMetadata("ResolvedFrom"), true);
}
/// <summary>
/// Verify we log an error if no configuration is on the sdk reference
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void LogErrorWhenNoConfiguration()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "true");
item.SetMetadata("TargetedSDKConfiguration", "");
item.SetMetadata("TargetedSDKArchitecture", "amd64");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.False(success);
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.CannotHaveEmptyTargetConfiguration", _sdkDirectory);
}
/// <summary>
/// Verify we log an error if no configuration is on the sdk reference
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void LogErrorWhenNoArchitecture()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "true");
item.SetMetadata("TargetedSDKConfiguration", "Debug");
item.SetMetadata("TargetedSDKArchitecture", "");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.False(success);
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.CannotHaveEmptyTargetArchitecture", _sdkDirectory);
}
/// <summary>
/// Verify the correct reference files are found and that by default we do log the reference files
/// added.
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void VerifyReferencesLoggedAmd64()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "true");
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "amd64");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Empty(t.CopyLocalFiles);
Assert.Equal(8, t.References.Length);
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[0].ItemSpec.Replace(t.References[0].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[1].ItemSpec.Replace(t.References[1].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[2].ItemSpec.Replace(t.References[2].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[3].ItemSpec.Replace(t.References[3].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[4].ItemSpec.Replace(t.References[4].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[5].ItemSpec.Replace(t.References[5].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[6].ItemSpec.Replace(t.References[6].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[7].ItemSpec.Replace(t.References[7].GetMetadata("SDKRootPath"), String.Empty));
Assert.True(t.References[0].ItemSpec.IndexOf("x64", StringComparison.OrdinalIgnoreCase) > -1);
Assert.Equal("A.winmd", Path.GetFileName(t.References[0].ItemSpec));
Assert.Equal("SDKWithManifest, Version=2.0", t.References[0].GetMetadata("ReferenceGrouping"));
Assert.Empty(t.References[0].GetMetadata("ReferenceGroupingDisplayName"));
Assert.Equal("true", t.References[0].GetMetadata("WinMDFile"));
Assert.Equal("Managed", t.References[0].GetMetadata("WinMDFileType"));
Assert.Equal("false", t.References[0].GetMetadata("CopyLocal"));
Assert.Equal("SDkWithManifest, Version=2.0", t.References[0].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.References[0].GetMetadata("ResolvedFrom"), true);
Assert.Equal("E.dll", Path.GetFileName(t.References[4].ItemSpec));
Assert.Equal("false", t.References[4].GetMetadata("WinMDFile"));
Assert.Empty(t.References[4].GetMetadata("WinMDFileType"));
Assert.Equal("false", t.References[4].GetMetadata("CopyLocal"));
Assert.Equal("SDkWithManifest, Version=2.0", t.References[4].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.References[4].GetMetadata("ResolvedFrom"), true);
}
/// <summary>
/// Verify the correct reference files are found and that by default we do log the reference files
/// added.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void VerifyReferencesLoggedX64()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "true");
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x64");
item.SetMetadata("DisplayName", "SDKWithManifestDisplayName");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Empty(t.CopyLocalFiles);
Assert.Equal(8, t.References.Length);
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[0].ItemSpec.Replace(t.References[0].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[1].ItemSpec.Replace(t.References[1].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[2].ItemSpec.Replace(t.References[2].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[3].ItemSpec.Replace(t.References[3].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[4].ItemSpec.Replace(t.References[4].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[5].ItemSpec.Replace(t.References[5].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[6].ItemSpec.Replace(t.References[6].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[7].ItemSpec.Replace(t.References[7].GetMetadata("SDKRootPath"), String.Empty));
Assert.True(t.References[0].ItemSpec.IndexOf("x64", StringComparison.OrdinalIgnoreCase) > -1);
Assert.Equal("A.winmd", Path.GetFileName(t.References[0].ItemSpec));
Assert.Equal("true", t.References[0].GetMetadata("WinMDFile"));
Assert.Equal("SDKWithManifest, Version=2.0", t.References[0].GetMetadata("ReferenceGrouping"));
Assert.Equal("Managed", t.References[0].GetMetadata("WinMDFileType"));
Assert.Equal("SDKWithManifestDisplayName", t.References[0].GetMetadata("ReferenceGroupingDisplayName"));
Assert.Equal("false", t.References[0].GetMetadata("CopyLocal"));
Assert.Equal("SDkWithManifest, Version=2.0", t.References[0].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.References[0].GetMetadata("ResolvedFrom"), true);
Assert.Equal("E.dll", Path.GetFileName(t.References[4].ItemSpec));
Assert.Equal("false", t.References[4].GetMetadata("WinMDFile"));
Assert.Empty(t.References[4].GetMetadata("WinMDFileType"));
Assert.Equal("false", t.References[4].GetMetadata("CopyLocal"));
Assert.Equal("SDkWithManifest, Version=2.0", t.References[4].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.References[4].GetMetadata("ResolvedFrom"), true);
}
/// <summary>
/// Verify the correct reference files are found and that if we do not want to log them we can set a property to do so.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void VerifyLogReferencesFalse()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "true");
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x86");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
t.LogReferencesList = false;
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Empty(t.CopyLocalFiles);
Assert.Equal(8, t.References.Length);
engine.AssertLogDoesntContainMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[0].ItemSpec.Replace(t.References[0].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogDoesntContainMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[1].ItemSpec.Replace(t.References[1].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogDoesntContainMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[2].ItemSpec.Replace(t.References[2].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogDoesntContainMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[3].ItemSpec.Replace(t.References[3].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogDoesntContainMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[4].ItemSpec.Replace(t.References[4].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogDoesntContainMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[5].ItemSpec.Replace(t.References[5].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogDoesntContainMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[6].ItemSpec.Replace(t.References[6].GetMetadata("SDKRootPath"), String.Empty));
engine.AssertLogDoesntContainMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingReference", t.References[7].ItemSpec.Replace(t.References[7].GetMetadata("SDKRootPath"), String.Empty));
}
/// <summary>
/// Verify the correct redist files are found and that by default we do not log the redist files
/// added.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void VerifyRedistFilesLogRedistFalse()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "true");
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x86");
item.SetMetadata("CopyRedist", "true");
item.SetMetadata("CopyRedistToSubDirectory", "Super");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
t.LogRedistFilesList = false;
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Empty(t.CopyLocalFiles);
Assert.Equal(8, t.References.Length);
Assert.Equal(5, t.RedistFiles.Length);
engine.AssertLogDoesntContainMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[0].ItemSpec.Replace(t.RedistFiles[0].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[0].GetMetadata("TargetPath"));
engine.AssertLogDoesntContainMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[1].ItemSpec.Replace(t.RedistFiles[1].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[1].GetMetadata("TargetPath"));
engine.AssertLogDoesntContainMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[2].ItemSpec.Replace(t.RedistFiles[2].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[2].GetMetadata("TargetPath"));
engine.AssertLogDoesntContainMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[3].ItemSpec.Replace(t.RedistFiles[3].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[3].GetMetadata("TargetPath"));
engine.AssertLogDoesntContainMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[4].ItemSpec.Replace(t.RedistFiles[4].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[4].GetMetadata("TargetPath"));
Assert.Equal("A.dll", Path.GetFileName(t.RedistFiles[0].ItemSpec));
Assert.Equal("Super\\A.dll", t.RedistFiles[0].GetMetadata("TargetPath"), true);
Assert.Equal("SDkWithManifest, Version=2.0", t.RedistFiles[0].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.RedistFiles[0].GetMetadata("ResolvedFrom"), true);
Assert.Empty(t.RedistFiles[0].GetMetadata("Root"));
Assert.Equal("B.dll", Path.GetFileName(t.RedistFiles[1].ItemSpec), true);
Assert.Equal("Super\\ASubDirectory\\TwoDeep\\B.dll", t.RedistFiles[1].GetMetadata("TargetPath"), true);
Assert.Equal("SDkWithManifest, Version=2.0", t.RedistFiles[1].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.RedistFiles[1].GetMetadata("ResolvedFrom"), true);
Assert.Empty(t.RedistFiles[1].GetMetadata("Root"));
Assert.Equal("B.PRI", Path.GetFileName(t.RedistFiles[2].ItemSpec), true);
Assert.Equal("Super\\B.PRI", t.RedistFiles[2].GetMetadata("TargetPath"), true);
Assert.Equal("SDkWithManifest, Version=2.0", t.RedistFiles[2].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.RedistFiles[2].GetMetadata("ResolvedFrom"), true);
Assert.Equal("Super", t.RedistFiles[2].GetMetadata("Root"));
Assert.Equal("C.dll", Path.GetFileName(t.RedistFiles[3].ItemSpec), true);
Assert.Equal("Super\\C.dll", t.RedistFiles[3].GetMetadata("TargetPath"), true);
Assert.Equal("SDkWithManifest, Version=2.0", t.RedistFiles[3].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.RedistFiles[3].GetMetadata("ResolvedFrom"), true);
Assert.Empty(t.RedistFiles[3].GetMetadata("Root"));
Assert.Equal("D.dll", Path.GetFileName(t.RedistFiles[4].ItemSpec), true);
Assert.Equal("Super\\D.dll", t.RedistFiles[4].GetMetadata("TargetPath"), true);
Assert.Equal("SDkWithManifest, Version=2.0", t.RedistFiles[4].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.RedistFiles[4].GetMetadata("ResolvedFrom"), true);
Assert.Empty(t.RedistFiles[4].GetMetadata("Root"));
}
/// <summary>
/// Verify the correct redist files are found and that by default we do not log the redist files
/// added.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void VerifyRedistFilesLogRedistTrue()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x86");
item.SetMetadata("CopyRedist", "true");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Empty(t.CopyLocalFiles);
Assert.Equal(5, t.RedistFiles.Length);
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[0].ItemSpec.Replace(t.RedistFiles[0].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[0].GetMetadata("TargetPath"));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[1].ItemSpec.Replace(t.RedistFiles[1].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[1].GetMetadata("TargetPath"));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[2].ItemSpec.Replace(t.RedistFiles[2].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[2].GetMetadata("TargetPath"));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[3].ItemSpec.Replace(t.RedistFiles[3].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[3].GetMetadata("TargetPath"));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[4].ItemSpec.Replace(t.RedistFiles[4].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[4].GetMetadata("TargetPath"));
}
/// <summary>
/// Verify the correct redist files are found and that by default we do not log the redist files
/// added.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void VerifyRedistFilesLogRedistTrueX64()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x64");
item.SetMetadata("CopyRedist", "true");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Empty(t.CopyLocalFiles);
Assert.Equal(5, t.RedistFiles.Length);
Assert.True(t.RedistFiles[0].ItemSpec.IndexOf("x64", StringComparison.OrdinalIgnoreCase) > -1);
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[0].ItemSpec.Replace(t.RedistFiles[0].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[0].GetMetadata("TargetPath"));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[1].ItemSpec.Replace(t.RedistFiles[1].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[1].GetMetadata("TargetPath"));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[2].ItemSpec.Replace(t.RedistFiles[2].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[2].GetMetadata("TargetPath"));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[3].ItemSpec.Replace(t.RedistFiles[3].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[3].GetMetadata("TargetPath"));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[4].ItemSpec.Replace(t.RedistFiles[4].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[4].GetMetadata("TargetPath"));
}
/// <summary>
/// Verify the correct redist files are found and that by default we do not log the redist files
/// added.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void VerifyRedistFilesLogRedistTrueAmd64()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "amd64");
item.SetMetadata("CopyRedist", "true");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Empty(t.CopyLocalFiles);
Assert.Equal(5, t.RedistFiles.Length);
Assert.True(t.RedistFiles[0].ItemSpec.IndexOf("x64", StringComparison.OrdinalIgnoreCase) > -1);
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[0].ItemSpec.Replace(t.RedistFiles[0].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[0].GetMetadata("TargetPath"));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[1].ItemSpec.Replace(t.RedistFiles[1].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[1].GetMetadata("TargetPath"));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[2].ItemSpec.Replace(t.RedistFiles[2].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[2].GetMetadata("TargetPath"));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[3].ItemSpec.Replace(t.RedistFiles[3].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[3].GetMetadata("TargetPath"));
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.AddingRedistFile", t.RedistFiles[4].ItemSpec.Replace(t.RedistFiles[4].GetMetadata("SDKRootPath"), String.Empty), t.RedistFiles[4].GetMetadata("TargetPath"));
}
/// <summary>
/// Make sure by default conflicts between references are logged as a comment if they are within the sdk itself
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void LogNoWarningForReferenceConflictWithinSDK()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "true");
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x86");
item.SetMetadata("CopyRedist", "false");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Equal(8, t.References.Length);
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.ConflictReferenceSameSDK", "SDKWithManifest, Version=2.0", "References\\Retail\\X86\\A.winmd", "References\\CommonConfiguration\\Neutral\\A.dll");
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.ConflictReferenceSameSDK", "SDKWithManifest, Version=2.0", "References\\Retail\\X86\\A.winmd", "References\\CommonConfiguration\\Neutral\\A.winmd");
Assert.Equal(0, engine.Warnings);
}
/// <summary>
/// Make sure that if the LogReferenceConflictsWithinSDKAsWarning is set log a warning for conflicts within an SDK for references.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void LogWarningForReferenceConflictWithinSDK()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "true");
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x86");
item.SetMetadata("CopyRedist", "false");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
t.LogReferenceConflictWithinSDKAsWarning = true;
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Equal(8, t.References.Length);
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.ConflictReferenceSameSDK", "SDKWithManifest, Version=2.0", "References\\Retail\\X86\\A.winmd", "References\\CommonConfiguration\\Neutral\\A.dll");
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.ConflictReferenceSameSDK", "SDKWithManifest, Version=2.0", "References\\Retail\\X86\\A.winmd", "References\\CommonConfiguration\\Neutral\\A.winmd");
Assert.Equal(2, engine.Warnings);
}
/// <summary>
/// Make sure by default conflicts between references are logged as a comment if they are within the sdk itself
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void LogNoWarningForRedistConflictWithinSDK()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "false");
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x86");
item.SetMetadata("CopyRedist", "true");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Equal(5, t.RedistFiles.Length);
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.ConflictRedistSameSDK", "A.dll", "SDKWithManifest, Version=2.0", "Redist\\Retail\\X86\\A.dll", "Redist\\CommonConfiguration\\Neutral\\A.dll");
Assert.Equal(0, engine.Warnings);
}
/// <summary>
/// Make sure that if the LogRedistConflictsWithinSDKAsWarning is set log a warning for conflicts within an SDK for redist files.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void LogWarningForRedistConflictWithinSDK()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "false");
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x86");
item.SetMetadata("CopyRedist", "true");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item };
t.LogRedistConflictWithinSDKAsWarning = true;
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Equal(5, t.RedistFiles.Length);
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.ConflictRedistSameSDK", "A.dll", "SDKWithManifest, Version=2.0", "Redist\\Retail\\X86\\A.dll", "Redist\\CommonConfiguration\\Neutral\\A.dll");
Assert.Equal(1, engine.Warnings);
}
/// <summary>
/// Verify if there are conflicts between references or redist files between sdks that we log a warning by default.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void LogReferenceAndRedistConflictBetweenSdks()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "true");
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x86");
item.SetMetadata("CopyRedist", "true");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
ITaskItem item2 = new TaskItem(_sdkDirectory2);
item2.SetMetadata("ExpandReferenceAssemblies", "true");
item2.SetMetadata("TargetedSDKConfiguration", "Retail");
item2.SetMetadata("TargetedSDKArchitecture", "x86");
item2.SetMetadata("CopyRedist", "true");
item2.SetMetadata("OriginalItemSpec", "AnotherSDK, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item, item2 };
t.LogReferencesList = false;
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Empty(t.CopyLocalFiles);
Assert.Equal(8, t.References.Length);
Assert.Equal(6, t.RedistFiles.Length);
Assert.Equal(2, engine.Warnings);
string redistWinner = Path.Combine(_sdkDirectory, "Redist\\Retail\\Neutral\\B.pri");
string redistVictim = Path.Combine(_sdkDirectory2, "Redist\\Retail\\X86\\B.pri");
string referenceWinner = Path.Combine(_sdkDirectory, "References\\Retail\\Neutral\\B.WinMD");
string referenceVictim = Path.Combine(_sdkDirectory2, "References\\Retail\\X86\\B.WinMD");
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.ConflictRedistDifferentSDK", "B.PRI", "SDKWithManifest, Version=2.0", "AnotherSDK, Version=2.0", redistWinner, redistVictim);
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.ConflictReferenceDifferentSDK", "SDKWithManifest, Version=2.0", "AnotherSDK, Version=2.0", referenceWinner, referenceVictim);
}
/// <summary>
/// If a user create a target path that causes a conflict between two sdks then we want to warn
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void LogReferenceAndRedistConflictBetweenSdksDueToCustomTargetPath()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "true");
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x86");
item.SetMetadata("CopyRedist", "true");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
ITaskItem item2 = new TaskItem(_sdkDirectory2);
item2.SetMetadata("ExpandReferenceAssemblies", "true");
item2.SetMetadata("TargetedSDKConfiguration", "Retail");
item2.SetMetadata("TargetedSDKArchitecture", "x86");
item2.SetMetadata("CopyRedist", "true");
item2.SetMetadata("OriginalItemSpec", "AnotherSDK, Version=2.0");
item2.SetMetadata("CopyRedistToSubDirectory", "ASubDirectory\\TwoDeep");
t.ResolvedSDKReferences = new ITaskItem[] { item, item2 };
t.LogReferencesList = false;
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Empty(t.CopyLocalFiles);
Assert.Equal(8, t.References.Length);
Assert.Equal(6, t.RedistFiles.Length);
Assert.Equal(2, engine.Warnings);
string redistWinner = Path.Combine(_sdkDirectory, "Redist\\Retail\\Neutral\\ASubDirectory\\TwoDeep\\B.dll");
string redistVictim = Path.Combine(_sdkDirectory2, "Redist\\Retail\\X86\\B.dll");
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.ConflictRedistDifferentSDK", "ASUBDIRECTORY\\TWODEEP\\B.DLL", "SDKWithManifest, Version=2.0", "AnotherSDK, Version=2.0", redistWinner, redistVictim);
}
/// <summary>
/// Verify if there are conflicts between references or redist files between sdks that we do not log a warning if a certain property (LogxxxConflictBetweenSDKsAsWarning is set to false.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void LogReferenceAndRedistConflictBetweenSdksNowarning()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "true");
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x86");
item.SetMetadata("CopyRedist", "true");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
ITaskItem item2 = new TaskItem(_sdkDirectory2);
item2.SetMetadata("ExpandReferenceAssemblies", "true");
item2.SetMetadata("TargetedSDKConfiguration", "Retail");
item2.SetMetadata("TargetedSDKArchitecture", "x86");
item2.SetMetadata("CopyRedist", "true");
item2.SetMetadata("OriginalItemSpec", "AnotherSDK, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item, item2 };
t.LogReferencesList = false;
t.LogReferenceConflictBetweenSDKsAsWarning = false;
t.LogRedistConflictBetweenSDKsAsWarning = false;
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Empty(t.CopyLocalFiles);
Assert.Equal(8, t.References.Length);
Assert.Equal(6, t.RedistFiles.Length);
Assert.Equal(0, engine.Warnings);
string redistWinner = Path.Combine(_sdkDirectory, "Redist\\Retail\\Neutral\\B.pri");
string redistVictim = Path.Combine(_sdkDirectory2, "Redist\\Retail\\X86\\B.pri");
string referenceWinner = Path.Combine(_sdkDirectory, "References\\Retail\\Neutral\\B.WinMD");
string referenceVictim = Path.Combine(_sdkDirectory2, "References\\Retail\\X86\\B.WinMD");
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.ConflictRedistDifferentSDK", "B.PRI", "SDKWithManifest, Version=2.0", "AnotherSDK, Version=2.0", redistWinner, redistVictim);
engine.AssertLogContainsMessageFromResource(_resourceDelegate, "GetSDKReferenceFiles.ConflictReferenceDifferentSDK", "SDKWithManifest, Version=2.0", "AnotherSDK, Version=2.0", referenceWinner, referenceVictim);
}
/// <summary>
/// If there are conflicting redist files between two sdks but their target paths are different then we should copy both to the appx
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TwoSDKSConflictRedistButDifferentTargetPaths()
{
var engine = new MockEngine(_output);
var t = new GetSDKReferenceFiles();
t.BuildEngine = engine;
t.CacheFileFolderPath = _cacheDirectory;
ITaskItem item = new TaskItem(_sdkDirectory);
item.SetMetadata("ExpandReferenceAssemblies", "false");
item.SetMetadata("TargetedSDKConfiguration", "Retail");
item.SetMetadata("TargetedSDKArchitecture", "x86");
item.SetMetadata("CopyRedistToSubDirectory", "SDK1");
item.SetMetadata("CopyRedist", "true");
item.SetMetadata("OriginalItemSpec", "SDKWithManifest, Version=2.0");
ITaskItem item2 = new TaskItem(_sdkDirectory2);
item2.SetMetadata("ExpandReferenceAssemblies", "false");
item2.SetMetadata("TargetedSDKConfiguration", "Retail");
item2.SetMetadata("TargetedSDKArchitecture", "x86");
item2.SetMetadata("CopyRedistToSubDirectory", "SDK2");
item2.SetMetadata("CopyRedist", "true");
item2.SetMetadata("OriginalItemSpec", "AnotherSDK, Version=2.0");
t.ResolvedSDKReferences = new ITaskItem[] { item, item2 };
t.LogReferencesList = false;
bool success = t.Execute(_getAssemblyName, _getAssemblyRuntimeVersion, p => FileUtilities.FileExistsNoThrow(p), synchronous: true);
Assert.True(success);
Assert.Equal(7, t.RedistFiles.Length);
Assert.Equal(0, engine.Warnings);
Assert.Equal("A.dll", Path.GetFileName(t.RedistFiles[0].ItemSpec), true);
Assert.Equal("SDK1\\A.dll", t.RedistFiles[0].GetMetadata("TargetPath"), true);
Assert.Equal("SDkWithManifest, Version=2.0", t.RedistFiles[0].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.RedistFiles[0].GetMetadata("ResolvedFrom"), true);
Assert.Empty(t.RedistFiles[0].GetMetadata("Root"));
Assert.Equal("B.dll", Path.GetFileName(t.RedistFiles[1].ItemSpec), true);
Assert.Equal("SDK2\\B.dll", t.RedistFiles[1].GetMetadata("TargetPath"), true);
Assert.Equal("AnotherSDK, Version=2.0", t.RedistFiles[1].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.RedistFiles[1].GetMetadata("ResolvedFrom"), true);
Assert.Empty(t.RedistFiles[1].GetMetadata("Root"));
Assert.Equal("B.dll", Path.GetFileName(t.RedistFiles[2].ItemSpec), true);
Assert.Equal("SDK1\\ASubDirectory\\TwoDeep\\B.dll", t.RedistFiles[2].GetMetadata("TargetPath"), true);
Assert.Equal("SDkWithManifest, Version=2.0", t.RedistFiles[2].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.RedistFiles[2].GetMetadata("ResolvedFrom"), true);
Assert.Empty(t.RedistFiles[2].GetMetadata("Root"));
Assert.Equal("B.pri", Path.GetFileName(t.RedistFiles[3].ItemSpec), true);
Assert.Equal("SDK2\\B.Pri", t.RedistFiles[3].GetMetadata("TargetPath"), true);
Assert.Equal("AnotherSDK, Version=2.0", t.RedistFiles[3].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.RedistFiles[3].GetMetadata("ResolvedFrom"), true);
Assert.Equal("SDK2", t.RedistFiles[3].GetMetadata("Root"), true);
Assert.Equal("B.PRI", Path.GetFileName(t.RedistFiles[4].ItemSpec), true);
Assert.Equal("SDK1\\B.PRI", t.RedistFiles[4].GetMetadata("TargetPath"), true);
Assert.Equal("SDkWithManifest, Version=2.0", t.RedistFiles[4].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.RedistFiles[4].GetMetadata("ResolvedFrom"), true);
Assert.Equal("SDK1", t.RedistFiles[4].GetMetadata("Root"), true);
Assert.Equal("C.dll", Path.GetFileName(t.RedistFiles[5].ItemSpec), true);
Assert.Equal("SDK1\\C.dll", t.RedistFiles[5].GetMetadata("TargetPath"), true);
Assert.Equal("SDkWithManifest, Version=2.0", t.RedistFiles[5].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.RedistFiles[5].GetMetadata("ResolvedFrom"), true);
Assert.Empty(t.RedistFiles[5].GetMetadata("Root"));
Assert.Equal("D.dll", Path.GetFileName(t.RedistFiles[6].ItemSpec), true);
Assert.Equal("SDK1\\D.dll", t.RedistFiles[6].GetMetadata("TargetPath"), true);
Assert.Equal("SDkWithManifest, Version=2.0", t.RedistFiles[6].GetMetadata("OriginalItemSpec"), true);
Assert.Equal("GetSDKReferenceFiles", t.RedistFiles[6].GetMetadata("ResolvedFrom"), true);
Assert.Empty(t.RedistFiles[6].GetMetadata("Root"));
}
private static AssemblyNameExtension GetAssemblyName(string path)
{
if (Path.GetFileName(path).Equals("C.winmd", StringComparison.OrdinalIgnoreCase))
{
throw new BadImageFormatException();
}
if (Path.GetExtension(path).Equals(".winmd", StringComparison.OrdinalIgnoreCase) || Path.GetExtension(path).Equals(".dll", StringComparison.OrdinalIgnoreCase))
{
string fileName = Path.GetFileNameWithoutExtension(path);
return new AssemblyNameExtension(fileName + ", Version=2.0.0.0, Culture=Neutral, PublicKeyToken=null");
}
return null;
}
private static string GetImageRuntimeVersion(string path)
{
if (Path.GetFileName(path).Equals("A.winmd", StringComparison.OrdinalIgnoreCase))
{
return "WindowsRuntime 1.0;CLR V2.0.50727";
}
if (Path.GetExtension(path).Equals(".winmd", StringComparison.OrdinalIgnoreCase))
{
return "WindowsRuntime 1.0";
}
if (Path.GetExtension(path).Equals(".dll", StringComparison.OrdinalIgnoreCase))
{
return "CLR V2.0.50727";
}
return null;
}
}
}
| |
// Asteroid Field Editor C# Script (version: 1.02)
// SPACE UNITY - Space Scene Construction Kit
// http://www.spaceunity.com
// (c) 2013 Stefan Persson
// DESCRIPTION
// This is an editor script (must reside in the /Editor project folder.) The purpose of
// the script is to improve presentation and configuration of the AsteroidField.cs script
// used to create asteroid fields.
// INSTRUCTIONS
// You don't need to do anything with this script, it will automatically detect objects
// that use the C# script AsteroidField and override the inspector to simplify configuration
// of the script parameters.
// Version History
// 1.02 - Prefixed with SU_AsteroidFieldEditor to avoid naming conflicts.
// 0.8 - Initial Release.
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(SU_AsteroidField))]
public class SU_AsteroidFieldEditor : Editor {
// Range Values Configuration
private int _displayMinAsteroidCount = 1;
private int _displayMaxAsteroidCount = 3000;
private int _displayMinRange = 10;
private int _displayMaxRange = 100000;
// Warning Threshholds
private int _warningHighAsteroidCount = 1000;
// Serialized Object
SerializedObject myTarget;
// Serialized Properties
SerializedProperty polyCount;
SerializedProperty polyCountCollider;
SerializedProperty maxAsteroids;
SerializedProperty respawnIfOutOfRange;
SerializedProperty respawnDestroyedAsteroids;
SerializedProperty range;
SerializedProperty distanceSpawn;
SerializedProperty fadeAsteroids;
SerializedProperty distanceFade;
SerializedProperty minAsteroidScale;
SerializedProperty maxAsteroidScale;
SerializedProperty scaleMultiplier;
SerializedProperty minAsteroidRotationSpeed;
SerializedProperty maxAsteroidRotationSpeed;
SerializedProperty rotationSpeedMultiplier;
SerializedProperty minAsteroidDriftSpeed;
SerializedProperty maxAsteroidDriftSpeed;
SerializedProperty driftSpeedMultiplier;
SerializedProperty isRigidbody;
SerializedProperty mass;
SerializedProperty minAsteroidAngularVelocity;
SerializedProperty maxAsteroidAngularVelocity;
SerializedProperty angularVelocityMultiplier;
SerializedProperty minAsteroidVelocity;
SerializedProperty maxAsteroidVelocity;
SerializedProperty velocityMultiplier;
// Temporary variables since properties can't be modified directly when using Ref and/or Out paremeters
private float _minScale;
private float _maxScale;
private float _minRotationSpeed;
private float _maxRotationSpeed;
private float _minDriftSpeed;
private float _maxDriftSpeed;
private float _minAngularVelocity;
private float _maxAngularVelocity;
private float _minVelocity;
private float _maxVelocity;
// Bool display collapse/expand section helpers
private bool _showPrefabs;
private bool _showMaterials;
void OnEnable() {
// Reference the serialized object (instance of AsteroidField.cs)
myTarget = new SerializedObject(target);
// Find and reference the properties of the target object
polyCount = myTarget.FindProperty("polyCount");
polyCountCollider = myTarget.FindProperty("polyCountCollider");
maxAsteroids = myTarget.FindProperty("maxAsteroids");
respawnIfOutOfRange = myTarget.FindProperty("respawnIfOutOfRange");
respawnDestroyedAsteroids = myTarget.FindProperty("respawnDestroyedAsteroids");
range = myTarget.FindProperty("range");
distanceSpawn = myTarget.FindProperty("distanceSpawn");
fadeAsteroids = myTarget.FindProperty("fadeAsteroids");
distanceFade = myTarget.FindProperty("distanceFade");
minAsteroidScale = myTarget.FindProperty("minAsteroidScale");
maxAsteroidScale = myTarget.FindProperty("maxAsteroidScale");
scaleMultiplier = myTarget.FindProperty("scaleMultiplier");
minAsteroidRotationSpeed = myTarget.FindProperty("minAsteroidRotationSpeed");
maxAsteroidRotationSpeed = myTarget.FindProperty("maxAsteroidRotationSpeed");
rotationSpeedMultiplier = myTarget.FindProperty("rotationSpeedMultiplier");
minAsteroidDriftSpeed = myTarget.FindProperty("minAsteroidDriftSpeed");
maxAsteroidDriftSpeed = myTarget.FindProperty("maxAsteroidDriftSpeed");
driftSpeedMultiplier = myTarget.FindProperty("driftSpeedMultiplier");
isRigidbody = myTarget.FindProperty("isRigidbody");
minAsteroidAngularVelocity = myTarget.FindProperty("minAsteroidAngularVelocity");
maxAsteroidAngularVelocity = myTarget.FindProperty("maxAsteroidAngularVelocity");
angularVelocityMultiplier = myTarget.FindProperty("angularVelocityMultiplier");
minAsteroidVelocity = myTarget.FindProperty("minAsteroidVelocity");
maxAsteroidVelocity = myTarget.FindProperty("maxAsteroidVelocity");
velocityMultiplier = myTarget.FindProperty("velocityMultiplier");
mass = myTarget.FindProperty("mass");
}
// Override the OnInspectorGUI and present these EditorGUI gadgets instead of the default ones
public override void OnInspectorGUI() {
// Update the serialized object
myTarget.Update();
// Present inspector GUI gadgets/objects and modify AsteroidField.cs instances with configured values
maxAsteroids.intValue = EditorGUILayout.IntSlider("Number of Asteroids", maxAsteroids.intValue, _displayMinAsteroidCount, _displayMaxAsteroidCount);
if (maxAsteroids.intValue > _warningHighAsteroidCount) {
EditorGUILayout.LabelField("Warning! Many asteroids may impact performance! Consider smaller range and fewer asteroids instead.", EditorStyles.wordWrappedMiniLabel);
}
range.floatValue = EditorGUILayout.Slider("Range", range.floatValue, _displayMinRange, _displayMaxRange);
if (range.floatValue > Camera.main.farClipPlane) {
EditorGUILayout.LabelField("Warning! Main camera clipping plane is closer than asteroid range.", EditorStyles.wordWrappedMiniLabel);
}
EditorGUILayout.LabelField("Range is distance from the center to the edge of the asteroid field. If the transform of the AsteroidField moves, asteroids " +
"that become out of range will respawn to a new location at spawn distance of range.", EditorStyles.wordWrappedMiniLabel);
respawnIfOutOfRange.boolValue = EditorGUILayout.Toggle("Respawn if Out of Range", respawnIfOutOfRange.boolValue);
EditorGUILayout.LabelField("Note: Respawn if out of range must be enabled for endless/infinite asteroid fields", EditorStyles.wordWrappedMiniLabel);
respawnDestroyedAsteroids.boolValue = EditorGUILayout.Toggle("Respawn if Destroyed", respawnDestroyedAsteroids.boolValue);
EditorGUILayout.Separator();
distanceSpawn.floatValue = EditorGUILayout.Slider("Spawn at % of Range", distanceSpawn.floatValue, 0.0f, 1.0f);
EditorGUILayout.Separator();
EditorGUILayout.LabelField("Asteroid Scale (Min/Max Range)", EditorStyles.boldLabel);
_minScale = minAsteroidScale.floatValue;
_maxScale = maxAsteroidScale.floatValue;
GUIContent _scaleContent = new GUIContent( string.Format( "Min:{0:F1}, Max:{1:F1}", _minScale , _maxScale ) );
EditorGUILayout.MinMaxSlider(_scaleContent, ref _minScale, ref _maxScale, 0.1f, 1.0f);
minAsteroidScale.floatValue = _minScale;
maxAsteroidScale.floatValue = _maxScale;
scaleMultiplier.floatValue = EditorGUILayout.FloatField( "Scale Multiplier", scaleMultiplier.floatValue);
EditorGUILayout.Separator();
// Rigidbody or non-rigidbody Asteroids
isRigidbody.boolValue = EditorGUILayout.Toggle("Is Rigidbody", isRigidbody.boolValue);
if (isRigidbody.boolValue) {
mass.floatValue = EditorGUILayout.FloatField("Mass (scales with size)", mass.floatValue);
EditorGUILayout.LabelField("Asteroid Angular Velocity (Min/Max Range)", EditorStyles.boldLabel);
_minAngularVelocity = minAsteroidAngularVelocity.floatValue;
_maxAngularVelocity = maxAsteroidAngularVelocity.floatValue;
GUIContent _rotationContent = new GUIContent( string.Format( "Min:{0:F1}, Max:{1:F1}", _minAngularVelocity , _maxAngularVelocity ) );
EditorGUILayout.MinMaxSlider(_rotationContent, ref _minAngularVelocity, ref _maxAngularVelocity, 0.0f, 1.0f);
minAsteroidAngularVelocity.floatValue = _minAngularVelocity;
maxAsteroidAngularVelocity.floatValue = _maxAngularVelocity;
angularVelocityMultiplier.floatValue = EditorGUILayout.FloatField( "Rotation Speed Multiplier", angularVelocityMultiplier.floatValue);
EditorGUILayout.LabelField("Asteroid Velocity (Min/Max Range)", EditorStyles.boldLabel);
_minVelocity = minAsteroidVelocity.floatValue;
_maxVelocity = maxAsteroidVelocity.floatValue;
GUIContent _driftContent = new GUIContent( string.Format( "Min:{0:F1}, Max:{1:F1}", _minVelocity , _maxVelocity ) );
EditorGUILayout.MinMaxSlider(_driftContent, ref _minVelocity, ref _maxVelocity, 0.0f, 1.0f);
minAsteroidVelocity.floatValue = _minVelocity;
maxAsteroidVelocity.floatValue = _maxVelocity;
velocityMultiplier.floatValue = EditorGUILayout.FloatField( "Drift Speed Multiplier", velocityMultiplier.floatValue);
} else {
EditorGUILayout.LabelField("Asteroid Rotation Speed (Min/Max Range)", EditorStyles.boldLabel);
_minRotationSpeed = minAsteroidRotationSpeed.floatValue;
_maxRotationSpeed = maxAsteroidRotationSpeed.floatValue;
GUIContent _rotationContent = new GUIContent( string.Format( "Min:{0:F1}, Max:{1:F1}", _minRotationSpeed , _maxRotationSpeed ) );
EditorGUILayout.MinMaxSlider(_rotationContent, ref _minRotationSpeed, ref _maxRotationSpeed, 0.0f, 1.0f);
minAsteroidRotationSpeed.floatValue = _minRotationSpeed;
maxAsteroidRotationSpeed.floatValue = _maxRotationSpeed;
rotationSpeedMultiplier.floatValue = EditorGUILayout.FloatField( "Rotation Speed Multiplier", rotationSpeedMultiplier.floatValue);
EditorGUILayout.LabelField("Asteroid Drift Speed (Min/Max Range)", EditorStyles.boldLabel);
_minDriftSpeed = minAsteroidDriftSpeed.floatValue;
_maxDriftSpeed = maxAsteroidDriftSpeed.floatValue;
GUIContent _driftContent = new GUIContent( string.Format( "Min:{0:F1}, Max:{1:F1}", _minDriftSpeed , _maxDriftSpeed ) );
EditorGUILayout.MinMaxSlider(_driftContent, ref _minDriftSpeed, ref _maxDriftSpeed, 0.0f, 1.0f);
minAsteroidDriftSpeed.floatValue = _minDriftSpeed;
maxAsteroidDriftSpeed.floatValue = _maxDriftSpeed;
driftSpeedMultiplier.floatValue = EditorGUILayout.FloatField( "Drift Speed Multiplier", driftSpeedMultiplier.floatValue);
}
EditorGUILayout.Separator();
// Visual Settings
EditorGUILayout.LabelField("Visual Settings", EditorStyles.boldLabel);
fadeAsteroids.boolValue = EditorGUILayout.Toggle("Fade Asteroids", fadeAsteroids.boolValue);
if (fadeAsteroids.boolValue) {
distanceFade.floatValue = EditorGUILayout.Slider("Fade from % of Spawn", distanceFade.floatValue, 0.0f, 1.0f);
EditorGUILayout.LabelField("Alpha is 1.0 at distanceFade*distanceSpawn*range and " +
"gradually fades out to 0.0 at distanceSpawn*range.", EditorStyles.wordWrappedMiniLabel);
}
EditorGUILayout.Separator();
// Asteroid Mesh Quality
EditorGUILayout.LabelField("Asteroid Mesh Quality", EditorStyles.boldLabel);
EditorGUILayout.PropertyField( polyCount);
EditorGUILayout.PropertyField( polyCountCollider);
if (polyCountCollider.enumValueIndex != (int) SU_Asteroid.PolyCount.LOW) {
EditorGUILayout.LabelField("Warning! Using detailed collider meshes may heavily impact performance or raise errors if the mesh is too detailed.", EditorStyles.wordWrappedMiniLabel);
}
// Asteroid Prefab (array of asteroid shapes the asteroid field should randomly consist of)
EditorGUILayout.LabelField("Asteroid Prefabs", EditorStyles.boldLabel);
_showPrefabs = EditorGUILayout.Foldout(_showPrefabs, "Prefabs");
EditorGUIUtility.LookLikeInspector();
if (_showPrefabs) {
ArrayGUI(myTarget, "prefabAsteroids");
}
EditorGUIUtility.LookLikeControls();
EditorGUILayout.Separator();
// Asteroid Materials (array of asteroid materials the asteroid field should randomly consist of)
// The random selection is weighted between common and rare materials.
EditorGUILayout.LabelField("Asteroid Materials", EditorStyles.boldLabel);
_showMaterials = EditorGUILayout.Foldout(_showMaterials, "Materials");
EditorGUIUtility.LookLikeInspector();
if (_showMaterials) {
EditorGUILayout.LabelField("Very Common Materials (50%)", EditorStyles.boldLabel);
ArrayGUI(myTarget, "materialVeryCommon");
EditorGUILayout.LabelField("Common Materials (30%)", EditorStyles.boldLabel);
ArrayGUI(myTarget, "materialCommon");
EditorGUILayout.LabelField("Rare Materials (15%)", EditorStyles.boldLabel);
ArrayGUI(myTarget, "materialRare");
EditorGUILayout.LabelField("Very Rare Materials (5%)", EditorStyles.boldLabel);
ArrayGUI(myTarget, "materialVeryRare");
}
EditorGUIUtility.LookLikeControls();
// Apply the modified properties
myTarget.ApplyModifiedProperties();
}
// Function to ovveride and display custom object array in inspector
void ArrayGUI(SerializedObject obj, string name) {
int size = obj.FindProperty(name + ".Array.size").intValue;
int newSize = EditorGUILayout.IntField("Size", size);
if (newSize != size) obj.FindProperty(name + ".Array.size").intValue = newSize;
EditorGUI.indentLevel = 3;
for (int i=0;i<newSize;i++) {
var prop = obj.FindProperty(string.Format("{0}.Array.data[{1}]", name, i));
EditorGUILayout.PropertyField(prop);
}
EditorGUI.indentLevel = 0;
}
}
| |
///////////////////////////////////////////////////////////////
// FSXml - A library for representing file system data as //
// Xml. //
// Shukri Adams ([email protected]) //
// https://github.com/shukriadams/browsemonkey //
// MIT License (MIT) Copyright (c) 2014 Shukri Adams //
///////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.Xml;
using vcFramework.Parsers;
namespace FSXml
{
/// <summary>
/// Static class contain methods for working with directory and file structures using XML.
/// </summary>
public class FSXmlLib
{
#region METHODS
/// <summary>
/// Gets a list of unique, distinct, alphabetically sorted file extensions in the given
/// FSXml data. File extensions are are returned in lower case
/// </summary>
/// <returns></returns>
static public string[] GetFileExtensions(
XmlNode nFSXmlData
)
{
ArrayList fileTypes = new ArrayList();
XmlNode nXmlStartNode = null;
// determines start node - we dont know for sure where in fsxml structure
// the passed Xml data is, and we want the "folders" node that's as close
// to the start node as possible
if (nFSXmlData.Name == "d")
nXmlStartNode = nFSXmlData;
else if (nFSXmlData.SelectSingleNode("d") != null)
nXmlStartNode = nFSXmlData.SelectSingleNode("d");
else if (nFSXmlData.SelectSingleNode(".//d") != null)
nXmlStartNode = nFSXmlData.SelectSingleNode(".//d");
// starts recursive process
GetFileExtensions_Internal(
nXmlStartNode,
fileTypes);
fileTypes.Sort();
// transfers arraylist contents to string array
string[] returnedFileTypes = new string[fileTypes.Count];
for (int i = 0 ; i < fileTypes.Count ; i ++)
returnedFileTypes[i] = fileTypes[i].ToString();
return returnedFileTypes;
}
/// <summary>
/// "behind the scenes" recursive loop for public GetFileExtensions() method
/// </summary>
static private void GetFileExtensions_Internal(
XmlNode nXmlCurrentNode,
ArrayList fileTypes
)
{
string filename = "";
// process files
for (int i = 0 ; i < nXmlCurrentNode.SelectSingleNode(".//fs").ChildNodes.Count ; i ++)
{
filename = nXmlCurrentNode.SelectSingleNode(".//fs").ChildNodes[i].SelectSingleNode(".//n").InnerText;
filename = ParserLib.ReturnAfterLast(filename, ".").ToLower();
if (filename.Length > 0 && !fileTypes.Contains(filename))
fileTypes.Add(filename);
}
// process folders - recursion happens here
for (int i = 0 ; i < nXmlCurrentNode.SelectSingleNode(".//ds").ChildNodes.Count ; i ++)
GetFileExtensions_Internal(
nXmlCurrentNode.SelectSingleNode(".//ds").ChildNodes[i],
fileTypes);
}
/// <summary>
/// Returns the node from Xmlnode structure (containing valid XmlFileStructure) using
/// the specified filesystem-style path, example "c\folder\filename.extension"
/// </summary>
/// <param name="strFolderPath"></param>
static public XmlNode GetNode(
string folderPath,
XmlNode nXmlFileStructure,
NodeTypes nodeType
)
{
XmlNode nXmlCurrentNode = null;
string currentPathSection = "";
bool onFinalNode = false;
bool folderNodeFound = false;
// why is NodeType required? to prevent possible ambiguous
// references. it is possible to have identically-named file and
// folder at the same point in a file structure heirarchy. by
// specifying nodetype, we can assume that all parents to the node
// are folders, and we can be sure of the final node too
// strFolderPath Typically begins with a @ char, and the delimiter
// between path objects is \ .There is no \ at the end of the string,
// ie, the string is "unterminated"
// "terminates" strFolderPath, making it easier to parse.
// Terminator will be removed later note - termination occurs only
// if the string isn't already terminated, as happens with some
// folder references . eg - "d:\"
if (!folderPath.EndsWith("\\"))
folderPath += "\\";
// gets the "start" node. there can be several seperate xml directory
// structures in the document being scanned each stucture must have a
// unique root folder though. this assumption is used below to
// determine which dir. structure to being searching in (ie, the
// "start" node.
nXmlCurrentNode = nXmlFileStructure;
// ok, here comes a workaround ! sometimes, there might be a double
// "\\" in the string, which makes parsing it a nightmare - the
// followin removes all double "\"'s ...
folderPath = folderPath.Replace(@"\\", @"\");
// all Xml file structures begin with a folder so the first part
// of strFolderPath can now be discarded as its node has just been
// selected as the "start" node
if (folderPath.Length > folderPath.IndexOf("\\"))
folderPath = folderPath.Substring(
folderPath.IndexOf("\\") + 1, folderPath.Length - folderPath.IndexOf("\\") - 1);
else
folderPath = "";
// if strFolderPath is empty, there is no need to continue - the node
// selected up to here is all that's needed this only happens if the
// share is one folder level deep
if (folderPath.Length == 0)
return nXmlCurrentNode;
while (folderPath.Length > 0)
{
// returns everything upto and including the first \ encountered
// in string
currentPathSection = folderPath.Substring(
0, folderPath.IndexOf("\\") + 1);
// removes the currently process pathsubsection from strFolderPath
if (folderPath.Length > folderPath.IndexOf("\\"))
folderPath = folderPath.Substring(
folderPath.IndexOf("\\") + 1, folderPath.Length - folderPath.IndexOf("\\") - 1);
else
folderPath = "";
if(folderPath.Length == 0)
onFinalNode = true;
// gets the node. assumptions : if not blnOnFinalNode, assume the
// currently processed node is a folder if blnOnFinalNode, then use
// NodeType to determine what current node is
if (!onFinalNode)
{
// if reached here, then we are still looking for a folder
// must first remove the \ at end of string - TODO : perhaps
// the string should not be built up with the extra \ in the
// first place
currentPathSection = currentPathSection.Substring(
0, currentPathSection.Length - 1);
folderNodeFound = false;
for (int i = 0 ; i < nXmlCurrentNode.SelectSingleNode(".//ds").ChildNodes.Count ; i ++)
if (nXmlCurrentNode.SelectSingleNode(".//ds").ChildNodes[i].SelectSingleNode(".//n").InnerText == currentPathSection)
{
nXmlCurrentNode = nXmlCurrentNode.SelectSingleNode(".//ds").ChildNodes[i];
folderNodeFound = true;
break;
}
if (!folderNodeFound)
return null; // if reached here, the strCurrentlyPathSubSection value does not exists, so the path is invalid
}
else
{
// if here, then we are now looking for a either a file or a folder
// must first remove that / that was added to aid parsing
currentPathSection = currentPathSection.Substring(0, currentPathSection.Length - 1);
if (nodeType == NodeTypes.File)
for (int i = 0 ; i < nXmlCurrentNode.SelectSingleNode(".//fs").ChildNodes.Count ; i ++)
{
if (nXmlCurrentNode.SelectSingleNode(".//fs").ChildNodes[i].SelectSingleNode(".//n").InnerText == currentPathSection)
{
nXmlCurrentNode = nXmlCurrentNode.SelectSingleNode(".//fs").ChildNodes[i];
return nXmlCurrentNode;
}
}
else if (nodeType == NodeTypes.Folder)
for (int i = 0 ; i < nXmlCurrentNode.SelectSingleNode(".//ds").ChildNodes.Count ; i ++)
{
if (nXmlCurrentNode.SelectSingleNode(".//ds").ChildNodes[i].SelectSingleNode(".//n").InnerText == currentPathSection)
{
nXmlCurrentNode = nXmlCurrentNode.SelectSingleNode(".//ds").ChildNodes[i];
return nXmlCurrentNode;
}
}
}// if
}// while
return null;
}
/// <summary>
/// Returns the number of bytes contained in a directory
/// </summary>
/// <param name="nXmlFileStructure"></param>
/// <param name="blnRecurse">True if all sub-items size must be included</param>
/// <returns></returns>
static public long DirectoryNodeBytes(
XmlNode nXmlFileStructure,
bool recurse
)
{
long bytes = 0;
DirectoryNodeBytes_internal(
nXmlFileStructure,
recurse,
ref bytes);
return bytes;
}
/// <summary>
/// Internal method - used by DirectoryNodeBytes
/// </summary>
/// <param name="nXmlFileStructure"></param>
/// <param name="blnRecurse"></param>
/// <param name="lngBytes"></param>
/// <returns></returns>
static private void DirectoryNodeBytes_internal(
XmlNode nXmlFileStructure,
bool recurse,
ref long bytes
)
{
string strSize = "";
// 1. gets byte total for this node
for (int i = 0 ; i < nXmlFileStructure.SelectSingleNode(".//fs").ChildNodes.Count ; i ++)
{
strSize = nXmlFileStructure.SelectSingleNode(".//fs").ChildNodes[i].SelectSingleNode(".//s").InnerText;
if (strSize.Length > 0)
bytes += Convert.ToInt64(strSize);
}
// 2. processes child nodes if necessary
if (recurse)
for (int i = 0 ; i < nXmlFileStructure.SelectSingleNode(".//ds").ChildNodes.Count ; i ++)
DirectoryNodeBytes_internal(
nXmlFileStructure.SelectSingleNode(".//ds").ChildNodes[i],
true,
ref bytes);
}
/// <summary>
/// Returns the full path of the given XmlNode's filestructure item. The file name
/// of the file itself IS attached. Requires that the root node must be specified.
/// </summary>
/// <param name="dXmlItem"></param>
/// <returns></returns>
static public string GetFullPathForFile(
XmlNode dXmlItem,
XmlNode dXmlRootNode,
string delimiter
)
{
string fullPath = "";
XmlNode currentNode = null;
bool rootReached = false;
// gets file name
fullPath = delimiter + dXmlItem.SelectSingleNode(".//n").InnerText;
// checks if the xmlnode is a file under the topmost node - note, there is no need to worry about
// overshooting the documentElement with the parentnode.parentnode check, because a file item is
// always at least two nodes from the document element
if (dXmlItem.ParentNode.ParentNode == dXmlRootNode)
{
// gets parent folder name
fullPath = dXmlItem.ParentNode.ParentNode.SelectSingleNode(".//n").InnerText + fullPath;
return fullPath;
}
// "moves up" to the folder that holds the file node - the loop below works on folder nodes, not file
// nodes, so need to shift to folder node to enter loop
currentNode = dXmlItem.ParentNode.ParentNode;
fullPath = delimiter + currentNode.SelectSingleNode(".//n").InnerText + fullPath;
// typically, the supplied node, if it has a filestructure parent, will have it's parent two nodes above it
// if the node is the very first node in the filestructure hierarchy, it will be the document element
// either way, there should always be two nodes above it.
while (!rootReached)
{
// gets name of current folder node
currentNode = currentNode.ParentNode.ParentNode;
fullPath = delimiter + currentNode.SelectSingleNode(".//n").InnerText + fullPath;
if (currentNode == dXmlRootNode)
rootReached = true;
}
// removes unnecessary strDelimiter at start path string
fullPath = fullPath.Substring(delimiter.Length, fullPath.Length - delimiter.Length);
return fullPath;
}
/// <summary>
/// Returns the full path of the given XmlNode's filestructure item. The file name
/// of the file itself IS attached. Doesnt require the root node of the node
/// structure - works its way up along xml structure until runs out of valid
/// XmlFileStructure data to work with, then returns its value
/// </summary>
/// <param name="dXmlItem"></param>
/// <param name="strDelimiter"></param>
/// <returns></returns>
static public string GetFullPathForFile(
XmlNode dXmlItem,
string delimiter
)
{
string fullPath = "";
XmlNode nXmlCurrentProcessedNode = null;
bool rootReached = false;
// gets file name
fullPath = delimiter + dXmlItem.SelectSingleNode(".//n").InnerText;
// checks if the xmlnode is a file under the topmost node - note, there is no need to worry about
// overshooting the documentElement with the parentnode.parentnode check, because a file item is
// always at least two nodes from the document element
rootReached = true;
if (dXmlItem.ParentNode != null &&
dXmlItem.ParentNode.ParentNode != null &&
dXmlItem.ParentNode.ParentNode.Name == "d")
rootReached = false;
if (rootReached)
{
// gets parent folder name
fullPath = dXmlItem.ParentNode.ParentNode.SelectSingleNode(".//n").InnerText + fullPath;
return fullPath;
}
// "moves up" to the folder that holds the file node - the loop below works on folder nodes, not file
// nodes, so need to shift to folder node to enter loop
nXmlCurrentProcessedNode = dXmlItem.ParentNode.ParentNode;
fullPath = delimiter + nXmlCurrentProcessedNode.SelectSingleNode(".//n").InnerText + fullPath;
// typically, the supplied node, if it has a filestructure parent, will have it's parent two nodes above it
// if the node is the very first node in the filestructure hierarchy, it will be the document element
// either way, there should always be two nodes above it.
rootReached = false;
while (!rootReached)
{
// gets name of current folder node
rootReached = true;
if (nXmlCurrentProcessedNode.ParentNode != null &&
nXmlCurrentProcessedNode.ParentNode.ParentNode != null &&
nXmlCurrentProcessedNode.ParentNode.ParentNode.Name == "d")
rootReached = false;
if (!rootReached)
{
nXmlCurrentProcessedNode = nXmlCurrentProcessedNode.ParentNode.ParentNode;
fullPath = delimiter + nXmlCurrentProcessedNode.SelectSingleNode(".//n").InnerText + fullPath;
}
}
// removes unnecessary strDelimiter at start path string
fullPath = fullPath.Substring(delimiter.Length, fullPath.Length - delimiter.Length);
return fullPath;
}
/// <summary>
/// Returns the full path of the given XmlNode's filestructure item. The file
/// name of the folder itself IS attached. Note that this method will only work
/// with PURE XmlFileStructure data - if the the xml data is appended to any
/// accessory data, as is normal with most applications that use the Xmlflestructure
/// system, this method will NOT work, as it assumes that the root node of the file
/// structure is also the xml document element
/// </summary>
/// <param name="dXmlItem"></param>
/// <returns></returns>
static public string GetFullPathForFolder(
XmlNode dXmlItem,
XmlNode dXmlRootNode,
string delimiter
)
{
string fullPath = "";
XmlNode nXmlCurrentProcessedNode = null;
bool rootReached = false;
// handles if the node is the document element
if (dXmlItem == dXmlRootNode)
{
// gets file name
fullPath = dXmlItem.SelectSingleNode(".//n").InnerText;
return fullPath;
}
nXmlCurrentProcessedNode = dXmlItem;
fullPath = delimiter + nXmlCurrentProcessedNode.SelectSingleNode(".//n").InnerText + fullPath;
// typically, the supplied node, if it has a filestructure parent, will have it's parent two nodes above it
// if the node is the very first node in the filestructure hierarchy, it will be the document element
// either way, there should always be two nodes above it.
while (!rootReached)
{
// gets name of current folder node
nXmlCurrentProcessedNode = nXmlCurrentProcessedNode.ParentNode.ParentNode;
fullPath = delimiter + nXmlCurrentProcessedNode.SelectSingleNode(".//n").InnerText + fullPath;
if (nXmlCurrentProcessedNode == dXmlRootNode)
rootReached = true;
}
// removes unnecessary strDelimiter at start path string
fullPath = fullPath.Substring(delimiter.Length, fullPath.Length - delimiter.Length);
return fullPath;
}
/// <summary>
/// Returns the full path of the given XmlNode's filestructure item. The file name
/// of the file itself IS attached. Doesnt require the root node of the node
/// structure - works its way up along xml structure until runs out of valid
/// XmlFileStructure data to work with, then returns its value
/// </summary>
/// <param name="dXmlItem"></param>
/// <param name="strDelimiter"></param>
/// <returns></returns>
static public string GetFullPathForFolder(
XmlNode dXmlItem,
string delimiter
)
{
string fullPath = "";
XmlNode nXmlCurrentProcessedNode = null;
bool rootReached = false;
rootReached = true;
if (dXmlItem.ParentNode != null &&
dXmlItem.ParentNode.ParentNode != null &&
dXmlItem.ParentNode.ParentNode.Name == "d")
rootReached = false;
// handles if the node is the document element
if (rootReached)
{
// gets file name
fullPath = dXmlItem.SelectSingleNode(".//n").InnerText;
return fullPath;
}
nXmlCurrentProcessedNode = dXmlItem;
fullPath = delimiter + nXmlCurrentProcessedNode.SelectSingleNode(".//n").InnerText + fullPath;
// typically, the supplied node, if it has a filestructure parent, will have it's parent two nodes above it
// if the node is the very first node in the filestructure hierarchy, it will be the document element
// either way, there should always be two nodes above it.
rootReached = false;
while (!rootReached)
{
rootReached = true;
if (nXmlCurrentProcessedNode.ParentNode != null &&
nXmlCurrentProcessedNode.ParentNode.ParentNode != null &&
nXmlCurrentProcessedNode.ParentNode.ParentNode.Name == "d")
rootReached = false;
if (!rootReached)
{
// gets name of current folder node
nXmlCurrentProcessedNode = nXmlCurrentProcessedNode.ParentNode.ParentNode;
fullPath = delimiter + nXmlCurrentProcessedNode.SelectSingleNode(".//n").InnerText + fullPath;
}
}
// removes unnecessary strDelimiter at start path string
fullPath = fullPath.Substring(delimiter.Length, fullPath.Length - delimiter.Length);
return fullPath;
}
#endregion
}
}
| |
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Text;
using Rynchodon.Autopilot.Data;
using Rynchodon.Autopilot.Instruction;
using Rynchodon.Autopilot.Pathfinding;
using Rynchodon.Settings;
using Rynchodon.Update;
using Rynchodon.Utility;
using Rynchodon.Utility.Network;
using Sandbox.Game.Entities;
using Sandbox.Game.Gui;
using Sandbox.Game.Screens.Terminal.Controls;
using Sandbox.ModAPI;
using VRage.Game.ModAPI;
using VRage.ModAPI;
using VRage.Utils;
namespace Rynchodon.Autopilot
{
/// <summary>
/// Autopilot terminal controls when not using GUI programming.
/// </summary>
public class AutopilotTerminal
{
[StructLayout(LayoutKind.Explicit)]
private struct DistanceValues
{
[FieldOffset(0)]
public float LinearDistance;
[FieldOffset(4)]
public float AngularDistance;
[FieldOffset(0)]
public long PackedValue;
}
public class StaticVariables
{
public readonly MyTerminalControlCheckbox<MyShipController> autopilotControl;
public readonly MyTerminalControlTextbox<MyShipController> autopilotCommands;
public readonly ValueSync<ShipAutopilot.State, AutopilotTerminal> autopilotStatus;
public readonly ValueSync<AutopilotFlags, AutopilotTerminal> autopilotFlags;
public readonly ValueSync<Pathfinder.State, AutopilotTerminal> pathfinderState;
public readonly ValueSync<GridFinder.ReasonCannotTarget, AutopilotTerminal> reasonCannotTarget;
public readonly ValueSync<InfoString.StringId, AutopilotTerminal> complaint;
public readonly ValueSync<InfoString.StringId_Jump, AutopilotTerminal> jumpComplaint;
public readonly ValueSync<long, AutopilotTerminal> blockedBy, enemyFinderBestTarget, distance;
public readonly ValueSync<int, AutopilotTerminal> welderUnfinishedBlocks;
public readonly ValueSync<string, AutopilotTerminal> prevNavMover, prevNavRotator;
public readonly StringBuilderSync<AutopilotTerminal> prevNavMoverInfo, prevNavRotatorInfo;
public readonly ValueSync<DateTime, AutopilotTerminal> waitUntil;
public StaticVariables()
{
Logger.DebugLog("entered", Logger.severity.TRACE);
TerminalControlHelper.EnsureTerminalControlCreated<MyCockpit>();
TerminalControlHelper.EnsureTerminalControlCreated<MyRemoteControl>();
AddControl(new MyTerminalControlSeparator<MyShipController>() { Enabled = ShipAutopilot.IsAutopilotBlock, Visible = ShipAutopilot.IsAutopilotBlock });
autopilotControl = new MyTerminalControlCheckbox<MyShipController>("ArmsAp_OnOff", MyStringId.GetOrCompute("ARMS Autopilot"), MyStringId.GetOrCompute("Enable ARMS Autopilot"));
new ValueSync<bool, AutopilotTerminal>(autopilotControl, "value_autopilotControl");
AddControl(autopilotControl);
AddAction(new MyTerminalAction<MyShipController>("ArmsAp_OnOff", new StringBuilder("ARMS Autopilot On/Off"), @"Textures\GUI\Icons\Actions\Toggle.dds") { Action = ToggleAutopilotControl });
AddAction(new MyTerminalAction<MyShipController>("ArmsAp_On", new StringBuilder("ARMS Autopilot On"), @"Textures\GUI\Icons\Actions\SwitchOn.dds") { Action = block => SetAutopilotControl(block, true) });
AddAction(new MyTerminalAction<MyShipController>("ArmsAp_Off", new StringBuilder("ARMS Autopilot Off"), @"Textures\GUI\Icons\Actions\SwitchOff.dds") { Action = block => SetAutopilotControl(block, false) });
autopilotCommands = new MyTerminalControlTextbox<MyShipController>("ArmsAp_Commands", MyStringId.GetOrCompute("Autopilot Commands"), MyStringId.NullOrEmpty);
new StringBuilderSync<AutopilotTerminal>(autopilotCommands, (autopilot) => autopilot.value_autopilotCommands, (autopilot, value) => {
autopilot.value_autopilotCommands = value;
AutopilotCommands.GetOrCreate(autopilot.m_block)?.OnCommandsChanged();
});
AddControl(autopilotCommands);
MyTerminalControlButton<MyShipController> gooeyProgram = new MyTerminalControlButton<MyShipController>("ArmsAp_GuiProgram", MyStringId.GetOrCompute("Program Autopilot"), MyStringId.GetOrCompute("Interactive programming for autopilot"), GooeyProgram);
gooeyProgram.Enabled = ShipAutopilot.IsAutopilotBlock;
AddControl(gooeyProgram);
AddPropertyAndSync<ShipAutopilot.State, Enum>("ArmsAp_Status", out autopilotStatus, "value_autopilotStatus");
FieldInfo value_autopilotFlags = typeof(AutopilotTerminal).GetField("value_autopilotFlags", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
autopilotFlags = new ValueSync<AutopilotFlags, AutopilotTerminal>("ArmsAp_AutopilotFlags", GenerateGetter<AutopilotFlags>(value_autopilotFlags), GenerateSetter<AutopilotFlags>(value_autopilotFlags), false);
foreach (AutopilotFlags flag in Enum.GetValues(typeof(AutopilotFlags)))
if (flag != 0)
AddPropertyAndSync(flag);
AddPropertyAndSync<Pathfinder.State, Enum>("ArmsAp_PathStatus", out pathfinderState, "value_pathfinderState");
AddPropertyAndSync<GridFinder.ReasonCannotTarget, Enum>("ArmsAp_ReasonCannotTarget", out reasonCannotTarget, "value_reasonCannotTarget");
AddPropertyAndSync<InfoString.StringId, Enum>("ArmsAp_Complaint", out complaint, "value_complaint");
AddPropertyAndSync<InfoString.StringId_Jump, Enum>("ArmsAp_JumpComplaint", out jumpComplaint, "value_jumpComplaint");
AddPropertyAndSync("ArmsAp_WaitUntil", out waitUntil, "value_waitUntil");
AddPropertyAndSyncEntityId("ArmsAp_BlockedBy", out blockedBy, "value_blockedBy");
FieldInfo value_distance = typeof(AutopilotTerminal).GetField("value_distance", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
distance = new ValueSync<long, AutopilotTerminal>("ArmsAp_Distance", GenerateGetter<long>(value_distance), GenerateSetter<long>(value_distance), false);
MyTerminalControlProperty<MyShipController, float> linearDistance = new MyTerminalControlProperty<MyShipController, float>("ArmsAp_LinearDistance") { Getter = GetLinearDistance };
AddControl(linearDistance, false);
MyTerminalControlProperty<MyShipController, float> angularDistance = new MyTerminalControlProperty<MyShipController, float>("ArmsAp_AngularDistance") { Getter = GetAngularDistance };
AddControl(angularDistance, false);
AddPropertyAndSyncEntityId("ArmsAp_EnemyFinderBestTarget", out enemyFinderBestTarget, "value_enemyFinderBestTarget");
AddPropertyAndSync("ArmsAp_WelderUnfinishedBlocks", out welderUnfinishedBlocks, "value_welderUnfinishedBlocks");
AddPropertyAndSync("ArmsAp_NavigatorMover", out prevNavMover, "value_prevNavMover");
AddPropertyAndSync("ArmsAp_NavigatorRotator", out prevNavRotator, "value_prevNavRotator");
AddPropertyAndSync("ArmsAp_NavigatorMoverInfo", out prevNavMoverInfo, "value_prevNavMoverInfo");
AddPropertyAndSync("ArmsAp_NavigatorRotatorInfo", out prevNavRotatorInfo, "value_prevNavRotatorInfo");
}
}
public static StaticVariables Static { get; private set; }
[OnWorldLoad]
private static void Load()
{
Static = new StaticVariables();
}
[OnWorldClose]
private static void Unload()
{
Static = null;
}
private static void AddControl(MyTerminalControl<MyShipController> control, bool visible = true)
{
control.Enabled = ShipAutopilot.IsAutopilotBlock;
if (visible)
control.Visible = ShipAutopilot.IsAutopilotBlock;
else
control.Visible = False;
MyTerminalControlFactory.AddControl<MyShipController, MyCockpit>(control);
if (ServerSettings.GetSetting<bool>(ServerSettings.SettingName.bUseRemoteControl))
MyTerminalControlFactory.AddControl<MyShipController, MyRemoteControl>(control);
}
private static void AddAction(MyTerminalAction<MyShipController> action)
{
action.Enabled = ShipAutopilot.IsAutopilotBlock;
MyTerminalControlFactory.AddAction<MyShipController, MyCockpit>(action);
if (ServerSettings.GetSetting<bool>(ServerSettings.SettingName.bUseRemoteControl))
MyTerminalControlFactory.AddAction<MyShipController, MyRemoteControl>(action);
}
private static AValueSync<T, AutopilotTerminal>.GetterDelegate GenerateGetter<T>(FieldInfo field)
{
DynamicMethod getter = new DynamicMethod(field.DeclaringType.Name + ".get_" + field.Name, field.FieldType, new Type[] { typeof(AutopilotTerminal) }, true);
ILGenerator il = getter.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, field);
il.Emit(OpCodes.Ret);
return (AValueSync<T, AutopilotTerminal>.GetterDelegate)getter.CreateDelegate(typeof(AValueSync<T, AutopilotTerminal>.GetterDelegate));
}
private static AValueSync<T, AutopilotTerminal>.SetterDelegate GenerateSetter<T>(FieldInfo field)
{
FieldInfo m_block = typeof(AutopilotTerminal).GetField("m_block", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (m_block == null)
throw new NullReferenceException("m_block");
MethodInfo UpdateCustomInfo = typeof(IMyTerminalBlockExtensions).GetMethod("UpdateCustomInfo");
if (UpdateCustomInfo == null)
throw new NullReferenceException("UpdateCustomInfo");
DynamicMethod setter = new DynamicMethod(field.DeclaringType.Name + ".set_" + field.Name, null, new Type[] { typeof(AutopilotTerminal), typeof(T) }, true);
ILGenerator il = setter.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Stfld, field);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, m_block);
il.Emit(OpCodes.Call, UpdateCustomInfo);
il.Emit(OpCodes.Ret);
return (AValueSync<T, AutopilotTerminal>.SetterDelegate)setter.CreateDelegate(typeof(AValueSync<T, AutopilotTerminal>.SetterDelegate));
}
private static void AddPropertyAndSync(AutopilotFlags flag)
{
MyTerminalControlProperty<MyShipController, bool> property = new MyTerminalControlProperty<MyShipController, bool>("ArmsAp_" + flag);
property.Getter = (block) => {
AutopilotTerminal autopilot;
if (!Registrar.TryGetValue(block, out autopilot))
{
if (!Globals.WorldClosed)
Logger.AlwaysLog("failed lookup of block: " + block.getBestName(), Logger.severity.WARNING);
return default(bool);
}
return (autopilot.value_autopilotFlags & flag) != 0;
};
AddControl(property, false);
}
private static void AddPropertyAndSync<T>(string id, out ValueSync<T, AutopilotTerminal> sync, string fieldName)
{
MyTerminalControlProperty<MyShipController, T> property = new MyTerminalControlProperty<MyShipController, T>(id);
FieldInfo field = typeof(AutopilotTerminal).GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
sync = new ValueSync<T, AutopilotTerminal>(id, GenerateGetter<T>(field), GenerateSetter<T>(field), false);
ValueSync<T, AutopilotTerminal> syncRef = sync;
property.Getter = syncRef.GetValue;
AddControl(property, false);
}
private static void AddPropertyAndSync(string id, out StringBuilderSync<AutopilotTerminal> sync, string fieldName)
{
MyTerminalControlProperty<MyShipController, StringBuilder> property = new MyTerminalControlProperty<MyShipController, StringBuilder>(id);
FieldInfo field = typeof(AutopilotTerminal).GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
sync = new StringBuilderSync<AutopilotTerminal>(id, GenerateGetter<StringBuilder>(field), GenerateSetter<StringBuilder>(field), false);
StringBuilderSync<AutopilotTerminal> syncRef = sync;
property.Getter = syncRef.GetValue;
AddControl(property, false);
}
private static void AddPropertyAndSync<TSync, TYield>(string id, out ValueSync<TSync, AutopilotTerminal> sync, string fieldName)
where TSync : TYield
{
MyTerminalControlProperty<MyShipController, TYield> property = new MyTerminalControlProperty<MyShipController, TYield>(id);
FieldInfo field = typeof(AutopilotTerminal).GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
sync = new ValueSync<TSync, AutopilotTerminal>(id, GenerateGetter<TSync>(field), GenerateSetter<TSync>(field), false);
ValueSync<TSync, AutopilotTerminal> syncRef = sync;
property.Getter = (block) => syncRef.GetValue(block);
AddControl(property, false);
}
private static void AddPropertyAndSyncEntityId(string id, out ValueSync<long, AutopilotTerminal> sync, string fieldName)
{
MyTerminalControlProperty<MyShipController, string> property = new MyTerminalControlProperty<MyShipController, string>(id);
FieldInfo field = typeof(AutopilotTerminal).GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
sync = new ValueSync<long, AutopilotTerminal>(id, GenerateGetter<long>(field), GenerateSetter<long>(field), false);
ValueSync<long, AutopilotTerminal> syncRef = sync;
property.Getter = (block) => {
AutopilotTerminal autopilot;
if (!Registrar.TryGetValue(block, out autopilot))
{
if (!Globals.WorldClosed)
Logger.AlwaysLog("failed lookup of block: " + block.getBestName(), Logger.severity.WARNING);
return default(string);
}
long entityId = syncRef.GetValue(autopilot);
IMyEntity entity;
if (!MyAPIGateway.Entities.TryGetEntityById(entityId, out entity))
{
Logger.DebugLog("Failed to get entity for " + entityId, Logger.severity.WARNING);
return "Unknown Entity";
}
return entity.GetNameForDisplay(autopilot.m_block.OwnerId);
};
AddControl(property, false);
}
private static bool False(IMyCubeBlock block)
{
return false;
}
private static float GetLinearDistance(IMyTerminalBlock block)
{
AutopilotTerminal autopilot;
if (!Registrar.TryGetValue(block, out autopilot))
{
Logger.AlwaysLog("Failed lookup of block: " + block.getBestName(), Logger.severity.WARNING);
return 0f;
}
return autopilot.LinearDistance;
}
private static float GetAngularDistance(IMyTerminalBlock block)
{
AutopilotTerminal autopilot;
if (!Registrar.TryGetValue(block, out autopilot))
{
Logger.AlwaysLog("Failed lookup of block: " + block.getBestName(), Logger.severity.WARNING);
return 0f;
}
return autopilot.AngularDistance;
}
private static void SetAutopilotControl(IMyTerminalBlock block, bool value)
{
AutopilotTerminal autopilot;
if (!Registrar.TryGetValue(block, out autopilot))
{
Logger.AlwaysLog("Failed lookup of block: " + block.getBestName(), Logger.severity.WARNING);
return;
}
autopilot.AutopilotControlSwitch = value;
}
private static void ToggleAutopilotControl(IMyTerminalBlock block)
{
AutopilotTerminal autopilot;
if (!Registrar.TryGetValue(block, out autopilot))
{
Logger.AlwaysLog("Failed lookup of block: " + block.getBestName(), Logger.severity.WARNING);
return;
}
autopilot.AutopilotControlSwitch = !autopilot.AutopilotControlSwitch;
}
public static StringBuilder GetAutopilotCommands(IMyTerminalBlock block)
{
AutopilotTerminal autopilot;
if (!Registrar.TryGetValue(block, out autopilot))
{
Logger.AlwaysLog("Failed lookup of block: " + block.getBestName(), Logger.severity.WARNING);
return new StringBuilder();
}
return autopilot.AutopilotCommandsText;
}
public static void SetAutopilotCommands(IMyTerminalBlock block, StringBuilder value)
{
AutopilotTerminal autopilot;
if (!Registrar.TryGetValue(block, out autopilot))
{
Logger.AlwaysLog("Failed lookup of block: " + block.getBestName(), Logger.severity.WARNING);
return;
}
autopilot.AutopilotCommandsText = value;
}
public static void GooeyProgram(MyShipController block)
{
AutopilotCommands cmds = AutopilotCommands.GetOrCreate(block);
if (cmds != null)
cmds.StartGooeyProgramming();
}
private static string GetNameForDisplay(AutopilotTerminal autopilot, long entityId)
{
IMyEntity entity;
if (!MyAPIGateway.Entities.TryGetEntityById(entityId, out entity))
{
Logger.DebugLog("Failed to get entity for " + entityId, Logger.severity.WARNING);
return "Unknown Entity";
}
return entity.GetNameForDisplay(autopilot.m_block.OwnerId);
}
public readonly IMyTerminalBlock m_block;
private bool value_waitUpdate;
private bool WaitingNeedsUpdate
{
get { return value_waitUpdate; }
set
{
if (value == value_waitUpdate)
return;
value_waitUpdate = value;
if (value_waitUpdate)
UpdateManager.Register(10u, RefreshWhileWaiting);
else
UpdateManager.Unregister(10u, RefreshWhileWaiting);
}
}
private Sandbox.Game.EntityComponents.MyResourceSinkComponent ResourceSink { get { return ((MyCubeBlock)m_block).ResourceSink; } }
private Logable Log { get { return new Logable(m_block); } }
#region Terminal Controls
#pragma warning disable CS0649
private bool value_autopilotControl;
public bool AutopilotControlSwitch
{
get { return value_autopilotControl; }
set { Static.autopilotControl.SetValue(m_block, value); }
}
private StringBuilder value_autopilotCommands;
public StringBuilder AutopilotCommandsText
{
get { return value_autopilotCommands; }
set { Static.autopilotCommands.SetValue(m_block, value); }
}
#endregion Terminal Controls
#region Terminal Properties
[Flags]
public enum AutopilotFlags : byte
{
None = 0,
HasControl = 1,
//MovementBlocked = 2,
RotationBlocked = 4,
EnemyFinderIssue = 8,
HasNavigatorMover = 16,
HasNavigatorRotator = 32,
}
private ShipAutopilot.State value_autopilotStatus;
public ShipAutopilot.State m_autopilotStatus
{
get { return value_autopilotStatus; }
set { Static.autopilotStatus.SetValue(m_block, value); }
}
private AutopilotFlags value_autopilotFlags;
public AutopilotFlags m_autopilotFlags
{
get { return value_autopilotFlags; }
set { Static.autopilotFlags.SetValue(m_block, value); }
}
private Pathfinder.State value_pathfinderState;
public Pathfinder.State m_pathfinderState
{
get { return value_pathfinderState; }
set { Static.pathfinderState.SetValue(m_block, value); }
}
private GridFinder.ReasonCannotTarget value_reasonCannotTarget;
public GridFinder.ReasonCannotTarget m_reasonCannotTarget
{
get { return value_reasonCannotTarget; }
set { Static.reasonCannotTarget.SetValue(m_block, value); }
}
private InfoString.StringId value_complaint;
public InfoString.StringId m_complaint
{
get { return value_complaint; }
set { Static.complaint.SetValue(m_block, value); }
}
private InfoString.StringId_Jump value_jumpComplaint;
public InfoString.StringId_Jump m_jumpComplaint
{
get { return value_jumpComplaint; }
set { Static.jumpComplaint.SetValue(m_block, value); }
}
private long value_blockedBy;
public long m_blockedBy
{
get { return value_blockedBy; }
set { Static.blockedBy.SetValue(m_block, value); }
}
private long value_enemyFinderBestTarget;
public long m_enemyFinderBestTarget
{
get { return value_enemyFinderBestTarget; }
set { Static.enemyFinderBestTarget.SetValue(m_block, value); }
}
private int value_welderUnfinishedBlocks;
public int m_welderUnfinishedBlocks
{
get { return value_welderUnfinishedBlocks; }
set { Static.welderUnfinishedBlocks.SetValue(m_block, value); }
}
private string value_prevNavMover;
public string m_prevNavMover
{
get { return value_prevNavMover; }
set { Static.prevNavMover.SetValue(m_block, value); }
}
private string value_prevNavRotator;
public string m_prevNavRotator
{
get { return value_prevNavRotator; }
set { Static.prevNavRotator.SetValue(m_block, value); }
}
private StringBuilder value_prevNavMoverInfo;
public StringBuilder m_prevNavMoverInfo
{
get { return value_prevNavMoverInfo; }
set { Static.prevNavMoverInfo.SetValue(m_block, value); }
}
private StringBuilder value_prevNavRotatorInfo;
public StringBuilder m_prevNavRotatorInfo
{
get { return value_prevNavRotatorInfo; }
set { Static.prevNavRotatorInfo.SetValue(m_block, value); }
}
private DateTime value_waitUntil;
private DateTime m_waitUntil
{
get { return value_waitUntil; }
set { Static.waitUntil.SetValue(m_block, value); }
}
private long value_distance;
private long m_distance
{
get { return value_distance; }
set { Static.distance.SetValue(m_block, value); }
}
public float LinearDistance { get { return new DistanceValues() { PackedValue = m_distance }.LinearDistance; } }
public float AngularDistance { get { return new DistanceValues() { PackedValue = m_distance }.AngularDistance; } }
public void SetDistance(float linear, float angular)
{
DistanceValues dv = new DistanceValues() { PackedValue = m_distance };
if (Math.Abs(linear / dv.LinearDistance - 1f) > 0.01f || Math.Abs(angular / dv.AngularDistance - 1f) > 0.01f)
m_distance = new DistanceValues() { LinearDistance = linear, AngularDistance = angular }.PackedValue;
}
public void SetWaitUntil(TimeSpan waitUntil)
{
DateTime newValue = DateTime.UtcNow + waitUntil - Globals.ElapsedTime;
if (Math.Abs((m_waitUntil - newValue).Ticks) > TimeSpan.TicksPerSecond)
m_waitUntil = newValue;
}
#pragma warning restore CS0649
#endregion Terminal Properties
public AutopilotTerminal(IMyCubeBlock block)
{
this.m_block = (IMyTerminalBlock)block;
m_block.AppendingCustomInfo += AppendingCustomInfo;
Registrar.Add(block, this);
Log.DebugLog("Initialized", Logger.severity.INFO);
}
public void AppendingCustomInfo(IMyTerminalBlock block, StringBuilder customInfo)
{
ResourceSink.SetRequiredInputByType(Globals.Electricity, m_autopilotStatus == ShipAutopilot.State.Enabled ? m_waitUntil < DateTime.UtcNow ? 0.1f : 0.01f : 0.001f);
AppendingCustomInfo(customInfo);
}
public void AppendingCustomInfo(StringBuilder customInfo)
{
AppendMain(customInfo);
// power
customInfo.Append("Current Input: ");
customInfo.Append(PrettySI.makePretty(ResourceSink.RequiredInputByType(Globals.Electricity) * 1e6f));
customInfo.AppendLine("W");
}
private void AppendMain(StringBuilder customInfo)
{
if (m_autopilotStatus == ShipAutopilot.State.Halted)
{
if (MyAPIGateway.Multiplayer.IsServer)
customInfo.AppendLine("Autopilot crashed, please upload log files and report on steam page");
else
customInfo.AppendLine("Autopilot crashed, please upload server's log files and report on steam page");
return;
}
if (m_pathfinderState == Pathfinder.State.Crashed)
{
if (MyAPIGateway.Multiplayer.IsServer)
customInfo.AppendLine("Pathfinder crashed, please upload log files and report on steam page");
else
customInfo.AppendLine("Pathfinder crashed, please upload server's log files and report on steam page");
return;
}
if (!HasFlag(AutopilotFlags.HasControl))
{
if (m_autopilotStatus == ShipAutopilot.State.Disabled)
customInfo.AppendLine("Disabled");
else if (m_block.CubeGrid.IsStatic)
customInfo.AppendLine("Grid is a station");
else if (!m_block.IsWorking)
customInfo.AppendLine("Not working");
else
{
MyCubeGrid mcg = (MyCubeGrid)m_block.CubeGrid;
if (mcg.HasMainCockpit() && !((MyShipController)m_block).IsMainCockpit)
customInfo.AppendLine("Not main cockpit");
else
customInfo.AppendLine("Does not have control of ship");
}
return;
}
if (m_waitUntil > DateTime.UtcNow)
{
WaitingNeedsUpdate = true;
customInfo.Append("Waiting for ");
customInfo.AppendLine(PrettySI.makePretty(m_waitUntil - DateTime.UtcNow));
return;
}
else
WaitingNeedsUpdate = false;
IMyPlayer controlling = MyAPIGateway.Players.GetPlayerControllingEntity(m_block.CubeGrid);
if (controlling != null)
{
customInfo.Append("Player controlling: ");
customInfo.AppendLine(controlling.DisplayName);
AppendingCustomInfo_EnemyFinder(customInfo);
return;
}
// pathfinder
switch (m_pathfinderState)
{
case Pathfinder.State.SearchingForPath:
customInfo.Append("Searching for path around ");
customInfo.AppendLine(GetNameForDisplay(this, m_blockedBy));
break;
case Pathfinder.State.FollowingPath:
customInfo.Append("Following path around ");
customInfo.AppendLine(GetNameForDisplay(this, m_blockedBy));
break;
case Pathfinder.State.FailedToFindPath:
customInfo.Append("No path around ");
customInfo.AppendLine(GetNameForDisplay(this, m_blockedBy));
break;
default:
if (HasFlag(AutopilotFlags.RotationBlocked))
{
customInfo.Append("Rotation blocked by ");
customInfo.AppendLine(GetNameForDisplay(this, m_blockedBy));
}
break;
}
// nav mover info
if (HasFlag(AutopilotFlags.HasNavigatorMover))
{
float linear = LinearDistance;
if (linear.ValidNonZero())
{
customInfo.Append(m_prevNavMoverInfo);
customInfo.Append("Distance: ");
customInfo.Append(PrettySI.makePretty(LinearDistance));
customInfo.AppendLine("m");
}
}
// nav rotator info
if (HasFlag(AutopilotFlags.HasNavigatorRotator))
{
float angular = AngularDistance;
if (angular.ValidNonZero())
{
customInfo.Append(m_prevNavRotatorInfo);
customInfo.Append("Angle: ");
customInfo.Append(PrettySI.toSigFigs(AngularDistance));
customInfo.AppendLine(" rad");
}
}
// enemy finder
AppendingCustomInfo_EnemyFinder(customInfo);
// complaint
InfoString.StringId ids = m_complaint;
if (ids != InfoString.StringId.None)
foreach (InfoString.StringId flag in InfoString.AllStringIds())
if ((ids & flag) != 0)
customInfo.AppendLine(InfoString.GetString(flag));
InfoString.StringId_Jump jc = m_jumpComplaint;
if (jc != InfoString.StringId_Jump.None)
customInfo.AppendLine(InfoString.GetString(jc));
return;
}
private void AppendingCustomInfo_EnemyFinder(StringBuilder customInfo)
{
if (HasFlag(AutopilotFlags.EnemyFinderIssue))
{
switch (m_reasonCannotTarget)
{
case GridFinder.ReasonCannotTarget.None:
customInfo.AppendLine("No enemy detected");
break;
case GridFinder.ReasonCannotTarget.Too_Far:
customInfo.Append(GetNameForDisplay(this, m_enemyFinderBestTarget));
customInfo.AppendLine(" is too far");
break;
case GridFinder.ReasonCannotTarget.Too_Fast:
customInfo.Append(GetNameForDisplay(this, m_enemyFinderBestTarget));
customInfo.AppendLine(" is too fast");
break;
case GridFinder.ReasonCannotTarget.Grid_Condition:
customInfo.Append(GetNameForDisplay(this, m_enemyFinderBestTarget));
customInfo.AppendLine(" cannot be targeted");
break;
}
}
}
private bool HasFlag(AutopilotFlags flag)
{
return (m_autopilotFlags & flag) != 0;
}
private void RefreshWhileWaiting()
{
if (m_block.Closed)
{
WaitingNeedsUpdate = false;
return;
}
m_block.UpdateCustomInfo();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftRightArithmeticInt3232()
{
var test = new SimpleUnaryOpTest__ShiftRightArithmeticInt3232();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ShiftRightArithmeticInt3232
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Int32);
private const int RetElementCount = VectorSize / sizeof(Int32);
private static Int32[] _data = new Int32[Op1ElementCount];
private static Vector256<Int32> _clsVar;
private Vector256<Int32> _fld;
private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable;
static SimpleUnaryOpTest__ShiftRightArithmeticInt3232()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ShiftRightArithmeticInt3232()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.ShiftRightArithmetic(
Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.ShiftRightArithmetic(
Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.ShiftRightArithmetic(
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightArithmetic), new Type[] { typeof(Vector256<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightArithmetic), new Type[] { typeof(Vector256<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightArithmetic), new Type[] { typeof(Vector256<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.ShiftRightArithmetic(
_clsVar,
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftRightArithmetic(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightArithmetic(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightArithmetic(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ShiftRightArithmeticInt3232();
var result = Avx2.ShiftRightArithmetic(test._fld, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.ShiftRightArithmetic(_fld, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Int32> firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
if ((int)(firstOp[0] >> 31) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((int)(firstOp[i] >> 31) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightArithmetic)}<Int32>(Vector256<Int32><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
#region Copyright (c) 2006-2008, Nate Zobrist
/*
* Copyright (c) 2006-2008, Nate Zobrist
* 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 "Nate Zobrist" nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion Copyright (c) 2006-2008, Nate Zobrist
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Xml;
namespace Delicious
{
public static class Connection
{
private static string _Username;
private static string _Password;
private static int _MaxRetries = Constants.MaxRetries;
private static int _TimeOut = Constants.DefaultTimeOut;
private static string _ApiBaseUrl;
private static DateTime lastConnectTime = DateTime.MinValue;
/// <summary>
/// Connect to the del.icio.us API, returning an <c>XmlDocument</c> of the response
/// </summary>
/// <param name="relativeUrl">Constant defined in <c>Delicious.Constants.RelativeUrl</c></param>
/// <returns>XmlDocument containing data from the del.icio.us api call</returns>
internal static XmlDocument Connect (string relativeUrl)
{
System.Xml.XmlDocument xmlDoc;
try
{
xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml (GetRawXml (relativeUrl));
}
catch (XmlException)
{
throw new Exceptions.DeliciousException ("The webserver did not return valid XML.");
}
return xmlDoc;
}
/// <summary>
/// Connect to the del.icio.us API, returning the raw xml response
/// </summary>
/// <param name="relativeUrl">Constant defined in <c>Delicious.Constants.RelativeUrl</c></param>
/// <returns>string containing raw xml data from the del.icio.us api call</returns>
internal static string GetRawXml (string relativeUrl)
{
return GetRawXml (relativeUrl, 0);
}
/// <summary>
/// Connect to the del.icio.us API.
/// Per instructions on the api site, don't allow queries more than once per second.
/// </summary>
/// <param name="relativeUrl">Constant defined in <c>Delicious.Constants.RelativeUrl</c></param>
/// <param name="callCount">Beginning at 0, this number should be incremented by one each time the method
/// is recursively called due to a Timeout error. The increased number will increase the forced delay
/// in contacting the del.icio.us servers.</param>
/// <returns>XmlDocument containing data from the del.icio.us api call</returns>
private static string GetRawXml (string relativeUrl, int callCount)
{
int millisecondsBetweenQueries = Constants.MinimumMillisecondsBetweenQueries +
(1000 * callCount * callCount);
string fullUrl = ApiBaseUrl + relativeUrl;
string rawXml;
TimeSpan span = System.DateTime.Now - lastConnectTime.AddMilliseconds (millisecondsBetweenQueries);
if (span.TotalMilliseconds < 0)
Thread.Sleep (Math.Abs ((int)span.TotalMilliseconds));
HttpWebResponse response = null;
StreamReader readStream = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (fullUrl);
request.Credentials = new System.Net.NetworkCredential (Username, Password);
request.Timeout = TimeOut;
request.AllowAutoRedirect = false;
request.UserAgent = Constants.UserAgentValue;
request.MaximumResponseHeadersLength = 4;
request.KeepAlive = false;
request.Pipelined = false;
response = (HttpWebResponse)request.GetResponse ();
Stream receiveStream = response.GetResponseStream ();
readStream = new StreamReader (receiveStream, Encoding.UTF8);
rawXml = readStream.ReadToEnd ();
lastConnectTime = System.DateTime.Now;
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError ||
e.Status == WebExceptionStatus.Timeout)
{
HttpWebResponse webResponse = e.Response as HttpWebResponse;
if (webResponse != null)
{
// del.icio.us servers seem to have less-than-ideal response times quite often.
// we try to compensate for those probelms, but eventually error out.
if (e.Status == WebExceptionStatus.Timeout ||
webResponse.StatusCode == HttpStatusCode.ServiceUnavailable /*503 we have been throttled*/||
(int)webResponse.StatusCode == 999 /*Unable to process request at this time*/)
{
if (callCount < MaxRetries) // don't loop endlessly here, eventually just error out
return GetRawXml (relativeUrl, callCount + 1);
else
throw new Exceptions.DeliciousTimeoutException (String.Format ("The server is not responding.\t{0}", webResponse.StatusCode));
}
else if (webResponse.StatusCode == HttpStatusCode.Unauthorized /*401*/)
{
throw new Exceptions.DeliciousNotAuthorizedException ("Invalid username/password combination");
}
else
{
throw new Exceptions.DeliciousException (webResponse.StatusCode.ToString ());
}
}
}
throw new Exceptions.DeliciousException (e.Status.ToString ());
}
catch (IOException e)
{
// Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
throw new Exceptions.DeliciousTimeoutException (e.ToString ());
}
finally
{
if (response != null)
response.Close();
if (readStream != null)
readStream.Close();
}
return rawXml;
}
/// <summary>
/// Gets or sets the API base URL.
/// </summary>
/// <value>The API base URL.</value>
public static string ApiBaseUrl
{
get
{
if (_ApiBaseUrl == null || _ApiBaseUrl.Length == 0)
return Constants.ApiBaseUrl;
return _ApiBaseUrl;
}
set
{
_ApiBaseUrl = value;
// a bunch of stuff depeneds on this already having the trailing slash
if (!_ApiBaseUrl.EndsWith ("/"))
_ApiBaseUrl += "/";
}
}
/// <summary>
/// Gets or sets the username.
/// </summary>
/// <value>The username.</value>
public static string Username
{
get { return _Username; }
set
{
if (_Username == value)
return;
_Username = value;
}
}
/// <summary>
/// Gets or sets the password.
/// </summary>
/// <value>The password.</value>
public static string Password
{
get { return _Password; }
set
{
if (_Password == value)
return;
_Password = value;
}
}
/// <summary>
/// Gets or sets the max retries.
/// </summary>
/// <value>The max retries.</value>
public static int MaxRetries
{
get { return _MaxRetries; }
set { _MaxRetries = (value < 0) ? 0 : value; }
}
/// <summary>
/// Gets or sets the time out.
/// </summary>
/// <value>The time out.</value>
public static int TimeOut
{
get { return _TimeOut; }
set { _TimeOut = (value < 0) ? Constants.DefaultTimeOut : value; }
}
/// <summary>
/// Gets the time of the last update to the del.icio.us account
/// </summary>
/// <returns>Returns a DateTime representing the last update time or DateTime.MinValue if there was an error</returns>
public static DateTime LastUpdated ()
{
DateTime lastUpdated = DateTime.MinValue;
System.Xml.XmlDocument xmlDoc = Connection.Connect (Constants.RelativeUrl.PostsUpdate);
if (xmlDoc == null)
return DateTime.MinValue;
XmlElement xmlElement = xmlDoc[ Constants.XmlTag.Update ];
if (xmlElement != null)
{
string time = xmlElement.GetAttribute (Constants.XmlAttribute.Time);
try
{
lastUpdated = DateTime.Parse (time, CultureInfo.InvariantCulture);
}
catch (FormatException e)
{
Debug.Fail (e.ToString ());
}
}
return lastUpdated;
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Archimedes.Web.Models;
namespace Archimedes.Web.Controllers
{
[HandleError]
public class AccountController : Controller
{
// This constructor is used by the MVC framework to instantiate the controller using
// the default forms authentication and membership providers.
public AccountController()
: this(null, null)
{
}
// This constructor is not used by the MVC framework but is instead provided for ease
// of unit testing this type. See the comments in AccountModels.cs for more information.
public AccountController(IFormsAuthenticationService formsService, IMembershipService membershipService)
{
FormsService = formsService ?? new FormsAuthenticationService();
MembershipService = membershipService ?? new AccountMembershipService();
}
public IFormsAuthenticationService FormsService
{
get;
private set;
}
public IMembershipService MembershipService
{
get;
private set;
}
protected override void Initialize(RequestContext requestContext)
{
if (requestContext.HttpContext.User.Identity is WindowsIdentity)
{
throw new InvalidOperationException("Windows authentication is not supported.");
}
else
{
base.Initialize(requestContext);
}
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
base.OnActionExecuting(filterContext);
}
[Authorize]
public ActionResult ChangePassword()
{
return View();
}
[Authorize]
[HttpPost]
public ActionResult ChangePassword(ChangePasswordModel model)
{
if (ModelState.IsValid)
{
if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
{
return RedirectToAction("ChangePasswordSuccess");
}
else
{
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
public ActionResult ChangePasswordSuccess()
{
return View();
}
public ActionResult LogOff()
{
FormsService.SignOut();
return RedirectToAction("Index", "Home");
}
public ActionResult LogOn()
{
return View();
}
[HttpPost]
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
Justification = "Needs to take same parameter type as Controller.Redirect()")]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
FormsService.SignIn(model.UserName, model.RememberMe);
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);
if (createStatus == MembershipCreateStatus.Success)
{
FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
private static string ErrorCodeToString(MembershipCreateStatus createStatus)
{
// See http://go.microsoft.com/fwlink/?LinkID=177550 for
// a full list of status codes.
switch (createStatus)
{
case MembershipCreateStatus.DuplicateUserName:
return "Username already exists. Please enter a different user name.";
case MembershipCreateStatus.DuplicateEmail:
return "A username for that e-mail address already exists. Please enter a different e-mail address.";
case MembershipCreateStatus.InvalidPassword:
return "The password provided is invalid. Please enter a valid password value.";
case MembershipCreateStatus.InvalidEmail:
return "The e-mail address provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidAnswer:
return "The password retrieval answer provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidQuestion:
return "The password retrieval question provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidUserName:
return "The user name provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.ProviderError:
return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
case MembershipCreateStatus.UserRejected:
return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
default:
return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ChangeSignature;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ChangeSignature
{
[ExportLanguageService(typeof(AbstractChangeSignatureService), LanguageNames.CSharp), Shared]
internal sealed class CSharpChangeSignatureService : AbstractChangeSignatureService
{
public override async Task<ISymbol> GetInvocationSymbolAsync(
Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken)
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var token = tree.GetRoot(cancellationToken).FindToken(position != tree.Length ? position : Math.Max(0, position - 1));
var ancestorDeclarationKinds = restrictToDeclarations ? _invokableAncestorKinds.Add(SyntaxKind.Block) : _invokableAncestorKinds;
SyntaxNode matchingNode = token.Parent.AncestorsAndSelf().FirstOrDefault(n => ancestorDeclarationKinds.Contains(n.Kind()));
if (matchingNode == null || matchingNode.IsKind(SyntaxKind.Block))
{
return null;
}
ISymbol symbol;
var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken);
symbol = semanticModel.GetDeclaredSymbol(matchingNode, cancellationToken);
if (symbol != null)
{
return symbol;
}
if (matchingNode.IsKind(SyntaxKind.ObjectCreationExpression))
{
var objectCreation = matchingNode as ObjectCreationExpressionSyntax;
if (token.Parent.AncestorsAndSelf().Any(a => a == objectCreation.Type))
{
var typeSymbol = semanticModel.GetSymbolInfo(objectCreation.Type, cancellationToken).Symbol;
if (typeSymbol != null && typeSymbol.IsKind(SymbolKind.NamedType) && (typeSymbol as ITypeSymbol).TypeKind == TypeKind.Delegate)
{
return typeSymbol;
}
}
}
var symbolInfo = semanticModel.GetSymbolInfo(matchingNode, cancellationToken);
return symbolInfo.Symbol ?? symbolInfo.CandidateSymbols.FirstOrDefault();
}
private ImmutableArray<SyntaxKind> _invokableAncestorKinds = new[]
{
SyntaxKind.MethodDeclaration,
SyntaxKind.ConstructorDeclaration,
SyntaxKind.IndexerDeclaration,
SyntaxKind.InvocationExpression,
SyntaxKind.ElementAccessExpression,
SyntaxKind.ThisConstructorInitializer,
SyntaxKind.BaseConstructorInitializer,
SyntaxKind.ObjectCreationExpression,
SyntaxKind.Attribute,
SyntaxKind.NameMemberCref,
SyntaxKind.SimpleLambdaExpression,
SyntaxKind.ParenthesizedLambdaExpression,
SyntaxKind.DelegateDeclaration
}.ToImmutableArray();
private ImmutableArray<SyntaxKind> _updatableAncestorKinds = new[]
{
SyntaxKind.ConstructorDeclaration,
SyntaxKind.IndexerDeclaration,
SyntaxKind.InvocationExpression,
SyntaxKind.ElementAccessExpression,
SyntaxKind.ThisConstructorInitializer,
SyntaxKind.BaseConstructorInitializer,
SyntaxKind.ObjectCreationExpression,
SyntaxKind.Attribute,
SyntaxKind.DelegateDeclaration,
SyntaxKind.SimpleLambdaExpression,
SyntaxKind.ParenthesizedLambdaExpression,
SyntaxKind.NameMemberCref
}.ToImmutableArray();
private ImmutableArray<SyntaxKind> _updatableNodeKinds = new[]
{
SyntaxKind.MethodDeclaration,
SyntaxKind.ConstructorDeclaration,
SyntaxKind.IndexerDeclaration,
SyntaxKind.InvocationExpression,
SyntaxKind.ElementAccessExpression,
SyntaxKind.ThisConstructorInitializer,
SyntaxKind.BaseConstructorInitializer,
SyntaxKind.ObjectCreationExpression,
SyntaxKind.Attribute,
SyntaxKind.DelegateDeclaration,
SyntaxKind.NameMemberCref,
SyntaxKind.AnonymousMethodExpression,
SyntaxKind.ParenthesizedLambdaExpression,
SyntaxKind.SimpleLambdaExpression
}.ToImmutableArray();
public override SyntaxNode FindNodeToUpdate(Document document, SyntaxNode node)
{
if (_updatableNodeKinds.Contains(node.Kind()))
{
return node;
}
// TODO: file bug about this: var invocation = csnode.Ancestors().FirstOrDefault(a => a.Kind == SyntaxKind.InvocationExpression);
var matchingNode = node.AncestorsAndSelf().FirstOrDefault(n => _updatableAncestorKinds.Contains(n.Kind()));
if (matchingNode == null)
{
return null;
}
var nodeContainingOriginal = GetNodeContainingTargetNode(matchingNode);
if (nodeContainingOriginal == null)
{
return null;
}
return node.AncestorsAndSelf().Any(n => n == nodeContainingOriginal) ? matchingNode : null;
}
private SyntaxNode GetNodeContainingTargetNode(SyntaxNode matchingNode)
{
switch (matchingNode.Kind())
{
case SyntaxKind.InvocationExpression:
return (matchingNode as InvocationExpressionSyntax).Expression;
case SyntaxKind.ElementAccessExpression:
return (matchingNode as ElementAccessExpressionSyntax).ArgumentList;
case SyntaxKind.ObjectCreationExpression:
return (matchingNode as ObjectCreationExpressionSyntax).Type;
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.ThisConstructorInitializer:
case SyntaxKind.BaseConstructorInitializer:
case SyntaxKind.Attribute:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.NameMemberCref:
return matchingNode;
default:
return null;
}
}
public override SyntaxNode ChangeSignature(
Document document,
ISymbol declarationSymbol,
SyntaxNode potentiallyUpdatedNode,
SyntaxNode originalNode,
SignatureChange signaturePermutation,
CancellationToken cancellationToken)
{
var updatedNode = potentiallyUpdatedNode as CSharpSyntaxNode;
// Update <param> tags.
if (updatedNode.IsKind(SyntaxKind.MethodDeclaration) ||
updatedNode.IsKind(SyntaxKind.ConstructorDeclaration) ||
updatedNode.IsKind(SyntaxKind.IndexerDeclaration) ||
updatedNode.IsKind(SyntaxKind.DelegateDeclaration))
{
var updatedLeadingTrivia = UpdateParamTagsInLeadingTrivia(updatedNode, declarationSymbol, signaturePermutation);
if (updatedLeadingTrivia != null)
{
updatedNode = updatedNode.WithLeadingTrivia(updatedLeadingTrivia);
}
}
// Update declarations parameter lists
if (updatedNode.IsKind(SyntaxKind.MethodDeclaration))
{
var method = updatedNode as MethodDeclarationSyntax;
var updatedParameters = PermuteDeclaration(method.ParameterList.Parameters, signaturePermutation);
return method.WithParameterList(method.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.ConstructorDeclaration))
{
var constructor = updatedNode as ConstructorDeclarationSyntax;
var updatedParameters = PermuteDeclaration(constructor.ParameterList.Parameters, signaturePermutation);
return constructor.WithParameterList(constructor.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.IndexerDeclaration))
{
var indexer = updatedNode as IndexerDeclarationSyntax;
var updatedParameters = PermuteDeclaration(indexer.ParameterList.Parameters, signaturePermutation);
return indexer.WithParameterList(indexer.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.DelegateDeclaration))
{
var delegateDeclaration = updatedNode as DelegateDeclarationSyntax;
var updatedParameters = PermuteDeclaration(delegateDeclaration.ParameterList.Parameters, signaturePermutation);
return delegateDeclaration.WithParameterList(delegateDeclaration.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.AnonymousMethodExpression))
{
var anonymousMethod = updatedNode as AnonymousMethodExpressionSyntax;
// Delegates may omit parameters in C#
if (anonymousMethod.ParameterList == null)
{
return anonymousMethod;
}
var updatedParameters = PermuteDeclaration(anonymousMethod.ParameterList.Parameters, signaturePermutation);
return anonymousMethod.WithParameterList(anonymousMethod.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.SimpleLambdaExpression))
{
var lambda = updatedNode as SimpleLambdaExpressionSyntax;
if (signaturePermutation.UpdatedConfiguration.ToListOfParameters().Any())
{
Debug.Assert(false, "Updating a simple lambda expression without removing its parameter");
}
else
{
// No parameters. Change to a parenthesized lambda expression
var emptyParameterList = SyntaxFactory.ParameterList()
.WithLeadingTrivia(lambda.Parameter.GetLeadingTrivia())
.WithTrailingTrivia(lambda.Parameter.GetTrailingTrivia());
return SyntaxFactory.ParenthesizedLambdaExpression(lambda.AsyncKeyword, emptyParameterList, lambda.ArrowToken, lambda.RefKeyword, lambda.Body);
}
}
if (updatedNode.IsKind(SyntaxKind.ParenthesizedLambdaExpression))
{
var lambda = updatedNode as ParenthesizedLambdaExpressionSyntax;
var updatedParameters = PermuteDeclaration(lambda.ParameterList.Parameters, signaturePermutation);
return lambda.WithParameterList(lambda.ParameterList.WithParameters(updatedParameters));
}
// Update reference site argument lists
if (updatedNode.IsKind(SyntaxKind.InvocationExpression))
{
var invocation = updatedNode as InvocationExpressionSyntax;
var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var symbolInfo = semanticModel.GetSymbolInfo(originalNode as InvocationExpressionSyntax, cancellationToken);
var methodSymbol = symbolInfo.Symbol as IMethodSymbol;
var isReducedExtensionMethod = false;
if (methodSymbol != null && methodSymbol.MethodKind == MethodKind.ReducedExtension)
{
isReducedExtensionMethod = true;
}
var newArguments = PermuteArgumentList(document, declarationSymbol, invocation.ArgumentList.Arguments, signaturePermutation, isReducedExtensionMethod);
return invocation.WithArgumentList(invocation.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.ObjectCreationExpression))
{
var objCreation = updatedNode as ObjectCreationExpressionSyntax;
var newArguments = PermuteArgumentList(document, declarationSymbol, objCreation.ArgumentList.Arguments, signaturePermutation);
return objCreation.WithArgumentList(objCreation.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.ThisConstructorInitializer) ||
updatedNode.IsKind(SyntaxKind.BaseConstructorInitializer))
{
var objCreation = updatedNode as ConstructorInitializerSyntax;
var newArguments = PermuteArgumentList(document, declarationSymbol, objCreation.ArgumentList.Arguments, signaturePermutation);
return objCreation.WithArgumentList(objCreation.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.ElementAccessExpression))
{
var elementAccess = updatedNode as ElementAccessExpressionSyntax;
var newArguments = PermuteArgumentList(document, declarationSymbol, elementAccess.ArgumentList.Arguments, signaturePermutation);
return elementAccess.WithArgumentList(elementAccess.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.Attribute))
{
var attribute = updatedNode as AttributeSyntax;
var newArguments = PermuteAttributeArgumentList(document, declarationSymbol, attribute.ArgumentList.Arguments, signaturePermutation);
return attribute.WithArgumentList(attribute.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
// Handle references in crefs
if (updatedNode.IsKind(SyntaxKind.NameMemberCref))
{
var nameMemberCref = updatedNode as NameMemberCrefSyntax;
if (nameMemberCref.Parameters == null ||
!nameMemberCref.Parameters.Parameters.Any())
{
return nameMemberCref;
}
var newParameters = PermuteDeclaration(nameMemberCref.Parameters.Parameters, signaturePermutation);
var newCrefParameterList = nameMemberCref.Parameters.WithParameters(newParameters);
return nameMemberCref.WithParameters(newCrefParameterList);
}
Debug.Assert(false, "Unknown reference location");
return null;
}
private SeparatedSyntaxList<T> PermuteDeclaration<T>(SeparatedSyntaxList<T> list, SignatureChange updatedSignature) where T : SyntaxNode
{
var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters();
var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var newParameters = new List<T>();
foreach (var newParam in reorderedParameters)
{
var pos = originalParameters.IndexOf(newParam);
var param = list[pos];
newParameters.Add(param);
}
var numSeparatorsToSkip = originalParameters.Count - reorderedParameters.Count;
return SyntaxFactory.SeparatedList(newParameters, GetSeparators(list, numSeparatorsToSkip));
}
private static SeparatedSyntaxList<AttributeArgumentSyntax> PermuteAttributeArgumentList(
Document document,
ISymbol declarationSymbol,
SeparatedSyntaxList<AttributeArgumentSyntax> arguments,
SignatureChange updatedSignature)
{
var newArguments = PermuteArguments(document, declarationSymbol, arguments.Select(a => UnifiedArgumentSyntax.Create(a)).ToList(), updatedSignature);
var numSeparatorsToSkip = arguments.Count - newArguments.Count;
return SyntaxFactory.SeparatedList(newArguments.Select(a => (AttributeArgumentSyntax)(UnifiedArgumentSyntax)a), GetSeparators(arguments, numSeparatorsToSkip));
}
private static SeparatedSyntaxList<ArgumentSyntax> PermuteArgumentList(
Document document,
ISymbol declarationSymbol,
SeparatedSyntaxList<ArgumentSyntax> arguments,
SignatureChange updatedSignature,
bool isReducedExtensionMethod = false)
{
var newArguments = PermuteArguments(document, declarationSymbol, arguments.Select(a => UnifiedArgumentSyntax.Create(a)).ToList(), updatedSignature, isReducedExtensionMethod);
var numSeparatorsToSkip = arguments.Count - newArguments.Count;
return SyntaxFactory.SeparatedList(newArguments.Select(a => (ArgumentSyntax)(UnifiedArgumentSyntax)a), GetSeparators(arguments, numSeparatorsToSkip));
}
private List<SyntaxTrivia> UpdateParamTagsInLeadingTrivia(CSharpSyntaxNode node, ISymbol declarationSymbol, SignatureChange updatedSignature)
{
if (!node.HasLeadingTrivia)
{
return null;
}
var paramNodes = node
.DescendantNodes(descendIntoTrivia: true)
.OfType<XmlElementSyntax>()
.Where(e => e.StartTag.Name.ToString() == DocumentationCommentXmlNames.ParameterElementName);
var permutedParamNodes = VerifyAndPermuteParamNodes(paramNodes, declarationSymbol, updatedSignature);
if (permutedParamNodes == null)
{
return null;
}
return GetPermutedTrivia(node, permutedParamNodes);
}
private List<XmlElementSyntax> VerifyAndPermuteParamNodes(IEnumerable<XmlElementSyntax> paramNodes, ISymbol declarationSymbol, SignatureChange updatedSignature)
{
// Only reorder if count and order match originally.
var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters();
var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var declaredParameters = declarationSymbol.GetParameters();
if (paramNodes.Count() != declaredParameters.Count())
{
return null;
}
var dictionary = new Dictionary<string, XmlElementSyntax>();
int i = 0;
foreach (var paramNode in paramNodes)
{
var nameAttribute = paramNode.StartTag.Attributes.FirstOrDefault(a => a.Name.ToString().Equals("name", StringComparison.OrdinalIgnoreCase));
if (nameAttribute == null)
{
return null;
}
var identifier = nameAttribute.DescendantNodes(descendIntoTrivia: true).OfType<IdentifierNameSyntax>().FirstOrDefault();
if (identifier == null || identifier.ToString() != declaredParameters.ElementAt(i).Name)
{
return null;
}
dictionary.Add(originalParameters[i].Name.ToString(), paramNode);
i++;
}
// Everything lines up, so permute them.
var permutedParams = new List<XmlElementSyntax>();
foreach (var parameter in reorderedParameters)
{
permutedParams.Add(dictionary[parameter.Name]);
}
return permutedParams;
}
private List<SyntaxTrivia> GetPermutedTrivia(CSharpSyntaxNode node, List<XmlElementSyntax> permutedParamNodes)
{
var updatedLeadingTrivia = new List<SyntaxTrivia>();
var index = 0;
foreach (var trivia in node.GetLeadingTrivia())
{
if (!trivia.HasStructure)
{
updatedLeadingTrivia.Add(trivia);
continue;
}
var structuredTrivia = trivia.GetStructure() as DocumentationCommentTriviaSyntax;
if (structuredTrivia == null)
{
updatedLeadingTrivia.Add(trivia);
continue;
}
var updatedNodeList = new List<XmlNodeSyntax>();
var structuredContent = structuredTrivia.Content.ToList();
for (int i = 0; i < structuredContent.Count; i++)
{
var content = structuredContent[i];
if (!content.IsKind(SyntaxKind.XmlElement))
{
updatedNodeList.Add(content);
continue;
}
var xmlElement = content as XmlElementSyntax;
if (xmlElement.StartTag.Name.ToString() != DocumentationCommentXmlNames.ParameterElementName)
{
updatedNodeList.Add(content);
continue;
}
// Found a param tag, so insert the next one from the reordered list
if (index < permutedParamNodes.Count)
{
updatedNodeList.Add(permutedParamNodes[index].WithLeadingTrivia(content.GetLeadingTrivia()).WithTrailingTrivia(content.GetTrailingTrivia()));
index++;
}
else
{
// Inspecting a param element that we are deleting but not replacing.
}
}
var newDocComments = SyntaxFactory.DocumentationCommentTrivia(structuredTrivia.Kind(), SyntaxFactory.List(updatedNodeList.AsEnumerable()));
newDocComments = newDocComments.WithEndOfComment(structuredTrivia.EndOfComment);
newDocComments = newDocComments.WithLeadingTrivia(structuredTrivia.GetLeadingTrivia()).WithTrailingTrivia(structuredTrivia.GetTrailingTrivia());
var newTrivia = SyntaxFactory.Trivia(newDocComments);
updatedLeadingTrivia.Add(newTrivia);
}
return updatedLeadingTrivia;
}
private static List<SyntaxToken> GetSeparators<T>(SeparatedSyntaxList<T> arguments, int numSeparatorsToSkip = 0) where T : SyntaxNode
{
var separators = new List<SyntaxToken>();
for (int i = 0; i < arguments.SeparatorCount - numSeparatorsToSkip; i++)
{
separators.Add(arguments.GetSeparator(i));
}
return separators;
}
public override async Task<IEnumerable<ISymbol>> DetermineCascadedSymbolsFromDelegateInvoke(IMethodSymbol symbol, Document document, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var nodes = root.DescendantNodes();
var convertedMethodGroups = nodes
.Where(
n =>
{
if (!n.IsKind(SyntaxKind.IdentifierName) ||
!semanticModel.GetMemberGroup(n, cancellationToken).Any())
{
return false;
}
ISymbol convertedType = semanticModel.GetTypeInfo(n, cancellationToken).ConvertedType;
if (convertedType != null)
{
convertedType = convertedType.OriginalDefinition;
}
if (convertedType != null)
{
convertedType = SymbolFinder.FindSourceDefinitionAsync(convertedType, document.Project.Solution, cancellationToken).WaitAndGetResult(cancellationToken) ?? convertedType;
}
return convertedType == symbol.ContainingType;
})
.Select(n => semanticModel.GetSymbolInfo(n, cancellationToken).Symbol);
return convertedMethodGroups;
}
protected override IEnumerable<IFormattingRule> GetFormattingRules(Document document)
{
return new[] { new ChangeSignatureFormattingRule() }.Concat(Formatter.GetDefaultFormattingRules(document));
}
}
}
| |
// 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.Contracts;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Runtime
{
public static class TaskHelpers
{
//This replaces the Wait<TException>(this Task task) method as we want to await and not Wait()
public static async Task AsyncWait<TException>(this Task task)
{
try
{
await task;
}
catch
{
throw Fx.Exception.AsError<TException>(task.Exception);
}
}
// Helper method when implementing an APM wrapper around a Task based async method which returns a result.
// In the BeginMethod method, you would call use ToApm to wrap a call to MethodAsync:
// return MethodAsync(params).ToApm(callback, state);
// In the EndMethod, you would use ToApmEnd<TResult> to ensure the correct exception handling
// This will handle throwing exceptions in the correct place and ensure the IAsyncResult contains the provided
// state object
public static Task<TResult> ToApm<TResult>(this Task<TResult> task, AsyncCallback callback, object state)
{
// When using APM, the returned IAsyncResult must have the passed in state object stored in AsyncState. This
// is so the callback can regain state. If the incoming task already holds the state object, there's no need
// to create a TaskCompletionSource to ensure the returned (IAsyncResult)Task has the right state object.
// This is a performance optimization for this special case.
if (task.AsyncState == state)
{
if (callback != null)
{
task.ContinueWith((antecedent, obj) =>
{
var callbackObj = obj as AsyncCallback;
callbackObj(antecedent);
}, callback, CancellationToken.None, TaskContinuationOptions.HideScheduler, TaskScheduler.Default);
}
return task;
}
// Need to create a TaskCompletionSource so that the returned Task object has the correct AsyncState value.
var tcs = new TaskCompletionSource<TResult>(state);
var continuationState = Tuple.Create(tcs, callback);
task.ContinueWith((antecedent, obj) =>
{
var tuple = obj as Tuple<TaskCompletionSource<TResult>, AsyncCallback>;
var tcsObj = tuple.Item1;
var callbackObj = tuple.Item2;
if (antecedent.IsFaulted) tcsObj.TrySetException(antecedent.Exception.InnerException);
else if (antecedent.IsCanceled) tcsObj.TrySetCanceled();
else tcsObj.TrySetResult(antecedent.Result);
if (callbackObj != null) callback(tcsObj.Task);
}, continuationState, CancellationToken.None, TaskContinuationOptions.HideScheduler, TaskScheduler.Default);
return tcs.Task;
}
// Helper method when implementing an APM wrapper around a Task based async method which returns a result.
// In the BeginMethod method, you would call use ToApm to wrap a call to MethodAsync:
// return MethodAsync(params).ToApm(callback, state);
// In the EndMethod, you would use ToApmEnd to ensure the correct exception handling
// This will handle throwing exceptions in the correct place and ensure the IAsyncResult contains the provided
// state object
public static Task ToApm(this Task task, AsyncCallback callback, object state)
{
// When using APM, the returned IAsyncResult must have the passed in state object stored in AsyncState. This
// is so the callback can regain state. If the incoming task already holds the state object, there's no need
// to create a TaskCompletionSource to ensure the returned (IAsyncResult)Task has the right state object.
// This is a performance optimization for this special case.
if (task.AsyncState == state)
{
if (callback != null)
{
task.ContinueWith((antecedent, obj) =>
{
var callbackObj = obj as AsyncCallback;
callbackObj(antecedent);
}, callback, CancellationToken.None, TaskContinuationOptions.HideScheduler, TaskScheduler.Default);
}
return task;
}
// Need to create a TaskCompletionSource so that the returned Task object has the correct AsyncState value.
// As we intend to create a task with no Result value, we don't care what result type the TCS holds as we
// won't be using it. As Task<TResult> derives from Task, the returned Task is compatible.
var tcs = new TaskCompletionSource<object>(state);
var continuationState = Tuple.Create(tcs, callback);
task.ContinueWith((antecedent, obj) =>
{
var tuple = obj as Tuple<TaskCompletionSource<object>, AsyncCallback>;
var tcsObj = tuple.Item1;
var callbackObj = tuple.Item2;
if (antecedent.IsFaulted)
{
tcsObj.TrySetException(antecedent.Exception.InnerException);
}
else if (antecedent.IsCanceled)
{
tcsObj.TrySetCanceled();
}
else
{
tcsObj.TrySetResult(null);
}
if (callback != null)
{
callbackObj(tcsObj.Task);
}
}, continuationState, CancellationToken.None, TaskContinuationOptions.HideScheduler, TaskScheduler.Default);
return tcs.Task;
}
// Helper method to implement the End method of an APM method pair which is wrapping a Task based
// async method when the Task returns a result. By using task.GetAwaiter.GetResult(), the exception
// handling conventions are the same as when await'ing a task, i.e. this throws the first exception
// and doesn't wrap it in an AggregateException. It also throws the right exception if the task was
// cancelled.
public static TResult ToApmEnd<TResult>(this IAsyncResult iar)
{
Task<TResult> task = iar as Task<TResult>;
Contract.Assert(task != null, "IAsyncResult must be an instance of Task<TResult>");
return task.GetAwaiter().GetResult();
}
// Helper method to implement the End method of an APM method pair which is wrapping a Task based
// async method when the Task does not return result.
public static void ToApmEnd(this IAsyncResult iar)
{
Task task = iar as Task;
Contract.Assert(task != null, "IAsyncResult must be an instance of Task");
task.GetAwaiter().GetResult();
}
// Awaitable helper to await a maximum amount of time for a task to complete. If the task doesn't
// complete in the specified amount of time, returns false. This does not modify the state of the
// passed in class, but instead is a mechanism to allow interrupting awaiting a task if a timeout
// period passes.
public static async Task<bool> AwaitWithTimeout(this Task task, TimeSpan timeout)
{
using (CancellationTokenSource cts = new CancellationTokenSource())
{
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, cts.Token));
if (completedTask == task)
{
cts.Cancel();
return true;
}
else
{
return (task.IsCompleted);
}
}
}
// Task.GetAwaiter().GetResult() calls an internal variant of Wait() which doesn't wrap exceptions in
// an AggregateException.
public static void WaitForCompletion(this Task task)
{
task.GetAwaiter().GetResult();
}
public static TResult WaitForCompletion<TResult>(this Task<TResult> task)
{
return task.GetAwaiter().GetResult();
}
public static Task CompletedTask()
{
return Task.FromResult(true);
}
public static DefaultTaskSchedulerAwaiter EnsureDefaultTaskScheduler()
{
return DefaultTaskSchedulerAwaiter.Singleton;
}
public static Action<object> OnAsyncCompletionCallback = OnAsyncCompletion;
// Method to act as callback for asynchronous code which uses AsyncCompletionResult as the return type when used within
// a Task based async method. These methods require a callback which is called in the case of the IO completing asynchronously.
// This pattern still requires an allocation, whereas the purpose of using the AsyncCompletionResult enum is to avoid allocation.
// In the future, this pattern should be replaced with a reusable awaitable object, potentially with a global pool.
private static void OnAsyncCompletion(object state)
{
var tcs = state as TaskCompletionSource<bool>;
Contract.Assert(state != null, "Async state should be of type TaskCompletionSource<bool>");
tcs.TrySetResult(true);
}
}
// This awaiter causes an awaiting async method to continue on the same thread if using the
// default task scheduler, otherwise it posts the continuation to the ThreadPool. While this
// does a similar function to Task.ConfigureAwait, this code doesn't require a Task to function.
// With Task.ConfigureAwait, you would need to call it on the first task on each potential code
// path in a method. This could mean calling ConfigureAwait multiple times in a single method.
// This awaiter can be awaited on at the beginning of a method a single time and isn't dependant
// on running other awaitable code.
public struct DefaultTaskSchedulerAwaiter : INotifyCompletion
{
public static DefaultTaskSchedulerAwaiter Singleton = new DefaultTaskSchedulerAwaiter();
// If the current TaskScheduler is the default, if we aren't currently running inside a task and
// the default SynchronizationContext isn't current, when a Task starts, it will change the TaskScheduler
// to one based off the current SynchronizationContext. Also, any async api's that WCF consumes will
// post back to the same SynchronizationContext as they were started in which could cause WCF to deadlock
// on our Sync code path.
public bool IsCompleted
{
get
{
return (TaskScheduler.Current == TaskScheduler.Default) &&
(SynchronizationContext.Current == null ||
(SynchronizationContext.Current.GetType() == typeof(SynchronizationContext)));
}
}
// Only called when IsCompleted returns false, otherwise the caller will call the continuation
// directly causing it to stay on the same thread.
public void OnCompleted(Action continuation)
{
Task.Run(continuation);
}
// Awaiter is only used to control where subsequent awaitable's run so GetResult needs no
// implementation. Normally any exceptions would be thrown here, but we have nothing to throw
// as we don't run anything, only control where other code runs.
public void GetResult() { }
public DefaultTaskSchedulerAwaiter GetAwaiter()
{
return this;
}
}
// Async methods can't take an out (or ref) argument. This wrapper allows passing in place of an out argument
// and can be used to return a value via a method argument.
public class OutWrapper<T> where T : class
{
public OutWrapper()
{
Value = null;
}
public T Value { get; set; }
public static implicit operator T(OutWrapper<T> wrapper)
{
return wrapper.Value;
}
}
}
| |
/*
* 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 log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Services.Connectors.Simulation
{
public class SimulationServiceConnector : ISimulationService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// we use this dictionary to track the pending updateagent requests, maps URI --> position update
private Dictionary<string,AgentPosition> m_updateAgentQueue = new Dictionary<string,AgentPosition>();
//private GridRegion m_Region;
public SimulationServiceConnector()
{
}
public SimulationServiceConnector(IConfigSource config)
{
//m_Region = region;
}
public IScene GetScene(UUID regionId)
{
return null;
}
public ISimulationService GetInnerService()
{
return null;
}
#region Agents
protected virtual string AgentPath()
{
return "agent/";
}
protected virtual void PackData(OSDMap args, GridRegion source, AgentCircuitData aCircuit, GridRegion destination, uint flags)
{
if (source != null)
{
args["source_x"] = OSD.FromString(source.RegionLocX.ToString());
args["source_y"] = OSD.FromString(source.RegionLocY.ToString());
args["source_name"] = OSD.FromString(source.RegionName);
args["source_uuid"] = OSD.FromString(source.RegionID.ToString());
if (!String.IsNullOrEmpty(source.RawServerURI))
args["source_server_uri"] = OSD.FromString(source.RawServerURI);
}
args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString());
args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString());
args["destination_name"] = OSD.FromString(destination.RegionName);
args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());
args["teleport_flags"] = OSD.FromString(flags.ToString());
}
public bool CreateAgent(GridRegion source, GridRegion destination, AgentCircuitData aCircuit, uint flags, out string reason)
{
string tmp = String.Empty;
return CreateAgent(source, destination, aCircuit, flags, out tmp, out reason);
}
public bool CreateAgent(GridRegion source, GridRegion destination, AgentCircuitData aCircuit, uint flags, out string myipaddress, out string reason)
{
m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: Creating agent at {0}", destination.ServerURI);
reason = String.Empty;
myipaddress = String.Empty;
if (destination == null)
{
m_log.Debug("[REMOTE SIMULATION CONNECTOR]: Given destination is null");
return false;
}
string uri = destination.ServerURI + AgentPath() + aCircuit.AgentID + "/";
try
{
OSDMap args = aCircuit.PackAgentCircuitData();
PackData(args, source, aCircuit, destination, flags);
OSDMap result = WebUtil.PostToServiceCompressed(uri, args, 30000);
bool success = result["success"].AsBoolean();
if (success && result.ContainsKey("_Result"))
{
OSDMap data = (OSDMap)result["_Result"];
reason = data["reason"].AsString();
success = data["success"].AsBoolean();
myipaddress = data["your_ip"].AsString();
return success;
}
// Try the old version, uncompressed
result = WebUtil.PostToService(uri, args, 30000, false);
if (result["Success"].AsBoolean())
{
if (result.ContainsKey("_Result"))
{
OSDMap data = (OSDMap)result["_Result"];
reason = data["reason"].AsString();
success = data["success"].AsBoolean();
myipaddress = data["your_ip"].AsString();
m_log.WarnFormat(
"[REMOTE SIMULATION CONNECTOR]: Remote simulator {0} did not accept compressed transfer, suggest updating it.", destination.RegionName);
return success;
}
}
m_log.WarnFormat(
"[REMOTE SIMULATION CONNECTOR]: Failed to create agent {0} {1} at remote simulator {2}",
aCircuit.firstname, aCircuit.lastname, destination.RegionName);
reason = result["Message"] != null ? result["Message"].AsString() : "error";
return false;
}
catch (Exception e)
{
m_log.Warn("[REMOTE SIMULATION CONNECTOR]: CreateAgent failed with exception: " + e.ToString());
reason = e.Message;
}
return false;
}
/// <summary>
/// Send complete data about an agent in this region to a neighbor
/// </summary>
public bool UpdateAgent(GridRegion destination, AgentData data)
{
return UpdateAgent(destination, (IAgentData)data, 200000); // yes, 200 seconds
}
private ThreadedClasses.ExpiringCache<string, bool> _failedSims = new ThreadedClasses.ExpiringCache<string, bool>(30);
/// <summary>
/// Send updated position information about an agent in this region to a neighbor
/// This operation may be called very frequently if an avatar is moving about in
/// the region.
/// </summary>
public bool UpdateAgent(GridRegion destination, AgentPosition data)
{
bool v = true;
if (_failedSims.TryGetValue(destination.ServerURI, out v))
return false;
// The basic idea of this code is that the first thread that needs to
// send an update for a specific avatar becomes the worker for any subsequent
// requests until there are no more outstanding requests. Further, only send the most
// recent update; this *should* never be needed but some requests get
// slowed down and once that happens the problem with service end point
// limits kicks in and nothing proceeds
string uri = destination.ServerURI + AgentPath() + data.AgentID + "/";
lock (m_updateAgentQueue)
{
if (m_updateAgentQueue.ContainsKey(uri))
{
// Another thread is already handling
// updates for this simulator, just update
// the position and return, overwrites are
// not a problem since we only care about the
// last update anyway
m_updateAgentQueue[uri] = data;
return true;
}
// Otherwise update the reference and start processing
m_updateAgentQueue[uri] = data;
}
AgentPosition pos = null;
bool success = true;
while (success)
{
lock (m_updateAgentQueue)
{
// save the position
AgentPosition lastpos = pos;
pos = m_updateAgentQueue[uri];
// this is true if no one put a new
// update in the map since the last
// one we processed, if thats the
// case then we are done
if (pos == lastpos)
{
m_updateAgentQueue.Remove(uri);
return true;
}
}
success = UpdateAgent(destination, (IAgentData)pos, 10000);
}
// we get here iff success == false
// blacklist sim for 2 minutes
lock (m_updateAgentQueue)
{
_failedSims.AddOrUpdate(destination.ServerURI, true, 120);
m_updateAgentQueue.Remove(uri);
}
return false;
}
/// <summary>
/// This is the worker function to send AgentData to a neighbor region
/// </summary>
private bool UpdateAgent(GridRegion destination, IAgentData cAgentData, int timeout)
{
// m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: UpdateAgent in {0}", destination.ServerURI);
// Eventually, we want to use a caps url instead of the agentID
string uri = destination.ServerURI + AgentPath() + cAgentData.AgentID + "/";
try
{
OSDMap args = cAgentData.Pack();
args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString());
args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString());
args["destination_name"] = OSD.FromString(destination.RegionName);
args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());
OSDMap result;
try
{
result = WebUtil.PutToServiceCompressed(uri, args, timeout);
if (result["Success"].AsBoolean())
return true;
result = WebUtil.PutToService(uri, args, timeout);
}
catch
{
result = WebUtil.PutToService(uri, args, timeout);
}
return result["Success"].AsBoolean();
}
catch (Exception e)
{
m_log.Warn("[REMOTE SIMULATION CONNECTOR]: UpdateAgent failed with exception: " + e.ToString());
}
return false;
}
public bool QueryAccess(GridRegion destination, UUID agentID, string agentHomeURI, Vector3 position, string myversion, out string version, out string reason)
{
reason = "Failed to contact destination";
version = "Unknown";
// m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: QueryAccess start, position={0}", position);
IPEndPoint ext = destination.ExternalEndPoint;
if (ext == null) return false;
// Eventually, we want to use a caps url instead of the agentID
string uri = destination.ServerURI + AgentPath() + agentID + "/" + destination.RegionID.ToString() + "/";
OSDMap request = new OSDMap();
request.Add("position", OSD.FromString(position.ToString()));
request.Add("my_version", OSD.FromString(myversion));
if (agentHomeURI != null)
request.Add("agent_home_uri", OSD.FromString(agentHomeURI));
try
{
OSDMap result = WebUtil.ServiceOSDRequest(uri, request, "QUERYACCESS", 30000, false, false);
bool success = result["success"].AsBoolean();
if (result.ContainsKey("_Result"))
{
OSDMap data = (OSDMap)result["_Result"];
// FIXME: If there is a _Result map then it's the success key here that indicates the true success
// or failure, not the sibling result node.
success = data["success"];
reason = data["reason"].AsString();
if (data["version"] != null && data["version"].AsString() != string.Empty)
version = data["version"].AsString();
m_log.DebugFormat(
"[REMOTE SIMULATION CONNECTOR]: QueryAccess to {0} returned {1}, reason {2}, version {3} ({4})",
uri, success, reason, version, data["version"].AsString());
}
if (!success)
{
// If we don't check this then OpenSimulator 0.7.3.1 and some period before will never see the
// actual failure message
if (!result.ContainsKey("_Result"))
{
if (result.ContainsKey("Message"))
{
string message = result["Message"].AsString();
if (message == "Service request failed: [MethodNotAllowed] MethodNotAllowed") // Old style region
{
m_log.Info("[REMOTE SIMULATION CONNECTOR]: The above web util error was caused by a TP to a sim that doesn't support QUERYACCESS and can be ignored");
return true;
}
reason = result["Message"];
}
else
{
reason = "Communications failure";
}
}
return false;
}
return success;
}
catch (Exception e)
{
m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] QueryAcesss failed with exception; {0}",e.ToString());
}
return false;
}
/// <summary>
/// </summary>
public bool ReleaseAgent(UUID origin, UUID id, string uri)
{
// m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: ReleaseAgent start");
try
{
WebUtil.ServiceOSDRequest(uri, null, "DELETE", 10000, false, false);
}
catch (Exception e)
{
m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] ReleaseAgent failed with exception; {0}",e.ToString());
}
return true;
}
/// <summary>
/// </summary>
public bool CloseAgent(GridRegion destination, UUID id, string auth_code)
{
string uri = destination.ServerURI + AgentPath() + id + "/" + destination.RegionID.ToString() + "/?auth=" + auth_code;
m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: CloseAgent {0}", uri);
try
{
WebUtil.ServiceOSDRequest(uri, null, "DELETE", 10000, false, false);
}
catch (Exception e)
{
m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] CloseAgent failed with exception; {0}",e.ToString());
}
return true;
}
#endregion Agents
#region Objects
protected virtual string ObjectPath()
{
return "object/";
}
/// <summary>
///
/// </summary>
public bool CreateObject(GridRegion destination, Vector3 newPosition, ISceneObject sog, bool isLocalCall)
{
// m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: CreateObject start");
string uri = destination.ServerURI + ObjectPath() + sog.UUID + "/";
try
{
OSDMap args = new OSDMap(2);
args["sog"] = OSD.FromString(sog.ToXml2());
args["extra"] = OSD.FromString(sog.ExtraToXmlString());
args["modified"] = OSD.FromBoolean(sog.HasGroupChanged);
args["new_position"] = newPosition.ToString();
string state = sog.GetStateSnapshot();
if (state.Length > 0)
args["state"] = OSD.FromString(state);
// Add the input general arguments
args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString());
args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString());
args["destination_name"] = OSD.FromString(destination.RegionName);
args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());
OSDMap result = WebUtil.PostToService(uri, args, 40000, false);
if (result == null)
return false;
bool success = result["success"].AsBoolean();
if (!success)
return false;
}
catch (Exception e)
{
m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] CreateObject failed with exception; {0}",e.ToString());
return false;
}
return true;
}
/// <summary>
///
/// </summary>
public bool CreateObject(GridRegion destination, UUID userID, UUID itemID)
{
// TODO, not that urgent
return false;
}
#endregion Objects
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using Newtonsoft.Json.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Elasticsearch.Net.Serialization;
using Elasticsearch.Net;
namespace Nest
{
internal static class Extensions
{
internal static TReturn InvokeOrDefault<T, TReturn>(this Func<T, TReturn> func, T @default)
where T: class, TReturn where TReturn: class =>
func?.Invoke(@default) ?? @default;
internal static TReturn InvokeOrDefault<T1, T2, TReturn>(this Func<T1, T2, TReturn> func, T1 @default, T2 param2)
where T1: class, TReturn where TReturn: class =>
func?.Invoke(@default, param2) ?? @default;
internal static QueryContainer InvokeQuery<T>(
this Func<QueryContainerDescriptor<T>, QueryContainer> f,
QueryContainerDescriptor<T> container)
where T : class
{
var c = f.Invoke(container);
//if query is not conditionless or is verbatim: return a container that holds the query
if (c != null && (!c.IsConditionless || c.IsVerbatim))
return c;
//query is conditionless but the container is marked as strict, throw exception
if (c != null && c.IsStrict)
throw new DslException("Query is conditionless but strict is turned on") { Offender = c };
//query is conditionless return an empty container that can later be rewritten
return null;
}
internal static string GetStringValue(this Enum enumValue)
{
var knownEnum = KnownEnums.Resolve(enumValue);
if (knownEnum != KnownEnums.UnknownEnum) return knownEnum;
var type = enumValue.GetType();
var info = type.GetField(enumValue.ToString());
var da = (EnumMemberAttribute[])(info.GetCustomAttributes(typeof(EnumMemberAttribute), false));
if (da.Length > 0)
return da[0].Value;
else
return Enum.GetName(enumValue.GetType(), enumValue);
}
internal static readonly JsonConverter dateConverter = new IsoDateTimeConverter { Culture = CultureInfo.InvariantCulture };
internal static readonly JsonSerializer serializer = new JsonSerializer();
internal static string ToJsonNetString(this DateTime date)
{
using (var writer = new JTokenWriter())
{
dateConverter.WriteJson(writer, date, new JsonSerializer());
return writer.Token.ToString();
}
}
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property)
{
return items.GroupBy(property).Select(x => x.First());
}
//TODO Memoize?
public static T? ToEnum<T>(this string str) where T : struct
{
var enumType = typeof(T);
foreach (var name in Enum.GetNames(enumType))
{
if (name.Equals(str, StringComparison.OrdinalIgnoreCase)) return (T)Enum.Parse(enumType, name);
var enumAttributes = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true));
if (!enumAttributes.HasAny()) continue;
var enumMemberAttribute = enumAttributes.Single();
if (enumMemberAttribute.Value == str) return (T)Enum.Parse(enumType, name);
}
//throw exception or whatever handling you want or
return null;
}
internal static string Utf8String(this byte[] bytes)
{
return bytes == null ? null : Encoding.UTF8.GetString(bytes);
}
internal static byte[] Utf8Bytes(this string s)
{
return s.IsNullOrEmpty() ? null : Encoding.UTF8.GetBytes(s);
}
internal static string GetStringValue(this IEnumerable<Enum> enumValues)
{
return string.Join(",", enumValues.Select(e => e.GetStringValue()));
}
internal static bool JsonEquals(this string json, string otherjson)
{
var nJson = JObject.Parse(json).ToString();
var nOtherJson = JObject.Parse(otherjson).ToString();
return nJson == nOtherJson;
}
internal static bool IsNullOrEmpty(this TypeName value)
{
return value == null || value.GetHashCode() == 0;
}
internal static void ThrowIfNullOrEmpty(this string @object, string parameterName, string when = null)
{
@object.ThrowIfNull(parameterName, when);
if (string.IsNullOrWhiteSpace(@object))
throw new ArgumentException("Argument can't be null or empty" + (when.IsNullOrEmpty() ? "" : " when " + when), parameterName);
}
internal static void ThrowIfEmpty<T>(this IEnumerable<T> @object, string parameterName)
{
@object.ThrowIfNull(parameterName);
if ([email protected]())
throw new ArgumentException("Argument can not be an empty collection", parameterName);
}
internal static IList<T> EagerConcat<T>(this IEnumerable<T> list, IEnumerable<T> other)
{
list = list.HasAny() ? list : Enumerable.Empty<T>();
var l = new List<T>(list);
if (other.HasAny()) l.AddRange(other);
return l;
}
internal static bool HasAny<T>(this IEnumerable<T> list, Func<T, bool> predicate)
{
return list != null && list.Any(predicate);
}
internal static bool HasAny<T>(this IEnumerable<T> list)
{
return list != null && list.Any();
}
internal static void ThrowIfNull<T>(this T value, string name, string message = null)
{
if (value == null && message.IsNullOrEmpty()) throw new ArgumentNullException(name);
else if (value == null) throw new ArgumentNullException(name, "Argument can not be null when " + message);
}
internal static string F(this string format, params object[] args)
{
var c = CultureInfo.InvariantCulture;
format.ThrowIfNull(nameof(format));
return string.Format(c, format, args);
}
internal static string EscapedFormat(this string format, params object[] args)
{
format.ThrowIfNull(nameof(format));
var arguments = new List<object>();
foreach (var a in args)
{
var s = a as string;
arguments.Add(s != null ? Uri.EscapeDataString(s) : a);
}
return string.Format(format, arguments.ToArray());
}
internal static bool IsNullOrEmpty(this string value)
{
return string.IsNullOrWhiteSpace(value);
}
internal static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> handler)
{
foreach (T item in enumerable) handler(item);
}
internal static void ForEachWithIndex<T>(this IEnumerable<T> enumerable, Action<T, int> handler)
{
int idx = 0;
foreach (T item in enumerable)
handler(item, idx++);
}
//TODO also filter nulls
internal static List<T> ToListOrNullIfEmpty<T>(this IEnumerable<T> xs, Func<T, bool> predicate) =>
!xs.HasAny(predicate) ? null : xs.ToList();
internal static List<T> ToListOrNullIfEmpty<T>(this IEnumerable<T> enumerable) =>
enumerable.HasAny() ? enumerable.ToList() : null;
internal static void AddIfNotNull<T>(this IList<T> list, T item) where T : class
{
if (item == null) return;
list.Add(item);
}
internal static Dictionary<TKey, TValue> NullIfNoKeys<TKey, TValue>(this Dictionary<TKey, TValue> dictionary)
{
var i = dictionary?.Count;
return i.GetValueOrDefault(0) > 0 ? dictionary : null;
}
internal static IDictionary<TKey, TValue> NullIfNoKeys<TKey, TValue>(this IDictionary<TKey, TValue> dictionary)
{
var i = dictionary?.Count;
return i.GetValueOrDefault(0) > 0 ? dictionary : null;
}
internal static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> xs) => xs ?? new T[0];
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Rssdp
{
/// <summary>
/// Represents a custom HTTP header sent on device search response or notification messages.
/// </summary>
public sealed class CustomHttpHeader
{
#region Fields
private string _Name;
private string _Value;
#endregion
#region Constructors
/// <summary>
/// Full constructor.
/// </summary>
/// <param name="name">The field name of the header.</param>
/// <param name="value">The value of the header</param>
/// <remarks>
/// <para>As per RFC 822 and 2616, the name must contain only printable ASCII characters (33-126) excluding colon (:). The value may contain any ASCII characters except carriage return or line feed.</para>
/// </remarks>
/// <exception cref="System.ArgumentNullException">Thrown if the name is null.</exception>
/// <exception cref="System.ArgumentException">Thrown if the name is an empty value, or contains an invalid character. Also thrown if the value contains a \r or \n character.</exception>
public CustomHttpHeader(string name, string value)
{
Name = name;
Value = value;
}
#endregion
#region Public Properties
/// <summary>
/// Return the name of this header.
/// </summary>
public string Name
{
get { return _Name; }
private set
{
EnsureValidName(value);
_Name = value;
}
}
/// <summary>
/// Returns the value of this header.
/// </summary>
public string Value
{
get { return _Value; }
private set
{
EnsureValidValue(value);
_Value = value;
}
}
#endregion
#region Overrides
/// <summary>
/// Returns the header formatted for use in an HTTP message.
/// </summary>
/// <returns>A string representing this header in the format of 'name: value'.</returns>
public override string ToString()
{
return this.Name + ": " + this.Value;
}
#endregion
#region Private Methods
private static void EnsureValidName(string name)
{
if (name == null) throw new ArgumentNullException(nameof(name), "Name cannot be null.");
if (name.Length == 0) throw new ArgumentException("Name cannot be blank.", nameof(name));
foreach (var c in name)
{
var b = (byte)c;
if (c == ':' || b < 33 || b > 126) throw new ArgumentException("Name contains illegal characters.", nameof(name));
}
}
private static void EnsureValidValue(string value)
{
if (String.IsNullOrEmpty(value)) return;
if (value.Contains("\r") || value.Contains("\n")) throw new ArgumentException("Invalid value.", nameof(value));
}
#endregion
}
/// <summary>
/// Represents a collection of custom HTTP headers, keyed by name.
/// </summary>
public class CustomHttpHeadersCollection : IEnumerable<CustomHttpHeader>
{
#region Fields
private IDictionary<string, CustomHttpHeader> _Headers;
#endregion
#region Constructors
/// <summary>
/// Default constructor.
/// </summary>
public CustomHttpHeadersCollection()
{
_Headers = new Dictionary<string, CustomHttpHeader>(StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Full constructor.
/// </summary>
/// <param name="capacity">Specifies the initial capacity of the collection.</param>
public CustomHttpHeadersCollection(int capacity)
{
_Headers = new Dictionary<string, CustomHttpHeader>(capacity);
}
#endregion
#region Public Methpds
/// <summary>
/// Adds a <see cref="CustomHttpHeader"/> instance to the collection.
/// </summary>
/// <param name="header">The <see cref="CustomHttpHeader"/> instance to add to the collection.</param>
/// <remarks>
/// <para></para>
/// </remarks>
/// <exception cref="System.ArgumentNullException">Thrown if <paramref name="header"/> is null.</exception>
public void Add(CustomHttpHeader header)
{
if (header == null) throw new ArgumentNullException(nameof(header));
lock (_Headers)
{
_Headers.Add(header.Name, header);
}
}
#region Remove Overloads
/// <summary>
/// Removes the specified header instance from the collection.
/// </summary>
/// <param name="header">The <see cref="CustomHttpHeader"/> instance to remove from the collection.</param>
/// <remarks>
/// <para>Only removes the specified header if that instance was in the collection, if another header with the same name exists in the collection it is not removed.</para>
/// </remarks>
/// <returns>True if an item was removed from the collection, otherwise false (because it did not exist or was not the same instance).</returns>
/// <seealso cref="Remove(string)"/>
/// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="header"/> is null.</exception>
public bool Remove(CustomHttpHeader header)
{
if (header == null) throw new ArgumentNullException(nameof(header));
lock (_Headers)
{
if (_Headers.ContainsKey(header.Name) && _Headers[header.Name] == header)
return _Headers.Remove(header.Name);
}
return false;
}
/// <summary>
/// Removes the property with the specified key (<see cref="CustomHttpHeader.Name"/> from the collection.
/// </summary>
/// <param name="headerName">The name of the <see cref="CustomHttpHeader"/> instance to remove from the collection.</param>
/// <returns>True if an item was removed from the collection, otherwise false (because no item exists in the collection with that key).</returns>
/// <exception cref="System.ArgumentException">Thrown if the <paramref name="headerName"/> argument is null or empty string.</exception>
public bool Remove(string headerName)
{
if (String.IsNullOrEmpty(headerName)) throw new ArgumentException("headerName cannot be null or empty.", nameof(headerName));
lock (_Headers)
{
return _Headers.Remove(headerName);
}
}
#endregion
/// <summary>
/// Returns a boolean indicating whether or not the specified <see cref="CustomHttpHeader"/> instance is in the collection.
/// </summary>
/// <param name="header">An <see cref="CustomHttpHeader"/> instance to check the collection for.</param>
/// <returns>True if the specified instance exists in the collection, otherwise false.</returns>
public bool Contains(CustomHttpHeader header)
{
if (header == null) throw new ArgumentNullException(nameof(header));
lock (_Headers)
{
if (_Headers.ContainsKey(header.Name))
return _Headers[header.Name] == header;
}
return false;
}
/// <summary>
/// Returns a boolean indicating whether or not a <see cref="CustomHttpHeader"/> instance with the specified full name value exists in the collection.
/// </summary>
/// <param name="headerName">A string containing the full name of the <see cref="CustomHttpHeader"/> instance to check for.</param>
/// <returns>True if an item with the specified full name exists in the collection, otherwise false.</returns>
public bool Contains(string headerName)
{
if (String.IsNullOrEmpty(headerName)) throw new ArgumentException("headerName cannot be null or empty.", nameof(headerName));
lock (_Headers)
{
return _Headers.ContainsKey(headerName);
}
}
#endregion
#region Public Properties
/// <summary>
/// Returns the number of items in the collection.
/// </summary>
public int Count
{
get { return _Headers.Count; }
}
/// <summary>
/// Returns the <see cref="CustomHttpHeader"/> instance from the collection that has the specified <see cref="CustomHttpHeader.Name"/> value.
/// </summary>
/// <param name="name">The full name of the property to return.</param>
/// <returns>A <see cref="CustomHttpHeader"/> instance from the collection.</returns>
/// <exception cref="System.Collections.Generic.KeyNotFoundException">Thrown if no item exists in the collection with the specified <paramref name="name"/> value.</exception>
public CustomHttpHeader this[string name]
{
get
{
return _Headers[name];
}
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator of <see cref="CustomHttpHeader"/> instances in this collection.
/// </summary>
/// <returns>An enumerator of <see cref="CustomHttpHeader"/> instances in this collection.</returns>
public IEnumerator<CustomHttpHeader> GetEnumerator()
{
lock (_Headers)
{
return _Headers.Values.GetEnumerator();
}
}
/// <summary>
/// Returns an enumerator of <see cref="CustomHttpHeader"/> instances in this collection.
/// </summary>
/// <returns>An enumerator of <see cref="CustomHttpHeader"/> instances in this collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
lock (_Headers)
{
return _Headers.Values.GetEnumerator();
}
}
#endregion
}
}
| |
using SharpFlame.Generators;
using SharpFlame.Mapping.Tiles;
using SharpFlame.Maths;
using SharpFlame.Util;
namespace SharpFlame.Painters
{
internal sealed class PainterFactory
{
public static void CreatePainterArizona()
{
CliffBrush NewBrushCliff;
TransitionBrush NewBrush;
RoadBrush NewRoadBrush;
App.Painter_Arizona = new Painter();
//arizona
var Terrain_Red = new Terrain();
Terrain_Red.Name = "Red";
App.Painter_Arizona.AddTerrain(Terrain_Red);
var Terrain_Yellow = new Terrain();
Terrain_Yellow.Name = "Yellow";
App.Painter_Arizona.AddTerrain(Terrain_Yellow);
var Terrain_Sand = new Terrain();
Terrain_Sand.Name = "Sand";
App.Painter_Arizona.AddTerrain(Terrain_Sand);
var Terrain_Brown = new Terrain();
Terrain_Brown.Name = "Brown";
App.Painter_Arizona.AddTerrain(Terrain_Brown);
var Terrain_Green = new Terrain();
Terrain_Green.Name = "Green";
App.Painter_Arizona.AddTerrain(Terrain_Green);
var Terrain_Concrete = new Terrain();
Terrain_Concrete.Name = "Concrete";
App.Painter_Arizona.AddTerrain(Terrain_Concrete);
var Terrain_Water = new Terrain();
Terrain_Water.Name = "Water";
App.Painter_Arizona.AddTerrain(Terrain_Water);
//red centre brush
Terrain_Red.Tiles.TileAdd(48, TileUtil.None, 1);
Terrain_Red.Tiles.TileAdd(53, TileUtil.None, 1);
Terrain_Red.Tiles.TileAdd(54, TileUtil.None, 1);
Terrain_Red.Tiles.TileAdd(76, TileUtil.None, 1);
//yellow centre brushTerrain_yellow
Terrain_Yellow.Tiles.TileAdd(9, TileUtil.None, 1);
Terrain_Yellow.Tiles.TileAdd(11, TileUtil.None, 1);
//sand centre brush
Terrain_Sand.Tiles.TileAdd(12, TileUtil.None, 1);
//brown centre brush
Terrain_Brown.Tiles.TileAdd(5, TileUtil.None, 1);
Terrain_Brown.Tiles.TileAdd(6, TileUtil.None, 1);
Terrain_Brown.Tiles.TileAdd(7, TileUtil.None, 1);
Terrain_Brown.Tiles.TileAdd(8, TileUtil.None, 1);
//green centre brush
Terrain_Green.Tiles.TileAdd(23, TileUtil.None, 1);
//concrete centre brush
Terrain_Concrete.Tiles.TileAdd(22, TileUtil.None, 1);
//water centre brush
Terrain_Water.Tiles.TileAdd(17, TileUtil.None, 1);
//red cliff brush
NewBrushCliff = new CliffBrush();
NewBrushCliff.Name = "Red Cliff";
NewBrushCliff.Terrain_Inner = Terrain_Red;
NewBrushCliff.Terrain_Outer = Terrain_Red;
NewBrushCliff.Tiles_Straight.TileAdd(46, TileUtil.Bottom, 1);
NewBrushCliff.Tiles_Straight.TileAdd(71, TileUtil.Bottom, 1);
NewBrushCliff.Tiles_Corner_In.TileAdd(45, TileUtil.TopRight, 1);
NewBrushCliff.Tiles_Corner_In.TileAdd(75, TileUtil.TopLeft, 1);
NewBrushCliff.Tiles_Corner_Out.TileAdd(45, TileUtil.BottomLeft, 1);
NewBrushCliff.Tiles_Corner_Out.TileAdd(75, TileUtil.BottomRight, 1);
App.Painter_Arizona.AddBrush(NewBrushCliff);
//water to sand transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Water->Sand";
NewBrush.TerrainInner = Terrain_Water;
NewBrush.TerrainOuter = Terrain_Sand;
NewBrush.TilesStraight.TileAdd(14, TileUtil.Bottom, 1);
NewBrush.TilesCornerIn.TileAdd(16, TileUtil.BottomLeft, 1);
NewBrush.TilesCornerOut.TileAdd(15, TileUtil.BottomLeft, 1);
App.Painter_Arizona.AddBrush(NewBrush);
//water to green transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Water->Green";
NewBrush.TerrainInner = Terrain_Water;
NewBrush.TerrainOuter = Terrain_Green;
NewBrush.TilesStraight.TileAdd(31, TileUtil.Top, 1);
NewBrush.TilesCornerIn.TileAdd(33, TileUtil.TopLeft, 1);
NewBrush.TilesCornerOut.TileAdd(32, TileUtil.TopLeft, 1);
App.Painter_Arizona.AddBrush(NewBrush);
//yellow to red transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Yellow->Red";
NewBrush.TerrainInner = Terrain_Yellow;
NewBrush.TerrainOuter = Terrain_Red;
NewBrush.TilesStraight.TileAdd(27, TileUtil.Right, 1);
NewBrush.TilesCornerIn.TileAdd(28, TileUtil.BottomRight, 1);
NewBrush.TilesCornerOut.TileAdd(29, TileUtil.BottomRight, 1);
App.Painter_Arizona.AddBrush(NewBrush);
//sand to red transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Sand->Red";
NewBrush.TerrainInner = Terrain_Sand;
NewBrush.TerrainOuter = Terrain_Red;
NewBrush.TilesStraight.TileAdd(43, TileUtil.Left, 1);
NewBrush.TilesCornerIn.TileAdd(42, TileUtil.TopLeft, 1);
NewBrush.TilesCornerOut.TileAdd(41, TileUtil.TopLeft, 1);
App.Painter_Arizona.AddBrush(NewBrush);
//sand to yellow transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Sand->Yellow";
NewBrush.TerrainInner = Terrain_Sand;
NewBrush.TerrainOuter = Terrain_Yellow;
NewBrush.TilesStraight.TileAdd(10, TileUtil.Left, 1);
NewBrush.TilesCornerIn.TileAdd(1, TileUtil.TopLeft, 1);
NewBrush.TilesCornerOut.TileAdd(0, TileUtil.TopLeft, 1);
App.Painter_Arizona.AddBrush(NewBrush);
//brown to red transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Brown->Red";
NewBrush.TerrainInner = Terrain_Brown;
NewBrush.TerrainOuter = Terrain_Red;
NewBrush.TilesStraight.TileAdd(34, TileUtil.Left, 1);
NewBrush.TilesCornerIn.TileAdd(36, TileUtil.TopLeft, 1);
NewBrush.TilesCornerOut.TileAdd(35, TileUtil.TopLeft, 1);
App.Painter_Arizona.AddBrush(NewBrush);
//brown to yellow transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Brown->Yellow";
NewBrush.TerrainInner = Terrain_Brown;
NewBrush.TerrainOuter = Terrain_Yellow;
NewBrush.TilesStraight.TileAdd(38, TileUtil.Left, 1);
NewBrush.TilesCornerIn.TileAdd(39, TileUtil.BottomRight, 1);
NewBrush.TilesCornerOut.TileAdd(40, TileUtil.BottomRight, 1);
App.Painter_Arizona.AddBrush(NewBrush);
//brown to sand transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Brown->Sand";
NewBrush.TerrainInner = Terrain_Brown;
NewBrush.TerrainOuter = Terrain_Sand;
NewBrush.TilesStraight.TileAdd(2, TileUtil.Left, 1);
NewBrush.TilesCornerIn.TileAdd(3, TileUtil.BottomRight, 1);
NewBrush.TilesCornerOut.TileAdd(4, TileUtil.BottomRight, 1);
App.Painter_Arizona.AddBrush(NewBrush);
//brown to green transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Brown->Green";
NewBrush.TerrainInner = Terrain_Brown;
NewBrush.TerrainOuter = Terrain_Green;
NewBrush.TilesStraight.TileAdd(24, TileUtil.Left, 1);
NewBrush.TilesCornerIn.TileAdd(26, TileUtil.TopLeft, 1);
NewBrush.TilesCornerOut.TileAdd(25, TileUtil.TopLeft, 1);
App.Painter_Arizona.AddBrush(NewBrush);
//concrete to red transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Concrete->Red";
NewBrush.TerrainInner = Terrain_Concrete;
NewBrush.TerrainOuter = Terrain_Red;
NewBrush.TilesStraight.TileAdd(21, TileUtil.Right, 1);
NewBrush.TilesCornerIn.TileAdd(19, TileUtil.BottomRight, 1);
NewBrush.TilesCornerOut.TileAdd(20, TileUtil.BottomRight, 1);
App.Painter_Arizona.AddBrush(NewBrush);
var Road_Road = new Road();
Road_Road = new Road();
Road_Road.Name = "Road";
App.Painter_Arizona.AddRoad(Road_Road);
var Road_Track = new Road();
Road_Track = new Road();
Road_Track.Name = "Track";
App.Painter_Arizona.AddRoad(Road_Track);
//road
NewRoadBrush = new RoadBrush();
NewRoadBrush.Road = Road_Road;
NewRoadBrush.Terrain = Terrain_Red;
NewRoadBrush.Tile_TIntersection.TileAdd(57, TileUtil.Bottom, 1);
NewRoadBrush.Tile_Straight.TileAdd(59, TileUtil.Left, 1);
NewRoadBrush.Tile_End.TileAdd(47, TileUtil.Left, 1);
App.Painter_Arizona.AddBrush(NewRoadBrush);
//track
NewRoadBrush = new RoadBrush();
NewRoadBrush.Road = Road_Track;
NewRoadBrush.Terrain = Terrain_Red;
NewRoadBrush.Tile_CrossIntersection.TileAdd(73, TileUtil.None, 1);
NewRoadBrush.Tile_TIntersection.TileAdd(72, TileUtil.Right, 1);
NewRoadBrush.Tile_Straight.TileAdd(49, TileUtil.Top, 1);
NewRoadBrush.Tile_Straight.TileAdd(51, TileUtil.Top, 2);
NewRoadBrush.Tile_Corner_In.TileAdd(50, TileUtil.BottomRight, 1);
NewRoadBrush.Tile_End.TileAdd(52, TileUtil.Bottom, 1);
App.Painter_Arizona.AddBrush(NewRoadBrush);
DefaultGenerator.Generator_TilesetArizona.OldTextureLayers.Layers = new clsLayer[0];
DefaultGenerator.Generator_TilesetArizona.OldTextureLayers.LayerCount = 0;
var NewLayer = default(clsLayer);
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetArizona.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetArizona.OldTextureLayers.LayerCount, NewLayer);
NewLayer.Terrain = Terrain_Red;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = (float)MathUtil.RadOf90Deg;
NewLayer.Scale = 0.0F;
NewLayer.Density = 1.0F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetArizona.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetArizona.OldTextureLayers.LayerCount, NewLayer);
NewLayer.Terrain = Terrain_Sand;
NewLayer.HeightMax = -1.0F; //signals water distribution
NewLayer.SlopeMax = -1.0F; //signals water distribution
NewLayer.Scale = 0.0F;
NewLayer.Density = 1.0F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetArizona.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetArizona.OldTextureLayers.LayerCount, NewLayer);
NewLayer.WithinLayer = 1;
NewLayer.Terrain = Terrain_Water;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = (float)MathUtil.RadOf90Deg;
NewLayer.Scale = 0.0F;
NewLayer.Density = 1.0F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetArizona.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetArizona.OldTextureLayers.LayerCount, NewLayer);
NewLayer.AvoidLayers[1] = true;
NewLayer.Terrain = Terrain_Brown;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = -1.0F; //signals to use cliff angle
NewLayer.Scale = 3.0F;
NewLayer.Density = 0.35F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetArizona.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetArizona.OldTextureLayers.LayerCount, NewLayer);
NewLayer.AvoidLayers[1] = true;
NewLayer.AvoidLayers[3] = true;
NewLayer.Terrain = Terrain_Yellow;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = -1.0F; //signals to use cliff angle
NewLayer.Scale = 2.0F;
NewLayer.Density = 0.6F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetArizona.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetArizona.OldTextureLayers.LayerCount, NewLayer);
NewLayer.AvoidLayers[1] = true;
NewLayer.WithinLayer = 4;
NewLayer.Terrain = Terrain_Sand;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = (float)MathUtil.RadOf90Deg;
NewLayer.Scale = 1.0F;
NewLayer.Density = 0.5F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetArizona.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetArizona.OldTextureLayers.LayerCount, NewLayer);
NewLayer.AvoidLayers[1] = true;
NewLayer.WithinLayer = 3;
NewLayer.Terrain = Terrain_Green;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = (float)MathUtil.RadOf90Deg;
NewLayer.Scale = 2.0F;
NewLayer.Density = 0.4F;
}
public static void CreatePainterUrban()
{
var NewBrushCliff = default(CliffBrush);
var NewBrush = default(TransitionBrush);
var NewRoadBrush = default(RoadBrush);
//urban
App.Painter_Urban = new Painter();
var Terrain_Green = new Terrain();
Terrain_Green.Name = "Green";
App.Painter_Urban.AddTerrain(Terrain_Green);
var Terrain_Blue = new Terrain();
Terrain_Blue.Name = "Blue";
App.Painter_Urban.AddTerrain(Terrain_Blue);
var Terrain_Gray = new Terrain();
Terrain_Gray.Name = "Gray";
App.Painter_Urban.AddTerrain(Terrain_Gray);
var Terrain_Orange = new Terrain();
Terrain_Orange.Name = "Orange";
App.Painter_Urban.AddTerrain(Terrain_Orange);
var Terrain_Concrete = new Terrain();
Terrain_Concrete.Name = "Concrete";
App.Painter_Urban.AddTerrain(Terrain_Concrete);
var Terrain_Water = new Terrain();
Terrain_Water.Name = "Water";
App.Painter_Urban.AddTerrain(Terrain_Water);
//green centre brush
Terrain_Green.Tiles.TileAdd(50, TileUtil.None, 1);
//blue centre brush
Terrain_Blue.Tiles.TileAdd(0, TileUtil.None, 14);
Terrain_Blue.Tiles.TileAdd(2, TileUtil.None, 1); //line
//gray centre brush
Terrain_Gray.Tiles.TileAdd(5, TileUtil.None, 1);
Terrain_Gray.Tiles.TileAdd(7, TileUtil.None, 4);
Terrain_Gray.Tiles.TileAdd(8, TileUtil.None, 4);
Terrain_Gray.Tiles.TileAdd(78, TileUtil.None, 4);
//orange centre brush
Terrain_Orange.Tiles.TileAdd(31, TileUtil.None, 1); //pipe
Terrain_Orange.Tiles.TileAdd(22, TileUtil.None, 50);
//concrete centre brush
Terrain_Concrete.Tiles.TileAdd(51, TileUtil.None, 200);
//water centre brush
Terrain_Water.Tiles.TileAdd(17, TileUtil.None, 1);
//cliff brush
NewBrushCliff = new CliffBrush();
NewBrushCliff.Name = "Cliff";
NewBrushCliff.Terrain_Inner = Terrain_Gray;
NewBrushCliff.Terrain_Outer = Terrain_Gray;
NewBrushCliff.Tiles_Straight.TileAdd(69, TileUtil.Bottom, 1);
NewBrushCliff.Tiles_Straight.TileAdd(70, TileUtil.Bottom, 1);
NewBrushCliff.Tiles_Corner_In.TileAdd(68, TileUtil.TopRight, 1);
NewBrushCliff.Tiles_Corner_Out.TileAdd(68, TileUtil.BottomLeft, 1);
App.Painter_Urban.AddBrush(NewBrushCliff);
//water to gray transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Water->Gray";
NewBrush.TerrainInner = Terrain_Water;
NewBrush.TerrainOuter = Terrain_Gray;
NewBrush.TilesStraight.TileAdd(23, TileUtil.Left, 1);
NewBrush.TilesStraight.TileAdd(24, TileUtil.Top, 1);
NewBrush.TilesCornerIn.TileAdd(25, TileUtil.TopLeft, 1);
NewBrush.TilesCornerOut.TileAdd(26, TileUtil.TopLeft, 1);
App.Painter_Urban.AddBrush(NewBrush);
//water to concrete transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Water->Concrete";
NewBrush.TerrainInner = Terrain_Water;
NewBrush.TerrainOuter = Terrain_Concrete;
NewBrush.TilesStraight.TileAdd(13, TileUtil.Left, 1);
NewBrush.TilesStraight.TileAdd(14, TileUtil.Bottom, 1);
NewBrush.TilesCornerIn.TileAdd(16, TileUtil.BottomLeft, 1);
NewBrush.TilesCornerOut.TileAdd(15, TileUtil.BottomLeft, 1);
App.Painter_Urban.AddBrush(NewBrush);
//gray to blue transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Gray->Blue";
NewBrush.TerrainInner = Terrain_Gray;
NewBrush.TerrainOuter = Terrain_Blue;
NewBrush.TilesStraight.TileAdd(6, TileUtil.Left, 1);
NewBrush.TilesCornerIn.TileAdd(4, TileUtil.BottomRight, 1);
NewBrush.TilesCornerOut.TileAdd(3, TileUtil.BottomRight, 1);
App.Painter_Urban.AddBrush(NewBrush);
//concrete to gray transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Concrete->Gray";
NewBrush.TerrainInner = Terrain_Concrete;
NewBrush.TerrainOuter = Terrain_Gray;
NewBrush.TilesStraight.TileAdd(9, TileUtil.Left, 1);
NewBrush.TilesStraight.TileAdd(27, TileUtil.Right, 1);
NewBrush.TilesCornerIn.TileAdd(30, TileUtil.BottomLeft, 1);
NewBrush.TilesCornerOut.TileAdd(10, TileUtil.BottomLeft, 1);
NewBrush.TilesCornerOut.TileAdd(29, TileUtil.BottomLeft, 1);
App.Painter_Urban.AddBrush(NewBrush);
//orange to blue transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Orange->Blue";
NewBrush.TerrainInner = Terrain_Orange;
NewBrush.TerrainOuter = Terrain_Blue;
NewBrush.TilesStraight.TileAdd(33, TileUtil.Right, 1);
NewBrush.TilesCornerIn.TileAdd(34, TileUtil.BottomRight, 1);
NewBrush.TilesCornerOut.TileAdd(35, TileUtil.BottomRight, 1);
App.Painter_Urban.AddBrush(NewBrush);
//orange to green transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Orange->Green";
NewBrush.TerrainInner = Terrain_Orange;
NewBrush.TerrainOuter = Terrain_Green;
NewBrush.TilesStraight.TileAdd(39, TileUtil.Right, 1);
NewBrush.TilesCornerIn.TileAdd(38, TileUtil.TopLeft, 1);
NewBrush.TilesCornerOut.TileAdd(37, TileUtil.TopLeft, 1);
App.Painter_Urban.AddBrush(NewBrush);
//orange to gray transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Orange->Gray";
NewBrush.TerrainInner = Terrain_Orange;
NewBrush.TerrainOuter = Terrain_Gray;
NewBrush.TilesStraight.TileAdd(60, TileUtil.Right, 1);
NewBrush.TilesCornerIn.TileAdd(73, TileUtil.TopLeft, 1);
NewBrush.TilesCornerOut.TileAdd(72, TileUtil.TopLeft, 1);
App.Painter_Urban.AddBrush(NewBrush);
//orange to concrete transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Orange->Concrete";
NewBrush.TerrainInner = Terrain_Orange;
NewBrush.TerrainOuter = Terrain_Concrete;
NewBrush.TilesStraight.TileAdd(71, TileUtil.Right, 1);
NewBrush.TilesCornerIn.TileAdd(76, TileUtil.BottomRight, 1);
NewBrush.TilesCornerOut.TileAdd(75, TileUtil.BottomRight, 1);
App.Painter_Urban.AddBrush(NewBrush);
//gray to green transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Gray->Green";
NewBrush.TerrainInner = Terrain_Gray;
NewBrush.TerrainOuter = Terrain_Green;
NewBrush.TilesStraight.TileAdd(77, TileUtil.Right, 1);
NewBrush.TilesCornerIn.TileAdd(58, TileUtil.BottomLeft, 1);
NewBrush.TilesCornerOut.TileAdd(79, TileUtil.BottomLeft, 1);
App.Painter_Urban.AddBrush(NewBrush);
//road
var Road_Road = new Road();
Road_Road.Name = "Road";
App.Painter_Urban.AddRoad(Road_Road);
//road green
NewRoadBrush = new RoadBrush();
NewRoadBrush.Road = Road_Road;
NewRoadBrush.Terrain = Terrain_Green;
NewRoadBrush.Tile_CrossIntersection.TileAdd(49, TileUtil.None, 1);
NewRoadBrush.Tile_TIntersection.TileAdd(40, TileUtil.Bottom, 1);
NewRoadBrush.Tile_Straight.TileAdd(42, TileUtil.Left, 1);
NewRoadBrush.Tile_End.TileAdd(45, TileUtil.Left, 1);
App.Painter_Urban.AddBrush(NewRoadBrush);
//road blue
NewRoadBrush = new RoadBrush();
NewRoadBrush.Road = Road_Road;
NewRoadBrush.Terrain = Terrain_Blue;
NewRoadBrush.Tile_CrossIntersection.TileAdd(49, TileUtil.None, 1);
NewRoadBrush.Tile_TIntersection.TileAdd(40, TileUtil.Bottom, 1);
NewRoadBrush.Tile_Straight.TileAdd(42, TileUtil.Left, 1);
NewRoadBrush.Tile_End.TileAdd(41, TileUtil.Left, 1);
App.Painter_Urban.AddBrush(NewRoadBrush);
//road gray
NewRoadBrush = new RoadBrush();
NewRoadBrush.Road = Road_Road;
NewRoadBrush.Terrain = Terrain_Gray;
NewRoadBrush.Tile_CrossIntersection.TileAdd(49, TileUtil.None, 1);
NewRoadBrush.Tile_TIntersection.TileAdd(40, TileUtil.Bottom, 1);
NewRoadBrush.Tile_Straight.TileAdd(42, TileUtil.Left, 1);
NewRoadBrush.Tile_End.TileAdd(43, TileUtil.Left, 1);
NewRoadBrush.Tile_End.TileAdd(44, TileUtil.Left, 1);
App.Painter_Urban.AddBrush(NewRoadBrush);
//road orange
NewRoadBrush = new RoadBrush();
NewRoadBrush.Road = Road_Road;
NewRoadBrush.Terrain = Terrain_Orange;
NewRoadBrush.Tile_CrossIntersection.TileAdd(49, TileUtil.None, 1);
NewRoadBrush.Tile_TIntersection.TileAdd(40, TileUtil.Bottom, 1);
NewRoadBrush.Tile_Straight.TileAdd(42, TileUtil.Left, 1);
App.Painter_Urban.AddBrush(NewRoadBrush);
//road concrete
NewRoadBrush = new RoadBrush();
NewRoadBrush.Road = Road_Road;
NewRoadBrush.Terrain = Terrain_Concrete;
NewRoadBrush.Tile_CrossIntersection.TileAdd(49, TileUtil.None, 1);
NewRoadBrush.Tile_TIntersection.TileAdd(40, TileUtil.Bottom, 1);
NewRoadBrush.Tile_Straight.TileAdd(42, TileUtil.Left, 1);
App.Painter_Urban.AddBrush(NewRoadBrush);
DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.Layers = new clsLayer[0];
DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.LayerCount = 0;
var NewLayer = default(clsLayer);
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.LayerCount, NewLayer);
NewLayer.Terrain = Terrain_Gray;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = (float)MathUtil.RadOf90Deg;
NewLayer.Scale = 0.0F;
NewLayer.Density = 1.0F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.LayerCount, NewLayer);
NewLayer.Terrain = Terrain_Water;
NewLayer.HeightMax = -1.0F;
NewLayer.SlopeMax = -1.0F;
NewLayer.Scale = 0.0F;
NewLayer.Density = 1.0F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.LayerCount, NewLayer);
NewLayer.AvoidLayers[1] = true;
NewLayer.Terrain = Terrain_Blue;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = -1.0F;
NewLayer.Scale = 3.0F;
NewLayer.Density = 0.3F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.LayerCount, NewLayer);
NewLayer.AvoidLayers[1] = true;
NewLayer.AvoidLayers[2] = true;
NewLayer.Terrain = Terrain_Orange;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = -1.0F;
NewLayer.Scale = 2.5F;
NewLayer.Density = 0.4F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.LayerCount, NewLayer);
NewLayer.AvoidLayers[1] = true;
NewLayer.AvoidLayers[2] = true;
NewLayer.AvoidLayers[3] = true;
NewLayer.Terrain = Terrain_Concrete;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = -1.0F;
NewLayer.Scale = 1.5F;
NewLayer.Density = 0.6F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.LayerCount, NewLayer);
NewLayer.AvoidLayers[1] = true;
NewLayer.AvoidLayers[2] = true;
NewLayer.AvoidLayers[3] = true;
NewLayer.AvoidLayers[4] = true;
NewLayer.Terrain = Terrain_Green;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = -1.0F;
NewLayer.Scale = 2.5F;
NewLayer.Density = 0.6F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.LayerCount, NewLayer);
NewLayer.WithinLayer = 2;
NewLayer.Terrain = Terrain_Orange;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = (float)MathUtil.RadOf90Deg;
NewLayer.Scale = 1.5F;
NewLayer.Density = 0.5F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.LayerCount, NewLayer);
NewLayer.WithinLayer = 3;
NewLayer.Terrain = Terrain_Blue;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = (float)MathUtil.RadOf90Deg;
NewLayer.Scale = 1.5F;
NewLayer.Density = 0.5F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetUrban.OldTextureLayers.LayerCount, NewLayer);
NewLayer.WithinLayer = 3;
NewLayer.AvoidLayers[7] = true;
NewLayer.Terrain = Terrain_Green;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = (float)MathUtil.RadOf90Deg;
NewLayer.Scale = 1.5F;
NewLayer.Density = 0.5F;
}
public static void CreatePainterRockies()
{
var NewBrushCliff = default(CliffBrush);
var NewBrush = default(TransitionBrush);
var NewRoadBrush = default(RoadBrush);
App.Painter_Rockies = new Painter();
var Terrain_Grass = new Terrain();
Terrain_Grass.Name = "Grass";
App.Painter_Rockies.AddTerrain(Terrain_Grass);
var Terrain_Gravel = new Terrain();
Terrain_Gravel.Name = "Gravel";
App.Painter_Rockies.AddTerrain(Terrain_Gravel);
var Terrain_Dirt = new Terrain();
Terrain_Dirt.Name = "Dirt";
App.Painter_Rockies.AddTerrain(Terrain_Dirt);
var Terrain_GrassSnow = new Terrain();
Terrain_GrassSnow.Name = "Grass Snow";
App.Painter_Rockies.AddTerrain(Terrain_GrassSnow);
var Terrain_GravelSnow = new Terrain();
Terrain_GravelSnow.Name = "Gravel Snow";
App.Painter_Rockies.AddTerrain(Terrain_GravelSnow);
var Terrain_Snow = new Terrain();
Terrain_Snow.Name = "Snow";
App.Painter_Rockies.AddTerrain(Terrain_Snow);
var Terrain_Concrete = new Terrain();
Terrain_Concrete.Name = "Concrete";
App.Painter_Rockies.AddTerrain(Terrain_Concrete);
var Terrain_Water = new Terrain();
Terrain_Water.Name = "Water";
App.Painter_Rockies.AddTerrain(Terrain_Water);
//grass centre brush
Terrain_Grass.Tiles.TileAdd(0, TileUtil.None, 1);
//gravel centre brush
Terrain_Gravel.Tiles.TileAdd(5, TileUtil.None, 1);
Terrain_Gravel.Tiles.TileAdd(6, TileUtil.None, 1);
Terrain_Gravel.Tiles.TileAdd(7, TileUtil.None, 1);
//dirt centre brush
Terrain_Dirt.Tiles.TileAdd(53, TileUtil.None, 1);
//grass snow centre brush
Terrain_GrassSnow.Tiles.TileAdd(23, TileUtil.None, 1);
//gravel snow centre brush
Terrain_GravelSnow.Tiles.TileAdd(41, TileUtil.None, 1);
//snow centre brush
Terrain_Snow.Tiles.TileAdd(64, TileUtil.None, 1);
//concrete centre brush
Terrain_Concrete.Tiles.TileAdd(22, TileUtil.None, 1);
//water centre brush
Terrain_Water.Tiles.TileAdd(17, TileUtil.None, 1);
//gravel to gravel cliff brush
NewBrushCliff = new CliffBrush();
NewBrushCliff.Name = "Gravel Cliff";
NewBrushCliff.Terrain_Inner = Terrain_Gravel;
NewBrushCliff.Terrain_Outer = Terrain_Gravel;
NewBrushCliff.Tiles_Straight.TileAdd(46, TileUtil.Bottom, 1);
NewBrushCliff.Tiles_Straight.TileAdd(71, TileUtil.Bottom, 1);
NewBrushCliff.Tiles_Corner_In.TileAdd(45, TileUtil.TopRight, 1);
NewBrushCliff.Tiles_Corner_Out.TileAdd(45, TileUtil.BottomLeft, 1);
App.Painter_Rockies.AddBrush(NewBrushCliff);
//gravel snow to gravel cliff brush
NewBrushCliff = new CliffBrush();
NewBrushCliff.Name = "Gravel Snow -> Gravel Cliff";
NewBrushCliff.Terrain_Inner = Terrain_GravelSnow;
NewBrushCliff.Terrain_Outer = Terrain_Gravel;
NewBrushCliff.Tiles_Straight.TileAdd(29, TileUtil.Bottom, 1);
NewBrushCliff.Tiles_Corner_In.TileAdd(9, TileUtil.TopLeft, 1);
NewBrushCliff.Tiles_Corner_Out.TileAdd(42, TileUtil.BottomLeft, 1);
App.Painter_Rockies.AddBrush(NewBrushCliff);
//snow to gravel cliff brush
NewBrushCliff = new CliffBrush();
NewBrushCliff.Name = "Snow -> Gravel Cliff";
NewBrushCliff.Terrain_Inner = Terrain_Snow;
NewBrushCliff.Terrain_Outer = Terrain_Gravel;
NewBrushCliff.Tiles_Straight.TileAdd(68, TileUtil.Bottom, 1);
NewBrushCliff.Tiles_Corner_In.TileAdd(63, TileUtil.TopLeft, 1);
NewBrushCliff.Tiles_Corner_Out.TileAdd(42, TileUtil.BottomLeft, 1);
App.Painter_Rockies.AddBrush(NewBrushCliff);
//gravel snow cliff brush
NewBrushCliff = new CliffBrush();
NewBrushCliff.Name = "Gravel Snow Cliff";
NewBrushCliff.Terrain_Inner = Terrain_GravelSnow;
NewBrushCliff.Terrain_Outer = Terrain_GravelSnow;
NewBrushCliff.Tiles_Straight.TileAdd(44, TileUtil.Bottom, 1);
NewBrushCliff.Tiles_Corner_In.TileAdd(9, TileUtil.TopLeft, 1);
NewBrushCliff.Tiles_Corner_Out.TileAdd(9, TileUtil.BottomRight, 1);
App.Painter_Rockies.AddBrush(NewBrushCliff);
//snow to gravel snow cliff brush
NewBrushCliff = new CliffBrush();
NewBrushCliff.Name = "Snow -> Gravel Snow Cliff";
NewBrushCliff.Terrain_Inner = Terrain_Snow;
NewBrushCliff.Terrain_Outer = Terrain_GravelSnow;
NewBrushCliff.Tiles_Straight.TileAdd(78, TileUtil.Bottom, 1);
NewBrushCliff.Tiles_Corner_In.TileAdd(63, TileUtil.TopLeft, 1);
NewBrushCliff.Tiles_Corner_Out.TileAdd(9, TileUtil.BottomRight, 1);
App.Painter_Rockies.AddBrush(NewBrushCliff);
//snow to snow cliff brush
NewBrushCliff = new CliffBrush();
NewBrushCliff.Name = "Snow -> Snow Cliff";
NewBrushCliff.Terrain_Inner = Terrain_Snow;
NewBrushCliff.Terrain_Outer = Terrain_Snow;
NewBrushCliff.Tiles_Straight.TileAdd(78, TileUtil.Bottom, 1);
NewBrushCliff.Tiles_Corner_In.TileAdd(63, TileUtil.TopLeft, 1);
NewBrushCliff.Tiles_Corner_Out.TileAdd(63, TileUtil.BottomRight, 1);
App.Painter_Rockies.AddBrush(NewBrushCliff);
//water to grass transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Water -> Grass";
NewBrush.TerrainInner = Terrain_Water;
NewBrush.TerrainOuter = Terrain_Grass;
NewBrush.TilesStraight.TileAdd(14, TileUtil.Bottom, 1);
NewBrush.TilesCornerIn.TileAdd(16, TileUtil.BottomLeft, 1);
NewBrush.TilesCornerOut.TileAdd(15, TileUtil.BottomLeft, 1);
App.Painter_Rockies.AddBrush(NewBrush);
//water to gravel transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Water -> Gravel";
NewBrush.TerrainInner = Terrain_Water;
NewBrush.TerrainOuter = Terrain_Gravel;
NewBrush.TilesStraight.TileAdd(31, TileUtil.Top, 1);
NewBrush.TilesCornerIn.TileAdd(32, TileUtil.TopLeft, 1);
NewBrush.TilesCornerOut.TileAdd(33, TileUtil.TopLeft, 1);
App.Painter_Rockies.AddBrush(NewBrush);
//grass to gravel transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Grass -> Gravel";
NewBrush.TerrainInner = Terrain_Grass;
NewBrush.TerrainOuter = Terrain_Gravel;
NewBrush.TilesStraight.TileAdd(2, TileUtil.Left, 1);
NewBrush.TilesCornerIn.TileAdd(3, TileUtil.TopLeft, 1);
NewBrush.TilesCornerOut.TileAdd(4, TileUtil.TopLeft, 1);
App.Painter_Rockies.AddBrush(NewBrush);
//grass to grass snow transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Grass -> Grass Snow";
NewBrush.TerrainInner = Terrain_Grass;
NewBrush.TerrainOuter = Terrain_GrassSnow;
NewBrush.TilesStraight.TileAdd(26, TileUtil.Top, 1);
NewBrush.TilesCornerIn.TileAdd(25, TileUtil.TopLeft, 1);
NewBrush.TilesCornerOut.TileAdd(24, TileUtil.TopLeft, 1);
App.Painter_Rockies.AddBrush(NewBrush);
//grass to dirt transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Grass -> Dirt";
NewBrush.TerrainInner = Terrain_Grass;
NewBrush.TerrainOuter = Terrain_Dirt;
NewBrush.TilesStraight.TileAdd(34, TileUtil.Right, 1);
NewBrush.TilesCornerIn.TileAdd(35, TileUtil.BottomRight, 1);
NewBrush.TilesCornerOut.TileAdd(36, TileUtil.BottomRight, 1);
App.Painter_Rockies.AddBrush(NewBrush);
//gravel snow to gravel transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Gravel Snow -> Gravel";
NewBrush.TerrainInner = Terrain_GravelSnow;
NewBrush.TerrainOuter = Terrain_Gravel;
NewBrush.TilesStraight.TileAdd(12, TileUtil.Bottom, 1);
NewBrush.TilesCornerIn.TileAdd(10, TileUtil.BottomRight, 1);
NewBrush.TilesCornerOut.TileAdd(11, TileUtil.BottomRight, 1);
App.Painter_Rockies.AddBrush(NewBrush);
//snow to gravel snow transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Snow -> Gravel Snow";
NewBrush.TerrainInner = Terrain_Snow;
NewBrush.TerrainOuter = Terrain_GravelSnow;
NewBrush.TilesStraight.TileAdd(67, TileUtil.Bottom, 1);
NewBrush.TilesCornerIn.TileAdd(65, TileUtil.BottomRight, 1);
NewBrush.TilesCornerOut.TileAdd(66, TileUtil.BottomRight, 1);
App.Painter_Rockies.AddBrush(NewBrush);
//concrete to dirt transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Concrete -> Dirt";
NewBrush.TerrainInner = Terrain_Concrete;
NewBrush.TerrainOuter = Terrain_Dirt;
NewBrush.TilesStraight.TileAdd(21, TileUtil.Right, 1);
NewBrush.TilesCornerIn.TileAdd(19, TileUtil.BottomRight, 1);
NewBrush.TilesCornerOut.TileAdd(20, TileUtil.BottomRight, 1);
App.Painter_Rockies.AddBrush(NewBrush);
//gravel to dirt transition brush
NewBrush = new TransitionBrush();
NewBrush.Name = "Gravel -> Dirt";
NewBrush.TerrainInner = Terrain_Gravel;
NewBrush.TerrainOuter = Terrain_Dirt;
NewBrush.TilesStraight.TileAdd(38, TileUtil.Left, 1);
NewBrush.TilesCornerIn.TileAdd(40, TileUtil.TopLeft, 1);
NewBrush.TilesCornerOut.TileAdd(39, TileUtil.TopLeft, 1);
App.Painter_Rockies.AddBrush(NewBrush);
//road
var Road_Road = new Road();
Road_Road.Name = "Road";
App.Painter_Rockies.AddRoad(Road_Road);
//road brown
NewRoadBrush = new RoadBrush();
NewRoadBrush.Road = Road_Road;
NewRoadBrush.Terrain = Terrain_Dirt;
NewRoadBrush.Tile_TIntersection.TileAdd(13, TileUtil.Bottom, 1);
NewRoadBrush.Tile_Straight.TileAdd(59, TileUtil.Left, 1);
NewRoadBrush.Tile_End.TileAdd(60, TileUtil.Left, 1);
App.Painter_Rockies.AddBrush(NewRoadBrush);
//track
var Road_Track = new Road();
Road_Track.Name = "Track";
App.Painter_Rockies.AddRoad(Road_Track);
//track brown
NewRoadBrush = new RoadBrush();
NewRoadBrush.Road = Road_Track;
NewRoadBrush.Terrain = Terrain_Dirt;
NewRoadBrush.Tile_TIntersection.TileAdd(72, TileUtil.Right, 1);
NewRoadBrush.Tile_Straight.TileAdd(49, TileUtil.Top, 1);
NewRoadBrush.Tile_Straight.TileAdd(51, TileUtil.Top, 2);
NewRoadBrush.Tile_Corner_In.TileAdd(50, TileUtil.BottomRight, 1);
NewRoadBrush.Tile_End.TileAdd(52, TileUtil.Bottom, 1);
App.Painter_Rockies.AddBrush(NewRoadBrush);
DefaultGenerator.Generator_TilesetRockies.OldTextureLayers.Layers = new clsLayer[0];
DefaultGenerator.Generator_TilesetRockies.OldTextureLayers.LayerCount = 0;
var NewLayer = default(clsLayer);
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetRockies.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetRockies.OldTextureLayers.LayerCount, NewLayer);
NewLayer.Terrain = Terrain_Gravel;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = (float)MathUtil.RadOf90Deg;
NewLayer.Scale = 0.0F;
NewLayer.Density = 1.0F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetRockies.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetRockies.OldTextureLayers.LayerCount, NewLayer);
NewLayer.Terrain = Terrain_Water;
NewLayer.HeightMax = -1.0F;
NewLayer.SlopeMax = -1.0F;
NewLayer.Scale = 0.0F;
NewLayer.Density = 1.0F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetRockies.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetRockies.OldTextureLayers.LayerCount, NewLayer);
NewLayer.AvoidLayers[1] = true;
NewLayer.Terrain = Terrain_Grass;
NewLayer.HeightMax = 60.0F;
NewLayer.SlopeMax = -1.0F;
NewLayer.Scale = 0.0F;
NewLayer.Density = 1.0F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetRockies.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetRockies.OldTextureLayers.LayerCount, NewLayer);
NewLayer.AvoidLayers[1] = true;
NewLayer.AvoidLayers[3] = true;
NewLayer.Terrain = Terrain_GravelSnow;
NewLayer.HeightMin = 150.0F;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = (float)MathUtil.RadOf90Deg;
NewLayer.Scale = 0.0F;
NewLayer.Density = 1.0F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetRockies.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetRockies.OldTextureLayers.LayerCount, NewLayer);
NewLayer.WithinLayer = 3;
NewLayer.AvoidLayers[1] = true;
NewLayer.Terrain = Terrain_Snow;
NewLayer.HeightMin = 200.0F;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = (float)MathUtil.RadOf90Deg;
NewLayer.Scale = 0.0F;
NewLayer.Density = 1.0F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetRockies.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetRockies.OldTextureLayers.LayerCount, NewLayer);
NewLayer.WithinLayer = 3;
NewLayer.AvoidLayers[4] = true;
NewLayer.Terrain = Terrain_Snow;
NewLayer.HeightMin = 150.0F;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = -1.0F;
NewLayer.Scale = 1.5F;
NewLayer.Density = 0.45F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetRockies.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetRockies.OldTextureLayers.LayerCount, NewLayer);
NewLayer.AvoidLayers[1] = true;
NewLayer.AvoidLayers[2] = true;
NewLayer.AvoidLayers[3] = true;
NewLayer.Terrain = Terrain_GravelSnow;
NewLayer.HeightMin = 0.0F;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = -1.0F;
NewLayer.Scale = 1.5F;
NewLayer.Density = 0.45F;
NewLayer = new clsLayer();
DefaultGenerator.Generator_TilesetRockies.OldTextureLayers.LayerInsert(DefaultGenerator.Generator_TilesetRockies.OldTextureLayers.LayerCount, NewLayer);
NewLayer.AvoidLayers[1] = true;
NewLayer.WithinLayer = 2;
NewLayer.Terrain = Terrain_Dirt;
NewLayer.HeightMin = 0.0F;
NewLayer.HeightMax = 255.0F;
NewLayer.SlopeMax = (float)MathUtil.RadOf90Deg;
NewLayer.Scale = 1.0F;
NewLayer.Density = 0.3F;
}
}
}
| |
// Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;
namespace DBus
{
using Protocol;
public class BusObject
{
static Dictionary<object,BusObject> boCache = new Dictionary<object,BusObject>();
protected Connection conn;
string bus_name;
ObjectPath object_path;
public BusObject ()
{
}
public BusObject (Connection conn, string bus_name, ObjectPath object_path)
{
this.conn = conn;
this.bus_name = bus_name;
this.object_path = object_path;
}
public Connection Connection
{
get {
return conn;
}
}
public string BusName
{
get {
return bus_name;
}
}
public ObjectPath Path
{
get {
return object_path;
}
}
public void ToggleSignal (string iface, string member, Delegate dlg, bool adding)
{
MatchRule rule = new MatchRule ();
rule.MessageType = MessageType.Signal;
rule.Fields.Add (FieldCode.Interface, new MatchTest (iface));
rule.Fields.Add (FieldCode.Member, new MatchTest (member));
rule.Fields.Add (FieldCode.Path, new MatchTest (object_path));
// FIXME: Cause a regression compared to 0.6 as name wasn't matched before
// the problem arises because busname is not used by DBus daemon and
// instead it uses the canonical name of the sender (i.e. similar to ':1.13')
// rule.Fields.Add (FieldCode.Sender, new MatchTest (bus_name));
if (adding) {
if (conn.Handlers.ContainsKey (rule))
conn.Handlers[rule] = Delegate.Combine (conn.Handlers[rule], dlg);
else {
conn.Handlers[rule] = dlg;
conn.AddMatch (rule.ToString ());
}
} else if (conn.Handlers.ContainsKey (rule)) {
conn.Handlers[rule] = Delegate.Remove (conn.Handlers[rule], dlg);
if (conn.Handlers[rule] == null) {
conn.RemoveMatch (rule.ToString ());
conn.Handlers.Remove (rule);
}
}
}
public void SendSignal (string iface, string member, string inSigStr, MessageWriter writer, Type retType, out Exception exception)
{
exception = null;
Signature outSig = String.IsNullOrEmpty (inSigStr) ? Signature.Empty : new Signature (inSigStr);
MessageContainer signal = new MessageContainer {
Type = MessageType.Signal,
Path = object_path,
Interface = iface,
Member = member,
Signature = outSig,
};
Message signalMsg = signal.Message;
signalMsg.AttachBodyTo (writer);
conn.Send (signalMsg);
}
public MessageReader SendMethodCall (string iface, string member, string inSigStr, MessageWriter writer, Type retType, out Exception exception)
{
if (string.IsNullOrEmpty (bus_name))
throw new ArgumentNullException ("bus_name");
if (object_path == null)
throw new ArgumentNullException ("object_path");
exception = null;
Signature inSig = String.IsNullOrEmpty (inSigStr) ? Signature.Empty : new Signature (inSigStr);
MessageContainer method_call = new MessageContainer {
Path = object_path,
Interface = iface,
Member = member,
Destination = bus_name,
Signature = inSig
};
Message callMsg = method_call.Message;
callMsg.AttachBodyTo (writer);
bool needsReply = true;
callMsg.ReplyExpected = needsReply;
callMsg.Signature = inSig;
if (!needsReply) {
conn.Send (callMsg);
return null;
}
#if PROTO_REPLY_SIGNATURE
if (needsReply) {
Signature outSig = Signature.GetSig (retType);
callMsg.Header[FieldCode.ReplySignature] = outSig;
}
#endif
Message retMsg = conn.SendWithReplyAndBlock (callMsg);
MessageReader retVal = null;
//handle the reply message
switch (retMsg.Header.MessageType) {
case MessageType.MethodReturn:
retVal = new MessageReader (retMsg);
break;
case MessageType.Error:
MessageContainer error = MessageContainer.FromMessage (retMsg);
string errMsg = String.Empty;
if (retMsg.Signature.Value.StartsWith ("s")) {
MessageReader reader = new MessageReader (retMsg);
errMsg = reader.ReadString ();
}
exception = new Exception (error.ErrorName + ": " + errMsg);
break;
default:
throw new Exception ("Got unexpected message of type " + retMsg.Header.MessageType + " while waiting for a MethodReturn or Error");
}
return retVal;
}
public void Invoke (MethodBase methodBase, string methodName, object[] inArgs, out object[] outArgs, out object retVal, out Exception exception)
{
outArgs = new object[0];
retVal = null;
exception = null;
MethodInfo mi = methodBase as MethodInfo;
if (mi != null && mi.IsSpecialName && (methodName.StartsWith ("add_") || methodName.StartsWith ("remove_"))) {
string[] parts = methodName.Split (new char[]{'_'}, 2);
string ename = parts[1];
Delegate dlg = (Delegate)inArgs[0];
ToggleSignal (Mapper.GetInterfaceName (mi), ename, dlg, parts[0] == "add");
return;
}
Type[] inTypes = Mapper.GetTypes (ArgDirection.In, mi.GetParameters ());
Signature inSig = Signature.GetSig (inTypes);
string iface = null;
if (mi != null)
iface = Mapper.GetInterfaceName (mi);
if (mi != null && mi.IsSpecialName) {
methodName = methodName.Replace ("get_", "Get");
methodName = methodName.Replace ("set_", "Set");
}
MessageWriter writer = new MessageWriter (conn);
if (inArgs != null && inArgs.Length != 0) {
for (int i = 0 ; i != inTypes.Length ; i++)
writer.Write (inTypes[i], inArgs[i]);
}
MessageReader reader = SendMethodCall (iface, methodName, inSig.Value, writer, mi.ReturnType, out exception);
if (reader == null)
return;
retVal = reader.ReadValue (mi.ReturnType);
}
public static object GetObject (Connection conn, string bus_name, ObjectPath object_path, Type declType)
{
Type proxyType = TypeImplementer.Root.GetImplementation (declType);
object instObj = Activator.CreateInstance (proxyType);
BusObject inst = GetBusObject (instObj);
inst.conn = conn;
inst.bus_name = bus_name;
inst.object_path = object_path;
return instObj;
}
public static BusObject GetBusObject (object instObj)
{
if (instObj is BusObject)
return (BusObject)instObj;
BusObject inst;
if (boCache.TryGetValue (instObj, out inst))
return inst;
inst = new BusObject ();
boCache[instObj] = inst;
return inst;
}
public Delegate GetHookupDelegate (EventInfo ei)
{
DynamicMethod hookupMethod = TypeImplementer.GetHookupMethod (ei);
Delegate d = hookupMethod.CreateDelegate (ei.EventHandlerType, this);
return d;
}
}
}
| |
// 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.Linq;
using Xunit;
namespace System.Tests
{
public static class GuidTests
{
private static readonly Guid s_testGuid = new Guid("a8a110d5-fc49-43c5-bf46-802db8f843ff");
[Fact]
public static void Empty()
{
Assert.Equal(new Guid(0, 0, 0, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }), Guid.Empty);
}
public static IEnumerable<object[]> Ctor_ByteArray_TestData()
{
yield return new object[] { new byte[16], Guid.Empty };
yield return new object[] { new byte[] { 0x44, 0x33, 0x22, 0x11, 0x66, 0x55, 0x88, 0x77, 0x99, 0x00, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF }, new Guid("11223344-5566-7788-9900-aabbccddeeff") };
yield return new object[] { new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF }, new Guid("44332211-6655-8877-9900-aabbccddeeff") };
yield return new object[] { s_testGuid.ToByteArray(), s_testGuid };
}
[Theory]
[MemberData(nameof(Ctor_ByteArray_TestData))]
public static void Ctor_ByteArray(byte[] b, Guid expected)
{
Assert.Equal(expected, new Guid(b));
}
[Fact]
public static void Ctor_ByteArray_Invalid()
{
Assert.Throws<ArgumentNullException>("b", () => new Guid((byte[])null)); // Byte array is null
Assert.Throws<ArgumentException>("b", () => new Guid(new byte[15])); // Byte array is not 16 bytes long
Assert.Throws<ArgumentException>("b", () => new Guid(new byte[17])); // Byte array is not 16 bytes long
}
[Theory]
[MemberData(nameof(GuidStrings_Valid_TestData))]
public static void Ctor_String(string input, string _, Guid expected)
{
Assert.Equal(expected, new Guid(input));
}
[Theory]
[MemberData(nameof(GuidStrings_Invalid_TestData))]
public static void Ctor_String_Invalid(string value, Type exceptionType)
{
Assert.Throws(exceptionType, () => new Guid(value));
}
public static IEnumerable<object[]> Ctor_Int_Short_Short_ByteArray_TestData()
{
yield return new object[] { unchecked((int)0xa8a110d5), unchecked((short)0xfc49), 0x43c5, new byte[] { 0xbf, 0x46, 0x80, 0x2d, 0xb8, 0xf8, 0x43, 0xff }, s_testGuid };
yield return new object[] { 1, 2, 3, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }, new Guid("00000001-0002-0003-0001-020304050607") };
yield return new object[] { 2147483647, 32767, 32767, new byte[] { 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, 0xAA, 0xBB }, new Guid("7fffffff-7fff-7fff-0a0b-0c0d0e0faabb") };
}
[Theory]
[MemberData(nameof(Ctor_Int_Short_Short_ByteArray_TestData))]
public static void Ctor_Int_Short_Short_ByteArray(int a, short b, short c, byte[] d, Guid expected)
{
Assert.Equal(expected, new Guid(a, b, c, d));
Assert.Equal(expected, new Guid(a, b, c, d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7]));
}
[Fact]
public static void Ctor_Int_Short_Short_ByteArray_Invalid()
{
Assert.Throws<ArgumentNullException>("d", () => new Guid(0, 0, 0, null)); // Byte array is null
Assert.Throws<ArgumentException>("d", () => new Guid(0, 0, 0, new byte[7])); // Byte array is not 8 bytes long
Assert.Throws<ArgumentException>("d", () => new Guid(0, 0, 0, new byte[9])); // Byte array is not 8 bytes long
}
[Fact]
public static void Ctor_UInt_UShort_UShort_Byte_Byte_Byte_Byte_Byte_Byte_Byte_Byte()
{
var guid = new Guid(0xa8a110d5, 0xfc49, 0x43c5, 0xbf, 0x46, 0x80, 0x2d, 0xb8, 0xf8, 0x43, 0xff);
Assert.Equal(s_testGuid, guid);
}
[Fact]
public static void NewGuid()
{
Guid guid1 = Guid.NewGuid();
Assert.NotEqual(Guid.Empty, guid1);
Guid guid2 = Guid.NewGuid();
Assert.NotEqual(guid1, guid2);
}
[Fact]
public static void NewGuid_Randomness()
{
const int Iterations = 100;
const int GuidSize = 16;
var random = new byte[GuidSize * Iterations];
for (int i = 0; i < Iterations; i++)
{
// Get a new Guid
Guid guid = Guid.NewGuid();
byte[] bytes = guid.ToByteArray();
// Make sure it's different from all of the previously created ones
for (int j = 0; j < i; j++)
{
Assert.False(bytes.SequenceEqual(new ArraySegment<byte>(random, j * GuidSize, GuidSize)));
}
// Copy it to our randomness array
Array.Copy(bytes, 0, random, i * GuidSize, GuidSize);
}
// Verify the randomness of the data in the array. Guid has some small bias in it
// due to several bits fixed based on the format, but that bias is small enough and
// the variability allowed by VerifyRandomDistribution large enough that we don't do
// anything special for it.
RandomDataGenerator.VerifyRandomDistribution(random);
}
[Theory]
[MemberData(nameof(GuidStrings_Valid_TestData))]
public static void Parse(string input, string format, Guid expected)
{
Assert.Equal(expected, Guid.Parse(input));
Assert.Equal(expected, Guid.ParseExact(input, format.ToUpperInvariant()));
Assert.Equal(expected, Guid.ParseExact(input, format.ToLowerInvariant())); // Format should be case insensitive
Guid result1;
Assert.True(Guid.TryParse(input, out result1));
Assert.Equal(expected, result1);
Guid result2;
Assert.True(Guid.TryParseExact(input, format.ToUpperInvariant(), out result2));
Assert.Equal(expected, result2);
Guid result3;
Assert.True(Guid.TryParseExact(input, format.ToLowerInvariant(), out result3)); // Format should be case insensitive
Assert.Equal(expected, result3);
}
[Theory]
[MemberData(nameof(GuidStrings_Invalid_TestData))]
public static void Parse_Invalid(string input, Type exceptionType)
{
// Overflow exceptions throw as format exceptions in Parse
if (exceptionType.Equals(typeof(OverflowException)))
{
exceptionType = typeof(FormatException);
}
Assert.Throws(exceptionType, () => Guid.Parse(input));
Assert.Throws(exceptionType, () => Guid.ParseExact(input, "N"));
Assert.Throws(exceptionType, () => Guid.ParseExact(input, "D"));
Assert.Throws(exceptionType, () => Guid.ParseExact(input, "B"));
Assert.Throws(exceptionType, () => Guid.ParseExact(input, "P"));
Assert.Throws(exceptionType, () => Guid.ParseExact(input, "X"));
Guid result;
Assert.False(Guid.TryParse(input, out result));
Assert.Equal(Guid.Empty, result);
Assert.False(Guid.TryParseExact(input, "N", out result));
Assert.Equal(Guid.Empty, result);
Assert.False(Guid.TryParseExact(input, "D", out result));
Assert.Equal(Guid.Empty, result);
Assert.False(Guid.TryParseExact(input, "B", out result));
Assert.Equal(Guid.Empty, result);
Assert.False(Guid.TryParseExact(input, "P", out result));
Assert.Equal(Guid.Empty, result);
Assert.False(Guid.TryParseExact(input, "X", out result));
Assert.Equal(Guid.Empty, result);
}
[Theory]
[MemberData(nameof(GuidStrings_Format_Invalid_TestData))]
public static void ParseExact_Invalid(string input, string format, Type exceptionType)
{
Assert.Throws(exceptionType, () => Guid.ParseExact(input, format));
Guid result;
Assert.False(Guid.TryParseExact(input, format, out result));
Assert.Equal(Guid.Empty, result);
}
public static IEnumerable<object[]> CompareTo_TestData()
{
yield return new object[] { s_testGuid, s_testGuid, 0 };
yield return new object[] { s_testGuid, new Guid("a8a110d5-fc49-43c5-bf46-802db8f843ff"), 0 };
yield return new object[] { s_testGuid, Guid.Empty, 1 };
yield return new object[] { s_testGuid, new Guid("98a110d5-fc49-43c5-bf46-802db8f843ff"), 1 };
yield return new object[] { s_testGuid, new Guid("e8a110d5-fc49-43c5-bf46-802db8f843ff"), -1 };
// a
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), 1 };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), -1 };
// b
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11), 1 };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11), -1 };
// c
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 2, 4, 5, 6, 7, 8, 9, 10, 11), 1 };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 4, 4, 5, 6, 7, 8, 9, 10, 11), -1 };
// d
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 3, 5, 6, 7, 8, 9, 10, 11), 1 };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 5, 4, 6, 7, 8, 9, 10, 11), -1 };
// e
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 4, 6, 7, 8, 9, 10, 11), 1 };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 6, 6, 7, 8, 9, 10, 11), -1 };
// f
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 5, 5, 7, 8, 9, 10, 11), 1 };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 5, 7, 7, 8, 9, 10, 11), -1 };
// g
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 5, 6, 6, 8, 9, 10, 11), 1 };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 5, 6, 8, 8, 9, 10, 11), -1 };
// h
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 5, 6, 7, 7, 9, 10, 11), 1 };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 5, 6, 7, 9, 9, 10, 11), -1 };
// i
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 5, 6, 7, 8, 8, 10, 11), 1 };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 5, 6, 7, 8, 10, 10, 11), -1 };
// j
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 11), 1 };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 11), -1 };
// k
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10), 1 };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12), -1 };
yield return new object[] { s_testGuid, null, 1 };
}
[Theory]
[MemberData(nameof(CompareTo_TestData))]
public static void CompareTo(Guid guid, object obj, int expected)
{
if (obj is Guid)
{
Assert.Equal(expected, Math.Sign(guid.CompareTo((Guid)obj)));
}
IComparable comparable = guid;
Assert.Equal(expected, Math.Sign(comparable.CompareTo(obj)));
}
[Fact]
public static void CompareTo_ValueNotGuid_ThrowsArgumentException()
{
IComparable comparable = s_testGuid;
Assert.Throws<ArgumentException>("value", () => comparable.CompareTo("a8a110d5-fc49-43c5-bf46-802db8f843ff")); // Value is not a guid
}
public static IEnumerable<object[]> Equals_TestData()
{
yield return new object[] { s_testGuid, s_testGuid, true };
yield return new object[] { s_testGuid, new Guid("a8a110d5-fc49-43c5-bf46-802db8f843ff"), true };
yield return new object[] { s_testGuid, Guid.Empty, false };
yield return new object[] { s_testGuid, "a8a110d5-fc49-43c5-bf46-802db8f843ff", false };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), true };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), false };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 0, 3, 4, 5, 6, 7, 8, 9, 10, 11), false };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 0, 4, 5, 6, 7, 8, 9, 10, 11), false };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 0, 5, 6, 7, 8, 9, 10, 11), false };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 0, 6, 7, 8, 9, 10, 11), false };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 5, 0, 7, 8, 9, 10, 11), false };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 5, 6, 0, 8, 9, 10, 11), false };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 5, 6, 7, 0, 9, 10, 11), false };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 5, 6, 7, 8, 0, 10, 11), false };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 11), false };
yield return new object[] { new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0), false };
yield return new object[] { s_testGuid, new object(), false};
yield return new object[] { s_testGuid, null, false};
}
[Theory]
[MemberData(nameof(Equals_TestData))]
public static void Equals(Guid guid1, object obj, bool expected)
{
if (obj is Guid)
{
Guid guid2 = (Guid)obj;
Assert.Equal(expected, guid1.Equals(guid2));
Assert.Equal(expected, guid1 == guid2);
Assert.Equal(!expected, guid1 != guid2);
}
Assert.Equal(expected, guid1.Equals(obj));
}
[Fact]
public static void ToByteArray()
{
Assert.Equal(new byte[] { 0xd5, 0x10, 0xa1, 0xa8, 0x49, 0xfc, 0xc5, 0x43, 0xbf, 0x46, 0x80, 0x2d, 0xb8, 0xf8, 0x43, 0xff }, s_testGuid.ToByteArray());
}
public static IEnumerable<object[]> ToString_TestData()
{
yield return new object[] { s_testGuid, "N", "a8a110d5fc4943c5bf46802db8f843ff" };
yield return new object[] { s_testGuid, "D", "a8a110d5-fc49-43c5-bf46-802db8f843ff" };
yield return new object[] { s_testGuid, "B", "{a8a110d5-fc49-43c5-bf46-802db8f843ff}" };
yield return new object[] { s_testGuid, "P", "(a8a110d5-fc49-43c5-bf46-802db8f843ff)" };
yield return new object[] { s_testGuid, "X", "{0xa8a110d5,0xfc49,0x43c5,{0xbf,0x46,0x80,0x2d,0xb8,0xf8,0x43,0xff}}" };
yield return new object[] { s_testGuid, null, "a8a110d5-fc49-43c5-bf46-802db8f843ff" };
yield return new object[] { s_testGuid, "", "a8a110d5-fc49-43c5-bf46-802db8f843ff" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void ToString(Guid guid, string format, string expected)
{
IFormattable formattable = guid;
if (string.IsNullOrEmpty(format) || format == "D")
{
Assert.Equal(expected, guid.ToString());
Assert.Equal(expected, formattable.ToString());
}
Assert.Equal(expected, guid.ToString(format));
Assert.Equal(expected, formattable.ToString(format, null));
}
[Fact]
public static void ToString_InvalidFormat_ThrowsFormatException()
{
Assert.Throws<FormatException>(() => s_testGuid.ToString("Y")); // Invalid format
Assert.Throws<FormatException>(() => s_testGuid.ToString("XX")); // Invalid format
}
public static IEnumerable<object[]> GuidStrings_Valid_TestData()
{
yield return new object[] { "a8a110d5fc4943c5bf46802db8f843ff", "N", s_testGuid };
yield return new object[] { " \r \n \t a8a110d5fc4943c5bf46802db8f843ff \r \n \t ", "N", s_testGuid };
yield return new object[] { "a8a110d5-fc49-43c5-bf46-802db8f843ff", "D", s_testGuid };
yield return new object[] { " \r \n \t a8a110d5-fc49-43c5-bf46-802db8f843ff \r \n \t ", "D", s_testGuid };
yield return new object[] { "{a8a110d5-fc49-43c5-bf46-802db8f843ff}", "B", s_testGuid };
yield return new object[] { " \r \n \t {a8a110d5-fc49-43c5-bf46-802db8f843ff} \r \n \t ", "B", s_testGuid };
yield return new object[] { "(a8a110d5-fc49-43c5-bf46-802db8f843ff)", "P", s_testGuid };
yield return new object[] { " \r \n \t (a8a110d5-fc49-43c5-bf46-802db8f843ff) \r \n \t ", "P", s_testGuid };
yield return new object[] { "{0xa8a110d5,0xfc49,0x43c5,{0xbf,0x46,0x80,0x2d,0xb8,0xf8,0x43,0xff}}", "X", s_testGuid };
yield return new object[] { " { 0 x a 8\t a 1 1 0 d 5 , 0 x f c 4\r 9 , 0 x 4 3 c 5 , { 0 x b f , 0 x 4 6 , 0 x 8 0 , 0\n x 2 d , 0 x b 8 , 0 x f 8 , 0 x 4 3 , 0 x f f } } ", "X", s_testGuid };
}
public static IEnumerable<object[]> GuidStrings_Invalid_TestData()
{
yield return new object[] { null, typeof(ArgumentNullException) }; // String is null
yield return new object[] { "", typeof(FormatException) }; // String is invalid
yield return new object[] { " \t", typeof(FormatException) }; // String is invalid
yield return new object[] { "ddddddddddddddddddddddddddddddd", typeof(FormatException) }; // Length < 32
yield return new object[] { "ddddddddddddddddddddddddddddddddd", typeof(FormatException) }; // Length > 32
yield return new object[] { "{dddddddddddddddddddddddddddddddd}", typeof(FormatException) }; // Surrounded by braces
// Can't contain inner whitespace
yield return new object[] { "d d d d d dd d d d d d dd d d d dd d d dd d dd d d d d d d", typeof(FormatException) };
yield return new object[] { "{d d d d d dd d d d d d dd d d d dd d d dd d dd d d d d d d}", typeof(FormatException) };
yield return new object[] { "(d d d d d dd d d d d d dd d d d dd d d dd d dd d d d d d d)", typeof(FormatException) };
yield return new object[] { "dddddddd-dddddddd-dddddddd", typeof(FormatException) }; // 8-8-8
yield return new object[] { "dddddddd-dddddddd-dddddddd-ddddddddd", typeof(FormatException) }; // 8-8-8
yield return new object[] { "dddddddd-dddddddd-dddddddd-dddddddd-dddddddd", typeof(FormatException) }; // 8-8-8-8
yield return new object[] { "ddddddd-dddd-dddd-dddd-dddddddd", typeof(FormatException) }; // 7-4-4-4-8
yield return new object[] { "ddddddddd-dddd-dddd-dddd-dddddddd", typeof(FormatException) }; // 9-4-4-4-8
yield return new object[] { "dddddddd-ddd-dddd-dddd-dddddddd", typeof(FormatException) }; // 8-3-4-4-8
yield return new object[] { "dddddddd-ddddd-dddd-dddd-dddddddd", typeof(FormatException) }; // 8-5-4-4-8
yield return new object[] { "dddddddd-dddd-ddd-dddd-dddddddd", typeof(FormatException) }; // 8-4-3-4-8
yield return new object[] { "dddddddd-dddd-ddddd-dddd-dddddddd", typeof(FormatException) }; // 8-4-5-4-8
yield return new object[] { "dddddddd-dddd-dddd-ddd-dddddddd", typeof(FormatException) }; // 8-4-4-3-8
yield return new object[] { "dddddddd-dddd-dddd-ddddd-dddddddd", typeof(FormatException) }; // 8-4-4-5-8
yield return new object[] { "dddddddd-dddd-dddd-dddd-ddddddd", typeof(FormatException) }; // 8-4-4-4-7
yield return new object[] { "dddddddd-dddd-dddd-dddd-ddddddddd", typeof(FormatException) }; // 8-4-4-9
yield return new object[] { "{dddddddd-dddd-dddd-dddd-dddddddd", typeof(FormatException) }; // 8-4-4-4-8 with leading brace only
yield return new object[] { "dddddddd-dddd-dddd-dddd-dddddddd}", typeof(FormatException) }; // 8-4-4-4-8 with trailing brace only
yield return new object[] { "(dddddddd-dddd-dddd-dddd-dddddddd", typeof(FormatException) }; // 8-4-4-4-8 with leading parenthesis only
yield return new object[] { "dddddddd-dddd-dddd-dddd-dddddddd)", typeof(FormatException) }; // 8-4-4-4-8 with trailing parenthesis only
yield return new object[] { "(dddddddd-dddd-dddd-dddd-dddddddd}", typeof(FormatException) }; // 8-4-4-4-8 with leading parenthesis and trailing brace
yield return new object[] { "{dddddddd-dddd-dddd-dddd-dddddddd)", typeof(FormatException) }; // 8-4-4-4-8 with trailing parenthesis and leading brace
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd}", typeof(FormatException) }; // 8-4-4
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} - missing group
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2-2} - extra group
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} with leading brace only
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} with leading brace only
yield return new object[] { "0xdddddddd, 0xdddd, 0xdddd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} with trailing brace only
yield return new object[] { "0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} with trailing brace only
yield return new object[] { "(0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd))", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} with parentheses
yield return new object[] { "(0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd))", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} with parentheses
yield return new object[] { "{0xdddddddd 0xdddd 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(OverflowException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without comma
yield return new object[] { "{0xdddddddd, 0xdddd 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without comma
yield return new object[] { "{0xdddddddd, 0xdddd 0xdddd{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without comma
yield return new object[] { "{dddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without 0x prefix
yield return new object[] { "{0xdddddddd, dddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without 0x prefix
yield return new object[] { "{0xdddddddd, 0xdddd, dddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without 0x prefix
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{dd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without 0x prefix
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,dd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without 0x prefix
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,dd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without 0x prefix
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,dd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without 0x prefix
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,dd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without 0x prefix
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,dd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without 0x prefix
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,dd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without 0x prefix
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,dd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without 0x prefix
yield return new object[] { "{0x, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without string after 0x
yield return new object[] { "{0xddddddddd, 0x, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(OverflowException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without string after 0x
yield return new object[] { "{0xddddddddd, 0xdddd, 0x,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(OverflowException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without string after 0x
yield return new object[] { "{0xddddddddd, 0xdddd, 0xdddd,{0x,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(OverflowException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without string after 0x
yield return new object[] { "{0xddddddddd, 0xdddd, 0xdddd,{0xdd,0x,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(OverflowException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without string after 0x
yield return new object[] { "{0xddddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0x,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(OverflowException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without string after 0x
yield return new object[] { "{0xddddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0x,0xdd,0xdd,0xdd,0xdd}}", typeof(OverflowException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without string after 0x
yield return new object[] { "{0xddddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0x,0xdd,0xdd,0xdd}}", typeof(OverflowException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without string after 0x
yield return new object[] { "{0xddddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0x,0xdd,0xdd}}", typeof(OverflowException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without string after 0x
yield return new object[] { "{0xddddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0x,0xdd}}", typeof(OverflowException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without string after 0x
yield return new object[] { "{0xddddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0x}}", typeof(OverflowException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without string after 0x
yield return new object[] { "{0xddddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(OverflowException) }; // 9-4-4-{2-2-2-2-2-2-2-2}
yield return new object[] { "{0xdddddddd, 0xddddd, 0xdddd,{0xdd,0xddd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-5-4-{2-2-2-2-2-2-2-2}
yield return new object[] { "{0xdddddddd, 0xdddd, 0xddddd,{0xdd,0xddd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-5-4-{2-2-2-2-2-2-2-2}
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xddd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{3-2-2-2-2-2-2-2}
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xddd,0xdd,0xddd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-3-2-2-2-2-2-2}
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xddd,0xdd,0xddd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-3-2-2-2-2-2}
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xddd,0xdd,0xdd,0xddd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-3-2-2-2-2}
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xddd,0xddd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-3-2-2}
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xddd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-3-2}
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xddd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-3}
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without comma
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without comma
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without comma
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without comma
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd0xdd,0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without comma
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd0xdd,0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without comma
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd0xdd}}", typeof(FormatException) }; // 8-4-4-{2-2-2-2-2-2-2-2} without comma
yield return new object[] { "{0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}abc", typeof(FormatException) };
// Invalid hex
yield return new object[] { "Gdddddddddddddddddddddddddddddddd", typeof(FormatException) };
yield return new object[] { "ddddddddGdddddddddddddddddddddddd", typeof(FormatException) };
yield return new object[] { "ddddddddddddGdddddddddddddddddddd", typeof(FormatException) };
yield return new object[] { "ddddddddddddddddGdddddddddddddddd", typeof(FormatException) };
yield return new object[] { "ddddddddddddddddddddGdddddddddddd", typeof(FormatException) };
yield return new object[] { "Gddddddd-dddd-dddd-dddd-dddddddddddd", typeof(FormatException) };
yield return new object[] { "dddddddd-Gddd-dddd-dddd-dddddddddddd", typeof(FormatException) };
yield return new object[] { "dddddddd-dddd-Gddd-dddd-dddddddddddd", typeof(FormatException) };
yield return new object[] { "dddddddd-dddd-dddd-Gddd-dddddddddddd", typeof(FormatException) };
yield return new object[] { "dddddddd-dddd-dddd-dddd-Gddddddddddd", typeof(FormatException) };
yield return new object[] { "{0xGddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) };
yield return new object[] { "{0xdddddddd,0xGddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) };
yield return new object[] { "{0xdddddddd,0xdddd,0Gdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) };
yield return new object[] { "{0xdddddddd,0xdddd,0xdddd,{0xGd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) };
yield return new object[] { "{0xdddddddd,0xdddd,0xdddd,{0xdd,0xGd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) };
yield return new object[] { "{0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xGd,0xdd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) };
yield return new object[] { "{0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xGd,0xdd,0xdd,0xdd,0xdd}}", typeof(FormatException) };
yield return new object[] { "{0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xGd,0xdd,0xdd,0xdd}}", typeof(FormatException) };
yield return new object[] { "{0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xGd,0xdd,0xdd}}", typeof(FormatException) };
yield return new object[] { "{0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xGd,0xdd}}", typeof(FormatException) };
yield return new object[] { "{0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xGd}}", typeof(FormatException) };
}
public static IEnumerable<object[]> GuidStrings_Format_Invalid_TestData()
{
yield return new object[] { null, "D", typeof(ArgumentNullException) }; // String is null
yield return new object[] { "", null, typeof(ArgumentNullException) }; // Format is null
yield return new object[] { "", "", typeof(FormatException) }; // Format is invalid
yield return new object[] { "", "Y", typeof(FormatException) }; // Format is invalid
yield return new object[] { "", "XX", typeof(FormatException) }; // Format is invalid
yield return new object[] { "dddddddddddddddddddddddddddddddd", "D", typeof(FormatException) }; // 32 digits
yield return new object[] { "dddddddddddddddddddddddddddddddd", "B", typeof(FormatException) }; // 32 digits
yield return new object[] { "dddddddddddddddddddddddddddddddd", "P", typeof(FormatException) }; // 32 digits
yield return new object[] { "dddddddddddddddddddddddddddddddd", "X", typeof(FormatException) }; // 32 digits
yield return new object[] { "dddddddd-dddd-dddd-dddd-dddddddd", "N", typeof(FormatException) }; // 32 digits with hyphens
yield return new object[] { "dddddddd-dddd-dddd-dddd-dddddddd", "B", typeof(FormatException) }; // 32 digits with hyphens
yield return new object[] { "dddddddd-dddd-dddd-dddd-dddddddd", "P", typeof(FormatException) }; // 32 digits with hyphens
yield return new object[] { "dddddddd-dddd-dddd-dddd-dddddddd", "X", typeof(FormatException) }; // 32 digits with hyphens
yield return new object[] { "{dddddddd-dddd-dddd-dddd-dddddddd}", "N", typeof(FormatException) }; // 32 digits with hyphens and braces
yield return new object[] { "{dddddddd-dddd-dddd-dddd-dddddddd}", "D", typeof(FormatException) }; // 32 digits with hyphens and braces
yield return new object[] { "{dddddddd-dddd-dddd-dddd-dddddddd}", "P", typeof(FormatException) }; // 32 digits with hyphens and braces
yield return new object[] { "{dddddddd-dddd-dddd-dddd-dddddddd}", "X", typeof(FormatException) }; // 32 digits with hyphens and braces
yield return new object[] { "(dddddddd-dddd-dddd-dddd-dddddddd)", "N", typeof(FormatException) }; // 32 digits with hyphens and parentheses
yield return new object[] { "(dddddddd-dddd-dddd-dddd-dddddddd)", "D", typeof(FormatException) }; // 32 digits with hyphens and parentheses
yield return new object[] { "(dddddddd-dddd-dddd-dddd-dddddddd)", "B", typeof(FormatException) }; // 32 digits with hyphens and parentheses
yield return new object[] { "(dddddddd-dddd-dddd-dddd-dddddddd)", "X", typeof(FormatException) }; // 32 digits with hyphens and parentheses
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", "N", typeof(FormatException) }; // Hex values
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", "D", typeof(FormatException) }; // Hex values
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", "B", typeof(FormatException) }; // Hex values
yield return new object[] { "{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}", "P", typeof(FormatException) }; // Hex values
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Globalization
{
public partial class CompareInfo
{
[NonSerialized]
private Interop.GlobalizationInterop.SafeSortHandle _sortHandle;
[NonSerialized]
private bool _isAsciiEqualityOrdinal;
private void InitSort(CultureInfo culture)
{
_sortName = culture.SortName;
if (_invariantMode)
{
_isAsciiEqualityOrdinal = true;
}
else
{
Interop.GlobalizationInterop.ResultCode resultCode = Interop.GlobalizationInterop.GetSortHandle(GetNullTerminatedUtf8String(_sortName), out _sortHandle);
if (resultCode != Interop.GlobalizationInterop.ResultCode.Success)
{
_sortHandle.Dispose();
if (resultCode == Interop.GlobalizationInterop.ResultCode.OutOfMemory)
throw new OutOfMemoryException();
throw new ExternalException(SR.Arg_ExternalException);
}
_isAsciiEqualityOrdinal = (_sortName == "en-US" || _sortName == "");
}
}
internal static unsafe int IndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(source != null);
Debug.Assert(value != null);
if (value.Length == 0)
{
return startIndex;
}
if (count < value.Length)
{
return -1;
}
if (ignoreCase)
{
fixed (char* pSource = source)
{
int index = Interop.GlobalizationInterop.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + startIndex, count, findLast: false);
return index != -1 ?
startIndex + index :
-1;
}
}
int endIndex = startIndex + (count - value.Length);
for (int i = startIndex; i <= endIndex; i++)
{
int valueIndex, sourceIndex;
for (valueIndex = 0, sourceIndex = i;
valueIndex < value.Length && source[sourceIndex] == value[valueIndex];
valueIndex++, sourceIndex++) ;
if (valueIndex == value.Length)
{
return i;
}
}
return -1;
}
internal static unsafe int LastIndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(source != null);
Debug.Assert(value != null);
if (value.Length == 0)
{
return startIndex;
}
if (count < value.Length)
{
return -1;
}
// startIndex is the index into source where we start search backwards from.
// leftStartIndex is the index into source of the start of the string that is
// count characters away from startIndex.
int leftStartIndex = startIndex - count + 1;
if (ignoreCase)
{
fixed (char* pSource = source)
{
int lastIndex = Interop.GlobalizationInterop.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + leftStartIndex, count, findLast: true);
return lastIndex != -1 ?
leftStartIndex + lastIndex :
-1;
}
}
for (int i = startIndex - value.Length + 1; i >= leftStartIndex; i--)
{
int valueIndex, sourceIndex;
for (valueIndex = 0, sourceIndex = i;
valueIndex < value.Length && source[sourceIndex] == value[valueIndex];
valueIndex++, sourceIndex++) ;
if (valueIndex == value.Length) {
return i;
}
}
return -1;
}
private int GetHashCodeOfStringCore(string source, CompareOptions options)
{
Debug.Assert(source != null);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return GetHashCodeOfStringCore(source, options, forceRandomizedHashing: false, additionalEntropy: 0);
}
private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2)
{
Debug.Assert(!GlobalizationMode.Invariant);
return Interop.GlobalizationInterop.CompareStringOrdinalIgnoreCase(string1, count1, string2, count2);
}
private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
Debug.Assert(!_invariantMode);
Debug.Assert(string1 != null);
Debug.Assert(string2 != null);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
fixed (char* pString1 = string1)
{
fixed (char* pString2 = string2)
{
return Interop.GlobalizationInterop.CompareString(_sortHandle, pString1 + offset1, length1, pString2 + offset2, length2, options);
}
}
}
internal unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options, int* matchLengthPtr)
{
Debug.Assert(!_invariantMode);
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(target != null);
Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
int index;
if (target.Length == 0)
{
if(matchLengthPtr != null)
*matchLengthPtr = 0;
return startIndex;
}
if (options == CompareOptions.Ordinal)
{
index = IndexOfOrdinal(source, target, startIndex, count, ignoreCase: false);
if(index != -1)
{
if(matchLengthPtr != null)
*matchLengthPtr = target.Length;
}
return index;
}
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && target.IsFastSort())
{
index = IndexOf(source, target, startIndex, count, GetOrdinalCompareOptions(options));
if(index != -1)
{
if(matchLengthPtr != null)
*matchLengthPtr = target.Length;
}
return index;
}
fixed (char* pSource = source)
{
index = Interop.GlobalizationInterop.IndexOf(_sortHandle, target, target.Length, pSource + startIndex, count, options, matchLengthPtr);
return index != -1 ? index + startIndex : -1;
}
}
private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
Debug.Assert(!_invariantMode);
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(target != null);
Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
if (target.Length == 0)
{
return startIndex;
}
if (options == CompareOptions.Ordinal)
{
return LastIndexOfOrdinalCore(source, target, startIndex, count, ignoreCase: false);
}
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && target.IsFastSort())
{
return LastIndexOf(source, target, startIndex, count, GetOrdinalCompareOptions(options));
}
// startIndex is the index into source where we start search backwards from. leftStartIndex is the index into source
// of the start of the string that is count characters away from startIndex.
int leftStartIndex = (startIndex - count + 1);
fixed (char* pSource = source)
{
int lastIndex = Interop.GlobalizationInterop.LastIndexOf(_sortHandle, target, target.Length, pSource + (startIndex - count + 1), count, options);
return lastIndex != -1 ? lastIndex + leftStartIndex : -1;
}
}
private bool StartsWith(string source, string prefix, CompareOptions options)
{
Debug.Assert(!_invariantMode);
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(!string.IsNullOrEmpty(prefix));
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && prefix.IsFastSort())
{
return IsPrefix(source, prefix, GetOrdinalCompareOptions(options));
}
return Interop.GlobalizationInterop.StartsWith(_sortHandle, prefix, prefix.Length, source, source.Length, options);
}
private bool EndsWith(string source, string suffix, CompareOptions options)
{
Debug.Assert(!_invariantMode);
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(!string.IsNullOrEmpty(suffix));
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && suffix.IsFastSort())
{
return IsSuffix(source, suffix, GetOrdinalCompareOptions(options));
}
return Interop.GlobalizationInterop.EndsWith(_sortHandle, suffix, suffix.Length, source, source.Length, options);
}
private unsafe SortKey CreateSortKey(String source, CompareOptions options)
{
Debug.Assert(!_invariantMode);
if (source==null) { throw new ArgumentNullException(nameof(source)); }
Contract.EndContractBlock();
if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
byte [] keyData;
if (source.Length == 0)
{
keyData = Array.Empty<Byte>();
}
else
{
int sortKeyLength = Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, null, 0, options);
keyData = new byte[sortKeyLength];
fixed (byte* pSortKey = keyData)
{
Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
}
}
return new SortKey(Name, source, options, keyData);
}
private unsafe static bool IsSortable(char *text, int length)
{
Debug.Assert(!GlobalizationMode.Invariant);
int index = 0;
UnicodeCategory uc;
while (index < length)
{
if (Char.IsHighSurrogate(text[index]))
{
if (index == length - 1 || !Char.IsLowSurrogate(text[index+1]))
return false; // unpaired surrogate
uc = CharUnicodeInfo.InternalGetUnicodeCategory(Char.ConvertToUtf32(text[index], text[index+1]));
if (uc == UnicodeCategory.PrivateUse || uc == UnicodeCategory.OtherNotAssigned)
return false;
index += 2;
continue;
}
if (Char.IsLowSurrogate(text[index]))
{
return false; // unpaired surrogate
}
uc = CharUnicodeInfo.GetUnicodeCategory(text[index]);
if (uc == UnicodeCategory.PrivateUse || uc == UnicodeCategory.OtherNotAssigned)
{
return false;
}
index++;
}
return true;
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
internal unsafe int GetHashCodeOfStringCore(string source, CompareOptions options, bool forceRandomizedHashing, long additionalEntropy)
{
Debug.Assert(!_invariantMode);
Debug.Assert(source != null);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (source.Length == 0)
{
return 0;
}
int sortKeyLength = Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, null, 0, options);
// As an optimization, for small sort keys we allocate the buffer on the stack.
if (sortKeyLength <= 256)
{
byte* pSortKey = stackalloc byte[sortKeyLength];
Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy);
}
byte[] sortKey = new byte[sortKeyLength];
fixed (byte* pSortKey = sortKey)
{
Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy);
}
}
[DllImport(JitHelpers.QCall)]
[SuppressUnmanagedCodeSecurity]
private static unsafe extern int InternalHashSortKey(byte* sortKey, int sortKeyLength, [MarshalAs(UnmanagedType.Bool)] bool forceRandomizedHashing, long additionalEntropy);
private static CompareOptions GetOrdinalCompareOptions(CompareOptions options)
{
if ((options & CompareOptions.IgnoreCase) == CompareOptions.IgnoreCase)
{
return CompareOptions.OrdinalIgnoreCase;
}
else
{
return CompareOptions.Ordinal;
}
}
private static bool CanUseAsciiOrdinalForOptions(CompareOptions options)
{
// Unlike the other Ignore options, IgnoreSymbols impacts ASCII characters (e.g. ').
return (options & CompareOptions.IgnoreSymbols) == 0;
}
private static byte[] GetNullTerminatedUtf8String(string s)
{
int byteLen = System.Text.Encoding.UTF8.GetByteCount(s);
// Allocate an extra byte (which defaults to 0) as the null terminator.
byte[] buffer = new byte[byteLen + 1];
int bytesWritten = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, buffer, 0);
Debug.Assert(bytesWritten == byteLen);
return buffer;
}
private SortVersion GetSortVersion()
{
Debug.Assert(!_invariantMode);
int sortVersion = Interop.GlobalizationInterop.GetSortVersion(_sortHandle);
return new SortVersion(sortVersion, LCID, new Guid(sortVersion, 0, 0, 0, 0, 0, 0,
(byte) (LCID >> 24),
(byte) ((LCID & 0x00FF0000) >> 16),
(byte) ((LCID & 0x0000FF00) >> 8),
(byte) (LCID & 0xFF)));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Prism.Regions;
using Prism.Regions.Behaviors;
using Prism.Wpf.Tests.Mocks;
namespace Prism.Wpf.Tests.Regions.Behaviors
{
[TestClass]
public class RegionMemberLifetimeBehaviorFixture
{
protected Region Region { get; set; }
protected RegionMemberLifetimeBehavior Behavior { get; set; }
[TestInitialize]
public void TestInitialize()
{
Arrange();
}
protected virtual void Arrange()
{
this.Region = new Region();
this.Behavior = new RegionMemberLifetimeBehavior();
this.Behavior.Region = this.Region;
this.Behavior.Attach();
}
[TestMethod]
public void WhenBehaviorAttachedThenReportsIsAttached()
{
Assert.IsTrue(Behavior.IsAttached);
}
[TestMethod]
public void WhenIRegionMemberLifetimeItemReturnsKeepAliveFalseRemovesWhenInactive()
{
// Arrange
var regionItemMock = new Mock<IRegionMemberLifetime>();
regionItemMock.Setup(i => i.KeepAlive).Returns(false);
Region.Add(regionItemMock.Object);
Region.Activate(regionItemMock.Object);
// Act
Region.Deactivate(regionItemMock.Object);
// Assert
Assert.IsFalse(Region.Views.Contains(regionItemMock.Object));
}
[TestMethod]
public void WhenIRegionMemberLifetimeItemReturnsKeepAliveTrueDoesNotRemoveOnDeactivation()
{
// Arrange
var regionItemMock = new Mock<IRegionMemberLifetime>();
regionItemMock.Setup(i => i.KeepAlive).Returns(true);
Region.Add(regionItemMock.Object);
Region.Activate(regionItemMock.Object);
// Act
Region.Deactivate(regionItemMock.Object);
// Assert
Assert.IsTrue(Region.Views.Contains(regionItemMock.Object));
}
[TestMethod]
public void WhenRegionContainsMultipleMembers_OnlyRemovesThoseDeactivated()
{
// Arrange
var firstMockItem = new Mock<IRegionMemberLifetime>();
firstMockItem.Setup(i => i.KeepAlive).Returns(true);
var secondMockItem = new Mock<IRegionMemberLifetime>();
secondMockItem.Setup(i => i.KeepAlive).Returns(false);
Region.Add(firstMockItem.Object);
Region.Activate(firstMockItem.Object);
Region.Add(secondMockItem.Object);
Region.Activate(secondMockItem.Object);
// Act
Region.Deactivate(secondMockItem.Object);
// Assert
Assert.IsTrue(Region.Views.Contains(firstMockItem.Object));
Assert.IsFalse(Region.Views.Contains(secondMockItem.Object));
}
[TestMethod]
public void WhenMemberNeverActivatedThenIsNotRemovedOnAnothersDeactivation()
{
// Arrange
var firstMockItem = new Mock<IRegionMemberLifetime>();
firstMockItem.Setup(i => i.KeepAlive).Returns(false);
var secondMockItem = new Mock<IRegionMemberLifetime>();
secondMockItem.Setup(i => i.KeepAlive).Returns(false);
Region.Add(firstMockItem.Object); // Never activated
Region.Add(secondMockItem.Object);
Region.Activate(secondMockItem.Object);
// Act
Region.Deactivate(secondMockItem.Object);
// Assert
Assert.IsTrue(Region.Views.Contains(firstMockItem.Object));
Assert.IsFalse(Region.Views.Contains(secondMockItem.Object));
}
[TestMethod]
public virtual void RemovesRegionItemIfDataContextReturnsKeepAliveFalse()
{
// Arrange
var regionItemMock = new Mock<IRegionMemberLifetime>();
regionItemMock.Setup(i => i.KeepAlive).Returns(false);
var regionItem = new MockFrameworkElement();
regionItem.DataContext = regionItemMock.Object;
Region.Add(regionItem);
Region.Activate(regionItem);
// Act
Region.Deactivate(regionItem);
// Assert
Assert.IsFalse(Region.Views.Contains(regionItem));
}
[TestMethod]
public virtual void RemovesOnlyDeactivatedItemsInRegionBasedOnDataContextKeepAlive()
{
// Arrange
var retionItemDataContextToKeepAlive = new Mock<IRegionMemberLifetime>();
retionItemDataContextToKeepAlive.Setup(i => i.KeepAlive).Returns(true);
var regionItemToKeepAlive = new MockFrameworkElement();
regionItemToKeepAlive.DataContext = retionItemDataContextToKeepAlive.Object;
Region.Add(regionItemToKeepAlive);
Region.Activate(regionItemToKeepAlive);
var regionItemMock = new Mock<IRegionMemberLifetime>();
regionItemMock.Setup(i => i.KeepAlive).Returns(false);
var regionItem = new MockFrameworkElement();
regionItem.DataContext = regionItemMock.Object;
Region.Add(regionItem);
Region.Activate(regionItem);
// Act
Region.Deactivate(regionItem);
// Assert
Assert.IsFalse(Region.Views.Contains(regionItem));
Assert.IsTrue(Region.Views.Contains(regionItemToKeepAlive));
}
[TestMethod]
public virtual void WillRemoveDeactivatedItemIfKeepAliveAttributeFalse()
{
// Arrange
var regionItem = new RegionMemberNotKeptAlive();
Region.Add(regionItem);
Region.Activate(regionItem);
// Act
Region.Deactivate(regionItem);
// Assert
Assert.IsFalse(Region.Views.Contains((object)regionItem));
}
[TestMethod]
public virtual void WillNotRemoveDeactivatedItemIfKeepAliveAttributeTrue()
{
// Arrange
var regionItem = new RegionMemberKeptAlive();
Region.Add(regionItem);
Region.Activate(regionItem);
// Act
Region.Deactivate(regionItem);
// Assert
Assert.IsTrue(Region.Views.Contains((object)regionItem));
}
[TestMethod]
public virtual void WillRemoveDeactivatedItemIfDataContextKeepAliveAttributeFalse()
{
// Arrange
var regionItemDataContext = new RegionMemberNotKeptAlive();
var regionItem = new MockFrameworkElement() { DataContext = regionItemDataContext };
Region.Add(regionItem);
Region.Activate(regionItem);
// Act
Region.Deactivate(regionItem);
// Assert
Assert.IsFalse(Region.Views.Contains(regionItem));
}
[RegionMemberLifetime(KeepAlive = false)]
public class RegionMemberNotKeptAlive
{
}
[RegionMemberLifetime(KeepAlive = true)]
public class RegionMemberKeptAlive
{
}
}
[TestClass]
public class RegionMemberLifetimeBehaviorAgainstSingleActiveRegionFixture
: RegionMemberLifetimeBehaviorFixture
{
protected override void Arrange()
{
this.Region = new SingleActiveRegion();
this.Behavior = new RegionMemberLifetimeBehavior();
this.Behavior.Region = this.Region;
this.Behavior.Attach();
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using Spring.Transaction;
using Spring.Transaction.Support;
namespace Spring.Testing.Microsoft
{
/// <summary>
/// Convenient superclass for tests that should occur in a transaction, but normally
/// will roll the transaction back on the completion of each test.
/// </summary>
/// <remarks>
/// <p>This is useful in a range of circumstances, allowing the following benefits:</p>
/// <ul>
/// <li>Ability to delete or insert any data in the database, without affecting other tests</li>
/// <li>Providing a transactional context for any code requiring a transaction</li>
/// <li>Ability to write anything to the database without any need to clean up.</li>
/// </ul>
///
/// <p>This class is typically very fast, compared to traditional setup/teardown scripts.</p>
///
/// <p>If data should be left in the database, call the <code>SetComplete()</code>
/// method in each test. The "DefaultRollback" property, which defaults to "true",
/// determines whether transactions will complete by default.</p>
///
/// <p>It is even possible to end the transaction early; for example, to verify lazy
/// loading behavior of an O/R mapping tool. (This is a valuable away to avoid
/// unexpected errors when testing a web UI, for example.) Simply call the
/// <code>endTransaction()</code> method. Execution will then occur without a
/// transactional context.</p>
///
/// <p>The <code>StartNewTransaction()</code> method may be called after a call to
/// <code>EndTransaction()</code> if you wish to create a new transaction, quite
/// independent of the old transaction. The new transaction's default fate will be to
/// roll back, unless <code>setComplete()</code> is called again during the scope of the
/// new transaction. Any number of transactions may be created and ended in this way.
/// The final transaction will automatically be rolled back when the test case is
/// torn down.</p>
///
/// <p>Transactional behavior requires a single object in the context implementing the
/// IPlatformTransactionManager interface. This will be set by the superclass's
/// Dependency Injection mechanism. If using the superclass's Field Injection mechanism,
/// the implementation should be named "transactionManager". This mechanism allows the
/// use of this superclass even when there's more than one transaction manager in the context.</p>
///
/// <p><i>This superclass can also be used without transaction management, if no
/// IPlatformTransactionManager object is found in the context provided. Be careful about
/// using this mode, as it allows the potential to permanently modify data.
/// This mode is available only if dependency checking is turned off in
/// the AbstractDependencyInjectionSpringContextTests superclass. The non-transactional
/// capability is provided to enable use of the same subclass in different environments.</i></p>
///
/// </remarks>
///
/// <author>Rod Johnson</author>
/// <author>Juergen Hoeller</author>
/// <author>Rick Evans</author>
/// <author>Mark Pollack (.NET)</author>
public abstract class AbstractTransactionalSpringContextTests : AbstractDependencyInjectionSpringContextTests
{
/// <summary>
/// The transaction manager to use
/// </summary>
protected IPlatformTransactionManager transactionManager;
/// <summary>
/// Should we roll back by default?
/// </summary>
private bool defaultRollback = true;
/// <summary>
/// Should we commit the current transaction?
/// </summary>
private bool complete = false;
/// <summary>
/// Number of transactions started
/// </summary>
private int transactionsStarted = 0;
/// <summary>
/// Default transaction definition is used.
/// Subclasses can change this to cause different behaviour.
/// </summary>
private ITransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
/// <summary>
/// TransactionStatus for this test. Typical subclasses won't need to use it.
/// </summary>
protected ITransactionStatus transactionStatus;
/// <summary>
/// Initializes a new instance of the <see cref="AbstractTransactionalSpringContextTests"/> class.
/// </summary>
public AbstractTransactionalSpringContextTests()
{
}
/// <summary>
/// Sets the transaction manager to use.
/// </summary>
public IPlatformTransactionManager TransactionManager
{
set { transactionManager = value; }
}
/// <summary>
/// Sets the default rollback flag.
/// </summary>
public bool DefaultRollback
{
set { defaultRollback = value; }
}
/// <summary>
/// Set the <see cref="ITransactionDefinition"/> to be used
/// </summary>
/// <remarks>
/// Defaults to <see cref="DefaultTransactionDefinition"/>
/// </remarks>
protected ITransactionDefinition TransactionDefinition
{
set { transactionDefinition = value; }
}
/// <summary>
/// Prevents the transaction.
/// </summary>
protected virtual void PreventTransaction()
{
this.transactionDefinition = null;
}
/// <summary>
/// Creates a transaction
/// </summary>
protected override void OnTestInitialize()
{
this.complete = !this.defaultRollback;
if (this.transactionManager == null)
{
logger.Info("No transaction manager set: test will NOT run within a transaction");
}
else if (this.transactionDefinition == null)
{
logger.Info("No transaction definition set: test will NOT run within a transaction");
}
else
{
OnSetUpBeforeTransaction();
StartNewTransaction();
try
{
OnSetUpInTransaction();
}
catch (Exception)
{
EndTransaction();
throw;
}
}
}
/// <summary>
/// Callback method called before transaction is setup.
/// </summary>
protected virtual void OnSetUpBeforeTransaction()
{
}
/// <summary>
/// Callback method called after transaction is setup.
/// </summary>
protected virtual void OnSetUpInTransaction()
{
}
/// <summary>
/// rollback the transaction.
/// </summary>
protected override void OnTestCleanup()
{
// Call onTearDownInTransaction and end transaction if the transaction is still active.
if (this.transactionStatus != null && !this.transactionStatus.Completed)
{
try
{
OnTearDownInTransaction();
}
finally
{
EndTransaction();
}
}
// Call onTearDownAfterTransaction if there was at least one transaction,
// even if it has been completed early through an endTransaction() call.
if (this.transactionsStarted > 0)
{
OnTearDownAfterTransaction();
}
}
/// <summary>
/// Callback before rolling back the transaction.
/// </summary>
protected virtual void OnTearDownInTransaction()
{
}
/// <summary>
/// Callback after rolling back the transaction.
/// </summary>
protected virtual void OnTearDownAfterTransaction()
{
}
/// <summary>
/// Set the complete flag..
/// </summary>
protected virtual void SetComplete()
{
if (this.transactionManager == null)
{
throw new InvalidOperationException("No transaction manager set");
}
this.complete = true;
}
/// <summary>
/// Ends the transaction.
/// </summary>
protected virtual void EndTransaction()
{
if (this.transactionStatus != null)
{
try
{
if (!this.complete)
{
this.transactionManager.Rollback(this.transactionStatus);
logger.Info("Rolled back transaction after test execution");
}
else
{
this.transactionManager.Commit(this.transactionStatus);
logger.Info("Committed transaction after test execution");
}
}
finally
{
this.transactionStatus = null;
}
}
}
/// <summary>
/// Starts the new transaction.
/// </summary>
protected void StartNewTransaction()
{
if (this.transactionStatus != null)
{
throw new InvalidOperationException("Cannot start new transaction without ending existing transaction: " +
"Invoke endTransaction() before startNewTransaction()");
}
if (this.transactionManager == null)
{
throw new InvalidOperationException("No transaction manager set");
}
this.transactionStatus = this.transactionManager.GetTransaction(this.transactionDefinition);
++this.transactionsStarted;
this.complete = !this.defaultRollback;
if (logger.IsInfoEnabled)
{
logger.Info("Began transaction (" + this.transactionsStarted + "): transaction manager [" +
this.transactionManager + "]; default rollback = " + this.defaultRollback);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace MyPortFolio.Api.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Globalization;
using System.Management.Automation;
using System.Runtime.Serialization;
using Microsoft.Management.Infrastructure;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Cmdletization.Cim
{
/// <summary>
/// Represents an error during execution of a CIM job.
/// </summary>
[Serializable]
public class CimJobException : SystemException, IContainsErrorRecord
{
#region Standard constructors and methods required for all exceptions
/// <summary>
/// Initializes a new instance of the <see cref="CimJobException"/> class.
/// </summary>
public CimJobException() : this(null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CimJobException"/> class with a specified error message.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public CimJobException(string message) : this(message, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CimJobException"/> class with a specified error message.
/// </summary>
/// <param name="message">The message that describes the error.</param>
/// <param name="inner">The exception that is the cause of the current exception, or a null reference if no inner exception is specified.</param>
public CimJobException(string message, Exception inner) : base(message, inner)
{
InitializeErrorRecord(null, "CimJob_ExternalError", ErrorCategory.NotSpecified);
}
/// <summary>
/// Initializes a new instance of the <see cref="CimJobException"/> class with serialized data.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
protected CimJobException(
SerializationInfo info,
StreamingContext context) : base(info, context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
_errorRecord = (ErrorRecord)info.GetValue("errorRecord", typeof(ErrorRecord));
}
/// <summary>
/// Sets the SerializationInfo with information about the exception.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
base.GetObjectData(info, context);
info.AddValue("errorRecord", _errorRecord);
}
#endregion
internal static CimJobException CreateFromCimException(
string jobDescription,
CimJobContext jobContext,
CimException cimException)
{
Dbg.Assert(!string.IsNullOrEmpty(jobDescription), "Caller should verify jobDescription != null");
Dbg.Assert(jobContext != null, "Caller should verify jobContext != null");
Dbg.Assert(cimException != null, "Caller should verify cimException != null");
string message = BuildErrorMessage(jobDescription, jobContext, cimException.Message);
CimJobException cimJobException = new CimJobException(message, cimException);
cimJobException.InitializeErrorRecord(jobContext, cimException);
return cimJobException;
}
internal static CimJobException CreateFromAnyException(
string jobDescription,
CimJobContext jobContext,
Exception inner)
{
Dbg.Assert(!string.IsNullOrEmpty(jobDescription), "Caller should verify jobDescription != null");
Dbg.Assert(jobContext != null, "Caller should verify jobContext != null");
Dbg.Assert(inner != null, "Caller should verify inner != null");
CimException cimException = inner as CimException;
if (cimException != null)
{
return CreateFromCimException(jobDescription, jobContext, cimException);
}
string message = BuildErrorMessage(jobDescription, jobContext, inner.Message);
CimJobException cimJobException = new CimJobException(message, inner);
var containsErrorRecord = inner as IContainsErrorRecord;
if (containsErrorRecord != null)
{
cimJobException.InitializeErrorRecord(
jobContext,
errorId: "CimJob_" + containsErrorRecord.ErrorRecord.FullyQualifiedErrorId,
errorCategory: containsErrorRecord.ErrorRecord.CategoryInfo.Category);
}
else
{
cimJobException.InitializeErrorRecord(
jobContext,
errorId: "CimJob_" + inner.GetType().Name,
errorCategory: ErrorCategory.NotSpecified);
}
return cimJobException;
}
internal static CimJobException CreateWithFullControl(
CimJobContext jobContext,
string message,
string errorId,
ErrorCategory errorCategory,
Exception inner = null)
{
Dbg.Assert(jobContext != null, "Caller should verify jobContext != null");
Dbg.Assert(!string.IsNullOrEmpty(message), "Caller should verify message != null");
Dbg.Assert(!string.IsNullOrEmpty(errorId), "Caller should verify errorId != null");
CimJobException cimJobException = new CimJobException(jobContext.PrependComputerNameToMessage(message), inner);
cimJobException.InitializeErrorRecord(jobContext, errorId, errorCategory);
return cimJobException;
}
internal static CimJobException CreateWithoutJobContext(
string message,
string errorId,
ErrorCategory errorCategory,
Exception inner = null)
{
Dbg.Assert(!string.IsNullOrEmpty(message), "Caller should verify message != null");
Dbg.Assert(!string.IsNullOrEmpty(errorId), "Caller should verify errorId != null");
CimJobException cimJobException = new CimJobException(message, inner);
cimJobException.InitializeErrorRecord(null, errorId, errorCategory);
return cimJobException;
}
internal static CimJobException CreateFromMethodErrorCode(string jobDescription, CimJobContext jobContext, string methodName, string errorCodeFromMethod)
{
string rawErrorMessage = string.Format(
CultureInfo.InvariantCulture,
CmdletizationResources.CimJob_ErrorCodeFromMethod,
errorCodeFromMethod);
string errorMessage = BuildErrorMessage(jobDescription, jobContext, rawErrorMessage);
CimJobException cje = new CimJobException(errorMessage);
cje.InitializeErrorRecord(jobContext, "CimJob_" + methodName + "_" + errorCodeFromMethod, ErrorCategory.InvalidResult);
return cje;
}
private static string BuildErrorMessage(string jobDescription, CimJobContext jobContext, string errorMessage)
{
Dbg.Assert(!string.IsNullOrEmpty(errorMessage), "Caller should verify !string.IsNullOrEmpty(errorMessage)");
if (string.IsNullOrEmpty(jobDescription))
{
return jobContext.PrependComputerNameToMessage(errorMessage);
}
else
{
string errorMessageWithJobDescription = string.Format(
CultureInfo.InvariantCulture,
CmdletizationResources.CimJob_GenericCimFailure,
errorMessage,
jobDescription);
return jobContext.PrependComputerNameToMessage(errorMessageWithJobDescription);
}
}
private void InitializeErrorRecordCore(CimJobContext jobContext, Exception exception, string errorId, ErrorCategory errorCategory)
{
ErrorRecord coreErrorRecord = new ErrorRecord(
exception: exception,
errorId: errorId,
errorCategory: errorCategory,
targetObject: jobContext != null ? jobContext.TargetObject : null);
if (jobContext != null)
{
System.Management.Automation.Remoting.OriginInfo originInfo = new System.Management.Automation.Remoting.OriginInfo(
jobContext.Session.ComputerName,
Guid.Empty);
_errorRecord = new System.Management.Automation.Runspaces.RemotingErrorRecord(
coreErrorRecord,
originInfo);
_errorRecord.SetInvocationInfo(jobContext.CmdletInvocationInfo);
_errorRecord.PreserveInvocationInfoOnce = true;
}
else
{
_errorRecord = coreErrorRecord;
}
}
private void InitializeErrorRecord(CimJobContext jobContext, string errorId, ErrorCategory errorCategory)
{
InitializeErrorRecordCore(
jobContext: jobContext,
exception: this,
errorId: errorId,
errorCategory: errorCategory);
}
private void InitializeErrorRecord(CimJobContext jobContext, CimException cimException)
{
InitializeErrorRecordCore(
jobContext: jobContext,
exception: cimException,
errorId: cimException.MessageId ?? "MiClientApiError_" + cimException.NativeErrorCode,
errorCategory: ConvertCimExceptionToErrorCategory(cimException));
if (cimException.ErrorData != null)
{
_errorRecord.CategoryInfo.TargetName = cimException.ErrorSource;
_errorRecord.CategoryInfo.TargetType = jobContext != null ? jobContext.CmdletizationClassName : null;
}
}
private static ErrorCategory ConvertCimExceptionToErrorCategory(CimException cimException)
{
ErrorCategory result = ErrorCategory.NotSpecified;
if (cimException.ErrorData != null)
{
result = ConvertCimErrorToErrorCategory(cimException.ErrorData);
}
if (result == ErrorCategory.NotSpecified)
{
result = ConvertCimNativeErrorCodeToErrorCategory(cimException.NativeErrorCode);
}
return result;
}
private static ErrorCategory ConvertCimNativeErrorCodeToErrorCategory(NativeErrorCode nativeErrorCode)
{
switch (nativeErrorCode)
{
case NativeErrorCode.Ok:
return ErrorCategory.NotSpecified;
case NativeErrorCode.Failed:
return ErrorCategory.NotSpecified;
case NativeErrorCode.AccessDenied:
return ErrorCategory.PermissionDenied;
case NativeErrorCode.InvalidNamespace:
return ErrorCategory.MetadataError;
case NativeErrorCode.InvalidParameter:
return ErrorCategory.InvalidArgument;
case NativeErrorCode.InvalidClass:
return ErrorCategory.MetadataError;
case NativeErrorCode.NotFound:
return ErrorCategory.ObjectNotFound;
case NativeErrorCode.NotSupported:
return ErrorCategory.NotImplemented;
case NativeErrorCode.ClassHasChildren:
return ErrorCategory.MetadataError;
case NativeErrorCode.ClassHasInstances:
return ErrorCategory.MetadataError;
case NativeErrorCode.InvalidSuperClass:
return ErrorCategory.MetadataError;
case NativeErrorCode.AlreadyExists:
return ErrorCategory.ResourceExists;
case NativeErrorCode.NoSuchProperty:
return ErrorCategory.MetadataError;
case NativeErrorCode.TypeMismatch:
return ErrorCategory.InvalidType;
case NativeErrorCode.QueryLanguageNotSupported:
return ErrorCategory.NotImplemented;
case NativeErrorCode.InvalidQuery:
return ErrorCategory.InvalidArgument;
case NativeErrorCode.MethodNotAvailable:
return ErrorCategory.MetadataError;
case NativeErrorCode.MethodNotFound:
return ErrorCategory.MetadataError;
case NativeErrorCode.NamespaceNotEmpty:
return ErrorCategory.MetadataError;
case NativeErrorCode.InvalidEnumerationContext:
return ErrorCategory.MetadataError;
case NativeErrorCode.InvalidOperationTimeout:
return ErrorCategory.InvalidArgument;
case NativeErrorCode.PullHasBeenAbandoned:
return ErrorCategory.OperationStopped;
case NativeErrorCode.PullCannotBeAbandoned:
return ErrorCategory.CloseError;
case NativeErrorCode.FilteredEnumerationNotSupported:
return ErrorCategory.NotImplemented;
case NativeErrorCode.ContinuationOnErrorNotSupported:
return ErrorCategory.NotImplemented;
case NativeErrorCode.ServerLimitsExceeded:
return ErrorCategory.ResourceBusy;
case NativeErrorCode.ServerIsShuttingDown:
return ErrorCategory.ResourceUnavailable;
default:
return ErrorCategory.NotSpecified;
}
}
private static ErrorCategory ConvertCimErrorToErrorCategory(CimInstance cimError)
{
if (cimError == null)
{
return ErrorCategory.NotSpecified;
}
CimProperty errorCategoryProperty = cimError.CimInstanceProperties["Error_Category"];
if (errorCategoryProperty == null)
{
return ErrorCategory.NotSpecified;
}
ErrorCategory errorCategoryValue;
if (!LanguagePrimitives.TryConvertTo<ErrorCategory>(errorCategoryProperty.Value, CultureInfo.InvariantCulture, out errorCategoryValue))
{
return ErrorCategory.NotSpecified;
}
return errorCategoryValue;
}
/// <summary>
/// <see cref="ErrorRecord"/> which provides additional information about the error.
/// </summary>
public ErrorRecord ErrorRecord
{
get { return _errorRecord; }
}
private ErrorRecord _errorRecord;
internal bool IsTerminatingError
{
get
{
var cimException = this.InnerException as CimException;
if ((cimException == null) || (cimException.ErrorData == null))
{
return false;
}
CimProperty perceivedSeverityProperty = cimException.ErrorData.CimInstanceProperties["PerceivedSeverity"];
if ((perceivedSeverityProperty == null) || (perceivedSeverityProperty.CimType != CimType.UInt16) || (perceivedSeverityProperty.Value == null))
{
return false;
}
UInt16 perceivedSeverityValue = (UInt16)perceivedSeverityProperty.Value;
if (perceivedSeverityValue != 7)
{
/* from CIM Schema: Interop\CIM_Error.mof:
"7 - Fatal/NonRecoverable should be used to indicate an "
"error occurred, but it\'s too late to take remedial "
"action. \n"
*/
return false;
}
return true;
}
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Apple;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class AppleCrypto
{
private const string OidPbes2 = "1.2.840.113549.1.5.13";
private const string OidPbkdf2 = "1.2.840.113549.1.5.12";
private const string OidSha1 = "1.3.14.3.2.26";
private const string OidTripleDesCbc = "1.2.840.113549.3.7";
private static readonly SafeCreateHandle s_nullExportString = new SafeCreateHandle();
private static readonly SafeCreateHandle s_emptyExportString =
CoreFoundation.CFStringCreateWithCString("");
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_SecKeyExport(
SafeSecKeyRefHandle key,
int exportPrivate,
SafeCreateHandle cfExportPassphrase,
out SafeCFDataHandle cfDataOut,
out int pOSStatus);
internal static DerSequenceReader SecKeyExport(
SafeSecKeyRefHandle key,
bool exportPrivate)
{
// Apple requires all private keys to be exported encrypted, but since we're trying to export
// as parsed structures we will need to decrypt it for the user.
const string ExportPassword = "DotnetExportPassphrase";
SafeCreateHandle exportPassword = exportPrivate
? CoreFoundation.CFStringCreateWithCString(ExportPassword)
: s_nullExportString;
int ret;
SafeCFDataHandle cfData;
int osStatus;
try
{
ret = AppleCryptoNative_SecKeyExport(
key,
exportPrivate ? 1 : 0,
exportPassword,
out cfData,
out osStatus);
}
finally
{
if (exportPassword != s_nullExportString)
{
exportPassword.Dispose();
}
}
byte[] exportedData;
using (cfData)
{
if (ret == 0)
{
throw CreateExceptionForOSStatus(osStatus);
}
if (ret != 1)
{
Debug.Fail($"AppleCryptoNative_SecKeyExport returned {ret}");
throw new CryptographicException();
}
exportedData = CoreFoundation.CFGetData(cfData);
}
DerSequenceReader reader = new DerSequenceReader(exportedData);
if (!exportPrivate)
{
return reader;
}
byte tag = reader.PeekTag();
// PKCS#8 defines two structures, PrivateKeyInfo, which starts with an integer,
// and EncryptedPrivateKey, which starts with an encryption algorithm (DER sequence).
if (tag == (byte)DerSequenceReader.DerTag.Integer)
{
return reader;
}
const byte ConstructedSequence =
DerSequenceReader.ConstructedFlag | (byte)DerSequenceReader.DerTag.Sequence;
if (tag == ConstructedSequence)
{
return ReadEncryptedPkcs8Blob(ExportPassword, reader);
}
Debug.Fail($"Data was neither PrivateKey or EncryptedPrivateKey: {tag:X2}");
throw new CryptographicException();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "3DES identified from payload by OID")]
private static DerSequenceReader ReadEncryptedPkcs8Blob(string passphrase, DerSequenceReader reader)
{
// EncryptedPrivateKeyInfo::= SEQUENCE {
// encryptionAlgorithm EncryptionAlgorithmIdentifier,
// encryptedData EncryptedData }
//
// EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
//
// EncryptedData ::= OCTET STRING
DerSequenceReader algorithmIdentifier = reader.ReadSequence();
string algorithmOid = algorithmIdentifier.ReadOidAsString();
// PBES2 (Password-Based Encryption Scheme 2)
if (algorithmOid != OidPbes2)
{
Debug.Fail($"Expected PBES2 ({OidPbes2}), got {algorithmOid}");
throw new CryptographicException();
}
// PBES2-params ::= SEQUENCE {
// keyDerivationFunc AlgorithmIdentifier { { PBES2 - KDFs} },
// encryptionScheme AlgorithmIdentifier { { PBES2 - Encs} }
// }
DerSequenceReader pbes2Params = algorithmIdentifier.ReadSequence();
algorithmIdentifier = pbes2Params.ReadSequence();
string kdfOid = algorithmIdentifier.ReadOidAsString();
// PBKDF2 (Password-Based Key Derivation Function 2)
if (kdfOid != OidPbkdf2)
{
Debug.Fail($"Expected PBKDF2 ({OidPbkdf2}), got {kdfOid}");
throw new CryptographicException();
}
// PBKDF2-params ::= SEQUENCE {
// salt CHOICE {
// specified OCTET STRING,
// otherSource AlgorithmIdentifier { { PBKDF2 - SaltSources} }
// },
// iterationCount INTEGER (1..MAX),
// keyLength INTEGER(1..MAX) OPTIONAL,
// prf AlgorithmIdentifier { { PBKDF2 - PRFs} } DEFAULT algid - hmacWithSHA1
// }
DerSequenceReader pbkdf2Params = algorithmIdentifier.ReadSequence();
byte[] salt = pbkdf2Params.ReadOctetString();
int iterCount = pbkdf2Params.ReadInteger();
int keySize = -1;
if (pbkdf2Params.HasData && pbkdf2Params.PeekTag() == (byte)DerSequenceReader.DerTag.Integer)
{
keySize = pbkdf2Params.ReadInteger();
}
if (pbkdf2Params.HasData)
{
string prfOid = pbkdf2Params.ReadOidAsString();
// SHA-1 is the only hash algorithm our PBKDF2 supports.
if (prfOid != OidSha1)
{
Debug.Fail($"Expected SHA1 ({OidSha1}), got {prfOid}");
throw new CryptographicException();
}
}
DerSequenceReader encryptionScheme = pbes2Params.ReadSequence();
string cipherOid = encryptionScheme.ReadOidAsString();
// DES-EDE3-CBC (TripleDES in CBC mode)
if (cipherOid != OidTripleDesCbc)
{
Debug.Fail($"Expected DES-EDE3-CBC ({OidTripleDesCbc}), got {cipherOid}");
throw new CryptographicException();
}
byte[] decrypted;
using (TripleDES des3 = TripleDES.Create())
{
if (keySize == -1)
{
foreach (KeySizes keySizes in des3.LegalKeySizes)
{
keySize = Math.Max(keySize, keySizes.MaxSize);
}
}
byte[] iv = encryptionScheme.ReadOctetString();
using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(passphrase, salt, iterCount))
using (ICryptoTransform decryptor = des3.CreateDecryptor(pbkdf2.GetBytes(keySize / 8), iv))
{
byte[] encrypted = reader.ReadOctetString();
decrypted = decryptor.TransformFinalBlock(encrypted, 0, encrypted.Length);
}
}
DerSequenceReader pkcs8Reader = new DerSequenceReader(decrypted);
return pkcs8Reader;
}
}
}
| |
// Copyright 2007-2017 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.NLogIntegration.Logging
{
using System;
using MassTransit.Logging;
using NLog;
/// <summary>
/// A logger that wraps to NLog. See http://stackoverflow.com/questions/7412156/how-to-retain-callsite-information-when-wrapping-nlog
/// </summary>
public class NLogLog :
ILog
{
readonly NLog.Logger _log;
/// <summary>
/// Create a new NLog logger instance.
/// </summary>
/// <param name="log"></param>
/// <param name="name">Name of type to log as.</param>
public NLogLog(NLog.Logger log, string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
_log = log;
}
public bool IsDebugEnabled => _log.IsDebugEnabled;
public bool IsInfoEnabled => _log.IsInfoEnabled;
public bool IsWarnEnabled => _log.IsWarnEnabled;
public bool IsErrorEnabled => _log.IsErrorEnabled;
public bool IsFatalEnabled => _log.IsFatalEnabled;
public void Log(MassTransit.Logging.LogLevel level, object obj)
{
_log.Log(GetNLogLevel(level), obj);
}
public void Log(MassTransit.Logging.LogLevel level, object obj, Exception exception)
{
_log.Log(GetNLogLevel(level), exception, obj?.ToString() ?? "");
}
public void Log(MassTransit.Logging.LogLevel level, LogOutputProvider messageProvider)
{
_log.Log(GetNLogLevel(level), ToGenerator(messageProvider));
}
public void LogFormat(MassTransit.Logging.LogLevel level, IFormatProvider formatProvider, string format,
params object[] args)
{
_log.Log(GetNLogLevel(level), formatProvider, format, args);
}
public void LogFormat(MassTransit.Logging.LogLevel level, string format, params object[] args)
{
_log.Log(GetNLogLevel(level), format, args);
}
public void Debug(object obj)
{
_log.Log(NLog.LogLevel.Debug, obj);
}
public void Debug(object obj, Exception exception)
{
_log.Log(NLog.LogLevel.Debug, exception, obj?.ToString() ?? "");
}
public void Debug(LogOutputProvider messageProvider)
{
_log.Debug(ToGenerator(messageProvider));
}
public void Info(object obj)
{
_log.Log(NLog.LogLevel.Info, obj);
}
public void Info(object obj, Exception exception)
{
_log.Log(NLog.LogLevel.Info, exception, obj?.ToString() ?? "");
}
public void Info(LogOutputProvider messageProvider)
{
_log.Info(ToGenerator(messageProvider));
}
public void Warn(object obj)
{
_log.Log(NLog.LogLevel.Warn, obj);
}
public void Warn(object obj, Exception exception)
{
_log.Log(NLog.LogLevel.Warn, exception, obj?.ToString() ?? "");
}
public void Warn(LogOutputProvider messageProvider)
{
_log.Warn(ToGenerator(messageProvider));
}
public void Error(object obj)
{
_log.Log(NLog.LogLevel.Error, obj);
}
public void Error(object obj, Exception exception)
{
_log.Log(NLog.LogLevel.Error, exception, obj?.ToString() ?? "");
}
public void Error(LogOutputProvider messageProvider)
{
_log.Error(ToGenerator(messageProvider));
}
public void Fatal(object obj)
{
_log.Log(NLog.LogLevel.Fatal, obj);
}
public void Fatal(object obj, Exception exception)
{
_log.Log(NLog.LogLevel.Fatal, exception, obj?.ToString() ?? "");
}
public void Fatal(LogOutputProvider messageProvider)
{
_log.Fatal(ToGenerator(messageProvider));
}
public void DebugFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_log.Log(NLog.LogLevel.Debug, formatProvider, format, args);
}
public void DebugFormat(string format, params object[] args)
{
_log.Log(NLog.LogLevel.Debug, format, args);
}
public void InfoFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_log.Log(NLog.LogLevel.Info, formatProvider, format, args);
}
public void InfoFormat(string format, params object[] args)
{
_log.Log(NLog.LogLevel.Info, format, args);
}
public void WarnFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_log.Log(NLog.LogLevel.Warn, formatProvider, format, args);
}
public void WarnFormat(string format, params object[] args)
{
_log.Log(NLog.LogLevel.Warn, format, args);
}
public void ErrorFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_log.Log(NLog.LogLevel.Error, formatProvider, format, args);
}
public void ErrorFormat(string format, params object[] args)
{
_log.Log(NLog.LogLevel.Error, format, args);
}
public void FatalFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_log.Log(NLog.LogLevel.Fatal, formatProvider, format, args);
}
public void FatalFormat(string format, params object[] args)
{
_log.Log(NLog.LogLevel.Fatal, format, args);
}
NLog.LogLevel GetNLogLevel(MassTransit.Logging.LogLevel level)
{
if (level == MassTransit.Logging.LogLevel.Fatal)
return NLog.LogLevel.Fatal;
if (level == MassTransit.Logging.LogLevel.Error)
return NLog.LogLevel.Error;
if (level == MassTransit.Logging.LogLevel.Warn)
return NLog.LogLevel.Warn;
if (level == MassTransit.Logging.LogLevel.Info)
return NLog.LogLevel.Info;
if (level == MassTransit.Logging.LogLevel.Debug)
return NLog.LogLevel.Debug;
if (level == MassTransit.Logging.LogLevel.All)
return NLog.LogLevel.Trace;
return NLog.LogLevel.Off;
}
LogMessageGenerator ToGenerator(LogOutputProvider provider)
{
return () =>
{
var obj = provider();
return obj?.ToString() ?? "";
};
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcsv = Google.Cloud.ServiceDirectory.V1;
using sys = System;
namespace Google.Cloud.ServiceDirectory.V1
{
/// <summary>Resource name for the <c>Namespace</c> resource.</summary>
public sealed partial class NamespaceName : gax::IResourceName, sys::IEquatable<NamespaceName>
{
/// <summary>The possible contents of <see cref="NamespaceName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/namespaces/{namespace}</c>.
/// </summary>
ProjectLocationNamespace = 1,
}
private static gax::PathTemplate s_projectLocationNamespace = new gax::PathTemplate("projects/{project}/locations/{location}/namespaces/{namespace}");
/// <summary>Creates a <see cref="NamespaceName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="NamespaceName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static NamespaceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new NamespaceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="NamespaceName"/> with the pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="NamespaceName"/> constructed from the provided ids.</returns>
public static NamespaceName FromProjectLocationNamespace(string projectId, string locationId, string namespaceId) =>
new NamespaceName(ResourceNameType.ProjectLocationNamespace, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), namespaceId: gax::GaxPreconditions.CheckNotNullOrEmpty(namespaceId, nameof(namespaceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="NamespaceName"/> with pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="NamespaceName"/> with pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string namespaceId) =>
FormatProjectLocationNamespace(projectId, locationId, namespaceId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="NamespaceName"/> with pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="NamespaceName"/> with pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}</c>.
/// </returns>
public static string FormatProjectLocationNamespace(string projectId, string locationId, string namespaceId) =>
s_projectLocationNamespace.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(namespaceId, nameof(namespaceId)));
/// <summary>Parses the given resource name string into a new <see cref="NamespaceName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/namespaces/{namespace}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="namespaceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="NamespaceName"/> if successful.</returns>
public static NamespaceName Parse(string namespaceName) => Parse(namespaceName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="NamespaceName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/namespaces/{namespace}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="namespaceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="NamespaceName"/> if successful.</returns>
public static NamespaceName Parse(string namespaceName, bool allowUnparsed) =>
TryParse(namespaceName, allowUnparsed, out NamespaceName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="NamespaceName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/namespaces/{namespace}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="namespaceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="NamespaceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string namespaceName, out NamespaceName result) => TryParse(namespaceName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="NamespaceName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/namespaces/{namespace}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="namespaceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="NamespaceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string namespaceName, bool allowUnparsed, out NamespaceName result)
{
gax::GaxPreconditions.CheckNotNull(namespaceName, nameof(namespaceName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationNamespace.TryParseName(namespaceName, out resourceName))
{
result = FromProjectLocationNamespace(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(namespaceName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private NamespaceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string namespaceId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
NamespaceId = namespaceId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="NamespaceName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param>
public NamespaceName(string projectId, string locationId, string namespaceId) : this(ResourceNameType.ProjectLocationNamespace, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), namespaceId: gax::GaxPreconditions.CheckNotNullOrEmpty(namespaceId, nameof(namespaceId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Namespace</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string NamespaceId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationNamespace: return s_projectLocationNamespace.Expand(ProjectId, LocationId, NamespaceId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as NamespaceName);
/// <inheritdoc/>
public bool Equals(NamespaceName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(NamespaceName a, NamespaceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(NamespaceName a, NamespaceName b) => !(a == b);
}
public partial class Namespace
{
/// <summary>
/// <see cref="gcsv::NamespaceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcsv::NamespaceName NamespaceName
{
get => string.IsNullOrEmpty(Name) ? null : gcsv::NamespaceName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Collections.Tests
{
public static class BitArray_CtorTests
{
private const int BitsPerByte = 8;
private const int BitsPerInt32 = 32;
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(BitsPerByte)]
[InlineData(BitsPerByte * 2)]
[InlineData(BitsPerInt32)]
[InlineData(BitsPerInt32 * 2)]
[InlineData(200)]
[InlineData(65551)]
public static void Ctor_Int(int length)
{
BitArray bitArray = new BitArray(length);
Assert.Equal(length, bitArray.Length);
for (int i = 0; i < bitArray.Length; i++)
{
Assert.False(bitArray[i]);
Assert.False(bitArray.Get(i));
}
ICollection collection = bitArray;
Assert.Equal(length, collection.Count);
Assert.False(collection.IsSynchronized);
}
[Theory]
[InlineData(0, true)]
[InlineData(0, false)]
[InlineData(1, true)]
[InlineData(1, false)]
[InlineData(BitsPerByte, true)]
[InlineData(BitsPerByte, false)]
[InlineData(BitsPerByte * 2, true)]
[InlineData(BitsPerByte * 2, false)]
[InlineData(BitsPerInt32, true)]
[InlineData(BitsPerInt32, false)]
[InlineData(BitsPerInt32 * 2, true)]
[InlineData(BitsPerInt32 * 2, false)]
[InlineData(200, true)]
[InlineData(200, false)]
[InlineData(65551, true)]
[InlineData(65551, false)]
public static void Ctor_Int_Bool(int length, bool defaultValue)
{
BitArray bitArray = new BitArray(length, defaultValue);
Assert.Equal(length, bitArray.Length);
for (int i = 0; i < bitArray.Length; i++)
{
Assert.Equal(defaultValue, bitArray[i]);
Assert.Equal(defaultValue, bitArray.Get(i));
}
ICollection collection = bitArray;
Assert.Equal(length, collection.Count);
Assert.False(collection.IsSynchronized);
}
[Fact]
public static void Ctor_Int_NegativeLength_ThrowsArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>("length", () => new BitArray(-1));
Assert.Throws<ArgumentOutOfRangeException>("length", () => new BitArray(-1, false));
}
public static IEnumerable<object[]> Ctor_BoolArray_TestData()
{
yield return new object[] { new bool[0] };
foreach (int size in new[] { 1, BitsPerByte, BitsPerByte * 2, BitsPerInt32, BitsPerInt32 * 2 })
{
yield return new object[] { Enumerable.Repeat(true, size).ToArray() };
yield return new object[] { Enumerable.Repeat(false, size).ToArray() };
yield return new object[] { Enumerable.Range(0, size).Select(x => x % 2 == 0).ToArray() };
}
}
[Theory]
[MemberData(nameof(Ctor_BoolArray_TestData))]
public static void Ctor_BoolArray(bool[] values)
{
BitArray bitArray = new BitArray(values);
Assert.Equal(values.Length, bitArray.Length);
for (int i = 0; i < bitArray.Length; i++)
{
Assert.Equal(values[i], bitArray[i]);
Assert.Equal(values[i], bitArray.Get(i));
}
ICollection collection = bitArray;
Assert.Equal(values.Length, collection.Count);
Assert.False(collection.IsSynchronized);
}
[Fact]
public static void Ctor_NullBoolArray_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("values", () => new BitArray((bool[])null));
}
public static IEnumerable<object[]> Ctor_BitArray_TestData()
{
yield return new object[] { "bool[](empty)", new BitArray(new bool[0]) };
yield return new object[] { "byte[](empty)", new BitArray(new byte[0]) };
yield return new object[] { "int[](empty)", new BitArray(new int[0]) };
foreach (int size in new[] { 1, BitsPerByte, BitsPerByte * 2, BitsPerInt32, BitsPerInt32 * 2 })
{
yield return new object[] { "length", new BitArray(size) };
yield return new object[] { "length|default(true)", new BitArray(size, true) };
yield return new object[] { "length|default(false)", new BitArray(size, false) };
yield return new object[] { "bool[](all)", new BitArray(Enumerable.Repeat(true, size).ToArray()) };
yield return new object[] { "bool[](none)", new BitArray(Enumerable.Repeat(false, size).ToArray()) };
yield return new object[] { "bool[](alternating)", new BitArray(Enumerable.Range(0, size).Select(x => x % 2 == 0).ToArray()) };
if (size >= BitsPerByte)
{
yield return new object[] { "byte[](all)", new BitArray(Enumerable.Repeat((byte)0xff, size / BitsPerByte).ToArray()) };
yield return new object[] { "byte[](none)", new BitArray(Enumerable.Repeat((byte)0x00, size / BitsPerByte).ToArray()) };
yield return new object[] { "byte[](alternating)", new BitArray(Enumerable.Repeat((byte)0xaa, size / BitsPerByte).ToArray()) };
}
if (size >= BitsPerInt32)
{
yield return new object[] { "int[](all)", new BitArray(Enumerable.Repeat(unchecked((int)0xffffffff), size / BitsPerInt32).ToArray()) };
yield return new object[] { "int[](none)", new BitArray(Enumerable.Repeat(0x00000000, size / BitsPerInt32).ToArray()) };
yield return new object[] { "int[](alternating)", new BitArray(Enumerable.Repeat(unchecked((int)0xaaaaaaaa), size / BitsPerInt32).ToArray()) };
}
}
}
[Theory]
[MemberData(nameof(Ctor_BitArray_TestData))]
public static void Ctor_BitArray(string label, BitArray bits)
{
BitArray bitArray = new BitArray(bits);
Assert.Equal(bits.Length, bitArray.Length);
for (int i = 0; i < bitArray.Length; i++)
{
Assert.Equal(bits[i], bitArray[i]);
Assert.Equal(bits[i], bitArray.Get(i));
}
ICollection collection = bitArray;
Assert.Equal(bits.Length, collection.Count);
Assert.False(collection.IsSynchronized);
}
[Fact]
public static void Ctor_NullBitArray_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("bits", () => new BitArray((BitArray)null));
}
public static IEnumerable<object[]> Ctor_IntArray_TestData()
{
yield return new object[] { new int[0], new bool[0] };
foreach (int size in new[] { 1, 10 })
{
yield return new object[] { Enumerable.Repeat(unchecked((int)0xffffffff), size).ToArray(), Enumerable.Repeat(true, size * BitsPerInt32).ToArray() };
yield return new object[] { Enumerable.Repeat(0x00000000, size).ToArray(), Enumerable.Repeat(false, size * BitsPerInt32).ToArray() };
yield return new object[] { Enumerable.Repeat(unchecked((int)0xaaaaaaaa), size).ToArray(), Enumerable.Range(0, size * BitsPerInt32).Select(i => i % 2 == 1).ToArray() };
}
}
[Theory]
[MemberData(nameof(Ctor_IntArray_TestData))]
public static void Ctor_IntArray(int[] array, bool[] expected)
{
BitArray bitArray = new BitArray(array);
Assert.Equal(expected.Length, bitArray.Length);
for (int i = 0; i < expected.Length; i++)
{
Assert.Equal(expected[i], bitArray[i]);
Assert.Equal(expected[i], bitArray.Get(i));
}
ICollection collection = bitArray;
Assert.Equal(expected.Length, collection.Count);
Assert.False(collection.IsSynchronized);
}
[Fact]
public static void Ctor_NullIntArray_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("values", () => new BitArray((int[])null));
}
[Fact]
public static void Ctor_LargeIntArrayOverflowingBitArray_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>("values", () => new BitArray(new int[int.MaxValue / BitsPerInt32 + 1 ]));
}
public static IEnumerable<object[]> Ctor_ByteArray_TestData()
{
yield return new object[] { new byte[0], new bool[0] };
foreach (int size in new[] { 1, 2, 3, BitsPerInt32 / BitsPerByte, 2 * BitsPerInt32 / BitsPerByte })
{
yield return new object[] { Enumerable.Repeat((byte)0xff, size).ToArray(), Enumerable.Repeat(true, size * BitsPerByte).ToArray() };
yield return new object[] { Enumerable.Repeat((byte)0x00, size).ToArray(), Enumerable.Repeat(false, size * BitsPerByte).ToArray() };
yield return new object[] { Enumerable.Repeat((byte)0xaa, size).ToArray(), Enumerable.Range(0, size * BitsPerByte).Select(i => i % 2 == 1).ToArray() };
}
}
[Theory]
[MemberData(nameof(Ctor_ByteArray_TestData))]
public static void Ctor_ByteArray(byte[] bytes, bool[] expected)
{
BitArray bitArray = new BitArray(bytes);
Assert.Equal(expected.Length, bitArray.Length);
for (int i = 0; i < bitArray.Length; i++)
{
Assert.Equal(expected[i], bitArray[i]);
Assert.Equal(expected[i], bitArray.Get(i));
}
ICollection collection = bitArray;
Assert.Equal(expected.Length, collection.Count);
Assert.False(collection.IsSynchronized);
}
[Fact]
public static void Ctor_NullByteArray_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("bytes", () => new BitArray((byte[])null));
}
[Fact]
public static void Ctor_LargeByteArrayOverflowingBitArray_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>("bytes", () => new BitArray(new byte[int.MaxValue / BitsPerByte + 1 ]));
}
[Fact]
public static void Ctor_Simple_Method_Tests()
{
int length = 0;
BitArray bitArray = new BitArray(length);
Assert.NotNull(bitArray.SyncRoot);
Assert.False(bitArray.IsSynchronized);
Assert.False(bitArray.IsReadOnly);
Assert.Equal(bitArray, bitArray.Clone());
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "A bug in BitArray.Clone() caused an ArgumentExeption to be thrown in this case.")]
[Fact]
public static void Clone_LongLength_Works()
{
BitArray bitArray = new BitArray(int.MaxValue - 30);
BitArray clone = (BitArray)bitArray.Clone();
Assert.Equal(bitArray.Length, clone.Length);
}
}
}
| |
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
using System;
using System.Collections.Generic;
using System.Linq;
using Glass.Mapper.Pipelines.ConfigurationResolver.Tasks.OnDemandResolver;
using Glass.Mapper.Pipelines.DataMapperResolver;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.Configuration.Attributes;
using Glass.Mapper.Sc.DataMappers;
using Glass.Mapper.Sc.DataMappers.SitecoreQueryParameters;
using NUnit.Framework;
using Sitecore.Data;
using Sitecore.FakeDb;
namespace Glass.Mapper.Sc.FakeDb.DataMappers
{
[TestFixture]
public class SitecoreQueryMapperFixture
{
#region Property - ReadOnly
[Test]
public void ReadOnly_ReturnsTrue()
{
//Assign
var mapper = new SitecoreQueryMapper(null);
//Act
var result = mapper.ReadOnly;
//Assert
Assert.IsTrue(result);
}
#endregion
#region Method - CanHandle
[Test]
public void CanHandle_CorrectConfigIEnumerableMappedClass_ReturnsTrue()
{
//Assign
var mapper = new SitecoreQueryMapper(null);
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMappeds");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubClass)));
//Act
var result = mapper.CanHandle(config, context);
//Assert
Assert.IsTrue(result);
}
[Test]
public void CanHandle_CorrectConfigIEnumerableNotMappedClass_ReturnsTrueOnDemand()
{
//Assign
var mapper = new SitecoreQueryMapper(null);
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubNotMappeds");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubClass)));
//Act
var result = mapper.CanHandle(config, context);
//Assert
Assert.IsTrue(result);
}
[Test]
public void CanHandle_CorrectConfigNotMappedClass_ReturnsTrueOnDemand()
{
//Assign
var mapper = new SitecoreQueryMapper(null);
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubNotMapped");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubClass)));
//Act
var result = mapper.CanHandle(config, context);
//Assert
Assert.IsTrue(result);
}
[Test]
public void CanHandle_CorrectConfigMappedClass_ReturnsFalse()
{
//Assign
var mapper = new SitecoreQueryMapper(null);
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMapped");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubClass)));
//Act
var result = mapper.CanHandle(config, context);
//Assert
Assert.IsTrue(result);
}
[Test]
public void CanHandle_IncorrectConfigMappedClass_ReturnsFalse()
{
//Assign
var mapper = new SitecoreQueryMapper(null);
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMapped");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubClass)));
//Act
var result = mapper.CanHandle(config, context);
//Assert
Assert.IsFalse(result);
}
#endregion
#region Method - MapToProperty
[Test]
public void MapToProperty_RelativeQuery_ReturnsNoResults()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbItem("Child1"),
new Sitecore.FakeDb.DbItem("Child2")
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMappeds");
config.Query = "../Target/DoesNotExist/*";
config.IsRelative = true;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target");
var service = new SitecoreService(database.Database, context);
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service)) as
IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(0, results.Count());
}
}
[Test]
public void MapToProperty_RelativeQuerySelf_ReturnsSelf()
{
//Assign
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbItem("Child1"),
new Sitecore.FakeDb.DbItem("Child2")
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMapped");
config.Query = "ancestor-or-self::*";
config.IsRelative = true;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target");
var service = new SitecoreService(database.Database, context);
//Act
var result =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service)) as StubMapped;
//Assert
Assert.AreEqual(source.ID.Guid, result.Id);
}
}
[Test]
public void MapToProperty_RelativeQuery_ReturnsResults()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbItem("Child1"),
new Sitecore.FakeDb.DbItem("Child2")
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMappeds");
config.Query = "../Target/*";
config.IsRelative = true;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target");
var service = new SitecoreService(database.Database, context);
var result1 = database.GetItem("/sitecore/content/Target/Child1");
var result2 = database.GetItem("/sitecore/content/Target/Child2");
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service)) as
IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(2, results.Count());
Assert.IsTrue(results.Any(x => x.Id == result1.ID.Guid));
Assert.IsTrue(results.Any(x => x.Id == result2.ID.Guid));
}
}
[Test]
public void MapToProperty_AbsoluteQuery_ReturnsResults()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbItem("Child1"),
new Sitecore.FakeDb.DbItem("Child2")
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMappeds");
config.Query = "/sitecore/content/Target/*";
config.IsRelative = false;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target");
var service = new SitecoreService(database.Database, context);
var result1 = database.GetItem("/sitecore/content/Target/Child1");
var result2 = database.GetItem("/sitecore/content/Target/Child2");
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service)) as
IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(2, results.Count());
Assert.IsTrue(results.Any(x => x.Id == result1.ID.Guid));
Assert.IsTrue(results.Any(x => x.Id == result2.ID.Guid));
}
}
[Test]
public void MapToProperty_RelativeQuery_ReturnsSingleResults()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbItem("Child1"),
new Sitecore.FakeDb.DbItem("Child2")
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMapped");
config.Query = "../Target/Child1";
config.IsRelative = true;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target");
var service = new SitecoreService(database.Database, context);
var result1 = database.GetItem("/sitecore/content/Target/Child1");
//Act
var result =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service)) as StubMapped;
//Assert
Assert.AreEqual(result1.ID.Guid, result.Id);
}
}
[Test]
public void MapToProperty_AbsoluteQuery_ReturnsSingleResults()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbItem("Child1"),
new Sitecore.FakeDb.DbItem("Child2")
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMapped");
config.Query = "/sitecore/content/Target/Child1";
config.IsRelative = false;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target");
var service = new SitecoreService(database.Database, context);
var result1 = database.GetItem("/sitecore/content/Target/Child1");
//Act
var result =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service)) as StubMapped;
//Assert
Assert.AreEqual(result1.ID.Guid, result.Id);
}
}
[Test]
public void MapToProperty_RelativeQueryWithQueryContext_ReturnsResults()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbItem("Child1"),
new Sitecore.FakeDb.DbItem("Child2")
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMappeds");
config.Query = "../Target/*";
config.IsRelative = true;
config.UseQueryContext = true;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target");
var service = new SitecoreService(database.Database, context);
var result1 = database.GetItem("/sitecore/content/Target/Child1");
var result2 = database.GetItem("/sitecore/content/Target/Child2");
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service)) as
IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(2, results.Count());
Assert.IsTrue(results.Any(x => x.Id == result1.ID.Guid));
Assert.IsTrue(results.Any(x => x.Id == result2.ID.Guid));
}
}
[Test]
public void MapToProperty_AbsoluteQueryWithQueryContext_ReturnsResults()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbItem("Child1"),
new Sitecore.FakeDb.DbItem("Child2")
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMappeds");
config.Query = "/sitecore/content/Target/*";
config.IsRelative = false;
config.UseQueryContext = true;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target");
var service = new SitecoreService(database.Database, context);
var result1 = database.GetItem("/sitecore/content/Target/Child1");
var result2 = database.GetItem("/sitecore/content/Target/Child2");
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service)) as
IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(2, results.Count());
Assert.IsTrue(results.Any(x => x.Id == result1.ID.Guid));
Assert.IsTrue(results.Any(x => x.Id == result2.ID.Guid));
}
}
[Test]
[Category("LocalOnly")]
public void MapToProperty_AbsoluteQueryWithParameter_ReturnsResults()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbItem("Child1"),
new Sitecore.FakeDb.DbItem("Child2")
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMappeds");
config.Query = "{path}/../Results/*";
config.IsRelative = false;
config.UseQueryContext = true;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(new[] {new ItemPathParameter()});
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target");
var service = new SitecoreService(database.Database, context);
var result1 = database.GetItem("/sitecore/content/Target/Child1");
var result2 = database.GetItem("/sitecore/content/Target/Child2");
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service)) as
IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(2, results.Count());
Assert.IsTrue(results.Any(x => x.Id == result1.ID.Guid));
Assert.IsTrue(results.Any(x => x.Id == result2.ID.Guid));
}
}
#endregion
#region Stubs
[SitecoreType]
public class StubMapped
{
[SitecoreId]
public virtual Guid Id { get; set; }
}
public class StubNotMapped { }
public class StubClass
{
public IEnumerable<StubMapped> StubMappeds { get; set; }
public IEnumerable<StubNotMapped> StubNotMappeds { get; set; }
public StubMapped StubMapped { get; set; }
public StubNotMapped StubNotMapped { get; set; }
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.Network.Fluent;
using Microsoft.Azure.Management.Network.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using Microsoft.Azure.Management.Samples.Common;
using System;
using System.Collections.Generic;
using System.Linq;
namespace ManageInternetFacingLoadBalancer
{
public class Program
{
private static readonly string HttpProbe = "httpProbe";
private static readonly string HttpsProbe = "httpsProbe";
private static readonly string HttpLoadBalancingRule = "httpRule";
private static readonly string HttpsLoadBalancingRule = "httpsRule";
private static readonly string NatRule5000to22forVM1 = "nat5000to22forVM1";
private static readonly string NatRule5001to23forVM1 = "nat5001to23forVM1";
private static readonly string NatRule5002to22forVM2 = "nat5002to22forVM2";
private static readonly string NatRule5003to23forVM2 = "nat5003to23forVM2";
private static readonly string UserName = "tirekicker";
private static readonly string SshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD [email protected]";
/**
* Azure Network sample for managing Internet facing load balancers -
*
* High-level ...
*
* - Create an Internet facing load balancer that receives network traffic on
* port 80 and 443 and sends load-balanced traffic to two virtual machines
*
* - Create NAT rules for SSH and TELNET access to virtual
* machines behind the load balancer
*
* - Create health probes
*
* Details ...
*
* Create an Internet facing load balancer with ...
* - A frontend public IP address
* - Two backend address pools which contain network interfaces for the virtual
* machines to receive HTTP and HTTPS network traffic from the load balancer
* - Two load balancing rules for HTTP and HTTPS to map public ports on the load
* balancer to ports in the backend address pool
* - Two probes which contain HTTP and HTTPS health probes used to check availability
* of virtual machines in the backend address pool
* - Two inbound NAT rules which contain rules that map a public port on the load
* balancer to a port for a specific virtual machine in the backend address pool
* - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23
*
* Create two network interfaces in the frontend subnet ...
* - And associate network interfaces to backend pools and NAT rules
*
* Create two virtual machines in the frontend subnet ...
* - And assign network interfaces
*
* Update an existing load balancer, configure TCP idle timeout
* Create another load balancer
* Remove an existing load balancer
*/
public static void RunSample(IAzure azure)
{
string rgName = SdkContext.RandomResourceName("rgNEML", 15);
string vnetName = SdkContext.RandomResourceName("vnet", 24);
string loadBalancerName1 = SdkContext.RandomResourceName("intlb1" + "-", 18);
string loadBalancerName2 = SdkContext.RandomResourceName("intlb2" + "-", 18);
string publicIpName1 = "pip1-" + loadBalancerName1;
string publicIpName2 = "pip2-" + loadBalancerName1;
string frontendName = loadBalancerName1 + "-FE1";
string backendPoolName1 = loadBalancerName1 + "-BAP1";
string backendPoolName2 = loadBalancerName1 + "-BAP2";
string networkInterfaceName1 = SdkContext.RandomResourceName("nic1", 24);
string networkInterfaceName2 = SdkContext.RandomResourceName("nic2", 24);
string availSetName = SdkContext.RandomResourceName("av", 24);
string vmName1 = SdkContext.RandomResourceName("lVM1", 24);
string vmName2 = SdkContext.RandomResourceName("lVM2", 24);
try
{
//=============================================================
// Create a virtual network with a frontend and a backend subnets
Utilities.Log("Creating virtual network with a frontend and a backend subnets...");
var network = azure.Networks.Define(vnetName)
.WithRegion(Region.USEast)
.WithNewResourceGroup(rgName)
.WithAddressSpace("172.16.0.0/16")
.DefineSubnet("Front-end")
.WithAddressPrefix("172.16.1.0/24")
.Attach()
.DefineSubnet("Back-end")
.WithAddressPrefix("172.16.3.0/24")
.Attach()
.Create();
Utilities.Log("Created a virtual network");
// Print the virtual network details
Utilities.PrintVirtualNetwork(network);
//=============================================================
// Create a public IP address
Utilities.Log("Creating a public IP address...");
var publicIpAddress = azure.PublicIPAddresses.Define(publicIpName1)
.WithRegion(Region.USEast)
.WithExistingResourceGroup(rgName)
.WithLeafDomainLabel(publicIpName1)
.Create();
Utilities.Log("Created a public IP address");
// Print the virtual network details
Utilities.PrintIPAddress(publicIpAddress);
//=============================================================
// Create an Internet facing load balancer
// Create a frontend IP address
// Two backend address pools which contain network interfaces for the virtual
// machines to receive HTTP and HTTPS network traffic from the load balancer
// Two load balancing rules for HTTP and HTTPS to map public ports on the load
// balancer to ports in the backend address pool
// Two probes which contain HTTP and HTTPS health probes used to check availability
// of virtual machines in the backend address pool
// Two inbound NAT rules which contain rules that map a public port on the load
// balancer to a port for a specific virtual machine in the backend address pool
// - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23
Utilities.Log("Creating a Internet facing load balancer with ...");
Utilities.Log("- A frontend IP address");
Utilities.Log("- Two backend address pools which contain network interfaces for the virtual\n"
+ " machines to receive HTTP and HTTPS network traffic from the load balancer");
Utilities.Log("- Two load balancing rules for HTTP and HTTPS to map public ports on the load\n"
+ " balancer to ports in the backend address pool");
Utilities.Log("- Two probes which contain HTTP and HTTPS health probes used to check availability\n"
+ " of virtual machines in the backend address pool");
Utilities.Log("- Two inbound NAT rules which contain rules that map a public port on the load\n"
+ " balancer to a port for a specific virtual machine in the backend address pool\n"
+ " - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23");
var loadBalancer1 = azure.LoadBalancers.Define(loadBalancerName1)
.WithRegion(Region.USEast)
.WithExistingResourceGroup(rgName)
// Add two rules that uses above backend and probe
.DefineLoadBalancingRule(HttpLoadBalancingRule)
.WithProtocol(TransportProtocol.Tcp)
.FromFrontend(frontendName)
.FromFrontendPort(80)
.ToBackend(backendPoolName1)
.WithProbe(HttpProbe)
.Attach()
.DefineLoadBalancingRule(HttpsLoadBalancingRule)
.WithProtocol(TransportProtocol.Tcp)
.FromFrontend(frontendName)
.FromFrontendPort(443)
.ToBackend(backendPoolName2)
.WithProbe(HttpsProbe)
.Attach()
// Add two nat pools to enable direct VM connectivity for
// SSH to port 22 and TELNET to port 23
.DefineInboundNatRule(NatRule5000to22forVM1)
.WithProtocol(TransportProtocol.Tcp)
.FromFrontend(frontendName)
.FromFrontendPort(5000)
.ToBackendPort(22)
.Attach()
.DefineInboundNatRule(NatRule5001to23forVM1)
.WithProtocol(TransportProtocol.Tcp)
.FromFrontend(frontendName)
.FromFrontendPort(5001)
.ToBackendPort(23)
.Attach()
.DefineInboundNatRule(NatRule5002to22forVM2)
.WithProtocol(TransportProtocol.Tcp)
.FromFrontend(frontendName)
.FromFrontendPort(5002)
.ToBackendPort(22)
.Attach()
.DefineInboundNatRule(NatRule5003to23forVM2)
.WithProtocol(TransportProtocol.Tcp)
.FromFrontend(frontendName)
.FromFrontendPort(5003)
.ToBackendPort(23)
.Attach()
// Explicitly define the frontend
.DefinePublicFrontend(frontendName)
.WithExistingPublicIPAddress(publicIpAddress)
.Attach()
// Add two probes one per rule
.DefineHttpProbe(HttpProbe)
.WithRequestPath("/")
.WithPort(80)
.Attach()
.DefineHttpProbe(HttpsProbe)
.WithRequestPath("/")
.WithPort(443)
.Attach()
.Create();
// Print load balancer details
Utilities.Log("Created a load balancer");
Utilities.PrintLoadBalancer(loadBalancer1);
//=============================================================
// Create two network interfaces in the frontend subnet
// associate network interfaces to NAT rules, backend pools
Utilities.Log("Creating two network interfaces in the frontend subnet ...");
Utilities.Log("- And associating network interfaces to backend pools and NAT rules");
var networkInterfaceCreatables = new List<ICreatable<INetworkInterface>>();
ICreatable<INetworkInterface> networkInterface1Creatable;
ICreatable<INetworkInterface> networkInterface2Creatable;
networkInterface1Creatable = azure.NetworkInterfaces.Define(networkInterfaceName1)
.WithRegion(Region.USEast)
.WithNewResourceGroup(rgName)
.WithExistingPrimaryNetwork(network)
.WithSubnet("Front-end")
.WithPrimaryPrivateIPAddressDynamic()
.WithExistingLoadBalancerBackend(loadBalancer1, backendPoolName1)
.WithExistingLoadBalancerBackend(loadBalancer1, backendPoolName2)
.WithExistingLoadBalancerInboundNatRule(loadBalancer1, NatRule5000to22forVM1)
.WithExistingLoadBalancerInboundNatRule(loadBalancer1, NatRule5001to23forVM1);
networkInterfaceCreatables.Add(networkInterface1Creatable);
networkInterface2Creatable = azure.NetworkInterfaces.Define(networkInterfaceName2)
.WithRegion(Region.USEast)
.WithNewResourceGroup(rgName)
.WithExistingPrimaryNetwork(network)
.WithSubnet("Front-end")
.WithPrimaryPrivateIPAddressDynamic()
.WithExistingLoadBalancerBackend(loadBalancer1, backendPoolName1)
.WithExistingLoadBalancerBackend(loadBalancer1, backendPoolName2)
.WithExistingLoadBalancerInboundNatRule(loadBalancer1, NatRule5002to22forVM2)
.WithExistingLoadBalancerInboundNatRule(loadBalancer1, NatRule5003to23forVM2);
networkInterfaceCreatables.Add(networkInterface2Creatable);
var networkInterfaces1 = azure.NetworkInterfaces.Create(networkInterfaceCreatables.ToArray());
// Print network interface details
Utilities.Log("Created two network interfaces");
Utilities.Log("Network Interface ONE -");
Utilities.PrintNetworkInterface(networkInterfaces1.ElementAt(0));
Utilities.Log();
Utilities.Log("Network Interface TWO -");
Utilities.PrintNetworkInterface(networkInterfaces1.ElementAt(1));
//=============================================================
// Create an availability set
Utilities.Log("Creating an availability set ...");
var availSet1 = azure.AvailabilitySets.Define(availSetName)
.WithRegion(Region.USEast)
.WithNewResourceGroup(rgName)
.WithFaultDomainCount(2)
.WithUpdateDomainCount(4)
.Create();
Utilities.Log("Created first availability set: " + availSet1.Id);
Utilities.PrintAvailabilitySet(availSet1);
//=============================================================
// Create two virtual machines and assign network interfaces
Utilities.Log("Creating two virtual machines in the frontend subnet ...");
Utilities.Log("- And assigning network interfaces");
var virtualMachineCreatables1 = new List<ICreatable<IVirtualMachine>>();
ICreatable<IVirtualMachine> virtualMachine1Creatable;
ICreatable<IVirtualMachine> virtualMachine2Creatable;
virtualMachine1Creatable = azure.VirtualMachines.Define(vmName1)
.WithRegion(Region.USEast)
.WithExistingResourceGroup(rgName)
.WithExistingPrimaryNetworkInterface(networkInterfaces1.ElementAt(0))
.WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
.WithRootUsername(UserName)
.WithSsh(SshKey)
.WithSize(VirtualMachineSizeTypes.StandardD3V2)
.WithExistingAvailabilitySet(availSet1);
virtualMachineCreatables1.Add(virtualMachine1Creatable);
virtualMachine2Creatable = azure.VirtualMachines.Define(vmName2)
.WithRegion(Region.USEast)
.WithExistingResourceGroup(rgName)
.WithExistingPrimaryNetworkInterface(networkInterfaces1.ElementAt(1))
.WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
.WithRootUsername(UserName)
.WithSsh(SshKey)
.WithSize(VirtualMachineSizeTypes.StandardD3V2)
.WithExistingAvailabilitySet(availSet1);
virtualMachineCreatables1.Add(virtualMachine2Creatable);
var t1 = DateTime.UtcNow;
var virtualMachines = azure.VirtualMachines.Create(virtualMachineCreatables1.ToArray());
var t2 = DateTime.UtcNow;
Utilities.Log($"Created 2 Linux VMs: (took {(t2 - t1).TotalSeconds} seconds) ");
Utilities.Log();
// Print virtual machine details
Utilities.Log("Virtual Machine ONE -");
Utilities.PrintVirtualMachine(virtualMachines.ElementAt(0));
Utilities.Log();
Utilities.Log("Virtual Machine TWO - ");
Utilities.PrintVirtualMachine(virtualMachines.ElementAt(1));
//=============================================================
// Update a load balancer
// configure TCP idle timeout to 15 minutes
Utilities.Log("Updating the load balancer ...");
loadBalancer1.Update()
.UpdateLoadBalancingRule(HttpLoadBalancingRule)
.WithIdleTimeoutInMinutes(15)
.Parent()
.UpdateLoadBalancingRule(HttpsLoadBalancingRule)
.WithIdleTimeoutInMinutes(15)
.Parent()
.Apply();
Utilities.Log("Update the load balancer with a TCP idle timeout to 15 minutes");
//=============================================================
// Create another public IP address
Utilities.Log("Creating another public IP address...");
var publicIpAddress2 = azure.PublicIPAddresses.Define(publicIpName2)
.WithRegion(Region.USEast)
.WithExistingResourceGroup(rgName)
.WithLeafDomainLabel(publicIpName2)
.Create();
Utilities.Log("Created another public IP address");
// Print the virtual network details
Utilities.PrintIPAddress(publicIpAddress2);
//=============================================================
// Create another Internet facing load balancer
// Create a frontend IP address
// Two backend address pools which contain network interfaces for the virtual
// machines to receive HTTP and HTTPS network traffic from the load balancer
// Two load balancing rules for HTTP and HTTPS to map public ports on the load
// balancer to ports in the backend address pool
// Two probes which contain HTTP and HTTPS health probes used to check availability
// of virtual machines in the backend address pool
// Two inbound NAT rules which contain rules that map a public port on the load
// balancer to a port for a specific virtual machine in the backend address pool
// - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23
Utilities.Log("Creating another Internet facing load balancer with ...");
Utilities.Log("- A frontend IP address");
Utilities.Log("- Two backend address pools which contain network interfaces for the virtual\n"
+ " machines to receive HTTP and HTTPS network traffic from the load balancer");
Utilities.Log("- Two load balancing rules for HTTP and HTTPS to map public ports on the load\n"
+ " balancer to ports in the backend address pool");
Utilities.Log("- Two probes which contain HTTP and HTTPS health probes used to check availability\n"
+ " of virtual machines in the backend address pool");
Utilities.Log("- Two inbound NAT rules which contain rules that map a public port on the load\n"
+ " balancer to a port for a specific virtual machine in the backend address pool\n"
+ " - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23");
var loadBalancer2 = azure.LoadBalancers.Define(loadBalancerName2)
.WithRegion(Region.USEast)
.WithExistingResourceGroup(rgName)
// Add two rules that uses above backend and probe
.DefineLoadBalancingRule(HttpLoadBalancingRule)
.WithProtocol(TransportProtocol.Tcp)
.FromFrontend(frontendName)
.FromFrontendPort(80)
.ToBackend(backendPoolName1)
.WithProbe(HttpProbe)
.Attach()
.DefineLoadBalancingRule(HttpsLoadBalancingRule)
.WithProtocol(TransportProtocol.Tcp)
.FromFrontend(frontendName)
.FromFrontendPort(443)
.ToBackend(backendPoolName2)
.WithProbe(HttpsProbe)
.Attach()
// Add two nat pools to enable direct VM connectivity for
// SSH to port 22 and TELNET to port 23
.DefineInboundNatRule(NatRule5000to22forVM1)
.WithProtocol(TransportProtocol.Tcp)
.FromFrontend(frontendName)
.FromFrontendPort(5000)
.ToBackendPort(22)
.Attach()
.DefineInboundNatRule(NatRule5001to23forVM1)
.WithProtocol(TransportProtocol.Tcp)
.FromFrontend(frontendName)
.FromFrontendPort(5001)
.ToBackendPort(23)
.Attach()
.DefineInboundNatRule(NatRule5002to22forVM2)
.WithProtocol(TransportProtocol.Tcp)
.FromFrontend(frontendName)
.FromFrontendPort(5002)
.ToBackendPort(22)
.Attach()
.DefineInboundNatRule(NatRule5003to23forVM2)
.WithProtocol(TransportProtocol.Tcp)
.FromFrontend(frontendName)
.FromFrontendPort(5003)
.ToBackendPort(23)
.Attach()
// Explicitly define the frontend
.DefinePublicFrontend(frontendName)
.WithExistingPublicIPAddress(publicIpAddress2)
.Attach()
// Add two probes one per rule
.DefineHttpProbe(HttpProbe)
.WithRequestPath("/")
.WithPort(80)
.Attach()
.DefineHttpProbe(HttpsProbe)
.WithRequestPath("/")
.WithPort(443)
.Attach()
.Create();
// Print load balancer details
Utilities.Log("Created another load balancer");
Utilities.PrintLoadBalancer(loadBalancer2);
//=============================================================
// List load balancers
var loadBalancers = azure.LoadBalancers.List();
Utilities.Log("Walking through the list of load balancers");
foreach (var loadBalancer in loadBalancers)
{
Utilities.PrintLoadBalancer(loadBalancer);
}
//=============================================================
// Remove a load balancer
Utilities.Log("Deleting load balancer " + loadBalancerName2
+ "(" + loadBalancer2.Id + ")");
azure.LoadBalancers.DeleteById(loadBalancer2.Id);
Utilities.Log("Deleted load balancer" + loadBalancerName2);
}
finally
{
try
{
Utilities.Log("Deleting Resource Group: " + rgName);
azure.ResourceGroups.DeleteByName(rgName);
Utilities.Log("Deleted Resource Group: " + rgName);
}
catch (NullReferenceException)
{
Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
}
catch (Exception ex)
{
Utilities.Log(ex);
}
}
}
public static void Main(string[] args)
{
try
{
//=================================================================
// Authenticate
var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
// Print selected subscription
Utilities.Log("Selected subscription: " + azure.SubscriptionId);
RunSample(azure);
}
catch (Exception ex)
{
Utilities.Log(ex);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Articles.WebAPI.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Interactivity;
using Avalonia.VisualTree;
namespace Avalonia.Input
{
/// <summary>
/// Handles access keys for a window.
/// </summary>
public class AccessKeyHandler : IAccessKeyHandler
{
/// <summary>
/// Defines the AccessKeyPressed attached event.
/// </summary>
public static readonly RoutedEvent<RoutedEventArgs> AccessKeyPressedEvent =
RoutedEvent.Register<RoutedEventArgs>(
"AccessKeyPressed",
RoutingStrategies.Bubble,
typeof(AccessKeyHandler));
/// <summary>
/// The registered access keys.
/// </summary>
private readonly List<Tuple<string, IInputElement>> _registered = new List<Tuple<string, IInputElement>>();
/// <summary>
/// The window to which the handler belongs.
/// </summary>
private IInputRoot? _owner;
/// <summary>
/// Whether access keys are currently being shown;
/// </summary>
private bool _showingAccessKeys;
/// <summary>
/// Whether to ignore the Alt KeyUp event.
/// </summary>
private bool _ignoreAltUp;
/// <summary>
/// Whether the AltKey is down.
/// </summary>
private bool _altIsDown;
/// <summary>
/// Element to restore following AltKey taking focus.
/// </summary>
private IInputElement? _restoreFocusElement;
/// <summary>
/// The window's main menu.
/// </summary>
private IMainMenu? _mainMenu;
/// <summary>
/// Gets or sets the window's main menu.
/// </summary>
public IMainMenu? MainMenu
{
get => _mainMenu;
set
{
if (_mainMenu != null)
{
_mainMenu.MenuClosed -= MainMenuClosed;
}
_mainMenu = value;
if (_mainMenu != null)
{
_mainMenu.MenuClosed += MainMenuClosed;
}
}
}
/// <summary>
/// Sets the owner of the access key handler.
/// </summary>
/// <param name="owner">The owner.</param>
/// <remarks>
/// This method can only be called once, typically by the owner itself on creation.
/// </remarks>
public void SetOwner(IInputRoot owner)
{
if (_owner != null)
{
throw new InvalidOperationException("AccessKeyHandler owner has already been set.");
}
_owner = owner ?? throw new ArgumentNullException(nameof(owner));
_owner.AddHandler(InputElement.KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
_owner.AddHandler(InputElement.KeyDownEvent, OnKeyDown, RoutingStrategies.Bubble);
_owner.AddHandler(InputElement.KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
_owner.AddHandler(InputElement.PointerPressedEvent, OnPreviewPointerPressed, RoutingStrategies.Tunnel);
}
/// <summary>
/// Registers an input element to be associated with an access key.
/// </summary>
/// <param name="accessKey">The access key.</param>
/// <param name="element">The input element.</param>
public void Register(char accessKey, IInputElement element)
{
var existing = _registered.FirstOrDefault(x => x.Item2 == element);
if (existing != null)
{
_registered.Remove(existing);
}
_registered.Add(Tuple.Create(accessKey.ToString().ToUpper(), element));
}
/// <summary>
/// Unregisters the access keys associated with the input element.
/// </summary>
/// <param name="element">The input element.</param>
public void Unregister(IInputElement element)
{
foreach (var i in _registered.Where(x => x.Item2 == element).ToList())
{
_registered.Remove(i);
}
}
/// <summary>
/// Called when a key is pressed in the owner window.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
protected virtual void OnPreviewKeyDown(object? sender, KeyEventArgs e)
{
if (e.Key == Key.LeftAlt || e.Key == Key.RightAlt)
{
_altIsDown = true;
if (MainMenu == null || !MainMenu.IsOpen)
{
// TODO: Use FocusScopes to store the current element and restore it when context menu is closed.
// Save currently focused input element.
_restoreFocusElement = FocusManager.Instance?.Current;
// When Alt is pressed without a main menu, or with a closed main menu, show
// access key markers in the window (i.e. "_File").
_owner!.ShowAccessKeys = _showingAccessKeys = true;
}
else
{
// If the Alt key is pressed and the main menu is open, close the main menu.
CloseMenu();
_ignoreAltUp = true;
_restoreFocusElement?.Focus();
_restoreFocusElement = null;
e.Handled = true;
}
}
else if (_altIsDown)
{
_ignoreAltUp = true;
}
}
/// <summary>
/// Called when a key is pressed in the owner window.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
protected virtual void OnKeyDown(object? sender, KeyEventArgs e)
{
bool menuIsOpen = MainMenu?.IsOpen == true;
if (e.KeyModifiers.HasAllFlags(KeyModifiers.Alt) || menuIsOpen)
{
// If any other key is pressed with the Alt key held down, or the main menu is open,
// find all controls who have registered that access key.
var text = e.Key.ToString().ToUpper();
var matches = _registered
.Where(x => x.Item1 == text && x.Item2.IsEffectivelyVisible)
.Select(x => x.Item2);
// If the menu is open, only match controls in the menu's visual tree.
if (menuIsOpen)
{
matches = matches.Where(x => x is not null && MainMenu!.IsVisualAncestorOf(x));
}
var match = matches.FirstOrDefault();
// If there was a match, raise the AccessKeyPressed event on it.
if (match != null)
{
match.RaiseEvent(new RoutedEventArgs(AccessKeyPressedEvent));
e.Handled = true;
}
}
}
/// <summary>
/// Handles the Alt/F10 keys being released in the window.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
protected virtual void OnPreviewKeyUp(object? sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.LeftAlt:
case Key.RightAlt:
_altIsDown = false;
if (_ignoreAltUp)
{
_ignoreAltUp = false;
}
else if (_showingAccessKeys && MainMenu != null)
{
MainMenu.Open();
e.Handled = true;
}
break;
}
}
/// <summary>
/// Handles pointer presses in the window.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
protected virtual void OnPreviewPointerPressed(object? sender, PointerEventArgs e)
{
if (_showingAccessKeys)
{
_owner!.ShowAccessKeys = false;
}
}
/// <summary>
/// Closes the <see cref="MainMenu"/> and performs other bookeeping.
/// </summary>
private void CloseMenu()
{
MainMenu!.Close();
_owner!.ShowAccessKeys = _showingAccessKeys = false;
}
private void MainMenuClosed(object? sender, EventArgs e)
{
_owner!.ShowAccessKeys = false;
}
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// 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.IO;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using Sensus.Probes;
using Sensus.Anonymization;
using Sensus.UI.UiProperties;
using Sensus.Probes.Location;
using Sensus.Probes.User.Scripts;
using Sensus.Anonymization.Anonymizers;
using Xamarin.Forms;
using Newtonsoft.Json;
using Sensus.UI.Inputs;
using System.Net;
using System;
using System.Threading.Tasks;
namespace Sensus.UI
{
/// <summary>
/// Displays a single probe.
/// </summary>
public class ProbePage : ContentPage
{
/// <summary>
/// Initializes a new instance of the <see cref="ProbePage"/> class.
/// </summary>
/// <param name="probe">Probe to display.</param>
public ProbePage(Probe probe)
{
Title = "Probe";
StackLayout contentLayout = new StackLayout
{
Orientation = StackOrientation.Vertical,
VerticalOptions = LayoutOptions.FillAndExpand
};
string type = "";
if (probe is ListeningProbe)
{
type = "Listening";
}
else if (probe is PollingProbe)
{
type = "Polling";
}
contentLayout.Children.Add(new ContentView
{
Content = new Label
{
Text = probe.DisplayName + (type == "" ? "" : " (" + type + ")"),
FontSize = 20,
FontAttributes = FontAttributes.Italic,
TextColor = Color.Accent,
HorizontalOptions = LayoutOptions.Center
},
Padding = new Thickness(0, 10, 0, 10)
});
foreach (StackLayout stack in UiProperty.GetPropertyStacks(probe))
{
contentLayout.Children.Add(stack);
}
#region script probes
if (probe is ScriptProbe)
{
ScriptProbe scriptProbe = probe as ScriptProbe;
Button editScriptsButton = new Button
{
Text = "Edit Scripts",
FontSize = 20
};
contentLayout.Children.Add(editScriptsButton);
editScriptsButton.Clicked += async (o, e) =>
{
await Navigation.PushAsync(new ScriptRunnersPage(scriptProbe));
};
Button shareScriptButton = new Button
{
Text = "Share Definition",
FontSize = 20
};
contentLayout.Children.Add(shareScriptButton);
shareScriptButton.Clicked += async (o, e) =>
{
string sharePath = SensusServiceHelper.Get().GetSharePath(".json");
using (StreamWriter shareFile = new StreamWriter(sharePath))
{
shareFile.WriteLine(JsonConvert.SerializeObject(probe, SensusServiceHelper.JSON_SERIALIZER_SETTINGS));
}
await SensusServiceHelper.Get().ShareFileAsync(sharePath, "Probe Definition", "application/json");
};
Button setAgentButton = new Button
{
Text = "Set Agent" + (scriptProbe.Agent == null ? "" : ": " + scriptProbe.Agent.Id),
FontSize = 20,
HorizontalOptions = LayoutOptions.FillAndExpand
};
setAgentButton.Clicked += async (sender, e) =>
{
await SetAgentButton_Clicked(setAgentButton, scriptProbe);
};
contentLayout.Children.Add(setAgentButton);
Button clearAgentButton = new Button
{
Text = "Clear Agent",
FontSize = 20,
HorizontalOptions = LayoutOptions.FillAndExpand
};
clearAgentButton.Clicked += async (sender, e) =>
{
if (scriptProbe.Agent != null)
{
if (await DisplayAlert("Confirm", "Are you sure you wish to clear the survey agent?", "Yes", "No"))
{
scriptProbe.Agent = null;
setAgentButton.Text = "Set Agent";
}
}
await SensusServiceHelper.Get().FlashNotificationAsync("Survey agent cleared.");
};
contentLayout.Children.Add(clearAgentButton);
}
#endregion
#region proximity probe
if (probe is IPointsOfInterestProximityProbe)
{
Button editTriggersButton = new Button
{
Text = "Edit Triggers",
FontSize = 20,
HorizontalOptions = LayoutOptions.FillAndExpand
};
contentLayout.Children.Add(editTriggersButton);
editTriggersButton.Clicked += async (o, e) =>
{
await Navigation.PushAsync(new ProximityTriggersPage(probe as IPointsOfInterestProximityProbe));
};
}
#endregion
#region estimote probe
if (probe is EstimoteBeaconProbe)
{
EstimoteBeaconProbe estimoteBeaconProbe = probe as EstimoteBeaconProbe;
Button editBeaconsButton = new Button
{
Text = "Edit Beacons",
FontSize = 20,
HorizontalOptions = LayoutOptions.FillAndExpand
};
contentLayout.Children.Add(editBeaconsButton);
editBeaconsButton.Clicked += async (sender, e) =>
{
await Navigation.PushAsync(new EstimoteBeaconProbeBeaconsPage(estimoteBeaconProbe));
};
Button setLocationButton = new Button
{
Text = estimoteBeaconProbe.Location == null ? "Set Location" : "Location: " + estimoteBeaconProbe.Location,
FontSize = 20,
HorizontalOptions = LayoutOptions.FillAndExpand
};
contentLayout.Children.Add(setLocationButton);
setLocationButton.Clicked += async (sender, e) =>
{
List<EstimoteLocation> locations;
try
{
locations = await estimoteBeaconProbe.GetLocationsFromCloudAsync(TimeSpan.FromSeconds(10));
if (locations.Count == 0)
{
throw new Exception("No locations present within Estimote Cloud.");
}
}
catch (Exception ex)
{
await SensusServiceHelper.Get().FlashNotificationAsync("Failed to set location: " + ex.Message);
return;
}
List<Input> inputs = await SensusServiceHelper.Get().PromptForInputsAsync("Set Location", new Input[]
{
new ItemPickerDialogInput("Location:", null, locations.Select(location => location.Name + " (" + location.Identifier + ")").ToList())
{
AllowClearSelection = true
}
}, null, true, null, null, null, null, false);
if (inputs == null || inputs[0]?.Value == null)
{
estimoteBeaconProbe.Location = null;
await SensusServiceHelper.Get().FlashNotificationAsync("Location cleared.");
setLocationButton.Text = "Set Location";
}
else
{
try
{
string locationIdentifier = inputs[0].Value.ToString().Split(new char[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)[1];
estimoteBeaconProbe.Location = locations.Single(location => location.Identifier == locationIdentifier);
setLocationButton.Text = "Location: " + estimoteBeaconProbe.Location;
}
catch (Exception)
{
await SensusServiceHelper.Get().FlashNotificationAsync("Failed to set location.");
}
}
};
}
#endregion
#region anonymization
List<PropertyInfo> anonymizableProperties = probe.DatumType.GetProperties().Where(property => property.GetCustomAttribute<Anonymizable>() != null).ToList();
if (anonymizableProperties.Count > 0)
{
contentLayout.Children.Add(new Label
{
Text = "Anonymization",
FontSize = 20,
FontAttributes = FontAttributes.Italic,
TextColor = Color.Accent,
HorizontalOptions = LayoutOptions.Center
});
List<StackLayout> anonymizablePropertyStacks = new List<StackLayout>();
foreach (PropertyInfo anonymizableProperty in anonymizableProperties)
{
Anonymizable anonymizableAttribute = anonymizableProperty.GetCustomAttribute<Anonymizable>(true);
Label propertyLabel = new Label
{
Text = anonymizableAttribute.PropertyDisplayName ?? anonymizableProperty.Name + ":",
FontSize = 20,
HorizontalOptions = LayoutOptions.Start,
VerticalTextAlignment = TextAlignment.Center
};
// populate a picker of anonymizers for the current property
Picker anonymizerPicker = new Picker
{
Title = "Select Anonymizer",
HorizontalOptions = LayoutOptions.FillAndExpand
};
Button configureButton = new Button
{
Text = "Settings",
FontSize = 20
};
// get the current anonymizer for this property
Anonymizer currentAnonymizer = probe.Protocol.JsonAnonymizer.GetAnonymizer(anonymizableProperty);
for (int index = 0; index < anonymizableAttribute.AvailableAnonymizers.Count; index++)
{
if (currentAnonymizer != null && anonymizableAttribute.AvailableAnonymizers[index].GetType() == currentAnonymizer.GetType())
{
anonymizableAttribute.AvailableAnonymizers[index] = currentAnonymizer;
}
}
anonymizerPicker.Items.Add("Do Not Anonymize");
foreach (Anonymizer anonymizer in anonymizableAttribute.AvailableAnonymizers)
{
anonymizerPicker.Items.Add(anonymizer.DisplayText);
}
anonymizerPicker.SelectedIndexChanged += (o, e) =>
{
Anonymizer selectedAnonymizer = null;
if (anonymizerPicker.SelectedIndex > 0)
{
selectedAnonymizer = anonymizableAttribute.AvailableAnonymizers[anonymizerPicker.SelectedIndex - 1]; // subtract one from the selected index since the JsonAnonymizer's collection of anonymizers start after the "None" option within the picker.
configureButton.IsVisible = UiProperty.HasUiProperties(selectedAnonymizer);
}
else
{
configureButton.IsVisible = false;
}
probe.Protocol.JsonAnonymizer.SetAnonymizer(anonymizableProperty, selectedAnonymizer);
};
configureButton.Clicked += async (o, e) =>
{
Anonymizer selectedAnonymizer = anonymizableAttribute.AvailableAnonymizers[anonymizerPicker.SelectedIndex - 1];
await ShowAnonymizerSettings(selectedAnonymizer, anonymizerPicker);
};
// set the picker's index to the current anonymizer (or "Do Not Anonymize" if there is no current)
//Anonymizer currentAnonymizer = probe.Protocol.JsonAnonymizer.GetAnonymizer(anonymizableProperty);
int currentIndex = 0;
if (currentAnonymizer != null)
{
currentIndex = anonymizableAttribute.AvailableAnonymizers.IndexOf(currentAnonymizer) + 1;
}
anonymizerPicker.SelectedIndex = currentIndex;
StackLayout anonymizablePropertyStack = new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { propertyLabel, anonymizerPicker, configureButton }
};
anonymizablePropertyStacks.Add(anonymizablePropertyStack);
}
foreach (StackLayout anonymizablePropertyStack in anonymizablePropertyStacks.OrderBy(s => (s.Children[0] as Label).Text))
{
contentLayout.Children.Add(anonymizablePropertyStack);
}
}
#endregion
Content = new ScrollView
{
Content = contentLayout
};
}
private async Task ShowAnonymizerSettings(Anonymizer selectedAnonymizer, Picker anonymizerPicker)
{
if (selectedAnonymizer != null && UiProperty.HasUiProperties(selectedAnonymizer))
{
AnonymizerPage anonymizerPage = new AnonymizerPage(selectedAnonymizer);
anonymizerPage.Disappearing += (o2, e2) =>
{
if (selectedAnonymizer.IsValid == false)
{
anonymizerPicker.SelectedIndex = 0;
}
};
await Navigation.PushModalAsync(anonymizerPage);
}
}
private async Task SetAgentButton_Clicked(Button setAgentButton, ScriptProbe scriptProbe)
{
List<Input> agentSelectionInputs = new List<Input>();
// show any existing agents
List<IScriptProbeAgent> currentAgents = null;
// android allows us to dynamically load code assemblies, but iOS does not. so, the current approach
// is to only support dynamic loading on android and force compile-time assembly inclusion on ios.
#if __ANDROID__
// try to extract agents from a previously loaded assembly
try
{
currentAgents = ScriptProbe.GetAgents(scriptProbe.AgentAssemblyBytes);
}
catch (Exception)
{ }
#elif __IOS__
currentAgents = ScriptProbe.GetAgents();
// display warning message, as there is no other option to load agents.
if (currentAgents.Count == 0)
{
await SensusServiceHelper.Get().FlashNotificationAsync("No agents available.");
return;
}
#endif
// let the user pick from currently available agents
ItemPickerPageInput currentAgentsPicker = null;
if (currentAgents != null && currentAgents.Count > 0)
{
currentAgentsPicker = new ItemPickerPageInput("Available agent" + (currentAgents.Count > 1 ? "s" : "") + ":", currentAgents.Cast<object>().ToList())
{
Required = false
};
agentSelectionInputs.Add(currentAgentsPicker);
}
#if __ANDROID__
// add option to scan qr code to import a new assembly
QrCodeInput agentAssemblyUrlQrCodeInput = new QrCodeInput(QrCodePrefix.SURVEY_AGENT, "URL:", false, "Agent URL:")
{
Required = false
};
agentSelectionInputs.Add(agentAssemblyUrlQrCodeInput);
#endif
List<Input> completedInputs = await SensusServiceHelper.Get().PromptForInputsAsync("Survey Agent", agentSelectionInputs, null, true, "Set", null, null, null, false);
if (completedInputs == null)
{
return;
}
// check for QR code on android. this doesn't exist on ios.
string agentURL = null;
#if __ANDROID__
agentURL = agentAssemblyUrlQrCodeInput.Value?.ToString();
#endif
// if there is no URL, check if the user has selected an agent.
if (string.IsNullOrWhiteSpace(agentURL))
{
if (currentAgentsPicker != null)
{
IScriptProbeAgent selectedAgent = (currentAgentsPicker.Value as List<object>).FirstOrDefault() as IScriptProbeAgent;
// set the selected agent, watching out for a null (clearing) selection that needs to be confirmed
if (selectedAgent != null || await DisplayAlert("Confirm", "Are you sure you wish to clear the survey agent?", "Yes", "No"))
{
scriptProbe.Agent = selectedAgent;
setAgentButton.Text = "Set Agent" + (scriptProbe.Agent == null ? "" : ": " + scriptProbe.Agent.Id);
if (scriptProbe.Agent == null)
{
await SensusServiceHelper.Get().FlashNotificationAsync("Survey agent cleared.");
}
}
}
}
#if __ANDROID__
else
{
// download agent assembly from scanned QR code
byte[] downloadedBytes = null;
string downloadErrorMessage = null;
try
{
// download the assembly and extract agents
downloadedBytes = scriptProbe.AgentAssemblyBytes = await new WebClient().DownloadDataTaskAsync(new Uri(agentURL));
List<IScriptProbeAgent> qrCodeAgents = ScriptProbe.GetAgents(downloadedBytes);
if (qrCodeAgents.Count == 0)
{
throw new Exception("No agents were present in the specified file.");
}
}
catch (Exception ex)
{
downloadErrorMessage = ex.Message;
}
// if error message is null, then we have 1 or more agents in the downloaded assembly.
if (downloadErrorMessage == null)
{
// redisplay the current input prompt including the agents we just downloaded
scriptProbe.AgentAssemblyBytes = downloadedBytes;
await SetAgentButton_Clicked(setAgentButton, scriptProbe);
}
else
{
SensusServiceHelper.Get().Logger.Log(downloadErrorMessage, LoggingLevel.Normal, typeof(Protocol));
await SensusServiceHelper.Get().FlashNotificationAsync(downloadErrorMessage);
}
}
#endif
}
}
}
| |
//
// HomeView.cs
//
// Authors:
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2009 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.Collections.Generic;
using System.Linq;
using Mono.Unix;
using Gtk;
using Hyena.Collections;
using Hyena.Data.Sqlite;
using Hyena.Data;
using Hyena.Data.Gui;
using Hyena.Widgets;
using Banshee.Base;
using Banshee.Collection;
using Banshee.Collection.Gui;
using Banshee.Collection.Database;
using Banshee.Configuration;
using Banshee.Database;
using Banshee.Gui;
using Banshee.Library;
using Banshee.MediaEngine;
using Banshee.PlaybackController;
using Banshee.Playlist;
using Banshee.Preferences;
using Banshee.ServiceStack;
using Banshee.Sources;
using Banshee.Widgets;
using IA=InternetArchive;
namespace Banshee.InternetArchive
{
public class HomeView : Gtk.HBox, Banshee.Sources.Gui.ISourceContents
{
private HomeSource source;
public HomeView (HomeSource source)
{
this.source = source;
//var sw = new Gtk.ScrolledWindow ();
//sw.BorderWidth = 4;
//sw.AddWithViewport (Build ());
var frame = new Hyena.Widgets.RoundedFrame ();
frame.Child = Build ();
PackStart (frame, true, true, 0);
ShowAll ();
}
private Widget Build ()
{
var hbox = new HBox () { Spacing = 8, BorderWidth = 4 };
hbox.PackStart (BuildTiles (), false, false, 0);
hbox.PackStart (BuildCenter (), true, true, 0);
return hbox;
}
private Widget BuildCenter ()
{
var vbox = new VBox () { Spacing = 2 };
// Search entry/button
var search_box = new HBox () { Spacing = 6, BorderWidth = 4 };
var entry = new SearchEntry () {
Visible = true,
EmptyMessage = String.Format (Catalog.GetString ("Search..."))
};
source.Properties.Set<SearchEntry> ("Nereid.SearchEntry", entry);
// Make the search entry text nice and big
var font = entry.InnerEntry.Style.FontDescription.Copy ();
font.Size = (int) (font.Size * Pango.Scale.XLarge);
entry.InnerEntry.ModifyFont (font);
font.Dispose ();
var button = new Hyena.Widgets.ImageButton (Catalog.GetString ("_Go"), Stock.Find);
entry.Activated += (o, a) => { button.Activate (); };
button.Clicked += (o, a) => source.SetSearch (new SearchDescription (null, entry.Query, IA.Sort.DownloadsDesc, null));
search_box.PackStart (entry, true, true, 0);
search_box.PackStart (button, false, false, 0);
var example_searches = new SearchDescription [] {
new SearchDescription (Catalog.GetString ("Staff Picks"), "pick:1", IA.Sort.WeekDesc, null),
new SearchDescription (Catalog.GetString ("Creative Commons"), "license:creativecommons", IA.Sort.DownloadsDesc, null),
new SearchDescription (Catalog.GetString ("History"), "subject:history", IA.Sort.DownloadsDesc, null),
new SearchDescription (Catalog.GetString ("Classic Cartoons"), "", IA.Sort.DateCreatedAsc, IA.MediaType.Get ("animationandcartoons")),
new SearchDescription (Catalog.GetString ("Speeches"), "subject:speeches OR title:speech", IA.Sort.DownloadsDesc, null),
new SearchDescription (Catalog.GetString ("For Children"), "subject:children", IA.Sort.DownloadsDesc, null),
new SearchDescription (Catalog.GetString ("Poetry"), "subject:poetry", IA.Sort.DownloadsDesc, null),
new SearchDescription (Catalog.GetString ("Creator is United States"), "creator:\"United States\"", IA.Sort.DownloadsDesc, null),
new SearchDescription (Catalog.GetString ("Old Movies"), "", IA.Sort.DateCreatedAsc, IA.MediaType.Get ("moviesandfilms")),
new SearchDescription (Catalog.GetString ("New From LibriVox"), "publisher:LibriVox", IA.Sort.DateAddedDesc, IA.MediaType.Get ("audio")),
new SearchDescription (Catalog.GetString ("Old Texts"), "", IA.Sort.DateCreatedAsc, IA.MediaType.Get ("texts")),
new SearchDescription (Catalog.GetString ("Charlie Chaplin"), "\"Charlie Chaplin\"", IA.Sort.DownloadsDesc, null),
new SearchDescription (Catalog.GetString ("NASA"), "NASA", IA.Sort.DownloadsDesc, null),
new SearchDescription (Catalog.GetString ("Library of Congress"), "creator:\"Library of Congress\"", IA.Sort.DownloadsDesc, null)
};
var examples = new FlowBox () { Spacing = 0 };
examples.Add (PaddingBox (new Label () { Markup = Catalog.GetString ("Examples:") }));
foreach (var search in example_searches) {
var this_search = search;
var link = CreateLink (search.Name, search.Query);
link.TooltipText = search.Query;
link.Clicked += (o, a) => source.SetSearch (this_search);
examples.Add (link);
}
// Intro text and visit button
var intro_label = new Hyena.Widgets.WrapLabel () {
Markup = Catalog.GetString ("The Internet Archive, a 501(c)(3) non-profit, is building a digital library of Internet sites and other cultural artifacts in digital form. Like a paper library, we provide free access to researchers, historians, scholars, and the general public.")
};
var visit_button = new LinkButton ("http://archive.org/", Catalog.GetString ("Visit the Internet Archive online at archive.org"));
visit_button.Clicked += (o, a) => Banshee.Web.Browser.Open ("http://archive.org/");
visit_button.Xalign = 0f;
var visit_box = new HBox ();
visit_box.PackStart (visit_button, false, false, 0);
visit_box.PackStart (new Label () { Visible = true }, true, true, 0);
// Packing
vbox.PackStart (search_box, false, false, 0);
vbox.PackStart (examples, false, false, 0);
vbox.PackStart (PaddingBox (new HSeparator ()), false, false, 6);
vbox.PackStart (PaddingBox (intro_label), false, false, 0);
vbox.PackStart (visit_box, false, false, 0);
return vbox;
}
private Widget PaddingBox (Widget child)
{
var box = new HBox () { BorderWidth = 4 };
box.PackStart (child, true, true, 0);
child.Show ();
box.Show ();
return box;
}
public class FlowBox : VBox
{
private List<HBox> rows = new List<HBox> ();
private List<Widget> children = new List<Widget> ();
private int hspacing;
public int HSpacing {
get { return hspacing; }
set {
hspacing = value;
foreach (var box in rows) {
box.Spacing = hspacing;
}
}
}
public FlowBox ()
{
HSpacing = 2;
Spacing = 2;
bool updating_layout = false;
SizeAllocated += (o, a) => {
if (!updating_layout) {
updating_layout = true;
UpdateLayout ();
updating_layout = false;
}
};
}
public new void Add (Widget widget)
{
children.Add (widget);
UpdateLayout ();
}
private void UpdateLayout ()
{
if (Allocation.Width < 2)
return;
int width = Allocation.Width;
int y = 0;
int x = 0;
int j = 0;
foreach (var widget in children) {
x += widget.Allocation.Width + hspacing;
if (x > width) {
y++;
j = 0;
x = widget.Allocation.Width;
}
Reparent (widget, GetRow (y), j);
j++;
}
for (int i = y + 1; i < rows.Count; i++) {
var row = GetRow (i);
rows.Remove (row);
Remove (row);
}
}
private void Reparent (Widget widget, HBox box, int index)
{
if (widget.Parent == box) {
return;
}
if (widget.Parent == null) {
box.PackStart (widget, false, false, 0);
} else {
widget.Reparent (box);
box.SetChildPacking (widget, false, false, 0, PackType.Start);
}
box.ReorderChild (widget, index);
widget.Show ();
}
private HBox GetRow (int i)
{
if (i < rows.Count) {
return rows[i];
} else {
var box = new HBox () { Spacing = HSpacing };
rows.Add (box);
PackStart (box, false, false, 0);
box.Show ();
return box;
}
}
}
private Button CreateLink (string title, string url)
{
var button = new LinkButton (url, "") {
Relief = ReliefStyle.None,
};
var label = button.Child as Label;
if (label != null) {
label.Markup = title;//"<small>" + title + "</small>";
}
return button;
}
private class Category : SearchDescription
{
public long Count { get; private set; }
public string IconName { get; private set; }
public Category (string media_type, string name, int count, string icon_name)
: this (media_type, name, null, count, icon_name) {}
public Category (string media_type, string name, string query, int count, string icon_name)
: base (name, query, IA.Sort.DownloadsDesc, IA.MediaType.Get (media_type))
{
Count = count;
IconName = icon_name;
}
}
private Widget BuildTiles ()
{
var vbox = new VBox () { Spacing = 12, BorderWidth = 4 };
var categories = new Category [] {
new Category ("audio_bookspoetry", Catalog.GetString ("Audiobooks"), 4300, "audio-x-generic"),
new Category ("movies", Catalog.GetString ("Movies"), 200000, "video-x-generic"),
new Category (null, Catalog.GetString ("Lectures"), "subject:ocw OR creator:university OR mediatype:education OR publisher:University", 1290, "x-office-presentation"),
new Category ("etree", Catalog.GetString ("Concerts"), 69000, "audio-x-generic"),
new Category ("texts", Catalog.GetString ("Books"), 1600000, "x-office-document")
};
foreach (var cat in categories.OrderBy (c => c.Name)) {
var this_cat = cat;
var tile = new ImageButton (cat.Name, cat.IconName) {
InnerPadding = 4
};
tile.LabelWidget.Xalign = 0;
tile.Clicked += (o, a) => source.SetSearch (this_cat);
vbox.PackStart (tile, false, false, 0);
}
return vbox;
}
#region ISourceContents
public bool SetSource (ISource source)
{
this.source = source as HomeSource;
return this.source != null;
}
public void ResetSource ()
{
source = null;
}
public ISource Source { get { return source; } }
public Widget Widget { get { return this; } }
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using TddEbook.TddToolkit.CommonTypes;
using TypeReflection.ImplementationDetails;
using TypeReflection.ImplementationDetails.ConstructorRetrievals;
using TypeReflection.Interfaces;
using static TypeReflection.ImplementationDetails.ConstructorWrapper;
namespace TddEbook.TypeReflection
{
public interface ISmartType : IType, IConstructorQueries
{
}
public class SmartType : ISmartType
{
private readonly Type _type;
private readonly ConstructorRetrieval _constructorRetrieval;
private readonly TypeInfo _typeInfo;
public SmartType(Type type, ConstructorRetrieval constructorRetrieval)
{
_type = type;
_constructorRetrieval = constructorRetrieval;
_typeInfo = _type.GetTypeInfo();
}
public bool HasPublicParameterlessConstructor()
{
return GetPublicParameterlessConstructor().HasValue || _typeInfo.IsPrimitive || _typeInfo.IsAbstract;
}
public Maybe<IConstructorWrapper> GetNonPublicParameterlessConstructorInfo()
{
var constructorInfo = _type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
if (constructorInfo != null)
{
return Maybe.Wrap(DefaultParameterlessConstructor.ForOrdinaryType(constructorInfo));
}
else
{
return Maybe<IConstructorWrapper>.Not;
}
}
public Maybe<IConstructorWrapper> GetPublicParameterlessConstructor()
{
var constructorInfo = _type.GetConstructor(
BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes, null);
if (constructorInfo == null)
{
return Maybe<IConstructorWrapper>.Not;
}
else
{
return Maybe.Wrap(DefaultParameterlessConstructor.ForOrdinaryType(constructorInfo));
}
}
public bool IsImplementationOfOpenGeneric(Type openGenericType)
{
return _typeInfo.GetInterfaces().Any(
ifaceType => IsOpenGeneric(ifaceType, openGenericType));
}
public bool IsOpenGeneric(Type openGenericType)
{
return IsOpenGeneric(_typeInfo, openGenericType);
}
private static bool IsOpenGeneric(Type checkedType, Type openGenericType)
{
return checkedType.GetTypeInfo().IsGenericType &&
checkedType.GetGenericTypeDefinition() == openGenericType;
}
public bool IsConcrete()
{
return !_typeInfo.IsAbstract && !_typeInfo.IsInterface;
}
public IEnumerable<IFieldWrapper> GetAllInstanceFields()
{
var fields = _typeInfo.GetFields(
BindingFlags.Instance
| BindingFlags.Public
| BindingFlags.NonPublic);
return fields.Select(f => new FieldWrapper(f));
}
public IEnumerable<IFieldWrapper> GetAllStaticFields()
{
//bug first convert to field wrappers and then ask questions, not the other way round.
//bug GetAllFields() should return field wrappers
return GetAllFields(_type).Where(fieldInfo =>
fieldInfo.IsStatic &&
!new FieldWrapper(fieldInfo).IsConstant() &&
!IsCompilerGenerated(fieldInfo) &&
!IsDelegate(fieldInfo.FieldType))
.Select(f => new FieldWrapper(f));
}
public IEnumerable<IFieldWrapper> GetAllConstants()
{
return GetAllFields(_type).Select(f => new FieldWrapper(f)).Where(f => f.IsConstant());
}
public IEnumerable<IPropertyWrapper> GetAllPublicInstanceProperties()
{
var properties = _typeInfo.GetProperties(BindingFlags.Instance | BindingFlags.Public);
return properties.Select(p => new PropertyWrapper(p));
}
public Maybe<IConstructorWrapper> PickConstructorWithLeastNonPointersParameters()
{
IConstructorWrapper leastParamsConstructor = null;
var constructors = For(_type).GetAllPublicConstructors();
var numberOfParams = int.MaxValue;
foreach (var typeConstructor in constructors)
{
if (
typeConstructor.HasNonPointerArgumentsOnly()
&& typeConstructor.HasLessParametersThan(numberOfParams))
{
leastParamsConstructor = typeConstructor;
numberOfParams = typeConstructor.GetParametersCount();
}
}
return Maybe.Wrap(leastParamsConstructor);
}
private const string OpEquality = "op_Equality";
private const string OpInequality = "op_Inequality";
private Maybe<MethodInfo> EqualityMethod()
{
var equality = _typeInfo.GetMethod(OpEquality);
return equality == null ? Maybe<MethodInfo>.Not : new Maybe<MethodInfo>(equality);
}
private Maybe<MethodInfo> InequalityMethod()
{
var inequality = _typeInfo.GetMethod(OpInequality);
return inequality == null ? Maybe<MethodInfo>.Not : new Maybe<MethodInfo>(inequality);
}
private Maybe<MethodInfo> ValueTypeEqualityMethod()
{
return _typeInfo.IsValueType ?
Maybe.Wrap(GetType().GetTypeInfo().GetMethod("ValuesEqual"))
: Maybe<MethodInfo>.Not;
}
private Maybe<MethodInfo> ValueTypeInequalityMethod()
{
return _typeInfo.IsValueType ?
Maybe.Wrap(GetType().GetTypeInfo().GetMethod("ValuesNotEqual"))
: Maybe<MethodInfo>.Not;
}
public IBinaryOperator Equality()
{
return BinaryOperator.Wrap(EqualityMethod(), ValueTypeEqualityMethod(), "operator ==");
}
public IBinaryOperator Inequality()
{
return BinaryOperator.Wrap(InequalityMethod(), ValueTypeInequalityMethod(), "operator !=");
}
public static ISmartType For(Type type)
{
return new SmartType(type, new ConstructorRetrievalFactory().Create());
}
public static ISmartType ForTypeOf(object obj)
{
return new SmartType(obj.GetType(), new ConstructorRetrievalFactory().Create());
}
public static bool ValuesEqual(object instance1, object instance2)
{
return Equals(instance1, instance2);
}
public static bool ValuesNotEqual(object instance1, object instance2)
{
return !Equals(instance1, instance2);
}
public bool IsInterface()
{
return _typeInfo.IsInterface;
}
private static bool IsCompilerGenerated(FieldInfo fieldInfo) //?? should it be defined on a type?
{
return fieldInfo.FieldType.GetTypeInfo().IsDefined(typeof(CompilerGeneratedAttribute), false);
}
private static IEnumerable<FieldInfo> GetAllFields(Type type)
{
return type.GetTypeInfo().GetNestedTypes().SelectMany(GetAllFields)
.Concat(type.GetTypeInfo().GetFields(
BindingFlags.Public
| BindingFlags.NonPublic
| BindingFlags.Static
| BindingFlags.DeclaredOnly));
}
private static bool IsDelegate(Type type)
{
return typeof(MulticastDelegate).GetTypeInfo().IsAssignableFrom(
type.GetTypeInfo().BaseType);
}
public IEnumerable<IEventWrapper> GetAllNonPublicEventsWithoutExplicitlyImplemented()
{
return _typeInfo.GetEvents(
BindingFlags.NonPublic
| BindingFlags.Instance
| BindingFlags.DeclaredOnly)
.Where(IsNotExplicitlyImplemented)
.Select(e => new EventWrapper(e));
}
private static bool IsNotExplicitlyImplemented(EventInfo eventInfo)
{
var eventDeclaringType = eventInfo.DeclaringType;
if (eventDeclaringType != null)
{
var interfaces = eventDeclaringType.GetTypeInfo().GetInterfaces();
foreach (var @interface in interfaces)
{
var methodsImplementedInInterface = eventDeclaringType
.GetInterfaceMap(@interface).TargetMethods;
var addMethod = eventInfo.GetAddMethod(true);
if (methodsImplementedInInterface.Where(m => m.IsPrivate).Contains(addMethod))
{
return false;
}
}
}
return true;
}
public IEnumerable<IConstructorWrapper> GetAllPublicConstructors()
{
return _constructorRetrieval.RetrieveFrom(this);
}
public List<IConstructorWrapper> TryToObtainInternalConstructorsWithoutRecursiveArguments()
{
return TryToObtainInternalConstructors().Where(c => c.IsNotRecursive()).ToList();
}
private List<IConstructorWrapper> TryToObtainInternalConstructors()
{
var constructorInfos = _typeInfo.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
var enumerable = constructorInfos.Where(IsInternal);
var wrappers = enumerable.Select(c => (IConstructorWrapper) (FromConstructorInfo(c))).ToList();
return wrappers;
}
public List<ConstructorWrapper> TryToObtainPublicConstructors()
{
return _typeInfo.GetConstructors(BindingFlags.Public | BindingFlags.Instance)
.Select(c => FromConstructorInfo(c)).ToList();
}
public IEnumerable<IConstructorWrapper> TryToObtainPublicConstructorsWithoutRecursiveArguments()
{
return TryToObtainPublicConstructors().Where(c => c.IsNotRecursive());
}
public IEnumerable<IConstructorWrapper> TryToObtainPublicConstructorsWithRecursiveArguments()
{
return TryToObtainPublicConstructors().Where(c => c.IsRecursive());
}
public IEnumerable<IConstructorWrapper> TryToObtainInternalConstructorsWithRecursiveArguments()
{
return TryToObtainInternalConstructors().Where(c => c.IsRecursive()).ToList();
}
public IEnumerable<IConstructorWrapper> TryToObtainPrimitiveTypeConstructor()
{
return DefaultParameterlessConstructor.ForValue(_type);
}
public IEnumerable<IConstructorWrapper> TryToObtainPublicStaticFactoryMethodWithoutRecursion()
{
return _typeInfo.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(m => !m.IsSpecialName)
.Where(IsNotImplicitCast)
.Where(IsNotExplicitCast)
.Select(FromStaticMethodInfo)
.Where(c => c.IsFactoryMethod());
}
public IEnumerable<IFieldWrapper> GetAllPublicInstanceFields()
{
return _typeInfo.GetFields(
BindingFlags.Public | BindingFlags.Instance).Select(f => new FieldWrapper(f));
}
public IEnumerable<IPropertyWrapper> GetPublicInstanceWritableProperties()
{
return _typeInfo.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanWrite)
.Select(p => new PropertyWrapper(p));
}
public IEnumerable<IMethod> GetAllPublicInstanceMethodsWithReturnValue()
{
return _typeInfo.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.ReturnType != typeof(void)).
Select(p => new SmartMethod(p));
}
//TODO even strict mocks can be done this way...
public bool HasConstructorWithParameters()
{
return _typeInfo.IsPrimitive;
}
public bool CanBeAssignedNullValue()
{
return !_typeInfo.IsValueType && !_typeInfo.IsPrimitive;
}
public Type ToClrType()
{
return _type; //todo at the very end, this should be removed
}
public bool IsException()
{
return _type == typeof(Exception) ||
_typeInfo.IsSubclassOf(typeof(Exception));
}
public bool HasPublicConstructorCountOfAtMost(int i)
{
return GetAllPublicConstructors().Count() <= i;
}
private static bool IsNotExplicitCast(MethodInfo mi)
{
return !string.Equals(mi.Name, "op_Explicit", StringComparison.Ordinal);
}
private static bool IsNotImplicitCast(MethodInfo mi)
{
return !string.Equals(mi.Name, "op_Implicit", StringComparison.Ordinal);
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Tests
{
public class BufferedStream_StreamAsync : StreamAsync
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
[Fact]
public async Task ConcurrentOperationsAreSerialized()
{
byte[] data = Enumerable.Range(0, 1000).Select(i => unchecked((byte)i)).ToArray();
var mcaos = new ManuallyReleaseAsyncOperationsStream();
var stream = new BufferedStream(mcaos, 1);
var tasks = new Task[4];
for (int i = 0; i < 4; i++)
{
tasks[i] = stream.WriteAsync(data, 250 * i, 250);
}
Assert.False(tasks.All(t => t.IsCompleted));
mcaos.Release();
await Task.WhenAll(tasks);
stream.Position = 0;
for (int i = 0; i < tasks.Length; i++)
{
Assert.Equal(i, stream.ReadByte());
}
}
[Fact]
public void UnderlyingStreamThrowsExceptions()
{
var stream = new BufferedStream(new ThrowsExceptionFromAsyncOperationsStream());
Assert.Equal(TaskStatus.Faulted, stream.ReadAsync(new byte[1], 0, 1).Status);
Assert.Equal(TaskStatus.Faulted, stream.WriteAsync(new byte[10000], 0, 10000).Status);
stream.WriteByte(1);
Assert.Equal(TaskStatus.Faulted, stream.FlushAsync().Status);
}
[Fact]
public async Task CopyToAsyncTest_RequiresAsyncFlushingOfWrites()
{
byte[] data = Enumerable.Range(0, 1000).Select(i => (byte)(i % 256)).ToArray();
var manualReleaseStream = new ManuallyReleaseAsyncOperationsStream();
var src = new BufferedStream(manualReleaseStream);
src.Write(data, 0, data.Length);
src.Position = 0;
var dst = new MemoryStream();
data[0] = 42;
src.WriteByte(42);
dst.WriteByte(42);
Task copyTask = src.CopyToAsync(dst);
manualReleaseStream.Release();
await copyTask;
Assert.Equal(data, dst.ToArray());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task CopyToAsyncTest_ReadBeforeCopy_CopiesAllData(bool wrappedStreamCanSeek)
{
byte[] data = Enumerable.Range(0, 1000).Select(i => (byte)(i % 256)).ToArray();
var wrapped = new ManuallyReleaseAsyncOperationsStream();
wrapped.Release();
wrapped.Write(data, 0, data.Length);
wrapped.Position = 0;
wrapped.SetCanSeek(wrappedStreamCanSeek);
var src = new BufferedStream(wrapped, 100);
src.ReadByte();
var dst = new MemoryStream();
await src.CopyToAsync(dst);
var expected = new byte[data.Length - 1];
Array.Copy(data, 1, expected, 0, expected.Length);
Assert.Equal(expected, dst.ToArray());
}
}
public class BufferedStream_StreamMethods : StreamMethods
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
protected override Stream CreateStream(int bufferSize)
{
return new BufferedStream(new MemoryStream(), bufferSize);
}
}
public class BufferedStream_TestLeaveOpen : TestLeaveOpen
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
}
public class StreamWriterWithBufferedStream_CloseTests : CloseTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
}
public class StreamWriterWithBufferedStream_FlushTests : FlushTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
[Fact]
public void WriteAfterRead_NonSeekableStream_Throws()
{
var wrapped = new WrappedMemoryStream(canRead: true, canWrite: true, canSeek: false, data: new byte[] { 1, 2, 3, 4, 5 });
var s = new BufferedStream(wrapped);
s.Read(new byte[3], 0, 3);
Assert.Throws<NotSupportedException>(() => s.Write(new byte[10], 0, 10));
}
}
public class StreamWriterWithBufferedStream_WriteTests : WriteTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
}
public class StreamReaderWithBufferedStream_Tests : StreamReaderTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
protected override Stream GetSmallStream()
{
byte[] testData = new byte[] { 72, 69, 76, 76, 79 };
return new BufferedStream(new MemoryStream(testData));
}
protected override Stream GetLargeStream()
{
byte[] testData = new byte[] { 72, 69, 76, 76, 79 };
List<byte> data = new List<byte>();
for (int i = 0; i < 1000; i++)
{
data.AddRange(testData);
}
return new BufferedStream(new MemoryStream(data.ToArray()));
}
}
public class BinaryWriterWithBufferedStream_Tests : BinaryWriterTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
[Fact]
public override void BinaryWriter_FlushTests()
{
// [] Check that flush updates the underlying stream
using (Stream memstr2 = CreateStream())
using (BinaryWriter bw2 = new BinaryWriter(memstr2))
{
string str = "HelloWorld";
int expectedLength = str.Length + 1; // 1 for 7-bit encoded length
bw2.Write(str);
Assert.Equal(expectedLength, memstr2.Length);
bw2.Flush();
Assert.Equal(expectedLength, memstr2.Length);
}
// [] Flushing a closed writer may throw an exception depending on the underlying stream
using (Stream memstr2 = CreateStream())
{
BinaryWriter bw2 = new BinaryWriter(memstr2);
bw2.Dispose();
Assert.Throws<ObjectDisposedException>(() => bw2.Flush());
}
}
}
public class BinaryWriterWithBufferedStream_WriteByteCharTests : BinaryWriter_WriteByteCharTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
}
public class BinaryWriterWithBufferedStream_WriteTests : BinaryWriter_WriteTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
}
internal sealed class ManuallyReleaseAsyncOperationsStream : MemoryStream
{
private readonly TaskCompletionSource<bool> _tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
private bool _canSeek = true;
public override bool CanSeek => _canSeek;
public void SetCanSeek(bool canSeek) => _canSeek = canSeek;
public void Release() { _tcs.SetResult(true); }
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await _tcs.Task;
return await base.ReadAsync(buffer, offset, count, cancellationToken);
}
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await _tcs.Task;
await base.WriteAsync(buffer, offset, count, cancellationToken);
}
public override async Task FlushAsync(CancellationToken cancellationToken)
{
await _tcs.Task;
await base.FlushAsync(cancellationToken);
}
}
internal sealed class ThrowsExceptionFromAsyncOperationsStream : MemoryStream
{
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
throw new InvalidOperationException("Exception from ReadAsync");
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
throw new InvalidOperationException("Exception from WriteAsync");
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
throw new InvalidOperationException("Exception from FlushAsync");
}
}
public class BufferedStream_NS17
{
protected Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
public void EndCallback(IAsyncResult ar)
{ }
[Fact]
public void BeginEndReadTest()
{
Stream stream = CreateStream();
IAsyncResult result = stream.BeginRead(new byte[1], 0, 1, new AsyncCallback(EndCallback), new object());
stream.EndRead(result);
}
[Fact]
public void BeginEndWriteTest()
{
Stream stream = CreateStream();
IAsyncResult result = stream.BeginWrite(new byte[1], 0, 1, new AsyncCallback(EndCallback), new object());
stream.EndWrite(result);
}
}
}
| |
#pragma warning disable 618, CA1001
// ReSharper disable once CheckNamespace
namespace ControlzEx.Behaviors
{
using System;
using System.Collections.Generic;
using System.Security;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Threading;
using ControlzEx;
using ControlzEx.Internal;
using ControlzEx.Internal.KnownBoxes;
using ControlzEx.Native;
using global::Windows.Win32;
using global::Windows.Win32.Foundation;
using global::Windows.Win32.Graphics.Dwm;
using global::Windows.Win32.Graphics.Gdi;
using global::Windows.Win32.UI.WindowsAndMessaging;
using Microsoft.Xaml.Behaviors;
public enum WindowCornerPreference
{
/// <summary>
/// Use the windows default.
/// </summary>
Default = DWM_WINDOW_CORNER_PREFERENCE.DWMWCP_DEFAULT,
/// <summary>
/// Do NOT round window corners.
/// </summary>
DoNotRound = DWM_WINDOW_CORNER_PREFERENCE.DWMWCP_DONOTROUND,
/// <summary>
/// Round window corners.
/// </summary>
Round = DWM_WINDOW_CORNER_PREFERENCE.DWMWCP_ROUND,
/// <summary>
/// Round window corners with small radius.
/// </summary>
RoundSmall = DWM_WINDOW_CORNER_PREFERENCE.DWMWCP_ROUNDSMALL,
}
/// <summary>
/// With this class we can make custom window styles.
/// </summary>
public partial class WindowChromeBehavior : Behavior<Window>
{
/// <summary>Underlying HWND for the _window.</summary>
/// <SecurityNote>
/// Critical : Critical member
/// </SecurityNote>
[SecurityCritical]
private HWND windowHandle;
/// <summary>Underlying HWND for the _window.</summary>
/// <SecurityNote>
/// Critical : Critical member provides access to HWND's window messages which are critical
/// </SecurityNote>
[SecurityCritical]
private HwndSource? hwndSource;
private PropertyChangeNotifier? borderThicknessChangeNotifier;
private Thickness? savedBorderThickness;
private bool isCleanedUp;
private readonly Thickness cornerGripThickness = new(Constants.ResizeCornerGripThickness);
private struct SystemParameterBoundProperty
{
public string SystemParameterPropertyName { get; set; }
public DependencyProperty DependencyProperty { get; set; }
}
/// <summary>
/// Mirror property for <see cref="ResizeBorderThickness"/>.
/// </summary>
public Thickness ResizeBorderThickness
{
get { return (Thickness)this.GetValue(ResizeBorderThicknessProperty); }
set { this.SetValue(ResizeBorderThicknessProperty, value); }
}
/// <summary>Identifies the <see cref="ResizeBorderThickness"/> dependency property.</summary>
public static readonly DependencyProperty ResizeBorderThicknessProperty =
DependencyProperty.Register(nameof(ResizeBorderThickness), typeof(Thickness), typeof(WindowChromeBehavior), new PropertyMetadata(GetDefaultResizeBorderThickness(), OnResizeBorderThicknessChanged), (value) => ((Thickness)value).IsNonNegative());
private static void OnResizeBorderThicknessChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var behavior = (WindowChromeBehavior)d;
behavior._OnChromePropertyChangedThatRequiresRepaint();
}
/// <summary>
/// Defines if the Taskbar should be ignored when maximizing a Window.
/// This only works with WindowStyle = None.
/// </summary>
public bool IgnoreTaskbarOnMaximize
{
get { return (bool)this.GetValue(IgnoreTaskbarOnMaximizeProperty); }
set { this.SetValue(IgnoreTaskbarOnMaximizeProperty, BooleanBoxes.Box(value)); }
}
/// <summary>
/// <see cref="DependencyProperty"/> for <see cref="IgnoreTaskbarOnMaximize"/>.
/// </summary>
public static readonly DependencyProperty IgnoreTaskbarOnMaximizeProperty =
DependencyProperty.Register(nameof(IgnoreTaskbarOnMaximize), typeof(bool), typeof(WindowChromeBehavior), new PropertyMetadata(BooleanBoxes.FalseBox, OnIgnoreTaskbarOnMaximizeChanged));
/// <summary>
/// Gets/sets if the border thickness value should be kept on maximize
/// if the MaxHeight/MaxWidth of the window is less than the monitor resolution.
/// </summary>
public bool KeepBorderOnMaximize
{
get { return (bool)this.GetValue(KeepBorderOnMaximizeProperty); }
set { this.SetValue(KeepBorderOnMaximizeProperty, BooleanBoxes.Box(value)); }
}
/// <summary>
/// <see cref="DependencyProperty"/> for <see cref="KeepBorderOnMaximize"/>.
/// </summary>
public static readonly DependencyProperty KeepBorderOnMaximizeProperty = DependencyProperty.Register(nameof(KeepBorderOnMaximize), typeof(bool), typeof(WindowChromeBehavior), new PropertyMetadata(BooleanBoxes.TrueBox, OnKeepBorderOnMaximizeChanged));
private static readonly DependencyPropertyKey IsNCActivePropertyKey = DependencyProperty.RegisterReadOnly(nameof(IsNCActive), typeof(bool), typeof(WindowChromeBehavior), new PropertyMetadata(BooleanBoxes.FalseBox));
/// <summary>
/// <see cref="DependencyProperty"/> for <see cref="IsNCActive"/>.
/// </summary>
public static readonly DependencyProperty IsNCActiveProperty = IsNCActivePropertyKey.DependencyProperty;
/// <summary>
/// Gets whether the non-client area is active or not.
/// </summary>
public bool IsNCActive
{
get { return (bool)this.GetValue(IsNCActiveProperty); }
private set { this.SetValue(IsNCActivePropertyKey, BooleanBoxes.Box(value)); }
}
public static readonly DependencyProperty EnableMinimizeProperty = DependencyProperty.Register(nameof(EnableMinimize), typeof(bool), typeof(WindowChromeBehavior), new PropertyMetadata(BooleanBoxes.TrueBox, OnEnableMinimizeChanged));
private static void OnEnableMinimizeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue != e.OldValue && e.NewValue is bool showMinButton)
{
var behavior = (WindowChromeBehavior)d;
behavior.UpdateMinimizeSystemMenu(showMinButton);
}
}
private void UpdateMinimizeSystemMenu(bool isVisible)
{
if (this.windowHandle == IntPtr.Zero)
{
return;
}
if (this.hwndSource?.IsDisposed == true)
{
return;
}
if (isVisible)
{
this._ModifyStyle(0, WINDOW_STYLE.WS_MINIMIZEBOX);
}
else
{
this._ModifyStyle(WINDOW_STYLE.WS_MINIMIZEBOX, 0);
}
this._UpdateSystemMenu(this.AssociatedObject?.WindowState);
}
/// <summary>
/// Gets or sets whether if the minimize button is visible and the minimize system menu is enabled.
/// </summary>
public bool EnableMinimize
{
get { return (bool)this.GetValue(EnableMinimizeProperty); }
set { this.SetValue(EnableMinimizeProperty, BooleanBoxes.Box(value)); }
}
public static readonly DependencyProperty EnableMaxRestoreProperty = DependencyProperty.Register(nameof(EnableMaxRestore), typeof(bool), typeof(WindowChromeBehavior), new PropertyMetadata(BooleanBoxes.TrueBox, OnEnableMaxRestoreChanged));
private static void OnEnableMaxRestoreChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue != e.OldValue && e.NewValue is bool showMaxRestoreButton)
{
var behavior = (WindowChromeBehavior)d;
behavior.UpdateMaxRestoreSystemMenu(showMaxRestoreButton);
}
}
private void UpdateMaxRestoreSystemMenu(bool isVisible)
{
if (this.windowHandle == IntPtr.Zero)
{
return;
}
if (this.hwndSource?.IsDisposed == true)
{
return;
}
if (isVisible)
{
this._ModifyStyle(0, WINDOW_STYLE.WS_MAXIMIZEBOX);
}
else
{
this._ModifyStyle(WINDOW_STYLE.WS_MAXIMIZEBOX, 0);
}
this._UpdateSystemMenu(this.AssociatedObject?.WindowState);
}
/// <summary>
/// Gets or sets whether if the maximize/restore button is visible and the maximize/restore system menu is enabled.
/// </summary>
public bool EnableMaxRestore
{
get { return (bool)this.GetValue(EnableMaxRestoreProperty); }
set { this.SetValue(EnableMaxRestoreProperty, BooleanBoxes.Box(value)); }
}
public static readonly DependencyProperty CornerPreferenceProperty =
DependencyProperty.Register(nameof(CornerPreference), typeof(WindowCornerPreference), typeof(WindowChromeBehavior), new PropertyMetadata(WindowCornerPreference.Default, OnCornerPreferenceChanged));
public WindowCornerPreference CornerPreference
{
get => (WindowCornerPreference)this.GetValue(CornerPreferenceProperty);
set => this.SetValue(CornerPreferenceProperty, value);
}
private static void OnCornerPreferenceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var behavior = (WindowChromeBehavior)d;
behavior.UpdateDWMCornerPreference((WindowCornerPreference)e.NewValue);
}
/// <inheritdoc />
protected override void OnAttached()
{
base.OnAttached();
// no transparency, because it has more then one unwanted issues
if (this.AssociatedObject.AllowsTransparency)
{
try
{
this.AssociatedObject.SetCurrentValue(Window.AllowsTransparencyProperty, BooleanBoxes.FalseBox);
}
catch (Exception)
{
//For some reason, we can't determine if the window has loaded or not, so we swallow the exception.
}
}
this.savedBorderThickness = this.AssociatedObject.BorderThickness;
this.borderThicknessChangeNotifier = new PropertyChangeNotifier(this.AssociatedObject, Control.BorderThicknessProperty);
this.borderThicknessChangeNotifier.ValueChanged += this.BorderThicknessChangeNotifierOnValueChanged;
this.AssociatedObject.Closed += this.AssociatedObject_Closed;
this.AssociatedObject.StateChanged += this.AssociatedObject_StateChanged;
this.Initialize();
}
/// <summary>
/// Gets the default resize border thickness from the system parameters.
/// </summary>
public static Thickness GetDefaultResizeBorderThickness()
{
var dpiX = PInvoke.GetDeviceCaps(PInvoke.GetDC(default), GET_DEVICE_CAPS_INDEX.LOGPIXELSX);
var dpiY = PInvoke.GetDeviceCaps(PInvoke.GetDC(default), GET_DEVICE_CAPS_INDEX.LOGPIXELSY);
var xframe = PInvoke.GetSystemMetrics(SYSTEM_METRICS_INDEX.SM_CXFRAME);
var yframe = PInvoke.GetSystemMetrics(SYSTEM_METRICS_INDEX.SM_CYFRAME);
var padding = PInvoke.GetSystemMetrics(SYSTEM_METRICS_INDEX.SM_CXPADDEDBORDER);
xframe += padding;
yframe += padding;
var logical = DpiHelper.DeviceSizeToLogical(new Size(xframe, yframe), dpiX / 96.0, dpiY / 96.0);
return new Thickness(logical.Width, logical.Height, logical.Width, logical.Height);
}
private void BorderThicknessChangeNotifierOnValueChanged(object? sender, EventArgs e)
{
// It's bad if the window is null at this point, but we check this here to prevent the possible occurred exception
var window = this.AssociatedObject;
if (window is not null)
{
this.savedBorderThickness = window.BorderThickness;
}
}
private static void OnIgnoreTaskbarOnMaximizeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var behavior = (WindowChromeBehavior)d;
// A few things to consider when removing the below hack
// - ResizeMode="NoResize"
// WindowState="Maximized"
// IgnoreTaskbarOnMaximize="True"
// - Changing IgnoreTaskbarOnMaximize while window is maximized
// Changing the WindowState solves all, known, issues with changing IgnoreTaskbarOnMaximize.
// Since IgnoreTaskbarOnMaximize is not changed all the time this hack seems to be less risky than anything else.
if (behavior.AssociatedObject?.WindowState == WindowState.Maximized)
{
behavior._OnChromePropertyChangedThatRequiresRepaint();
behavior.AssociatedObject.SetCurrentValue(Window.WindowStateProperty, WindowState.Normal);
behavior.AssociatedObject.SetCurrentValue(Window.WindowStateProperty, WindowState.Maximized);
}
}
private static void OnKeepBorderOnMaximizeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var behavior = (WindowChromeBehavior)d;
behavior.HandleStateChanged();
}
[SecuritySafeCritical]
private void Cleanup(bool isClosing)
{
if (this.isCleanedUp)
{
return;
}
this.isCleanedUp = true;
this.OnCleanup();
// clean up events
this.AssociatedObject.Closed -= this.AssociatedObject_Closed;
this.AssociatedObject.StateChanged -= this.AssociatedObject_StateChanged;
this.hwndSource?.RemoveHook(this.WindowProc);
}
/// <summary>
/// Occurs during the cleanup of this behavior.
/// </summary>
protected virtual void OnCleanup()
{
// nothing here
}
/// <inheritdoc />
protected override void OnDetaching()
{
this.Cleanup(false);
base.OnDetaching();
}
private void Initialize()
{
this.windowHandle = new(new WindowInteropHelper(this.AssociatedObject).EnsureHandle());
this.nonClientControlManager = new NonClientControlManager(this.AssociatedObject);
if (this.windowHandle == IntPtr.Zero)
{
throw new Exception("Uups, at this point we really need the Handle from the associated object!");
}
if (this.AssociatedObject.SizeToContent != SizeToContent.Manual
&& this.AssociatedObject.WindowState == WindowState.Normal)
{
// Another try to fix SizeToContent
// without this we get nasty glitches at the borders
Invoke(this.AssociatedObject, () =>
{
this.AssociatedObject.InvalidateMeasure();
});
}
this.hwndSource = HwndSource.FromHwnd(this.windowHandle);
this.hwndSource?.AddHook(this.WindowProc);
this._ApplyNewCustomChrome();
// handle the maximized state here too (to handle the border in a correct way)
this.HandleStateChanged();
}
private void AssociatedObject_Closed(object? sender, EventArgs e)
{
this.Cleanup(true);
}
private void AssociatedObject_StateChanged(object? sender, EventArgs e)
{
this.HandleStateChanged();
}
private void HandleStateChanged()
{
this.HandleBorderThicknessDuringMaximize();
if (this.AssociatedObject.WindowState == WindowState.Maximized)
{
// Workaround for:
// MaxWidth="someValue"
// SizeToContent = "WidthAndHeight"
// Dragging the window to the top with those things set does not change the height of the Window
if (this.AssociatedObject.SizeToContent != SizeToContent.Manual)
{
this.AssociatedObject.SetCurrentValue(Window.SizeToContentProperty, SizeToContent.Manual);
}
}
else if (this.AssociatedObject.WindowState == WindowState.Normal
&& this.IgnoreTaskbarOnMaximize)
{
// Required to fix wrong NC area rendering.
this.ForceNativeWindowRedraw();
}
}
private void ForceNativeWindowRedraw()
{
if (this.windowHandle == IntPtr.Zero
|| this.hwndSource is null
|| this.hwndSource.IsDisposed)
{
return;
}
PInvoke.SetWindowPos(this.windowHandle, default, 0, 0, 0, 0, SwpFlags);
}
/// <summary>
/// This fix is needed because style triggers don't work if someone sets the value locally/directly on the window.
/// </summary>
private void HandleBorderThicknessDuringMaximize()
{
this.borderThicknessChangeNotifier!.RaiseValueChanged = false;
if (this.AssociatedObject.WindowState == WindowState.Maximized)
{
var monitor = IntPtr.Zero;
if (this.windowHandle != IntPtr.Zero)
{
monitor = PInvoke.MonitorFromWindow(this.windowHandle, MONITOR_FROM_FLAGS.MONITOR_DEFAULTTONEAREST);
}
if (monitor != IntPtr.Zero)
{
var rightBorderThickness = 0D;
var bottomBorderThickness = 0D;
if (this.KeepBorderOnMaximize
&& this.savedBorderThickness.HasValue)
{
var monitorInfo = PInvoke.GetMonitorInfo(monitor);
var monitorRect = this.IgnoreTaskbarOnMaximize ? monitorInfo.rcMonitor : monitorInfo.rcWork;
// If the maximized window will have a width less than the monitor size, show the right border.
if (this.AssociatedObject.MaxWidth < monitorRect.GetWidth())
{
rightBorderThickness = this.savedBorderThickness.Value.Right;
}
// If the maximized window will have a height less than the monitor size, show the bottom border.
if (this.AssociatedObject.MaxHeight < monitorRect.GetHeight())
{
bottomBorderThickness = this.savedBorderThickness.Value.Bottom;
}
}
// set window border, so we can move the window from top monitor position
this.AssociatedObject.SetCurrentValue(Control.BorderThicknessProperty, new Thickness(0, 0, rightBorderThickness, bottomBorderThickness));
}
else // Can't get monitor info, so just remove all border thickness
{
this.AssociatedObject.SetCurrentValue(Control.BorderThicknessProperty, new Thickness(0));
}
}
else
{
this.AssociatedObject.SetCurrentValue(Control.BorderThicknessProperty, this.savedBorderThickness.GetValueOrDefault(new Thickness(0)));
}
this.borderThicknessChangeNotifier.RaiseValueChanged = true;
}
private bool UpdateDWMCornerPreference(WindowCornerPreference cornerPreference)
{
return this.UpdateDWMCornerPreference((DWM_WINDOW_CORNER_PREFERENCE)cornerPreference);
}
private bool UpdateDWMCornerPreference(DWM_WINDOW_CORNER_PREFERENCE cornerPreference)
{
if (this.windowHandle == IntPtr.Zero)
{
return false;
}
return DwmHelper.SetWindowAttributeValue(this.windowHandle, DWMWINDOWATTRIBUTE.DWMWA_WINDOW_CORNER_PREFERENCE, (int)cornerPreference);
}
private static void Invoke(DispatcherObject dispatcherObject, Action invokeAction)
{
if (dispatcherObject is null)
{
throw new ArgumentNullException(nameof(dispatcherObject));
}
if (invokeAction is null)
{
throw new ArgumentNullException(nameof(invokeAction));
}
if (dispatcherObject.Dispatcher.CheckAccess())
{
invokeAction();
}
else
{
dispatcherObject.Dispatcher.Invoke(invokeAction);
}
}
private static readonly List<SystemParameterBoundProperty> boundProperties = new()
{
new SystemParameterBoundProperty { DependencyProperty = ResizeBorderThicknessProperty, SystemParameterPropertyName = nameof(SystemParameters.WindowResizeBorderThickness) },
};
}
}
| |
// 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.Text;
namespace System.Text.Encodings.Web.Utf8
{
public class UrlEncoder
{
static bool[] IsAllowed = new bool[0x7F + 1];
[Obsolete("Use UrlEncoder.Utf8.Encode")]
public static bool TryEncode(ReadOnlySpan<byte> input, Span<byte> output, out int written)
{
written = 0;
for (int inputIndex = 0; inputIndex < input.Length; inputIndex++)
{
var next = input[inputIndex];
if(next > 0x7F)
{
throw new NotImplementedException();
}
if(written >= output.Length)
{
written = 0;
return false;
}
if (IsAllowed[next])
{
output[written++] = input[inputIndex];
}
else
{
output[written++] = (byte)'%';
if(!Utf8Formatter.TryFormat(next, output.Slice(written), out int formatted, 'X'))
{
written = 0;
return false;
}
written += formatted;
}
}
return true;
}
/// <summary>
/// Unescape a URL path
/// </summary>
/// <param name="source">The byte span represents a UTF8 encoding url path.</param>
/// <param name="destination">The byte span where unescaped url path is copied to.</param>
/// <returns>The length of the byte sequence of the unescaped url path.</returns>
[Obsolete("Use UrlDecoder.Utf8.Decode")]
public static int Decode(ReadOnlySpan<byte> source, Span<byte> destination)
{
if (destination.Length < source.Length)
{
throw new ArgumentException(
"Lenghth of the destination byte span is less then the source.",
nameof(destination));
}
// This requires the destination span to be larger or equal to source span
source.CopyTo(destination);
return DecodeInPlace(destination);
}
/// <summary>
/// Unescape a URL path in place.
/// </summary>
/// <param name="buffer">The byte span represents a UTF8 encoding url path.</param>
/// <returns>The number of the bytes representing the result.</returns>
/// <remarks>
/// The unescape is done in place, which means after decoding the result is the subset of
/// the input span.
/// </remarks>
[Obsolete("Use UrlDecoder.Utf8.DecodeInPlace")]
public static int DecodeInPlace(Span<byte> buffer)
{
// the slot to read the input
var sourceIndex = 0;
// the slot to write the unescaped byte
var destinationIndex = 0;
while (true)
{
if (sourceIndex == buffer.Length)
{
break;
}
if (buffer[sourceIndex] == '%')
{
var decodeIndex = sourceIndex;
// If decoding process succeeds, the writer iterator will be moved
// to the next write-ready location. On the other hand if the scanned
// percent-encodings cannot be interpreted as sequence of UTF-8 octets,
// these bytes should be copied to output as is.
// The decodeReader iterator is always moved to the first byte not yet
// be scanned after the process. A failed decoding means the chars
// between the reader and decodeReader can be copied to output untouched.
if (!DecodeCore(ref decodeIndex, ref destinationIndex, buffer))
{
Copy(sourceIndex, decodeIndex, ref destinationIndex, buffer);
}
sourceIndex = decodeIndex;
}
else
{
buffer[destinationIndex++] = buffer[sourceIndex++];
}
}
return destinationIndex;
}
/// <summary>
/// Unescape the percent-encodings
/// </summary>
/// <param name="sourceIndex">The iterator point to the first % char</param>
/// <param name="destinationIndex">The place to write to</param>
/// <param name="end">The end of the buffer</param>
/// <param name="buffer">The byte array</param>
private static bool DecodeCore(ref int sourceIndex, ref int destinationIndex, Span<byte> buffer)
{
// preserves the original head. if the percent-encodings cannot be interpreted as sequence of UTF-8 octets,
// bytes from this till the last scanned one will be copied to the memory pointed by writer.
var byte1 = UnescapePercentEncoding(ref sourceIndex, buffer);
if (byte1 == -1)
{
return false;
}
if (byte1 == 0)
{
throw new InvalidOperationException("The path contains null characters.");
}
if (byte1 <= 0x7F)
{
// first byte < U+007f, it is a single byte ASCII
buffer[destinationIndex++] = (byte)byte1;
return true;
}
int byte2 = 0, byte3 = 0, byte4 = 0;
// anticipate more bytes
var currentDecodeBits = 0;
var byteCount = 1;
var expectValueMin = 0;
if ((byte1 & 0xE0) == 0xC0)
{
// 110x xxxx, expect one more byte
currentDecodeBits = byte1 & 0x1F;
byteCount = 2;
expectValueMin = 0x80;
}
else if ((byte1 & 0xF0) == 0xE0)
{
// 1110 xxxx, expect two more bytes
currentDecodeBits = byte1 & 0x0F;
byteCount = 3;
expectValueMin = 0x800;
}
else if ((byte1 & 0xF8) == 0xF0)
{
// 1111 0xxx, expect three more bytes
currentDecodeBits = byte1 & 0x07;
byteCount = 4;
expectValueMin = 0x10000;
}
else
{
// invalid first byte
return false;
}
var remainingBytes = byteCount - 1;
while (remainingBytes > 0)
{
// read following three chars
if (sourceIndex == buffer.Length)
{
return false;
}
var nextSourceIndex = sourceIndex;
var nextByte = UnescapePercentEncoding(ref nextSourceIndex, buffer);
if (nextByte == -1)
{
return false;
}
if ((nextByte & 0xC0) != 0x80)
{
// the follow up byte is not in form of 10xx xxxx
return false;
}
currentDecodeBits = (currentDecodeBits << 6) | (nextByte & 0x3F);
remainingBytes--;
if (remainingBytes == 1 && currentDecodeBits >= 0x360 && currentDecodeBits <= 0x37F)
{
// this is going to end up in the range of 0xD800-0xDFFF UTF-16 surrogates that
// are not allowed in UTF-8;
return false;
}
if (remainingBytes == 2 && currentDecodeBits >= 0x110)
{
// this is going to be out of the upper Unicode bound 0x10FFFF.
return false;
}
sourceIndex = nextSourceIndex;
if (byteCount - remainingBytes == 2)
{
byte2 = nextByte;
}
else if (byteCount - remainingBytes == 3)
{
byte3 = nextByte;
}
else if (byteCount - remainingBytes == 4)
{
byte4 = nextByte;
}
}
if (currentDecodeBits < expectValueMin)
{
// overlong encoding (e.g. using 2 bytes to encode something that only needed 1).
return false;
}
// all bytes are verified, write to the output
// TODO: measure later to determine if the performance of following logic can be improved
// the idea is to combine the bytes into short/int and write to span directly to avoid
// range check cost
if (byteCount > 0)
{
buffer[destinationIndex++] = (byte)byte1;
}
if (byteCount > 1)
{
buffer[destinationIndex++] = (byte)byte2;
}
if (byteCount > 2)
{
buffer[destinationIndex++] = (byte)byte3;
}
if (byteCount > 3)
{
buffer[destinationIndex++] = (byte)byte4;
}
return true;
}
private static void Copy(int begin, int end, ref int writer, Span<byte> buffer)
{
while (begin != end)
{
buffer[writer++] = buffer[begin++];
}
}
/// <summary>
/// Read the percent-encoding and try unescape it.
///
/// The operation first peek at the character the <paramref name="scan"/>
/// iterator points at. If it is % the <paramref name="scan"/> is then
/// moved on to scan the following to characters. If the two following
/// characters are hexadecimal literals they will be unescaped and the
/// value will be returned.
///
/// If the first character is not % the <paramref name="scan"/> iterator
/// will be removed beyond the location of % and -1 will be returned.
///
/// If the following two characters can't be successfully unescaped the
/// <paramref name="scan"/> iterator will be move behind the % and -1
/// will be returned.
/// </summary>
/// <param name="scan">The value to read</param>
/// <param name="buffer">The byte array</param>
/// <returns>The unescaped byte if success. Otherwise return -1.</returns>
private static int UnescapePercentEncoding(ref int scan, Span<byte> buffer)
{
if (buffer[scan++] != '%')
{
return -1;
}
buffer = buffer.Slice(scan);
if (buffer.Length < 2)
{
return -1;
}
if (!Utf8Parser.TryParse(buffer.Slice(0, 2), out byte value, out var bytesConsumed, 'X'))
{
return -1;
}
if (bytesConsumed != 2)
{
return -1;
}
// skip %2F - '/'
if (value == 0x2F)
{
return -1;
}
scan += 2;
return value;
}
static UrlEncoder()
{
// Unreserved
IsAllowed['A'] = true;
IsAllowed['B'] = true;
IsAllowed['C'] = true;
IsAllowed['D'] = true;
IsAllowed['E'] = true;
IsAllowed['F'] = true;
IsAllowed['G'] = true;
IsAllowed['H'] = true;
IsAllowed['I'] = true;
IsAllowed['J'] = true;
IsAllowed['K'] = true;
IsAllowed['L'] = true;
IsAllowed['M'] = true;
IsAllowed['N'] = true;
IsAllowed['O'] = true;
IsAllowed['P'] = true;
IsAllowed['Q'] = true;
IsAllowed['R'] = true;
IsAllowed['S'] = true;
IsAllowed['T'] = true;
IsAllowed['U'] = true;
IsAllowed['V'] = true;
IsAllowed['W'] = true;
IsAllowed['X'] = true;
IsAllowed['Y'] = true;
IsAllowed['Z'] = true;
IsAllowed['a'] = true;
IsAllowed['b'] = true;
IsAllowed['c'] = true;
IsAllowed['d'] = true;
IsAllowed['e'] = true;
IsAllowed['f'] = true;
IsAllowed['g'] = true;
IsAllowed['h'] = true;
IsAllowed['i'] = true;
IsAllowed['j'] = true;
IsAllowed['k'] = true;
IsAllowed['l'] = true;
IsAllowed['m'] = true;
IsAllowed['n'] = true;
IsAllowed['o'] = true;
IsAllowed['p'] = true;
IsAllowed['q'] = true;
IsAllowed['r'] = true;
IsAllowed['s'] = true;
IsAllowed['t'] = true;
IsAllowed['u'] = true;
IsAllowed['v'] = true;
IsAllowed['w'] = true;
IsAllowed['x'] = true;
IsAllowed['y'] = true;
IsAllowed['z'] = true;
IsAllowed['0'] = true;
IsAllowed['1'] = true;
IsAllowed['2'] = true;
IsAllowed['3'] = true;
IsAllowed['4'] = true;
IsAllowed['5'] = true;
IsAllowed['6'] = true;
IsAllowed['7'] = true;
IsAllowed['8'] = true;
IsAllowed['9'] = true;
IsAllowed['-'] = true;
IsAllowed['_'] = true;
IsAllowed['.'] = true;
IsAllowed['~'] = true;
}
public static Utf8UriEncoder Utf8 { get; } = new Utf8UriEncoder();
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Encog.App.Analyst.Script.Normalize;
using Encog.App.Analyst.Script.Prop;
using Encog.App.Analyst.Script.Segregate;
using Encog.App.Analyst.Script.Task;
using Encog.Persist;
using Encog.Util.Arrayutil;
namespace Encog.App.Analyst.Script
{
/// <summary>
/// Used to save an Encog Analyst script.
/// </summary>
public class ScriptSave
{
/// <summary>
/// The script to save.
/// </summary>
private readonly AnalystScript _script;
/// <summary>
/// Construct the script.
/// </summary>
/// <param name="theScript">The script to save.</param>
public ScriptSave(AnalystScript theScript)
{
_script = theScript;
}
/// <summary>
/// Save the script to a stream.
/// </summary>
/// <param name="stream">The output stream.</param>
public void Save(Stream stream)
{
var xout = new EncogWriteHelper(stream);
SaveSubSection(xout, "HEADER", "DATASOURCE");
SaveConfig(xout);
if (_script.Fields != null)
{
SaveData(xout);
SaveNormalize(xout);
}
SaveSubSection(xout, "RANDOMIZE", "CONFIG");
SaveSubSection(xout, "CLUSTER", "CONFIG");
SaveSubSection(xout, "BALANCE", "CONFIG");
SaveSubSection(xout, "CODE", "CONFIG");
if (_script.Segregate.SegregateTargets != null)
{
SaveSegregate(xout);
}
SaveSubSection(xout, "GENERATE", "CONFIG");
SaveMachineLearning(xout);
SaveTasks(xout);
xout.Flush();
}
/// <summary>
/// Save the config info.
/// </summary>
/// <param name="xout">THe output file.</param>
private void SaveConfig(EncogWriteHelper xout)
{
SaveSubSection(xout, "SETUP", "CONFIG");
xout.AddSubSection("FILENAMES");
IList<String> list = _script.Properties.Filenames;
foreach (string key in list)
{
String v = _script.Properties.GetFilename(key);
var f = new FileInfo(v);
xout.WriteProperty(key,
f.DirectoryName.Equals(_script.BasePath, StringComparison.InvariantCultureIgnoreCase)
? f.Name
: v);
}
}
/// <summary>
/// Save the data fields.
/// </summary>
/// <param name="xout">The output file.</param>
private void SaveData(EncogWriteHelper xout)
{
SaveSubSection(xout, "DATA", "CONFIG");
xout.AddSubSection("STATS");
xout.AddColumn("name");
xout.AddColumn("isclass");
xout.AddColumn("iscomplete");
xout.AddColumn("isint");
xout.AddColumn("isreal");
xout.AddColumn("amax");
xout.AddColumn("amin");
xout.AddColumn("mean");
xout.AddColumn("sdev");
xout.AddColumn("source");
xout.WriteLine();
foreach (DataField field in _script.Fields)
{
xout.AddColumn(field.Name);
xout.AddColumn(field.Class);
xout.AddColumn(field.Complete);
xout.AddColumn(field.Integer);
xout.AddColumn(field.Real);
xout.AddColumn(field.Max);
xout.AddColumn(field.Min);
xout.AddColumn(field.Mean);
xout.AddColumn(field.StandardDeviation);
xout.AddColumn(field.Source);
xout.WriteLine();
}
xout.Flush();
xout.AddSubSection("CLASSES");
xout.AddColumn("field");
xout.AddColumn("code");
xout.AddColumn("name");
xout.WriteLine();
foreach (DataField field in _script.Fields)
{
if (field.Class)
{
foreach (AnalystClassItem col in field.ClassMembers)
{
xout.AddColumn(field.Name);
xout.AddColumn(col.Code);
xout.AddColumn(col.Name);
xout.AddColumn(col.Count);
xout.WriteLine();
}
}
}
}
/// <summary>
/// Save the ML sections.
/// </summary>
/// <param name="xout">The output file.</param>
private void SaveMachineLearning(EncogWriteHelper xout)
{
SaveSubSection(xout, "ML", "CONFIG");
SaveSubSection(xout, "ML", "TRAIN");
}
/// <summary>
/// Save the normalization data.
/// </summary>
/// <param name="xout">The output file.</param>
private void SaveNormalize(EncogWriteHelper xout)
{
SaveSubSection(xout, "NORMALIZE", "CONFIG");
xout.AddSubSection("RANGE");
xout.AddColumn("name");
xout.AddColumn("io");
xout.AddColumn("timeSlice");
xout.AddColumn("action");
xout.AddColumn("high");
xout.AddColumn("low");
xout.WriteLine();
foreach (AnalystField field in _script.Normalize.NormalizedFields)
{
xout.AddColumn(field.Name);
xout.AddColumn(field.Input ? "input" : "output");
xout.AddColumn(field.TimeSlice);
switch (field.Action)
{
case NormalizationAction.Ignore:
xout.AddColumn("ignore");
break;
case NormalizationAction.Normalize:
xout.AddColumn("range");
break;
case NormalizationAction.PassThrough:
xout.AddColumn("pass");
break;
case NormalizationAction.OneOf:
xout.AddColumn("oneof");
break;
case NormalizationAction.Equilateral:
xout.AddColumn("equilateral");
break;
case NormalizationAction.SingleField:
xout.AddColumn("single");
break;
default:
throw new AnalystError("Unknown action: " + field.Action);
}
xout.AddColumn(field.NormalizedHigh);
xout.AddColumn(field.NormalizedLow);
xout.WriteLine();
}
}
/// <summary>
/// Save segregate info.
/// </summary>
/// <param name="xout">The output file.</param>
private void SaveSegregate(EncogWriteHelper xout)
{
SaveSubSection(xout, "SEGREGATE", "CONFIG");
xout.AddSubSection("FILES");
xout.AddColumn("file");
xout.AddColumn("percent");
xout.WriteLine();
foreach (AnalystSegregateTarget target in _script.Segregate.SegregateTargets)
{
xout.AddColumn(target.File);
xout.AddColumn(target.Percent);
xout.WriteLine();
}
}
/// <summary>
/// Save a subsection.
/// </summary>
/// <param name="xout">The output file.</param>
/// <param name="section">The section.</param>
/// <param name="subSection">The subsection.</param>
private void SaveSubSection(EncogWriteHelper xout,
String section, String subSection)
{
if (!section.Equals(xout.CurrentSection))
{
xout.AddSection(section);
}
xout.AddSubSection(subSection);
List<PropertyEntry> list = PropertyConstraints.Instance
.GetEntries(section, subSection);
list.Sort();
foreach (PropertyEntry entry in list)
{
String key = section + ":" + subSection + "_"
+ entry.Name;
String v = _script.Properties.GetPropertyString(
key);
xout.WriteProperty(entry.Name, v ?? "");
}
}
/// <summary>
/// Save the tasks.
/// </summary>
/// <param name="xout">The output file.</param>
private void SaveTasks(EncogWriteHelper xout)
{
xout.AddSection("TASKS");
List<string> list = _script.Tasks.Keys.ToList();
list.Sort();
foreach (String key in list)
{
AnalystTask task = _script.GetTask(key);
xout.AddSubSection(task.Name);
foreach (String line in task.Lines)
{
xout.AddLine(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.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Data
{
internal sealed class Merger
{
private DataSet _dataSet = null;
private DataTable _dataTable = null;
private bool _preserveChanges;
private MissingSchemaAction _missingSchemaAction;
private bool _isStandAlonetable = false;
private bool _IgnoreNSforTableLookup = false; // Everett Behavior : SQL BU DT 370850
internal Merger(DataSet dataSet, bool preserveChanges, MissingSchemaAction missingSchemaAction)
{
_dataSet = dataSet;
_preserveChanges = preserveChanges;
// map AddWithKey -> Add
_missingSchemaAction = missingSchemaAction == MissingSchemaAction.AddWithKey ?
MissingSchemaAction.Add :
missingSchemaAction;
}
internal Merger(DataTable dataTable, bool preserveChanges, MissingSchemaAction missingSchemaAction)
{
_isStandAlonetable = true;
_dataTable = dataTable;
_preserveChanges = preserveChanges;
// map AddWithKey -> Add
_missingSchemaAction = missingSchemaAction == MissingSchemaAction.AddWithKey ?
MissingSchemaAction.Add :
missingSchemaAction;
}
internal void MergeDataSet(DataSet source)
{
if (source == _dataSet) return; //somebody is doing an 'automerge'
bool fEnforce = _dataSet.EnforceConstraints;
_dataSet.EnforceConstraints = false;
_IgnoreNSforTableLookup = (_dataSet._namespaceURI != source._namespaceURI); // if two DataSets have different
// Namespaces, ignore NS for table lookups as we won't be able to find the right tables which inherits its NS
List<DataColumn> existingColumns = null;// need to cache existing columns
if (MissingSchemaAction.Add == _missingSchemaAction)
{
existingColumns = new List<DataColumn>(); // need to cache existing columns
foreach (DataTable dt in _dataSet.Tables)
{
foreach (DataColumn dc in dt.Columns)
{
existingColumns.Add(dc);
}
}
}
for (int i = 0; i < source.Tables.Count; i++)
{
MergeTableData(source.Tables[i]); // since column expression might have dependency on relation, we do not set
//column expression at this point. We need to set it after adding relations
}
if (MissingSchemaAction.Ignore != _missingSchemaAction)
{
// Add all independent constraints
MergeConstraints(source);
// Add all relationships
for (int i = 0; i < source.Relations.Count; i++)
{
MergeRelation(source.Relations[i]);
}
}
if (MissingSchemaAction.Add == _missingSchemaAction)
{
// for which other options we should add expressions also?
foreach (DataTable sourceTable in source.Tables)
{
DataTable targetTable;
if (_IgnoreNSforTableLookup)
{
targetTable = _dataSet.Tables[sourceTable.TableName];
}
else
{
targetTable = _dataSet.Tables[sourceTable.TableName, sourceTable.Namespace];// we know that target table won't be null since MissingSchemaAction is Add , we have already added it!
}
foreach (DataColumn dc in sourceTable.Columns)
{
// Should we overwrite the previous expression column? No, refer to spec, if it is new column we need to add the schema
if (dc.Computed)
{
DataColumn targetColumn = targetTable.Columns[dc.ColumnName];
if (!existingColumns.Contains(targetColumn))
{
targetColumn.Expression = dc.Expression;
}
}
}
}
}
MergeExtendedProperties(source.ExtendedProperties, _dataSet.ExtendedProperties);
foreach (DataTable dt in _dataSet.Tables)
{
dt.EvaluateExpressions();
}
_dataSet.EnforceConstraints = fEnforce;
}
internal void MergeTable(DataTable src)
{
bool fEnforce = false;
if (!_isStandAlonetable)
{
if (src.DataSet == _dataSet) return; //somebody is doing an 'automerge'
fEnforce = _dataSet.EnforceConstraints;
_dataSet.EnforceConstraints = false;
}
else
{
if (src == _dataTable) return; //somebody is doing an 'automerge'
_dataTable.SuspendEnforceConstraints = true;
}
if (_dataSet != null)
{
// this is ds.Merge
// if source does not have a DS, or if NS of both DS does not match, ignore the NS
if (src.DataSet == null || src.DataSet._namespaceURI != _dataSet._namespaceURI)
{
_IgnoreNSforTableLookup = true;
}
}
else
{
// this is dt.Merge
if (_dataTable.DataSet == null || src.DataSet == null || src.DataSet._namespaceURI != _dataTable.DataSet._namespaceURI)
{
_IgnoreNSforTableLookup = true;
}
}
MergeTableData(src);
DataTable dt = _dataTable;
if (dt == null && _dataSet != null)
{
dt = _IgnoreNSforTableLookup ?
_dataSet.Tables[src.TableName] :
_dataSet.Tables[src.TableName, src.Namespace];
}
if (dt != null)
{
dt.EvaluateExpressions();
}
if (!_isStandAlonetable)
{
_dataSet.EnforceConstraints = fEnforce;
}
else
{
_dataTable.SuspendEnforceConstraints = false;
try
{
if (_dataTable.EnforceConstraints)
{
_dataTable.EnableConstraints();
}
}
catch (ConstraintException)
{
if (_dataTable.DataSet != null)
{
_dataTable.DataSet.EnforceConstraints = false;
}
throw;
}
}
}
private void MergeTable(DataTable src, DataTable dst)
{
int rowsCount = src.Rows.Count;
bool wasEmpty = dst.Rows.Count == 0;
if (0 < rowsCount)
{
Index ndxSearch = null;
DataKey key = default(DataKey);
dst.SuspendIndexEvents();
try
{
if (!wasEmpty && dst._primaryKey != null)
{
key = GetSrcKey(src, dst);
if (key.HasValue)
{
ndxSearch = dst._primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows | DataViewRowState.Added);
}
}
// this improves performance by iterating over the rows instead of computing their position
foreach (DataRow sourceRow in src.Rows)
{
DataRow targetRow = null;
if (ndxSearch != null)
{
targetRow = dst.FindMergeTarget(sourceRow, key, ndxSearch);
}
dst.MergeRow(sourceRow, targetRow, _preserveChanges, ndxSearch);
}
}
finally
{
dst.RestoreIndexEvents(true);
}
}
MergeExtendedProperties(src.ExtendedProperties, dst.ExtendedProperties);
}
internal void MergeRows(DataRow[] rows)
{
DataTable src = null;
DataTable dst = null;
DataKey key = default(DataKey);
Index ndxSearch = null;
bool fEnforce = _dataSet.EnforceConstraints;
_dataSet.EnforceConstraints = false;
for (int i = 0; i < rows.Length; i++)
{
DataRow row = rows[i];
if (row == null)
{
throw ExceptionBuilder.ArgumentNull($"{nameof(rows)}[{i}]");
}
if (row.Table == null)
{
throw ExceptionBuilder.ArgumentNull($"{nameof(rows)}[{i}].{nameof(DataRow.Table)}");
}
//somebody is doing an 'automerge'
if (row.Table.DataSet == _dataSet)
{
continue;
}
if (src != row.Table)
{ // row.Table changed from prev. row.
src = row.Table;
dst = MergeSchema(row.Table);
if (dst == null)
{
Debug.Assert(MissingSchemaAction.Ignore == _missingSchemaAction, "MergeSchema failed");
_dataSet.EnforceConstraints = fEnforce;
return;
}
if (dst._primaryKey != null)
{
key = GetSrcKey(src, dst);
}
if (key.HasValue)
{
// Getting our own copy instead. ndxSearch = dst.primaryKey.Key.GetSortIndex();
// IMO, Better would be to reuse index
// ndxSearch = dst.primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows | DataViewRowState.Added );
if (null != ndxSearch)
{
ndxSearch.RemoveRef();
ndxSearch = null;
}
ndxSearch = new Index(dst, dst._primaryKey.Key.GetIndexDesc(), DataViewRowState.OriginalRows | DataViewRowState.Added, null);
ndxSearch.AddRef(); // need to addref twice, otherwise it will be collected
ndxSearch.AddRef(); // in past first adref was done in const
}
}
if (row._newRecord == -1 && row._oldRecord == -1)
{
continue;
}
DataRow targetRow = null;
if (0 < dst.Rows.Count && ndxSearch != null)
{
targetRow = dst.FindMergeTarget(row, key, ndxSearch);
}
targetRow = dst.MergeRow(row, targetRow, _preserveChanges, ndxSearch);
if (targetRow.Table._dependentColumns != null && targetRow.Table._dependentColumns.Count > 0)
{
targetRow.Table.EvaluateExpressions(targetRow, DataRowAction.Change, null);
}
}
if (null != ndxSearch)
{
ndxSearch.RemoveRef();
ndxSearch = null;
}
_dataSet.EnforceConstraints = fEnforce;
}
private DataTable MergeSchema(DataTable table)
{
DataTable targetTable = null;
if (!_isStandAlonetable)
{
if (_dataSet.Tables.Contains(table.TableName, true))
{
if (_IgnoreNSforTableLookup)
{
targetTable = _dataSet.Tables[table.TableName];
}
else
{
targetTable = _dataSet.Tables[table.TableName, table.Namespace];
}
}
}
else
{
targetTable = _dataTable;
}
if (targetTable == null)
{
// in case of standalone table, we make sure that targetTable is not null, so if this check passes, it will be when it is called via detaset
if (MissingSchemaAction.Add == _missingSchemaAction)
{
targetTable = table.Clone(table.DataSet); // if we are here mainly we are called from DataSet.Merge at this point we don't set
//expression columns, since it might have refer to other columns via relation, so it won't find the table and we get exception;
// do it after adding relations.
_dataSet.Tables.Add(targetTable);
}
else if (MissingSchemaAction.Error == _missingSchemaAction)
{
throw ExceptionBuilder.MergeMissingDefinition(table.TableName);
}
}
else
{
if (MissingSchemaAction.Ignore != _missingSchemaAction)
{
// Do the columns
int oldCount = targetTable.Columns.Count;
for (int i = 0; i < table.Columns.Count; i++)
{
DataColumn src = table.Columns[i];
DataColumn dest = (targetTable.Columns.Contains(src.ColumnName, true)) ? targetTable.Columns[src.ColumnName] : null;
if (dest == null)
{
if (MissingSchemaAction.Add == _missingSchemaAction)
{
dest = src.Clone();
targetTable.Columns.Add(dest);
}
else
{
if (!_isStandAlonetable)
{
_dataSet.RaiseMergeFailed(targetTable, SR.Format(SR.DataMerge_MissingColumnDefinition, table.TableName, src.ColumnName), _missingSchemaAction);
}
else
{
throw ExceptionBuilder.MergeFailed(SR.Format(SR.DataMerge_MissingColumnDefinition, table.TableName, src.ColumnName));
}
}
}
else
{
if (dest.DataType != src.DataType ||
((dest.DataType == typeof(DateTime)) && (dest.DateTimeMode != src.DateTimeMode) && ((dest.DateTimeMode & src.DateTimeMode) != DataSetDateTime.Unspecified)))
{
if (!_isStandAlonetable)
_dataSet.RaiseMergeFailed(targetTable, SR.Format(SR.DataMerge_DataTypeMismatch, src.ColumnName), MissingSchemaAction.Error);
else
throw ExceptionBuilder.MergeFailed(SR.Format(SR.DataMerge_DataTypeMismatch, src.ColumnName));
}
MergeExtendedProperties(src.ExtendedProperties, dest.ExtendedProperties);
}
}
// Set DataExpression
if (_isStandAlonetable)
{
for (int i = oldCount; i < targetTable.Columns.Count; i++)
{
targetTable.Columns[i].Expression = table.Columns[targetTable.Columns[i].ColumnName].Expression;
}
}
// check the PrimaryKey
DataColumn[] targetPKey = targetTable.PrimaryKey;
DataColumn[] tablePKey = table.PrimaryKey;
if (targetPKey.Length != tablePKey.Length)
{
// special case when the target table does not have the PrimaryKey
if (targetPKey.Length == 0)
{
DataColumn[] key = new DataColumn[tablePKey.Length];
for (int i = 0; i < tablePKey.Length; i++)
{
key[i] = targetTable.Columns[tablePKey[i].ColumnName];
}
targetTable.PrimaryKey = key;
}
else if (tablePKey.Length != 0)
{
_dataSet.RaiseMergeFailed(targetTable, SR.DataMerge_PrimaryKeyMismatch, _missingSchemaAction);
}
}
else
{
for (int i = 0; i < targetPKey.Length; i++)
{
if (string.Compare(targetPKey[i].ColumnName, tablePKey[i].ColumnName, false, targetTable.Locale) != 0)
{
_dataSet.RaiseMergeFailed(table,
SR.Format(SR.DataMerge_PrimaryKeyColumnsMismatch, targetPKey[i].ColumnName, tablePKey[i].ColumnName),
_missingSchemaAction);
}
}
}
}
MergeExtendedProperties(table.ExtendedProperties, targetTable.ExtendedProperties);
}
return targetTable;
}
private void MergeTableData(DataTable src)
{
DataTable dest = MergeSchema(src);
if (dest == null) return;
dest.MergingData = true;
try
{
MergeTable(src, dest);
}
finally
{
dest.MergingData = false;
}
}
private void MergeConstraints(DataSet source)
{
for (int i = 0; i < source.Tables.Count; i++)
{
MergeConstraints(source.Tables[i]);
}
}
private void MergeConstraints(DataTable table)
{
// Merge constraints
for (int i = 0; i < table.Constraints.Count; i++)
{
Constraint src = table.Constraints[i];
Constraint dest = src.Clone(_dataSet, _IgnoreNSforTableLookup);
if (dest == null)
{
_dataSet.RaiseMergeFailed(table,
SR.Format(SR.DataMerge_MissingConstraint, src.GetType().FullName, src.ConstraintName),
_missingSchemaAction
);
}
else
{
Constraint cons = dest.Table.Constraints.FindConstraint(dest);
if (cons == null)
{
if (MissingSchemaAction.Add == _missingSchemaAction)
{
try
{
// try to keep the original name
dest.Table.Constraints.Add(dest);
}
catch (DuplicateNameException)
{
// if fail, assume default name
dest.ConstraintName = string.Empty;
dest.Table.Constraints.Add(dest);
}
}
else if (MissingSchemaAction.Error == _missingSchemaAction)
{
_dataSet.RaiseMergeFailed(table,
SR.Format(SR.DataMerge_MissingConstraint, src.GetType().FullName, src.ConstraintName),
_missingSchemaAction
);
}
}
else
{
MergeExtendedProperties(src.ExtendedProperties, cons.ExtendedProperties);
}
}
}
}
private void MergeRelation(DataRelation relation)
{
Debug.Assert(MissingSchemaAction.Error == _missingSchemaAction ||
MissingSchemaAction.Add == _missingSchemaAction,
"Unexpected value of MissingSchemaAction parameter : " + _missingSchemaAction.ToString());
DataRelation destRelation = null;
// try to find given relation in this dataSet
int iDest = _dataSet.Relations.InternalIndexOf(relation.RelationName);
if (iDest >= 0)
{
// check the columns and Relation properties..
destRelation = _dataSet.Relations[iDest];
if (relation.ParentKey.ColumnsReference.Length != destRelation.ParentKey.ColumnsReference.Length)
{
_dataSet.RaiseMergeFailed(null,
SR.Format(SR.DataMerge_MissingDefinition, relation.RelationName),
_missingSchemaAction);
}
for (int i = 0; i < relation.ParentKey.ColumnsReference.Length; i++)
{
DataColumn dest = destRelation.ParentKey.ColumnsReference[i];
DataColumn src = relation.ParentKey.ColumnsReference[i];
if (0 != string.Compare(dest.ColumnName, src.ColumnName, false, dest.Table.Locale))
{
_dataSet.RaiseMergeFailed(null,
SR.Format(SR.DataMerge_ReltionKeyColumnsMismatch, relation.RelationName),
_missingSchemaAction);
}
dest = destRelation.ChildKey.ColumnsReference[i];
src = relation.ChildKey.ColumnsReference[i];
if (0 != string.Compare(dest.ColumnName, src.ColumnName, false, dest.Table.Locale))
{
_dataSet.RaiseMergeFailed(null,
SR.Format(SR.DataMerge_ReltionKeyColumnsMismatch, relation.RelationName),
_missingSchemaAction);
}
}
}
else
{
if (MissingSchemaAction.Add == _missingSchemaAction)
{
// create identical realtion in the current dataset
DataTable parent = _IgnoreNSforTableLookup ?
_dataSet.Tables[relation.ParentTable.TableName] :
_dataSet.Tables[relation.ParentTable.TableName, relation.ParentTable.Namespace];
DataTable child = _IgnoreNSforTableLookup ?
_dataSet.Tables[relation.ChildTable.TableName] :
_dataSet.Tables[relation.ChildTable.TableName, relation.ChildTable.Namespace];
DataColumn[] parentColumns = new DataColumn[relation.ParentKey.ColumnsReference.Length];
DataColumn[] childColumns = new DataColumn[relation.ParentKey.ColumnsReference.Length];
for (int i = 0; i < relation.ParentKey.ColumnsReference.Length; i++)
{
parentColumns[i] = parent.Columns[relation.ParentKey.ColumnsReference[i].ColumnName];
childColumns[i] = child.Columns[relation.ChildKey.ColumnsReference[i].ColumnName];
}
try
{
destRelation = new DataRelation(relation.RelationName, parentColumns, childColumns, relation._createConstraints);
destRelation.Nested = relation.Nested;
_dataSet.Relations.Add(destRelation);
}
catch (Exception e) when (Common.ADP.IsCatchableExceptionType(e))
{
ExceptionBuilder.TraceExceptionForCapture(e);
_dataSet.RaiseMergeFailed(null, e.Message, _missingSchemaAction);
}
}
else
{
Debug.Assert(MissingSchemaAction.Error == _missingSchemaAction, "Unexpected value of MissingSchemaAction parameter : " + _missingSchemaAction.ToString());
throw ExceptionBuilder.MergeMissingDefinition(relation.RelationName);
}
}
MergeExtendedProperties(relation.ExtendedProperties, destRelation.ExtendedProperties);
return;
}
private void MergeExtendedProperties(PropertyCollection src, PropertyCollection dst)
{
if (MissingSchemaAction.Ignore == _missingSchemaAction)
{
return;
}
IDictionaryEnumerator srcDE = src.GetEnumerator();
while (srcDE.MoveNext())
{
if (!_preserveChanges || dst[srcDE.Key] == null)
{
dst[srcDE.Key] = srcDE.Value;
}
}
}
private DataKey GetSrcKey(DataTable src, DataTable dst)
{
if (src._primaryKey != null)
{
return src._primaryKey.Key;
}
DataKey key = default(DataKey);
if (dst._primaryKey != null)
{
DataColumn[] dstColumns = dst._primaryKey.Key.ColumnsReference;
DataColumn[] srcColumns = new DataColumn[dstColumns.Length];
for (int j = 0; j < dstColumns.Length; j++)
{
srcColumns[j] = src.Columns[dstColumns[j].ColumnName];
}
key = new DataKey(srcColumns, false); // DataKey will take ownership of srcColumns
}
return key;
}
}
}
| |
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Support;
using NUnit.Framework;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using MaxBytesLengthExceededException = Lucene.Net.Util.BytesRefHash.MaxBytesLengthExceededException;
[TestFixture]
public class TestBytesRefHash : LuceneTestCase
{
internal BytesRefHash Hash;
internal ByteBlockPool Pool;
[SetUp]
public override void SetUp()
{
base.SetUp();
Pool = NewPool();
Hash = NewHash(Pool);
}
private ByteBlockPool NewPool()
{
return Random().NextBoolean() && Pool != null ? Pool : new ByteBlockPool(new RecyclingByteBlockAllocator(ByteBlockPool.BYTE_BLOCK_SIZE, Random().Next(25)));
}
private BytesRefHash NewHash(ByteBlockPool blockPool)
{
int initSize = 2 << 1 + Random().Next(5);
return Random().NextBoolean() ? new BytesRefHash(blockPool) : new BytesRefHash(blockPool, initSize, new BytesRefHash.DirectBytesStartArray(initSize));
}
/// <summary>
/// Test method for <seealso cref="Lucene.Net.Util.BytesRefHash#size()"/>.
/// </summary>
[Test]
public virtual void TestSize()
{
BytesRef @ref = new BytesRef();
int num = AtLeast(2);
for (int j = 0; j < num; j++)
{
int mod = 1 + Random().Next(39);
for (int i = 0; i < 797; i++)
{
string str;
do
{
str = TestUtil.RandomRealisticUnicodeString(Random(), 1000);
} while (str.Length == 0);
@ref.CopyChars(str);
int count = Hash.Size();
int key = Hash.Add(@ref);
if (key < 0)
{
Assert.AreEqual(Hash.Size(), count);
}
else
{
Assert.AreEqual(Hash.Size(), count + 1);
}
if (i % mod == 0)
{
Hash.Clear();
Assert.AreEqual(0, Hash.Size());
Hash.Reinit();
}
}
}
}
/// <summary>
/// Test method for
/// <seealso cref="Lucene.Net.Util.BytesRefHash#get(int, BytesRef)"/>
/// .
/// </summary>
[Test]
public virtual void TestGet()
{
BytesRef @ref = new BytesRef();
BytesRef scratch = new BytesRef();
int num = AtLeast(2);
for (int j = 0; j < num; j++)
{
IDictionary<string, int?> strings = new Dictionary<string, int?>();
int uniqueCount = 0;
for (int i = 0; i < 797; i++)
{
string str;
do
{
str = TestUtil.RandomRealisticUnicodeString(Random(), 1000);
} while (str.Length == 0);
@ref.CopyChars(str);
int count = Hash.Size();
int key = Hash.Add(@ref);
if (key >= 0)
{
Assert.IsFalse(strings.ContainsKey(str));
strings[str] = Convert.ToInt32(key);
Assert.AreEqual(uniqueCount, key);
uniqueCount++;
Assert.AreEqual(Hash.Size(), count + 1);
}
else
{
Assert.IsTrue((-key) - 1 < count);
Assert.AreEqual(Hash.Size(), count);
}
}
foreach (KeyValuePair<string, int?> entry in strings)
{
@ref.CopyChars(entry.Key);
Assert.AreEqual(@ref, Hash.Get((int)entry.Value, scratch));
}
Hash.Clear();
Assert.AreEqual(0, Hash.Size());
Hash.Reinit();
}
}
/// <summary>
/// Test method for <seealso cref="Lucene.Net.Util.BytesRefHash#compact()"/>.
/// </summary>
[Test]
public virtual void TestCompact()
{
BytesRef @ref = new BytesRef();
int num = AtLeast(2);
for (int j = 0; j < num; j++)
{
int numEntries = 0;
const int size = 797;
BitArray bits = new BitArray(size);
for (int i = 0; i < size; i++)
{
string str;
do
{
str = TestUtil.RandomRealisticUnicodeString(Random(), 1000);
} while (str.Length == 0);
@ref.CopyChars(str);
int key = Hash.Add(@ref);
if (key < 0)
{
Assert.IsTrue(bits.SafeGet((-key) - 1));
}
else
{
Assert.IsFalse(bits.SafeGet(key));
bits.SafeSet(key, true);
numEntries++;
}
}
Assert.AreEqual(Hash.Size(), bits.Cardinality());
Assert.AreEqual(numEntries, bits.Cardinality());
Assert.AreEqual(numEntries, Hash.Size());
int[] compact = Hash.Compact();
Assert.IsTrue(numEntries < compact.Length);
for (int i = 0; i < numEntries; i++)
{
bits.SafeSet(compact[i], false);
}
Assert.AreEqual(0, bits.Cardinality());
Hash.Clear();
Assert.AreEqual(0, Hash.Size());
Hash.Reinit();
}
}
/// <summary>
/// Test method for
/// <seealso cref="Lucene.Net.Util.BytesRefHash#sort(java.util.Comparator)"/>.
/// </summary>
[Test]
public virtual void TestSort()
{
BytesRef @ref = new BytesRef();
int num = AtLeast(2);
for (int j = 0; j < num; j++)
{
SortedSet<string> strings = new SortedSet<string>();
for (int k = 0; k < 797; k++)
{
string str;
do
{
str = TestUtil.RandomRealisticUnicodeString(Random(), 1000);
} while (str.Length == 0);
@ref.CopyChars(str);
Hash.Add(@ref);
strings.Add(str);
}
// We use the UTF-16 comparator here, because we need to be able to
// compare to native String.CompareTo() [UTF-16]:
int[] sort = Hash.Sort(BytesRef.UTF8SortedAsUTF16Comparer);
Assert.IsTrue(strings.Count < sort.Length);
int i = 0;
BytesRef scratch = new BytesRef();
foreach (string @string in strings)
{
@ref.CopyChars(@string);
Assert.AreEqual(@ref, Hash.Get(sort[i++], scratch));
}
Hash.Clear();
Assert.AreEqual(0, Hash.Size());
Hash.Reinit();
}
}
/// <summary>
/// Test method for
/// <seealso cref="Lucene.Net.Util.BytesRefHash#add(Lucene.Net.Util.BytesRef)"/>
/// .
/// </summary>
[Test]
public virtual void TestAdd()
{
BytesRef @ref = new BytesRef();
BytesRef scratch = new BytesRef();
int num = AtLeast(2);
for (int j = 0; j < num; j++)
{
HashSet<string> strings = new HashSet<string>();
int uniqueCount = 0;
for (int i = 0; i < 797; i++)
{
string str;
do
{
str = TestUtil.RandomRealisticUnicodeString(Random(), 1000);
} while (str.Length == 0);
@ref.CopyChars(str);
int count = Hash.Size();
int key = Hash.Add(@ref);
if (key >= 0)
{
Assert.IsTrue(strings.Add(str));
Assert.AreEqual(uniqueCount, key);
Assert.AreEqual(Hash.Size(), count + 1);
uniqueCount++;
}
else
{
Assert.IsFalse(strings.Add(str));
Assert.IsTrue((-key) - 1 < count);
Assert.AreEqual(str, Hash.Get((-key) - 1, scratch).Utf8ToString());
Assert.AreEqual(count, Hash.Size());
}
}
AssertAllIn(strings, Hash);
Hash.Clear();
Assert.AreEqual(0, Hash.Size());
Hash.Reinit();
}
}
[Test]
public virtual void TestFind()
{
BytesRef @ref = new BytesRef();
BytesRef scratch = new BytesRef();
int num = AtLeast(2);
for (int j = 0; j < num; j++)
{
HashSet<string> strings = new HashSet<string>();
int uniqueCount = 0;
for (int i = 0; i < 797; i++)
{
string str;
do
{
str = TestUtil.RandomRealisticUnicodeString(Random(), 1000);
} while (str.Length == 0);
@ref.CopyChars(str);
int count = Hash.Size();
int key = Hash.Find(@ref); //hash.Add(ref);
if (key >= 0) // string found in hash
{
Assert.IsFalse(strings.Add(str));
Assert.IsTrue(key < count);
Assert.AreEqual(str, Hash.Get(key, scratch).Utf8ToString());
Assert.AreEqual(count, Hash.Size());
}
else
{
key = Hash.Add(@ref);
Assert.IsTrue(strings.Add(str));
Assert.AreEqual(uniqueCount, key);
Assert.AreEqual(Hash.Size(), count + 1);
uniqueCount++;
}
}
AssertAllIn(strings, Hash);
Hash.Clear();
Assert.AreEqual(0, Hash.Size());
Hash.Reinit();
}
}
[Test]
[ExpectedException(typeof(MaxBytesLengthExceededException))]
public virtual void TestLargeValue()
{
int[] sizes = { Random().Next(5), ByteBlockPool.BYTE_BLOCK_SIZE - 33 + Random().Next(31), ByteBlockPool.BYTE_BLOCK_SIZE - 1 + Random().Next(37) };
BytesRef @ref = new BytesRef();
for (int i = 0; i < sizes.Length; i++)
{
@ref.Bytes = new byte[sizes[i]];
@ref.Offset = 0;
@ref.Length = sizes[i];
try
{
Assert.AreEqual(i, Hash.Add(@ref));
}
catch (MaxBytesLengthExceededException e)
{
if (i < sizes.Length - 1)
{
Assert.Fail("unexpected exception at size: " + sizes[i]);
}
throw e;
}
}
}
/// <summary>
/// Test method for
/// <seealso cref="Lucene.Net.Util.BytesRefHash#addByPoolOffset(int)"/>
/// .
/// </summary>
[Test]
public virtual void TestAddByPoolOffset()
{
BytesRef @ref = new BytesRef();
BytesRef scratch = new BytesRef();
BytesRefHash offsetHash = NewHash(Pool);
int num = AtLeast(2);
for (int j = 0; j < num; j++)
{
HashSet<string> strings = new HashSet<string>();
int uniqueCount = 0;
for (int i = 0; i < 797; i++)
{
string str;
do
{
str = TestUtil.RandomRealisticUnicodeString(Random(), 1000);
} while (str.Length == 0);
@ref.CopyChars(str);
int count = Hash.Size();
int key = Hash.Add(@ref);
if (key >= 0)
{
Assert.IsTrue(strings.Add(str));
Assert.AreEqual(uniqueCount, key);
Assert.AreEqual(Hash.Size(), count + 1);
int offsetKey = offsetHash.AddByPoolOffset(Hash.ByteStart(key));
Assert.AreEqual(uniqueCount, offsetKey);
Assert.AreEqual(offsetHash.Size(), count + 1);
uniqueCount++;
}
else
{
Assert.IsFalse(strings.Add(str));
Assert.IsTrue((-key) - 1 < count);
Assert.AreEqual(str, Hash.Get((-key) - 1, scratch).Utf8ToString());
Assert.AreEqual(count, Hash.Size());
int offsetKey = offsetHash.AddByPoolOffset(Hash.ByteStart((-key) - 1));
Assert.IsTrue((-offsetKey) - 1 < count);
Assert.AreEqual(str, Hash.Get((-offsetKey) - 1, scratch).Utf8ToString());
Assert.AreEqual(count, Hash.Size());
}
}
AssertAllIn(strings, Hash);
foreach (string @string in strings)
{
@ref.CopyChars(@string);
int key = Hash.Add(@ref);
BytesRef bytesRef = offsetHash.Get((-key) - 1, scratch);
Assert.AreEqual(@ref, bytesRef);
}
Hash.Clear();
Assert.AreEqual(0, Hash.Size());
offsetHash.Clear();
Assert.AreEqual(0, offsetHash.Size());
Hash.Reinit(); // init for the next round
offsetHash.Reinit();
}
}
private void AssertAllIn(ISet<string> strings, BytesRefHash hash)
{
BytesRef @ref = new BytesRef();
BytesRef scratch = new BytesRef();
int count = hash.Size();
foreach (string @string in strings)
{
@ref.CopyChars(@string);
int key = hash.Add(@ref); // add again to check duplicates
Assert.AreEqual(@string, hash.Get((-key) - 1, scratch).Utf8ToString());
Assert.AreEqual(count, hash.Size());
Assert.IsTrue(key < count, "key: " + key + " count: " + count + " string: " + @string);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using u32 = System.UInt32;
using Pgno = System.UInt32;
namespace Community.CsharpSqlite
{
using sqlite3_value = Sqlite3.Mem;
using sqlite3_pcache = Sqlite3.PCache1;
public partial class Sqlite3
{
/*
** 2008 August 05
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file implements that page cache.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
**
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** A complete page cache is an instance of this structure.
*/
public class PCache
{
public PgHdr pDirty, pDirtyTail; /* List of dirty pages in LRU order */
public PgHdr pSynced; /* Last synced page in dirty page list */
public int _nRef; /* Number of referenced pages */
public int nMax; /* Configured cache size */
public int szPage; /* Size of every page in this cache */
public int szExtra; /* Size of extra space for each page */
public bool bPurgeable; /* True if pages are on backing store */
public dxStress xStress; //int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
public object pStress; /* Argument to xStress */
public sqlite3_pcache pCache; /* Pluggable cache module */
public PgHdr pPage1; /* Reference to page 1 */
public int nRef /* Number of referenced pages */
{
get
{
return _nRef;
}
set
{
_nRef = value;
}
}
public void Clear()
{
pDirty = null;
pDirtyTail = null;
pSynced = null;
nRef = 0;
}
};
/*
** Some of the Debug.Assert() macros in this code are too expensive to run
** even during normal debugging. Use them only rarely on long-running
** tests. Enable the expensive asserts using the
** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
*/
#if SQLITE_ENABLE_EXPENSIVE_ASSERT
//# define expensive_assert(X) Debug.Assert(X)
static void expensive_assert( bool x ) { Debug.Assert( x ); }
#else
//# define expensive_assert(X)
#endif
/********************************** Linked List Management ********************/
#if !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT
/*
** Check that the pCache.pSynced variable is set correctly. If it
** is not, either fail an Debug.Assert or return zero. Otherwise, return
** non-zero. This is only used in debugging builds, as follows:
**
** expensive_assert( pcacheCheckSynced(pCache) );
*/
static int pcacheCheckSynced(PCache pCache){
PgHdr p ;
for(p=pCache.pDirtyTail; p!=pCache.pSynced; p=p.pDirtyPrev){
Debug.Assert( p.nRef !=0|| (p.flags&PGHDR_NEED_SYNC) !=0);
}
return (p==null || p.nRef!=0 || (p.flags&PGHDR_NEED_SYNC)==0)?1:0;
}
#endif //* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
/*
** Remove page pPage from the list of dirty pages.
*/
static void pcacheRemoveFromDirtyList( PgHdr pPage )
{
PCache p = pPage.pCache;
Debug.Assert( pPage.pDirtyNext != null || pPage == p.pDirtyTail );
Debug.Assert( pPage.pDirtyPrev != null || pPage == p.pDirty );
/* Update the PCache1.pSynced variable if necessary. */
if ( p.pSynced == pPage )
{
PgHdr pSynced = pPage.pDirtyPrev;
while ( pSynced != null && ( pSynced.flags & PGHDR_NEED_SYNC ) != 0 )
{
pSynced = pSynced.pDirtyPrev;
}
p.pSynced = pSynced;
}
if ( pPage.pDirtyNext != null )
{
pPage.pDirtyNext.pDirtyPrev = pPage.pDirtyPrev;
}
else
{
Debug.Assert( pPage == p.pDirtyTail );
p.pDirtyTail = pPage.pDirtyPrev;
}
if ( pPage.pDirtyPrev != null )
{
pPage.pDirtyPrev.pDirtyNext = pPage.pDirtyNext;
}
else
{
Debug.Assert( pPage == p.pDirty );
p.pDirty = pPage.pDirtyNext;
}
pPage.pDirtyNext = null;
pPage.pDirtyPrev = null;
#if SQLITE_ENABLE_EXPENSIVE_ASSERT
expensive_assert( pcacheCheckSynced(p) );
#endif
}
/*
** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
** pPage).
*/
static void pcacheAddToDirtyList( PgHdr pPage )
{
PCache p = pPage.pCache;
Debug.Assert( pPage.pDirtyNext == null && pPage.pDirtyPrev == null && p.pDirty != pPage );
pPage.pDirtyNext = p.pDirty;
if ( pPage.pDirtyNext != null )
{
Debug.Assert( pPage.pDirtyNext.pDirtyPrev == null );
pPage.pDirtyNext.pDirtyPrev = pPage;
}
p.pDirty = pPage;
if ( null == p.pDirtyTail )
{
p.pDirtyTail = pPage;
}
if ( null == p.pSynced && 0 == ( pPage.flags & PGHDR_NEED_SYNC ) )
{
p.pSynced = pPage;
}
#if SQLITE_ENABLE_EXPENSIVE_ASSERT
expensive_assert( pcacheCheckSynced(p) );
#endif
}
/*
** Wrapper around the pluggable caches xUnpin method. If the cache is
** being used for an in-memory database, this function is a no-op.
*/
static void pcacheUnpin( PgHdr p )
{
PCache pCache = p.pCache;
if ( pCache.bPurgeable )
{
if ( p.pgno == 1 )
{
pCache.pPage1 = null;
}
sqlite3GlobalConfig.pcache.xUnpin( pCache.pCache, p, false );
}
}
/*************************************************** General Interfaces ******
**
** Initialize and shutdown the page cache subsystem. Neither of these
** functions are threadsafe.
*/
static int sqlite3PcacheInitialize()
{
if ( sqlite3GlobalConfig.pcache.xInit == null )
{
/* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
** built-in default page cache is used instead of the application defined
** page cache. */
sqlite3PCacheSetDefault();
}
return sqlite3GlobalConfig.pcache.xInit( sqlite3GlobalConfig.pcache.pArg );
}
static void sqlite3PcacheShutdown()
{
if ( sqlite3GlobalConfig.pcache.xShutdown != null )
{
/* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
sqlite3GlobalConfig.pcache.xShutdown( sqlite3GlobalConfig.pcache.pArg );
}
}
/*
** Return the size in bytes of a PCache object.
*/
static int sqlite3PcacheSize()
{
return 4;
}// sizeof( PCache ); }
/*
** Create a new PCache object. Storage space to hold the object
** has already been allocated and is passed in as the p pointer.
** The caller discovers how much space needs to be allocated by
** calling sqlite3PcacheSize().
*/
static void sqlite3PcacheOpen(
int szPage, /* Size of every page */
int szExtra, /* Extra space associated with each page */
bool bPurgeable, /* True if pages are on backing store */
dxStress xStress,//int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
object pStress, /* Argument to xStress */
PCache p /* Preallocated space for the PCache */
)
{
p.Clear();//memset(p, 0, sizeof(PCache));
p.szPage = szPage;
p.szExtra = szExtra;
p.bPurgeable = bPurgeable;
p.xStress = xStress;
p.pStress = pStress;
p.nMax = 100;
}
/*
** Change the page size for PCache object. The caller must ensure that there
** are no outstanding page references when this function is called.
*/
static void sqlite3PcacheSetPageSize( PCache pCache, int szPage )
{
Debug.Assert( pCache.nRef == 0 && pCache.pDirty == null );
if ( pCache.pCache != null )
{
sqlite3GlobalConfig.pcache.xDestroy( ref pCache.pCache );
pCache.pCache = null;
}
pCache.szPage = szPage;
}
/*
** Try to obtain a page from the cache.
*/
static int sqlite3PcacheFetch(
PCache pCache, /* Obtain the page from this cache */
u32 pgno, /* Page number to obtain */
int createFlag, /* If true, create page if it does not exist already */
ref PgHdr ppPage /* Write the page here */
)
{
PgHdr pPage = null;
int eCreate;
Debug.Assert( pCache != null );
Debug.Assert( createFlag == 1 || createFlag == 0 );
Debug.Assert( pgno > 0 );
/* If the pluggable cache (sqlite3_pcache*) has not been allocated,
** allocate it now.
*/
if ( null == pCache.pCache && createFlag != 0 )
{
sqlite3_pcache p;
int nByte;
nByte = pCache.szPage + pCache.szExtra + 0;// sizeof( PgHdr );
p = sqlite3GlobalConfig.pcache.xCreate( nByte, pCache.bPurgeable );
//if ( null == p )
//{
// return SQLITE_NOMEM;
//}
sqlite3GlobalConfig.pcache.xCachesize( p, pCache.nMax );
pCache.pCache = p;
}
eCreate = createFlag * ( 1 + ( ( !pCache.bPurgeable || null == pCache.pDirty ) ? 1 : 0 ) );
if ( pCache.pCache != null )
{
pPage = sqlite3GlobalConfig.pcache.xFetch( pCache.pCache, pgno, eCreate );
}
if ( null == pPage && eCreate == 1 )
{
PgHdr pPg;
/* Find a dirty page to write-out and recycle. First try to find a
** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
** cleared), but if that is not possible settle for any other
** unreferenced dirty page.
*/
#if SQLITE_ENABLE_EXPENSIVE_ASSERT
expensive_assert( pcacheCheckSynced(pCache) );
#endif
for ( pPg = pCache.pSynced;
pPg != null && ( pPg.nRef != 0 || ( pPg.flags & PGHDR_NEED_SYNC ) != 0 );
pPg = pPg.pDirtyPrev
)
;
pCache.pSynced = pPg;
if ( null == pPg )
{
for ( pPg = pCache.pDirtyTail; pPg != null && pPg.nRef != 0; pPg = pPg.pDirtyPrev )
;
}
if ( pPg != null )
{
int rc;
#if SQLITE_LOG_CACHE_SPILL
sqlite3_log(SQLITE_FULL,
"spill page %d making room for %d - cache used: %d/%d",
pPg->pgno, pgno,
sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
pCache->nMax);
#endif
rc = pCache.xStress( pCache.pStress, pPg );
if ( rc != SQLITE_OK && rc != SQLITE_BUSY )
{
return rc;
}
}
pPage = sqlite3GlobalConfig.pcache.xFetch( pCache.pCache, pgno, 2 );
}
if ( pPage != null )
{
if ( null == pPage.pData )
{
// memset(pPage, 0, sizeof(PgHdr));
pPage.pData = sqlite3Malloc( pCache.szPage );// pPage->pData = (void*)&pPage[1];
//pPage->pExtra = (void*)&((char*)pPage->pData)[pCache->szPage];
//memset(pPage->pExtra, 0, pCache->szExtra);
pPage.pCache = pCache;
pPage.pgno = pgno;
}
Debug.Assert( pPage.pCache == pCache );
Debug.Assert( pPage.pgno == pgno );
//assert(pPage->pData == (void*)&pPage[1]);
//assert(pPage->pExtra == (void*)&((char*)&pPage[1])[pCache->szPage]);
if ( 0 == pPage.nRef )
{
pCache.nRef++;
}
pPage.nRef++;
if ( pgno == 1 )
{
pCache.pPage1 = pPage;
}
}
ppPage = pPage;
return ( pPage == null && eCreate != 0 ) ? SQLITE_NOMEM : SQLITE_OK;
}
/*
** Decrement the reference count on a page. If the page is clean and the
** reference count drops to 0, then it is made elible for recycling.
*/
static void sqlite3PcacheRelease( PgHdr p )
{
Debug.Assert( p.nRef > 0 );
p.nRef--;
if ( p.nRef == 0 )
{
PCache pCache = p.pCache;
pCache.nRef--;
if ( ( p.flags & PGHDR_DIRTY ) == 0 )
{
pcacheUnpin( p );
}
else
{
/* Move the page to the head of the dirty list. */
pcacheRemoveFromDirtyList( p );
pcacheAddToDirtyList( p );
}
}
}
/*
** Increase the reference count of a supplied page by 1.
*/
static void sqlite3PcacheRef( PgHdr p )
{
Debug.Assert( p.nRef > 0 );
p.nRef++;
}
/*
** Drop a page from the cache. There must be exactly one reference to the
** page. This function deletes that reference, so after it returns the
** page pointed to by p is invalid.
*/
static void sqlite3PcacheDrop( PgHdr p )
{
PCache pCache;
Debug.Assert( p.nRef == 1 );
if ( ( p.flags & PGHDR_DIRTY ) != 0 )
{
pcacheRemoveFromDirtyList( p );
}
pCache = p.pCache;
pCache.nRef--;
if ( p.pgno == 1 )
{
pCache.pPage1 = null;
}
sqlite3GlobalConfig.pcache.xUnpin( pCache.pCache, p, true );
}
/*
** Make sure the page is marked as dirty. If it isn't dirty already,
** make it so.
*/
static void sqlite3PcacheMakeDirty( PgHdr p )
{
p.flags &= ~PGHDR_DONT_WRITE;
Debug.Assert( p.nRef > 0 );
if ( 0 == ( p.flags & PGHDR_DIRTY ) )
{
p.flags |= PGHDR_DIRTY;
pcacheAddToDirtyList( p );
}
}
/*
** Make sure the page is marked as clean. If it isn't clean already,
** make it so.
*/
static void sqlite3PcacheMakeClean( PgHdr p )
{
if ( ( p.flags & PGHDR_DIRTY ) != 0 )
{
pcacheRemoveFromDirtyList( p );
p.flags &= ~( PGHDR_DIRTY | PGHDR_NEED_SYNC );
if ( p.nRef == 0 )
{
pcacheUnpin( p );
}
}
}
/*
** Make every page in the cache clean.
*/
static void sqlite3PcacheCleanAll( PCache pCache )
{
PgHdr p;
while ( ( p = pCache.pDirty ) != null )
{
sqlite3PcacheMakeClean( p );
}
}
/*
** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
*/
static void sqlite3PcacheClearSyncFlags( PCache pCache )
{
PgHdr p;
for ( p = pCache.pDirty; p != null; p = p.pDirtyNext )
{
p.flags &= ~PGHDR_NEED_SYNC;
}
pCache.pSynced = pCache.pDirtyTail;
}
/*
** Change the page number of page p to newPgno.
*/
static void sqlite3PcacheMove( PgHdr p, Pgno newPgno )
{
PCache pCache = p.pCache;
Debug.Assert( p.nRef > 0 );
Debug.Assert( newPgno > 0 );
sqlite3GlobalConfig.pcache.xRekey( pCache.pCache, p, p.pgno, newPgno );
p.pgno = newPgno;
if ( ( p.flags & PGHDR_DIRTY ) != 0 && ( p.flags & PGHDR_NEED_SYNC ) != 0 )
{
pcacheRemoveFromDirtyList( p );
pcacheAddToDirtyList( p );
}
}
/*
** Drop every cache entry whose page number is greater than "pgno". The
** caller must ensure that there are no outstanding references to any pages
** other than page 1 with a page number greater than pgno.
**
** If there is a reference to page 1 and the pgno parameter passed to this
** function is 0, then the data area associated with page 1 is zeroed, but
** the page object is not dropped.
*/
static void sqlite3PcacheTruncate( PCache pCache, u32 pgno )
{
if ( pCache.pCache != null )
{
PgHdr p;
PgHdr pNext;
for ( p = pCache.pDirty; p != null; p = pNext )
{
pNext = p.pDirtyNext;
/* This routine never gets call with a positive pgno except right
** after sqlite3PcacheCleanAll(). So if there are dirty pages,
** it must be that pgno==0.
*/
Debug.Assert( p.pgno > 0 );
if ( ALWAYS( p.pgno > pgno ) )
{
Debug.Assert( ( p.flags & PGHDR_DIRTY ) != 0 );
sqlite3PcacheMakeClean( p );
}
}
if ( pgno == 0 && pCache.pPage1 != null )
{
// memset( pCache.pPage1.pData, 0, pCache.szPage );
pCache.pPage1.pData = sqlite3Malloc( pCache.szPage );
pgno = 1;
}
sqlite3GlobalConfig.pcache.xTruncate( pCache.pCache, pgno + 1 );
}
}
/*
** Close a cache.
*/
static void sqlite3PcacheClose( PCache pCache )
{
if ( pCache.pCache != null )
{
sqlite3GlobalConfig.pcache.xDestroy( ref pCache.pCache );
}
}
/*
** Discard the contents of the cache.
*/
static void sqlite3PcacheClear( PCache pCache )
{
sqlite3PcacheTruncate( pCache, 0 );
}
/*
** Merge two lists of pages connected by pDirty and in pgno order.
** Do not both fixing the pDirtyPrev pointers.
*/
static PgHdr pcacheMergeDirtyList( PgHdr pA, PgHdr pB )
{
PgHdr result = new PgHdr();
PgHdr pTail = result;
while ( pA != null && pB != null )
{
if ( pA.pgno < pB.pgno )
{
pTail.pDirty = pA;
pTail = pA;
pA = pA.pDirty;
}
else
{
pTail.pDirty = pB;
pTail = pB;
pB = pB.pDirty;
}
}
if ( pA != null )
{
pTail.pDirty = pA;
}
else if ( pB != null )
{
pTail.pDirty = pB;
}
else
{
pTail.pDirty = null;
}
return result.pDirty;
}
/*
** Sort the list of pages in accending order by pgno. Pages are
** connected by pDirty pointers. The pDirtyPrev pointers are
** corrupted by this sort.
**
** Since there cannot be more than 2^31 distinct pages in a database,
** there cannot be more than 31 buckets required by the merge sorter.
** One extra bucket is added to catch overflow in case something
** ever changes to make the previous sentence incorrect.
*/
//#define N_SORT_BUCKET 32
const int N_SORT_BUCKET = 32;
static PgHdr pcacheSortDirtyList( PgHdr pIn )
{
PgHdr[] a;
PgHdr p;//a[N_SORT_BUCKET], p;
int i;
a = new PgHdr[N_SORT_BUCKET];//memset(a, 0, sizeof(a));
while ( pIn != null )
{
p = pIn;
pIn = p.pDirty;
p.pDirty = null;
for ( i = 0; ALWAYS( i < N_SORT_BUCKET - 1 ); i++ )
{
if ( a[i] == null )
{
a[i] = p;
break;
}
else
{
p = pcacheMergeDirtyList( a[i], p );
a[i] = null;
}
}
if ( NEVER( i == N_SORT_BUCKET - 1 ) )
{
/* To get here, there need to be 2^(N_SORT_BUCKET) elements in
** the input list. But that is impossible.
*/
a[i] = pcacheMergeDirtyList( a[i], p );
}
}
p = a[0];
for ( i = 1; i < N_SORT_BUCKET; i++ )
{
p = pcacheMergeDirtyList( p, a[i] );
}
return p;
}
/*
** Return a list of all dirty pages in the cache, sorted by page number.
*/
static PgHdr sqlite3PcacheDirtyList( PCache pCache )
{
PgHdr p;
for ( p = pCache.pDirty; p != null; p = p.pDirtyNext )
{
p.pDirty = p.pDirtyNext;
}
return pcacheSortDirtyList( pCache.pDirty );
}
/*
** Return the total number of referenced pages held by the cache.
*/
static int sqlite3PcacheRefCount( PCache pCache )
{
return pCache.nRef;
}
/*
** Return the number of references to the page supplied as an argument.
*/
static int sqlite3PcachePageRefcount( PgHdr p )
{
return p.nRef;
}
/*
** Return the total number of pages in the cache.
*/
static int sqlite3PcachePagecount( PCache pCache )
{
int nPage = 0;
if ( pCache.pCache != null )
{
nPage = sqlite3GlobalConfig.pcache.xPagecount( pCache.pCache );
}
return nPage;
}
#if SQLITE_TEST
/*
** Get the suggested cache-size value.
*/
static int sqlite3PcacheGetCachesize( PCache pCache )
{
return pCache.nMax;
}
#endif
/*
** Set the suggested cache-size value.
*/
static void sqlite3PcacheSetCachesize( PCache pCache, int mxPage )
{
pCache.nMax = mxPage;
if ( pCache.pCache != null )
{
sqlite3GlobalConfig.pcache.xCachesize( pCache.pCache, mxPage );
}
}
#if SQLITE_CHECK_PAGES || (SQLITE_DEBUG)
/*
** For all dirty pages currently in the cache, invoke the specified
** callback. This is only used if the SQLITE_CHECK_PAGES macro is
** defined.
*/
static void sqlite3PcacheIterateDirty( PCache pCache, dxIter xIter )
{
PgHdr pDirty;
for ( pDirty = pCache.pDirty; pDirty != null; pDirty = pDirty.pDirtyNext )
{
xIter( pDirty );
}
}
#endif
}
}
| |
/*
* $Id$
* $URL$
* $Rev$
* $Author$
* $Date$
*
* SmartIrc4net - the IRC library for .NET/C# <http://smartirc4net.sf.net>
*
* Copyright (c) 2003-2005 Mirco Bauer <[email protected]> <http://www.meebey.net>
*
* Full LGPL License: <http://www.gnu.org/licenses/lgpl.txt>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections.Generic;
namespace Meebey.SmartIrc4net
{
/// <summary>
///
/// </summary>
public class ActionEventArgs : CtcpEventArgs
{
private string _ActionMessage;
public string ActionMessage {
get {
return _ActionMessage;
}
}
internal ActionEventArgs(IrcMessageData data, string actionmsg) : base(data, "ACTION", actionmsg)
{
_ActionMessage = actionmsg;
}
}
/// <summary>
///
/// </summary>
public class CtcpEventArgs : IrcEventArgs
{
private string _CtcpCommand;
private string _CtcpParameter;
public string CtcpCommand {
get {
return _CtcpCommand;
}
}
public string CtcpParameter {
get {
return _CtcpParameter;
}
}
internal CtcpEventArgs(IrcMessageData data, string ctcpcmd, string ctcpparam) : base(data)
{
_CtcpCommand = ctcpcmd;
_CtcpParameter = ctcpparam;
}
}
/// <summary>
///
/// </summary>
public class ErrorEventArgs : IrcEventArgs
{
private string _ErrorMessage;
public string ErrorMessage {
get {
return _ErrorMessage;
}
}
internal ErrorEventArgs(IrcMessageData data, string errormsg) : base(data)
{
_ErrorMessage = errormsg;
}
}
/// <summary>
///
/// </summary>
public class MotdEventArgs : IrcEventArgs
{
private string _MotdMessage;
public string MotdMessage {
get {
return _MotdMessage;
}
}
internal MotdEventArgs(IrcMessageData data, string motdmsg) : base(data)
{
_MotdMessage = motdmsg;
}
}
/// <summary>
///
/// </summary>
public class PingEventArgs : IrcEventArgs
{
private string _PingData;
public string PingData {
get {
return _PingData;
}
}
internal PingEventArgs(IrcMessageData data, string pingdata) : base(data)
{
_PingData = pingdata;
}
}
/// <summary>
///
/// </summary>
public class PongEventArgs : IrcEventArgs
{
private TimeSpan _Lag;
public TimeSpan Lag {
get {
return _Lag;
}
}
internal PongEventArgs(IrcMessageData data, TimeSpan lag) : base(data)
{
_Lag = lag;
}
}
/// <summary>
///
/// </summary>
public class KickEventArgs : IrcEventArgs
{
private string _Channel;
private string _Who;
private string _Whom;
private string _KickReason;
public string Channel {
get {
return _Channel;
}
}
public string Who {
get {
return _Who;
}
}
public string Whom {
get {
return _Whom;
}
}
public string KickReason {
get {
return _KickReason;
}
}
internal KickEventArgs(IrcMessageData data, string channel, string who, string whom, string kickreason) : base(data)
{
_Channel = channel;
_Who = who;
_Whom = whom;
_KickReason = kickreason;
}
}
/// <summary>
///
/// </summary>
public class JoinEventArgs : IrcEventArgs
{
private string _Channel;
private string _Who;
public string Channel {
get {
return _Channel;
}
}
public string Who {
get {
return _Who;
}
}
internal JoinEventArgs(IrcMessageData data, string channel, string who) : base(data)
{
_Channel = channel;
_Who = who;
}
}
/// <summary>
///
/// </summary>
public class NamesEventArgs : IrcEventArgs
{
private string _Channel;
private string[] _UserList;
public string[] RawUserList { get; private set; }
public string Channel {
get {
return _Channel;
}
}
public string[] UserList {
get {
return _UserList;
}
}
internal NamesEventArgs(IrcMessageData data, string channel, string[] userlist, string[] rawUserList) : base(data)
{
_Channel = channel;
_UserList = userlist;
RawUserList = rawUserList;
}
}
/// <summary>
///
/// </summary>
public class ListEventArgs : IrcEventArgs
{
private ChannelInfo f_ListInfo;
public ChannelInfo ListInfo {
get {
return f_ListInfo;
}
}
internal ListEventArgs(IrcMessageData data, ChannelInfo listInfo) : base(data)
{
f_ListInfo = listInfo;
}
}
/// <summary>
///
/// </summary>
public class InviteEventArgs : IrcEventArgs
{
private string _Channel;
private string _Who;
public string Channel {
get {
return _Channel;
}
}
public string Who {
get {
return _Who;
}
}
internal InviteEventArgs(IrcMessageData data, string channel, string who) : base(data)
{
_Channel = channel;
_Who = who;
}
}
/// <summary>
///
/// </summary>
public class PartEventArgs : IrcEventArgs
{
private string _Channel;
private string _Who;
private string _PartMessage;
public string Channel {
get {
return _Channel;
}
}
public string Who {
get {
return _Who;
}
}
public string PartMessage {
get {
return _PartMessage;
}
}
internal PartEventArgs(IrcMessageData data, string channel, string who, string partmessage) : base(data)
{
_Channel = channel;
_Who = who;
_PartMessage = partmessage;
}
}
/// <summary>
///
/// </summary>
public class WhoEventArgs : IrcEventArgs
{
private WhoInfo f_WhoInfo;
[Obsolete("Use WhoEventArgs.WhoInfo instead.")]
public string Channel {
get {
return f_WhoInfo.Channel;
}
}
[Obsolete("Use WhoEventArgs.WhoInfo instead.")]
public string Nick {
get {
return f_WhoInfo.Nick;
}
}
[Obsolete("Use WhoEventArgs.WhoInfo instead.")]
public string Ident {
get {
return f_WhoInfo.Ident;
}
}
[Obsolete("Use WhoEventArgs.WhoInfo instead.")]
public string Host {
get {
return f_WhoInfo.Host;
}
}
[Obsolete("Use WhoEventArgs.WhoInfo instead.")]
public string Realname {
get {
return f_WhoInfo.Realname;
}
}
[Obsolete("Use WhoEventArgs.WhoInfo instead.")]
public bool IsAway {
get {
return f_WhoInfo.IsAway;
}
}
[Obsolete("Use WhoEventArgs.WhoInfo instead.")]
public bool IsOp {
get {
return f_WhoInfo.IsOp;
}
}
[Obsolete("Use WhoEventArgs.WhoInfo instead.")]
public bool IsVoice {
get {
return f_WhoInfo.IsVoice;
}
}
[Obsolete("Use WhoEventArgs.WhoInfo instead.")]
public bool IsIrcOp {
get {
return f_WhoInfo.IsIrcOp;
}
}
[Obsolete("Use WhoEventArgs.WhoInfo instead.")]
public string Server {
get {
return f_WhoInfo.Server;
}
}
[Obsolete("Use WhoEventArgs.WhoInfo instead.")]
public int HopCount {
get {
return f_WhoInfo.HopCount;
}
}
public WhoInfo WhoInfo {
get {
return f_WhoInfo;
}
}
internal WhoEventArgs(IrcMessageData data, WhoInfo whoInfo) : base(data)
{
f_WhoInfo = whoInfo;
}
}
/// <summary>
///
/// </summary>
public class QuitEventArgs : IrcEventArgs
{
private string _Who;
private string _QuitMessage;
public string Who {
get {
return _Who;
}
}
public string QuitMessage {
get {
return _QuitMessage;
}
}
internal QuitEventArgs(IrcMessageData data, string who, string quitmessage) : base(data)
{
_Who = who;
_QuitMessage = quitmessage;
}
}
/// <summary>
///
/// </summary>
public class AwayEventArgs : IrcEventArgs
{
private string _Who;
private string _AwayMessage;
public string Who {
get {
return _Who;
}
}
public string AwayMessage{
get {
return _AwayMessage;
}
}
internal AwayEventArgs(IrcMessageData data, string who, string awaymessage) : base(data)
{
_Who = who;
_AwayMessage = awaymessage;
}
}
/// <summary>
///
/// </summary>
public class NickChangeEventArgs : IrcEventArgs
{
private string _OldNickname;
private string _NewNickname;
public string OldNickname {
get {
return _OldNickname;
}
}
public string NewNickname {
get {
return _NewNickname;
}
}
internal NickChangeEventArgs(IrcMessageData data, string oldnick, string newnick) : base(data)
{
_OldNickname = oldnick;
_NewNickname = newnick;
}
}
/// <summary>
///
/// </summary>
public class TopicEventArgs : IrcEventArgs
{
private string _Channel;
private string _Topic;
public string Channel {
get {
return _Channel;
}
}
public string Topic {
get {
return _Topic;
}
}
internal TopicEventArgs(IrcMessageData data, string channel, string topic) : base(data)
{
_Channel = channel;
_Topic = topic;
}
}
/// <summary>
///
/// </summary>
public class TopicChangeEventArgs : IrcEventArgs
{
private string _Channel;
private string _Who;
private string _NewTopic;
public string Channel {
get {
return _Channel;
}
}
public string Who {
get {
return _Who;
}
}
public string NewTopic {
get {
return _NewTopic;
}
}
internal TopicChangeEventArgs(IrcMessageData data, string channel, string who, string newtopic) : base(data)
{
_Channel = channel;
_Who = who;
_NewTopic = newtopic;
}
}
/// <summary>
///
/// </summary>
public class BanEventArgs : IrcEventArgs
{
private string _Channel;
private string _Who;
private string _Hostmask;
public string Channel {
get {
return _Channel;
}
}
public string Who {
get {
return _Who;
}
}
public string Hostmask {
get {
return _Hostmask;
}
}
internal BanEventArgs(IrcMessageData data, string channel, string who, string hostmask) : base(data)
{
_Channel = channel;
_Who = who;
_Hostmask = hostmask;
}
}
/// <summary>
///
/// </summary>
public class UnbanEventArgs : IrcEventArgs
{
private string _Channel;
private string _Who;
private string _Hostmask;
public string Channel {
get {
return _Channel;
}
}
public string Who {
get {
return _Who;
}
}
public string Hostmask {
get {
return _Hostmask;
}
}
internal UnbanEventArgs(IrcMessageData data, string channel, string who, string hostmask) : base(data)
{
_Channel = channel;
_Who = who;
_Hostmask = hostmask;
}
}
/// <summary>
/// Event arguments for any change in channel role.
/// </summary>
public class ChannelRoleChangeEventArgs : IrcEventArgs
{
public string Channel { get; private set; }
public string Who { get; private set; }
public string Whom { get; private set; }
internal ChannelRoleChangeEventArgs(IrcMessageData data, string channel, string who, string whom) : base(data)
{
Channel = channel;
Who = who;
Whom = whom;
}
}
/// <summary>
/// User gained owner status (non-RFC, channel mode +q, prefix ~).
/// </summary>
public class OwnerEventArgs : ChannelRoleChangeEventArgs
{
internal OwnerEventArgs(IrcMessageData data, string channel, string who, string whom) : base(data, channel, who, whom)
{
}
}
/// <summary>
/// User lost owner status (non-RFC, channel mode -q).
/// </summary>
public class DeownerEventArgs : ChannelRoleChangeEventArgs
{
internal DeownerEventArgs(IrcMessageData data, string channel, string who, string whom) : base(data, channel, who, whom)
{
}
}
/// <summary>
/// User gained channel admin status (non-RFC, channel mode +a, prefix &).
/// </summary>
public class ChannelAdminEventArgs : ChannelRoleChangeEventArgs
{
internal ChannelAdminEventArgs(IrcMessageData data, string channel, string who, string whom) : base(data, channel, who, whom)
{
}
}
/// <summary>
/// User lost channel admin status (non-RFC, channel mode -a).
/// </summary>
public class DeChannelAdminEventArgs : ChannelRoleChangeEventArgs
{
internal DeChannelAdminEventArgs(IrcMessageData data, string channel, string who, string whom) : base(data, channel, who, whom)
{
}
}
/// <summary>
/// User gained op status (channel mode +o, prefix @).
/// </summary>
public class OpEventArgs : ChannelRoleChangeEventArgs
{
internal OpEventArgs(IrcMessageData data, string channel, string who, string whom) : base(data, channel, who, whom)
{
}
}
/// <summary>
/// User lost op status (channel mode -o).
/// </summary>
public class DeopEventArgs : ChannelRoleChangeEventArgs
{
internal DeopEventArgs(IrcMessageData data, string channel, string who, string whom) : base(data, channel, who, whom)
{
}
}
/// <summary>
/// User gained halfop status (non-RFC, channel mode +h, prefix %).
/// </summary>
public class HalfopEventArgs : ChannelRoleChangeEventArgs
{
internal HalfopEventArgs(IrcMessageData data, string channel, string who, string whom) : base(data, channel, who, whom)
{
}
}
/// <summary>
/// User lost halfop status (non-RFC, channel mode -h).
/// </summary>
public class DehalfopEventArgs : ChannelRoleChangeEventArgs
{
internal DehalfopEventArgs(IrcMessageData data, string channel, string who, string whom) : base(data, channel, who, whom)
{
}
}
/// <summary>
/// User gained voice status (channel mode +v, prefix +).
/// </summary>
public class VoiceEventArgs : ChannelRoleChangeEventArgs
{
internal VoiceEventArgs(IrcMessageData data, string channel, string who, string whom) : base(data, channel, who, whom)
{
}
}
/// <summary>
/// User lost voice status (channel mode -v).
/// </summary>
public class DevoiceEventArgs : ChannelRoleChangeEventArgs
{
internal DevoiceEventArgs(IrcMessageData data, string channel, string who, string whom) : base(data, channel, who, whom)
{
}
}
public class BounceEventArgs : IrcEventArgs
{
/// <summary>
/// Hostname/address of the server to which the user is being redirected.
/// May be null if not successfully parsed from the message.
/// </summary>
public string Server { get; private set; }
/// <summary>
/// Port of the server to which the user is being redirected.
/// May be -1 if not successfully parsed from the message.
/// </summary>
public int Port { get; private set; }
internal BounceEventArgs(IrcMessageData data, string server, int port) : base(data)
{
Server = server;
Port = Port;
}
}
public class ChannelModeChangeEventArgs : IrcEventArgs
{
public string Channel { get; private set; }
public List<ChannelModeChangeInfo> ModeChanges { get; private set; }
internal ChannelModeChangeEventArgs(IrcMessageData data, string channel, List<ChannelModeChangeInfo> modeChanges) : base(data)
{
Channel = channel;
ModeChanges = modeChanges;
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace StreamWithContentType
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Image operations.
/// </summary>
public partial class Image : IServiceOperations<CowbellModerator>, IImage
{
/// <summary>
/// Initializes a new instance of the Image class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Image(CowbellModerator client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the CowbellModerator
/// </summary>
public CowbellModerator Client { get; private set; }
/// <param name='image'>
/// An image stream.
/// </param>
/// <param name='imageContentType'>
/// The content type of the image. Possible values include: 'image/gif',
/// 'image/jpeg', 'image/png', 'image/bmp', 'image/tiff'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> AWithHttpMessagesAsync(Stream image, ContentType? imageContentType = default(ContentType?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (image == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "image");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("image", image);
tracingParameters.Add("imageContentType", imageContentType);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "A", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "ProcessImage/FunctionA").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
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(image == null)
{
throw new System.ArgumentNullException("image");
}
if (image != null && image != Stream.Null)
{
_httpRequest.Content = new StreamContent(image);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse(imageContentType.ToSerializedValue());
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
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 HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <param name='image'>
/// An image stream.
/// </param>
/// <param name='imageContentType'>
/// The content type of the image. Possible values include: 'image/gif',
/// 'image/jpeg', 'image/png', 'image/bmp', 'image/tiff'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> BWithHttpMessagesAsync(Stream image, ContentType imageContentType, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (image == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "image");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("image", image);
tracingParameters.Add("imageContentType", imageContentType);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "B", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "ProcessImage/FunctionB").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
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(image == null)
{
throw new System.ArgumentNullException("image");
}
if (image != null && image != Stream.Null)
{
_httpRequest.Content = new StreamContent(image);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse(imageContentType.ToSerializedValue());
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
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 HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Configuration;
using System.Linq;
using System.Runtime.Caching;
using System.Web.Configuration;
using Microsoft.Xrm.Client.Services;
namespace Microsoft.Xrm.Client.Configuration
{
/// <summary>
/// The modes in which the <see cref="CrmConfigurationManager"/> instantiates <see cref="ObjectCache"/> objects.
/// </summary>
public enum ObjectCacheInstanceMode
{
/// <summary>
/// Create a static instance.
/// </summary>
Static,
/// <summary>
/// Create an instance for each element name.
/// </summary>
PerName,
/// <summary>
/// Create an instance on every invocation.
/// </summary>
PerInstance,
}
/// <summary>
/// The configuration settings for <see cref="ObjectCache"/> dependencies.
/// </summary>
/// <remarks>
/// For an example of the configuration format refer to the <see cref="CrmConfigurationManager"/>.
/// </remarks>
/// <seealso cref="CrmConfigurationManager"/>
public sealed class ObjectCacheElement : InitializableConfigurationElement<ObjectCache>, ICacheItemPolicyFactory
{
/// <summary>
/// The default element name.
/// </summary>
public const string DefaultObjectCacheName = "Microsoft.Xrm.Client";
private const string _defaultObjectCacheTypeName = "System.Runtime.Caching.MemoryCache, System.Runtime.Caching, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
private static readonly ConfigurationPropertyCollection _properties;
private static readonly ConfigurationProperty _propName;
private static readonly ConfigurationProperty _propType;
private static readonly ConfigurationProperty _propInstanceMode;
private static readonly ConfigurationProperty _propAbsoluteExpiration;
private static readonly ConfigurationProperty _propSlidingExpiration;
private static readonly ConfigurationProperty _propDuration;
private static readonly ConfigurationProperty _propPriority;
private static readonly ConfigurationProperty _propOutputCacheProfileName;
static ObjectCacheElement()
{
_propName = new ConfigurationProperty("name", typeof(string), null, ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey);
_propType = new ConfigurationProperty("type", typeof(string), _defaultObjectCacheTypeName, ConfigurationPropertyOptions.None);
_propInstanceMode = new ConfigurationProperty("instanceMode", typeof(ObjectCacheInstanceMode), ObjectCacheInstanceMode.PerName, ConfigurationPropertyOptions.None);
_propAbsoluteExpiration = new ConfigurationProperty("absoluteExpiration", typeof(DateTimeOffset), ObjectCache.InfiniteAbsoluteExpiration, ConfigurationPropertyOptions.None);
_propSlidingExpiration = new ConfigurationProperty("slidingExpiration", typeof(TimeSpan), ObjectCache.NoSlidingExpiration, ConfigurationPropertyOptions.None);
_propDuration = new ConfigurationProperty("duration", typeof(TimeSpan?), null, ConfigurationPropertyOptions.None);
_propPriority = new ConfigurationProperty("priority", typeof(CacheItemPriority), CacheItemPriority.Default, ConfigurationPropertyOptions.None);
_propOutputCacheProfileName = new ConfigurationProperty("outputCacheProfileName", typeof(string), null, ConfigurationPropertyOptions.None);
_properties = new ConfigurationPropertyCollection
{
_propName,
_propType,
_propInstanceMode,
_propAbsoluteExpiration,
_propSlidingExpiration,
_propDuration,
_propPriority,
_propOutputCacheProfileName,
};
}
protected override ConfigurationPropertyCollection Properties
{
get { return _properties; }
}
/// <summary>
/// Gets or sets the element name.
/// </summary>
[ConfigurationProperty("name", DefaultValue = null, IsKey = true, IsRequired = true)]
public override string Name
{
get { return (string)base[_propName]; }
set { base[_propName] = value; }
}
/// <summary>
/// The dependency type name.
/// </summary>
[ConfigurationProperty("type", DefaultValue = _defaultObjectCacheTypeName)]
public override string Type
{
get { return (string)base[_propType]; }
set { base[_propType] = value; }
}
/// <summary>
/// The instance mode.
/// </summary>
[ConfigurationProperty("instanceMode", DefaultValue = ObjectCacheInstanceMode.PerName)]
public ObjectCacheInstanceMode InstanceMode
{
get { return (ObjectCacheInstanceMode)base[_propInstanceMode]; }
set { base[_propInstanceMode] = value; }
}
/// <summary>
/// The cache policy absolute expiration date.
/// </summary>
[ConfigurationProperty("absoluteExpiration")]
public DateTimeOffset AbsoluteExpiration
{
get { return (DateTimeOffset)base[_propAbsoluteExpiration]; }
set { base[_propAbsoluteExpiration] = value; }
}
/// <summary>
/// The cache policy sliding expiration.
/// </summary>
[ConfigurationProperty("slidingExpiration")]
public TimeSpan SlidingExpiration
{
get { return (TimeSpan)base[_propSlidingExpiration]; }
set { base[_propSlidingExpiration] = value; }
}
/// <summary>
/// The cache policy cache duration.
/// </summary>
/// <remarks>
/// This value overrides the absolute expiration value as well as the duration specified by the OutputCacheProfileName property.
/// </remarks>
[ConfigurationProperty("duration")]
public TimeSpan? Duration
{
get { return (TimeSpan?)base[_propDuration]; }
set { base[_propDuration] = value; }
}
/// <summary>
/// The cache policy priority.
/// </summary>
[ConfigurationProperty("priority", DefaultValue = CacheItemPriority.Default)]
public CacheItemPriority Priority
{
get { return (CacheItemPriority)base[_propPriority]; }
set { base[_propPriority] = value; }
}
/// <summary>
/// The name of the <see cref="OutputCacheProfile"/> from which the cache profile duration is obtained.
/// </summary>
/// <remarks>
/// Only the duration value of the <see cref="OutputCacheProfile"/> is used. This value overrides the absolute expiration value.
/// </remarks>
[ConfigurationProperty("outputCacheProfileName")]
public string OutputCacheProfileName
{
get { return (string)base[_propOutputCacheProfileName]; }
set { base[_propOutputCacheProfileName] = value; }
}
/// <summary>
/// Creates a <see cref="ObjectCache"/> object.
/// </summary>
/// <param name="objectCacheName"></param>
/// <returns></returns>
public ObjectCache CreateObjectCache(string objectCacheName = null)
{
var name = objectCacheName ?? Name ?? DefaultObjectCacheName;
return CreateDependencyAndInitialize(
() => new MemoryCache(name, Parameters),
name, Parameters);
}
/// <summary>
/// Creates a <see cref="CacheItemPolicy"/> object.
/// </summary>
/// <returns></returns>
public CacheItemPolicy CreateCacheItemPolicy()
{
var duration = GetDuration();
return new CacheItemPolicy
{
AbsoluteExpiration = duration != null ? DateTimeOffset.UtcNow + duration.Value : AbsoluteExpiration,
SlidingExpiration = SlidingExpiration,
Priority = Priority,
};
}
private TimeSpan? GetDuration()
{
if (Duration != null) return Duration.Value;
if (!string.IsNullOrWhiteSpace(OutputCacheProfileName))
{
var section = ConfigurationManager.GetSection("system.web/caching/outputCacheSettings") as OutputCacheSettingsSection;
if (section != null)
{
var profile = section.OutputCacheProfiles.Cast<OutputCacheProfile>().FirstOrDefault(p => p.Name == OutputCacheProfileName);
if (profile != null && profile.Enabled && profile.Duration >= 0)
{
return new TimeSpan(0, 0, profile.Duration);
}
}
}
return null;
}
/// <summary>
/// Creates a <see cref="CacheItemPolicy"/> object.
/// </summary>
/// <returns></returns>
CacheItemPolicy ICacheItemPolicyFactory.Create()
{
return CreateCacheItemPolicy();
}
}
}
| |
//
// ColumnCellStatusIndicator.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2007-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 Gtk;
using Cairo;
using Mono.Unix;
using Hyena.Gui;
using Hyena.Data.Gui;
using Hyena.Data.Gui.Accessibility;
using Banshee.Gui;
using Banshee.Streaming;
using Banshee.MediaEngine;
using Banshee.ServiceStack;
namespace Banshee.Collection.Gui
{
class ColumnCellStatusIndicatorAccessible : ColumnCellAccessible, Atk.ImageImplementor
{
private string image_description;
public ColumnCellStatusIndicatorAccessible (object bound_object, ColumnCellStatusIndicator cell, ICellAccessibleParent parent) : base (bound_object, cell as ColumnCell, parent)
{
image_description = cell.GetTextAlternative (bound_object);
}
public override void Redrawn ()
{
string new_image_description = cell.GetTextAlternative (bound_object);
if (image_description != new_image_description)
GLib.Signal.Emit (this, "visible-data-changed");
image_description = new_image_description;
}
public string ImageLocale { get { return null; } }
public bool SetImageDescription (string description)
{
return false;
}
public void GetImageSize (out int width, out int height)
{
if (!String.IsNullOrEmpty (cell.GetTextAlternative (bound_object)))
width = height = 16;
else
width = height = Int32.MinValue;
}
public string ImageDescription {
get {
return image_description;
}
}
public void GetImagePosition (out int x, out int y, Atk.CoordType coordType)
{
if (!String.IsNullOrEmpty (cell.GetTextAlternative (bound_object))) {
GetPosition (out x, out y, coordType);
x += 4;
y += 4;
} else {
x = y = Int32.MinValue;
}
}
}
public class ColumnCellStatusIndicator : ColumnCell, ISizeRequestCell
{
const int padding = 2;
protected enum Icon : int {
Playing,
Paused,
Error,
Protected
}
private string [] status_names;
protected string [] StatusNames {
get { return status_names; }
}
private int pixbuf_size = 16;
protected virtual int PixbufSize {
get { return pixbuf_size; }
set { pixbuf_size = value; }
}
private int pixbuf_spacing = 4;
protected virtual int PixbufSpacing {
get { return pixbuf_spacing; }
set { pixbuf_spacing = value; }
}
private Gdk.Pixbuf [] pixbufs;
protected Gdk.Pixbuf [] Pixbufs {
get { return pixbufs; }
}
public ColumnCellStatusIndicator (string property) : this (property, true)
{
}
public ColumnCellStatusIndicator (string property, bool expand) : base (property, expand)
{
LoadPixbufs ();
RestrictSize = true;
}
public bool RestrictSize { get; set; }
public void GetWidthRange (Pango.Layout layout, out int min_width, out int max_width)
{
min_width = max_width = pixbuf_size + 2 * padding;
}
public override Atk.Object GetAccessible (ICellAccessibleParent parent)
{
return new ColumnCellStatusIndicatorAccessible (BoundObject, this, parent);
}
public override string GetTextAlternative (object obj)
{
var track = obj as TrackInfo;
if (track == null)
return "";
int icon_index = GetIconIndex (track);
if ((icon_index < 0) || (icon_index >= status_names.Length))
return "";
else
return status_names[icon_index];
}
protected virtual int PixbufCount {
get { return 4; }
}
protected virtual int GetIconIndex (TrackInfo track)
{
int icon_index = -1;
if (track.PlaybackError != StreamPlaybackError.None) {
icon_index = (int)(track.PlaybackError == StreamPlaybackError.Drm
? Icon.Protected
: Icon.Error);
} else if (track.IsPlaying) {
icon_index = (int)(ServiceManager.PlayerEngine.CurrentState == PlayerState.Paused
? Icon.Paused
: Icon.Playing);
} else {
icon_index = -1;
}
return icon_index;
}
protected virtual void LoadPixbufs ()
{
if (pixbufs != null && pixbufs.Length > 0) {
for (int i = 0; i < pixbufs.Length; i++) {
if (pixbufs[i] != null) {
pixbufs[i].Dispose ();
pixbufs[i] = null;
}
}
}
if (pixbufs == null) {
pixbufs = new Gdk.Pixbuf[PixbufCount];
}
pixbufs[(int)Icon.Playing] = IconThemeUtils.LoadIcon (PixbufSize, "media-playback-start");
pixbufs[(int)Icon.Paused] = IconThemeUtils.LoadIcon (PixbufSize, "media-playback-pause");
pixbufs[(int)Icon.Error] = IconThemeUtils.LoadIcon (PixbufSize, "emblem-unreadable", "dialog-error");
pixbufs[(int)Icon.Protected] = IconThemeUtils.LoadIcon (PixbufSize, "emblem-readonly", "dialog-error");
if (status_names == null) {
status_names = new string[PixbufCount];
for (int i=0; i<PixbufCount; i++)
status_names[i] = "";
}
status_names[(int)Icon.Playing] = Catalog.GetString ("Playing");
status_names[(int)Icon.Paused] = Catalog.GetString ("Paused");
status_names[(int)Icon.Error] = Catalog.GetString ("Error");
status_names[(int)Icon.Protected] = Catalog.GetString ("Protected");
}
public override void NotifyThemeChange ()
{
LoadPixbufs ();
}
public override void Render (CellContext context, StateType state, double cellWidth, double cellHeight)
{
TrackInfo track = BoundTrack;
if (track == null) {
return;
}
int icon_index = GetIconIndex (track);
if (icon_index < 0 || pixbufs == null || pixbufs[icon_index] == null) {
return;
}
context.Context.Translate (0, 0.5);
Gdk.Pixbuf render_pixbuf = pixbufs[icon_index];
Cairo.Rectangle pixbuf_area = new Cairo.Rectangle ((cellWidth - render_pixbuf.Width) / 2,
(cellHeight - render_pixbuf.Height) / 2, render_pixbuf.Width, render_pixbuf.Height);
if (!context.Opaque) {
context.Context.Save ();
}
Gdk.CairoHelper.SetSourcePixbuf (context.Context, render_pixbuf, pixbuf_area.X, pixbuf_area.Y);
context.Context.Rectangle (pixbuf_area);
if (!context.Opaque) {
context.Context.Clip ();
context.Context.PaintWithAlpha (0.5);
context.Context.Restore ();
} else {
context.Context.Fill ();
}
}
protected TrackInfo BoundTrack {
get { return BoundObject as TrackInfo; }
}
}
}
| |
using System;
using System.Threading.Tasks;
using System.Web;
using System.Net;
using System.Text;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.ComponentModel;
using SteamBot.SteamGroups;
using SteamKit2;
using SteamTrade;
using SteamKit2.Internal;
using SteamTrade.TradeOffer;
using System.Globalization;
namespace SteamBot
{
public class Bot : IDisposable
{
#region Bot delegates
public delegate UserHandler UserHandlerCreator(Bot bot, SteamID id);
#endregion
#region Private readonly variables
private readonly SteamUser.LogOnDetails logOnDetails;
private readonly string schemaLang;
private readonly string logFile;
private readonly Dictionary<SteamID, UserHandler> userHandlers;
private readonly Log.LogLevel consoleLogLevel;
private readonly Log.LogLevel fileLogLevel;
private readonly UserHandlerCreator createHandler;
private readonly bool isProccess;
private readonly BackgroundWorker botThread;
#endregion
#region Private variables
private Task<Inventory> myInventoryTask;
private TradeManager tradeManager;
private TradeOfferManager tradeOfferManager;
private int tradePollingInterval;
private string myUserNonce;
private string myUniqueId;
private bool cookiesAreInvalid = true;
private List<SteamID> friends;
private bool disposed = false;
#endregion
#region Public readonly variables
/// <summary>
/// Userhandler class bot is running.
/// </summary>
public readonly string BotControlClass;
/// <summary>
/// The display name of bot to steam.
/// </summary>
public readonly string DisplayName;
/// <summary>
/// The chat response from the config file.
/// </summary>
public readonly string ChatResponse;
/// <summary>
/// An array of admins for bot.
/// </summary>
public readonly IEnumerable<SteamID> Admins;
public readonly SteamClient SteamClient;
public readonly SteamUser SteamUser;
public readonly SteamFriends SteamFriends;
public readonly SteamTrading SteamTrade;
public readonly SteamGameCoordinator SteamGameCoordinator;
public readonly SteamNotifications SteamNotifications;
/// <summary>
/// The amount of time the bot will trade for.
/// </summary>
public readonly int MaximumTradeTime;
/// <summary>
/// The amount of time the bot will wait between user interactions with trade.
/// </summary>
public readonly int MaximumActionGap;
/// <summary>
/// The api key of bot.
/// </summary>
public readonly string ApiKey;
public readonly SteamWeb SteamWeb;
/// <summary>
/// The prefix shown before bot's display name.
/// </summary>
public readonly string DisplayNamePrefix;
#endregion
#region Public variables
public string AuthCode;
public bool IsRunning;
/// <summary>
/// Is bot fully Logged in.
/// Set only when bot did successfully Log in.
/// </summary>
public bool IsLoggedIn { get; private set; }
/// <summary>
/// The current trade the bot is in.
/// </summary>
public Trade CurrentTrade { get; private set; }
/// <summary>
/// The current game bot is in.
/// Default: 0 = No game.
/// </summary>
public int CurrentGame { get; private set; }
/// <summary>
/// The instance of the Logger for the bot.
/// </summary>
public Log Log;
#endregion
public IEnumerable<SteamID> FriendsList
{
get
{
CreateFriendsListIfNecessary();
return friends;
}
}
public Inventory MyInventory
{
get
{
myInventoryTask.Wait();
return myInventoryTask.Result;
}
}
/// <summary>
/// Compatibility sanity.
/// </summary>
[Obsolete("Refactored to be Log instead of log")]
public Log log { get { return Log; } }
public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false)
{
userHandlers = new Dictionary<SteamID, UserHandler>();
logOnDetails = new SteamUser.LogOnDetails
{
Username = config.Username,
Password = config.Password
};
DisplayName = config.DisplayName;
ChatResponse = config.ChatResponse;
MaximumTradeTime = config.MaximumTradeTime;
MaximumActionGap = config.MaximumActionGap;
DisplayNamePrefix = config.DisplayNamePrefix;
tradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
schemaLang = config.SchemaLang != null && config.SchemaLang.Length == 2 ? config.SchemaLang.ToLower() : "en";
Admins = config.Admins;
ApiKey = !String.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey;
isProccess = process;
try
{
if( config.LogLevel != null )
{
consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
Console.WriteLine(@"(Console) LogLevel configuration parameter used in bot {0} is depreciated and may be removed in future versions. Please use ConsoleLogLevel instead.", DisplayName);
}
else consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.ConsoleLogLevel, true);
}
catch (ArgumentException)
{
Console.WriteLine(@"(Console) ConsoleLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName);
consoleLogLevel = Log.LogLevel.Info;
}
try
{
fileLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.FileLogLevel, true);
}
catch (ArgumentException)
{
Console.WriteLine(@"(Console) FileLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName);
fileLogLevel = Log.LogLevel.Info;
}
logFile = config.LogFile;
CreateLog();
createHandler = handlerCreator;
BotControlClass = config.BotControlClass;
SteamWeb = new SteamWeb();
// Hacking around https
ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;
Log.Debug ("Initializing Steam Bot...");
SteamClient = new SteamClient();
SteamClient.AddHandler(new SteamNotifications());
SteamTrade = SteamClient.GetHandler<SteamTrading>();
SteamUser = SteamClient.GetHandler<SteamUser>();
SteamFriends = SteamClient.GetHandler<SteamFriends>();
SteamGameCoordinator = SteamClient.GetHandler<SteamGameCoordinator>();
SteamNotifications = SteamClient.GetHandler<SteamNotifications>();
botThread = new BackgroundWorker { WorkerSupportsCancellation = true };
botThread.DoWork += BackgroundWorkerOnDoWork;
botThread.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted;
botThread.RunWorkerAsync();
}
~Bot()
{
DisposeBot();
}
private void CreateLog()
{
if(Log == null)
Log = new Log (logFile, DisplayName, consoleLogLevel, fileLogLevel);
}
private void DisposeLog()
{
if(Log != null)
{
Log.Dispose();
Log = null;
}
}
private void CreateFriendsListIfNecessary()
{
if (friends != null)
return;
friends = new List<SteamID>();
for (int i = 0; i < SteamFriends.GetFriendCount(); i++)
friends.Add(SteamFriends.GetFriendByIndex(i));
}
/// <summary>
/// Occurs when the bot needs the SteamGuard authentication code.
/// </summary>
/// <remarks>
/// Return the code in <see cref="SteamGuardRequiredEventArgs.SteamGuard"/>
/// </remarks>
public event EventHandler<SteamGuardRequiredEventArgs> OnSteamGuardRequired;
/// <summary>
/// Starts the callback thread and connects to Steam via SteamKit2.
/// </summary>
/// <remarks>
/// THIS NEVER RETURNS.
/// </remarks>
/// <returns><c>true</c>. See remarks</returns>
public bool StartBot()
{
CreateLog();
IsRunning = true;
Log.Info("Connecting...");
if (!botThread.IsBusy)
botThread.RunWorkerAsync();
SteamClient.Connect();
Log.Success("Done Loading Bot!");
return true; // never get here
}
/// <summary>
/// Disconnect from the Steam network and stop the callback
/// thread.
/// </summary>
public void StopBot()
{
IsRunning = false;
Log.Debug("Trying to shut down bot thread.");
SteamClient.Disconnect();
botThread.CancelAsync();
userHandlers.Clear();
DisposeLog();
}
/// <summary>
/// Creates a new trade with the given partner.
/// </summary>
/// <returns>
/// <c>true</c>, if trade was opened,
/// <c>false</c> if there is another trade that must be closed first.
/// </returns>
public bool OpenTrade (SteamID other)
{
if (CurrentTrade != null || CheckCookies() == false)
return false;
SteamTrade.Trade(other);
return true;
}
/// <summary>
/// Closes the current active trade.
/// </summary>
public void CloseTrade()
{
if (CurrentTrade == null)
return;
UnsubscribeTrade (GetUserHandler (CurrentTrade.OtherSID), CurrentTrade);
tradeManager.StopTrade ();
CurrentTrade = null;
}
void OnTradeTimeout(object sender, EventArgs args)
{
// ignore event params and just null out the trade.
GetUserHandler(CurrentTrade.OtherSID).OnTradeTimeout();
}
/// <summary>
/// Create a new trade offer with the specified partner
/// </summary>
/// <param name="other">SteamId of the partner</param>
/// <returns></returns>
public TradeOffer NewTradeOffer(SteamID other)
{
return tradeOfferManager.NewOffer(other);
}
/// <summary>
/// Try to get a specific trade offer using the offerid
/// </summary>
/// <param name="offerId"></param>
/// <param name="tradeOffer"></param>
/// <returns></returns>
public bool TryGetTradeOffer(string offerId, out TradeOffer tradeOffer)
{
return tradeOfferManager.GetOffer(offerId, out tradeOffer);
}
public void HandleBotCommand(string command)
{
try
{
GetUserHandler(SteamClient.SteamID).OnBotCommand(command);
}
catch (ObjectDisposedException e)
{
// Writing to console because odds are the error was caused by a disposed Log.
Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e));
if (!this.IsRunning)
{
Console.WriteLine("The Bot is no longer running and could not write to the Log. Try Starting this bot first.");
}
}
catch (Exception e)
{
Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e));
}
}
bool HandleTradeSessionStart (SteamID other)
{
if (CurrentTrade != null)
return false;
try
{
tradeManager.InitializeTrade(SteamUser.SteamID, other);
CurrentTrade = tradeManager.CreateTrade(SteamUser.SteamID, other);
CurrentTrade.OnClose += CloseTrade;
SubscribeTrade(CurrentTrade, GetUserHandler(other));
tradeManager.StartTradeThread(CurrentTrade);
return true;
}
catch (SteamTrade.Exceptions.InventoryFetchException)
{
// we shouldn't get here because the inv checks are also
// done in the TradeProposedCallback handler.
/*string response = String.Empty;
if (ie.FailingSteamId.ConvertToUInt64() == other.ConvertToUInt64())
{
response = "Trade failed. Could not correctly fetch your backpack. Either the inventory is inaccessible or your backpack is private.";
}
else
{
response = "Trade failed. Could not correctly fetch my backpack.";
}
SteamFriends.SendChatMessage(other,
EChatEntryType.ChatMsg,
response);
Log.Info ("Bot sent other: {0}", response);
CurrentTrade = null;*/
return false;
}
}
public void SetGamePlaying(int id)
{
var gamePlaying = new SteamKit2.ClientMsgProtobuf<CMsgClientGamesPlayed>(EMsg.ClientGamesPlayed);
if (id != 0)
gamePlaying.Body.games_played.Add(new CMsgClientGamesPlayed.GamePlayed
{
game_id = new GameID(id),
});
SteamClient.Send(gamePlaying);
CurrentGame = id;
}
void HandleSteamMessage(ICallbackMsg msg)
{
Log.Debug(msg.ToString());
#region Login
msg.Handle<SteamClient.ConnectedCallback> (callback =>
{
Log.Debug ("Connection Callback: {0}", callback.Result);
if (callback.Result == EResult.OK)
{
UserLogOn();
}
else
{
Log.Error ("Failed to connect to Steam Community, trying again...");
SteamClient.Connect ();
}
});
msg.Handle<SteamUser.LoggedOnCallback> (callback =>
{
Log.Debug("Logged On Callback: {0}", callback.Result);
if (callback.Result == EResult.OK)
{
myUserNonce = callback.WebAPIUserNonce;
}
else
{
Log.Error("Login Error: {0}", callback.Result);
}
if (callback.Result == EResult.AccountLogonDenied)
{
Log.Interface ("This account is SteamGuard enabled. Enter the code via the `auth' command.");
// try to get the steamguard auth code from the event callback
var eva = new SteamGuardRequiredEventArgs();
FireOnSteamGuardRequired(eva);
if (!String.IsNullOrEmpty(eva.SteamGuard))
logOnDetails.AuthCode = eva.SteamGuard;
else
logOnDetails.AuthCode = Console.ReadLine();
}
if (callback.Result == EResult.InvalidLoginAuthCode)
{
Log.Interface("The given SteamGuard code was invalid. Try again using the `auth' command.");
logOnDetails.AuthCode = Console.ReadLine();
}
});
msg.Handle<SteamUser.LoginKeyCallback> (callback =>
{
myUniqueId = callback.UniqueID.ToString();
UserWebLogOn();
if (Trade.CurrentSchema == null)
{
Log.Info ("Downloading Schema...");
Trade.CurrentSchema = Schema.FetchSchema (ApiKey, schemaLang);
Log.Success ("Schema Downloaded!");
}
SteamFriends.SetPersonaName (DisplayNamePrefix+DisplayName);
SteamFriends.SetPersonaState (EPersonaState.Online);
Log.Success ("Steam Bot Logged In Completely!");
GetUserHandler(SteamClient.SteamID).OnLoginCompleted();
});
msg.Handle<SteamUser.WebAPIUserNonceCallback>(webCallback =>
{
Log.Debug("Received new WebAPIUserNonce.");
if (webCallback.Result == EResult.OK)
{
myUserNonce = webCallback.Nonce;
UserWebLogOn();
}
else
{
Log.Error("WebAPIUserNonce Error: " + webCallback.Result);
}
});
msg.Handle<SteamUser.UpdateMachineAuthCallback>(
authCallback => OnUpdateMachineAuthCallback(authCallback)
);
#endregion
#region Friends
msg.Handle<SteamFriends.FriendsListCallback>(callback =>
{
foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList)
{
switch (friend.SteamID.AccountType)
{
case EAccountType.Clan:
if (friend.Relationship == EFriendRelationship.RequestRecipient)
{
if (GetUserHandler(friend.SteamID).OnGroupAdd())
{
AcceptGroupInvite(friend.SteamID);
}
else
{
DeclineGroupInvite(friend.SteamID);
}
}
break;
default:
CreateFriendsListIfNecessary();
if (friend.Relationship == EFriendRelationship.None)
{
friends.Remove(friend.SteamID);
GetUserHandler(friend.SteamID).OnFriendRemove();
RemoveUserHandler(friend.SteamID);
}
else if (friend.Relationship == EFriendRelationship.RequestRecipient)
{
if (GetUserHandler(friend.SteamID).OnFriendAdd())
{
if (!friends.Contains(friend.SteamID))
{
friends.Add(friend.SteamID);
}
else
{
Log.Error("Friend was added who was already in friends list: " + friend.SteamID);
}
SteamFriends.AddFriend(friend.SteamID);
}
else
{
SteamFriends.RemoveFriend(friend.SteamID);
RemoveUserHandler(friend.SteamID);
}
}
break;
}
}
});
msg.Handle<SteamFriends.FriendMsgCallback> (callback =>
{
EChatEntryType type = callback.EntryType;
if (callback.EntryType == EChatEntryType.ChatMsg)
{
Log.Info ("Chat Message from {0}: {1}",
SteamFriends.GetFriendPersonaName (callback.Sender),
callback.Message
);
GetUserHandler(callback.Sender).OnMessageHandler(callback.Message, type);
}
});
#endregion
#region Group Chat
msg.Handle<SteamFriends.ChatMsgCallback>(callback =>
{
GetUserHandler(callback.ChatterID).OnChatRoomMessage(callback.ChatRoomID, callback.ChatterID, callback.Message);
});
#endregion
#region Trading
msg.Handle<SteamTrading.SessionStartCallback> (callback =>
{
bool started = HandleTradeSessionStart (callback.OtherClient);
if (!started)
Log.Error ("Could not start the trade session.");
else
Log.Debug ("SteamTrading.SessionStartCallback handled successfully. Trade Opened.");
});
msg.Handle<SteamTrading.TradeProposedCallback> (callback =>
{
if (CheckCookies() == false)
{
SteamTrade.RespondToTrade(callback.TradeID, false);
return;
}
try
{
tradeManager.InitializeTrade(SteamUser.SteamID, callback.OtherClient);
}
catch (WebException we)
{
SteamFriends.SendChatMessage(callback.OtherClient,
EChatEntryType.ChatMsg,
"Trade error: " + we.Message);
SteamTrade.RespondToTrade(callback.TradeID, false);
return;
}
catch (Exception)
{
SteamFriends.SendChatMessage(callback.OtherClient,
EChatEntryType.ChatMsg,
"Trade declined. Could not correctly fetch your backpack.");
SteamTrade.RespondToTrade(callback.TradeID, false);
return;
}
//if (tradeManager.OtherInventory.IsPrivate)
//{
// SteamFriends.SendChatMessage(callback.OtherClient,
// EChatEntryType.ChatMsg,
// "Trade declined. Your backpack cannot be private.");
// SteamTrade.RespondToTrade (callback.TradeID, false);
// return;
//}
if (CurrentTrade == null && GetUserHandler (callback.OtherClient).OnTradeRequest ())
SteamTrade.RespondToTrade (callback.TradeID, true);
else
SteamTrade.RespondToTrade (callback.TradeID, false);
});
msg.Handle<SteamTrading.TradeResultCallback> (callback =>
{
if (callback.Response == EEconTradeResponse.Accepted)
{
Log.Debug("Trade Status: {0}", callback.Response);
Log.Info ("Trade Accepted!");
GetUserHandler(callback.OtherClient).OnTradeRequestReply(true, callback.Response.ToString());
}
else
{
Log.Warn("Trade failed: {0}", callback.Response);
CloseTrade ();
GetUserHandler(callback.OtherClient).OnTradeRequestReply(false, callback.Response.ToString());
}
});
#endregion
#region Disconnect
msg.Handle<SteamUser.LoggedOffCallback> (callback =>
{
IsLoggedIn = false;
Log.Warn("Logged off Steam. Reason: {0}", callback.Result);
});
msg.Handle<SteamClient.DisconnectedCallback> (callback =>
{
if(IsLoggedIn)
{
IsLoggedIn = false;
CloseTrade();
Log.Warn("Disconnected from Steam Network!");
}
SteamClient.Connect ();
});
#endregion
#region Notifications
msg.Handle<SteamBot.SteamNotifications.NotificationCallback>(callback =>
{
//currently only appears to be of trade offer
if (callback.Notifications.Count != 0)
{
foreach (var notification in callback.Notifications)
{
Log.Info(notification.UserNotificationType + " notification");
}
}
// Get offers only if cookies are valid
if (CheckCookies())
tradeOfferManager.GetOffers();
});
msg.Handle<SteamBot.SteamNotifications.CommentNotificationCallback>(callback =>
{
//various types of comment notifications on profile/activity feed etc
//Log.Info("received CommentNotificationCallback");
//Log.Info("New Commments " + callback.CommentNotifications.CountNewComments);
//Log.Info("New Commments Owners " + callback.CommentNotifications.CountNewCommentsOwner);
//Log.Info("New Commments Subscriptions" + callback.CommentNotifications.CountNewCommentsSubscriptions);
});
#endregion
}
void UserLogOn()
{
// get sentry file which has the machine hw info saved
// from when a steam guard code was entered
Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles"));
FileInfo fi = new FileInfo(System.IO.Path.Combine("sentryfiles",String.Format("{0}.sentryfile", logOnDetails.Username)));
if (fi.Exists && fi.Length > 0)
logOnDetails.SentryFileHash = SHAHash(File.ReadAllBytes(fi.FullName));
else
logOnDetails.SentryFileHash = null;
SteamUser.LogOn(logOnDetails);
}
void UserWebLogOn()
{
do
{
IsLoggedIn = SteamWeb.Authenticate(myUniqueId, SteamClient, myUserNonce);
if(!IsLoggedIn)
{
Log.Warn("Authentication failed, retrying in 2s...");
Thread.Sleep(2000);
}
} while(!IsLoggedIn);
Log.Success("User Authenticated!");
tradeManager = new TradeManager(ApiKey, SteamWeb);
tradeManager.SetTradeTimeLimits(MaximumTradeTime, MaximumActionGap, tradePollingInterval);
tradeManager.OnTimeout += OnTradeTimeout;
tradeOfferManager = new TradeOfferManager(ApiKey, SteamWeb);
SubscribeTradeOffer(tradeOfferManager);
cookiesAreInvalid = false;
// Success, check trade offers which we have received while we were offline
tradeOfferManager.GetOffers();
}
/// <summary>
/// Checks if sessionId and token cookies are still valid.
/// Sets cookie flag if they are invalid.
/// </summary>
/// <returns>true if cookies are valid; otherwise false</returns>
bool CheckCookies()
{
// We still haven't re-authenticated
if (cookiesAreInvalid)
return false;
try
{
if (!SteamWeb.VerifyCookies())
{
// Cookies are no longer valid
Log.Warn("Cookies are invalid. Need to re-authenticate.");
cookiesAreInvalid = true;
SteamUser.RequestWebAPIUserNonce();
return false;
}
}
catch
{
// Even if exception is caught, we should still continue.
Log.Warn("Cookie check failed. http://steamcommunity.com is possibly down.");
}
return true;
}
UserHandler GetUserHandler(SteamID sid)
{
if (!userHandlers.ContainsKey(sid))
userHandlers[sid] = createHandler(this, sid);
return userHandlers[sid];
}
void RemoveUserHandler(SteamID sid)
{
if (userHandlers.ContainsKey(sid))
userHandlers.Remove(sid);
}
static byte [] SHAHash (byte[] input)
{
SHA1Managed sha = new SHA1Managed();
byte[] output = sha.ComputeHash( input );
sha.Clear();
return output;
}
void OnUpdateMachineAuthCallback(SteamUser.UpdateMachineAuthCallback machineAuth)
{
byte[] hash = SHAHash (machineAuth.Data);
Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles"));
File.WriteAllBytes (System.IO.Path.Combine("sentryfiles", String.Format("{0}.sentryfile", logOnDetails.Username)), machineAuth.Data);
var authResponse = new SteamUser.MachineAuthDetails
{
BytesWritten = machineAuth.BytesToWrite,
FileName = machineAuth.FileName,
FileSize = machineAuth.BytesToWrite,
Offset = machineAuth.Offset,
SentryFileHash = hash, // should be the sha1 hash of the sentry file we just wrote
OneTimePassword = machineAuth.OneTimePassword, // not sure on this one yet, since we've had no examples of steam using OTPs
LastError = 0, // result from win32 GetLastError
Result = EResult.OK, // if everything went okay, otherwise ~who knows~
JobID = machineAuth.JobID, // so we respond to the correct server job
};
// send off our response
SteamUser.SendMachineAuthResponse (authResponse);
}
/// <summary>
/// Gets the bot's inventory and stores it in MyInventory.
/// </summary>
/// <example> This sample shows how to find items in the bot's inventory from a user handler.
/// <code>
/// Bot.GetInventory(); // Get the inventory first
/// foreach (var item in Bot.MyInventory.Items)
/// {
/// if (item.Defindex == 5021)
/// {
/// // Bot has a key in its inventory
/// }
/// }
/// </code>
/// </example>
public void GetInventory()
{
myInventoryTask = Task.Factory.StartNew((Func<Inventory>) FetchBotsInventory);
}
public void TradeOfferRouter(TradeOffer offer)
{
if (offer.OfferState == TradeOfferState.TradeOfferStateActive)
{
GetUserHandler(offer.PartnerSteamId).OnNewTradeOffer(offer);
}
}
public void SubscribeTradeOffer(TradeOfferManager tradeOfferManager)
{
tradeOfferManager.OnNewTradeOffer += TradeOfferRouter;
}
//todo: should unsubscribe eventually...
public void UnsubscribeTradeOffer(TradeOfferManager tradeOfferManager)
{
tradeOfferManager.OnNewTradeOffer -= TradeOfferRouter;
}
/// <summary>
/// Subscribes all listeners of this to the trade.
/// </summary>
public void SubscribeTrade (Trade trade, UserHandler handler)
{
trade.OnSuccess += handler.OnTradeSuccess;
trade.OnAwaitingEmailConfirmation += handler.OnTradeAwaitingEmailConfirmation;
trade.OnClose += handler.OnTradeClose;
trade.OnError += handler.OnTradeError;
trade.OnStatusError += handler.OnStatusError;
//trade.OnTimeout += OnTradeTimeout;
trade.OnAfterInit += handler.OnTradeInit;
trade.OnUserAddItem += handler.OnTradeAddItem;
trade.OnUserRemoveItem += handler.OnTradeRemoveItem;
trade.OnMessage += handler.OnTradeMessageHandler;
trade.OnUserSetReady += handler.OnTradeReadyHandler;
trade.OnUserAccept += handler.OnTradeAcceptHandler;
}
/// <summary>
/// Unsubscribes all listeners of this from the current trade.
/// </summary>
public void UnsubscribeTrade (UserHandler handler, Trade trade)
{
trade.OnSuccess -= handler.OnTradeSuccess;
trade.OnAwaitingEmailConfirmation -= handler.OnTradeAwaitingEmailConfirmation;
trade.OnClose -= handler.OnTradeClose;
trade.OnError -= handler.OnTradeError;
trade.OnStatusError -= handler.OnStatusError;
//Trade.OnTimeout -= OnTradeTimeout;
trade.OnAfterInit -= handler.OnTradeInit;
trade.OnUserAddItem -= handler.OnTradeAddItem;
trade.OnUserRemoveItem -= handler.OnTradeRemoveItem;
trade.OnMessage -= handler.OnTradeMessageHandler;
trade.OnUserSetReady -= handler.OnTradeReadyHandler;
trade.OnUserAccept -= handler.OnTradeAcceptHandler;
}
/// <summary>
/// Fetch the Bot's inventory and log a warning if it's private
/// </summary>
private Inventory FetchBotsInventory()
{
var inventory = Inventory.FetchInventory(SteamUser.SteamID, ApiKey, SteamWeb);
if(inventory.IsPrivate)
{
log.Warn("The bot's backpack is private! If your bot adds any items it will fail! Your bot's backpack should be Public.");
}
return inventory;
}
#region Background Worker Methods
private void BackgroundWorkerOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
{
if (runWorkerCompletedEventArgs.Error != null)
{
Exception ex = runWorkerCompletedEventArgs.Error;
Log.Error("Unhandled exceptions in bot {0} callback thread: {1} {2}",
DisplayName,
Environment.NewLine,
ex);
Log.Info("This bot died. Stopping it..");
//backgroundWorker.RunWorkerAsync();
//Thread.Sleep(10000);
StopBot();
//StartBot();
}
Log.Dispose();
}
private void BackgroundWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
{
ICallbackMsg msg;
while (!botThread.CancellationPending)
{
try
{
msg = SteamClient.WaitForCallback(true);
HandleSteamMessage(msg);
}
catch (WebException e)
{
Log.Error("URI: {0} >> {1}", (e.Response != null && e.Response.ResponseUri != null ? e.Response.ResponseUri.ToString() : "unknown"), e.ToString());
System.Threading.Thread.Sleep(45000);//Steam is down, retry in 45 seconds.
}
catch (Exception e)
{
Log.Error(e.ToString());
Log.Warn("Restarting bot...");
}
}
}
#endregion Background Worker Methods
private void FireOnSteamGuardRequired(SteamGuardRequiredEventArgs e)
{
// Set to null in case this is another attempt
this.AuthCode = null;
EventHandler<SteamGuardRequiredEventArgs> handler = OnSteamGuardRequired;
if (handler != null)
handler(this, e);
else
{
while (true)
{
if (this.AuthCode != null)
{
e.SteamGuard = this.AuthCode;
break;
}
Thread.Sleep(5);
}
}
}
#region Group Methods
/// <summary>
/// Accepts the invite to a Steam Group
/// </summary>
/// <param name="group">SteamID of the group to accept the invite from.</param>
private void AcceptGroupInvite(SteamID group)
{
var AcceptInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite);
AcceptInvite.Body.GroupID = group.ConvertToUInt64();
AcceptInvite.Body.AcceptInvite = true;
this.SteamClient.Send(AcceptInvite);
}
/// <summary>
/// Declines the invite to a Steam Group
/// </summary>
/// <param name="group">SteamID of the group to decline the invite from.</param>
private void DeclineGroupInvite(SteamID group)
{
var DeclineInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite);
DeclineInvite.Body.GroupID = group.ConvertToUInt64();
DeclineInvite.Body.AcceptInvite = false;
this.SteamClient.Send(DeclineInvite);
}
/// <summary>
/// Invites a use to the specified Steam Group
/// </summary>
/// <param name="user">SteamID of the user to invite.</param>
/// <param name="groupId">SteamID of the group to invite the user to.</param>
public void InviteUserToGroup(SteamID user, SteamID groupId)
{
var InviteUser = new ClientMsg<CMsgInviteUserToGroup>((int)EMsg.ClientInviteUserToClan);
InviteUser.Body.GroupID = groupId.ConvertToUInt64();
InviteUser.Body.Invitee = user.ConvertToUInt64();
InviteUser.Body.UnknownInfo = true;
this.SteamClient.Send(InviteUser);
}
#endregion
public void Dispose()
{
DisposeBot();
GC.SuppressFinalize(this);
}
private void DisposeBot()
{
if (disposed)
return;
disposed = true;
StopBot();
}
}
}
| |
namespace StandaloneReview.Tests
{
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Model;
using MockViews;
using Presenters;
[TestClass]
public class FrmStandaloneReviewPresenterDeleteCommentTests
{
[TestMethod]
public void FrmStandaloneReviewTitle_CommentDeleted_ExpectStar()
{
// Arrange
var mockView = new MockFrmStandaloneReview();
mockView.AppState.CurrentReview = new Review
{
ReviewedFiles = new Dictionary<string, ReviewedFile>(),
Saved = true
};
mockView.AppState.CurrentReviewedFile = new ReviewedFile
{
Filename = "Test",
Comments = new List<ReviewComment>
{
new ReviewComment
{
Line = 5
}
}
};
var presenter = new FrmStandaloneReviewPresenter(mockView);
Assert.IsTrue(mockView.SetFrmStandaloneReviewTitleWasCalled);
//Assert.IsFalse(mockView.SetFrmStandaloneReviewTitleValue.EndsWith(" *")); // The title should not contain a star before deleting a comment
// Act
mockView.FireDeleteCommentToolStripMenuItemClickEvent(5, 5);
// Assert
Assert.IsTrue(mockView.SetFrmStandaloneReviewTitleWasCalled);
//Assert.IsTrue(mockView.SetFrmStandaloneReviewTitleValue.EndsWith(" *")); // The title should contain a star after a comment is deleted
}
[TestMethod]
public void FrmStandaloneReviewDeleteComment_TwoCommentsOnSameLine_ExpectCorrectOneToBeDeleted()
{
// Arrange
var mockView = new MockFrmStandaloneReview();
mockView.AppState.CurrentReview = new Review
{
ReviewedFiles = new Dictionary<string, ReviewedFile>(),
Saved = true
};
mockView.AppState.CurrentReviewedFile = new ReviewedFile
{
Filename = "Test",
Comments = new List<ReviewComment>
{
new ReviewComment
{
Line = 5
},
new ReviewComment
{
SelectionStartLine = 11,
SelectionStartColumn = 25,
SelectionEndLine = 11,
SelectionEndColumn = 35
},
new ReviewComment
{
SelectionStartLine = 11,
SelectionStartColumn = 55,
SelectionEndLine = 11,
SelectionEndColumn = 65
},
new ReviewComment
{
Line = 15
}
}
};
var presenter = new FrmStandaloneReviewPresenter(mockView);
// Act
mockView.FireDeleteCommentToolStripMenuItemClickEvent(11, 30);
// Assert
Assert.IsTrue(mockView.AppState.CurrentReviewedFile.Comments.Exists(p => p.Line == 5));
Assert.IsTrue(mockView.AppState.CurrentReviewedFile.Comments.Exists(p => p.SelectionStartLine == 11 && p.SelectionStartColumn == 55));
Assert.IsTrue(mockView.AppState.CurrentReviewedFile.Comments.Exists(p => p.Line == 15));
Assert.AreEqual(3, mockView.AppState.CurrentReviewedFile.Comments.Count);
}
[TestMethod]
public void FrmStandaloneReviewDeleteComment_OneSelectionComments_ExpectItToBeDeleted()
{
// Arrange
var mockView = new MockFrmStandaloneReview();
mockView.AppState.CurrentReview = new Review
{
ReviewedFiles = new Dictionary<string, ReviewedFile>(),
Saved = true
};
mockView.AppState.CurrentReviewedFile = new ReviewedFile
{
Filename = "Test",
Comments = new List<ReviewComment>
{
new ReviewComment
{
Line = 5
},
new ReviewComment
{
SelectionStartLine = 11,
SelectionStartColumn = 25,
SelectionEndLine = 11,
SelectionEndColumn = 35
},
new ReviewComment
{
Line = 15
}
}
};
var presenter = new FrmStandaloneReviewPresenter(mockView);
// Act
mockView.FireDeleteCommentToolStripMenuItemClickEvent(11, 30);
// Assert
Assert.IsTrue(mockView.AppState.CurrentReviewedFile.Comments.Exists(p => p.Line == 5));
Assert.IsTrue(mockView.AppState.CurrentReviewedFile.Comments.Exists(p => p.Line == 15));
Assert.AreEqual(2, mockView.AppState.CurrentReviewedFile.Comments.Count);
}
[TestMethod]
public void FrmStandaloneReviewDeleteComment_OneSelectionCommentsMarkerNotOnComment_ExpectItToBeDeleted()
{
// Arrange
var mockView = new MockFrmStandaloneReview();
mockView.AppState.CurrentReview = new Review
{
ReviewedFiles = new Dictionary<string, ReviewedFile>(),
Saved = true
};
mockView.AppState.CurrentReviewedFile = new ReviewedFile
{
Filename = "Test",
Comments = new List<ReviewComment>
{
new ReviewComment
{
Line = 5
},
new ReviewComment
{
SelectionStartLine = 11,
SelectionStartColumn = 25,
SelectionEndLine = 11,
SelectionEndColumn = 35
},
new ReviewComment
{
Line = 15
}
}
};
var presenter = new FrmStandaloneReviewPresenter(mockView);
// Act
mockView.FireDeleteCommentToolStripMenuItemClickEvent(11, 15);
// Assert
Assert.IsTrue(mockView.AppState.CurrentReviewedFile.Comments.Exists(p => p.Line == 5));
Assert.IsTrue(mockView.AppState.CurrentReviewedFile.Comments.Exists(p => p.SelectionStartLine == 11 && p.SelectionStartColumn == 25));
Assert.IsTrue(mockView.AppState.CurrentReviewedFile.Comments.Exists(p => p.Line == 15));
Assert.AreEqual(3, mockView.AppState.CurrentReviewedFile.Comments.Count);
}
[TestMethod]
public void FrmStandaloneReviewDeleteComment_OneLineCommentsMarker_ExpectItToBeDeleted()
{
// Arrange
var mockView = new MockFrmStandaloneReview();
mockView.AppState.CurrentReview = new Review
{
ReviewedFiles = new Dictionary<string, ReviewedFile>(),
Saved = true
};
mockView.AppState.CurrentReviewedFile = new ReviewedFile
{
Filename = "Test",
Comments = new List<ReviewComment>
{
new ReviewComment
{
Line = 5
},
new ReviewComment
{
SelectionStartLine = 11,
SelectionStartColumn = 25,
SelectionEndLine = 11,
SelectionEndColumn = 35
},
new ReviewComment
{
Line = 15
}
}
};
var presenter = new FrmStandaloneReviewPresenter(mockView);
// Act
mockView.FireDeleteCommentToolStripMenuItemClickEvent(5, 15);
// Assert
Assert.IsTrue(mockView.AppState.CurrentReviewedFile.Comments.Exists(p => p.SelectionStartLine == 11 && p.SelectionStartColumn == 25));
Assert.IsTrue(mockView.AppState.CurrentReviewedFile.Comments.Exists(p => p.Line == 15));
Assert.AreEqual(2, mockView.AppState.CurrentReviewedFile.Comments.Count);
}
[TestMethod]
public void FrmStandaloneReviewDeleteComment_BigSelectionComment_ExpectItToBeDeleted()
{
// Arrange
var mockView = new MockFrmStandaloneReview();
mockView.AppState.CurrentReview = new Review
{
ReviewedFiles = new Dictionary<string, ReviewedFile>(),
Saved = true
};
mockView.AppState.CurrentReviewedFile = new ReviewedFile
{
Filename = "Test",
Comments = new List<ReviewComment>
{
new ReviewComment
{
Line = 5
},
new ReviewComment
{
SelectionStartLine = 10,
SelectionStartColumn = 25,
SelectionEndLine = 20,
SelectionEndColumn = 35
},
new ReviewComment
{
Line = 25
}
}
};
var presenter = new FrmStandaloneReviewPresenter(mockView);
// Act
mockView.FireDeleteCommentToolStripMenuItemClickEvent(15, 65);
// Assert
Assert.IsTrue(mockView.AppState.CurrentReviewedFile.Comments.Exists(p => p.Line == 5));
Assert.IsTrue(mockView.AppState.CurrentReviewedFile.Comments.Exists(p => p.Line == 25));
Assert.AreEqual(2, mockView.AppState.CurrentReviewedFile.Comments.Count);
}
[TestMethod]
public void FrmStandaloneReviewDeleteComment_BigSelectionCommentCaretOnSelectionFirstLine_ExpectItToBeDeleted()
{
// Arrange
var mockView = new MockFrmStandaloneReview();
mockView.AppState.CurrentReview = new Review
{
ReviewedFiles = new Dictionary<string, ReviewedFile>(),
Saved = true
};
mockView.AppState.CurrentReviewedFile = new ReviewedFile
{
Filename = "Test",
Comments = new List<ReviewComment>
{
new ReviewComment
{
Line = 5
},
new ReviewComment
{
SelectionStartLine = 10,
SelectionStartColumn = 25,
SelectionEndLine = 20,
SelectionEndColumn = 35
},
new ReviewComment
{
Line = 25
}
}
};
var presenter = new FrmStandaloneReviewPresenter(mockView);
// Act
mockView.FireDeleteCommentToolStripMenuItemClickEvent(10, 30);
// Assert
Assert.IsTrue(mockView.AppState.CurrentReviewedFile.Comments.Exists(p => p.Line == 5));
Assert.IsTrue(mockView.AppState.CurrentReviewedFile.Comments.Exists(p => p.Line == 25));
Assert.AreEqual(2, mockView.AppState.CurrentReviewedFile.Comments.Count);
}
[TestMethod]
public void FrmStandaloneReviewDeleteComment_BigSelectionCommentCaretOnSelectionLastLine_ExpectItToBeDeleted()
{
// Arrange
var mockView = new MockFrmStandaloneReview();
mockView.AppState.CurrentReview = new Review
{
ReviewedFiles = new Dictionary<string, ReviewedFile>(),
Saved = true
};
mockView.AppState.CurrentReviewedFile = new ReviewedFile
{
Filename = "Test",
Comments = new List<ReviewComment>
{
new ReviewComment
{
Line = 5
},
new ReviewComment
{
SelectionStartLine = 10,
SelectionStartColumn = 25,
SelectionEndLine = 20,
SelectionEndColumn = 35
},
new ReviewComment
{
Line = 25
}
}
};
var presenter = new FrmStandaloneReviewPresenter(mockView);
// Act
mockView.FireDeleteCommentToolStripMenuItemClickEvent(20, 25);
// Assert
Assert.IsTrue(mockView.AppState.CurrentReviewedFile.Comments.Exists(p => p.Line == 5));
Assert.IsTrue(mockView.AppState.CurrentReviewedFile.Comments.Exists(p => p.Line == 25));
Assert.AreEqual(2, mockView.AppState.CurrentReviewedFile.Comments.Count);
}
[TestMethod]
public void FrmStandaloneReviewDeleteComment_VerifyCommentPositionsWhenFirstDeleted_ExpectAllPositionsDecremented()
{
// Arrange
var mockView = new MockFrmStandaloneReview();
mockView.AppState.CurrentReview = new Review
{
ReviewedFiles = new Dictionary<string, ReviewedFile>(),
Saved = true
};
mockView.AppState.CurrentReviewedFile = new ReviewedFile
{
Filename = "Test",
Comments = new List<ReviewComment>
{
new ReviewComment
{
Position = 0,
Line = 10
},
new ReviewComment
{
Position = 1,
Line = 1
},
new ReviewComment
{
Position = 2,
Line = 2
}
}
};
var presenter = new FrmStandaloneReviewPresenter(mockView);
// Act
mockView.FireDeleteCommentToolStripMenuItemClickEvent(10, 25);
// Assert
Assert.AreEqual(2, mockView.AppState.CurrentReviewedFile.Comments.Count);
var commentLine1 = mockView.AppState.CurrentReviewedFile.Comments.FirstOrDefault(p => p.Line == 1);
Assert.IsNotNull(commentLine1);
Assert.AreEqual(0, commentLine1.Position);
var commentLine2 = mockView.AppState.CurrentReviewedFile.Comments.FirstOrDefault(p => p.Line == 2);
Assert.IsNotNull(commentLine2);
Assert.AreEqual(1, commentLine2.Position);
}
[TestMethod]
public void FrmStandaloneReviewDeleteComment_VerifyCommentPositionsWhenMiddleDeleted_ExpectAllPositionsDecremented()
{
// Arrange
var mockView = new MockFrmStandaloneReview();
mockView.AppState.CurrentReview = new Review
{
ReviewedFiles = new Dictionary<string, ReviewedFile>(),
Saved = true
};
mockView.AppState.CurrentReviewedFile = new ReviewedFile
{
Filename = "Test",
Comments = new List<ReviewComment>
{
new ReviewComment
{
Position = 0,
Line = 10
},
new ReviewComment
{
Position = 1,
Line = 1
},
new ReviewComment
{
Position = 2,
Line = 2
}
}
};
var presenter = new FrmStandaloneReviewPresenter(mockView);
// Act
mockView.FireDeleteCommentToolStripMenuItemClickEvent(1, 25);
// Assert
Assert.AreEqual(2, mockView.AppState.CurrentReviewedFile.Comments.Count);
var commentLine1 = mockView.AppState.CurrentReviewedFile.Comments.FirstOrDefault(p => p.Line == 10);
Assert.IsNotNull(commentLine1);
Assert.AreEqual(0, commentLine1.Position);
var commentLine2 = mockView.AppState.CurrentReviewedFile.Comments.FirstOrDefault(p => p.Line == 2);
Assert.IsNotNull(commentLine2);
Assert.AreEqual(1, commentLine2.Position);
}
[TestMethod]
public void FrmStandaloneReviewDeleteComment_VerifyCommentPositionsWhenLastDeleted_ExpectAllPositionsDecremented()
{
// Arrange
var mockView = new MockFrmStandaloneReview();
mockView.AppState.CurrentReview = new Review
{
ReviewedFiles = new Dictionary<string, ReviewedFile>(),
Saved = true
};
mockView.AppState.CurrentReviewedFile = new ReviewedFile
{
Filename = "Test",
Comments = new List<ReviewComment>
{
new ReviewComment
{
Position = 0,
Line = 10
},
new ReviewComment
{
Position = 1,
Line = 1
},
new ReviewComment
{
Position = 2,
Line = 2
}
}
};
var presenter = new FrmStandaloneReviewPresenter(mockView);
// Act
mockView.FireDeleteCommentToolStripMenuItemClickEvent(2, 25);
// Assert
Assert.AreEqual(2, mockView.AppState.CurrentReviewedFile.Comments.Count);
var commentLine1 = mockView.AppState.CurrentReviewedFile.Comments.FirstOrDefault(p => p.Line == 10);
Assert.IsNotNull(commentLine1);
Assert.AreEqual(0, commentLine1.Position);
var commentLine2 = mockView.AppState.CurrentReviewedFile.Comments.FirstOrDefault(p => p.Line == 1);
Assert.IsNotNull(commentLine2);
Assert.AreEqual(1, commentLine2.Position);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;
using BulletSharp.Math;
using System.Diagnostics;
namespace BulletSharp
{
internal class ListDebugView
{
private System.Collections.IEnumerable _list;
public ListDebugView(System.Collections.IEnumerable list)
{
_list = list;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public System.Collections.ArrayList Items
{
get
{
var list = new System.Collections.ArrayList();
foreach (var o in _list)
list.Add(o);
return list;
}
}
};
internal class Vector3ListDebugView
{
private IList<Vector3> _list;
public Vector3ListDebugView(IList<Vector3> list)
{
_list = list;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public Vector3[] Items
{
get
{
Vector3[] arr = new Vector3[_list.Count];
_list.CopyTo(arr, 0);
return arr;
}
}
};
public class CompoundShapeChildArrayEnumerator : IEnumerator<CompoundShapeChild>
{
int _i;
int _count;
CompoundShapeChild[] _array;
public CompoundShapeChildArrayEnumerator(CompoundShapeChildArray array)
{
_array = array._backingArray;
_count = array.Count;
_i = -1;
}
public void Dispose()
{
}
public bool MoveNext()
{
_i++;
return _i != _count;
}
public void Reset()
{
_i = 0;
}
public CompoundShapeChild Current
{
get { return _array[_i]; }
}
object System.Collections.IEnumerator.Current
{
get { return _array[_i]; }
}
}
public class UIntArrayEnumerator : IEnumerator<uint>
{
int _i;
int _count;
IList<uint> _array;
public UIntArrayEnumerator(IList<uint> array)
{
_array = array;
_count = array.Count;
_i = -1;
}
public void Dispose()
{
}
public bool MoveNext()
{
_i++;
return _i != _count;
}
public void Reset()
{
_i = 0;
}
public uint Current
{
get { return _array[_i]; }
}
object System.Collections.IEnumerator.Current
{
get { return _array[_i]; }
}
}
public class Vector3ArrayEnumerator : IEnumerator<Vector3>
{
int _i;
int _count;
IList<Vector3> _array;
public Vector3ArrayEnumerator(IList<Vector3> array)
{
_array = array;
_count = array.Count;
_i = -1;
}
public void Dispose()
{
}
public bool MoveNext()
{
_i++;
return _i != _count;
}
public void Reset()
{
_i = 0;
}
public Vector3 Current
{
get { return _array[_i]; }
}
object System.Collections.IEnumerator.Current
{
get { return _array[_i]; }
}
}
public class FixedSizeArray
{
internal IntPtr _native;
protected int _count;
public FixedSizeArray(IntPtr native, int count)
{
_native = native;
_count = count;
}
public void Clear()
{
throw new InvalidOperationException();
}
public void RemoveAt(int index)
{
throw new NotSupportedException();
}
public int Count
{
get { return _count; }
}
public bool IsReadOnly
{
get { return false; }
}
}
public class CompoundShapeChildArray : FixedSizeArray, IList<CompoundShapeChild>
{
internal CompoundShapeChild[] _backingArray = new CompoundShapeChild[0];
internal CompoundShapeChildArray(IntPtr compoundShape)
: base(compoundShape, 0)
{
}
public void Add(CompoundShapeChild item)
{
throw new NotSupportedException();
}
public void AddChildShape(ref Matrix localTransform, CollisionShape shape)
{
IntPtr childListOld = (_count != 0) ? btCompoundShape_getChildList(_native) : IntPtr.Zero;
btCompoundShape_addChildShape(_native, ref localTransform, shape._native);
IntPtr childList = btCompoundShape_getChildList(_native);
// Adjust the native pointer of existing children if the array was reallocated.
if (childListOld != childList)
{
for (int i = 0; i < _count; i++)
{
_backingArray[i]._native = btCompoundShapeChild_array_at(childList, i);
}
}
// Add the child to the backing store.
int childIndex = _count;
_count++;
Array.Resize<CompoundShapeChild>(ref _backingArray, _count);
_backingArray[childIndex] = new CompoundShapeChild(btCompoundShapeChild_array_at(childList, childIndex), shape);
}
public int IndexOf(CompoundShapeChild item)
{
throw new NotImplementedException();
}
public CompoundShapeChild this[int index]
{
get { return _backingArray[index]; }
set
{
throw new NotImplementedException();
}
}
public bool Contains(CompoundShapeChild item)
{
throw new NotImplementedException();
}
public void CopyTo(CompoundShapeChild[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public IEnumerator<CompoundShapeChild> GetEnumerator()
{
return new CompoundShapeChildArrayEnumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new CompoundShapeChildArrayEnumerator(this);
}
public void Insert(int index, CompoundShapeChild item)
{
throw new InvalidOperationException();
}
public bool Remove(CompoundShapeChild item)
{
throw new NotSupportedException();
}
public void RemoveChildShape(CollisionShape shape)
{
IntPtr shapePtr = shape._native;
for (int i = 0; i < _count; i++)
{
if (_backingArray[i].ChildShape._native == shapePtr)
{
RemoveChildShapeByIndex(i);
}
}
}
internal void RemoveChildShapeByIndex(int childShapeIndex)
{
btCompoundShape_removeChildShapeByIndex(_native, childShapeIndex);
_count--;
// Swap the last item with the item to be removed like Bullet does.
if (childShapeIndex != _count)
{
CompoundShapeChild lastItem = _backingArray[_count];
lastItem._native = _backingArray[childShapeIndex]._native;
_backingArray[childShapeIndex] = lastItem;
}
_backingArray[_count] = null;
}
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btCompoundShape_addChildShape(IntPtr obj, [In] ref Matrix localTransform, IntPtr shape);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btCompoundShape_getChildList(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btCompoundShape_getNumChildShapes(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btCompoundShape_removeChildShape(IntPtr obj, IntPtr shape);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btCompoundShape_removeChildShapeByIndex(IntPtr obj, int childShapeindex);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btCompoundShapeChild_array_at(IntPtr obj, int n);
}
[DebuggerTypeProxy(typeof(ListDebugView))]
public class UIntArray : FixedSizeArray, IList<uint>
{
internal UIntArray(IntPtr native, int count)
: base(native, count)
{
}
public void Add(uint item)
{
throw new NotSupportedException();
}
public int IndexOf(uint item)
{
throw new NotImplementedException();
}
public uint this[int index]
{
get
{
if ((uint)index >= (uint)Count)
{
throw new ArgumentOutOfRangeException("index");
}
return (uint)Marshal.ReadInt32(_native.Add(index * sizeof(uint)));
}
set
{
Marshal.WriteInt32(_native, index * sizeof(uint), (int)value);
}
}
public bool Contains(uint item)
{
throw new NotImplementedException();
}
public void CopyTo(uint[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public IEnumerator<uint> GetEnumerator()
{
return new UIntArrayEnumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new UIntArrayEnumerator(this);
}
public void Insert(int index, uint item)
{
throw new InvalidOperationException();
}
public bool Remove(uint item)
{
throw new NotSupportedException();
}
}
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(Vector3ListDebugView))]
public class Vector3Array : FixedSizeArray, IList<Vector3>
{
internal Vector3Array(IntPtr native, int count)
: base(native, count)
{
}
public int IndexOf(Vector3 item)
{
throw new NotImplementedException();
}
public void Insert(int index, Vector3 item)
{
throw new NotSupportedException();
}
public Vector3 this[int index]
{
get
{
if ((uint)index >= (uint)Count)
{
throw new ArgumentOutOfRangeException("index");
}
Vector3 value;
btVector3_array_at(_native, index, out value);
return value;
}
set { btVector3_array_set(_native, index, ref value); }
}
public void Add(Vector3 item)
{
throw new NotSupportedException();
}
public bool Contains(Vector3 item)
{
throw new NotImplementedException();
}
public void CopyTo(Vector3[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("array");
int count = Count;
if (arrayIndex + count > array.Length)
throw new ArgumentException("Array too small.", "array");
for (int i = 0; i < count; i++)
{
array[arrayIndex + i] = this[i];
}
}
public bool Remove(Vector3 item)
{
throw new NotSupportedException();
}
public IEnumerator<Vector3> GetEnumerator()
{
return new Vector3ArrayEnumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Vector3ArrayEnumerator(this);
}
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btVector3_array_at(IntPtr obj, int n, [Out] out Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btVector3_array_set(IntPtr obj, int n, [In] ref Vector3 value);
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace MyApi.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Data
{
internal sealed class RecordManager
{
private readonly DataTable _table;
private int _lastFreeRecord;
private int _minimumCapacity = 50;
private int _recordCapacity = 0;
private readonly List<int> _freeRecordList = new List<int>();
private DataRow[] _rows;
internal RecordManager(DataTable table)
{
if (table == null)
{
throw ExceptionBuilder.ArgumentNull(nameof(table));
}
_table = table;
}
private void GrowRecordCapacity()
{
RecordCapacity = NewCapacity(_recordCapacity) < NormalizedMinimumCapacity(_minimumCapacity) ?
NormalizedMinimumCapacity(_minimumCapacity) :
NewCapacity(_recordCapacity);
// set up internal map : record --> row
DataRow[] newRows = _table.NewRowArray(_recordCapacity);
if (_rows != null)
{
Array.Copy(_rows, 0, newRows, 0, Math.Min(_lastFreeRecord, _rows.Length));
}
_rows = newRows;
}
internal int LastFreeRecord => _lastFreeRecord;
internal int MinimumCapacity
{
get { return _minimumCapacity; }
set
{
if (_minimumCapacity != value)
{
if (value < 0)
{
throw ExceptionBuilder.NegativeMinimumCapacity();
}
_minimumCapacity = value;
}
}
}
internal int RecordCapacity
{
get { return _recordCapacity; }
set
{
if (_recordCapacity != value)
{
for (int i = 0; i < _table.Columns.Count; i++)
{
_table.Columns[i].SetCapacity(value);
}
_recordCapacity = value;
}
}
}
internal static int NewCapacity(int capacity) =>
(capacity < 128) ? 128 : (capacity + capacity);
// Normalization: 64, 256, 1024, 2k, 3k, ....
private int NormalizedMinimumCapacity(int capacity)
{
if (capacity < 1024 - 10)
{
if (capacity < 256 - 10)
{
if (capacity < 54)
return 64;
return 256;
}
return 1024;
}
return (((capacity + 10) >> 10) + 1) << 10;
}
internal int NewRecordBase()
{
int record;
if (_freeRecordList.Count != 0)
{
record = _freeRecordList[_freeRecordList.Count - 1];
_freeRecordList.RemoveAt(_freeRecordList.Count - 1);
}
else
{
if (_lastFreeRecord >= _recordCapacity)
{
GrowRecordCapacity();
}
record = _lastFreeRecord;
_lastFreeRecord++;
}
Debug.Assert(record >= 0 && record < _recordCapacity, "NewRecord: Invalid record");
return record;
}
internal void FreeRecord(ref int record)
{
Debug.Assert(-1 <= record && record < _recordCapacity, "invalid record");
// Debug.Assert(record < lastFreeRecord, "Attempt to Free() <outofbounds> record");
if (-1 != record)
{
this[record] = null;
int count = _table._columnCollection.Count;
for (int i = 0; i < count; ++i)
{
_table._columnCollection[i].FreeRecord(record);
}
// if freeing the last record, recycle it
if (_lastFreeRecord == record + 1)
{
_lastFreeRecord--;
}
else if (record < _lastFreeRecord)
{
_freeRecordList.Add(record);
}
record = -1;
}
}
internal void Clear(bool clearAll)
{
if (clearAll)
{
for (int record = 0; record < _recordCapacity; ++record)
{
_rows[record] = null;
}
int count = _table._columnCollection.Count;
for (int i = 0; i < count; ++i)
{
// this improves performance by caching the column instead of obtaining it for each row
DataColumn column = _table._columnCollection[i];
for (int record = 0; record < _recordCapacity; ++record)
{
column.FreeRecord(record);
}
}
_lastFreeRecord = 0;
_freeRecordList.Clear();
}
else
{ // just clear attached rows
_freeRecordList.Capacity = _freeRecordList.Count + _table.Rows.Count;
for (int record = 0; record < _recordCapacity; ++record)
{
if (_rows[record] != null && _rows[record].rowID != -1)
{
int tempRecord = record;
FreeRecord(ref tempRecord);
}
}
}
}
internal DataRow this[int record]
{
get
{
Debug.Assert(record >= 0 && record < _rows.Length, "Invalid record number");
return _rows[record];
}
set
{
Debug.Assert(record >= 0 && record < _rows.Length, "Invalid record number");
_rows[record] = value;
}
}
internal void SetKeyValues(int record, DataKey key, object[] keyValues)
{
for (int i = 0; i < keyValues.Length; i++)
{
key.ColumnsReference[i][record] = keyValues[i];
}
}
// Increases AutoIncrementCurrent
internal int ImportRecord(DataTable src, int record)
{
return CopyRecord(src, record, -1);
}
// No impact on AutoIncrementCurrent if over written
internal int CopyRecord(DataTable src, int record, int copy)
{
Debug.Assert(src != null, "Can not Merge record without a table");
if (record == -1)
{
return copy;
}
int newRecord = -1;
try
{
newRecord = copy == -1 ?
_table.NewUninitializedRecord() :
copy;
int count = _table.Columns.Count;
for (int i = 0; i < count; ++i)
{
DataColumn dstColumn = _table.Columns[i];
DataColumn srcColumn = src.Columns[dstColumn.ColumnName];
if (null != srcColumn)
{
object value = srcColumn[record];
ICloneable cloneableObject = value as ICloneable;
if (null != cloneableObject)
{
dstColumn[newRecord] = cloneableObject.Clone();
}
else
{
dstColumn[newRecord] = value;
}
}
else if (-1 == copy)
{
dstColumn.Init(newRecord);
}
}
}
catch (Exception e) when (Common.ADP.IsCatchableOrSecurityExceptionType(e))
{
if (-1 == copy)
{
FreeRecord(ref newRecord);
}
throw;
}
return newRecord;
}
internal void SetRowCache(DataRow[] newRows)
{
_rows = newRows;
_lastFreeRecord = _rows.Length;
_recordCapacity = _lastFreeRecord;
}
[Conditional("DEBUG")]
internal void VerifyRecord(int record)
{
Debug.Assert((record < _lastFreeRecord) && (-1 == _freeRecordList.IndexOf(record)), "accessing free record");
Debug.Assert((null == _rows[record]) ||
(record == _rows[record]._oldRecord) ||
(record == _rows[record]._newRecord) ||
(record == _rows[record]._tempRecord), "record of a different row");
}
[Conditional("DEBUG")]
internal void VerifyRecord(int record, DataRow row)
{
Debug.Assert((record < _lastFreeRecord) && (-1 == _freeRecordList.IndexOf(record)), "accessing free record");
Debug.Assert((null == _rows[record]) || (row == _rows[record]), "record of a different row");
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.IO;
using Lucene.Net.Analysis.Tokenattributes;
using Lucene.Net.Support;
using NUnit.Framework;
using Analyzer = Lucene.Net.Analysis.Analyzer;
using TokenFilter = Lucene.Net.Analysis.TokenFilter;
using TokenStream = Lucene.Net.Analysis.TokenStream;
using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer;
using WhitespaceTokenizer = Lucene.Net.Analysis.WhitespaceTokenizer;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using Directory = Lucene.Net.Store.Directory;
using FSDirectory = Lucene.Net.Store.FSDirectory;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using UnicodeUtil = Lucene.Net.Util.UnicodeUtil;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using _TestUtil = Lucene.Net.Util._TestUtil;
namespace Lucene.Net.Index
{
[TestFixture]
public class TestPayloads:LuceneTestCase
{
private class AnonymousClassThread:ThreadClass
{
public AnonymousClassThread(int numDocs, System.String field, Lucene.Net.Index.TestPayloads.ByteArrayPool pool, Lucene.Net.Index.IndexWriter writer, TestPayloads enclosingInstance)
{
InitBlock(numDocs, field, pool, writer, enclosingInstance);
}
private void InitBlock(int numDocs, System.String field, Lucene.Net.Index.TestPayloads.ByteArrayPool pool, Lucene.Net.Index.IndexWriter writer, TestPayloads enclosingInstance)
{
this.numDocs = numDocs;
this.field = field;
this.pool = pool;
this.writer = writer;
this.enclosingInstance = enclosingInstance;
}
private int numDocs;
private System.String field;
private Lucene.Net.Index.TestPayloads.ByteArrayPool pool;
private Lucene.Net.Index.IndexWriter writer;
private TestPayloads enclosingInstance;
public TestPayloads Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
override public void Run()
{
try
{
for (int j = 0; j < numDocs; j++)
{
Document d = new Document();
d.Add(new Field(field, new PoolingPayloadTokenStream(enclosingInstance, pool)));
writer.AddDocument(d);
}
}
catch (System.Exception e)
{
System.Console.Error.WriteLine(e.StackTrace);
Assert.Fail(e.ToString());
}
}
}
// Simple tests to test the Payload class
[Test]
public virtual void TestPayload()
{
rnd = NewRandom();
byte[] testData = System.Text.UTF8Encoding.UTF8.GetBytes("This is a test!");
Payload payload = new Payload(testData);
Assert.AreEqual(testData.Length, payload.Length, "Wrong payload length.");
// test copyTo()
byte[] target = new byte[testData.Length - 1];
Assert.Throws<IndexOutOfRangeException>(() => payload.CopyTo(target, 0), "Expected exception not thrown");
target = new byte[testData.Length + 3];
payload.CopyTo(target, 3);
for (int i = 0; i < testData.Length; i++)
{
Assert.AreEqual(testData[i], target[i + 3]);
}
// test toByteArray()
target = payload.ToByteArray();
AssertByteArrayEquals(testData, target);
// test byteAt()
for (int i = 0; i < testData.Length; i++)
{
Assert.AreEqual(payload.ByteAt(i), testData[i]);
}
Assert.Throws<IndexOutOfRangeException>(() => payload.ByteAt(testData.Length + 1), "Expected exception not thrown");
Payload clone = (Payload) payload.Clone();
Assert.AreEqual(payload.Length, clone.Length);
for (int i = 0; i < payload.Length; i++)
{
Assert.AreEqual(payload.ByteAt(i), clone.ByteAt(i));
}
}
// Tests whether the DocumentWriter and SegmentMerger correctly enable the
// payload bit in the FieldInfo
[Test]
public virtual void TestPayloadFieldBit()
{
rnd = NewRandom();
Directory ram = new RAMDirectory();
PayloadAnalyzer analyzer = new PayloadAnalyzer();
IndexWriter writer = new IndexWriter(ram, analyzer, true, IndexWriter.MaxFieldLength.LIMITED);
Document d = new Document();
// this field won't have any payloads
d.Add(new Field("f1", "This field has no payloads", Field.Store.NO, Field.Index.ANALYZED));
// this field will have payloads in all docs, however not for all term positions,
// so this field is used to check if the DocumentWriter correctly enables the payloads bit
// even if only some term positions have payloads
d.Add(new Field("f2", "This field has payloads in all docs", Field.Store.NO, Field.Index.ANALYZED));
d.Add(new Field("f2", "This field has payloads in all docs", Field.Store.NO, Field.Index.ANALYZED));
// this field is used to verify if the SegmentMerger enables payloads for a field if it has payloads
// enabled in only some documents
d.Add(new Field("f3", "This field has payloads in some docs", Field.Store.NO, Field.Index.ANALYZED));
// only add payload data for field f2
analyzer.SetPayloadData("f2", 1, System.Text.UTF8Encoding.UTF8.GetBytes("somedata"), 0, 1);
writer.AddDocument(d);
// flush
writer.Close();
SegmentReader reader = SegmentReader.GetOnlySegmentReader(ram);
FieldInfos fi = reader.FieldInfos();
Assert.IsFalse(fi.FieldInfo("f1").storePayloads_ForNUnit, "Payload field bit should not be set.");
Assert.IsTrue(fi.FieldInfo("f2").storePayloads_ForNUnit, "Payload field bit should be set.");
Assert.IsFalse(fi.FieldInfo("f3").storePayloads_ForNUnit, "Payload field bit should not be set.");
reader.Close();
// now we add another document which has payloads for field f3 and verify if the SegmentMerger
// enabled payloads for that field
writer = new IndexWriter(ram, analyzer, true, IndexWriter.MaxFieldLength.LIMITED);
d = new Document();
d.Add(new Field("f1", "This field has no payloads", Field.Store.NO, Field.Index.ANALYZED));
d.Add(new Field("f2", "This field has payloads in all docs", Field.Store.NO, Field.Index.ANALYZED));
d.Add(new Field("f2", "This field has payloads in all docs", Field.Store.NO, Field.Index.ANALYZED));
d.Add(new Field("f3", "This field has payloads in some docs", Field.Store.NO, Field.Index.ANALYZED));
// add payload data for field f2 and f3
analyzer.SetPayloadData("f2", System.Text.UTF8Encoding.UTF8.GetBytes("somedata"), 0, 1);
analyzer.SetPayloadData("f3", System.Text.UTF8Encoding.UTF8.GetBytes("somedata"), 0, 3);
writer.AddDocument(d);
// force merge
writer.Optimize();
// flush
writer.Close();
reader = SegmentReader.GetOnlySegmentReader(ram);
fi = reader.FieldInfos();
Assert.IsFalse(fi.FieldInfo("f1").storePayloads_ForNUnit, "Payload field bit should not be set.");
Assert.IsTrue(fi.FieldInfo("f2").storePayloads_ForNUnit, "Payload field bit should be set.");
Assert.IsTrue(fi.FieldInfo("f3").storePayloads_ForNUnit, "Payload field bit should be set.");
reader.Close();
}
// Tests if payloads are correctly stored and loaded using both RamDirectory and FSDirectory
[Test]
public virtual void TestPayloadsEncoding()
{
rnd = NewRandom();
// first perform the test using a RAMDirectory
Directory dir = new RAMDirectory();
PerformTest(dir);
// now use a FSDirectory and repeat same test
System.IO.DirectoryInfo dirName = _TestUtil.GetTempDir("test_payloads");
dir = FSDirectory.Open(dirName);
PerformTest(dir);
_TestUtil.RmDir(dirName);
}
// builds an index with payloads in the given Directory and performs
// different tests to verify the payload encoding
private void PerformTest(Directory dir)
{
PayloadAnalyzer analyzer = new PayloadAnalyzer();
IndexWriter writer = new IndexWriter(dir, analyzer, true, IndexWriter.MaxFieldLength.LIMITED);
// should be in sync with value in TermInfosWriter
int skipInterval = 16;
int numTerms = 5;
System.String fieldName = "f1";
int numDocs = skipInterval + 1;
// create content for the test documents with just a few terms
Term[] terms = GenerateTerms(fieldName, numTerms);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < terms.Length; i++)
{
sb.Append(terms[i].Text);
sb.Append(" ");
}
System.String content = sb.ToString();
int payloadDataLength = numTerms * numDocs * 2 + numTerms * numDocs * (numDocs - 1) / 2;
byte[] payloadData = GenerateRandomData(payloadDataLength);
Document d = new Document();
d.Add(new Field(fieldName, content, Field.Store.NO, Field.Index.ANALYZED));
// add the same document multiple times to have the same payload lengths for all
// occurrences within two consecutive skip intervals
int offset = 0;
for (int i = 0; i < 2 * numDocs; i++)
{
analyzer.SetPayloadData(fieldName, payloadData, offset, 1);
offset += numTerms;
writer.AddDocument(d);
}
// make sure we create more than one segment to test merging
writer.Commit();
// now we make sure to have different payload lengths next at the next skip point
for (int i = 0; i < numDocs; i++)
{
analyzer.SetPayloadData(fieldName, payloadData, offset, i);
offset += i * numTerms;
writer.AddDocument(d);
}
writer.Optimize();
// flush
writer.Close();
/*
* Verify the index
* first we test if all payloads are stored correctly
*/
IndexReader reader = IndexReader.Open(dir, true);
byte[] verifyPayloadData = new byte[payloadDataLength];
offset = 0;
TermPositions[] tps = new TermPositions[numTerms];
for (int i = 0; i < numTerms; i++)
{
tps[i] = reader.TermPositions(terms[i]);
}
while (tps[0].Next())
{
for (int i = 1; i < numTerms; i++)
{
tps[i].Next();
}
int freq = tps[0].Freq;
for (int i = 0; i < freq; i++)
{
for (int j = 0; j < numTerms; j++)
{
tps[j].NextPosition();
tps[j].GetPayload(verifyPayloadData, offset);
offset += tps[j].PayloadLength;
}
}
}
for (int i = 0; i < numTerms; i++)
{
tps[i].Close();
}
AssertByteArrayEquals(payloadData, verifyPayloadData);
/*
* test lazy skipping
*/
TermPositions tp = reader.TermPositions(terms[0]);
tp.Next();
tp.NextPosition();
// now we don't read this payload
tp.NextPosition();
Assert.AreEqual(1, tp.PayloadLength, "Wrong payload length.");
byte[] payload = tp.GetPayload(null, 0);
Assert.AreEqual(payload[0], payloadData[numTerms]);
tp.NextPosition();
// we don't read this payload and skip to a different document
tp.SkipTo(5);
tp.NextPosition();
Assert.AreEqual(1, tp.PayloadLength, "Wrong payload length.");
payload = tp.GetPayload(null, 0);
Assert.AreEqual(payload[0], payloadData[5 * numTerms]);
/*
* Test different lengths at skip points
*/
tp.Seek(terms[1]);
tp.Next();
tp.NextPosition();
Assert.AreEqual(1, tp.PayloadLength, "Wrong payload length.");
tp.SkipTo(skipInterval - 1);
tp.NextPosition();
Assert.AreEqual(1, tp.PayloadLength, "Wrong payload length.");
tp.SkipTo(2 * skipInterval - 1);
tp.NextPosition();
Assert.AreEqual(1, tp.PayloadLength, "Wrong payload length.");
tp.SkipTo(3 * skipInterval - 1);
tp.NextPosition();
Assert.AreEqual(3 * skipInterval - 2 * numDocs - 1, tp.PayloadLength, "Wrong payload length.");
/*
* Test multiple call of getPayload()
*/
tp.GetPayload(null, 0);
// it is forbidden to call getPayload() more than once
// without calling nextPosition()
Assert.Throws<IOException>(() => tp.GetPayload(null, 0), "Expected exception not thrown");
reader.Close();
// test long payload
analyzer = new PayloadAnalyzer();
writer = new IndexWriter(dir, analyzer, true, IndexWriter.MaxFieldLength.LIMITED);
System.String singleTerm = "lucene";
d = new Document();
d.Add(new Field(fieldName, singleTerm, Field.Store.NO, Field.Index.ANALYZED));
// add a payload whose length is greater than the buffer size of BufferedIndexOutput
payloadData = GenerateRandomData(2000);
analyzer.SetPayloadData(fieldName, payloadData, 100, 1500);
writer.AddDocument(d);
writer.Optimize();
// flush
writer.Close();
reader = IndexReader.Open(dir, true);
tp = reader.TermPositions(new Term(fieldName, singleTerm));
tp.Next();
tp.NextPosition();
verifyPayloadData = new byte[tp.PayloadLength];
tp.GetPayload(verifyPayloadData, 0);
byte[] portion = new byte[1500];
Array.Copy(payloadData, 100, portion, 0, 1500);
AssertByteArrayEquals(portion, verifyPayloadData);
reader.Close();
}
private System.Random rnd;
private void GenerateRandomData(byte[] data)
{
rnd.NextBytes(data);
}
private byte[] GenerateRandomData(int n)
{
byte[] data = new byte[n];
GenerateRandomData(data);
return data;
}
private Term[] GenerateTerms(System.String fieldName, int n)
{
int maxDigits = (int) (System.Math.Log(n) / System.Math.Log(10));
Term[] terms = new Term[n];
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < n; i++)
{
sb.Length = 0;
sb.Append("t");
int zeros = maxDigits - (int) (System.Math.Log(i) / System.Math.Log(10));
for (int j = 0; j < zeros; j++)
{
sb.Append("0");
}
sb.Append(i);
terms[i] = new Term(fieldName, sb.ToString());
}
return terms;
}
internal virtual void AssertByteArrayEquals(byte[] b1, byte[] b2)
{
Assert.AreEqual(b1.Length, b2.Length, "Byte arrays have different lengths: " + b1.Length + ", " + b2.Length);
for (int i = 0; i < b1.Length; i++)
{
Assert.AreEqual(b1[i], b2[i], "Byte arrays different at index " + i + ": " + b1[i] + ", " + b2[i]);
}
}
/// <summary> This Analyzer uses an WhitespaceTokenizer and PayloadFilter.</summary>
private class PayloadAnalyzer:Analyzer
{
internal System.Collections.IDictionary fieldToData = new System.Collections.Hashtable();
internal virtual void SetPayloadData(System.String field, byte[] data, int offset, int length)
{
fieldToData[field] = new PayloadData(0, data, offset, length);
}
internal virtual void SetPayloadData(System.String field, int numFieldInstancesToSkip, byte[] data, int offset, int length)
{
fieldToData[field] = new PayloadData(numFieldInstancesToSkip, data, offset, length);
}
public override TokenStream TokenStream(System.String fieldName, System.IO.TextReader reader)
{
PayloadData payload = (PayloadData) fieldToData[fieldName];
TokenStream ts = new WhitespaceTokenizer(reader);
if (payload != null)
{
if (payload.numFieldInstancesToSkip == 0)
{
ts = new PayloadFilter(ts, payload.data, payload.offset, payload.length);
}
else
{
payload.numFieldInstancesToSkip--;
}
}
return ts;
}
private class PayloadData
{
internal byte[] data;
internal int offset;
internal int length;
internal int numFieldInstancesToSkip;
internal PayloadData(int skip, byte[] data, int offset, int length)
{
numFieldInstancesToSkip = skip;
this.data = data;
this.offset = offset;
this.length = length;
}
}
}
/// <summary> This Filter adds payloads to the tokens.</summary>
private class PayloadFilter:TokenFilter
{
private byte[] data;
private int length;
private int offset;
internal Payload payload = new Payload();
internal IPayloadAttribute payloadAtt;
public PayloadFilter(TokenStream in_Renamed, byte[] data, int offset, int length):base(in_Renamed)
{
this.data = data;
this.length = length;
this.offset = offset;
payloadAtt = AddAttribute<IPayloadAttribute>();
}
public override bool IncrementToken()
{
bool hasNext = input.IncrementToken();
if (hasNext)
{
if (offset + length <= data.Length)
{
Payload p = null;
if (p == null)
{
p = new Payload();
payloadAtt.Payload = p;
}
p.SetData(data, offset, length);
offset += length;
}
else
{
payloadAtt.Payload = null;
}
}
return hasNext;
}
}
[Test]
public virtual void TestThreadSafety()
{
rnd = NewRandom();
int numThreads = 5;
int numDocs = 50;
ByteArrayPool pool = new ByteArrayPool(numThreads, 5);
Directory dir = new RAMDirectory();
IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.LIMITED);
System.String field = "test";
ThreadClass[] ingesters = new ThreadClass[numThreads];
for (int i = 0; i < numThreads; i++)
{
ingesters[i] = new AnonymousClassThread(numDocs, field, pool, writer, this);
ingesters[i].Start();
}
for (int i = 0; i < numThreads; i++)
{
ingesters[i].Join();
}
writer.Close();
IndexReader reader = IndexReader.Open(dir, true);
TermEnum terms = reader.Terms();
while (terms.Next())
{
TermPositions tp = reader.TermPositions(terms.Term);
while (tp.Next())
{
int freq = tp.Freq;
for (int i = 0; i < freq; i++)
{
tp.NextPosition();
Assert.AreEqual(pool.BytesToString(tp.GetPayload(new byte[5], 0)), terms.Term.Text);
}
}
tp.Close();
}
terms.Close();
reader.Close();
Assert.AreEqual(pool.Size(), numThreads);
}
private class PoolingPayloadTokenStream:TokenStream
{
private void InitBlock(TestPayloads enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private TestPayloads enclosingInstance;
public TestPayloads Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
private byte[] payload;
private bool first;
private ByteArrayPool pool;
private System.String term;
internal ITermAttribute termAtt;
internal IPayloadAttribute payloadAtt;
internal PoolingPayloadTokenStream(TestPayloads enclosingInstance, ByteArrayPool pool)
{
InitBlock(enclosingInstance);
this.pool = pool;
payload = pool.Get();
Enclosing_Instance.GenerateRandomData(payload);
term = pool.BytesToString(payload);
first = true;
payloadAtt = AddAttribute<IPayloadAttribute>();
termAtt = AddAttribute<ITermAttribute>();
}
public override bool IncrementToken()
{
if (!first)
return false;
first = false;
ClearAttributes();
termAtt.SetTermBuffer(term);
payloadAtt.Payload = new Payload(payload);
return true;
}
protected override void Dispose(bool disposing)
{
pool.Release(payload);
}
}
internal class ByteArrayPool
{
private System.Collections.IList pool;
internal ByteArrayPool(int capacity, int size)
{
pool = new System.Collections.ArrayList();
for (int i = 0; i < capacity; i++)
{
pool.Add(new byte[size]);
}
}
private UnicodeUtil.UTF8Result utf8Result = new UnicodeUtil.UTF8Result();
internal virtual System.String BytesToString(byte[] bytes)
{
lock (this)
{
System.String s = System.Text.Encoding.Default.GetString(bytes);
UnicodeUtil.UTF16toUTF8(s, 0, s.Length, utf8Result);
try
{
return System.Text.Encoding.UTF8.GetString(utf8Result.result, 0, utf8Result.length);
}
catch (System.IO.IOException uee)
{
return null;
}
}
}
internal virtual byte[] Get()
{
lock (this)
{
System.Object tempObject;
tempObject = pool[0];
pool.RemoveAt(0);
return (byte[]) tempObject;
}
}
internal virtual void Release(byte[] b)
{
lock (this)
{
pool.Add(b);
}
}
internal virtual int Size()
{
lock (this)
{
return pool.Count;
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.Collections.Tests
{
public class ReadOnlyCollectionBaseTests
{
[Fact]
public void TesReadOnlyCollectionBasBasic()
{
MyReadOnlyCollectionBase mycol1;
MyReadOnlyCollectionBase mycol2;
Foo f1;
Foo[] arrF1;
Foo[] arrF2;
IEnumerator enu1;
int iCount;
object obj1;
ReadOnlyCollectionBase collectionBase;
//[]ReadOnlyCollectionBase implements IList (which means both ICollection and IEnumerator as well :-()
//To test this class, we will implement our own strongly typed ReadOnlyCollectionBase and call its methods
//[] SyncRoot property
arrF1 = new Foo[100];
for (int i = 0; i < 100; i++)
arrF1[i] = new Foo();
mycol1 = new MyReadOnlyCollectionBase(arrF1);
Assert.False(mycol1.SyncRoot is ArrayList, "Error SyncRoot returned ArrayList");
//[] Count property
arrF1 = new Foo[100];
for (int i = 0; i < 100; i++)
arrF1[i] = new Foo();
mycol1 = new MyReadOnlyCollectionBase(arrF1);
Assert.Equal(100, mycol1.Count);
//[]CopyTo
arrF2 = new Foo[100];
for (int i = 0; i < 100; i++)
arrF2[i] = new Foo(i, i.ToString());
mycol1 = new MyReadOnlyCollectionBase(arrF2);
arrF1 = new Foo[100];
mycol1.CopyTo(arrF1, 0);
for (int i = 0; i < 100; i++)
{
Assert.Equal(i, arrF1[i].IValue);
Assert.Equal(i.ToString(), arrF1[i].SValue);
}
//Argument checking
arrF2 = new Foo[100];
for (int i = 0; i < 100; i++)
arrF2[i] = new Foo(i, i.ToString());
mycol1 = new MyReadOnlyCollectionBase(arrF2);
arrF1 = new Foo[100];
Assert.Throws<ArgumentException>(() =>
{
mycol1.CopyTo(arrF1, 50);
}
);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
mycol1.CopyTo(arrF1, -1);
}
);
arrF1 = new Foo[200];
mycol1.CopyTo(arrF1, 100);
for (int i = 0; i < 100; i++)
{
Assert.Equal(i, arrF1[100 + i].IValue);
Assert.Equal(i.ToString(), arrF1[100 + i].SValue);
}
//[]GetEnumerator
arrF2 = new Foo[100];
for (int i = 0; i < 100; i++)
arrF2[i] = new Foo(i, i.ToString());
mycol1 = new MyReadOnlyCollectionBase(arrF2);
enu1 = mycol1.GetEnumerator();
//Calling current should throw here
Assert.Throws<InvalidOperationException>(() =>
{
f1 = (Foo)enu1.Current;
}
);
iCount = 0;
while (enu1.MoveNext())
{
f1 = (Foo)enu1.Current;
Assert.False((f1.IValue != iCount) || (f1.SValue != iCount.ToString()), "Error, does not match, " + f1.IValue);
iCount++;
}
Assert.Equal(100, iCount);
//Calling current should throw here
Assert.Throws<InvalidOperationException>(() =>
{
f1 = (Foo)enu1.Current;
}
);
//[]IsSynchronized
arrF2 = new Foo[100];
for (int i = 0; i < 100; i++)
arrF2[i] = new Foo(i, i.ToString());
Assert.False(((ICollection)mycol1).IsSynchronized);
//[]SyncRoot
arrF2 = new Foo[100];
for (int i = 0; i < 100; i++)
arrF2[i] = new Foo(i, i.ToString());
obj1 = mycol1.SyncRoot;
mycol2 = mycol1;
Assert.Equal(obj1, mycol2.SyncRoot);
//End of ICollection and IEnumerator methods
//Now to IList methods
//[]this, Contains, IndexOf
arrF2 = new Foo[100];
for (int i = 0; i < 100; i++)
arrF2[i] = new Foo(i, i.ToString());
mycol1 = new MyReadOnlyCollectionBase(arrF2);
for (int i = 0; i < 100; i++)
{
Assert.False((mycol1[i].IValue != i) || (mycol1[i].SValue != i.ToString()));
Assert.False((mycol1.IndexOf(new Foo(i, i.ToString())) != i));
Assert.False((!mycol1.Contains(new Foo(i, i.ToString()))));
}
//[]Rest of the IList methods: IsFixedSize, IsReadOnly
arrF2 = new Foo[100];
for (int i = 0; i < 100; i++)
arrF2[i] = new Foo(i, i.ToString());
mycol1 = new MyReadOnlyCollectionBase(arrF2);
Assert.True(mycol1.IsFixedSize);
Assert.True(mycol1.IsReadOnly);
//The following operations are not allowed by the compiler. Hence, commented out
arrF2 = new Foo[100];
for (int i = 0; i < 100; i++)
arrF2[i] = new Foo(i, i.ToString());
mycol1 = new MyReadOnlyCollectionBase(arrF2);
//[] Verify Count is virtual
collectionBase = new VirtualTestReadOnlyCollection();
Assert.Equal(collectionBase.Count, int.MinValue);
//[] Verify Count is virtual
collectionBase = new VirtualTestReadOnlyCollection();
Assert.Null(collectionBase.GetEnumerator());
}
//ReadOnlyCollectionBase is provided to be used as the base class for strongly typed collections. Lets use one of our own here.
//This collection only allows the type Foo
public class MyReadOnlyCollectionBase : ReadOnlyCollectionBase
{
//we need a way of initializing this collection
public MyReadOnlyCollectionBase(Foo[] values)
{
InnerList.AddRange(values);
}
public Foo this[int indx]
{
get { return (Foo)InnerList[indx]; }
}
public void CopyTo(Array array, int index)
{
((ICollection)this).CopyTo(array, index);// Use the base class explicit implemenation of ICollection.CopyTo
}
public virtual object SyncRoot
{
get
{
return ((ICollection)this).SyncRoot;// Use the base class explicit implemenation of ICollection.SyncRoot
}
}
public int IndexOf(Foo f)
{
return ((IList)InnerList).IndexOf(f);
}
public Boolean Contains(Foo f)
{
return ((IList)InnerList).Contains(f);
}
public Boolean IsFixedSize
{
get { return true; }
}
public Boolean IsReadOnly
{
get { return true; }
}
}
public class VirtualTestReadOnlyCollection : ReadOnlyCollectionBase
{
public override int Count
{
get
{
return int.MinValue;
}
}
public override IEnumerator GetEnumerator()
{
return null;
}
}
public class Foo
{
private int _iValue;
private String _strValue;
public Foo()
{
}
public Foo(int i, String str)
{
_iValue = i;
_strValue = str;
}
public int IValue
{
get { return _iValue; }
set { _iValue = value; }
}
public String SValue
{
get { return _strValue; }
set { _strValue = value; }
}
public override Boolean Equals(object obj)
{
if (obj == null)
return false;
if (!(obj is Foo))
return false;
if ((((Foo)obj).IValue == _iValue) && (((Foo)obj).SValue == _strValue))
return true;
return false;
}
public override int GetHashCode()
{
return _iValue;
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PanZoomGestureRecognizer.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Recognizes drag/pinch multitouch gestures and translates them into pan/zoom information.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace OxyPlot.Xamarin.iOS
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Foundation;
using UIKit;
/// <summary>
/// Recognizes drag/pinch multitouch gestures and translates them into pan/zoom information.
/// </summary>
public class PanZoomGestureRecognizer : UIGestureRecognizer
{
/// <summary>
/// Up to 2 touches being currently tracked in a pan/zoom.
/// </summary>
private List<UITouch> activeTouches = new List<UITouch>();
// Distance between touchpoints when the second touchpoint begins. Used to determine
// whether the touchpoints cross along a given axis during the zoom gesture.
//
private ScreenVector startingDistance = default(ScreenVector);
/// <summary>
/// Gets or sets a value indicating whether this <see cref="OxyPlot.Xamarin.iOS.PanZoomGestureRecognizer"/> keeps the aspect ratio when pinching.
/// </summary>
/// <value><c>true</c> if keep aspect ratio when pinching; otherwise, <c>false</c>.</value>
public bool KeepAspectRatioWhenPinching { get; set; }
/// <summary>
/// How far apart touch points must be on a certain axis to enable scaling that axis.
/// (only applies if KeepAspectRatioWhenPinching is <c>false</c>)
/// </summary>
public double ZoomThreshold { get; set; }
/// <summary>
/// If <c>true</c>, and KeepAspectRatioWhenPinching is <c>false</c>, a zoom-out gesture
/// can turn into a zoom-in gesture if the fingers cross. Setting to <c>false</c> will
/// instead simply stop the zoom at that point.
/// </summary>
public bool AllowPinchPastZero { get; set; }
/// <summary>
/// The current calculated pan/zoom changes
/// </summary>
public OxyTouchEventArgs TouchEventArgs { get; set; }
public PanZoomGestureRecognizer()
{
this.ZoomThreshold = 20d;
this.AllowPinchPastZero = true;
}
/// <summary>
/// Called when a touch gesture begins.
/// </summary>
/// <param name="touches">The touches.</param>
/// <param name="evt">The event arguments.</param>
public override void TouchesBegan(NSSet touches, UIEvent evt)
{
base.TouchesBegan(touches, evt);
if (this.activeTouches.Count >= 2)
{
// we already have two touches
return;
}
// Grab 1-2 touches to track
var newTouches = touches.ToArray<UITouch>();
var firstTouch = !this.activeTouches.Any();
activeTouches.AddRange(newTouches.Take(2 - this.activeTouches.Count));
if (firstTouch)
{
// HandleTouchStarted initializes the entire multitouch gesture,
// with the first touch used for panning.
//
TouchEventArgs = this.activeTouches.First().ToTouchEventArgs(this.View);
}
CalculateStartingDistance();
}
/// <summary>
/// Called when a touch gesture is moving.
/// </summary>
/// <param name="touches">The touches.</param>
/// <param name="evt">The event arguments.</param>
public override void TouchesMoved(NSSet touches, UIEvent evt)
{
base.TouchesMoved(touches, evt);
if (activeTouches.Any(touch => touch.Phase == UITouchPhase.Moved))
{
// get current and previous location of the first touch point
var t1 = this.activeTouches.First();
var l1 = t1.LocationInView(this.View).ToScreenPoint();
var pl1 = t1.Phase == UITouchPhase.Moved ? t1.PreviousLocationInView(this.View).ToScreenPoint() : l1;
var l = l1;
var t = l1 - pl1;
var s = new ScreenVector(1, 1);
if (activeTouches.Count > 1)
{
// get current and previous location of the second touch point
var t2 = this.activeTouches.ElementAt(1);
var l2 = t2.LocationInView(this.View).ToScreenPoint();
var pl2 = t2.Phase == UITouchPhase.Moved ? t2.PreviousLocationInView(this.View).ToScreenPoint() : l2;
var d = l1 - l2;
var pd = pl1 - pl2;
if (!this.KeepAspectRatioWhenPinching)
{
if (!this.AllowPinchPastZero)
{
// Don't allow fingers crossing in a zoom-out gesture to turn it back into a zoom-in gesture
d = PreventCross(d);
}
var scalex = CalculateScaleFactor(d.X, pd.X);
var scaley = CalculateScaleFactor(d.Y, pd.Y);
s = new ScreenVector(scalex, scaley);
}
else
{
var scale = pd.Length > 0 ? d.Length / pd.Length : 1;
s = new ScreenVector(scale, scale);
}
}
var e = new OxyTouchEventArgs { Position = l, DeltaTranslation = t, DeltaScale = s };
this.TouchEventArgs = e;
this.State = UIGestureRecognizerState.Changed;
}
}
/// <summary>
/// Called when a touch gesture ends.
/// </summary>
/// <param name="touches">The touches.</param>
/// <param name="evt">The event arguments.</param>
public override void TouchesEnded(NSSet touches, UIEvent evt)
{
base.TouchesEnded(touches, evt);
// We already have the only two touches we care about, so ignore the params
//
var secondTouch = this.activeTouches.ElementAtOrDefault(1);
if (secondTouch != null && secondTouch.Phase == UITouchPhase.Ended)
{
this.activeTouches.Remove(secondTouch);
}
var firstTouch = this.activeTouches.FirstOrDefault();
if (firstTouch != null && firstTouch.Phase == UITouchPhase.Ended)
{
this.activeTouches.Remove(firstTouch);
if (!this.activeTouches.Any())
{
TouchEventArgs = firstTouch.ToTouchEventArgs(this.View);
State = UIGestureRecognizerState.Ended;
}
}
}
/// <summary>
/// Called when a touch gesture is cancelled.
/// </summary>
/// <param name="touches">The touches.</param>
/// <param name="evt">The event arguments.</param>
public override void TouchesCancelled(NSSet touches, UIEvent evt)
{
base.TouchesCancelled(touches, evt);
// TODO: Is it possible for one touch to be canceled while others remain in play?
var touch = this.activeTouches.FirstOrDefault();
if (touch != null && touch.Phase == UITouchPhase.Cancelled)
{
TouchEventArgs = touch.ToTouchEventArgs(this.View);
State = UIGestureRecognizerState.Cancelled;
}
}
private double CalculateScaleFactor(double distance, double previousDistance)
{
return Math.Abs(previousDistance) > this.ZoomThreshold
&& Math.Abs(distance) > this.ZoomThreshold
? Math.Abs(distance / previousDistance)
: 1;
}
private void CalculateStartingDistance()
{
if (this.activeTouches.Count < 2)
{
this.startingDistance = default(ScreenVector);
return;
}
var loc1 = this.activeTouches.ElementAt(0).LocationInView(this.View).ToScreenPoint();
var loc2 = this.activeTouches.ElementAt(1).LocationInView(this.View).ToScreenPoint();
this.startingDistance = loc1 - loc2;
}
private ScreenVector PreventCross(ScreenVector currentDistance)
{
var x = currentDistance.X;
var y = currentDistance.Y;
if (DidDirectionChange(x, this.startingDistance.X))
{
x = 0;
}
if (DidDirectionChange(y, this.startingDistance.Y))
{
y = 0;
}
return new ScreenVector(x, y);
}
private static bool DidDirectionChange(double current, double original)
{
return ((current >= 0) != (original >= 0));
}
}
}
| |
// Application.Bindings.cs
// Script#/FX/Sharpen/Core
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Html;
using Sharpen.Bindings;
namespace Sharpen {
public sealed partial class Application {
private static Binder BindContent(Element element, string property, Expression expression) {
property = (property == "text") ? "textContent" : "innerHTML";
return new ContentBinder(element, property, expression);
}
private static Binder BindValue(Element element, string property, Expression expression) {
Debug.Assert((element.TagName.ToLowerCase() == "input") ||
(element.TagName.ToLowerCase() == "textarea") ||
(element.TagName.ToLowerCase() == "select"),
"Value can only be bound on user input elements.");
return new ValueBinder((InputElement)element, expression);
}
private static Binder BindVisibility(Element element, string property, Expression expression) {
return new VisibilityBinder(element, property, expression);
}
private static Expression ProcessModelExpression(object model, string expressionType, string value) {
Debug.Assert(Script.GetField(model, value) != null, "The model does not have a member named '" + value + '"');
if (expressionType == "exec") {
// TODO: Support scenarios where value is parent.method, or root.method (for invoking
// a method on the parent model or root model... useful in templating scenarios
// where items are not bound to view model but an object retrieved from the
// view model.
// When the expression is exec, the value is interpreted as a reference to a method
// on the model. An invoker function is created that when called invokes the referenced
// method in context of the model instance. The expression itself contains a delegate
// to this dynamically created invoker function.
// function _(e) {
// var result = this.modelMethod(e, this);
// if (result) { e.preventDefault(); }
// }
// TODO: If bound to parent/root, generated this instead:
// function _(e) {
// var model = Application.Current.GetModel(element.parentElement);
// var result = this.modelMethod(e, model);
// if (result) { e.preventDefault(); }
// }
string invokerCode = "var result = this." + value + "(e, this); if (result) { e.preventDefault(); }";
return new Expression(Delegate.Create(new Function(invokerCode, "e", "model"), model), /* canChange */ false);
}
// TODO: Eventually stop with the () business if we can switch over to true properties
// with getter/setter accessors in javascript.
// Check if the value is something like A.B.C, where A, B and C are identifiers.
bool propertyPathExpression = PropertyPathRegex.Test(value);
// The value represents a string that contains a script expression for properties off
// the model.
string getterCode;
if (propertyPathExpression) {
// If its a simple property path, then we parenthesize since in script, the
// properties are represented as functions.
value = value.Replace(".", "().");
getterCode = "return model." + value + "();";
}
else {
// If its not a simple property path, we're going to assume that the developer
// has referenced the property functions themselves, and we use as-is.
getterCode = "with(model) { return " + value + "; }";
}
Func<object, object> getter = (Func<object, object>)(object)new Function(getterCode, "model");
if (expressionType == "init") {
// Read-only, one-time binder... so execute the getter, and create
// an expression with the current value.
return new Expression(getter(model), /* canChange */ false);
}
else if (expressionType == "link") {
// Read-only, bound binder... create a BindExpression that tracks the
// value by observing any observables representing the property.
return new BindExpression(model, getter, null);
}
else {
// Read-write, bound binder ... must be a simple property path.
if (propertyPathExpression == false) {
Debug.Fail("A bind expression's value must be a property path. The expression '" + value + "' is invalid.");
}
string setterCode = "model." + value + "(value);";
Action<object, object> setter = (Action<object, object>)(object)new Function(setterCode, "model", "value");
return new BindExpression(model, getter, setter);
}
}
/// <summary>
/// Registers a binder factory. The supplied name prefixed with "data-" is used
/// as the attribute name in markup to create a binder.
/// </summary>
/// <param name="name">The name of the expression handler.</param>
/// <param name="factory">The factory being registered.</param>
public void RegisterBinder(string name, BinderFactory factory) {
Debug.Assert(String.IsNullOrEmpty(name) == false);
Debug.Assert(factory != null);
Debug.Assert(_registeredBinders.ContainsKey(name) == false, "A binder with name '" + name + "' was already registered.");
_registeredBinders[name] = factory;
}
/// <summary>
/// Registers an expression factory. The supplied name is used in markup to represent
/// an instance of the associated expression.
/// </summary>
/// <param name="name">The name of expression.</param>
/// <param name="factory">The factory to be used to handle the supplied name.</param>
public void RegisterExpression(string name, ExpressionFactory factory) {
Debug.Assert(String.IsNullOrEmpty(name) == false);
Debug.Assert(factory != null);
Debug.Assert(_registeredExpressions.ContainsKey(name) == false, "An expression factory with name '" + name + "' was already registered.");
_registeredExpressions[name] = factory;
}
private void SetupBindings(Element element, object model) {
Debug.Assert(element != null);
string bindings = (string)element.GetAttribute(Application.BindingsAttribute);
bindings.ReplaceRegex(Application.BindingsRegex, delegate(string match /*, string binderType, string expressionType, string expressionValue */) {
string binderType = (string)Arguments.GetArgument(1);
string expressionType = (string)Arguments.GetArgument(2);
string expressionValue = (string)Arguments.GetArgument(3);
ExpressionFactory expressionFactory = _registeredExpressions[expressionType];
Debug.Assert(expressionFactory != null, "Unknown expression of type '" + expressionType + "' found.");
if (expressionFactory != null) {
Expression expression = expressionFactory(model, expressionType, expressionValue);
Binder binder = null;
// TODO: Add support for binding attributes - @xxx
if (binderType.StartsWith("on.")) {
Debug.Assert(expression.CanChange == false, "Events cannot be bound to dynamic expressions.");
Debug.Assert(expression.GetValue() is Action);
binder = new EventBinder(element, binderType.Substr(3), (ElementEventListener)expression.GetValue());
}
else if (binderType.StartsWith("style.")) {
object style = element.Style;
binder = new PropertyBinder(style, binderType.Substr(6), expression);
}
else {
BinderFactory binderFactory = _registeredBinders[binderType];
if (binderFactory == null) {
binder = new PropertyBinder(element, binderType, expression);
}
else {
binder = binderFactory(element, binderType, expression);
}
}
if (binder != null) {
binder.Update();
if (expression.CanChange == false) {
// Since the expression value cannot change, there isn't a whole lot of need
// to keep the binder alive and manage it.
binder = null;
}
}
if (binder != null) {
// The binder is managed using a behavior that is attached to the element.
// This allows stashing the model for later retrieval, as well as a way to
// dispose bindings (the behavior disposes all binders it is managing).
BinderManager binderManager = (BinderManager)Behavior.GetBehavior(element, typeof(BinderManager));
if (binderManager == null) {
binderManager = new BinderManager();
binderManager.Initialize(element, null);
binderManager.Model = model;
}
binderManager.AddBinder(binder);
}
}
return String.Empty;
});
}
}
}
| |
#region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.SuperDom;
using NinjaTrader.Gui.Tools;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.Core.FloatingPoint;
using NinjaTrader.NinjaScript.DrawingTools;
#endregion
//This namespace holds Indicators in this folder and is required. Do not change it.
namespace NinjaTrader.NinjaScript.Indicators
{
public class ADXTrend : Indicator
{
enum BarState { Transition, UpTrend, DownTrend, Randomeness };
private BarState currentBarState, lastBarState, secondLastBarState;
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"";
Name = "ADXTrend";
Calculate = Calculate.OnBarClose;
IsOverlay = false;
DisplayInDataBox = true;
DrawOnPricePanel = true;
DrawHorizontalGridLines = true;
DrawVerticalGridLines = true;
PaintPriceMarkers = true;
ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
//Disable this property if your indicator requires custom values that cumulate with each new market data event.
//See Help Guide for additional information.
IsSuspendedWhileInactive = true;
TransitionColor = Brushes.DarkGreen;
UpTrendColor = Brushes.Green;
DownTrendColor = Brushes.Red;
RandomnessColor = Brushes.White;
AddPlot(new Stroke(Brushes.Orange, 6), PlotStyle.Bar, "BarPlot");
}
else if (State == State.Configure)
{
}
}
protected override void OnBarUpdate()
{
if (CurrentBar < 4)
{
return;
}
else if (CurrentBar == 4)
{
PlotBrushes[0][0] = TransitionColor;
lastBarState = BarState.Transition;
BarPlot[0] = 1.0;
return;
}
if (lastBarState == BarState.Transition)
{
if (isUptick())
{
if (secondLastBarState == BarState.Transition)
{
setUpTrend();
}
else
{
setTransition();
}
}
else
{
setRandomness();
}
}
else if (lastBarState == BarState.UpTrend)
{
if (isUptick())
{
setUpTrend();
}
else if (!isUptick(1))
{
setRandomness();
}
else
{
setUpTrend();
}
}
else if (lastBarState == BarState.Randomeness)
{
if (isUptick())
{
setTransition();
}
else if (secondLastBarState == BarState.Randomeness)
{
setDownTrend();
}
else
{
setRandomness();
}
}
else if (lastBarState == BarState.DownTrend)
{
if (!isUptick())
{
setDownTrend();
}
else
{
setTransition();
}
}
secondLastBarState = lastBarState;
lastBarState = currentBarState;
BarPlot[0] = 1.0;
}
private bool isUptick(int period = 0)
{
return Input[0 + period] > Input[1 + period];
}
private void setUpTrend()
{
PlotBrushes[0][0] = UpTrendColor;
currentBarState = BarState.UpTrend;
}
private void setDownTrend()
{
PlotBrushes[0][0] = DownTrendColor;
currentBarState = BarState.DownTrend;
}
private void setRandomness()
{
PlotBrushes[0][0] = RandomnessColor;
currentBarState = BarState.Randomeness;
}
private void setTransition()
{
PlotBrushes[0][0] = TransitionColor;
currentBarState = BarState.Transition;
}
#region Properties
[NinjaScriptProperty]
[XmlIgnore]
[Display(Name="TransitionColor", Order=1, GroupName="Parameters")]
public Brush TransitionColor
{ get; set; }
[Browsable(false)]
public string TransitionColorSerializable
{
get { return Serialize.BrushToString(TransitionColor); }
set { TransitionColor = Serialize.StringToBrush(value); }
}
[NinjaScriptProperty]
[XmlIgnore]
[Display(Name="UpTrendColor", Order=2, GroupName="Parameters")]
public Brush UpTrendColor
{ get; set; }
[Browsable(false)]
public string UpTrendColorSerializable
{
get { return Serialize.BrushToString(UpTrendColor); }
set { UpTrendColor = Serialize.StringToBrush(value); }
}
[NinjaScriptProperty]
[XmlIgnore]
[Display(Name="DownTrendColor", Order=3, GroupName="Parameters")]
public Brush DownTrendColor
{ get; set; }
[Browsable(false)]
public string DownTrendColorSerializable
{
get { return Serialize.BrushToString(DownTrendColor); }
set { DownTrendColor = Serialize.StringToBrush(value); }
}
[NinjaScriptProperty]
[XmlIgnore]
[Display(Name="RandomnessColor", Order=4, GroupName="Parameters")]
public Brush RandomnessColor
{ get; set; }
[Browsable(false)]
public string RandomnessColorSerializable
{
get { return Serialize.BrushToString(RandomnessColor); }
set { RandomnessColor = Serialize.StringToBrush(value); }
}
[Browsable(false)]
[XmlIgnore]
public Series<double> BarPlot
{
get { return Values[0]; }
}
#endregion
}
}
#region NinjaScript generated code. Neither change nor remove.
namespace NinjaTrader.NinjaScript.Indicators
{
public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
{
private ADXTrend[] cacheADXTrend;
public ADXTrend ADXTrend(Brush transitionColor, Brush upTrendColor, Brush downTrendColor, Brush randomnessColor)
{
return ADXTrend(Input, transitionColor, upTrendColor, downTrendColor, randomnessColor);
}
public ADXTrend ADXTrend(ISeries<double> input, Brush transitionColor, Brush upTrendColor, Brush downTrendColor, Brush randomnessColor)
{
if (cacheADXTrend != null)
for (int idx = 0; idx < cacheADXTrend.Length; idx++)
if (cacheADXTrend[idx] != null && cacheADXTrend[idx].TransitionColor == transitionColor && cacheADXTrend[idx].UpTrendColor == upTrendColor && cacheADXTrend[idx].DownTrendColor == downTrendColor && cacheADXTrend[idx].RandomnessColor == randomnessColor && cacheADXTrend[idx].EqualsInput(input))
return cacheADXTrend[idx];
return CacheIndicator<ADXTrend>(new ADXTrend(){ TransitionColor = transitionColor, UpTrendColor = upTrendColor, DownTrendColor = downTrendColor, RandomnessColor = randomnessColor }, input, ref cacheADXTrend);
}
}
}
namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
{
public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
{
public Indicators.ADXTrend ADXTrend(Brush transitionColor, Brush upTrendColor, Brush downTrendColor, Brush randomnessColor)
{
return indicator.ADXTrend(Input, transitionColor, upTrendColor, downTrendColor, randomnessColor);
}
public Indicators.ADXTrend ADXTrend(ISeries<double> input , Brush transitionColor, Brush upTrendColor, Brush downTrendColor, Brush randomnessColor)
{
return indicator.ADXTrend(input, transitionColor, upTrendColor, downTrendColor, randomnessColor);
}
}
}
namespace NinjaTrader.NinjaScript.Strategies
{
public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
{
public Indicators.ADXTrend ADXTrend(Brush transitionColor, Brush upTrendColor, Brush downTrendColor, Brush randomnessColor)
{
return indicator.ADXTrend(Input, transitionColor, upTrendColor, downTrendColor, randomnessColor);
}
public Indicators.ADXTrend ADXTrend(ISeries<double> input , Brush transitionColor, Brush upTrendColor, Brush downTrendColor, Brush randomnessColor)
{
return indicator.ADXTrend(input, transitionColor, upTrendColor, downTrendColor, randomnessColor);
}
}
}
#endregion
| |
//------------------------------------------------------------------------------
// <copyright
// file="StyleCopCmdTask.cs"
// company="Schley Andrew Kutz">
// Copyright (c) Schley Andrew Kutz. All rights reserved.
// </copyright>
// <authors>
// <author>Schley Andrew Kutz</author>
// </authors>
//------------------------------------------------------------------------------
/*******************************************************************************
* Copyright (c) 2008, Schley Andrew Kutz <[email protected]>
* 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 Schley Andrew Kutz 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 Net.SF.StyleCopCmd.Core
{
using System.Collections;
using System.Collections.Generic;
using Microsoft.StyleCop;
using NAnt.Core;
using NAnt.Core.Attributes;
using NAnt.Core.Types;
/// <summary>
/// This class provides a NAnt task that calls StyleCopCmd.
/// </summary>
[TaskName("styleCopCmd")]
public class StyleCopCmdTask : Task
{
/// <summary>
/// Gets or sets a list of directories used by the SyleCop processor
/// to load its own add-ins.
/// </summary>
[BuildElement("addinDirectories")]
public DirSet AddInDirectories
{
get;
set;
}
/// <summary>
/// Gets or sets a list of Visual Studio Solution files to check.
/// Visual Studio 2008 is supported.
/// </summary>
[BuildElement("solutionFiles")]
public FileSet SolutionFiles
{
get;
set;
}
/// <summary>
/// Gets or sets a list of Visual Studio Project files to check.
/// Visual Studio 2008 is supported.
/// </summary>
[BuildElement("projectFiles")]
public FileSet ProjectFiles
{
get;
set;
}
/// <summary>
/// Gets or sets a list of directories to check.
/// </summary>
[BuildElement("directories")]
public DirSet Directories
{
get;
set;
}
/// <summary>
/// Gets or sets a list of files to check.
/// </summary>
[BuildElement("files")]
public FileSet Files
{
get;
set;
}
/// <summary>
/// Gets or sets a list of regular expression patterns used
/// to ignore files (if a file name matches any of the patterns, the
/// file is not checked).
/// </summary>
[TaskAttribute("ignorePatterns")]
[StringValidator]
public string IgnorePatterns
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether or not directories are
/// recursed.
/// </summary>
[TaskAttribute("recursionEnabled")]
[BooleanValidator]
public bool RecursionEnabled
{
get;
set;
}
/// <summary>
/// Gets or sets a list of processor symbols (ex. DEBUG, CODE_ANALYSIS)
/// to be used by StyleCop.
/// </summary>
[TaskAttribute("processorSymbols")]
[StringValidator]
public string ProcessorSymbols
{
get;
set;
}
/// <summary>
/// Gets or sets the path to the StyleCop setting file to use.
/// </summary>
[TaskAttribute("styleCopSettingsFile")]
[StringValidator]
public string StyleCopSettingsFile
{
get;
set;
}
/// <summary>
/// Gets or sets the path to the XSL file used to transform the
/// outputted XML file to an HTML report.
/// </summary>
[TaskAttribute("transformFile")]
[StringValidator]
public string TransformFile
{
get;
set;
}
/// <summary>
/// Gets or sets the path to the output file.
/// </summary>
[TaskAttribute("outputXmlFile")]
[StringValidator]
public string OutputXmlFile
{
get;
set;
}
/// <summary>
/// Executes the task.
/// </summary>
protected override void ExecuteTask()
{
new StyleCopReport().ReportBuilder()
.WithAddInDirectories(GetDirectories(this.AddInDirectories))
.WithSolutionsFiles(GetFiles(this.SolutionFiles))
.WithProjectFiles(GetFiles(this.ProjectFiles))
.WithDirectories(GetDirectories(this.Directories))
.WithFiles(GetFiles(this.Files))
.WithProcessorSymbols(Split(this.ProcessorSymbols))
.WithIgnorePatterns(Split(this.IgnorePatterns))
.WithTransformFile(this.TransformFile)
.WithOutputEventHandler(this.LogOutput)
.WithRecursion(this.RecursionEnabled)
.WithStyleCopSettingsFile(this.StyleCopSettingsFile)
.Create(this.OutputXmlFile);
}
/// <summary>
/// Splits a string into an array of strings at commas.
/// </summary>
/// <param name="s">The string to split.</param>
/// <returns>
/// An array of strings. If the input is null a null value is returned.
/// </returns>
private static IList<string> Split(string s)
{
if (s == null)
{
return null;
}
return s.Split(',');
}
/// <summary>
/// Gets a generic list from a non-generic collection.
/// </summary>
/// <typeparam name="T">The type of list to get.</typeparam>
/// <param name="collection">
/// The collection to get the list from.
/// </param>
/// <returns>The generic list.</returns>
private static IList<T> GetIList<T>(ICollection collection)
{
if (collection == null)
{
return null;
}
var arr = new T[collection.Count];
collection.CopyTo(
arr,
0);
return arr;
}
/// <summary>
/// Gets a list of file names.
/// </summary>
/// <param name="fileSet">The fileset to get the names from.</param>
/// <returns>The list of file names; otherwise null.</returns>
private static IList<string> GetFiles(FileSet fileSet)
{
return fileSet == null ? null : GetIList<string>(fileSet.FileNames);
}
/// <summary>
/// Gets a list of directory names.
/// </summary>
/// <param name="dirSet">The dirset to get the names from.</param>
/// <returns>The list of directory names; otherwise null.</returns>
private static IList<string> GetDirectories(FileSet dirSet)
{
return dirSet == null ? null : GetIList<string>(dirSet.DirectoryNames);
}
/// <summary>
/// Logs StyleCop output to the NAnt logger.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The OutputEventArgs object.</param>
private void LogOutput(object sender, OutputEventArgs e)
{
this.Log(
Level.Info,
e.Output);
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.IO;
using System.Text;
using Encog.Bot.Browse.Range;
using Encog.Bot.DataUnits;
using Encog.Parse.Tags;
using Encog.Parse.Tags.Read;
namespace Encog.Bot.Browse
{
/// <summary>
/// Called to actually load a web page. This will read the HTML on a web page and
/// generate the DocumentRange classes.
/// </summary>
public class LoadWebPage
{
/// <summary>
/// The loaded webpage.
/// </summary>
private WebPage _page;
/// <summary>
/// The base URL for the page being loaded.
/// </summary>
private readonly Uri _baseURL;
/// <summary>
/// The last form that was processed.
/// </summary>
private Form _lastForm;
/// <summary>
/// The last hierarchy element that was processed.
/// </summary>
private DocumentRange _lastHierarchyElement;
/// <summary>
/// Construct a web page loader with the specified base URL.
/// </summary>
/// <param name="baseURL">The base URL to use when loading.</param>
public LoadWebPage(Uri baseURL)
{
_baseURL = baseURL;
}
/// <summary>
/// Add the specified hierarchy element.
/// </summary>
/// <param name="element">The hierarchy element to add.</param>
private void AddHierarchyElement(DocumentRange element)
{
if (_lastHierarchyElement == null)
{
_page.AddContent(element);
}
else
{
_lastHierarchyElement.AddElement(element);
}
_lastHierarchyElement = element;
}
/// <summary>
/// Create a dataunit to hode the code HTML tag.
/// </summary>
/// <param name="str">The code to create the data unit with.</param>
private void CreateCodeDataUnit(String str)
{
if (str.Trim().Length > 0)
{
var d = new CodeDataUnit {Code = str};
_page.AddDataUnit(d);
}
}
/// <summary>
/// Create a tag data unit.
/// </summary>
/// <param name="tag">The tag name to create the data unit for.</param>
private void CreateTagDataUnit(Tag tag)
{
var d = new TagDataUnit {Tag = (Tag) tag.Clone()};
_page.AddDataUnit(d);
}
/// <summary>
/// Create a text data unit.
/// </summary>
/// <param name="str">The text.</param>
private void CreateTextDataUnit(String str)
{
if (str.Trim().Length > 0)
{
var d = new TextDataUnit {Text = str};
_page.AddDataUnit(d);
}
}
/// <summary>
/// Find the end tag that lines up to the beginning tag.
/// </summary>
/// <param name="index">The index to start the search on. This specifies
/// the starting data unit.</param>
/// <param name="tag">The beginning tag that we are seeking the end tag
/// for.</param>
/// <returns>The index that the ending tag was found at. Returns -1
/// if not found.</returns>
protected int FindEndTag(int index, Tag tag)
{
int depth = 0;
int count = index;
while (count < _page.getDataSize())
{
DataUnit du = _page.GetDataUnit(count);
if (du is TagDataUnit)
{
Tag nextTag = ((TagDataUnit) du).Tag;
if (String.Compare(tag.Name, nextTag.Name, true) == 0)
{
if (nextTag.TagType == Tag.Type.End)
{
if (depth == 0)
{
return count;
}
depth--;
}
else if (nextTag.TagType == Tag.Type.Begin)
{
depth++;
}
}
}
count++;
}
return -1;
}
/// <summary>
/// Load a web page from the specified stream.
/// </summary>
/// <param name="istream">The input stream to load from.</param>
/// <returns>The loaded web page.</returns>
public WebPage Load(Stream istream)
{
_page = new WebPage();
LoadDataUnits(istream);
LoadContents();
return _page;
}
/// <summary>
/// Load the web page from a string that contains HTML.
/// </summary>
/// <param name="str">A string containing HTML.</param>
/// <returns>The loaded WebPage.</returns>
public WebPage Load(String str)
{
try
{
byte[] array = Encoding.UTF8.GetBytes(str);
Stream bis = new MemoryStream(array);
WebPage result = Load(bis);
bis.Close();
return result;
}
catch (IOException e)
{
#if logging
if (logger.IsDebugEnabled)
{
logger.Debug("Exception", e);
}
#endif
throw new BrowseError(e);
}
}
/// <summary>
/// Using the data units, which should have already been loaded by this
/// time, load the contents of the web page. This includes the title,
/// any links and forms. Div tags and spans are also processed.
/// </summary>
protected void LoadContents()
{
for (int index = 0; index < _page.getDataSize(); index++)
{
DataUnit du = _page.GetDataUnit(index);
if (du is TagDataUnit)
{
Tag tag = ((TagDataUnit) du).Tag;
if (tag.TagType != Tag.Type.End)
{
if (string.Compare(tag.Name, "a", true) == 0)
{
LoadLink(index, tag);
}
else if (string.Compare(tag.Name, "title", true) == 0)
{
LoadTitle(index, tag);
}
else if (string.Compare(tag.Name, "form", true) == 0)
{
LoadForm(index, tag);
}
else if (string.Compare(tag.Name, "input", true) == 0)
{
LoadInput(index, tag);
}
}
if (tag.TagType == Tag.Type.Begin)
{
if (String.Compare(tag.Name, "div", true) == 0)
{
LoadDiv(index, tag);
}
else if (String.Compare(tag.Name, "span", true) == 0)
{
LoadSpan(index, tag);
}
}
if (tag.TagType == Tag.Type.End)
{
if (string.Compare(tag.Name, "div") == 0)
{
if (_lastHierarchyElement != null)
{
_lastHierarchyElement =
_lastHierarchyElement.Parent;
}
}
else if (String.Compare(tag.Name, "span", true) == 0)
{
if (_lastHierarchyElement != null)
{
_lastHierarchyElement =
_lastHierarchyElement.Parent;
}
}
}
}
}
}
/// <summary>
/// Load the data units. Once the lower level data units have been
/// loaded, the contents can be loaded.
/// </summary>
/// <param name="istream">The input stream that the data units are loaded from.</param>
protected void LoadDataUnits(Stream istream)
{
var text = new StringBuilder();
int ch;
var parse = new ReadHTML(istream);
bool style = false;
bool script = false;
while ((ch = parse.Read()) != -1)
{
if (ch == 0)
{
if (style)
{
CreateCodeDataUnit(text.ToString());
}
else if (script)
{
CreateCodeDataUnit(text.ToString());
}
else
{
CreateTextDataUnit(text.ToString());
}
style = false;
script = false;
text.Length = 0;
CreateTagDataUnit(parse.LastTag);
if (String.Compare(parse.LastTag.Name, "style", true) == 0)
{
style = true;
}
else if (string.Compare(parse.LastTag.Name,
"script", true) == 0)
{
script = true;
}
}
else
{
text.Append((char) ch);
}
}
CreateTextDataUnit(text.ToString());
}
/// <summary>
/// Called by loadContents to load a div tag.
/// </summary>
/// <param name="index">The index to begin at.</param>
/// <param name="tag">The beginning div tag.</param>
private void LoadDiv(int index, Tag tag)
{
var div = new Div(_page);
String classAttribute = tag.GetAttributeValue("class");
String idAttribute = tag.GetAttributeValue("id");
div.IdAttribute = idAttribute;
div.ClassAttribute = (classAttribute);
div.Begin = index;
div.End = FindEndTag(index + 1, tag);
AddHierarchyElement(div);
}
/// <summary>
/// Called by loadContents to load a form on the page.
/// </summary>
/// <param name="index">The index to begin loading at.</param>
/// <param name="tag">The beginning tag.</param>
protected void LoadForm(int index, Tag tag)
{
String method = tag.GetAttributeValue("method");
String action = tag.GetAttributeValue("action");
var form = new Form(_page);
form.Begin = index;
form.End = FindEndTag(index + 1, tag);
if ((method == null) || string.Compare(method, "GET", true) == 0)
{
form.Method = Form.FormMethod.Get;
}
else
{
form.Method = Form.FormMethod.Post;
}
if (action == null)
{
form.Action = new Address(_baseURL);
}
else
{
form.Action = new Address(_baseURL, action);
}
_page.AddContent(form);
_lastForm = form;
}
/// <summary>
/// Called by loadContents to load an input tag on the form.
/// </summary>
/// <param name="index">The index to begin loading at.</param>
/// <param name="tag">The beginning tag.</param>
protected void LoadInput(int index, Tag tag)
{
String type = tag.GetAttributeValue("type");
String name = tag.GetAttributeValue("name");
String value = tag.GetAttributeValue("value");
var input = new Input(_page);
input.Type = type;
input.Name = name;
input.Value = value;
if (_lastForm != null)
{
_lastForm.AddElement(input);
}
else
{
_page.AddContent(input);
}
}
/// <summary>
/// Called by loadContents to load a link on the page.
/// </summary>
/// <param name="index">The index to begin loading at.</param>
/// <param name="tag">The beginning tag.</param>
protected void LoadLink(int index, Tag tag)
{
var link = new Link(_page);
String href = tag.GetAttributeValue("href");
if (href != null)
{
link.Target = new Address(_baseURL, href);
link.Begin = index;
link.End = FindEndTag(index + 1, tag);
_page.AddContent(link);
}
}
/// <summary>
/// Called by loadContents to load a span.
/// </summary>
/// <param name="index">The index to begin loading at.</param>
/// <param name="tag">The beginning tag.</param>
private void LoadSpan(int index, Tag tag)
{
var span = new Span(_page);
String classAttribute = tag.GetAttributeValue("class");
String idAttribute = tag.GetAttributeValue("id");
span.IdAttribute = idAttribute;
span.ClassAttribute = classAttribute;
span.Begin = index;
span.End = FindEndTag(index + 1, tag);
AddHierarchyElement(span);
}
/// <summary>
/// Called by loadContents to load the title of the page.
/// </summary>
/// <param name="index">The index to begin loading at.</param>
/// <param name="tag">The beginning tag.</param>
protected void LoadTitle(int index, Tag tag)
{
var title = new DocumentRange(_page);
title.Begin = index;
title.End = FindEndTag(index + 1, tag);
_page.Title = title;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Security
{
// SecureString attempts to provide a defense-in-depth solution.
//
// On Windows, this is done with several mechanisms:
// 1. keeping the data in unmanaged memory so that copies of it aren't implicitly made by the GC moving it around
// 2. zero'ing out that unmanaged memory so that the string is reliably removed from memory when done with it
// 3. encrypting the data while it's not being used (it's unencrypted to manipulate and use it)
//
// On Unix, we do 1 and 2, but we don't do 3 as there's no CryptProtectData equivalent.
public sealed partial class SecureString
{
private UnmanagedBuffer _buffer;
internal SecureString(SecureString str)
{
// Allocate enough space to store the provided string
EnsureCapacity(str._decryptedLength);
_decryptedLength = str._decryptedLength;
// Copy the string into the newly allocated space
if (_decryptedLength > 0)
{
UnmanagedBuffer.Copy(str._buffer, _buffer, (ulong)(str._decryptedLength * sizeof(char)));
}
}
private unsafe void InitializeSecureString(char* value, int length)
{
// Allocate enough space to store the provided string
EnsureCapacity(length);
_decryptedLength = length;
if (length == 0)
{
return;
}
// Copy the string into the newly allocated space
byte* ptr = null;
try
{
_buffer.AcquirePointer(ref ptr);
Buffer.MemoryCopy(value, ptr, _buffer.ByteLength, (ulong)(length * sizeof(char)));
}
finally
{
if (ptr != null)
{
_buffer.ReleasePointer();
}
}
}
private void DisposeCore()
{
if (_buffer != null && !_buffer.IsInvalid)
{
_buffer.Dispose();
_buffer = null;
}
}
private void ClearCore()
{
_decryptedLength = 0;
_buffer.Clear();
}
private unsafe void AppendCharCore(char c)
{
// Make sure we have enough space for the new character, then write it at the end.
EnsureCapacity(_decryptedLength + 1);
_buffer.Write((ulong)(_decryptedLength * sizeof(char)), c);
_decryptedLength++;
}
private unsafe void InsertAtCore(int index, char c)
{
// Make sure we have enough space for the new character, then shift all of the characters above it and insert it.
EnsureCapacity(_decryptedLength + 1);
byte* ptr = null;
try
{
_buffer.AcquirePointer(ref ptr);
ptr += index * sizeof(char);
long bytesToShift = (_decryptedLength - index) * sizeof(char);
Buffer.MemoryCopy(ptr, ptr + sizeof(char), bytesToShift, bytesToShift);
*((char*)ptr) = c;
++_decryptedLength;
}
finally
{
if (ptr != null)
{
_buffer.ReleasePointer();
}
}
}
private unsafe void RemoveAtCore(int index)
{
// Shift down all values above the specified index, then null out the empty space at the end.
byte* ptr = null;
try
{
_buffer.AcquirePointer(ref ptr);
ptr += index * sizeof(char);
long bytesToShift = (_decryptedLength - index - 1) * sizeof(char);
Buffer.MemoryCopy(ptr + sizeof(char), ptr, bytesToShift, bytesToShift);
*((char*)(ptr + bytesToShift)) = (char)0;
--_decryptedLength;
}
finally
{
if (ptr != null)
{
_buffer.ReleasePointer();
}
}
}
private void SetAtCore(int index, char c)
{
// Overwrite the character at the specified index
_buffer.Write((ulong)(index * sizeof(char)), c);
}
internal unsafe IntPtr MarshalToBSTRCore()
{
int length = _decryptedLength;
IntPtr ptr = IntPtr.Zero;
IntPtr result = IntPtr.Zero;
byte* bufferPtr = null;
try
{
_buffer.AcquirePointer(ref bufferPtr);
int resultByteLength = (length + 1) * sizeof(char);
ptr = Marshal.AllocBSTR(length);
Buffer.MemoryCopy(bufferPtr, (byte*)ptr, resultByteLength, length * sizeof(char));
result = ptr;
}
finally
{
// If we failed for any reason, free the new buffer
if (result == IntPtr.Zero && ptr != IntPtr.Zero)
{
RuntimeImports.RhZeroMemory(ptr, (UIntPtr)(length * sizeof(char)));
Marshal.FreeBSTR(ptr);
}
if (bufferPtr != null)
{
_buffer.ReleasePointer();
}
}
return result;
}
internal unsafe IntPtr MarshalToStringCore(bool globalAlloc, bool unicode)
{
int length = _decryptedLength;
byte* bufferPtr = null;
IntPtr stringPtr = IntPtr.Zero, result = IntPtr.Zero;
try
{
_buffer.AcquirePointer(ref bufferPtr);
if (unicode)
{
int resultLength = (length + 1) * sizeof(char);
stringPtr = globalAlloc ? Marshal.AllocHGlobal(resultLength) : Marshal.AllocCoTaskMem(resultLength);
Buffer.MemoryCopy(
source: bufferPtr,
destination: (byte*)stringPtr.ToPointer(),
destinationSizeInBytes: resultLength,
sourceBytesToCopy: length * sizeof(char));
*(length + (char*)stringPtr) = '\0';
}
else
{
int resultLength = Encoding.UTF8.GetByteCount((char*)bufferPtr, length) + 1;
stringPtr = globalAlloc ? Marshal.AllocHGlobal(resultLength) : Marshal.AllocCoTaskMem(resultLength);
int encodedLength = Encoding.UTF8.GetBytes((char*)bufferPtr, length, (byte*)stringPtr, resultLength);
Debug.Assert(encodedLength + 1 == resultLength, $"Expected encoded length to match result, got {encodedLength} != {resultLength}");
*(resultLength - 1 + (byte*)stringPtr) = 0;
}
result = stringPtr;
}
finally
{
// If there was a failure, such that result isn't initialized,
// release the string if we had one.
if (stringPtr != IntPtr.Zero && result == IntPtr.Zero)
{
RuntimeImports.RhZeroMemory(stringPtr, (UIntPtr)(length * sizeof(char)));
MarshalFree(stringPtr, globalAlloc);
}
if (bufferPtr != null)
{
_buffer.ReleasePointer();
}
}
return result;
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
private void EnsureCapacity(int capacity)
{
// Make sure the requested capacity doesn't exceed SecureString's defined limit
if (capacity > MaxLength)
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_Capacity);
}
// If we already have enough space allocated, we're done
if (_buffer != null && (capacity * sizeof(char)) <= (int)_buffer.ByteLength)
{
return;
}
// We need more space, so allocate a new buffer, copy all our data into it,
// and then swap the new for the old.
UnmanagedBuffer newBuffer = UnmanagedBuffer.Allocate(capacity * sizeof(char));
if (_buffer != null)
{
UnmanagedBuffer.Copy(_buffer, newBuffer, _buffer.ByteLength);
_buffer.Dispose();
}
_buffer = newBuffer;
}
/// <summary>SafeBuffer for managing memory meant to be kept confidential.</summary>
private sealed class UnmanagedBuffer : SafeBuffer
{
internal UnmanagedBuffer() : base(true) { }
internal static UnmanagedBuffer Allocate(int bytes)
{
Debug.Assert(bytes >= 0);
UnmanagedBuffer buffer = new UnmanagedBuffer();
buffer.SetHandle(Marshal.AllocHGlobal(bytes));
buffer.Initialize((ulong)bytes);
return buffer;
}
internal unsafe void Clear()
{
byte* ptr = null;
try
{
AcquirePointer(ref ptr);
RuntimeImports.RhZeroMemory((IntPtr)ptr, (UIntPtr)ByteLength);
}
finally
{
if (ptr != null)
{
ReleasePointer();
}
}
}
internal static unsafe void Copy(UnmanagedBuffer source, UnmanagedBuffer destination, ulong bytesLength)
{
if (bytesLength == 0)
{
return;
}
byte* srcPtr = null, dstPtr = null;
try
{
source.AcquirePointer(ref srcPtr);
destination.AcquirePointer(ref dstPtr);
Buffer.MemoryCopy(srcPtr, dstPtr, destination.ByteLength, bytesLength);
}
finally
{
if (dstPtr != null)
{
destination.ReleasePointer();
}
if (srcPtr != null)
{
source.ReleasePointer();
}
}
}
protected override unsafe bool ReleaseHandle()
{
Marshal.FreeHGlobal(handle);
return true;
}
}
}
}
| |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using Boo.Lang.Compiler.Ast;
using Boo.Lang.Compiler.Util;
using Boo.Lang.Compiler.TypeSystem;
using Boo.Lang.Compiler.TypeSystem.Reflection;
using Boo.Lang.Environments;
using Boo.Lang.Resources;
namespace Boo.Lang.Compiler
{
/// <summary>
/// Compiler parameters.
/// </summary>
public class CompilerParameters
{
public static IReflectionTypeSystemProvider SharedTypeSystemProvider = new ReflectionTypeSystemProvider();
private TextWriter _outputWriter;
private readonly CompilerInputCollection _input;
private readonly CompilerResourceCollection _resources;
private CompilerReferenceCollection _compilerReferences;
private string _outputAssembly;
private bool _strict;
private readonly List<string> _libPaths;
private readonly string _systemDir;
private Assembly _booAssembly;
private readonly Dictionary<string, string> _defines = new Dictionary<string, string>(StringComparer.Ordinal);
private TypeMemberModifiers _defaultTypeVisibility = TypeMemberModifiers.Public;
private TypeMemberModifiers _defaultMethodVisibility = TypeMemberModifiers.Public;
private TypeMemberModifiers _defaultPropertyVisibility = TypeMemberModifiers.Public;
private TypeMemberModifiers _defaultEventVisibility = TypeMemberModifiers.Public;
private TypeMemberModifiers _defaultFieldVisibility = TypeMemberModifiers.Protected;
private bool _defaultVisibilitySettingsRead;
public CompilerParameters() : this(true)
{
}
public CompilerParameters(bool loadDefaultReferences) : this(SharedTypeSystemProvider, loadDefaultReferences)
{
}
public CompilerParameters(IReflectionTypeSystemProvider reflectionProvider) : this(reflectionProvider, true)
{
}
public CompilerParameters(IReflectionTypeSystemProvider reflectionProvider, bool loadDefaultReferences)
{
_libPaths = new List<string>();
_systemDir = Permissions.WithDiscoveryPermission(() => GetSystemDir());
if (_systemDir != null)
{
_libPaths.Add(_systemDir);
_libPaths.Add(Directory.GetCurrentDirectory());
}
_input = new CompilerInputCollection();
_resources = new CompilerResourceCollection();
_compilerReferences = new CompilerReferenceCollection(reflectionProvider);
MaxExpansionIterations = 12;
_outputAssembly = String.Empty;
OutputType = CompilerOutputType.Auto;
_outputWriter = Console.Out;
Debug = true;
Checked = true;
#if !NET_40_OR_GREATER
GenerateCollectible = false;
#else
GenerateCollectible = true;
#endif
GenerateInMemory = true;
StdLib = true;
DelaySign = false;
Strict = false;
TraceLevel = DefaultTraceLevel();
this.CreateDoc = false;
if (loadDefaultReferences)
LoadDefaultReferences();
}
private static TraceLevel DefaultTraceLevel()
{
var booTraceLevel = Permissions.WithEnvironmentPermission(() => System.Environment.GetEnvironmentVariable("BOO_TRACE_LEVEL"));
return string.IsNullOrEmpty(booTraceLevel) ? TraceLevel.Off : (TraceLevel)Enum.Parse(typeof(TraceLevel), booTraceLevel);
}
public void LoadDefaultReferences()
{
//boo.lang.dll
_booAssembly = typeof(Builtins).Assembly;
_compilerReferences.Add(_booAssembly);
//boo.lang.extensions.dll
//try loading extensions next to Boo.Lang (in the same directory)
var extensionsAssembly = TryToLoadExtensionsAssembly();
if (extensionsAssembly != null)
_compilerReferences.Add(extensionsAssembly);
//boo.lang.compiler.dll
_compilerReferences.Add(GetType().Assembly);
//mscorlib
_compilerReferences.Add(LoadAssembly("mscorlib", true));
//System
_compilerReferences.Add(LoadAssembly("System", true));
//System.Core
_compilerReferences.Add(LoadAssembly("System.Core", true));
Permissions.WithDiscoveryPermission<object>(() =>
{
WriteTraceInfo("BOO LANG DLL: " + _booAssembly.Location);
WriteTraceInfo("BOO COMPILER EXTENSIONS DLL: " + (extensionsAssembly != null ? extensionsAssembly.ToString() : "NOT FOUND!"));
return null;
});
}
private IAssemblyReference TryToLoadExtensionsAssembly()
{
const string booLangExtensionsDll = "Boo.Lang.Extensions.dll";
return Permissions.WithDiscoveryPermission(() =>
{
var path = Path.Combine(Path.GetDirectoryName(_booAssembly.Location), booLangExtensionsDll);
return File.Exists(path) ? AssemblyReferenceFor(Assembly.LoadFrom(path)) : null;
}) ?? LoadAssembly(booLangExtensionsDll, false);
}
public Assembly BooAssembly
{
get { return _booAssembly; }
set
{
if (null == value)
throw new ArgumentNullException("value");
if (value != _booAssembly)
{
_compilerReferences.Remove(_booAssembly);
_booAssembly = value;
_compilerReferences.Add(value);
}
}
}
public ICompileUnit FindAssembly(string name)
{
return _compilerReferences.Find(name);
}
public void AddAssembly(Assembly asm)
{
if (null == asm) throw new ArgumentNullException();
_compilerReferences.Add(asm);
}
public IAssemblyReference LoadAssembly(string assembly)
{
return LoadAssembly(assembly, true);
}
public IAssemblyReference LoadAssembly(string assemblyName, bool throwOnError)
{
var assembly = ForName(assemblyName, throwOnError);
return assembly != null ? AssemblyReferenceFor(assembly) : null;
}
private IAssemblyReference AssemblyReferenceFor(Assembly assembly)
{
return _compilerReferences.Provider.ForAssembly(assembly);
}
protected virtual Assembly ForName(string assembly, bool throwOnError)
{
Assembly a = null;
try
{
if (assembly.IndexOfAny(new char[] {'/', '\\'}) != -1)
a = Assembly.LoadFrom(assembly);
else
a = LoadAssemblyFromGac(assembly);
}
catch (FileNotFoundException /*ignored*/)
{
return LoadAssemblyFromLibPaths(assembly, throwOnError);
}
catch (BadImageFormatException e)
{
if (throwOnError)
throw new ApplicationException(string.Format(Boo.Lang.Resources.StringResources.BooC_BadFormat, e.FusionLog), e);
}
catch (FileLoadException e)
{
if (throwOnError)
throw new ApplicationException(string.Format(Boo.Lang.Resources.StringResources.BooC_UnableToLoadAssembly, e.FusionLog), e);
}
catch (ArgumentNullException e)
{
if (throwOnError)
throw new ApplicationException(Boo.Lang.Resources.StringResources.BooC_NullAssembly, e);
}
return a ?? LoadAssemblyFromLibPaths(assembly, false);
}
private Assembly LoadAssemblyFromLibPaths(string assembly, bool throwOnError)
{
Assembly a = null;
string fullLog = "";
foreach (string dir in _libPaths)
{
string full_path = Path.Combine(dir, assembly);
FileInfo file = new FileInfo(full_path);
if (!IsAssemblyExtension(file.Extension))
full_path += ".dll";
try
{
a = Assembly.LoadFrom(full_path);
if (a != null)
{
return a;
}
}
catch (FileNotFoundException ff)
{
fullLog += ff.FusionLog;
continue;
}
}
if (throwOnError)
{
throw new ApplicationException(string.Format(Boo.Lang.Resources.StringResources.BooC_CannotFindAssembly, assembly));
//assembly, total_log)); //total_log contains the fusion log
}
return a;
}
private static bool IsAssemblyExtension(string extension)
{
switch (extension.ToLower())
{
case ".dll":
case ".exe":
return true;
}
return false;
}
private static Assembly LoadAssemblyFromGac(string assemblyName)
{
assemblyName = NormalizeAssemblyName(assemblyName);
// This is an intentional attempt to load an assembly with partial name
// so ignore the compiler warning
Assembly assembly = null;
#pragma warning disable 618
try
{
assembly = Permissions.WithDiscoveryPermission(()=> Assembly.LoadWithPartialName(assemblyName));
}
catch (FileNotFoundException)
{
}
#pragma warning restore 618
return assembly ?? Assembly.Load(assemblyName);
}
private static string NormalizeAssemblyName(string assembly)
{
var extension = Path.GetExtension(assembly).ToLower();
if (extension == ".dll" || extension == ".exe")
return assembly.Substring(0, assembly.Length - 4);
return assembly;
}
public void LoadReferencesFromPackage(string package)
{
string[] libs = Regex.Split(pkgconfig(package), @"\-r\:", RegexOptions.CultureInvariant);
foreach (string r in libs)
{
string reference = r.Trim();
if (reference.Length == 0) continue;
WriteTraceInfo("LOADING REFERENCE FROM PKGCONFIG '" + package + "' : " + reference);
References.Add(LoadAssembly(reference));
}
}
[Conditional("TRACE")]
private void WriteTraceInfo(string message)
{
if (TraceInfo)
Console.Error.WriteLine(message);
}
private static string pkgconfig(string package)
{
#if NO_SYSTEM_PROCESS
throw new System.NotSupportedException();
#else
Process process;
try
{
process = Builtins.shellp("pkg-config", String.Format("--libs {0}", package));
}
catch (Exception e)
{
throw new ApplicationException(StringResources.BooC_PkgConfigNotFound, e);
}
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new ApplicationException(string.Format(StringResources.BooC_PkgConfigReportedErrors, process.StandardError.ReadToEnd()));
}
return process.StandardOutput.ReadToEnd();
#endif
}
private static string GetSystemDir()
{
return Path.GetDirectoryName(typeof(string).Assembly.Location);
}
/// <summary>
/// Max number of iterations for the application of AST attributes and the
/// expansion of macros.
/// </summary>
public int MaxExpansionIterations { get; set; }
public CompilerInputCollection Input
{
get { return _input; }
}
public List<string> LibPaths
{
get { return _libPaths; }
}
public CompilerResourceCollection Resources
{
get { return _resources; }
}
public CompilerReferenceCollection References
{
get { return _compilerReferences; }
set
{
if (null == value) throw new ArgumentNullException("References");
_compilerReferences = value;
}
}
/// <summary>
/// The compilation pipeline.
/// </summary>
public CompilerPipeline Pipeline { get; set; }
/// <summary>
/// The name (full or partial) for the file
/// that should receive the resulting assembly.
/// </summary>
public string OutputAssembly
{
get { return _outputAssembly; }
set
{
if (String.IsNullOrEmpty(value)) throw new ArgumentNullException("OutputAssembly");
_outputAssembly = value;
}
}
/// <summary>
/// File name of the XML documentation (if such a documentation
/// shall be created).
/// </summary>
/// <see cref="CreateDoc"/>
public string OutputDoc { get; set; }
/// <summary>
/// True iff a XML file with documentation info shall be created.
/// If true, <see cref="OuputDoc"/> will be used to create a destination file.
/// If this property is undefined, use <see cref="OutputAssembly"/> with
/// stripped file name extension but appended ".xml".
/// </summary>
public bool CreateDoc { get; set; }
/// <summary>
/// Type and execution subsystem for the generated portable
/// executable file.
/// </summary>
public CompilerOutputType OutputType { get; set; }
public bool GenerateCollectible { get; set; }
public bool GenerateInMemory { get; set; }
public bool StdLib { get; set; }
public TextWriter OutputWriter
{
get { return _outputWriter; }
set
{
if (null == value) throw new ArgumentNullException("OutputWriter");
_outputWriter = value;
}
}
public bool Debug { get; set; }
/// <summary>
/// Treat System.Object as duck
/// </summary>
public virtual bool Ducky { get; set; }
public bool Checked { get; set; }
public string KeyFile { get; set; }
public string KeyContainer { get; set; }
public bool DelaySign { get; set; }
public bool WhiteSpaceAgnostic { get; set; }
public Dictionary<string, string> Defines
{
get { return _defines; }
}
public TypeMemberModifiers DefaultTypeVisibility
{
get
{
if (!_defaultVisibilitySettingsRead)
ReadDefaultVisibilitySettings();
return _defaultTypeVisibility;
}
set
{
_defaultTypeVisibility = value & TypeMemberModifiers.VisibilityMask;
}
}
public TypeMemberModifiers DefaultMethodVisibility
{
get
{
if (!_defaultVisibilitySettingsRead)
ReadDefaultVisibilitySettings();
return _defaultMethodVisibility;
}
set
{
_defaultMethodVisibility = value & TypeMemberModifiers.VisibilityMask;
}
}
public TypeMemberModifiers DefaultPropertyVisibility
{
get
{
if (!_defaultVisibilitySettingsRead)
ReadDefaultVisibilitySettings();
return _defaultPropertyVisibility;
}
set
{
_defaultPropertyVisibility = value & TypeMemberModifiers.VisibilityMask;
}
}
public TypeMemberModifiers DefaultEventVisibility
{
get
{
if (!_defaultVisibilitySettingsRead)
ReadDefaultVisibilitySettings();
return _defaultEventVisibility;
}
set
{
_defaultEventVisibility = value & TypeMemberModifiers.VisibilityMask;
}
}
public TypeMemberModifiers DefaultFieldVisibility
{
get
{
if (!_defaultVisibilitySettingsRead)
ReadDefaultVisibilitySettings();
return _defaultFieldVisibility;
}
set
{
_defaultFieldVisibility = value & TypeMemberModifiers.VisibilityMask;
}
}
public bool TraceInfo
{
get { return TraceLevel >= TraceLevel.Info; }
}
public bool TraceWarning
{
get { return TraceLevel >= TraceLevel.Warning; }
}
public bool TraceError
{
get { return TraceLevel >= TraceLevel.Error; }
}
public bool TraceVerbose
{
get { return TraceLevel >= TraceLevel.Verbose; }
}
public TraceLevel TraceLevel { get; set; }
private void ReadDefaultVisibilitySettings()
{
string visibility;
if (_defines.TryGetValue("DEFAULT_TYPE_VISIBILITY", out visibility))
DefaultTypeVisibility = ParseVisibility(visibility);
if (_defines.TryGetValue("DEFAULT_METHOD_VISIBILITY", out visibility))
DefaultMethodVisibility = ParseVisibility(visibility);
if (_defines.TryGetValue("DEFAULT_PROPERTY_VISIBILITY", out visibility))
DefaultPropertyVisibility = ParseVisibility(visibility);
if (_defines.TryGetValue("DEFAULT_EVENT_VISIBILITY", out visibility))
DefaultEventVisibility = ParseVisibility(visibility);
if (_defines.TryGetValue("DEFAULT_FIELD_VISIBILITY", out visibility))
DefaultFieldVisibility = ParseVisibility(visibility);
_defaultVisibilitySettingsRead = true;
}
private static TypeMemberModifiers ParseVisibility(string visibility)
{
if (String.IsNullOrEmpty(visibility))
throw new ArgumentNullException("visibility");
visibility = visibility.ToLower();
switch (visibility)
{
case "public":
return TypeMemberModifiers.Public;
case "protected":
return TypeMemberModifiers.Protected;
case "internal":
return TypeMemberModifiers.Internal;
case "private":
return TypeMemberModifiers.Private;
}
throw new ArgumentException("visibility", String.Format("Invalid visibility: '{0}'", visibility));
}
Util.Set<string> _disabledWarnings = new Util.Set<string>();
Util.Set<string> _promotedWarnings = new Util.Set<string>();
public bool NoWarn { get; set; }
public bool WarnAsError { get; set; }
public ICollection<string> DisabledWarnings
{
get { return _disabledWarnings; }
}
public ICollection<string> WarningsAsErrors
{
get { return _promotedWarnings; }
}
public void EnableWarning(string code)
{
if (_disabledWarnings.Contains(code))
_disabledWarnings.Remove(code);
}
public void DisableWarning(string code)
{
_disabledWarnings.Add(code);
}
public void ResetWarnings()
{
NoWarn = false;
_disabledWarnings.Clear();
Strict = _strict;
}
public void EnableWarningAsError(string code)
{
_promotedWarnings.Add(code);
}
public void DisableWarningAsError(string code)
{
if (_promotedWarnings.Contains(code))
_promotedWarnings.Remove(code);
}
public void ResetWarningsAsErrors()
{
WarnAsError = false;
_promotedWarnings.Clear();
}
public bool Strict
{
get { return _strict; }
set {
_strict = value;
if (_strict)
OnStrictMode();
else
OnNonStrictMode();
}
}
protected virtual void OnNonStrictMode()
{
_defaultTypeVisibility = TypeMemberModifiers.Public;
_defaultMethodVisibility = TypeMemberModifiers.Public;
_defaultPropertyVisibility = TypeMemberModifiers.Public;
_defaultEventVisibility = TypeMemberModifiers.Public;
_defaultFieldVisibility = TypeMemberModifiers.Protected;
DisableWarning(CompilerWarningFactory.Codes.ImplicitReturn);
DisableWarning(CompilerWarningFactory.Codes.VisibleMemberDoesNotDeclareTypeExplicitely);
DisableWarning(CompilerWarningFactory.Codes.ImplicitDowncast);
}
protected virtual void OnStrictMode()
{
_defaultTypeVisibility = TypeMemberModifiers.Private;
_defaultMethodVisibility = TypeMemberModifiers.Private;
_defaultPropertyVisibility = TypeMemberModifiers.Private;
_defaultEventVisibility = TypeMemberModifiers.Private;
_defaultFieldVisibility = TypeMemberModifiers.Private;
EnableWarning(CompilerWarningFactory.Codes.ImplicitReturn);
EnableWarning(CompilerWarningFactory.Codes.VisibleMemberDoesNotDeclareTypeExplicitely);
//by default strict mode forbids implicit downcasts
//disable warning so we get only the regular incompatible type error
DisableWarning(CompilerWarningFactory.Codes.ImplicitDowncast);
}
public bool Unsafe { get; set; }
public string Platform { get; set; }
public IEnvironment Environment { get; set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableHashSetBuilderTest : ImmutablesTestBase
{
[Fact]
public void CreateBuilder()
{
var builder = ImmutableHashSet.CreateBuilder<string>();
Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer);
builder = ImmutableHashSet.CreateBuilder<string>(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
}
[Fact]
public void ToBuilder()
{
var builder = ImmutableHashSet<int>.Empty.ToBuilder();
Assert.True(builder.Add(3));
Assert.True(builder.Add(5));
Assert.False(builder.Add(5));
Assert.Equal(2, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var set = builder.ToImmutable();
Assert.Equal(builder.Count, set.Count);
Assert.True(builder.Add(8));
Assert.Equal(3, builder.Count);
Assert.Equal(2, set.Count);
Assert.True(builder.Contains(8));
Assert.False(set.Contains(8));
}
[Fact]
public void BuilderFromSet()
{
var set = ImmutableHashSet<int>.Empty.Add(1);
var builder = set.ToBuilder();
Assert.True(builder.Contains(1));
Assert.True(builder.Add(3));
Assert.True(builder.Add(5));
Assert.False(builder.Add(5));
Assert.Equal(3, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var set2 = builder.ToImmutable();
Assert.Equal(builder.Count, set2.Count);
Assert.True(set2.Contains(1));
Assert.True(builder.Add(8));
Assert.Equal(4, builder.Count);
Assert.Equal(3, set2.Count);
Assert.True(builder.Contains(8));
Assert.False(set.Contains(8));
Assert.False(set2.Contains(8));
}
[Fact]
public void EnumerateBuilderWhileMutating()
{
var builder = ImmutableHashSet<int>.Empty.Union(Enumerable.Range(1, 10)).ToBuilder();
CollectionAssertAreEquivalent(Enumerable.Range(1, 10).ToArray(), builder.ToArray());
var enumerator = builder.GetEnumerator();
Assert.True(enumerator.MoveNext());
builder.Add(11);
// Verify that a new enumerator will succeed.
CollectionAssertAreEquivalent(Enumerable.Range(1, 11).ToArray(), builder.ToArray());
// Try enumerating further with the previous enumerable now that we've changed the collection.
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
enumerator.Reset();
enumerator.MoveNext(); // resetting should fix the problem.
// Verify that by obtaining a new enumerator, we can enumerate all the contents.
CollectionAssertAreEquivalent(Enumerable.Range(1, 11).ToArray(), builder.ToArray());
}
[Fact]
public void BuilderReusesUnchangedImmutableInstances()
{
var collection = ImmutableHashSet<int>.Empty.Add(1);
var builder = collection.ToBuilder();
Assert.Same(collection, builder.ToImmutable()); // no changes at all.
builder.Add(2);
var newImmutable = builder.ToImmutable();
Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance.
Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance.
}
[Fact]
public void EnumeratorTest()
{
var builder = ImmutableHashSet.Create(1).ToBuilder();
ManuallyEnumerateTest(new[] { 1 }, ((IEnumerable<int>)builder).GetEnumerator());
}
[Fact]
public void Clear()
{
var set = ImmutableHashSet.Create(1);
var builder = set.ToBuilder();
builder.Clear();
Assert.Equal(0, builder.Count);
}
[Fact]
public void KeyComparer()
{
var builder = ImmutableHashSet.Create("a", "B").ToBuilder();
Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer);
Assert.True(builder.Contains("a"));
Assert.False(builder.Contains("A"));
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
Assert.Equal(2, builder.Count);
Assert.True(builder.Contains("a"));
Assert.True(builder.Contains("A"));
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
}
[Fact]
public void KeyComparerCollisions()
{
var builder = ImmutableHashSet.Create("a", "A").ToBuilder();
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Equal(1, builder.Count);
Assert.True(builder.Contains("a"));
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
Assert.Equal(1, set.Count);
Assert.True(set.Contains("a"));
}
[Fact]
public void KeyComparerEmptyCollection()
{
var builder = ImmutableHashSet.Create<string>().ToBuilder();
Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer);
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
}
[Fact]
public void UnionWith()
{
var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder();
AssertExtensions.Throws<ArgumentNullException>("other", () => builder.UnionWith(null));
builder.UnionWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 1, 2, 3, 4 }, builder);
}
[Fact]
public void ExceptWith()
{
var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder();
AssertExtensions.Throws<ArgumentNullException>("other", () => builder.ExceptWith(null));
builder.ExceptWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 1 }, builder);
}
[Fact]
public void SymmetricExceptWith()
{
var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder();
AssertExtensions.Throws<ArgumentNullException>("other", () => builder.SymmetricExceptWith(null));
builder.SymmetricExceptWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 1, 4 }, builder);
}
[Fact]
public void IntersectWith()
{
var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder();
AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IntersectWith(null));
builder.IntersectWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 2, 3 }, builder);
}
[Fact]
public void IsProperSubsetOf()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IsProperSubsetOf(null));
Assert.False(builder.IsProperSubsetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsProperSubsetOf(Enumerable.Range(1, 5)));
}
[Fact]
public void IsProperSupersetOf()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IsProperSupersetOf(null));
Assert.False(builder.IsProperSupersetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsProperSupersetOf(Enumerable.Range(1, 2)));
}
[Fact]
public void IsSubsetOf()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IsSubsetOf(null));
Assert.False(builder.IsSubsetOf(Enumerable.Range(1, 2)));
Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 5)));
}
[Fact]
public void IsSupersetOf()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IsSupersetOf(null));
Assert.False(builder.IsSupersetOf(Enumerable.Range(1, 4)));
Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 2)));
}
[Fact]
public void Overlaps()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
AssertExtensions.Throws<ArgumentNullException>("other", () => builder.Overlaps(null));
Assert.True(builder.Overlaps(Enumerable.Range(3, 2)));
Assert.False(builder.Overlaps(Enumerable.Range(4, 3)));
}
[Fact]
public void Remove()
{
var builder = ImmutableHashSet.Create("a").ToBuilder();
Assert.False(builder.Remove("b"));
Assert.True(builder.Remove("a"));
}
[Fact]
public void SetEquals()
{
var builder = ImmutableHashSet.Create("a").ToBuilder();
AssertExtensions.Throws<ArgumentNullException>("other", () => builder.SetEquals(null));
Assert.False(builder.SetEquals(new[] { "b" }));
Assert.True(builder.SetEquals(new[] { "a" }));
Assert.True(builder.SetEquals(builder));
}
[Fact]
public void ICollectionOfTMethods()
{
ICollection<string> builder = ImmutableHashSet.Create("a").ToBuilder();
builder.Add("b");
Assert.True(builder.Contains("b"));
var array = new string[3];
builder.CopyTo(array, 1);
Assert.Null(array[0]);
CollectionAssertAreEquivalent(new[] { null, "a", "b" }, array);
Assert.False(builder.IsReadOnly);
CollectionAssertAreEquivalent(new[] { "a", "b" }, builder.ToArray()); // tests enumerator
}
[Fact]
public void NullHandling()
{
var builder = ImmutableHashSet<string>.Empty.ToBuilder();
Assert.True(builder.Add(null));
Assert.False(builder.Add(null));
Assert.True(builder.Contains(null));
Assert.True(builder.Remove(null));
builder.UnionWith(new[] { null, "a" });
Assert.True(builder.IsSupersetOf(new[] { null, "a" }));
Assert.True(builder.IsSubsetOf(new[] { null, "a" }));
Assert.True(builder.IsProperSupersetOf(new[] { default(string) }));
Assert.True(builder.IsProperSubsetOf(new[] { null, "a", "b" }));
builder.IntersectWith(new[] { default(string) });
Assert.Equal(1, builder.Count);
builder.ExceptWith(new[] { default(string) });
Assert.False(builder.Remove(null));
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableHashSet.CreateBuilder<int>());
}
[Fact]
public void ToImmutableHashSet()
{
ImmutableHashSet<int>.Builder builder = ImmutableHashSet.CreateBuilder<int>();
builder.Add(1);
builder.Add(2);
builder.Add(3);
var set = builder.ToImmutableSortedSet();
Assert.True(builder.Contains(1));
Assert.True(builder.Contains(2));
Assert.True(builder.Contains(3));
builder.Remove(3);
Assert.False(builder.Contains(3));
Assert.True(set.Contains(3));
builder.Clear();
Assert.True(builder.ToImmutableHashSet().IsEmpty);
Assert.False(set.IsEmpty);
ImmutableHashSet<int>.Builder nullBuilder = null;
AssertExtensions.Throws<ArgumentNullException>("builder", () => nullBuilder.ToImmutableHashSet());
}
}
}
| |
// Copyright (c) 2012-2013 Rotorz Limited. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
using UnityEngine;
using UnityEditor;
using System;
namespace InControl.ReorderableList.Internal
{
/// <summary>
/// Resources to assist with reorderable list control.
/// </summary>
internal static class ReorderableListResources
{
static ReorderableListResources()
{
GenerateSpecialTextures();
LoadResourceAssets();
}
#region Texture Resources
private enum ResourceName
{
add_button = 0,
add_button_active,
container_background,
grab_handle,
remove_button,
remove_button_active,
title_background,
}
/// <summary>
/// Resource assets for light skin.
/// </summary>
/// <remarks>
/// <para>Resource assets are PNG images which have been encoded using a base-64
/// string so that actual asset files are not necessary.</para>
/// </remarks>
private static string[] s_LightSkin = {
"iVBORw0KGgoAAAANSUhEUgAAAB4AAAAQCAYAAAABOs/SAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAZdEVYdFNvZnR3YXJlAEFkb2JlIEltYWdlUmVhZHlxyWU8AAAAW0lEQVRIS+3NywnAQAhF0anI4mzVCmzBBl7QEBgGE5JFhBAXd+OHM5gZZgYRKcktNxu+HRFF2e6qhtOjtQM7K/tZ+xY89wSbazg9eqOfw6oag4rcChjY8coAjA2l1RxFDY8IFAAAAABJRU5ErkJggg==",
"iVBORw0KGgoAAAANSUhEUgAAAB4AAAAQCAYAAAABOs/SAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGlJREFUeNpiFBER+f/jxw8GNjY2BnqAX79+MXBwcDAwMQwQGHoWnzp1CoxHjo8pBSykBi8+MTMzs2HmY2QfwXxKii9HExdZgNwgHuFB/efPH7pZCLOL8f///wyioqL/6enbL1++MAIEGABvGSLA+9GPZwAAAABJRU5ErkJggg==",
"iVBORw0KGgoAAAANSUhEUgAAAAUAAAAECAYAAABGM/VAAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAZdEVYdFNvZnR3YXJlAEFkb2JlIEltYWdlUmVhZHlxyWU8AAAAMElEQVQYV2P4//8/Q1FR0X8YBvHBAp8+ffp/+fJlMA3igwUfPnwIFgDRYEFM7f8ZAG1EOYL9INrfAAAAAElFTkSuQmCC",
"iVBORw0KGgoAAAANSUhEUgAAAAkAAAAFCAYAAACXU8ZrAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAZdEVYdFNvZnR3YXJlAEFkb2JlIEltYWdlUmVhZHlxyWU8AAAAIElEQVQYV2P49OnTf0KYobCw8D8hzPD/P2FMLesK/wMAs5yJpK+6aN4AAAAASUVORK5CYII=",
"iVBORw0KGgoAAAANSUhEUgAAAAgAAAACCAIAAADq9gq6AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAABVJREFUeNpiVFZWZsAGmBhwAIAAAwAURgBt4C03ZwAAAABJRU5ErkJggg==",
"iVBORw0KGgoAAAANSUhEUgAAAAgAAAACCAIAAADq9gq6AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAABVJREFUeNpivHPnDgM2wMSAAwAEGAB8VgKYlvqkBwAAAABJRU5ErkJggg==",
"iVBORw0KGgoAAAANSUhEUgAAAAUAAAAECAYAAABGM/VAAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAEFJREFUeNpi/P//P0NxcfF/BgRgZP78+fN/VVVVhpCQEAZjY2OGs2fPNrCApBwdHRkePHgAVwoWnDVrFgMyAAgwAAt4E1dCq1obAAAAAElFTkSuQmCC"
};
/// <summary>
/// Resource assets for dark skin.
/// </summary>
/// <remarks>
/// <para>Resource assets are PNG images which have been encoded using a base-64
/// string so that actual asset files are not necessary.</para>
/// </remarks>
private static string[] s_DarkSkin = {
"iVBORw0KGgoAAAANSUhEUgAAAB4AAAAQCAYAAAABOs/SAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAIBJREFUeNpiVFZW/u/i4sLw4sULBnoACQkJhj179jAwMQwQGHoWl5aWgvHI8TGlgIXU4MUn1t3dPcx8HB8fD2cvXLgQQ0xHR4c2FmMzmBTLhl5QYwt2cn1MtsXkWjg4gvrt27fgWoMeAGQXCDD+//+fQUVF5T89fXvnzh1GgAADAFmSI1Ed3FqgAAAAAElFTkSuQmCC",
"iVBORw0KGgoAAAANSUhEUgAAAB4AAAAQCAYAAAABOs/SAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAHlJREFUeNpiFBER+f/jxw8GNjY2BnqAX79+MXBwcDAwMQwQGHoWv3nzBoxHjo8pBSykBi8+MWAOGWY+5uLigrO/ffuGIYbMppnF5Fg2tFM1yKfk+pbkoKZGEA+OVP3nzx+6WQizi/H///8MoqKi/+np2y9fvjACBBgAoTYjgvihfz0AAAAASUVORK5CYII=",
"iVBORw0KGgoAAAANSUhEUgAAAAUAAAAECAYAAABGM/VAAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAD1JREFUeNpi/P//P4OKisp/Bii4c+cOIwtIwMXFheHFixcMEhISYAVMINm3b9+CBUA0CDCiazc0NGQECDAAdH0YelA27kgAAAAASUVORK5CYII=",
"iVBORw0KGgoAAAANSUhEUgAAAAkAAAAFCAYAAACXU8ZrAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACRJREFUeNpizM3N/c9AADAqKysTVMTi5eXFSFAREFPHOoAAAwBCfwcAO8g48QAAAABJRU5ErkJggg==",
"iVBORw0KGgoAAAANSUhEUgAAAAgAAAAECAYAAACzzX7wAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACJJREFUeNpi/P//PwM+wHL06FG8KpgYCABGZWVlvCYABBgA7/sHvGw+cz8AAAAASUVORK5CYII=",
"iVBORw0KGgoAAAANSUhEUgAAAAgAAAAECAYAAACzzX7wAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACBJREFUeNpi/P//PwM+wPKfgAomBgKAhYuLC68CgAADAAxjByOjCHIRAAAAAElFTkSuQmCC",
"iVBORw0KGgoAAAANSUhEUgAAAAUAAAAECAYAAABGM/VAAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADtJREFUeNpi/P//P4OKisp/Bii4c+cOIwtIQE9Pj+HLly9gQRCfBcQACbx69QqmmAEseO/ePQZkABBgAD04FXsmmijSAAAAAElFTkSuQmCC"
};
/// <summary>
/// Gets light or dark texture "add_button.png".
/// </summary>
public static Texture2D texAddButton
{
get { return s_Cached[(int)ResourceName.add_button]; }
}
/// <summary>
/// Gets light or dark texture "add_button_active.png".
/// </summary>
public static Texture2D texAddButtonActive
{
get { return s_Cached[(int)ResourceName.add_button_active]; }
}
/// <summary>
/// Gets light or dark texture "container_background.png".
/// </summary>
public static Texture2D texContainerBackground
{
get { return s_Cached[(int)ResourceName.container_background]; }
}
/// <summary>
/// Gets light or dark texture "grab_handle.png".
/// </summary>
public static Texture2D texGrabHandle
{
get { return s_Cached[(int)ResourceName.grab_handle]; }
}
/// <summary>
/// Gets light or dark texture "remove_button.png".
/// </summary>
public static Texture2D texRemoveButton
{
get { return s_Cached[(int)ResourceName.remove_button]; }
}
/// <summary>
/// Gets light or dark texture "remove_button_active.png".
/// </summary>
public static Texture2D texRemoveButtonActive
{
get { return s_Cached[(int)ResourceName.remove_button_active]; }
}
/// <summary>
/// Gets light or dark texture "title_background.png".
/// </summary>
public static Texture2D texTitleBackground
{
get { return s_Cached[(int)ResourceName.title_background]; }
}
#endregion
#region Generated Resources
public static Texture2D texItemSplitter { get; private set; }
/// <summary>
/// Generate special textures.
/// </summary>
private static void GenerateSpecialTextures()
{
var splitterColor = EditorGUIUtility.isProSkin
? new Color( 1f, 1f, 1f, 0.14f )
: new Color( 0.59f, 0.59f, 0.59f, 0.55f );
texItemSplitter = CreatePixelTexture( "(Generated) Item Splitter", splitterColor );
}
/// <summary>
/// Create 1x1 pixel texture of specified color.
/// </summary>
/// <param name="name">Name for texture object.</param>
/// <param name="color">Pixel color.</param>
/// <returns>
/// The new <c>Texture2D</c> instance.
/// </returns>
public static Texture2D CreatePixelTexture( string name, Color color )
{
var tex = new Texture2D( 1, 1, TextureFormat.ARGB32, false );
tex.name = name;
tex.hideFlags = HideFlags.HideAndDontSave;
tex.filterMode = FilterMode.Point;
tex.SetPixel( 0, 0, color );
tex.Apply();
return tex;
}
#endregion
#region Load PNG from Base-64 Encoded String
private static Texture2D[] s_Cached;
/// <summary>
/// Read textures from base-64 encoded strings. Automatically selects assets based
/// upon whether the light or dark (pro) skin is active.
/// </summary>
private static void LoadResourceAssets()
{
var skin = EditorGUIUtility.isProSkin ? s_DarkSkin : s_LightSkin;
s_Cached = new Texture2D[skin.Length];
for (int i = 0; i < s_Cached.Length; ++i)
{
// Get image data (PNG) from base64 encoded strings.
byte[] imageData = Convert.FromBase64String( skin[i] );
// Gather image size from image data.
int texWidth, texHeight;
GetImageSize( imageData, out texWidth, out texHeight );
// Generate texture asset.
var tex = new Texture2D( texWidth, texHeight, TextureFormat.ARGB32, false );
tex.hideFlags = HideFlags.HideAndDontSave;
tex.name = "(Generated) ReorderableList:" + i;
tex.filterMode = FilterMode.Point;
tex.LoadImage( imageData );
s_Cached[i] = tex;
}
s_LightSkin = null;
s_DarkSkin = null;
}
/// <summary>
/// Read width and height if PNG file in pixels.
/// </summary>
/// <param name="imageData">PNG image data.</param>
/// <param name="width">Width of image in pixels.</param>
/// <param name="height">Height of image in pixels.</param>
private static void GetImageSize( byte[] imageData, out int width, out int height )
{
width = ReadInt( imageData, 3 + 15 );
height = ReadInt( imageData, 3 + 15 + 2 + 2 );
}
private static int ReadInt( byte[] imageData, int offset )
{
return (imageData[offset] << 8) | imageData[offset + 1];
}
#endregion
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace WelcomeAppPartWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// #define StressTest // set to raise the amount of time spent in concurrency tests that stress the collections
using System;
using System.Collections.Generic;
using System.Collections.Tests;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
public abstract class ProducerConsumerCollectionTests : IEnumerable_Generic_Tests<int>
{
protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) => new List<ModifyEnumerable>();
protected override int CreateT(int seed) => new Random(seed).Next();
protected override EnumerableOrder Order => EnumerableOrder.Unspecified;
protected override IEnumerable<int> GenericIEnumerableFactory(int count) => CreateProducerConsumerCollection(count);
protected IProducerConsumerCollection<int> CreateProducerConsumerCollection() => CreateProducerConsumerCollection<int>();
protected IProducerConsumerCollection<int> CreateProducerConsumerCollection(int count) => CreateProducerConsumerCollection(Enumerable.Range(0, count));
protected abstract IProducerConsumerCollection<T> CreateProducerConsumerCollection<T>();
protected abstract IProducerConsumerCollection<int> CreateProducerConsumerCollection(IEnumerable<int> collection);
protected abstract bool IsEmpty(IProducerConsumerCollection<int> pcc);
protected abstract bool TryPeek<T>(IProducerConsumerCollection<T> pcc, out T result);
protected virtual IProducerConsumerCollection<int> CreateOracle() => CreateOracle(Enumerable.Empty<int>());
protected abstract IProducerConsumerCollection<int> CreateOracle(IEnumerable<int> collection);
protected static TaskFactory ThreadFactory { get; } = new TaskFactory(
CancellationToken.None, TaskCreationOptions.LongRunning, TaskContinuationOptions.LongRunning, TaskScheduler.Default);
private const double ConcurrencyTestSeconds =
#if StressTest
8.0;
#else
1.0;
#endif
protected virtual string CopyToNoLengthParamName => "destinationArray";
[Fact]
public void Ctor_InvalidArgs_Throws()
{
AssertExtensions.Throws<ArgumentNullException>("collection", () => CreateProducerConsumerCollection(null));
}
[Fact]
public void Ctor_NoArg_ItemsAndCountMatch()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Equal(0, c.Count);
Assert.True(IsEmpty(c));
Assert.Equal(Enumerable.Empty<int>(), c);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(1000)]
public void Ctor_Collection_ItemsAndCountMatch(int count)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, count));
IProducerConsumerCollection<int> oracle = CreateOracle(Enumerable.Range(1, count));
Assert.Equal(oracle.Count == 0, IsEmpty(c));
Assert.Equal(oracle.Count, c.Count);
Assert.Equal<int>(oracle, c);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(3)]
[InlineData(1000)]
public void Ctor_InitializeFromCollection_ContainsExpectedItems(int numItems)
{
var expected = new HashSet<int>(Enumerable.Range(0, numItems));
IProducerConsumerCollection<int> pcc = CreateProducerConsumerCollection(expected);
Assert.Equal(expected.Count, pcc.Count);
int item;
var actual = new HashSet<int>();
for (int i = 0; i < expected.Count; i++)
{
Assert.Equal(expected.Count - i, pcc.Count);
Assert.True(pcc.TryTake(out item));
actual.Add(item);
}
Assert.False(pcc.TryTake(out item));
Assert.Equal(0, item);
AssertSetsEqual(expected, actual);
}
[Fact]
public void Add_TakeFromAnotherThread_ExpectedItemsTaken()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.True(IsEmpty(c));
Assert.Equal(0, c.Count);
const int NumItems = 100000;
Task producer = Task.Run(() => Parallel.For(1, NumItems + 1, i => Assert.True(c.TryAdd(i))));
var hs = new HashSet<int>();
while (hs.Count < NumItems)
{
int item;
if (c.TryTake(out item)) hs.Add(item);
}
producer.GetAwaiter().GetResult();
Assert.True(IsEmpty(c));
Assert.Equal(0, c.Count);
AssertSetsEqual(new HashSet<int>(Enumerable.Range(1, NumItems)), hs);
}
[Fact]
public void AddSome_ThenInterleaveAddsAndTakes_MatchesOracle()
{
IProducerConsumerCollection<int> c = CreateOracle();
IProducerConsumerCollection<int> oracle = CreateProducerConsumerCollection();
Action take = () =>
{
int item1;
Assert.True(c.TryTake(out item1));
int item2;
Assert.True(oracle.TryTake(out item2));
Assert.Equal(item1, item2);
Assert.Equal(c.Count, oracle.Count);
Assert.Equal<int>(c, oracle);
};
for (int i = 0; i < 100; i++)
{
Assert.True(oracle.TryAdd(i));
Assert.True(c.TryAdd(i));
Assert.Equal(c.Count, oracle.Count);
Assert.Equal<int>(c, oracle);
// Start taking some after we've added some
if (i > 50)
{
take();
}
}
// Take the rest
while (c.Count > 0)
{
take();
}
}
[Fact]
public void AddTake_RandomChangesMatchOracle()
{
const int Iters = 1000;
var r = new Random(42);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IProducerConsumerCollection<int> oracle = CreateOracle();
for (int i = 0; i < Iters; i++)
{
if (r.NextDouble() < .5)
{
Assert.Equal(oracle.TryAdd(i), c.TryAdd(i));
}
else
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
}
}
Assert.Equal(oracle.Count, c.Count);
}
[Theory]
[InlineData(100, 1, 100, true)]
[InlineData(100, 4, 10, false)]
[InlineData(1000, 11, 100, true)]
[InlineData(100000, 2, 50000, true)]
public void Initialize_ThenTakeOrPeekInParallel_ItemsObtainedAsExpected(int numStartingItems, int threadsCount, int itemsPerThread, bool take)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, numStartingItems));
int successes = 0;
using (var b = new Barrier(threadsCount))
{
WaitAllOrAnyFailed(Enumerable.Range(0, threadsCount).Select(threadNum => ThreadFactory.StartNew(() =>
{
b.SignalAndWait();
for (int j = 0; j < itemsPerThread; j++)
{
int data;
if (take ? c.TryTake(out data) : TryPeek(c, out data))
{
Interlocked.Increment(ref successes);
Assert.NotEqual(0, data); // shouldn't be default(T)
}
}
})).ToArray());
}
Assert.Equal(
take ? numStartingItems : threadsCount * itemsPerThread,
successes);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(1000)]
public void ToArray_AddAllItemsThenEnumerate_ItemsAndCountMatch(int count)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IProducerConsumerCollection<int> oracle = CreateOracle();
for (int i = 0; i < count; i++)
{
Assert.Equal(oracle.TryAdd(i + count), c.TryAdd(i + count));
}
Assert.Equal(oracle.ToArray(), c.ToArray());
if (count > 0)
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
Assert.Equal(oracle.ToArray(), c.ToArray());
}
}
[Theory]
[InlineData(1, 10)]
[InlineData(2, 10)]
[InlineData(10, 10)]
[InlineData(100, 10)]
public void ToArray_AddAndTakeItemsIntermixedWithEnumeration_ItemsAndCountMatch(int initialCount, int iters)
{
IEnumerable<int> initialItems = Enumerable.Range(1, initialCount);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems);
IProducerConsumerCollection<int> oracle = CreateOracle(initialItems);
for (int i = 0; i < iters; i++)
{
Assert.Equal<int>(oracle, c);
Assert.Equal(oracle.TryAdd(initialCount + i), c.TryAdd(initialCount + i));
Assert.Equal<int>(oracle, c);
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
Assert.Equal<int>(oracle, c);
}
}
[Fact]
public void AddFromMultipleThreads_ItemsRemainAfterThreadsGoAway()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
for (int i = 0; i < 1000; i += 100)
{
// Create a thread that adds items to the collection
ThreadFactory.StartNew(() =>
{
for (int j = i; j < i + 100; j++)
{
Assert.True(c.TryAdd(j));
}
}).GetAwaiter().GetResult();
// Allow threads to be collected
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
AssertSetsEqual(new HashSet<int>(Enumerable.Range(0, 1000)), new HashSet<int>(c));
}
[Fact]
public void AddManyItems_ThenTakeOnSameThread_ItemsOutputInExpectedOrder()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(0, 100000));
IProducerConsumerCollection<int> oracle = CreateOracle(Enumerable.Range(0, 100000));
for (int i = 99999; i >= 0; --i)
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
}
}
[Fact]
public void TryPeek_SucceedsOnEmptyCollectionThatWasOnceNonEmpty()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
int item;
for (int i = 0; i < 2; i++)
{
Assert.False(TryPeek(c, out item));
Assert.Equal(0, item);
}
Assert.True(c.TryAdd(42));
for (int i = 0; i < 2; i++)
{
Assert.True(TryPeek(c, out item));
Assert.Equal(42, item);
}
Assert.True(c.TryTake(out item));
Assert.Equal(42, item);
Assert.False(TryPeek(c, out item));
Assert.Equal(0, item);
Assert.False(c.TryTake(out item));
Assert.Equal(0, item);
}
[Fact]
public void AddTakeWithAtLeastOneElementInCollection_IsEmpty_AlwaysFalse()
{
int items = 1000;
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.True(c.TryAdd(0)); // make sure it's never empty
var cts = new CancellationTokenSource();
// Consumer repeatedly calls IsEmpty until it's told to stop
Task consumer = Task.Run(() =>
{
while (!cts.IsCancellationRequested) Assert.False(IsEmpty(c));
});
// Producer adds/takes a bunch of items, then tells the consumer to stop
Task producer = Task.Run(() =>
{
int ignored;
for (int i = 1; i <= items; i++)
{
Assert.True(c.TryAdd(i));
Assert.True(c.TryTake(out ignored));
}
cts.Cancel();
});
Task.WaitAll(producer, consumer);
}
[Fact]
public void CopyTo_Empty_NothingCopied()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
c.CopyTo(new int[0], 0);
c.CopyTo(new int[10], 10);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
public void CopyTo_SzArray_ZeroIndex_ExpectedElementsCopied(int size)
{
IEnumerable<int> initialItems = Enumerable.Range(1, size);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems);
int[] actual = new int[size];
c.CopyTo(actual, 0);
IProducerConsumerCollection<int> oracle = CreateOracle(initialItems);
int[] expected = new int[size];
oracle.CopyTo(expected, 0);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
public void CopyTo_SzArray_NonZeroIndex_ExpectedElementsCopied(int size)
{
IEnumerable<int> initialItems = Enumerable.Range(1, size);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems);
int[] actual = new int[size + 2];
c.CopyTo(actual, 1);
IProducerConsumerCollection<int> oracle = CreateOracle(initialItems);
int[] expected = new int[size + 2];
oracle.CopyTo(expected, 1);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
public void CopyTo_ArrayZeroLowerBound_ZeroIndex_ExpectedElementsCopied(int size)
{
IEnumerable<int> initialItems = Enumerable.Range(1, size);
ICollection c = CreateProducerConsumerCollection(initialItems);
Array actual = Array.CreateInstance(typeof(int), new int[] { size }, new int[] { 0 });
c.CopyTo(actual, 0);
ICollection oracle = CreateOracle(initialItems);
Array expected = Array.CreateInstance(typeof(int), new int[] { size }, new int[] { 0 });
oracle.CopyTo(expected, 0);
Assert.Equal(expected.Cast<int>(), actual.Cast<int>());
}
[Fact]
public void CopyTo_ArrayNonZeroLowerBound_ExpectedElementsCopied()
{
if (!PlatformDetection.IsNonZeroLowerBoundArraySupported)
return;
int[] initialItems = Enumerable.Range(1, 10).ToArray();
const int LowerBound = 1;
ICollection c = CreateProducerConsumerCollection(initialItems);
Array actual = Array.CreateInstance(typeof(int), new int[] { initialItems.Length }, new int[] { LowerBound });
c.CopyTo(actual, LowerBound);
ICollection oracle = CreateOracle(initialItems);
int[] expected = new int[initialItems.Length];
oracle.CopyTo(expected, 0);
for (int i = 0; i < expected.Length; i++)
{
Assert.Equal(expected[i], actual.GetValue(i + LowerBound));
}
}
[Fact]
public void CopyTo_InvalidArgs_Throws()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(0, 10));
int[] dest = new int[10];
AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(dest, -1));
AssertExtensions.Throws<ArgumentException>(CopyToNoLengthParamName, "", () => c.CopyTo(dest, dest.Length));
AssertExtensions.Throws<ArgumentException>(CopyToNoLengthParamName, "", () => c.CopyTo(dest, dest.Length - 2));
AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new int[7, 7], 0));
}
[Fact]
public void ICollectionCopyTo_InvalidArgs_Throws()
{
ICollection c = CreateProducerConsumerCollection(Enumerable.Range(0, 10));
Array dest = new int[10];
AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(dest, -1));
AssertExtensions.Throws<ArgumentException>(CopyToNoLengthParamName, "", () => c.CopyTo(dest, dest.Length));
AssertExtensions.Throws<ArgumentException>(CopyToNoLengthParamName, "", () => c.CopyTo(dest, dest.Length - 2));
}
[Theory]
[InlineData(100, 1, 10)]
[InlineData(4, 100000, 10)]
public void BlockingCollection_WrappingCollection_ExpectedElementsTransferred(int numThreadsPerConsumerProducer, int numItemsPerThread, int producerSpin)
{
var bc = new BlockingCollection<int>(CreateProducerConsumerCollection());
long dummy = 0;
Task[] producers = Enumerable.Range(0, numThreadsPerConsumerProducer).Select(_ => ThreadFactory.StartNew(() =>
{
for (int i = 1; i <= numItemsPerThread; i++)
{
for (int j = 0; j < producerSpin; j++) dummy *= j; // spin a little
bc.Add(i);
}
})).ToArray();
Task[] consumers = Enumerable.Range(0, numThreadsPerConsumerProducer).Select(_ => ThreadFactory.StartNew(() =>
{
for (int i = 0; i < numItemsPerThread; i++)
{
const int TimeoutMs = 100000;
int item;
Assert.True(bc.TryTake(out item, TimeoutMs), $"Couldn't get {i}th item after {TimeoutMs}ms");
Assert.NotEqual(0, item);
}
})).ToArray();
WaitAllOrAnyFailed(producers);
WaitAllOrAnyFailed(consumers);
}
[Fact]
public void GetEnumerator_NonGeneric()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IEnumerable e = c;
Assert.False(e.GetEnumerator().MoveNext());
Assert.True(c.TryAdd(42));
Assert.True(c.TryAdd(84));
var hs = new HashSet<int>(e.Cast<int>());
Assert.Equal(2, hs.Count);
Assert.Contains(42, hs);
Assert.Contains(84, hs);
}
[Fact]
public void GetEnumerator_EnumerationsAreSnapshots()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Empty(c);
using (IEnumerator<int> e1 = c.GetEnumerator())
{
Assert.True(c.TryAdd(1));
using (IEnumerator<int> e2 = c.GetEnumerator())
{
Assert.True(c.TryAdd(2));
using (IEnumerator<int> e3 = c.GetEnumerator())
{
int item;
Assert.True(c.TryTake(out item));
using (IEnumerator<int> e4 = c.GetEnumerator())
{
Assert.False(e1.MoveNext());
Assert.True(e2.MoveNext());
Assert.False(e2.MoveNext());
Assert.True(e3.MoveNext());
Assert.True(e3.MoveNext());
Assert.False(e3.MoveNext());
Assert.True(e4.MoveNext());
Assert.False(e4.MoveNext());
}
}
}
}
}
[Theory]
[InlineData(0, true)]
[InlineData(1, true)]
[InlineData(1, false)]
[InlineData(10, true)]
[InlineData(100, true)]
[InlineData(100, false)]
public async Task GetEnumerator_Generic_ExpectedElementsYielded(int numItems, bool consumeFromSameThread)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
using (var e = c.GetEnumerator())
{
Assert.False(e.MoveNext());
}
// Add, and validate enumeration after each item added
for (int i = 1; i <= numItems; i++)
{
Assert.True(c.TryAdd(i));
Assert.Equal(i, c.Count);
Assert.Equal(i, c.Distinct().Count());
}
// Take, and validate enumerate after each item removed.
Action consume = () =>
{
for (int i = 1; i <= numItems; i++)
{
int item;
Assert.True(c.TryTake(out item));
Assert.Equal(numItems - i, c.Count);
Assert.Equal(numItems - i, c.Distinct().Count());
}
};
if (consumeFromSameThread)
{
consume();
}
else
{
await ThreadFactory.StartNew(consume);
}
}
[Fact]
public void TryAdd_TryTake_ToArray()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.True(c.TryAdd(42));
Assert.Equal(new[] { 42 }, c.ToArray());
Assert.True(c.TryAdd(84));
Assert.Equal(new[] { 42, 84 }, c.ToArray().OrderBy(i => i));
int item;
Assert.True(c.TryTake(out item));
int remainingItem = item == 42 ? 84 : 42;
Assert.Equal(new[] { remainingItem }, c.ToArray());
Assert.True(c.TryTake(out item));
Assert.Equal(remainingItem, item);
Assert.Empty(c.ToArray());
}
[Fact]
public void ICollection_IsSynchronized_SyncRoot()
{
ICollection c = CreateProducerConsumerCollection();
Assert.False(c.IsSynchronized);
Assert.Throws<NotSupportedException>(() => c.SyncRoot);
}
[Fact]
public void ToArray_ParallelInvocations_Succeed()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Empty(c.ToArray());
const int NumItems = 10000;
Parallel.For(0, NumItems, i => Assert.True(c.TryAdd(i)));
Assert.Equal(NumItems, c.Count);
Parallel.For(0, 10, i =>
{
var hs = new HashSet<int>(c.ToArray());
Assert.Equal(NumItems, hs.Count);
});
}
[Fact]
public void ToArray_AddTakeSameThread_ExpectedResultsAfterAddsAndTakes()
{
const int Items = 20;
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IProducerConsumerCollection<int> oracle = CreateOracle();
for (int i = 0; i < Items; i++)
{
Assert.True(c.TryAdd(i));
Assert.True(oracle.TryAdd(i));
Assert.Equal(oracle.ToArray(), c.ToArray());
}
for (int i = Items - 1; i >= 0; i--)
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
Assert.Equal(oracle.ToArray(), c.ToArray());
}
}
[Fact]
public void GetEnumerator_ParallelInvocations_Succeed()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Empty(c.ToArray());
const int NumItems = 10000;
Parallel.For(0, NumItems, i => Assert.True(c.TryAdd(i)));
Assert.Equal(NumItems, c.Count);
Parallel.For(0, 10, i =>
{
var hs = new HashSet<int>(c);
Assert.Equal(NumItems, hs.Count);
});
}
[Theory]
[InlineData(1, ConcurrencyTestSeconds / 2)]
[InlineData(4, ConcurrencyTestSeconds / 2)]
public void ManyConcurrentAddsTakes_EnsureTrackedCountsMatchResultingCollection(int threadsPerProc, double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
DateTime end = default(DateTime);
using (var b = new Barrier(Environment.ProcessorCount * threadsPerProc, _ => end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds)))
{
Task<int>[] tasks = Enumerable.Range(0, b.ParticipantCount).Select(_ => ThreadFactory.StartNew(() =>
{
b.SignalAndWait();
int count = 0;
var rand = new Random();
while (DateTime.UtcNow < end)
{
if (rand.NextDouble() < .5)
{
Assert.True(c.TryAdd(rand.Next()));
count++;
}
else
{
int item;
if (c.TryTake(out item)) count--;
}
}
return count;
})).ToArray();
Task.WaitAll(tasks);
Assert.Equal(tasks.Sum(t => t.Result), c.Count);
}
}
[Fact]
[OuterLoop]
public void ManyConcurrentAddsTakes_CollectionRemainsConsistent()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
const int operations = 30000;
Action addAndRemove = () =>
{
for (int i = 1; i < operations; i++)
{
int addCount = new Random(12354).Next(1, 100);
int item;
for (int j = 0; j < addCount; j++)
Assert.True(c.TryAdd(i));
for (int j = 0; j < addCount; j++)
Assert.True(c.TryTake(out item));
}
};
const int numberOfThreads = 3;
var tasks = new Task[numberOfThreads];
for (int i = 0; i < numberOfThreads; i++)
tasks[i] = ThreadFactory.StartNew(addAndRemove);
// Wait for them all to finish
WaitAllOrAnyFailed(tasks);
Assert.Empty(c);
}
[Theory]
[InlineData(ConcurrencyTestSeconds)]
public void ManyConcurrentAddsTakesPeeks_ForceContentionWithOtherThreadsTaking(double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task<long> addsTakes = ThreadFactory.StartNew(() =>
{
long total = 0;
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(i));
total++;
}
int item;
if (TryPeek(c, out item))
{
Assert.InRange(item, 1, MaxCount);
}
for (int i = 1; i <= MaxCount; i++)
{
if (c.TryTake(out item))
{
total--;
Assert.InRange(item, 1, MaxCount);
}
}
}
return total;
});
Task<long> takesFromOtherThread = ThreadFactory.StartNew(() =>
{
long total = 0;
int item;
while (DateTime.UtcNow < end)
{
if (c.TryTake(out item))
{
total++;
Assert.InRange(item, 1, MaxCount);
}
}
return total;
});
WaitAllOrAnyFailed(addsTakes, takesFromOtherThread);
long remaining = addsTakes.Result - takesFromOtherThread.Result;
Assert.InRange(remaining, 0, long.MaxValue);
Assert.Equal(remaining, c.Count);
}
[Theory]
[InlineData(ConcurrencyTestSeconds)]
public void ManyConcurrentAddsTakesPeeks_ForceContentionWithOtherThreadsPeeking(double seconds)
{
IProducerConsumerCollection<LargeStruct> c = CreateProducerConsumerCollection<LargeStruct>();
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task<long> addsTakes = ThreadFactory.StartNew(() =>
{
long total = 0;
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(new LargeStruct(i)));
total++;
}
LargeStruct item;
Assert.True(TryPeek(c, out item));
Assert.InRange(item.Value, 1, MaxCount);
for (int i = 1; i <= MaxCount; i++)
{
if (c.TryTake(out item))
{
total--;
Assert.InRange(item.Value, 1, MaxCount);
}
}
}
return total;
});
Task peeksFromOtherThread = ThreadFactory.StartNew(() =>
{
LargeStruct item;
while (DateTime.UtcNow < end)
{
if (TryPeek(c, out item))
{
Assert.InRange(item.Value, 1, MaxCount);
}
}
});
WaitAllOrAnyFailed(addsTakes, peeksFromOtherThread);
Assert.Equal(0, addsTakes.Result);
Assert.Equal(0, c.Count);
}
[Theory]
[InlineData(ConcurrencyTestSeconds)]
public void ManyConcurrentAddsTakes_ForceContentionWithToArray(double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task addsTakes = ThreadFactory.StartNew(() =>
{
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(i));
}
for (int i = 1; i <= MaxCount; i++)
{
int item;
Assert.True(c.TryTake(out item));
Assert.InRange(item, 1, MaxCount);
}
}
});
while (DateTime.UtcNow < end)
{
int[] arr = c.ToArray();
Assert.InRange(arr.Length, 0, MaxCount);
Assert.DoesNotContain(0, arr); // make sure we didn't get default(T)
}
addsTakes.GetAwaiter().GetResult();
Assert.Equal(0, c.Count);
}
[Theory]
[InlineData(0, ConcurrencyTestSeconds / 2)]
[InlineData(1, ConcurrencyTestSeconds / 2)]
public void ManyConcurrentAddsTakes_ForceContentionWithGetEnumerator(int initialCount, double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, initialCount));
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task addsTakes = ThreadFactory.StartNew(() =>
{
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(i));
}
for (int i = 1; i <= MaxCount; i++)
{
int item;
Assert.True(c.TryTake(out item));
Assert.InRange(item, 1, MaxCount);
}
}
});
while (DateTime.UtcNow < end)
{
int[] arr = c.Select(i => i).ToArray();
Assert.InRange(arr.Length, initialCount, MaxCount + initialCount);
Assert.DoesNotContain(0, arr); // make sure we didn't get default(T)
}
addsTakes.GetAwaiter().GetResult();
Assert.Equal(initialCount, c.Count);
}
[Theory]
[InlineData(0)]
[InlineData(10)]
public void DebuggerAttributes_Success(int count)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(count);
DebuggerAttributes.ValidateDebuggerDisplayReferences(c);
DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(c);
PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden);
Array items = itemProperty.GetValue(info.Instance) as Array;
Assert.Equal(c, items.Cast<int>());
}
[Fact]
public void DebuggerTypeProxy_Ctor_NullArgument_Throws()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Type proxyType = DebuggerAttributes.GetProxyType(c);
var tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, new object[] { null }));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
protected static void AssertSetsEqual<T>(HashSet<T> expected, HashSet<T> actual)
{
Assert.Equal(expected.Count, actual.Count);
Assert.Subset(expected, actual);
Assert.Subset(actual, expected);
}
protected static void WaitAllOrAnyFailed(params Task[] tasks)
{
if (tasks.Length == 0)
{
return;
}
int remaining = tasks.Length;
var mres = new ManualResetEventSlim();
foreach (Task task in tasks)
{
task.ContinueWith(t =>
{
if (Interlocked.Decrement(ref remaining) == 0 || t.IsFaulted)
{
mres.Set();
}
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
mres.Wait();
// Either all tasks are completed or at least one failed
foreach (Task t in tasks)
{
if (t.IsFaulted)
{
t.GetAwaiter().GetResult(); // propagate for the first one that failed
}
}
}
private struct LargeStruct // used to help validate that values aren't torn while being read
{
private readonly long _a, _b, _c, _d, _e, _f, _g, _h;
public LargeStruct(long value) { _a = _b = _c = _d = _e = _f = _g = _h = value; }
public long Value
{
get
{
if (_a != _b || _a != _c || _a != _d || _a != _e || _a != _f || _a != _g || _a != _h)
{
throw new Exception($"Inconsistent {nameof(LargeStruct)}: {_a} {_b} {_c} {_d} {_e} {_f} {_g} {_h}");
}
return _a;
}
}
}
}
}
| |
// 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.
/* The Computer Language Benchmarks Game
http://benchmarksgame.alioth.debian.org/
contributed by Isaac Gouy
optimizations by Alp Toker <[email protected]>
modified for use with xunit-performance
*/
using Microsoft.Xunit.Performance;
using System;
using System.IO;
using System.Text;
[assembly: OptimizeForBenchmarks]
namespace BenchmarksGame
{
public class Fasta
{
#if DEBUG
private const int Iterations = 1;
#else
const int Iterations = 800;
#endif
public static int Main(string[] args)
{
MakeCumulative(s_homoSapiens);
MakeCumulative(s_IUB);
int n = args.Length > 0 ? Int32.Parse(args[0]) : 1000;
using (Stream s = Console.OpenStandardOutput())
{
MakeRepeatFasta("ONE", "Homo sapiens alu", Encoding.ASCII.GetBytes(s_ALU), n * 2, s);
MakeRandomFasta("TWO", "IUB ambiguity codes", s_IUB, n * 3, s);
MakeRandomFasta("THREE", "Homo sapiens frequency", s_homoSapiens, n * 5, s);
}
return 100;
}
[Benchmark]
public static void Bench()
{
int n = 5000;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Iterations; i++)
{
using (Stream s = Stream.Null)
{
MakeRepeatFasta("ONE", "Homo sapiens alu", Encoding.ASCII.GetBytes(s_ALU), n * 2, s);
MakeRandomFasta("TWO", "IUB ambiguity codes", s_IUB, n * 3, s);
MakeRandomFasta("THREE", "Homo sapiens frequency", s_homoSapiens, n * 5, s);
}
}
}
}
}
// The usual pseudo-random number generator
private const int IM = 139968;
private const int IA = 3877;
private const int IC = 29573;
private static int s_seed = 42;
private static double random(double max)
{
return max * ((s_seed = (s_seed * IA + IC) % IM) * (1.0 / IM));
}
// Weighted selection from alphabet
private static string s_ALU =
"GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG" +
"GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA" +
"CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT" +
"ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA" +
"GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG" +
"AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC" +
"AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA";
private class Frequency
{
public byte c;
public double p;
public Frequency(char c, double p)
{
this.c = (byte)c;
this.p = p;
}
}
private static Frequency[] s_IUB = {
new Frequency ('a', 0.27)
,new Frequency ('c', 0.12)
,new Frequency ('g', 0.12)
,new Frequency ('t', 0.27)
,new Frequency ('B', 0.02)
,new Frequency ('D', 0.02)
,new Frequency ('H', 0.02)
,new Frequency ('K', 0.02)
,new Frequency ('M', 0.02)
,new Frequency ('N', 0.02)
,new Frequency ('R', 0.02)
,new Frequency ('S', 0.02)
,new Frequency ('V', 0.02)
,new Frequency ('W', 0.02)
,new Frequency ('Y', 0.02)
};
private static Frequency[] s_homoSapiens = {
new Frequency ('a', 0.3029549426680)
,new Frequency ('c', 0.1979883004921)
,new Frequency ('g', 0.1975473066391)
,new Frequency ('t', 0.3015094502008)
};
private static void MakeCumulative(Frequency[] a)
{
double cp = 0.0;
for (int i = 0; i < a.Length; i++)
{
cp += a[i].p;
a[i].p = cp;
}
}
// naive
private static byte SelectRandom(Frequency[] a)
{
double r = random(1.0);
for (int i = 0; i < a.Length; i++)
if (r < a[i].p)
return a[i].c;
return a[a.Length - 1].c;
}
private const int LineLength = 60;
private static int s_index = 0;
private static byte[] s_buf = new byte[1024];
private static void MakeRandomFasta(string id, string desc, Frequency[] a, int n, Stream s)
{
s_index = 0;
int m = 0;
byte[] descStr = Encoding.ASCII.GetBytes(">" + id + " " + desc + "\n");
s.Write(descStr, 0, descStr.Length);
while (n > 0)
{
m = n < LineLength ? n : LineLength;
if (s_buf.Length - s_index < m)
{
s.Write(s_buf, 0, s_index);
s_index = 0;
}
for (int i = 0; i < m; i++)
{
s_buf[s_index++] = SelectRandom(a);
}
s_buf[s_index++] = (byte)'\n';
n -= LineLength;
}
if (s_index != 0)
s.Write(s_buf, 0, s_index);
}
private static void MakeRepeatFasta(string id, string desc, byte[] alu, int n, Stream s)
{
s_index = 0;
int m = 0;
int k = 0;
int kn = alu.Length;
byte[] descStr = Encoding.ASCII.GetBytes(">" + id + " " + desc + "\n");
s.Write(descStr, 0, descStr.Length);
while (n > 0)
{
m = n < LineLength ? n : LineLength;
if (s_buf.Length - s_index < m)
{
s.Write(s_buf, 0, s_index);
s_index = 0;
}
for (int i = 0; i < m; i++)
{
if (k == kn)
k = 0;
s_buf[s_index++] = alu[k];
k++;
}
s_buf[s_index++] = (byte)'\n';
n -= LineLength;
}
if (s_index != 0)
s.Write(s_buf, 0, s_index);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.NodejsTools.Jade
{
internal sealed class ServiceManager : IDisposable
{
private const string ServiceManagerId = "ServiceManager";
private IPropertyOwner _propertyOwner;
private object _lock = new object();
private Dictionary<Type, object> _servicesByType = new Dictionary<Type, object>();
private Dictionary<Guid, object> _servicesByGuid = new Dictionary<Guid, object>();
private Dictionary<Tuple<Type, string>, object> _servicesByContentType = new Dictionary<Tuple<Type, string>, object>();
private ServiceManager(IPropertyOwner propertyOwner)
{
this._propertyOwner = propertyOwner;
this._propertyOwner.Properties.AddProperty(ServiceManagerId, this);
}
/// <summary>
/// Returns service manager attached to a given Property owner
/// </summary>
/// <param name="propertyOwner">Property owner</param>
/// <returns>Service manager instance</returns>
public static ServiceManager FromPropertyOwner(IPropertyOwner propertyOwner)
{
ServiceManager sm = null;
if (propertyOwner.Properties.ContainsProperty(ServiceManagerId))
{
sm = propertyOwner.Properties.GetProperty(ServiceManagerId) as ServiceManager;
return sm;
}
return new ServiceManager(propertyOwner);
}
/// <summary>
/// Retrieves service from a service manager for this Property owner given service type
/// </summary>
/// <typeparam name="T">Service type</typeparam>
/// <param name="propertyOwner">Property owner</param>
/// <returns>Service instance</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public static T GetService<T>(IPropertyOwner propertyOwner) where T : class
{
try
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
Debug.Assert(sm != null);
return sm.GetService<T>();
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// Retrieves service from a service manager for this property owner given service type GUID.
/// Primarily used to retrieve services that implement COM interop and are usable from native code.
/// </summary>
/// <typeparam name="T">Service type</typeparam>
/// <param name="propertyOwner">Property owner</param>
/// <returns>Service instance</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public static object GetService(IPropertyOwner propertyOwner, ref Guid serviceGuid)
{
try
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
Debug.Assert(sm != null);
return sm.GetService(ref serviceGuid);
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// Retrieves service from a service manager for this Property owner given service type and content type
/// </summary>
/// <typeparam name="T">Service type</typeparam>
/// <param name="propertyOwner">Property owner</param>
/// <param name="contentType">Content type</param>
/// <returns>Service instance</returns>
public static T GetService<T>(IPropertyOwner propertyOwner, IContentType contentType) where T : class
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
if (sm != null)
return sm.GetService<T>(contentType);
return null;
}
public static ICollection<T> GetAllServices<T>(IPropertyOwner propertyOwner) where T : class
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
if (sm != null)
return sm.GetAllServices<T>();
return new List<T>();
}
/// <summary>
/// Add service to a service manager associated with a particular Property owner
/// </summary>
/// <typeparam name="T">Service type</typeparam>
/// <param name="serviceInstance">Service instance</param>
/// <param name="propertyOwner">Property owner</param>
public static void AddService<T>(T serviceInstance, IPropertyOwner propertyOwner) where T : class
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
Debug.Assert(sm != null);
sm.AddService<T>(serviceInstance);
}
/// <summary>
/// Add content type specific service to a service manager associated with a particular Property owner
/// </summary>
/// <typeparam name="T">Service type</typeparam>
/// <param name="serviceInstance">Service instance</param>
/// <param name="propertyOwner">Property owner</param>
/// <param name="contentType">Content type of the service</param>
public static void AddService<T>(T serviceInstance, IPropertyOwner propertyOwner, IContentType contentType) where T : class
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
Debug.Assert(sm != null);
sm.AddService<T>(serviceInstance, contentType);
}
/// <summary>
/// Add service to a service manager associated with a particular property owner.
/// Typically used to store services implemented in native code and identified by
/// the interface GUID.
/// </summary>
/// <typeparam name="serviceGuid">Service GUID</typeparam>
/// <param name="serviceInstance">Service instance</param>
/// <param name="propertyOwner">Property owner</param>
public static void AddService(ref Guid serviceGuid, object serviceInstance, IPropertyOwner propertyOwner)
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
Debug.Assert(sm != null);
sm.AddService(ref serviceGuid, serviceInstance);
}
public static void RemoveService<T>(IPropertyOwner propertyOwner) where T : class
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
Debug.Assert(sm != null);
sm.RemoveService<T>();
}
public static void RemoveService<T>(IPropertyOwner propertyOwner, IContentType contentType) where T : class
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
Debug.Assert(sm != null);
sm.RemoveService<T>(contentType);
}
public static void RemoveService(IPropertyOwner propertyOwner, ref Guid guidService)
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
Debug.Assert(sm != null);
sm.RemoveService(ref guidService);
}
private T GetService<T>() where T : class
{
lock (this._lock)
{
object service = null;
if (!this._servicesByType.TryGetValue(typeof(T), out service))
{
// try walk through and cast. Perhaps someone is asking for IFoo
// that is implemented on class Bar but Bar was added as Bar, not as IFoo
foreach (var kvp in this._servicesByType)
{
service = kvp.Value as T;
if (service != null)
break;
}
}
return service as T;
}
}
private T GetService<T>(IContentType contentType) where T : class
{
lock (this._lock)
{
object service = null;
this._servicesByContentType.TryGetValue(Tuple.Create(typeof(T), contentType.TypeName), out service);
if (service != null)
return service as T;
// Try walking through and cast. Perhaps someone is asking for IFoo
// that is implemented on class Bar but Bar was added as Bar, not as IFoo
foreach (var kvp in this._servicesByContentType)
{
if (StringComparer.OrdinalIgnoreCase.Equals(kvp.Key.Item2, contentType.TypeName))
{
service = kvp.Value as T;
if (service != null)
{
return service as T;
}
}
}
// iterate through base types since Razor, PHP and ASP.NET content type derive from HTML
foreach (var ct in contentType.BaseTypes)
{
service = GetService<T>(ct);
if (service != null)
break;
}
return service as T;
}
}
private object GetService(ref Guid serviceGuid)
{
lock (this._lock)
{
foreach (var kvp in this._servicesByGuid)
{
if (serviceGuid.Equals(kvp.Key))
return kvp.Value;
}
foreach (var kvp in this._servicesByType)
{
if (serviceGuid.Equals(kvp.Value.GetType().GUID))
return kvp.Value;
}
return null;
}
}
private ICollection<T> GetAllServices<T>() where T : class
{
var list = new List<T>();
lock (this._lock)
{
foreach (var kvp in this._servicesByType)
{
var service = kvp.Value as T;
if (service != null)
list.Add(service);
}
}
return list;
}
private void AddService<T>(T serviceInstance) where T : class
{
lock (this._lock)
{
if (GetService<T>() == null)
{
this._servicesByType.Add(typeof(T), serviceInstance);
}
}
}
private void AddService<T>(T serviceInstance, IContentType contentType) where T : class
{
lock (this._lock)
{
if (GetService<T>(contentType) == null)
{
this._servicesByContentType.Add(Tuple.Create(typeof(T), contentType.TypeName), serviceInstance);
}
}
}
private void AddService(ref Guid serviceGuid, object serviceInstance)
{
lock (this._lock)
{
if (GetService(ref serviceGuid) == null)
this._servicesByGuid.Add(serviceGuid, serviceInstance);
}
}
private void RemoveService<T>() where T : class
{
this._servicesByType.Remove(typeof(T));
}
private void RemoveService<T>(IContentType contentType) where T : class
{
lock (this._lock)
{
this._servicesByContentType.Remove(Tuple.Create(typeof(T), contentType.TypeName));
}
}
private void RemoveService(ref Guid guidService)
{
this._servicesByGuid.Remove(guidService);
}
public void Dispose()
{
if (this._propertyOwner != null)
{
this._propertyOwner.Properties.RemoveProperty(ServiceManagerId);
this._servicesByGuid.Clear();
this._servicesByType.Clear();
this._servicesByContentType.Clear();
this._propertyOwner = null;
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: booking/guarantees/guarantee_changes.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.Guarantees {
/// <summary>Holder for reflection information generated from booking/guarantees/guarantee_changes.proto</summary>
public static partial class GuaranteeChangesReflection {
#region Descriptor
/// <summary>File descriptor for booking/guarantees/guarantee_changes.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static GuaranteeChangesReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cipib29raW5nL2d1YXJhbnRlZXMvZ3VhcmFudGVlX2NoYW5nZXMucHJvdG8S",
"HmhvbG1zLnR5cGVzLmJvb2tpbmcuZ3VhcmFudGVlcxouYm9va2luZy9pbmRp",
"Y2F0b3JzL3Jlc2VydmF0aW9uX2luZGljYXRvci5wcm90bxouYm9va2luZy9n",
"dWFyYW50ZWVzL3ZvaWRfZ3VhcmFudGVlX3Jlc3VsdC5wcm90byJhChRWb2lk",
"R3VhcmFudGVlUmVxdWVzdBJJCgtyZXNlcnZhdGlvbhgBIAEoCzI0LmhvbG1z",
"LnR5cGVzLmJvb2tpbmcuaW5kaWNhdG9ycy5SZXNlcnZhdGlvbkluZGljYXRv",
"ciJrChVWb2lkR3VhcmFudGVlUmVzcG9uc2USUgoVdm9pZF9ndWFyYW50ZWVf",
"cmVzdWx0GAEgASgOMjMuaG9sbXMudHlwZXMuYm9va2luZy5ndWFyYW50ZWVz",
"LlZvaWRHdWFyYW50ZWVSZXN1bHRCIaoCHkhPTE1TLlR5cGVzLkJvb2tpbmcu",
"R3VhcmFudGVlc2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Guarantees.VoidGuaranteeResultReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Guarantees.VoidGuaranteeRequest), global::HOLMS.Types.Booking.Guarantees.VoidGuaranteeRequest.Parser, new[]{ "Reservation" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Guarantees.VoidGuaranteeResponse), global::HOLMS.Types.Booking.Guarantees.VoidGuaranteeResponse.Parser, new[]{ "VoidGuaranteeResult" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class VoidGuaranteeRequest : pb::IMessage<VoidGuaranteeRequest> {
private static readonly pb::MessageParser<VoidGuaranteeRequest> _parser = new pb::MessageParser<VoidGuaranteeRequest>(() => new VoidGuaranteeRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<VoidGuaranteeRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.Guarantees.GuaranteeChangesReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public VoidGuaranteeRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public VoidGuaranteeRequest(VoidGuaranteeRequest other) : this() {
Reservation = other.reservation_ != null ? other.Reservation.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public VoidGuaranteeRequest Clone() {
return new VoidGuaranteeRequest(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;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as VoidGuaranteeRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(VoidGuaranteeRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Reservation, other.Reservation)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (reservation_ != null) hash ^= Reservation.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);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (reservation_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Reservation);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(VoidGuaranteeRequest other) {
if (other == null) {
return;
}
if (other.reservation_ != null) {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
Reservation.MergeFrom(other.Reservation);
}
}
[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;
}
}
}
}
}
public sealed partial class VoidGuaranteeResponse : pb::IMessage<VoidGuaranteeResponse> {
private static readonly pb::MessageParser<VoidGuaranteeResponse> _parser = new pb::MessageParser<VoidGuaranteeResponse>(() => new VoidGuaranteeResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<VoidGuaranteeResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.Guarantees.GuaranteeChangesReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public VoidGuaranteeResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public VoidGuaranteeResponse(VoidGuaranteeResponse other) : this() {
voidGuaranteeResult_ = other.voidGuaranteeResult_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public VoidGuaranteeResponse Clone() {
return new VoidGuaranteeResponse(this);
}
/// <summary>Field number for the "void_guarantee_result" field.</summary>
public const int VoidGuaranteeResultFieldNumber = 1;
private global::HOLMS.Types.Booking.Guarantees.VoidGuaranteeResult voidGuaranteeResult_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Guarantees.VoidGuaranteeResult VoidGuaranteeResult {
get { return voidGuaranteeResult_; }
set {
voidGuaranteeResult_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as VoidGuaranteeResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(VoidGuaranteeResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (VoidGuaranteeResult != other.VoidGuaranteeResult) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (VoidGuaranteeResult != 0) hash ^= VoidGuaranteeResult.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 (VoidGuaranteeResult != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) VoidGuaranteeResult);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (VoidGuaranteeResult != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) VoidGuaranteeResult);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(VoidGuaranteeResponse other) {
if (other == null) {
return;
}
if (other.VoidGuaranteeResult != 0) {
VoidGuaranteeResult = other.VoidGuaranteeResult;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
voidGuaranteeResult_ = (global::HOLMS.Types.Booking.Guarantees.VoidGuaranteeResult) input.ReadEnum();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
<?cs # A link to a package ?><?cs
def:package_link(pkg) ?>
<a href="<?cs var:toroot ?><?cs var:pkg.link ?>"><?cs var:pkg.name ?></a><?cs
/def ?>
<?cs # A link to a type, or not if it's a primitive type
link: whether to create a link at the top level, always creates links in
recursive invocations.
Expects the following fields:
.name
.link
.isPrimitive
.superBounds.N.(more links) (... super ... & ...)
.extendsBounds.N.(more links) (... extends ... & ...)
.typeArguments.N.(more links) (< ... >)
?><?cs
def:type_link_impl(type, link) ?><?cs
if:type.link && link=="true" ?><?cs
if:type.federated ?><a href="<?cs var:type.link ?>"><?cs
var:type.label ?></a><?cs
else ?><a href="<?cs var:toroot ?><?cs var:type.link ?>"><?cs var:type.label ?></a><?cs
/if ?><?cs
else ?><?cs var:type.label ?><?cs
/if ?><?cs if:subcount(type.extendsBounds) ?><?cs
each:t=type.extendsBounds ?><?cs
if:first(t) ?> extends <?cs else ?> & <?cs /if ?><?cs
call:type_link_impl(t, "true") ?><?cs
/each ?><?cs
/if ?><?cs
if:subcount(type.superBounds) ?><?cs
each:t=type.superBounds ?><?cs
if:first(t) ?> super <?cs else ?> & <?cs /if ?><?cs
call:type_link_impl(t, "true") ?><?cs
/each ?><?cs
/if ?><?cs
if:subcount(type.typeArguments)
?><<?cs each:t=type.typeArguments ?><?cs call:type_link_impl(t, "true") ?><?cs
if:!last(t) ?>, <?cs /if ?><?cs
/each ?>><?cs
/if ?><?cs
/def ?>
<?cs def:class_name(type) ?><?cs call:type_link_impl(type, "false") ?><?cs /def ?>
<?cs def:type_link(type) ?><?cs call:type_link_impl(type, "true") ?><?cs /def ?>
<?cs # a conditional link.
if the "condition" parameter evals to true then the link is displayed
otherwise only the text is displayed
?><?cs
def:cond_link(text, root, path, condition) ?><?cs
if:condition ?><a href="<?cs var:root ?><?cs var:path ?>"><?cs /if ?><?cs var:text ?><?cs if:condition ?></a><?cs /if ?><?cs
/def ?>
<?cs # A comma separated parameter list ?><?cs
def:parameter_list(params) ?><?cs
each:param = params ?><?cs
call:type_link(param.type)?> <?cs
var:param.name ?><?cs
if: name(param)!=subcount(params)-1?>, <?cs /if ?><?cs
/each ?><?cs
/def ?>
<?cs # Print a list of tags (e.g. description text ?><?cs
def:tag_list(tags) ?><?cs
each:tag = tags ?><?cs
if:tag.name == "Text" ?><?cs var:tag.text?><?cs
elif:tag.kind == "@more" ?><p><?cs
elif:tag.kind == "@see" ?><code><a href="<?cs
if:tag.isLocal?><?cs var:toroot ?><?cs /if ?><?cs
var:tag.href ?>"><?cs var:tag.label ?></a></code><?cs
elif:tag.kind == "@seeHref" ?><a href="<?cs var:tag.href ?>"><?cs var:tag.label ?></a><?cs
elif:tag.kind == "@seeJustLabel" ?><?cs var:tag.label ?><?cs
elif:tag.kind == "@code" ?><code><?cs var:tag.text ?></code><?cs
elif:tag.kind == "@samplecode" ?><pre><?cs var:tag.text ?></pre><?cs
elif:tag.name == "@sample" ?><pre><?cs var:tag.text ?></pre><?cs
elif:tag.name == "@include" ?><?cs var:tag.text ?><?cs
elif:tag.kind == "@docRoot" ?><?cs var:toroot ?><?cs
elif:tag.kind == "@sdkCurrent" ?><?cs var:sdk.current ?><?cs
elif:tag.kind == "@sdkCurrentVersion" ?><?cs var:sdk.version ?><?cs
elif:tag.kind == "@sdkCurrentRelId" ?><?cs var:sdk.rel.id ?><?cs
elif:tag.kind == "@sdkPlatformVersion" ?><?cs var:sdk.platform.version ?><?cs
elif:tag.kind == "@sdkPlatformApiLevel" ?><?cs var:sdk.platform.apiLevel ?><?cs
elif:tag.kind == "@sdkPlatformMajorMinor" ?><?cs var:sdk.platform.majorMinor ?><?cs
elif:tag.kind == "@sdkPlatformReleaseDate" ?><?cs var:sdk.platform.releaseDate ?><?cs
elif:tag.kind == "@sdkPlatformDeployableDate" ?><?cs var:sdk.platform.deployableDate ?><?cs
elif:tag.kind == "@adtZipVersion" ?><?cs var:adt.zip.version ?><?cs
elif:tag.kind == "@adtZipDownload" ?><?cs var:adt.zip.download ?><?cs
elif:tag.kind == "@adtZipBytes" ?><?cs var:adt.zip.bytes ?><?cs
elif:tag.kind == "@adtZipChecksum" ?><?cs var:adt.zip.checksum ?><?cs
elif:tag.kind == "@inheritDoc" ?><?cs # This is the case when @inheritDoc is in something
that doesn't inherit from anything?><?cs
elif:tag.kind == "@attr" ?><?cs
else ?>{<?cs var:tag.name?> <?cs var:tag.text ?>}<?cs
/if ?><?cs
/each ?><?cs
/def ?>
<?cs # The message about This xxx is deprecated. ?><?cs
def:deprecated_text(kind) ?>
This <?cs var:kind ?> is deprecated.<?cs
/def ?>
<?cs # Show the short-form description of something. These come from shortDescr and deprecated ?><?cs
def:short_descr(obj) ?><?cs
if:subcount(obj.deprecated) ?>
<em><?cs call:deprecated_text(obj.kind) ?>
<?cs call:tag_list(obj.deprecated) ?></em><?cs
else ?><?cs call:tag_list(obj.shortDescr) ?><?cs
/if ?><?cs
/def ?>
<?cs # Show the red box with the deprecated warning ?><?cs
def:deprecated_warning(obj) ?><?cs
if:subcount(obj.deprecated) ?><p>
<p class="caution">
<strong><?cs call:deprecated_text(obj.kind) ?></strong><br/> <?cs
call:tag_list(obj.deprecated) ?>
</p><?cs
/if ?><?cs
/def ?>
<?cs # print the See Also: section ?><?cs
def:see_also_tags(also) ?><?cs
if:subcount(also) ?>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">See Also</h5>
<ul class="nolist"><?cs
each:tag=also ?><li><?cs
if:tag.kind == "@see" ?><code><a href="<?cs var:toroot ?><?cs var:tag.href ?>"><?cs
var:tag.label ?></a></code><?cs
elif:tag.kind == "@seeHref" ?><a href="<?cs var:tag.href ?>"><?cs var:tag.label ?></a><?cs
elif:tag.kind == "@seeJustLabel" ?><?cs var:tag.label ?><?cs
else ?>[ERROR: Unknown @see kind]<?cs
/if ?></li><?cs
/each ?>
</ul>
</div><?cs
/if ?>
<?cs /def ?>
<?cs # print the API Level ?><?cs
def:since_tags(obj) ?>
<?cs if:reference.apilevels ?>
Since: <a href="<?cs var:toroot ?>guide/appendix/api-levels.html#level<?cs var:obj.since.key ?>">API Level <?cs var:obj.since.name ?></a>
<?cs /if ?>
<?cs /def ?>
<?cs def:federated_refs(obj) ?>
<?cs if:subcount(obj.federated) ?>
<div>
Also:
<?cs each:federated=obj.federated ?>
<a href="<?cs var:federated.url ?>"><?cs var:federated.name ?></a><?cs
if:!last(federated) ?>,<?cs /if ?>
<?cs /each ?>
</div>
<?cs /if ?>
<?cs /def ?>
<?cs # Print the long-form description for something.
Uses the following fields: deprecated descr seeAlso since ?><?cs
def:description(obj) ?><?cs
call:deprecated_warning(obj) ?>
<div class="jd-tagdata jd-tagdescr"><p><?cs call:tag_list(obj.descr) ?></p></div><?cs
if:subcount(obj.attrRefs) ?>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Related XML Attributes</h5>
<ul class="nolist"><?cs
each:attr=obj.attrRefs ?>
<li><a href="<?cs var:toroot ?><?cs var:attr.href ?>"><?cs var:attr.name ?></a></li><?cs
/each ?>
</ul>
</div><?cs
/if ?><?cs
if:subcount(obj.paramTags) ?>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable"><?cs
each:tag=obj.paramTags ?>
<tr>
<th><?cs if:tag.isTypeParameter ?><<?cs /if ?><?cs var:tag.name
?><?cs if:tag.isTypeParameter ?>><?cs /if ?></td>
<td><?cs call:tag_list(tag.comment) ?></td>
</tr><?cs
/each ?>
</table>
</div><?cs
/if ?><?cs
if:subcount(obj.returns) ?>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li><?cs call:tag_list(obj.returns) ?></li></ul>
</div><?cs
/if ?><?cs
if:subcount(obj.throws) ?>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Throws</h5>
<table class="jd-tagtable"><?cs
each:tag=obj.throws ?>
<tr>
<th><?cs call:type_link(tag.type) ?></td>
<td><?cs call:tag_list(tag.comment) ?></td>
</tr><?cs
/each ?>
</table>
</div><?cs
/if ?><?cs
call:see_also_tags(obj.seeAlso) ?><?cs
/def ?>
<?cs # A table of links to classes with descriptions, as in a package file or the nested classes ?><?cs
def:class_link_table(classes) ?><?cs
set:count = #1 ?>
<table class="jd-sumtable-expando"><?cs
each:cl=classes ?>
<tr class="<?cs if:count % #2 ?>alt-color<?cs /if ?> api apilevel-<?cs var:cl.type.since.key ?>" >
<td class="jd-linkcol"><?cs call:type_link(cl.type) ?></td>
<td class="jd-descrcol" width="100%"><?cs call:short_descr(cl) ?> </td>
</tr><?cs set:count = count + #1 ?><?cs
/each ?>
</table><?cs
/def ?>
<?cs # A list of links to classes, for use in the side navigation of classes when viewing a package (panel nav) ?><?cs
def:class_link_list(label, classes) ?><?cs
if:subcount(classes) ?>
<li><h2><?cs var:label ?></h2>
<ul><?cs
each:cl=classes ?>
<li class="api apilevel-<?cs var:cl.type.since.key ?>"><?cs call:type_link(cl.type) ?></li><?cs
/each ?>
</ul>
</li><?cs
/if ?><?cs
/def ?>
<?cs # A list of links to classes, for use in the side navigation of classes when viewing a class (panel nav) ?><?cs
def:list(label, classes) ?><?cs
if:subcount(classes) ?>
<li><h2><?cs var:label ?></h2>
<ul><?cs
each:cl=classes ?>
<li class="<?cs if:class.name == cl.label?>selected <?cs /if ?>api apilevel-<?cs var:cl.since.key ?>"><?cs call:type_link(cl) ?></li><?cs
/each ?>
</ul>
</li><?cs
/if ?><?cs
/def ?>
<?cs # A list of links to packages, for use in the side navigation of packages (panel nav) ?><?cs
def:package_link_list(packages) ?><?cs
each:pkg=packages ?>
<li class="<?cs if:(class.package.name == pkg.name) || (package.name == pkg.name)?>selected <?cs /if ?>api apilevel-<?cs var:pkg.since.key ?>"><?cs call:package_link(pkg) ?></li><?cs
/each ?><?cs
/def ?>
<?cs # An expando trigger ?><?cs
def:expando_trigger(id, default) ?>
<a href="#" onclick="return toggleInherited(this, null)" id="<?cs var:id ?>" class="jd-expando-trigger closed"
><img id="<?cs var:id ?>-trigger"
src="<?cs var:toassets ?>images/triangle-<?cs var:default ?>.png"
class="jd-expando-trigger-img" /></a><?cs
/def ?>
<?cs # An expandable list of classes ?><?cs
def:expandable_class_list(id, classes, default) ?>
<div id="<?cs var:id ?>">
<div id="<?cs var:id ?>-list"
class="jd-inheritedlinks"
<?cs if:default != "list" ?>style="display: none;"<?cs /if ?>
>
<?cs if:subcount(classes) <= #20 ?>
<?cs each:cl=classes ?>
<?cs call:type_link(cl.type) ?><?cs if:!last(cl) ?>,<?cs /if ?>
<?cs /each ?>
<?cs else ?>
<?cs set:leftovers = subcount(classes) - #15 ?>
<?cs loop:i = #0, #14, #1 ?>
<?cs with:cl=classes[i] ?>
<?cs call:type_link(cl.type) ?>,
<?cs /with ?>
<?cs if:(#i == #14) ?>and
<a href="#" onclick="return toggleInherited(document.getElementById('<?cs
var:id ?>', null))"><?cs var:leftovers ?> others.</a>
<?cs /if ?>
<?cs /loop ?>
<?cs /if ?>
</div>
<div id="<?cs var:id ?>-summary"
<?cs if:default != "summary" ?>style="display: none;"<?cs /if ?>
><?cs
call:class_link_table(classes) ?>
</div>
</div><?cs
/def ?>
<?cs include:"components.cs" ?>
| |
// 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.Globalization;
using Xunit;
public class DateTimeOffsetTests
{
[Fact]
public static void TestConstructors()
{
DateTimeOffset dt = new DateTimeOffset(new DateTime(2012, 6, 11, 0, 0, 0, DateTimeKind.Utc));
ValidateYearMonthDay(dt, 2012, 6, 11);
dt = new DateTimeOffset(new DateTime(2012, 12, 31, 13, 50, 10), TimeSpan.Zero);
ValidateYearMonthDay(dt, 2012, 12, 31, 13, 50, 10);
dt = new DateTimeOffset(1973, 10, 6, 14, 30, 0, 500, TimeSpan.Zero);
ValidateYearMonthDay(dt, 1973, 10, 6, 14, 30, 0, 500);
dt = new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, DateTimeKind.Local));
ValidateYearMonthDay(dt, 1986, 8, 15, 10, 20, 5);
dt = new DateTimeOffset(DateTime.MinValue, TimeSpan.FromHours(-14));
ValidateYearMonthDay(dt, 1, 1, 1, 0, 0, 0);
dt = new DateTimeOffset(DateTime.MaxValue, TimeSpan.FromHours(14));
ValidateYearMonthDay(dt, 9999, 12, 31, 23, 59, 59);
Assert.Throws<ArgumentException>(() => new DateTimeOffset(DateTime.Now, TimeSpan.FromHours(-15)));
Assert.Throws<ArgumentException>(() => new DateTimeOffset(DateTime.Now, TimeSpan.FromHours(15)));
}
[Fact]
public static void TestDateTimeLimits()
{
DateTimeOffset dt = DateTimeOffset.MaxValue;
ValidateYearMonthDay(dt, 9999, 12, 31);
dt = DateTimeOffset.MinValue;
ValidateYearMonthDay(dt, 1, 1, 1);
}
[Fact]
public static void TestAddition()
{
DateTimeOffset dt = new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70));
Assert.Equal(17, dt.AddDays(2).Day);
Assert.Equal(13, dt.AddDays(-2).Day);
Assert.Equal(10, dt.AddMonths(2).Month);
Assert.Equal(6, dt.AddMonths(-2).Month);
Assert.Equal(1996, dt.AddYears(10).Year);
Assert.Equal(1976, dt.AddYears(-10).Year);
Assert.Equal(13, dt.AddHours(3).Hour);
Assert.Equal(7, dt.AddHours(-3).Hour);
Assert.Equal(25, dt.AddMinutes(5).Minute);
Assert.Equal(15, dt.AddMinutes(-5).Minute);
Assert.Equal(35, dt.AddSeconds(30).Second);
Assert.Equal(2, dt.AddSeconds(-3).Second);
Assert.Equal(80, dt.AddMilliseconds(10).Millisecond);
Assert.Equal(60, dt.AddMilliseconds(-10).Millisecond);
}
[Fact]
public static void TestDayOfWeek()
{
DateTimeOffset dt = new DateTimeOffset(new DateTime(2012, 6, 18));
Assert.Equal(DayOfWeek.Monday, dt.DayOfWeek);
}
[Fact]
public static void TestTimeSpan()
{
DateTimeOffset dt = new DateTimeOffset(new DateTime(2012, 6, 18, 10, 5, 1, 0));
TimeSpan ts = dt.TimeOfDay;
DateTimeOffset newDate = dt.Subtract(ts);
Assert.Equal(new DateTimeOffset(new DateTime(2012, 6, 18, 0, 0, 0, 0)).Ticks, newDate.Ticks);
Assert.Equal(dt.Ticks, newDate.Add(ts).Ticks);
}
[Fact]
public static void TestToday()
{
DateTimeOffset today = new DateTimeOffset(DateTime.Today);
DateTimeOffset now = DateTimeOffset.Now;
ValidateYearMonthDay(today, now.Year, now.Month, now.Day);
today = new DateTimeOffset(new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, DateTimeKind.Utc));
Assert.Equal(TimeSpan.Zero, today.Offset);
Assert.Equal(false, today.UtcDateTime.IsDaylightSavingTime());
}
[Fact]
public static void TestConversion()
{
DateTimeOffset today = new DateTimeOffset(DateTime.Today);
long dateTimeRaw = today.ToFileTime();
Assert.Equal(today, DateTimeOffset.FromFileTime(dateTimeRaw));
}
[Fact]
public static void TestRoundTripDateTime()
{
DateTime now = DateTime.Now;
DateTimeOffset dto = new DateTimeOffset(now);
Assert.Equal(DateTime.Today, dto.Date);
Assert.Equal(now, dto.DateTime);
Assert.Equal(now.ToUniversalTime(), dto.UtcDateTime);
}
[Fact]
public static void TestOperators()
{
DateTimeOffset date1 = new DateTimeOffset(new DateTime(1996, 6, 3, 22, 15, 0, DateTimeKind.Utc));
DateTimeOffset date2 = new DateTimeOffset(new DateTime(1996, 12, 6, 13, 2, 0, DateTimeKind.Utc));
DateTimeOffset date3 = new DateTimeOffset(new DateTime(1996, 10, 12, 8, 42, 0, DateTimeKind.Utc));
// diff1 gets 185 days, 14 hours, and 47 minutes.
TimeSpan diff1 = date2.Subtract(date1);
Assert.Equal(new TimeSpan(185, 14, 47, 0), diff1);
// date4 gets 4/9/1996 5:55:00 PM.
DateTimeOffset date4 = date3.Subtract(diff1);
Assert.Equal(new DateTimeOffset(new DateTime(1996, 4, 9, 17, 55, 0, DateTimeKind.Utc)), date4);
// diff2 gets 55 days 4 hours and 20 minutes.
TimeSpan diff2 = date2 - date3;
Assert.Equal(new TimeSpan(55, 4, 20, 0), diff2);
// date5 gets 4/9/1996 5:55:00 PM.
DateTimeOffset date5 = date1 - diff2;
Assert.Equal(new DateTimeOffset(new DateTime(1996, 4, 9, 17, 55, 0, DateTimeKind.Utc)), date5);
}
[Fact]
public static void TestParsingDateTimeWithTimeDesignator()
{
DateTimeOffset result;
Assert.True(DateTimeOffset.TryParse("4/21 5am", new CultureInfo("en-US"), DateTimeStyles.None, out result));
Assert.Equal(4, result.Month);
Assert.Equal(21, result.Day);
Assert.Equal(5, result.Hour);
Assert.True(DateTimeOffset.TryParse("4/21 5pm", new CultureInfo("en-US"), DateTimeStyles.None, out result));
Assert.Equal(4, result.Month);
Assert.Equal(21, result.Day);
Assert.Equal(17, result.Hour);
}
public class MyFormatter : IFormatProvider
{
public object GetFormat(Type formatType)
{
if (typeof(IFormatProvider) == formatType)
{
return this;
}
else
{
return null;
}
}
}
[Fact]
public static void TestParseWithAssumeUniversal()
{
var formatter = new MyFormatter();
var dateBefore = DateTime.Now.ToString();
var dateAfter = DateTimeOffset.ParseExact(dateBefore, "G", formatter, DateTimeStyles.AssumeUniversal);
Assert.Equal(dateBefore, dateAfter.DateTime.ToString());
}
[Fact]
public static void TestFormatParse()
{
DateTimeOffset dt = new DateTimeOffset(new DateTime(2012, 12, 21, 10, 8, 6));
CultureInfo ci = new CultureInfo("ja-JP");
string s = string.Format(ci, "{0}", dt);
Assert.Equal(dt, DateTimeOffset.Parse(s, ci));
}
[Fact]
public static void TestParse1()
{
DateTimeOffset src = DateTimeOffset.MaxValue;
String s = src.ToString();
DateTimeOffset in_1 = DateTimeOffset.Parse(s);
String actual = in_1.ToString();
Assert.Equal(s, actual);
}
[Fact]
public static void TestParse2()
{
DateTimeOffset src = DateTimeOffset.MaxValue;
String s = src.ToString();
DateTimeOffset in_1 = DateTimeOffset.Parse(s, null);
String actual = in_1.ToString();
Assert.Equal(s, actual);
}
[Fact]
public static void TestParse3()
{
DateTimeOffset src = DateTimeOffset.MaxValue;
String s = src.ToString();
DateTimeOffset in_1 = DateTimeOffset.Parse(s, null, DateTimeStyles.None);
String actual = in_1.ToString();
Assert.Equal(s, actual);
}
[Fact]
public static void TestParseExact2()
{
DateTimeOffset src = DateTimeOffset.MaxValue;
String s = src.ToString("u");
DateTimeOffset in_1 = DateTimeOffset.ParseExact(s, "u", null, DateTimeStyles.None);
String actual = in_1.ToString("u");
Assert.Equal(s, actual);
}
[Fact]
public static void TestParseExact3()
{
DateTimeOffset src = DateTimeOffset.MaxValue;
String s = src.ToString("g");
DateTimeOffset in_1 = DateTimeOffset.ParseExact(s, "g", null, DateTimeStyles.AssumeUniversal);
String actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestParseExact4()
{
DateTimeOffset src = DateTimeOffset.MaxValue;
String s = src.ToString("o");
DateTimeOffset in_1 = DateTimeOffset.ParseExact(s, "o", null, DateTimeStyles.None);
String actual = in_1.ToString("o");
Assert.Equal(s, actual);
}
[Fact]
public static void TestParseExact4a()
{
DateTimeOffset src = DateTimeOffset.MaxValue;
String s = src.ToString("g");
String[] formats = { "g" };
DateTimeOffset in_1 = DateTimeOffset.ParseExact(s, formats, null, DateTimeStyles.AssumeUniversal);
String actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestTryParse1()
{
DateTimeOffset src = DateTimeOffset.MaxValue;
String s = src.ToString("u");
DateTimeOffset in_1;
bool b = DateTimeOffset.TryParse(s, out in_1);
Assert.True(b);
String actual = in_1.ToString("u");
Assert.Equal(s, actual);
}
[Fact]
public static void TestTryParse2()
{
DateTimeOffset src = DateTimeOffset.MaxValue;
String s = src.ToString("u");
DateTimeOffset in_1;
bool b = DateTimeOffset.TryParse(s, out in_1);
Assert.True(b);
String actual = in_1.ToString("u");
Assert.Equal(s, actual);
}
[Fact]
public static void TestTryParse4()
{
DateTimeOffset src = DateTimeOffset.MaxValue;
String s = src.ToString("u");
DateTimeOffset in_1;
bool b = DateTimeOffset.TryParse(s, null, DateTimeStyles.None, out in_1);
Assert.True(b);
String actual = in_1.ToString("u");
Assert.Equal(s, actual);
}
[Fact]
public static void TestTryParse4a()
{
DateTimeOffset src = DateTimeOffset.MaxValue;
String s = src.ToString("g");
DateTimeOffset in_1;
bool b = DateTimeOffset.TryParse(s, null, DateTimeStyles.AssumeUniversal, out in_1);
Assert.True(b);
String actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestTryParseExact()
{
DateTimeOffset src = DateTimeOffset.MaxValue;
String s = src.ToString("g");
DateTimeOffset in_1;
bool b = DateTimeOffset.TryParseExact(s, "g", null, DateTimeStyles.AssumeUniversal, out in_1);
Assert.True(b);
String actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestTryParseExactA()
{
DateTimeOffset src = DateTimeOffset.MaxValue;
String s = src.ToString("g");
String[] formats = { "g" };
DateTimeOffset in_1;
bool b = DateTimeOffset.TryParseExact(s, formats, null, DateTimeStyles.AssumeUniversal, out in_1);
Assert.True(b);
String actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
internal static void ValidateYearMonthDay(DateTimeOffset dt, int year, int month, int day)
{
Assert.Equal(year, dt.Year);
Assert.Equal(month, dt.Month);
Assert.Equal(day, dt.Day);
}
internal static void ValidateYearMonthDay(DateTimeOffset dt, int year, int month, int day, int hour, int minute, int second)
{
ValidateYearMonthDay(dt, year, month, day);
Assert.Equal(hour, dt.Hour);
Assert.Equal(minute, dt.Minute);
Assert.Equal(second, dt.Second);
}
internal static void ValidateYearMonthDay(DateTimeOffset dt, int year, int month, int day, int hour, int minute, int second, int millisecond)
{
ValidateYearMonthDay(dt, year, month, day, hour, minute, second);
Assert.Equal(dt.Millisecond, millisecond);
}
}
| |
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using NGraphics.Codes;
namespace NGraphics.Models
{
[StructLayout(LayoutKind.Sequential)]
public struct Color
{
public byte B;
public byte G;
public byte R;
public byte A;
public double Red
{
get { return R/255.0; }
set { R = Round(value); }
}
public double Green
{
get { return G/255.0; }
set { G = Round(value); }
}
public double Blue
{
get { return B/255.0; }
set { B = Round(value); }
}
public double Alpha
{
get { return A/255.0; }
set { A = Round(value); }
}
private static byte Round(double c)
{
return (byte) (Math.Min(255, Math.Max(0, (int) (c*255 + 0.5))));
}
public int Argb
{
get { return (A << 24) | (R << 16) | (G << 8) | B; }
}
private Color(byte r, byte g, byte b, byte a)
{
R = r;
G = g;
B = b;
A = a;
}
public Color(double red, double green, double blue, double alpha)
{
R = (byte) (Math.Min(255, Math.Max(0, (int) (red*255 + 0.5))));
G = (byte) (Math.Min(255, Math.Max(0, (int) (green*255 + 0.5))));
B = (byte) (Math.Min(255, Math.Max(0, (int) (blue*255 + 0.5))));
A = (byte) (Math.Min(255, Math.Max(0, (int) (alpha*255 + 0.5))));
}
public Color(double red, double green, double blue)
{
R = (byte) (Math.Min(255, Math.Max(0, (int) (red*255 + 0.5))));
G = (byte) (Math.Min(255, Math.Max(0, (int) (green*255 + 0.5))));
B = (byte) (Math.Min(255, Math.Max(0, (int) (blue*255 + 0.5))));
A = 255;
}
public Color(double white, double alpha = 1.0)
{
var W = (byte) (Math.Min(255, Math.Max(0, (int) (white*255 + 0.5))));
R = W;
G = W;
B = W;
A = (byte) (Math.Min(255, Math.Max(0, (int) (alpha*255 + 0.5))));
}
public Color(string colorString)
{
Color color;
if (Colors.TryParse(colorString, out color))
{
R = color.R;
G = color.G;
B = color.B;
A = color.A;
}
else
{
throw new ArgumentException("Bad color string: " + colorString);
}
}
public Color BlendWith(Color other, double otherWeight)
{
var t = otherWeight;
var t1 = 1 - t;
var r = Red*t1 + other.Red*t;
var g = Green*t1 + other.Green*t;
var b = Blue*t1 + other.Blue*t;
var a = Alpha*t1 + other.Alpha*t;
return new Color(r, g, b, a);
}
public Color WithAlpha(double alpha)
{
var a = (byte) (Math.Min(255, Math.Max(0, (int) (alpha*255 + 0.5))));
return new Color(R, G, B, a);
}
public static Color FromHSB(double hue, double saturation, double brightness, double alpha = 1.0)
{
var c = saturation*brightness;
var hp = hue;
if (hp < 0)
hp = 1 - ((-hp)%1);
if (hp > 1)
hp = hp%1;
hp *= 6;
var x = c*(1 - Math.Abs((hp%2) - 1));
double r1, g1, b1;
if (hp < 1)
{
r1 = c;
g1 = x;
b1 = 0;
}
else if (hp < 2)
{
r1 = x;
g1 = c;
b1 = 0;
}
else if (hp < 3)
{
r1 = 0;
g1 = c;
b1 = x;
}
else if (hp < 4)
{
r1 = 0;
g1 = x;
b1 = c;
}
else if (hp < 5)
{
r1 = x;
g1 = 0;
b1 = c;
}
else
{
r1 = c;
g1 = 0;
b1 = x;
}
var m = brightness - c;
return new Color(r1 + m, g1 + m, b1 + m, alpha);
}
public static Color FromHSL(double hue, double saturation, double lightness, double alpha = 1.0)
{
var c = (1 - Math.Abs(2 * lightness - 1)) * saturation;
var hp = hue;
if (hp < 0)
hp = 1 - ((-hp) % 1);
if (hp > 1)
hp = hp % 1;
hp *= 6;
var x = c * (1 - Math.Abs((hp % 2) - 1));
double r1, g1, b1;
if (hp < 1)
{
r1 = c;
g1 = x;
b1 = 0;
}
else if (hp < 2)
{
r1 = x;
g1 = c;
b1 = 0;
}
else if (hp < 3)
{
r1 = 0;
g1 = c;
b1 = x;
}
else if (hp < 4)
{
r1 = 0;
g1 = x;
b1 = c;
}
else if (hp < 5)
{
r1 = x;
g1 = 0;
b1 = c;
}
else
{
r1 = c;
g1 = 0;
b1 = x;
}
var m = lightness - 0.5 * c;
return new Color(r1 + m, g1 + m, b1 + m, alpha);
}
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "Color ({0}, {1}, {2}, {3})", Red, Green, Blue, Alpha);
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, 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.
//
using System;
using System.Collections.Generic;
using System.Text;
namespace NLog.MessageTemplates
{
/// <summary>
/// Render templates
/// </summary>
internal static class TemplateRenderer
{
/// <summary>
/// Render a template to a string.
/// </summary>
/// <param name="template">The template.</param>
/// <param name="formatProvider">Culture.</param>
/// <param name="parameters">Parameters for the holes.</param>
/// <param name="forceTemplateRenderer">Do not fallback to StringBuilder.Format for positional templates.</param>
/// <param name="sb">The String Builder destination.</param>
/// <param name="messageTemplateParameters">Parameters for the holes.</param>
public static void Render(this string template, IFormatProvider formatProvider, object[] parameters, bool forceTemplateRenderer, StringBuilder sb, out IList<MessageTemplateParameter> messageTemplateParameters)
{
int pos = 0;
int holeIndex = 0;
int holeStartPosition = 0;
messageTemplateParameters = null;
int originalLength = sb.Length;
TemplateEnumerator templateEnumerator = new TemplateEnumerator(template);
while (templateEnumerator.MoveNext())
{
if (holeIndex == 0 && !forceTemplateRenderer && templateEnumerator.Current.MaybePositionalTemplate && sb.Length == originalLength)
{
// Not a structured template
sb.AppendFormat(formatProvider, template, parameters);
return;
}
var literal = templateEnumerator.Current.Literal;
sb.Append(template, pos, literal.Print);
pos += literal.Print;
if (literal.Skip == 0)
{
pos++;
}
else
{
pos += literal.Skip;
var hole = templateEnumerator.Current.Hole;
if (hole.Alignment != 0)
holeStartPosition = sb.Length;
if (hole.Index != -1 && messageTemplateParameters == null)
{
holeIndex++;
RenderHole(sb, hole, formatProvider, parameters[hole.Index], true);
}
else
{
var holeParameter = parameters[holeIndex];
if (messageTemplateParameters == null)
{
messageTemplateParameters = new MessageTemplateParameter[parameters.Length];
if (holeIndex != 0)
{
// rewind and try again
templateEnumerator = new TemplateEnumerator(template);
sb.Length = originalLength;
holeIndex = 0;
pos = 0;
continue;
}
}
messageTemplateParameters[holeIndex++] = new MessageTemplateParameter(hole.Name, holeParameter, hole.Format, hole.CaptureType);
RenderHole(sb, hole, formatProvider, holeParameter);
}
if (hole.Alignment != 0)
RenderPadding(sb, hole.Alignment, holeStartPosition);
}
}
if (messageTemplateParameters != null && holeIndex != messageTemplateParameters.Count)
{
var truncateParameters = new MessageTemplateParameter[holeIndex];
for (int i = 0; i < truncateParameters.Length; ++i)
truncateParameters[i] = messageTemplateParameters[i];
messageTemplateParameters = truncateParameters;
}
}
/// <summary>
/// Render a template to a string.
/// </summary>
/// <param name="template">The template.</param>
/// <param name="sb">The String Builder destination.</param>
/// <param name="formatProvider">Culture.</param>
/// <param name="parameters">Parameters for the holes.</param>
/// <returns>Rendered template, never null.</returns>
public static void Render(this Template template, StringBuilder sb, IFormatProvider formatProvider, object[] parameters)
{
int pos = 0;
int holeIndex = 0;
int holeStartPosition = 0;
foreach (var literal in template.Literals)
{
sb.Append(template.Value, pos, literal.Print);
pos += literal.Print;
if (literal.Skip == 0)
{
pos++;
}
else
{
pos += literal.Skip;
var hole = template.Holes[holeIndex];
if (hole.Alignment != 0)
holeStartPosition = sb.Length;
var parameter = template.IsPositional ? parameters[hole.Index] : parameters[holeIndex];
++holeIndex;
RenderHole(sb, hole, formatProvider, parameter, template.IsPositional);
if (hole.Alignment != 0)
RenderPadding(sb, hole.Alignment, holeStartPosition);
}
}
}
private static void RenderHole(StringBuilder sb, Hole hole, IFormatProvider formatProvider, object value, bool legacy = false)
{
RenderHole(sb, hole.CaptureType, hole.Format, formatProvider, value, legacy);
}
public static void RenderHole(StringBuilder sb, CaptureType captureType, string holeFormat, IFormatProvider formatProvider, object value, bool legacy = false)
{
if (value == null)
{
sb.Append("NULL");
return;
}
if (captureType == CaptureType.Normal && legacy)
{
ValueFormatter.FormatToString(value, holeFormat, formatProvider, sb);
}
else
{
ValueFormatter.Instance.FormatValue(value, holeFormat, captureType, formatProvider, sb);
}
}
private static void RenderPadding(StringBuilder sb, int holeAlignment, int holeStartPosition)
{
int holeWidth = sb.Length - holeStartPosition;
int holePadding = Math.Abs(holeAlignment) - holeWidth;
if (holePadding > 0)
{
if (holeAlignment < 0 || holeWidth == 0)
{
sb.Append(' ', holePadding);
}
else
{
string holeFormatVaue = sb.ToString(holeStartPosition, holeWidth);
sb.Length = holeStartPosition;
sb.Append(' ', holePadding);
sb.Append(holeFormatVaue);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// This is used internally to create best fit behavior as per the original windows best fit behavior.
//
using System;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Text
{
[Serializable]
internal class InternalEncoderBestFitFallback : EncoderFallback
{
// Our variables
internal Encoding encoding = null;
internal char[] arrayBestFit = null;
internal InternalEncoderBestFitFallback(Encoding encoding)
{
// Need to load our replacement characters table.
this.encoding = encoding;
this.bIsMicrosoftBestFitFallback = true;
}
public override EncoderFallbackBuffer CreateFallbackBuffer()
{
return new InternalEncoderBestFitFallbackBuffer(this);
}
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount
{
get
{
return 1;
}
}
public override bool Equals(Object value)
{
InternalEncoderBestFitFallback that = value as InternalEncoderBestFitFallback;
if (that != null)
{
return (this.encoding.CodePage == that.encoding.CodePage);
}
return (false);
}
public override int GetHashCode()
{
return this.encoding.CodePage;
}
}
internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer
{
// Our variables
private char cBestFit = '\0';
private InternalEncoderBestFitFallback oFallback;
private int iCount = -1;
private int iSize;
// Private object for locking instead of locking on a public type for SQL reliability work.
private static Object s_InternalSyncObject;
private static Object InternalSyncObject
{
get
{
if (s_InternalSyncObject == null)
{
Object o = new Object();
Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
// Constructor
public InternalEncoderBestFitFallbackBuffer(InternalEncoderBestFitFallback fallback)
{
oFallback = fallback;
if (oFallback.arrayBestFit == null)
{
// Lock so we don't confuse ourselves.
lock (InternalSyncObject)
{
// Double check before we do it again.
if (oFallback.arrayBestFit == null)
oFallback.arrayBestFit = fallback.encoding.GetBestFitUnicodeToBytesData();
}
}
}
// Fallback methods
public override bool Fallback(char charUnknown, int index)
{
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array.
// Shouldn't be able to get here for all of our code pages, table would have to be messed up.
Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
iCount = iSize = 1;
cBestFit = TryBestFit(charUnknown);
if (cBestFit == '\0')
cBestFit = '?';
return true;
}
public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index)
{
// Double check input surrogate pair
if (!Char.IsHighSurrogate(charUnknownHigh))
throw new ArgumentOutOfRangeException(nameof(charUnknownHigh),
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xD800, 0xDBFF));
if (!Char.IsLowSurrogate(charUnknownLow))
throw new ArgumentOutOfRangeException(nameof(charUnknownLow),
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xDC00, 0xDFFF));
Contract.EndContractBlock();
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array. 0 is processing last character, < 0 is not falling back
// Shouldn't be able to get here, table would have to be messed up.
Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
// Go ahead and get our fallback, surrogates don't have best fit
cBestFit = '?';
iCount = iSize = 2;
return true;
}
// Default version is overridden in EncoderReplacementFallback.cs
public override char GetNextChar()
{
// We want it to get < 0 because == 0 means that the current/last character is a fallback
// and we need to detect recursion. We could have a flag but we already have this counter.
iCount--;
// Do we have anything left? 0 is now last fallback char, negative is nothing left
if (iCount < 0)
return '\0';
// Need to get it out of the buffer.
// Make sure it didn't wrap from the fast count-- path
if (iCount == int.MaxValue)
{
iCount = -1;
return '\0';
}
// Return the best fit character
return cBestFit;
}
public override bool MovePrevious()
{
// Exception fallback doesn't have anywhere to back up to.
if (iCount >= 0)
iCount++;
// Return true if we could do it.
return (iCount >= 0 && iCount <= iSize);
}
// How many characters left to output?
public override int Remaining
{
get
{
return (iCount > 0) ? iCount : 0;
}
}
// Clear the buffer
public override unsafe void Reset()
{
iCount = -1;
charStart = null;
bFallingBack = false;
}
// private helper methods
private char TryBestFit(char cUnknown)
{
// Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array
int lowBound = 0;
int highBound = oFallback.arrayBestFit.Length;
int index;
// Binary search the array
int iDiff;
while ((iDiff = (highBound - lowBound)) > 6)
{
// Look in the middle, which is complicated by the fact that we have 2 #s for each pair,
// so we don't want index to be odd because we want to be on word boundaries.
// Also note that index can never == highBound (because diff is rounded down)
index = ((iDiff / 2) + lowBound) & 0xFFFE;
char cTest = oFallback.arrayBestFit[index];
if (cTest == cUnknown)
{
// We found it
Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
"[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return oFallback.arrayBestFit[index + 1];
}
else if (cTest < cUnknown)
{
// We weren't high enough
lowBound = index;
}
else
{
// We weren't low enough
highBound = index;
}
}
for (index = lowBound; index < highBound; index += 2)
{
if (oFallback.arrayBestFit[index] == cUnknown)
{
// We found it
Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
"[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return oFallback.arrayBestFit[index + 1];
}
}
// Char wasn't in our table
return '\0';
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace Lucene.Net.Search
{
using NUnit.Framework;
using System.IO;
/*
* 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using IndexReader = Lucene.Net.Index.IndexReader;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/// <summary>
/// Utility class for asserting expected hits in tests.
/// </summary>
public class CheckHits
{
/// <summary>
/// Some explains methods calculate their values though a slightly
/// different order of operations from the actual scoring method ...
/// this allows for a small amount of relative variation
/// </summary>
public static float EXPLAIN_SCORE_TOLERANCE_DELTA = 0.001f;
/// <summary>
/// In general we use a relative epsilon, but some tests do crazy things
/// like boost documents with 0, creating tiny tiny scores where the
/// relative difference is large but the absolute difference is tiny.
/// we ensure the the epsilon is always at least this big.
/// </summary>
public static float EXPLAIN_SCORE_TOLERANCE_MINIMUM = 1e-6f;
/// <summary>
/// Tests that all documents up to maxDoc which are *not* in the
/// expected result set, have an explanation which indicates that
/// the document does not match
/// </summary>
public static void CheckNoMatchExplanations(Query q, string defaultFieldName, IndexSearcher searcher, int[] results)
{
string d = q.ToString(defaultFieldName);
SortedSet<int?> ignore = new SortedSet<int?>();
for (int i = 0; i < results.Length; i++)
{
ignore.Add(Convert.ToInt32(results[i]));
}
int maxDoc = searcher.IndexReader.MaxDoc;
for (int doc = 0; doc < maxDoc; doc++)
{
if (ignore.Contains(Convert.ToInt32(doc)))
{
continue;
}
Explanation exp = searcher.Explain(q, doc);
Assert.IsNotNull(exp, "Explanation of [[" + d + "]] for #" + doc + " is null");
Assert.IsFalse(exp.IsMatch, "Explanation of [[" + d + "]] for #" + doc + " doesn't indicate non-match: " + exp.ToString());
}
}
/// <summary>
/// Tests that a query matches the an expected set of documents using a
/// HitCollector.
///
/// <p>
/// Note that when using the HitCollector API, documents will be collected
/// if they "match" regardless of what their score is.
/// </p> </summary>
/// <param name="query"> the query to test </param>
/// <param name="searcher"> the searcher to test the query against </param>
/// <param name="defaultFieldName"> used for displaying the query in assertion messages </param>
/// <param name="results"> a list of documentIds that must match the query </param>
/// <seealso cref= #checkHits </seealso>
public static void CheckHitCollector(Random random, Query query, string defaultFieldName, IndexSearcher searcher, int[] results)
{
QueryUtils.Check(random, query, searcher);
Trace.TraceInformation("Checked");
SortedSet<int?> correct = new SortedSet<int?>();
for (int i = 0; i < results.Length; i++)
{
correct.Add(Convert.ToInt32(results[i]));
}
SortedSet<int?> actual = new SortedSet<int?>();
Collector c = new SetCollector(actual);
searcher.Search(query, c);
Assert.AreEqual(correct, actual, "Simple: " + query.ToString(defaultFieldName));
for (int i = -1; i < 2; i++)
{
actual.Clear();
IndexSearcher s = QueryUtils.WrapUnderlyingReader(random, searcher, i);
s.Search(query, c);
Assert.AreEqual(correct, actual, "Wrap Reader " + i + ": " + query.ToString(defaultFieldName));
}
}
/// <summary>
/// Just collects document ids into a set.
/// </summary>
public class SetCollector : Collector
{
internal readonly ISet<int?> Bag;
public SetCollector(ISet<int?> bag)
{
this.Bag = bag;
}
internal int @base = 0;
public override Scorer Scorer
{
set
{
}
}
public override void Collect(int doc)
{
Bag.Add(Convert.ToInt32(doc + @base));
}
public override AtomicReaderContext NextReader
{
set
{
@base = value.DocBase;
}
}
public override bool AcceptsDocsOutOfOrder()
{
return true;
}
}
/// <summary>
/// Tests that a query matches the an expected set of documents using Hits.
///
/// <p>
/// Note that when using the Hits API, documents will only be returned
/// if they have a positive normalized score.
/// </p> </summary>
/// <param name="query"> the query to test </param>
/// <param name="searcher"> the searcher to test the query against </param>
/// <param name="defaultFieldName"> used for displaing the query in assertion messages </param>
/// <param name="results"> a list of documentIds that must match the query </param>
/// <seealso cref= #checkHitCollector </seealso>
public static void DoCheckHits(Random random, Query query, string defaultFieldName, IndexSearcher searcher, int[] results)
{
ScoreDoc[] hits = searcher.Search(query, 1000).ScoreDocs;
SortedSet<int?> correct = new SortedSet<int?>();
for (int i = 0; i < results.Length; i++)
{
correct.Add(Convert.ToInt32(results[i]));
}
SortedSet<int?> actual = new SortedSet<int?>();
for (int i = 0; i < hits.Length; i++)
{
actual.Add(Convert.ToInt32(hits[i].Doc));
}
Assert.AreEqual(correct, actual, query.ToString(defaultFieldName));
QueryUtils.Check(random, query, searcher, LuceneTestCase.Rarely(random));
}
/// <summary>
/// Tests that a Hits has an expected order of documents </summary>
public static void CheckDocIds(string mes, int[] results, ScoreDoc[] hits)
{
Assert.AreEqual(hits.Length, results.Length, mes + " nr of hits");
for (int i = 0; i < results.Length; i++)
{
Assert.AreEqual(results[i], hits[i].Doc, mes + " doc nrs for hit " + i);
}
}
/// <summary>
/// Tests that two queries have an expected order of documents,
/// and that the two queries have the same score values.
/// </summary>
public static void CheckHitsQuery(Query query, ScoreDoc[] hits1, ScoreDoc[] hits2, int[] results)
{
CheckDocIds("hits1", results, hits1);
CheckDocIds("hits2", results, hits2);
CheckEqual(query, hits1, hits2);
}
public static void CheckEqual(Query query, ScoreDoc[] hits1, ScoreDoc[] hits2)
{
const float scoreTolerance = 1.0e-6f;
if (hits1.Length != hits2.Length)
{
Assert.Fail("Unequal lengths: hits1=" + hits1.Length + ",hits2=" + hits2.Length);
}
for (int i = 0; i < hits1.Length; i++)
{
if (hits1[i].Doc != hits2[i].Doc)
{
Assert.Fail("Hit " + i + " docnumbers don't match\n" + Hits2str(hits1, hits2, 0, 0) + "for query:" + query.ToString());
}
if ((hits1[i].Doc != hits2[i].Doc) || Math.Abs(hits1[i].Score - hits2[i].Score) > scoreTolerance)
{
Assert.Fail("Hit " + i + ", doc nrs " + hits1[i].Doc + " and " + hits2[i].Doc + "\nunequal : " + hits1[i].Score + "\n and: " + hits2[i].Score + "\nfor query:" + query.ToString());
}
}
}
public static string Hits2str(ScoreDoc[] hits1, ScoreDoc[] hits2, int start, int end)
{
StringBuilder sb = new StringBuilder();
int len1 = hits1 == null ? 0 : hits1.Length;
int len2 = hits2 == null ? 0 : hits2.Length;
if (end <= 0)
{
end = Math.Max(len1, len2);
}
sb.Append("Hits length1=").Append(len1).Append("\tlength2=").Append(len2);
sb.Append('\n');
for (int i = start; i < end; i++)
{
sb.Append("hit=").Append(i).Append(':');
if (i < len1)
{
sb.Append(" doc").Append(hits1[i].Doc).Append('=').Append(hits1[i].Score);
}
else
{
sb.Append(" ");
}
sb.Append(",\t");
if (i < len2)
{
sb.Append(" doc").Append(hits2[i].Doc).Append('=').Append(hits2[i].Score);
}
sb.Append('\n');
}
return sb.ToString();
}
public static string TopdocsString(TopDocs docs, int start, int end)
{
StringBuilder sb = new StringBuilder();
sb.Append("TopDocs totalHits=").Append(docs.TotalHits).Append(" top=").Append(docs.ScoreDocs.Length).Append('\n');
if (end <= 0)
{
end = docs.ScoreDocs.Length;
}
else
{
end = Math.Min(end, docs.ScoreDocs.Length);
}
for (int i = start; i < end; i++)
{
sb.Append('\t');
sb.Append(i);
sb.Append(") doc=");
sb.Append(docs.ScoreDocs[i].Doc);
sb.Append("\tscore=");
sb.Append(docs.ScoreDocs[i].Score);
sb.Append('\n');
}
return sb.ToString();
}
/// <summary>
/// Asserts that the explanation value for every document matching a
/// query corresponds with the true score.
/// </summary>
/// <seealso cref= ExplanationAsserter </seealso>
/// <seealso cref= #checkExplanations(Query, String, IndexSearcher, boolean) for a
/// "deep" testing of the explanation details.
/// </seealso>
/// <param name="query"> the query to test </param>
/// <param name="searcher"> the searcher to test the query against </param>
/// <param name="defaultFieldName"> used for displaing the query in assertion messages </param>
public static void CheckExplanations(Query query, string defaultFieldName, IndexSearcher searcher)
{
CheckExplanations(query, defaultFieldName, searcher, false);
}
/// <summary>
/// Asserts that the explanation value for every document matching a
/// query corresponds with the true score. Optionally does "deep"
/// testing of the explanation details.
/// </summary>
/// <seealso cref= ExplanationAsserter </seealso>
/// <param name="query"> the query to test </param>
/// <param name="searcher"> the searcher to test the query against </param>
/// <param name="defaultFieldName"> used for displaing the query in assertion messages </param>
/// <param name="deep"> indicates whether a deep comparison of sub-Explanation details should be executed </param>
public static void CheckExplanations(Query query, string defaultFieldName, IndexSearcher searcher, bool deep)
{
searcher.Search(query, new ExplanationAsserter(query, defaultFieldName, searcher, deep));
}
/// <summary>
/// returns a reasonable epsilon for comparing two floats,
/// where minor differences are acceptable such as score vs. explain
/// </summary>
public static float ExplainToleranceDelta(float f1, float f2)
{
return Math.Max(EXPLAIN_SCORE_TOLERANCE_MINIMUM, Math.Max(Math.Abs(f1), Math.Abs(f2)) * EXPLAIN_SCORE_TOLERANCE_DELTA);
}
/// <summary>
/// Assert that an explanation has the expected score, and optionally that its
/// sub-details max/sum/factor match to that score.
/// </summary>
/// <param name="q"> String representation of the query for assertion messages </param>
/// <param name="doc"> Document ID for assertion messages </param>
/// <param name="score"> Real score value of doc with query q </param>
/// <param name="deep"> indicates whether a deep comparison of sub-Explanation details should be executed </param>
/// <param name="expl"> The Explanation to match against score </param>
public static void VerifyExplanation(string q, int doc, float score, bool deep, Explanation expl)
{
float value = expl.Value;
Assert.AreEqual(score, value, ExplainToleranceDelta(score, value), q + ": score(doc=" + doc + ")=" + score + " != explanationScore=" + value + " Explanation: " + expl);
if (!deep)
{
return;
}
Explanation[] detail = expl.Details;
// TODO: can we improve this entire method? its really geared to work only with TF/IDF
if (expl.Description.EndsWith("computed from:"))
{
return; // something more complicated.
}
if (detail != null)
{
if (detail.Length == 1)
{
// simple containment, unless its a freq of: (which lets a query explain how the freq is calculated),
// just verify contained expl has same score
if (!expl.Description.EndsWith("with freq of:"))
{
VerifyExplanation(q, doc, score, deep, detail[0]);
}
}
else
{
// explanation must either:
// - end with one of: "product of:", "sum of:", "max of:", or
// - have "max plus <x> times others" (where <x> is float).
float x = 0;
string descr = expl.Description.ToLower(CultureInfo.InvariantCulture);
bool productOf = descr.EndsWith("product of:");
bool sumOf = descr.EndsWith("sum of:");
bool maxOf = descr.EndsWith("max of:");
bool maxTimesOthers = false;
if (!(productOf || sumOf || maxOf))
{
// maybe 'max plus x times others'
int k1 = descr.IndexOf("max plus ");
if (k1 >= 0)
{
k1 += "max plus ".Length;
int k2 = descr.IndexOf(" ", k1);
try
{
x = Convert.ToSingle(descr.Substring(k1, k2 - k1).Trim());
if (descr.Substring(k2).Trim().Equals("times others of:"))
{
maxTimesOthers = true;
}
}
catch (FormatException e)
{
}
}
}
// TODO: this is a TERRIBLE assertion!!!!
Assert.IsTrue(productOf || sumOf || maxOf || maxTimesOthers, q + ": multi valued explanation description=\"" + descr + "\" must be 'max of plus x times others' or end with 'product of'" + " or 'sum of:' or 'max of:' - " + expl);
float sum = 0;
float product = 1;
float max = 0;
for (int i = 0; i < detail.Length; i++)
{
float dval = detail[i].Value;
VerifyExplanation(q, doc, dval, deep, detail[i]);
product *= dval;
sum += dval;
max = Math.Max(max, dval);
}
float combined = 0;
if (productOf)
{
combined = product;
}
else if (sumOf)
{
combined = sum;
}
else if (maxOf)
{
combined = max;
}
else if (maxTimesOthers)
{
combined = max + x * (sum - max);
}
else
{
Assert.IsTrue(false, "should never get here!");
}
Assert.AreEqual(combined, value, ExplainToleranceDelta(combined, value), q + ": actual subDetails combined==" + combined + " != value=" + value + " Explanation: " + expl);
}
}
}
/// <summary>
/// an IndexSearcher that implicitly checks hte explanation of every match
/// whenever it executes a search.
/// </summary>
/// <seealso cref= ExplanationAsserter </seealso>
public class ExplanationAssertingSearcher : IndexSearcher
{
public ExplanationAssertingSearcher(IndexReader r)
: base(r)
{
}
protected internal virtual void CheckExplanations(Query q)
{
base.Search(q, null, new ExplanationAsserter(q, null, this));
}
public override TopFieldDocs Search(Query query, Filter filter, int n, Sort sort)
{
CheckExplanations(query);
return base.Search(query, filter, n, sort);
}
public override void Search(Query query, Collector results)
{
CheckExplanations(query);
base.Search(query, results);
}
public override void Search(Query query, Filter filter, Collector results)
{
CheckExplanations(query);
base.Search(query, filter, results);
}
public override TopDocs Search(Query query, Filter filter, int n)
{
CheckExplanations(query);
return base.Search(query, filter, n);
}
}
/// <summary>
/// Asserts that the score explanation for every document matching a
/// query corresponds with the true score.
///
/// NOTE: this HitCollector should only be used with the Query and Searcher
/// specified at when it is constructed.
/// </summary>
/// <seealso cref= CheckHits#verifyExplanation </seealso>
public class ExplanationAsserter : Collector
{
internal Query q;
internal IndexSearcher s;
internal string d;
internal bool Deep;
internal Scorer Scorer_Renamed;
internal int @base = 0;
/// <summary>
/// Constructs an instance which does shallow tests on the Explanation </summary>
public ExplanationAsserter(Query q, string defaultFieldName, IndexSearcher s)
: this(q, defaultFieldName, s, false)
{
}
public ExplanationAsserter(Query q, string defaultFieldName, IndexSearcher s, bool deep)
{
this.q = q;
this.s = s;
this.d = q.ToString(defaultFieldName);
this.Deep = deep;
}
public override Scorer Scorer
{
set
{
this.Scorer_Renamed = value;
}
}
public override void Collect(int doc)
{
Explanation exp = null;
doc = doc + @base;
try
{
exp = s.Explain(q, doc);
}
catch (IOException e)
{
throw new Exception("exception in hitcollector of [[" + d + "]] for #" + doc, e);
}
Assert.IsNotNull(exp, "Explanation of [[" + d + "]] for #" + doc + " is null");
VerifyExplanation(d, doc, Scorer_Renamed.Score(), Deep, exp);
Assert.IsTrue(exp.IsMatch, "Explanation of [[" + d + "]] for #" + doc + " does not indicate match: " + exp.ToString());
}
public override AtomicReaderContext NextReader
{
set
{
@base = value.DocBase;
}
}
public override bool AcceptsDocsOutOfOrder()
{
return true;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
using System.Threading;
internal static partial class Interop
{
internal static partial class HttpApi
{
internal static readonly HTTPAPI_VERSION s_version = new HTTPAPI_VERSION() { HttpApiMajorVersion = 2, HttpApiMinorVersion = 0 };
internal static readonly bool s_supported = InitHttpApi(s_version);
internal static IPEndPoint s_any = new IPEndPoint(IPAddress.Any, IPEndPoint.MinPort);
internal static IPEndPoint s_ipv6Any = new IPEndPoint(IPAddress.IPv6Any, IPEndPoint.MinPort);
internal const int IPv4AddressSize = 16;
internal const int IPv6AddressSize = 28;
private static unsafe bool InitHttpApi(HTTPAPI_VERSION version)
{
uint statusCode = HttpInitialize(version, (uint)HTTP_FLAGS.HTTP_INITIALIZE_SERVER, null);
return statusCode == ERROR_SUCCESS;
}
[StructLayout(LayoutKind.Sequential)]
internal struct HTTP_VERSION
{
internal ushort MajorVersion;
internal ushort MinorVersion;
}
internal enum HTTP_RESPONSE_INFO_TYPE
{
HttpResponseInfoTypeMultipleKnownHeaders,
HttpResponseInfoTypeAuthenticationProperty,
HttpResponseInfoTypeQosProperty,
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct HTTP_RESPONSE_INFO
{
internal HTTP_RESPONSE_INFO_TYPE Type;
internal uint Length;
internal void* pInfo;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct HTTP_RESPONSE_HEADERS
{
internal ushort UnknownHeaderCount;
internal HTTP_UNKNOWN_HEADER* pUnknownHeaders;
internal ushort TrailerCount;
internal HTTP_UNKNOWN_HEADER* pTrailers;
internal HTTP_KNOWN_HEADER KnownHeaders;
internal HTTP_KNOWN_HEADER KnownHeaders_02;
internal HTTP_KNOWN_HEADER KnownHeaders_03;
internal HTTP_KNOWN_HEADER KnownHeaders_04;
internal HTTP_KNOWN_HEADER KnownHeaders_05;
internal HTTP_KNOWN_HEADER KnownHeaders_06;
internal HTTP_KNOWN_HEADER KnownHeaders_07;
internal HTTP_KNOWN_HEADER KnownHeaders_08;
internal HTTP_KNOWN_HEADER KnownHeaders_09;
internal HTTP_KNOWN_HEADER KnownHeaders_10;
internal HTTP_KNOWN_HEADER KnownHeaders_11;
internal HTTP_KNOWN_HEADER KnownHeaders_12;
internal HTTP_KNOWN_HEADER KnownHeaders_13;
internal HTTP_KNOWN_HEADER KnownHeaders_14;
internal HTTP_KNOWN_HEADER KnownHeaders_15;
internal HTTP_KNOWN_HEADER KnownHeaders_16;
internal HTTP_KNOWN_HEADER KnownHeaders_17;
internal HTTP_KNOWN_HEADER KnownHeaders_18;
internal HTTP_KNOWN_HEADER KnownHeaders_19;
internal HTTP_KNOWN_HEADER KnownHeaders_20;
internal HTTP_KNOWN_HEADER KnownHeaders_21;
internal HTTP_KNOWN_HEADER KnownHeaders_22;
internal HTTP_KNOWN_HEADER KnownHeaders_23;
internal HTTP_KNOWN_HEADER KnownHeaders_24;
internal HTTP_KNOWN_HEADER KnownHeaders_25;
internal HTTP_KNOWN_HEADER KnownHeaders_26;
internal HTTP_KNOWN_HEADER KnownHeaders_27;
internal HTTP_KNOWN_HEADER KnownHeaders_28;
internal HTTP_KNOWN_HEADER KnownHeaders_29;
internal HTTP_KNOWN_HEADER KnownHeaders_30;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct HTTP_KNOWN_HEADER
{
internal ushort RawValueLength;
internal sbyte* pRawValue;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct HTTP_UNKNOWN_HEADER
{
internal ushort NameLength;
internal ushort RawValueLength;
internal sbyte* pName;
internal sbyte* pRawValue;
}
internal enum HTTP_DATA_CHUNK_TYPE : int
{
HttpDataChunkFromMemory = 0,
HttpDataChunkFromFileHandle = 1,
HttpDataChunkFromFragmentCache = 2,
HttpDataChunkMaximum = 3,
}
[StructLayout(LayoutKind.Sequential, Size = 32)]
internal unsafe struct HTTP_DATA_CHUNK
{
internal HTTP_DATA_CHUNK_TYPE DataChunkType;
internal uint p0;
internal byte* pBuffer;
internal uint BufferLength;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct HTTP_RESPONSE
{
internal uint Flags;
internal HTTP_VERSION Version;
internal ushort StatusCode;
internal ushort ReasonLength;
internal sbyte* pReason;
internal HTTP_RESPONSE_HEADERS Headers;
internal ushort EntityChunkCount;
internal HTTP_DATA_CHUNK* pEntityChunks;
internal ushort ResponseInfoCount;
internal HTTP_RESPONSE_INFO* pResponseInfo;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct HTTP_REQUEST_INFO
{
internal HTTP_REQUEST_INFO_TYPE InfoType;
internal uint InfoLength;
internal void* pInfo;
}
internal enum HTTP_REQUEST_INFO_TYPE
{
HttpRequestInfoTypeAuth,
HttpRequestInfoTypeChannelBind,
HttpRequestInfoTypeSslProtocol,
HttpRequestInfoTypeSslTokenBinding
}
internal enum HTTP_VERB : int
{
HttpVerbUnparsed = 0,
HttpVerbUnknown = 1,
HttpVerbInvalid = 2,
HttpVerbOPTIONS = 3,
HttpVerbGET = 4,
HttpVerbHEAD = 5,
HttpVerbPOST = 6,
HttpVerbPUT = 7,
HttpVerbDELETE = 8,
HttpVerbTRACE = 9,
HttpVerbCONNECT = 10,
HttpVerbTRACK = 11,
HttpVerbMOVE = 12,
HttpVerbCOPY = 13,
HttpVerbPROPFIND = 14,
HttpVerbPROPPATCH = 15,
HttpVerbMKCOL = 16,
HttpVerbLOCK = 17,
HttpVerbUNLOCK = 18,
HttpVerbSEARCH = 19,
HttpVerbMaximum = 20,
}
[StructLayout(LayoutKind.Sequential)]
internal struct SOCKADDR
{
internal ushort sa_family;
internal byte sa_data;
internal byte sa_data_02;
internal byte sa_data_03;
internal byte sa_data_04;
internal byte sa_data_05;
internal byte sa_data_06;
internal byte sa_data_07;
internal byte sa_data_08;
internal byte sa_data_09;
internal byte sa_data_10;
internal byte sa_data_11;
internal byte sa_data_12;
internal byte sa_data_13;
internal byte sa_data_14;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct HTTP_TRANSPORT_ADDRESS
{
internal SOCKADDR* pRemoteAddress;
internal SOCKADDR* pLocalAddress;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct HTTP_REQUEST_HEADERS
{
internal ushort UnknownHeaderCount;
internal HTTP_UNKNOWN_HEADER* pUnknownHeaders;
internal ushort TrailerCount;
internal HTTP_UNKNOWN_HEADER* pTrailers;
internal HTTP_KNOWN_HEADER KnownHeaders;
internal HTTP_KNOWN_HEADER KnownHeaders_02;
internal HTTP_KNOWN_HEADER KnownHeaders_03;
internal HTTP_KNOWN_HEADER KnownHeaders_04;
internal HTTP_KNOWN_HEADER KnownHeaders_05;
internal HTTP_KNOWN_HEADER KnownHeaders_06;
internal HTTP_KNOWN_HEADER KnownHeaders_07;
internal HTTP_KNOWN_HEADER KnownHeaders_08;
internal HTTP_KNOWN_HEADER KnownHeaders_09;
internal HTTP_KNOWN_HEADER KnownHeaders_10;
internal HTTP_KNOWN_HEADER KnownHeaders_11;
internal HTTP_KNOWN_HEADER KnownHeaders_12;
internal HTTP_KNOWN_HEADER KnownHeaders_13;
internal HTTP_KNOWN_HEADER KnownHeaders_14;
internal HTTP_KNOWN_HEADER KnownHeaders_15;
internal HTTP_KNOWN_HEADER KnownHeaders_16;
internal HTTP_KNOWN_HEADER KnownHeaders_17;
internal HTTP_KNOWN_HEADER KnownHeaders_18;
internal HTTP_KNOWN_HEADER KnownHeaders_19;
internal HTTP_KNOWN_HEADER KnownHeaders_20;
internal HTTP_KNOWN_HEADER KnownHeaders_21;
internal HTTP_KNOWN_HEADER KnownHeaders_22;
internal HTTP_KNOWN_HEADER KnownHeaders_23;
internal HTTP_KNOWN_HEADER KnownHeaders_24;
internal HTTP_KNOWN_HEADER KnownHeaders_25;
internal HTTP_KNOWN_HEADER KnownHeaders_26;
internal HTTP_KNOWN_HEADER KnownHeaders_27;
internal HTTP_KNOWN_HEADER KnownHeaders_28;
internal HTTP_KNOWN_HEADER KnownHeaders_29;
internal HTTP_KNOWN_HEADER KnownHeaders_30;
internal HTTP_KNOWN_HEADER KnownHeaders_31;
internal HTTP_KNOWN_HEADER KnownHeaders_32;
internal HTTP_KNOWN_HEADER KnownHeaders_33;
internal HTTP_KNOWN_HEADER KnownHeaders_34;
internal HTTP_KNOWN_HEADER KnownHeaders_35;
internal HTTP_KNOWN_HEADER KnownHeaders_36;
internal HTTP_KNOWN_HEADER KnownHeaders_37;
internal HTTP_KNOWN_HEADER KnownHeaders_38;
internal HTTP_KNOWN_HEADER KnownHeaders_39;
internal HTTP_KNOWN_HEADER KnownHeaders_40;
internal HTTP_KNOWN_HEADER KnownHeaders_41;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct HTTP_SSL_CLIENT_CERT_INFO
{
internal uint CertFlags;
internal uint CertEncodedSize;
internal byte* pCertEncoded;
internal void* Token;
internal byte CertDeniedByMapper;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct HTTP_SSL_INFO
{
internal ushort ServerCertKeySize;
internal ushort ConnectionKeySize;
internal uint ServerCertIssuerSize;
internal uint ServerCertSubjectSize;
internal sbyte* pServerCertIssuer;
internal sbyte* pServerCertSubject;
internal HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo;
internal uint SslClientCertNegotiated;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct HTTP_REQUEST
{
internal uint Flags;
internal ulong ConnectionId;
internal ulong RequestId;
internal ulong UrlContext;
internal HTTP_VERSION Version;
internal HTTP_VERB Verb;
internal ushort UnknownVerbLength;
internal ushort RawUrlLength;
internal sbyte* pUnknownVerb;
internal sbyte* pRawUrl;
internal HTTP_COOKED_URL CookedUrl;
internal HTTP_TRANSPORT_ADDRESS Address;
internal HTTP_REQUEST_HEADERS Headers;
internal ulong BytesReceived;
internal ushort EntityChunkCount;
internal HTTP_DATA_CHUNK* pEntityChunks;
internal ulong RawConnectionId;
internal HTTP_SSL_INFO* pSslInfo;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct HTTP_REQUEST_V2
{
internal HTTP_REQUEST RequestV1;
internal ushort RequestInfoCount;
internal HTTP_REQUEST_INFO* pRequestInfo;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct HTTP_COOKED_URL
{
internal ushort FullUrlLength;
internal ushort HostLength;
internal ushort AbsPathLength;
internal ushort QueryStringLength;
internal ushort* pFullUrl;
internal ushort* pHost;
internal ushort* pAbsPath;
internal ushort* pQueryString;
}
[StructLayout(LayoutKind.Sequential)]
internal struct HTTP_REQUEST_CHANNEL_BIND_STATUS
{
internal IntPtr ServiceName;
internal IntPtr ChannelToken;
internal uint ChannelTokenSize;
internal uint Flags;
}
internal enum HTTP_SERVER_PROPERTY
{
HttpServerAuthenticationProperty,
HttpServerLoggingProperty,
HttpServerQosProperty,
HttpServerTimeoutsProperty,
HttpServerQueueLengthProperty,
HttpServerStateProperty,
HttpServer503VerbosityProperty,
HttpServerBindingProperty,
HttpServerExtendedAuthenticationProperty,
HttpServerListenEndpointProperty,
HttpServerChannelBindProperty,
HttpServerProtectionLevelProperty,
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct HTTP_REQUEST_TOKEN_BINDING_INFO
{
public byte* TokenBinding;
public uint TokenBindingSize;
public byte* TlsUnique;
public uint TlsUniqueSize;
public IntPtr KeyType;
}
internal enum TOKENBINDING_HASH_ALGORITHM : byte
{
TOKENBINDING_HASH_ALGORITHM_SHA256 = 4,
}
internal enum TOKENBINDING_SIGNATURE_ALGORITHM : byte
{
TOKENBINDING_SIGNATURE_ALGORITHM_RSA = 1,
TOKENBINDING_SIGNATURE_ALGORITHM_ECDSAP256 = 3,
}
internal enum TOKENBINDING_TYPE : byte
{
TOKENBINDING_TYPE_PROVIDED = 0,
TOKENBINDING_TYPE_REFERRED = 1,
}
internal enum TOKENBINDING_EXTENSION_FORMAT
{
TOKENBINDING_EXTENSION_FORMAT_UNDEFINED = 0,
}
[StructLayout(LayoutKind.Sequential)]
internal struct TOKENBINDING_IDENTIFIER
{
public TOKENBINDING_TYPE bindingType;
public TOKENBINDING_HASH_ALGORITHM hashAlgorithm;
public TOKENBINDING_SIGNATURE_ALGORITHM signatureAlgorithm;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct TOKENBINDING_RESULT_DATA
{
public uint identifierSize;
public TOKENBINDING_IDENTIFIER* identifierData;
public TOKENBINDING_EXTENSION_FORMAT extensionFormat;
public uint extensionSize;
public IntPtr extensionData;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct TOKENBINDING_RESULT_LIST
{
public uint resultCount;
public TOKENBINDING_RESULT_DATA* resultData;
}
[Flags]
internal enum HTTP_FLAGS : uint
{
NONE = 0x00000000,
HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY = 0x00000001,
HTTP_RECEIVE_SECURE_CHANNEL_TOKEN = 0x00000001,
HTTP_SEND_RESPONSE_FLAG_DISCONNECT = 0x00000001,
HTTP_SEND_RESPONSE_FLAG_MORE_DATA = 0x00000002,
HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA = 0x00000004,
HTTP_SEND_RESPONSE_FLAG_RAW_HEADER = 0x00000004,
HTTP_SEND_REQUEST_FLAG_MORE_DATA = 0x00000001,
HTTP_PROPERTY_FLAG_PRESENT = 0x00000001,
HTTP_INITIALIZE_SERVER = 0x00000001,
HTTP_INITIALIZE_CBT = 0x00000004,
HTTP_SEND_RESPONSE_FLAG_OPAQUE = 0x00000040,
}
private const int HttpHeaderRequestMaximum = (int)HttpRequestHeader.UserAgent + 1;
private const int HttpHeaderResponseMaximum = (int)HttpResponseHeader.WwwAuthenticate + 1;
internal static class HTTP_REQUEST_HEADER_ID
{
internal static string ToString(int position)
{
return s_strings[position];
}
private static readonly string[] s_strings = {
"Cache-Control",
"Connection",
"Date",
"Keep-Alive",
"Pragma",
"Trailer",
"Transfer-Encoding",
"Upgrade",
"Via",
"Warning",
"Allow",
"Content-Length",
"Content-Type",
"Content-Encoding",
"Content-Language",
"Content-Location",
"Content-MD5",
"Content-Range",
"Expires",
"Last-Modified",
"Accept",
"Accept-Charset",
"Accept-Encoding",
"Accept-Language",
"Authorization",
"Cookie",
"Expect",
"From",
"Host",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Range",
"If-Unmodified-Since",
"Max-Forwards",
"Proxy-Authorization",
"Referer",
"Range",
"Te",
"Translate",
"User-Agent",
};
}
internal enum HTTP_TIMEOUT_TYPE
{
EntityBody,
DrainEntityBody,
RequestQueue,
IdleConnection,
HeaderWait,
MinSendRate,
}
[StructLayout(LayoutKind.Sequential)]
internal struct HTTP_TIMEOUT_LIMIT_INFO
{
internal HTTP_FLAGS Flags;
internal ushort EntityBody;
internal ushort DrainEntityBody;
internal ushort RequestQueue;
internal ushort IdleConnection;
internal ushort HeaderWait;
internal uint MinSendRate;
}
[StructLayout(LayoutKind.Sequential)]
internal struct HTTPAPI_VERSION
{
internal ushort HttpApiMajorVersion;
internal ushort HttpApiMinorVersion;
}
[StructLayout(LayoutKind.Sequential)]
internal struct HTTP_BINDING_INFO
{
internal HTTP_FLAGS Flags;
internal IntPtr RequestQueueHandle;
}
[DllImport(Libraries.HttpApi, SetLastError = true)]
internal static extern unsafe uint HttpInitialize(HTTPAPI_VERSION version, uint flags, void* pReserved);
[DllImport(Libraries.HttpApi, SetLastError = true)]
internal static extern uint HttpSetUrlGroupProperty(ulong urlGroupId, HTTP_SERVER_PROPERTY serverProperty, IntPtr pPropertyInfo, uint propertyInfoLength);
[DllImport(Libraries.HttpApi, SetLastError = true)]
internal static extern unsafe uint HttpCreateServerSession(HTTPAPI_VERSION version, ulong* serverSessionId, uint reserved);
[DllImport(Libraries.HttpApi, SetLastError = true)]
internal static extern unsafe uint HttpCreateUrlGroup(ulong serverSessionId, ulong* urlGroupId, uint reserved);
[DllImport(Libraries.HttpApi, SetLastError = true)]
internal static extern uint HttpCloseUrlGroup(ulong urlGroupId);
[DllImport(Libraries.HttpApi, CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern unsafe uint HttpCreateRequestQueue(HTTPAPI_VERSION version, string pName,
Interop.Kernel32.SECURITY_ATTRIBUTES* pSecurityAttributes, uint flags, out HttpRequestQueueV2Handle pReqQueueHandle);
[DllImport(Libraries.HttpApi, CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern uint HttpAddUrlToUrlGroup(ulong urlGroupId, string pFullyQualifiedUrl, ulong context, uint pReserved);
[DllImport(Libraries.HttpApi, CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern uint HttpRemoveUrlFromUrlGroup(ulong urlGroupId, string pFullyQualifiedUrl, uint flags);
[DllImport(Libraries.HttpApi, SetLastError = true)]
internal static extern unsafe uint HttpReceiveHttpRequest(SafeHandle requestQueueHandle, ulong requestId, uint flags, HTTP_REQUEST* pRequestBuffer, uint requestBufferLength, uint* pBytesReturned, NativeOverlapped* pOverlapped);
[DllImport(Libraries.HttpApi, SetLastError = true)]
internal static extern unsafe uint HttpSendHttpResponse(SafeHandle requestQueueHandle, ulong requestId, uint flags, HTTP_RESPONSE* pHttpResponse, void* pCachePolicy, uint* pBytesSent, SafeLocalAllocHandle pRequestBuffer, uint requestBufferLength, NativeOverlapped* pOverlapped, void* pLogData);
[DllImport(Libraries.HttpApi, SetLastError = true)]
internal static extern unsafe uint HttpWaitForDisconnect(SafeHandle requestQueueHandle, ulong connectionId, NativeOverlapped* pOverlapped);
[DllImport(Libraries.HttpApi, SetLastError = true)]
internal static extern unsafe uint HttpReceiveRequestEntityBody(SafeHandle requestQueueHandle, ulong requestId, uint flags, void* pEntityBuffer, uint entityBufferLength, out uint bytesReturned, NativeOverlapped* pOverlapped);
[DllImport(Libraries.HttpApi, SetLastError = true)]
internal static extern unsafe uint HttpSendResponseEntityBody(SafeHandle requestQueueHandle, ulong requestId, uint flags, ushort entityChunkCount, HTTP_DATA_CHUNK* pEntityChunks, uint* pBytesSent, SafeLocalAllocHandle pRequestBuffer, uint requestBufferLength, NativeOverlapped* pOverlapped, void* pLogData);
[DllImport(Libraries.HttpApi, SetLastError = true)]
internal static extern unsafe uint HttpCloseRequestQueue(IntPtr pReqQueueHandle);
[DllImport(Libraries.HttpApi, SetLastError = true)]
internal static extern uint HttpCancelHttpRequest(SafeHandle requestQueueHandle, ulong requestId, IntPtr pOverlapped);
[DllImport(Libraries.HttpApi, SetLastError = true)]
internal static extern uint HttpCloseServerSession(ulong serverSessionId);
internal sealed class SafeLocalFreeChannelBinding : ChannelBinding
{
private const int LMEM_FIXED = 0;
private int _size;
private SafeLocalFreeChannelBinding() { }
public override int Size
{
get { return _size; }
}
public static SafeLocalFreeChannelBinding LocalAlloc(int cb)
{
SafeLocalFreeChannelBinding result = HttpApi.LocalAlloc(LMEM_FIXED, (UIntPtr)cb);
if (result.IsInvalid)
{
result.SetHandleAsInvalid();
throw new OutOfMemoryException();
}
result._size = cb;
return result;
}
override protected bool ReleaseHandle()
{
return Interop.Kernel32.LocalFree(handle) == IntPtr.Zero;
}
}
[DllImport(Libraries.Kernel32, SetLastError = true)]
internal static extern SafeLocalFreeChannelBinding LocalAlloc(int uFlags, UIntPtr sizetdwBytes);
[DllImport(Libraries.HttpApi, SetLastError = true)]
internal static extern unsafe uint HttpReceiveClientCertificate(SafeHandle requestQueueHandle, ulong connectionId, uint flags, HTTP_SSL_CLIENT_CERT_INFO* pSslClientCertInfo, uint sslClientCertInfoSize, uint* pBytesReceived, NativeOverlapped* pOverlapped);
[DllImport(Libraries.HttpApi, SetLastError = true)]
internal static extern unsafe uint HttpReceiveClientCertificate(SafeHandle requestQueueHandle, ulong connectionId, uint flags, byte* pSslClientCertInfo, uint sslClientCertInfoSize, uint* pBytesReceived, NativeOverlapped* pOverlapped);
[Flags]
internal enum FileCompletionNotificationModes : byte
{
None = 0,
SkipCompletionPortOnSuccess = 1,
SkipSetEventOnHandle = 2
}
[DllImport(Libraries.Kernel32, SetLastError = true)]
internal static extern unsafe bool SetFileCompletionNotificationModes(SafeHandle handle, FileCompletionNotificationModes modes);
internal static readonly string[] HttpVerbs = new string[]
{
null,
"Unknown",
"Invalid",
"OPTIONS",
"GET",
"HEAD",
"POST",
"PUT",
"DELETE",
"TRACE",
"CONNECT",
"TRACK",
"MOVE",
"COPY",
"PROPFIND",
"PROPPATCH",
"MKCOL",
"LOCK",
"UNLOCK",
"SEARCH",
};
internal static class HTTP_RESPONSE_HEADER_ID
{
internal enum Enum
{
HttpHeaderCacheControl = 0, // general-header [section 4.5]
HttpHeaderConnection = 1, // general-header [section 4.5]
HttpHeaderDate = 2, // general-header [section 4.5]
HttpHeaderKeepAlive = 3, // general-header [not in rfc]
HttpHeaderPragma = 4, // general-header [section 4.5]
HttpHeaderTrailer = 5, // general-header [section 4.5]
HttpHeaderTransferEncoding = 6, // general-header [section 4.5]
HttpHeaderUpgrade = 7, // general-header [section 4.5]
HttpHeaderVia = 8, // general-header [section 4.5]
HttpHeaderWarning = 9, // general-header [section 4.5]
HttpHeaderAllow = 10, // entity-header [section 7.1]
HttpHeaderContentLength = 11, // entity-header [section 7.1]
HttpHeaderContentType = 12, // entity-header [section 7.1]
HttpHeaderContentEncoding = 13, // entity-header [section 7.1]
HttpHeaderContentLanguage = 14, // entity-header [section 7.1]
HttpHeaderContentLocation = 15, // entity-header [section 7.1]
HttpHeaderContentMd5 = 16, // entity-header [section 7.1]
HttpHeaderContentRange = 17, // entity-header [section 7.1]
HttpHeaderExpires = 18, // entity-header [section 7.1]
HttpHeaderLastModified = 19, // entity-header [section 7.1]
// Response Headers
HttpHeaderAcceptRanges = 20, // response-header [section 6.2]
HttpHeaderAge = 21, // response-header [section 6.2]
HttpHeaderEtag = 22, // response-header [section 6.2]
HttpHeaderLocation = 23, // response-header [section 6.2]
HttpHeaderProxyAuthenticate = 24, // response-header [section 6.2]
HttpHeaderRetryAfter = 25, // response-header [section 6.2]
HttpHeaderServer = 26, // response-header [section 6.2]
HttpHeaderSetCookie = 27, // response-header [not in rfc]
HttpHeaderVary = 28, // response-header [section 6.2]
HttpHeaderWwwAuthenticate = 29, // response-header [section 6.2]
HttpHeaderResponseMaximum = 30,
HttpHeaderMaximum = 41
}
private static readonly string[] s_strings =
{
"Cache-Control",
"Connection",
"Date",
"Keep-Alive",
"Pragma",
"Trailer",
"Transfer-Encoding",
"Upgrade",
"Via",
"Warning",
"Allow",
"Content-Length",
"Content-Type",
"Content-Encoding",
"Content-Language",
"Content-Location",
"Content-MD5",
"Content-Range",
"Expires",
"Last-Modified",
"Accept-Ranges",
"Age",
"ETag",
"Location",
"Proxy-Authenticate",
"Retry-After",
"Server",
"Set-Cookie",
"Vary",
"WWW-Authenticate",
};
private static readonly Dictionary<string, int> s_hashtable = CreateTable();
private static Dictionary<string, int> CreateTable()
{
var table = new Dictionary<string, int>((int)Enum.HttpHeaderResponseMaximum);
for (int i = 0; i < (int)Enum.HttpHeaderResponseMaximum; i++)
{
table.Add(s_strings[i], i);
}
return table;
}
internal static int IndexOfKnownHeader(string headerName)
{
int index;
return s_hashtable.TryGetValue(headerName, out index) ? index : -1;
}
internal static string ToString(int position)
{
return s_strings[position];
}
}
private static unsafe string GetKnownHeader(HTTP_REQUEST* request, long fixup, int headerIndex)
{
if (NetEventSource.IsEnabled) { NetEventSource.Enter(null); }
string header = null;
HTTP_KNOWN_HEADER* pKnownHeader = (&request->Headers.KnownHeaders) + headerIndex;
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(null, $"HttpApi::GetKnownHeader() pKnownHeader:0x{(IntPtr)pKnownHeader}");
NetEventSource.Info(null, $"HttpApi::GetKnownHeader() pRawValue:0x{(IntPtr)pKnownHeader->pRawValue} RawValueLength:{pKnownHeader->RawValueLength}");
}
// For known headers, when header value is empty, RawValueLength will be 0 and
// pRawValue will point to empty string
if (pKnownHeader->pRawValue != null)
{
header = new string(pKnownHeader->pRawValue + fixup, 0, pKnownHeader->RawValueLength);
}
if (NetEventSource.IsEnabled) { NetEventSource.Exit(null, $"HttpApi::GetKnownHeader() return:{header}"); }
return header;
}
internal static unsafe string GetKnownHeader(HTTP_REQUEST* request, int headerIndex)
{
return GetKnownHeader(request, 0, headerIndex);
}
private static unsafe string GetVerb(HTTP_REQUEST* request, long fixup)
{
string verb = null;
if ((int)request->Verb > (int)HTTP_VERB.HttpVerbUnknown && (int)request->Verb < (int)HTTP_VERB.HttpVerbMaximum)
{
verb = HttpVerbs[(int)request->Verb];
}
else if (request->Verb == HTTP_VERB.HttpVerbUnknown && request->pUnknownVerb != null)
{
verb = new string(request->pUnknownVerb + fixup, 0, request->UnknownVerbLength);
}
return verb;
}
internal static unsafe string GetVerb(HTTP_REQUEST* request)
{
return GetVerb(request, 0);
}
internal static unsafe string GetVerb(byte[] memoryBlob, IntPtr originalAddress)
{
fixed (byte* pMemoryBlob = memoryBlob)
{
return GetVerb((HTTP_REQUEST*)pMemoryBlob, pMemoryBlob - (byte*)originalAddress);
}
}
// Server API
internal static unsafe WebHeaderCollection GetHeaders(byte[] memoryBlob, IntPtr originalAddress)
{
NetEventSource.Enter(null);
// Return value.
WebHeaderCollection headerCollection = new WebHeaderCollection();
fixed (byte* pMemoryBlob = memoryBlob)
{
HTTP_REQUEST* request = (HTTP_REQUEST*)pMemoryBlob;
long fixup = pMemoryBlob - (byte*)originalAddress;
int index;
// unknown headers
if (request->Headers.UnknownHeaderCount != 0)
{
HTTP_UNKNOWN_HEADER* pUnknownHeader = (HTTP_UNKNOWN_HEADER*)(fixup + (byte*)request->Headers.pUnknownHeaders);
for (index = 0; index < request->Headers.UnknownHeaderCount; index++)
{
// For unknown headers, when header value is empty, RawValueLength will be 0 and
// pRawValue will be null.
if (pUnknownHeader->pName != null && pUnknownHeader->NameLength > 0)
{
string headerName = new string(pUnknownHeader->pName + fixup, 0, pUnknownHeader->NameLength);
string headerValue;
if (pUnknownHeader->pRawValue != null && pUnknownHeader->RawValueLength > 0)
{
headerValue = new string(pUnknownHeader->pRawValue + fixup, 0, pUnknownHeader->RawValueLength);
}
else
{
headerValue = string.Empty;
}
headerCollection.Add(headerName, headerValue);
}
pUnknownHeader++;
}
}
// known headers
HTTP_KNOWN_HEADER* pKnownHeader = &request->Headers.KnownHeaders;
for (index = 0; index < HttpHeaderRequestMaximum; index++)
{
// For known headers, when header value is empty, RawValueLength will be 0 and
// pRawValue will point to empty string ("\0")
if (pKnownHeader->pRawValue != null)
{
string headerValue = new string(pKnownHeader->pRawValue + fixup, 0, pKnownHeader->RawValueLength);
headerCollection.Add(HTTP_REQUEST_HEADER_ID.ToString(index), headerValue);
}
pKnownHeader++;
}
}
NetEventSource.Exit(null);
return headerCollection;
}
internal static unsafe uint GetChunks(byte[] memoryBlob, IntPtr originalAddress, ref int dataChunkIndex, ref uint dataChunkOffset, byte[] buffer, int offset, int size)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(null, $"HttpApi::GetChunks() memoryBlob:{memoryBlob}");
}
// Return value.
uint dataRead = 0;
fixed (byte* pMemoryBlob = memoryBlob)
{
HTTP_REQUEST* request = (HTTP_REQUEST*)pMemoryBlob;
long fixup = pMemoryBlob - (byte*)originalAddress;
if (request->EntityChunkCount > 0 && dataChunkIndex < request->EntityChunkCount && dataChunkIndex != -1)
{
HTTP_DATA_CHUNK* pDataChunk = (HTTP_DATA_CHUNK*)(fixup + (byte*)&request->pEntityChunks[dataChunkIndex]);
fixed (byte* pReadBuffer = buffer)
{
byte* pTo = &pReadBuffer[offset];
while (dataChunkIndex < request->EntityChunkCount && dataRead < size)
{
if (dataChunkOffset >= pDataChunk->BufferLength)
{
dataChunkOffset = 0;
dataChunkIndex++;
pDataChunk++;
}
else
{
byte* pFrom = pDataChunk->pBuffer + dataChunkOffset + fixup;
uint bytesToRead = pDataChunk->BufferLength - (uint)dataChunkOffset;
if (bytesToRead > (uint)size)
{
bytesToRead = (uint)size;
}
for (uint i = 0; i < bytesToRead; i++)
{
*(pTo++) = *(pFrom++);
}
dataRead += bytesToRead;
dataChunkOffset += bytesToRead;
}
}
}
}
//we're finished.
if (dataChunkIndex == request->EntityChunkCount)
{
dataChunkIndex = -1;
}
}
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(null);
}
return dataRead;
}
internal static unsafe HTTP_VERB GetKnownVerb(byte[] memoryBlob, IntPtr originalAddress)
{
NetEventSource.Enter(null);
// Return value.
HTTP_VERB verb = HTTP_VERB.HttpVerbUnknown;
fixed (byte* pMemoryBlob = memoryBlob)
{
HTTP_REQUEST* request = (HTTP_REQUEST*)pMemoryBlob;
if ((int)request->Verb > (int)HTTP_VERB.HttpVerbUnparsed && (int)request->Verb < (int)HTTP_VERB.HttpVerbMaximum)
{
verb = request->Verb;
}
}
NetEventSource.Exit(null);
return verb;
}
internal static unsafe IPEndPoint GetRemoteEndPoint(byte[] memoryBlob, IntPtr originalAddress)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null);
SocketAddress v4address = new SocketAddress(AddressFamily.InterNetwork, IPv4AddressSize);
SocketAddress v6address = new SocketAddress(AddressFamily.InterNetworkV6, IPv6AddressSize);
fixed (byte* pMemoryBlob = memoryBlob)
{
HTTP_REQUEST* request = (HTTP_REQUEST*)pMemoryBlob;
IntPtr address = request->Address.pRemoteAddress != null ? (IntPtr)(pMemoryBlob - (byte*)originalAddress + (byte*)request->Address.pRemoteAddress) : IntPtr.Zero;
CopyOutAddress(address, ref v4address, ref v6address);
}
IPEndPoint endpoint = null;
if (v4address != null)
{
endpoint = new IPEndPoint(IPAddress.Any, IPEndPoint.MinPort).Create(v4address) as IPEndPoint;
}
else if (v6address != null)
{
endpoint = new IPEndPoint(IPAddress.IPv6Any, IPEndPoint.MinPort).Create(v6address) as IPEndPoint;
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null);
return endpoint;
}
internal static unsafe IPEndPoint GetLocalEndPoint(byte[] memoryBlob, IntPtr originalAddress)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null);
SocketAddress v4address = new SocketAddress(AddressFamily.InterNetwork, IPv4AddressSize);
SocketAddress v6address = new SocketAddress(AddressFamily.InterNetworkV6, IPv6AddressSize);
fixed (byte* pMemoryBlob = memoryBlob)
{
HTTP_REQUEST* request = (HTTP_REQUEST*)pMemoryBlob;
IntPtr address = request->Address.pLocalAddress != null ? (IntPtr)(pMemoryBlob - (byte*)originalAddress + (byte*)request->Address.pLocalAddress) : IntPtr.Zero;
CopyOutAddress(address, ref v4address, ref v6address);
}
IPEndPoint endpoint = null;
if (v4address != null)
{
endpoint = s_any.Create(v4address) as IPEndPoint;
}
else if (v6address != null)
{
endpoint = s_ipv6Any.Create(v6address) as IPEndPoint;
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null);
return endpoint;
}
private static unsafe void CopyOutAddress(IntPtr address, ref SocketAddress v4address, ref SocketAddress v6address)
{
if (address != IntPtr.Zero)
{
ushort addressFamily = *((ushort*)address);
if (addressFamily == (ushort)AddressFamily.InterNetwork)
{
v6address = null;
for (int index = 2; index < IPv4AddressSize; index++)
{
v4address[index] = ((byte*)address)[index];
}
return;
}
if (addressFamily == (ushort)AddressFamily.InterNetworkV6)
{
v4address = null;
for (int index = 2; index < IPv6AddressSize; index++)
{
v6address[index] = ((byte*)address)[index];
}
return;
}
}
v4address = null;
v6address = null;
}
}
}
| |
using Newtonsoft.Json;
using System;
using System.Runtime.Serialization;
using System.Text;
namespace Model
{
/// <summary>
///
/// </summary>
[DataContract]
public class ResourceLimits : IEquatable<ResourceLimits>
{
/// <summary>
/// Initializes a new instance of the <see cref="ResourceLimits" /> class.
/// </summary>
public ResourceLimits()
{
}
/// <summary>
/// The total number of cores per server
/// </summary>
/// <value>The total number of cores per server</value>
[DataMember(Name = "coresPerServer", EmitDefaultValue = false)]
public int? CoresPerServer { get; set; }
/// <summary>
/// The total number of cores per contract
/// </summary>
/// <value>The total number of cores per contract</value>
[DataMember(Name = "coresPerContract", EmitDefaultValue = false)]
public int? CoresPerContract { get; set; }
/// <summary>
/// The number of cores currently in use
/// </summary>
/// <value>The number of cores currently in use</value>
[DataMember(Name = "coresProvisioned", EmitDefaultValue = false)]
public int? CoresProvisioned { get; set; }
/// <summary>
/// The total amount of RAM per server
/// </summary>
/// <value>The total amount of RAM per server</value>
[DataMember(Name = "ramPerServer", EmitDefaultValue = false)]
public int? RamPerServer { get; set; }
/// <summary>
/// The total amount of RAM per contract
/// </summary>
/// <value>The total amount of RAM per contract</value>
[DataMember(Name = "ramPerContract", EmitDefaultValue = false)]
public int? RamPerContract { get; set; }
/// <summary>
/// The total amount of RAM currently in use
/// </summary>
/// <value>The total amount of RAM currently in use</value>
[DataMember(Name = "ramProvisioned", EmitDefaultValue = false)]
public int? RamProvisioned { get; set; }
/// <summary>
/// The total size of HDD disk space per contract
/// </summary>
/// <value>The total size of HDD disk space per contract</value>
[DataMember(Name = "hddLimitPerContract", EmitDefaultValue = false)]
public int? HddLimitPerContract { get; set; }
/// <summary>
/// The total size of HDD disk space per volume
/// </summary>
/// <value>The total size of HDD disk space per volume</value>
[DataMember(Name = "hddLimitPerVolume", EmitDefaultValue = false)]
public int? HddLimitPerVolume { get; set; }
/// <summary>
/// The total size of HDD disk space currently in use
/// </summary>
/// <value>The total size of HDD disk space currently in use</value>
[DataMember(Name = "hddVolumeProvisioned", EmitDefaultValue = false)]
public int? HddVolumeProvisioned { get; set; }
/// <summary>
/// The total size of SSD disk space per contract
/// </summary>
/// <value>The total size of SSD disk space per contract</value>
[DataMember(Name = "ssdLimitPerContract", EmitDefaultValue = false)]
public int? SsdLimitPerContract { get; set; }
/// <summary>
/// The total size of SSD disk space per volume
/// </summary>
/// <value>The total size of SSD disk space per volume</value>
[DataMember(Name = "ssdLimitPerVolume", EmitDefaultValue = false)]
public int? SsdLimitPerVolume { get; set; }
/// <summary>
/// The total size of SSD disk space currently in use
/// </summary>
/// <value>The total size of SSD disk space currently in use</value>
[DataMember(Name = "ssdVolumeProvisioned", EmitDefaultValue = false)]
public int? SsdVolumeProvisioned { get; set; }
/// <summary>
/// The number of reservable IPs
/// </summary>
/// <value>The number of reservable IPs</value>
[DataMember(Name = "reservableIps", EmitDefaultValue = false)]
public int? ReservableIps { get; set; }
/// <summary>
/// The total number of reservable IPs on contract
/// </summary>
/// <value>The total number of reservable IPs on contract</value>
[DataMember(Name = "reservedIpsOnContract", EmitDefaultValue = false)]
public int? ReservedIpsOnContract { get; set; }
/// <summary>
/// The number of reservable IPs currently in use
/// </summary>
/// <value>The number of reservable IPs currently in use</value>
[DataMember(Name = "reservedIpsInUse", EmitDefaultValue = false)]
public int? ReservedIpsInUse { 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 ResourceLimits {\n");
sb.Append(" CoresPerServer: ").Append(CoresPerServer).Append("\n");
sb.Append(" CoresPerContract: ").Append(CoresPerContract).Append("\n");
sb.Append(" CoresProvisioned: ").Append(CoresProvisioned).Append("\n");
sb.Append(" RamPerServer: ").Append(RamPerServer).Append("\n");
sb.Append(" RamPerContract: ").Append(RamPerContract).Append("\n");
sb.Append(" RamProvisioned: ").Append(RamProvisioned).Append("\n");
sb.Append(" HddLimitPerVolume: ").Append(HddLimitPerVolume).Append("\n");
sb.Append(" HddLimitPerContract: ").Append(HddLimitPerContract).Append("\n");
sb.Append(" HddVolumeProvisioned: ").Append(HddVolumeProvisioned).Append("\n");
sb.Append(" SsdLimitPerVolume: ").Append(SsdLimitPerVolume).Append("\n");
sb.Append(" SsdLimitPerContract: ").Append(SsdLimitPerContract).Append("\n");
sb.Append(" SsdVolumeProvisioned: ").Append(SsdVolumeProvisioned).Append("\n");
sb.Append(" ReservableIps: ").Append(ReservableIps).Append("\n");
sb.Append(" ReservedIpsOnContract: ").Append(ReservedIpsOnContract).Append("\n");
sb.Append(" ReservedIpsInUse: ").Append(ReservedIpsInUse).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
return this.Equals(obj as ResourceLimits);
}
/// <summary>
/// Returns true if ResourceLimits instances are equal
/// </summary>
/// <param name="other">Instance of ResourceLimits to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ResourceLimits other)
{
if (other == null)
return false;
return
(
this.CoresPerServer == other.CoresPerServer ||
this.CoresPerServer != null &&
this.CoresPerServer.Equals(other.CoresPerServer)
) &&
(
this.CoresPerContract == other.CoresPerContract ||
this.CoresPerContract != null &&
this.CoresPerContract.Equals(other.CoresPerContract)
) &&
(
this.CoresProvisioned == other.CoresProvisioned ||
this.CoresProvisioned != null &&
this.CoresProvisioned.Equals(other.CoresProvisioned)
) &&
(
this.RamPerServer == other.RamPerServer ||
this.RamPerServer != null &&
this.RamPerServer.Equals(other.RamPerServer)
) &&
(
this.RamPerContract == other.RamPerContract ||
this.RamPerContract != null &&
this.RamPerContract.Equals(other.RamPerContract)
) &&
(
this.RamProvisioned == other.RamProvisioned ||
this.RamProvisioned != null &&
this.RamProvisioned.Equals(other.RamProvisioned)
) &&
(
this.HddLimitPerVolume == other.HddLimitPerVolume ||
this.HddLimitPerVolume != null &&
this.HddLimitPerVolume.Equals(other.HddLimitPerVolume)
) &&
(
this.HddLimitPerContract == other.HddLimitPerContract ||
this.HddLimitPerContract != null &&
this.HddLimitPerContract.Equals(other.HddLimitPerContract)
) &&
(
this.HddVolumeProvisioned == other.HddVolumeProvisioned ||
this.HddVolumeProvisioned != null &&
this.HddVolumeProvisioned.Equals(other.HddVolumeProvisioned)
) &&
(
this.SsdLimitPerVolume == other.SsdLimitPerVolume ||
this.SsdLimitPerVolume != null &&
this.SsdLimitPerVolume.Equals(other.SsdLimitPerVolume)
) &&
(
this.SsdLimitPerContract == other.SsdLimitPerContract ||
this.SsdLimitPerContract != null &&
this.SsdLimitPerContract.Equals(other.SsdLimitPerContract)
) &&
(
this.SsdVolumeProvisioned == other.SsdVolumeProvisioned ||
this.SsdVolumeProvisioned != null &&
this.SsdVolumeProvisioned.Equals(other.SsdVolumeProvisioned)
) &&
(
this.ReservableIps == other.ReservableIps ||
this.ReservableIps != null &&
this.ReservableIps.Equals(other.ReservableIps)
) &&
(
this.ReservedIpsOnContract == other.ReservedIpsOnContract ||
this.ReservedIpsOnContract != null &&
this.ReservedIpsOnContract.Equals(other.ReservedIpsOnContract)
) &&
(
this.ReservedIpsInUse == other.ReservedIpsInUse ||
this.ReservedIpsInUse != null &&
this.ReservedIpsInUse.Equals(other.ReservedIpsInUse)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked
{
int hash = 41;
if (this.CoresPerServer != null)
hash = hash * 59 + this.CoresPerServer.GetHashCode();
if (this.CoresPerContract != null)
hash = hash * 59 + this.CoresPerContract.GetHashCode();
if (this.CoresProvisioned != null)
hash = hash * 59 + this.CoresProvisioned.GetHashCode();
if (this.RamPerServer != null)
hash = hash * 59 + this.RamPerServer.GetHashCode();
if (this.RamPerContract != null)
hash = hash * 59 + this.RamPerContract.GetHashCode();
if (this.RamProvisioned != null)
hash = hash * 59 + this.RamProvisioned.GetHashCode();
if (this.HddLimitPerVolume != null)
hash = hash * 59 + this.HddLimitPerVolume.GetHashCode();
if (this.HddLimitPerContract != null)
hash = hash * 59 + this.HddLimitPerContract.GetHashCode();
if (this.HddVolumeProvisioned != null)
hash = hash * 59 + this.HddVolumeProvisioned.GetHashCode();
if (this.SsdLimitPerVolume != null)
hash = hash * 59 + this.SsdLimitPerVolume.GetHashCode();
if (this.SsdLimitPerContract != null)
hash = hash * 59 + this.SsdLimitPerContract.GetHashCode();
if (this.SsdVolumeProvisioned != null)
hash = hash * 59 + this.SsdVolumeProvisioned.GetHashCode();
if (this.ReservableIps != null)
hash = hash * 59 + this.ReservableIps.GetHashCode();
if (this.ReservedIpsOnContract != null)
hash = hash * 59 + this.ReservedIpsOnContract.GetHashCode();
if (this.ReservedIpsInUse != null)
hash = hash * 59 + this.ReservedIpsInUse.GetHashCode();
return hash;
}
}
}
}
| |
using System;
using Fonet.Layout;
using Fonet.Pdf;
using Fonet.Pdf.Gdi;
namespace Fonet.Render.Pdf.Fonts {
/// <summary>
/// Represents a TrueType font program.
/// </summary>
internal class TrueTypeFont : Font, IFontDescriptor {
public const string WinAnsiEncoding = "WinAnsiEncoding";
private CodePointMapping mapping =
CodePointMapping.GetMapping("WinAnsiEncoding");
/// <summary>
/// Wrapper around a Win32 HDC.
/// </summary>
private GdiDeviceContent dc;
/// <summary>
/// Provides font metrics using the Win32 Api.
/// </summary>
private GdiFontMetrics metrics;
/// <summary>
/// List of kerning pairs.
/// </summary>
private GdiKerningPairs kerning;
/// <summary>
/// Maps a glyph index to a PDF width
/// </summary>
private int[] widths;
/// <summary>
///
/// </summary>
protected FontProperties properties;
/// <summary>
/// Class constructor
/// </summary>
/// <param name="properties"></param>
public TrueTypeFont(FontProperties properties) {
this.properties = properties;
ObtainFontMetrics();
}
/// <summary>
/// Creates a <see cref="GdiFontMetrics"/> object from <b>baseFontName</b>
/// </summary>
private void ObtainFontMetrics() {
dc = new GdiDeviceContent();
GdiFont font = GdiFont.CreateDesignFont(
properties.FaceName, properties.IsBold, properties.IsItalic, dc);
metrics = font.GetMetrics(dc);
}
public PdfArray Array {
get {
PdfArray widthsArray = new PdfArray();
widthsArray.AddArray(Widths);
return widthsArray;
}
}
#region Implementation of Font members
/// <summary>
/// Returns <see cref="PdfFontSubTypeEnum.TrueType"/>.
/// </summary>
public override PdfFontSubTypeEnum SubType {
get { return PdfFontSubTypeEnum.TrueType; }
}
public override string FontName {
get {
// See section 5.5.2 "TrueType fonts" for more details
if (properties.IsBoldItalic) {
return String.Format("{0},BoldItalic", properties.FaceName);
}
else if (properties.IsBold) {
return String.Format("{0},Bold", properties.FaceName);
}
else if (properties.IsItalic) {
return String.Format("{0},Italic", properties.FaceName);
}
else {
return properties.FaceName;
}
}
}
public override PdfFontTypeEnum Type {
get { return PdfFontTypeEnum.TrueType; }
}
public override string Encoding {
get { return WinAnsiEncoding; }
}
public override IFontDescriptor Descriptor {
get { return this; }
}
public override bool MultiByteFont {
get { return false; }
}
public override ushort MapCharacter(char c) {
// TrueType fonts only support the Basic and Extended Latin blocks
if (c > Byte.MaxValue) {
return (ushort) FirstChar;
}
return mapping.MapCharacter(c);
}
public override int Ascender {
get { return metrics.Ascent; }
}
public override int Descender {
get { return metrics.Descent; }
}
public override int CapHeight {
get { return metrics.CapHeight; }
}
public override int FirstChar {
get { return 0; }
}
public override int LastChar {
get {
// Only support Latin1 character set
return 255;
}
}
/// <summary>
/// See <see cref="Font.GetWidth(ushort)"/>
/// </summary>
/// <param name="charIndex">A WinAnsi codepoint.</param>
/// <returns></returns>
public override int GetWidth(ushort charIndex) {
EnsureWidthsArray();
// The widths array is keyed on WinAnsiEncoding codepoint
return widths[charIndex];
}
public override int[] Widths {
get {
EnsureWidthsArray();
return widths;
}
}
#endregion
private void EnsureWidthsArray() {
if (widths == null) {
widths = metrics.GetAnsiWidths();
}
}
#region Implementation of IFontDescriptior interface
public int Flags {
get { return metrics.Flags; }
}
public int[] FontBBox {
get { return metrics.BoundingBox; }
}
public int ItalicAngle {
get { return metrics.ItalicAngle; }
}
public int StemV {
get { return metrics.StemV; }
}
public bool HasKerningInfo {
get {
if (kerning == null) {
kerning = metrics.AnsiKerningPairs;
}
return (kerning.Count != 0);
}
}
public bool IsEmbeddable {
get { return false; }
}
public bool IsSubsettable {
get { return false; }
}
public byte[] FontData {
get { return metrics.GetFontData(); }
}
public GdiKerningPairs KerningInfo {
get {
if (kerning == null) {
kerning = metrics.AnsiKerningPairs;
}
return kerning;
}
}
#endregion
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="FeedItemSetLinkServiceClient"/> instances.</summary>
public sealed partial class FeedItemSetLinkServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="FeedItemSetLinkServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="FeedItemSetLinkServiceSettings"/>.</returns>
public static FeedItemSetLinkServiceSettings GetDefault() => new FeedItemSetLinkServiceSettings();
/// <summary>
/// Constructs a new <see cref="FeedItemSetLinkServiceSettings"/> object with default settings.
/// </summary>
public FeedItemSetLinkServiceSettings()
{
}
private FeedItemSetLinkServiceSettings(FeedItemSetLinkServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetFeedItemSetLinkSettings = existing.GetFeedItemSetLinkSettings;
MutateFeedItemSetLinksSettings = existing.MutateFeedItemSetLinksSettings;
OnCopy(existing);
}
partial void OnCopy(FeedItemSetLinkServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>FeedItemSetLinkServiceClient.GetFeedItemSetLink</c> and
/// <c>FeedItemSetLinkServiceClient.GetFeedItemSetLinkAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetFeedItemSetLinkSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>FeedItemSetLinkServiceClient.MutateFeedItemSetLinks</c> and
/// <c>FeedItemSetLinkServiceClient.MutateFeedItemSetLinksAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateFeedItemSetLinksSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="FeedItemSetLinkServiceSettings"/> object.</returns>
public FeedItemSetLinkServiceSettings Clone() => new FeedItemSetLinkServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="FeedItemSetLinkServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class FeedItemSetLinkServiceClientBuilder : gaxgrpc::ClientBuilderBase<FeedItemSetLinkServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public FeedItemSetLinkServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public FeedItemSetLinkServiceClientBuilder()
{
UseJwtAccessWithScopes = FeedItemSetLinkServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref FeedItemSetLinkServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<FeedItemSetLinkServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override FeedItemSetLinkServiceClient Build()
{
FeedItemSetLinkServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<FeedItemSetLinkServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<FeedItemSetLinkServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private FeedItemSetLinkServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return FeedItemSetLinkServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<FeedItemSetLinkServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return FeedItemSetLinkServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => FeedItemSetLinkServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => FeedItemSetLinkServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => FeedItemSetLinkServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>FeedItemSetLinkService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage feed item set links.
/// </remarks>
public abstract partial class FeedItemSetLinkServiceClient
{
/// <summary>
/// The default endpoint for the FeedItemSetLinkService service, which is a host of "googleads.googleapis.com"
/// and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default FeedItemSetLinkService scopes.</summary>
/// <remarks>
/// The default FeedItemSetLinkService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="FeedItemSetLinkServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="FeedItemSetLinkServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="FeedItemSetLinkServiceClient"/>.</returns>
public static stt::Task<FeedItemSetLinkServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new FeedItemSetLinkServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="FeedItemSetLinkServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="FeedItemSetLinkServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="FeedItemSetLinkServiceClient"/>.</returns>
public static FeedItemSetLinkServiceClient Create() => new FeedItemSetLinkServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="FeedItemSetLinkServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="FeedItemSetLinkServiceSettings"/>.</param>
/// <returns>The created <see cref="FeedItemSetLinkServiceClient"/>.</returns>
internal static FeedItemSetLinkServiceClient Create(grpccore::CallInvoker callInvoker, FeedItemSetLinkServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
FeedItemSetLinkService.FeedItemSetLinkServiceClient grpcClient = new FeedItemSetLinkService.FeedItemSetLinkServiceClient(callInvoker);
return new FeedItemSetLinkServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC FeedItemSetLinkService client</summary>
public virtual FeedItemSetLinkService.FeedItemSetLinkServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested feed item set link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::FeedItemSetLink GetFeedItemSetLink(GetFeedItemSetLinkRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested feed item set link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::FeedItemSetLink> GetFeedItemSetLinkAsync(GetFeedItemSetLinkRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested feed item set link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::FeedItemSetLink> GetFeedItemSetLinkAsync(GetFeedItemSetLinkRequest request, st::CancellationToken cancellationToken) =>
GetFeedItemSetLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested feed item set link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the feed item set link to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::FeedItemSetLink GetFeedItemSetLink(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetFeedItemSetLink(new GetFeedItemSetLinkRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested feed item set link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the feed item set link to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::FeedItemSetLink> GetFeedItemSetLinkAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetFeedItemSetLinkAsync(new GetFeedItemSetLinkRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested feed item set link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the feed item set link to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::FeedItemSetLink> GetFeedItemSetLinkAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetFeedItemSetLinkAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested feed item set link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the feed item set link to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::FeedItemSetLink GetFeedItemSetLink(gagvr::FeedItemSetLinkName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetFeedItemSetLink(new GetFeedItemSetLinkRequest
{
ResourceNameAsFeedItemSetLinkName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested feed item set link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the feed item set link to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::FeedItemSetLink> GetFeedItemSetLinkAsync(gagvr::FeedItemSetLinkName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetFeedItemSetLinkAsync(new GetFeedItemSetLinkRequest
{
ResourceNameAsFeedItemSetLinkName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested feed item set link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the feed item set link to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::FeedItemSetLink> GetFeedItemSetLinkAsync(gagvr::FeedItemSetLinkName resourceName, st::CancellationToken cancellationToken) =>
GetFeedItemSetLinkAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes feed item set links.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateFeedItemSetLinksResponse MutateFeedItemSetLinks(MutateFeedItemSetLinksRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes feed item set links.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateFeedItemSetLinksResponse> MutateFeedItemSetLinksAsync(MutateFeedItemSetLinksRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes feed item set links.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateFeedItemSetLinksResponse> MutateFeedItemSetLinksAsync(MutateFeedItemSetLinksRequest request, st::CancellationToken cancellationToken) =>
MutateFeedItemSetLinksAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes feed item set links.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose feed item set links are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual feed item set links.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateFeedItemSetLinksResponse MutateFeedItemSetLinks(string customerId, scg::IEnumerable<FeedItemSetLinkOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateFeedItemSetLinks(new MutateFeedItemSetLinksRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes feed item set links.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose feed item set links are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual feed item set links.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateFeedItemSetLinksResponse> MutateFeedItemSetLinksAsync(string customerId, scg::IEnumerable<FeedItemSetLinkOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateFeedItemSetLinksAsync(new MutateFeedItemSetLinksRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes feed item set links.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose feed item set links are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual feed item set links.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateFeedItemSetLinksResponse> MutateFeedItemSetLinksAsync(string customerId, scg::IEnumerable<FeedItemSetLinkOperation> operations, st::CancellationToken cancellationToken) =>
MutateFeedItemSetLinksAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>FeedItemSetLinkService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage feed item set links.
/// </remarks>
public sealed partial class FeedItemSetLinkServiceClientImpl : FeedItemSetLinkServiceClient
{
private readonly gaxgrpc::ApiCall<GetFeedItemSetLinkRequest, gagvr::FeedItemSetLink> _callGetFeedItemSetLink;
private readonly gaxgrpc::ApiCall<MutateFeedItemSetLinksRequest, MutateFeedItemSetLinksResponse> _callMutateFeedItemSetLinks;
/// <summary>
/// Constructs a client wrapper for the FeedItemSetLinkService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="FeedItemSetLinkServiceSettings"/> used within this client.
/// </param>
public FeedItemSetLinkServiceClientImpl(FeedItemSetLinkService.FeedItemSetLinkServiceClient grpcClient, FeedItemSetLinkServiceSettings settings)
{
GrpcClient = grpcClient;
FeedItemSetLinkServiceSettings effectiveSettings = settings ?? FeedItemSetLinkServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetFeedItemSetLink = clientHelper.BuildApiCall<GetFeedItemSetLinkRequest, gagvr::FeedItemSetLink>(grpcClient.GetFeedItemSetLinkAsync, grpcClient.GetFeedItemSetLink, effectiveSettings.GetFeedItemSetLinkSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetFeedItemSetLink);
Modify_GetFeedItemSetLinkApiCall(ref _callGetFeedItemSetLink);
_callMutateFeedItemSetLinks = clientHelper.BuildApiCall<MutateFeedItemSetLinksRequest, MutateFeedItemSetLinksResponse>(grpcClient.MutateFeedItemSetLinksAsync, grpcClient.MutateFeedItemSetLinks, effectiveSettings.MutateFeedItemSetLinksSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateFeedItemSetLinks);
Modify_MutateFeedItemSetLinksApiCall(ref _callMutateFeedItemSetLinks);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetFeedItemSetLinkApiCall(ref gaxgrpc::ApiCall<GetFeedItemSetLinkRequest, gagvr::FeedItemSetLink> call);
partial void Modify_MutateFeedItemSetLinksApiCall(ref gaxgrpc::ApiCall<MutateFeedItemSetLinksRequest, MutateFeedItemSetLinksResponse> call);
partial void OnConstruction(FeedItemSetLinkService.FeedItemSetLinkServiceClient grpcClient, FeedItemSetLinkServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC FeedItemSetLinkService client</summary>
public override FeedItemSetLinkService.FeedItemSetLinkServiceClient GrpcClient { get; }
partial void Modify_GetFeedItemSetLinkRequest(ref GetFeedItemSetLinkRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateFeedItemSetLinksRequest(ref MutateFeedItemSetLinksRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested feed item set link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::FeedItemSetLink GetFeedItemSetLink(GetFeedItemSetLinkRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetFeedItemSetLinkRequest(ref request, ref callSettings);
return _callGetFeedItemSetLink.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested feed item set link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::FeedItemSetLink> GetFeedItemSetLinkAsync(GetFeedItemSetLinkRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetFeedItemSetLinkRequest(ref request, ref callSettings);
return _callGetFeedItemSetLink.Async(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes feed item set links.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateFeedItemSetLinksResponse MutateFeedItemSetLinks(MutateFeedItemSetLinksRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateFeedItemSetLinksRequest(ref request, ref callSettings);
return _callMutateFeedItemSetLinks.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes feed item set links.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateFeedItemSetLinksResponse> MutateFeedItemSetLinksAsync(MutateFeedItemSetLinksRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateFeedItemSetLinksRequest(ref request, ref callSettings);
return _callMutateFeedItemSetLinks.Async(request, callSettings);
}
}
}
| |
//
// System.Web.UI.DataSourceView
//
// Authors:
// Ben Maurer ([email protected])
// Sanjay Gupta ([email protected])
//
// (C) 2003 Ben Maurer
// (C) 2004 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.
//
#if NET_2_0
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.ComponentModel;
namespace System.Web.UI {
public abstract class DataSourceView
{
IDataSource dataSourceOwner;
string viewName = String.Empty;
protected DataSourceView (IDataSource owner, string viewName)
{
this.dataSourceOwner = owner;
this.viewName = viewName;
}
public virtual void Delete (IDictionary keys, IDictionary values,
DataSourceViewOperationCallback callBack)
{
if (callBack == null)
throw new ArgumentNullException ("callBack");
int rowAffected = 0;
Exception passOn = null;
try {
rowAffected = ExecuteDelete (keys, values);
} catch (Exception e) {
passOn = e;
}
if (!callBack (rowAffected, passOn) && passOn != null)
throw passOn;
}
protected virtual int ExecuteDelete(IDictionary keys, IDictionary values)
{
throw new NotSupportedException ();
}
protected virtual int ExecuteInsert (IDictionary keys)
{
throw new NotSupportedException();
}
protected internal abstract IEnumerable ExecuteSelect (
DataSourceSelectArguments arguments);
protected virtual int ExecuteUpdate (IDictionary keys, IDictionary values,
IDictionary oldValues )
{
throw new NotSupportedException ();
}
public virtual void Insert (IDictionary values,
DataSourceViewOperationCallback callBack)
{
if (callBack == null)
throw new ArgumentNullException("callBack");
int rowAffected = 0;
Exception passOn = null;
try {
rowAffected = ExecuteInsert (values);
} catch (Exception e) {
passOn = e;
}
if (!callBack (rowAffected, passOn) && passOn != null)
throw passOn;
}
protected virtual void OnDataSourceViewChanged (EventArgs eventArgs)
{
if (eventsList != null) {
EventHandler evtHandler = eventsList [EventDataSourceViewChanged] as EventHandler;
if (evtHandler != null)
evtHandler(this, eventArgs);
}
}
protected internal virtual void RaiseUnsupportedCapabilityError (
DataSourceCapabilities capability)
{
if ((capability & DataSourceCapabilities.Sort) != 0)
if (!CanSort)
throw new NotSupportedException ("Sort Capabilites");
if ((capability & DataSourceCapabilities.Page) != 0)
if (!CanPage)
throw new NotSupportedException("Page Capabilites");
if ((capability & DataSourceCapabilities.RetrieveTotalRowCount) != 0)
if (!CanRetrieveTotalRowCount)
throw new NotSupportedException("RetrieveTotalRowCount Capabilites");
return;
}
public virtual void Select (DataSourceSelectArguments selectArgs,
DataSourceViewSelectCallback callBack)
{
if (callBack == null)
throw new ArgumentNullException("callBack");
selectArgs.RaiseUnsupportedCapabilitiesError (this);
IEnumerable selectList = ExecuteSelect (selectArgs);
callBack (selectList);
}
public virtual void Update(IDictionary keys, IDictionary values,
IDictionary oldValues, DataSourceViewOperationCallback callBack)
{
if (callBack == null)
throw new ArgumentNullException ("callBack");
int rowAffected = 0;
Exception passOn = null;
try {
rowAffected = ExecuteUpdate (keys, values, oldValues);
} catch (Exception e) {
passOn = e;
}
if (!callBack (rowAffected, passOn) && passOn != null)
throw passOn;
}
public virtual bool CanDelete { get { return false; } }
public virtual bool CanInsert { get { return false; } }
public virtual bool CanPage { get { return false; } }
public virtual bool CanRetrieveTotalRowCount { get { return false; } }
public virtual bool CanSort { get { return false; } }
public virtual bool CanUpdate { get { return false; } }
EventHandlerList eventsList;
protected EventHandlerList Events {
get {
if (eventsList == null)
eventsList = new EventHandlerList();
return eventsList;
}
}
internal bool HasEvents ()
{
return eventsList != null;
}
public virtual string Name {
get { return viewName; }
}
static readonly object EventDataSourceViewChanged = new object ();
public event EventHandler DataSourceViewChanged
{
add { Events.AddHandler (EventDataSourceViewChanged, value); }
remove { Events.RemoveHandler (EventDataSourceViewChanged, value); }
}
}
}
#endif
| |
/*
* 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.Reflection;
using log4net;
using OpenMetaverse;
namespace OpenSim.Region.Framework.Scenes
{
public class EntityManager : IEnumerable<EntityBase>
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly Dictionary<UUID,EntityBase> m_eb_uuid = new Dictionary<UUID, EntityBase>();
private readonly Dictionary<uint, EntityBase> m_eb_localID = new Dictionary<uint, EntityBase>();
//private readonly Dictionary<UUID, ScenePresence> m_pres_uuid = new Dictionary<UUID, ScenePresence>();
private readonly Object m_lock = new Object();
[Obsolete("Use Add() instead.")]
public void Add(UUID id, EntityBase eb)
{
Add(eb);
}
public void Add(EntityBase entity)
{
lock (m_lock)
{
try
{
m_eb_uuid.Add(entity.UUID, entity);
m_eb_localID.Add(entity.LocalId, entity);
}
catch(Exception e)
{
m_log.ErrorFormat("Add Entity failed: {0}", e.Message);
}
}
}
public void InsertOrReplace(EntityBase entity)
{
lock (m_lock)
{
try
{
m_eb_uuid[entity.UUID] = entity;
m_eb_localID[entity.LocalId] = entity;
}
catch(Exception e)
{
m_log.ErrorFormat("Insert or Replace Entity failed: {0}", e.Message);
}
}
}
public void Clear()
{
lock (m_lock)
{
m_eb_uuid.Clear();
m_eb_localID.Clear();
}
}
public int Count
{
get
{
return m_eb_uuid.Count;
}
}
public bool ContainsKey(UUID id)
{
try
{
return m_eb_uuid.ContainsKey(id);
}
catch
{
return false;
}
}
public bool ContainsKey(uint localID)
{
try
{
return m_eb_localID.ContainsKey(localID);
}
catch
{
return false;
}
}
public bool Remove(uint localID)
{
lock (m_lock)
{
try
{
bool a = false;
EntityBase entity;
if (m_eb_localID.TryGetValue(localID, out entity))
a = m_eb_uuid.Remove(entity.UUID);
bool b = m_eb_localID.Remove(localID);
return a && b;
}
catch (Exception e)
{
m_log.ErrorFormat("Remove Entity failed for {0}", localID, e);
return false;
}
}
}
public bool Remove(UUID id)
{
lock (m_lock)
{
try
{
bool a = false;
EntityBase entity;
if (m_eb_uuid.TryGetValue(id, out entity))
a = m_eb_localID.Remove(entity.LocalId);
bool b = m_eb_uuid.Remove(id);
return a && b;
}
catch (Exception e)
{
m_log.ErrorFormat("Remove Entity failed for {0}", id, e);
return false;
}
}
}
public List<EntityBase> GetAllByType<T>()
{
List<EntityBase> tmp = new List<EntityBase>();
lock (m_lock)
{
try
{
foreach (KeyValuePair<UUID, EntityBase> pair in m_eb_uuid)
{
if (pair.Value is T)
{
tmp.Add(pair.Value);
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("GetAllByType failed for {0}", e);
tmp = null;
}
}
return tmp;
}
public List<EntityBase> GetEntities()
{
lock (m_lock)
{
return new List<EntityBase>(m_eb_uuid.Values);
}
}
public EntityBase this[UUID id]
{
get
{
lock (m_lock)
{
EntityBase entity;
if (m_eb_uuid.TryGetValue(id, out entity))
return entity;
else
return null;
}
}
set
{
InsertOrReplace(value);
}
}
public EntityBase this[uint localID]
{
get
{
lock (m_lock)
{
EntityBase entity;
if (m_eb_localID.TryGetValue(localID, out entity))
return entity;
else
return null;
}
}
set
{
InsertOrReplace(value);
}
}
public bool TryGetValue(UUID key, out EntityBase obj)
{
lock (m_lock)
{
return m_eb_uuid.TryGetValue(key, out obj);
}
}
public bool TryGetValue(uint key, out EntityBase obj)
{
lock (m_lock)
{
return m_eb_localID.TryGetValue(key, out obj);
}
}
/// <summary>
/// This could be optimised to work on the list 'live' rather than making a safe copy and iterating that.
/// </summary>
/// <returns></returns>
public IEnumerator<EntityBase> GetEnumerator()
{
return GetEntities().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| |
using Q42.HueApi.ColorConverters;
using Q42.HueApi.Streaming.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Q42.HueApi.Streaming.Extensions
{
public enum IteratorEffectMode
{
/// <summary>
/// Loops the lights one by one
/// </summary>
Cycle,
/// <summary>
/// Each light one by one, bounces back on the end of the list
/// </summary>
Bounce,
/// <summary>
/// Only Once
/// </summary>
Single,
/// <summary>
/// Will select a random light each iteration
/// </summary>
Random,
/// <summary>
/// Order lights random and do each light once
/// </summary>
RandomOrdered,
/// <summary>
/// Apply the effect on all lights at the same time, ignoring different start states.
/// Best for syncing all lights
/// </summary>
All,
/// <summary>
/// Apply the effect on all lights individually.
/// Best used for example random colors to all lights
/// </summary>
AllIndividual
}
/// <summary>
/// Function to apply light effects.
/// </summary>
/// <param name="current">Will contain 1 light, only contains multiple lights when IteratorEffectMode.All is used</param>
/// <param name="timeSpan"></param>
public delegate Task IteratorEffectFunc(IEnumerable<EntertainmentLight> current, CancellationToken cancellationToken, TimeSpan timeSpan);
public static class EntertainmentGroupExtensions
{
public static IEnumerable<EntertainmentLight> GetLeft(this IEnumerable<EntertainmentLight> group) => group.Where(x => x.LightLocation.IsLeft);
public static IEnumerable<EntertainmentLight> GetRight(this IEnumerable<EntertainmentLight> group) => group.Where(x => x.LightLocation.IsRight);
public static IEnumerable<EntertainmentLight> GetFront(this IEnumerable<EntertainmentLight> group) => group.Where(x => x.LightLocation.IsFront);
public static IEnumerable<EntertainmentLight> GetBack(this IEnumerable<EntertainmentLight> group) => group.Where(x => x.LightLocation.IsBack);
public static IEnumerable<EntertainmentLight> GetTop(this IEnumerable<EntertainmentLight> group) => group.Where(x => x.LightLocation.IsTop);
public static IEnumerable<EntertainmentLight> GetBottom(this IEnumerable<EntertainmentLight> group) => group.Where(x => x.LightLocation.IsBottom);
/// <summary>
/// X > -0.1 && X < 0.1
/// </summary>
/// <param name="group"></param>
/// <returns></returns>
public static IEnumerable<EntertainmentLight> GetCenter(this IEnumerable<EntertainmentLight> group) => group.Where(x => x.LightLocation.IsCenter);
/// <summary>
/// Apply the effectFunction repeatedly to a group of lights
/// </summary>
/// <param name="group"></param>
/// <param name="effectFunction"></param>
/// <param name="mode"></param>
/// <param name="waitTime"></param>
/// <param name="duration"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static async Task IteratorEffect(this IEnumerable<EntertainmentLight> group, CancellationToken cancellationToken, IteratorEffectFunc effectFunction, IteratorEffectMode mode, Func<TimeSpan> waitTime, TimeSpan? duration = null, int maxIterations = int.MaxValue)
{
if (waitTime == null)
waitTime = () => TimeSpan.FromSeconds(1);
if (duration == null)
duration = TimeSpan.MaxValue;
bool keepGoing = true;
var lights = group.ToList();
bool reverse = false;
Stopwatch sw = new Stopwatch();
sw.Start();
int i = 0;
while (keepGoing && !cancellationToken.IsCancellationRequested && !(sw.Elapsed > duration) && i < maxIterations)
{
//Apply to whole group if mode is all
if(mode == IteratorEffectMode.All)
{
effectFunction(group, cancellationToken, waitTime());
await Task.Delay(waitTime(), cancellationToken).ConfigureAwait(false);
i++;
continue;
}
if (reverse)
lights.Reverse();
if (mode == IteratorEffectMode.Random || mode == IteratorEffectMode.RandomOrdered)
lights = lights.OrderBy(x => Guid.NewGuid()).ToList();
foreach(var light in lights.Skip(reverse ? 1 : 0))
{
if (!cancellationToken.IsCancellationRequested)
{
effectFunction(new List<EntertainmentLight>() { light }, cancellationToken, waitTime());
if (mode != IteratorEffectMode.AllIndividual)
await Task.Delay(waitTime(), cancellationToken).ConfigureAwait(false);
}
}
if(mode == IteratorEffectMode.AllIndividual)
await Task.Delay(waitTime(), cancellationToken).ConfigureAwait(false);
keepGoing = mode == IteratorEffectMode.Single ? false : true;
if (mode == IteratorEffectMode.Bounce)
reverse = true;
i++;
}
}
/// <summary>
/// Apply the groupFunction repeatedly to a list of groups of lights
/// </summary>
/// <param name="list"></param>
/// <param name="groupFunction"></param>
/// <param name="mode"></param>
/// <param name="waitTime"></param>
/// <param name="duration"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static async Task IteratorEffect(this IEnumerable<IEnumerable<EntertainmentLight>> list, CancellationToken cancellationToken, IteratorEffectFunc groupFunction, IteratorEffectMode mode, IteratorEffectMode secondaryMode, Func<TimeSpan> waitTime, TimeSpan? duration = null, int maxIterations = int.MaxValue)
{
if (waitTime == null)
waitTime = () => TimeSpan.FromSeconds(1);
if (duration == null)
duration = TimeSpan.MaxValue;
int secondaryMaxIterations = 1;
//Normalize secondary iterator mode
switch (secondaryMode)
{
case IteratorEffectMode.Bounce:
secondaryMaxIterations = 2;
break;
case IteratorEffectMode.Cycle:
case IteratorEffectMode.Single:
secondaryMode = IteratorEffectMode.Single;
break;
case IteratorEffectMode.Random:
case IteratorEffectMode.RandomOrdered:
secondaryMode = IteratorEffectMode.RandomOrdered;
break;
case IteratorEffectMode.All:
case IteratorEffectMode.AllIndividual:
default:
break;
}
bool keepGoing = true;
var groups = list.ToList();
bool reverse = false;
if(mode == IteratorEffectMode.RandomOrdered)
groups = groups.OrderBy(x => Guid.NewGuid()).ToList();
Stopwatch sw = new Stopwatch();
sw.Start();
int i = 0;
while (keepGoing && !cancellationToken.IsCancellationRequested && !(sw.Elapsed > duration) && i < maxIterations)
{
//Apply to all groups if mode is all
if (mode == IteratorEffectMode.All)
{
var flatGroup = list.SelectMany(x => x);
if (!cancellationToken.IsCancellationRequested)
groupFunction(flatGroup, cancellationToken, waitTime());
//foreach (var group in list)
//{
// if (!cancellationToken.IsCancellationRequested)
// await groupFunction(group, waitTime);
//}
await Task.Delay(waitTime(), cancellationToken).ConfigureAwait(false);
i++;
continue;
}
if (reverse)
groups.Reverse();
if (mode == IteratorEffectMode.Random)
groups = groups.OrderBy(x => Guid.NewGuid()).ToList();
if (mode == IteratorEffectMode.AllIndividual)
{
List<Task> allIndividualTasks = new List<Task>();
foreach (var group in groups.Skip(reverse ? 1 : 0).Where(x => x.Any()))
{
//Do not await, AllIndividual runs them all at the same time
var t = group.IteratorEffect(cancellationToken, groupFunction, secondaryMode, waitTime, maxIterations: secondaryMaxIterations);
allIndividualTasks.Add(t);
}
await Task.WhenAll(allIndividualTasks).ConfigureAwait(false);
}
else
{
foreach (var group in groups.Skip(reverse ? 1 : 0).Where(x => x.Any()))
{
await group.IteratorEffect(cancellationToken, groupFunction, secondaryMode, waitTime, maxIterations: secondaryMaxIterations).ConfigureAwait(false);
}
}
keepGoing = mode == IteratorEffectMode.Single || mode == IteratorEffectMode.RandomOrdered ? false : true;
if (mode == IteratorEffectMode.Bounce)
reverse = true;
i++;
}
}
/// <summary>
/// Brightness between 0 and 1
/// </summary>
/// <param name="group"></param>
/// <param name="brightness">Between 0 and 1</param>
/// <param name="transitionTime"></param>
/// <param name="inSync">Syncs the transition over all lights. Set to false if each light has a different starting rgb/bri for the transition</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static IEnumerable<EntertainmentLight> SetBrightness(this IEnumerable<EntertainmentLight> group,
CancellationToken cancellationToken,
double brightness, TimeSpan transitionTime = default(TimeSpan), bool inSync = true)
{
group.SetState(cancellationToken, null, brightness, transitionTime, inSync);
return group;
}
/// <summary>
/// Transition to new RGB Color
/// </summary>
/// <param name="group"></param>
/// <param name="rgb"></param>
/// <param name="transitionTime"></param>
/// <param name="inSync">Syncs the transition over all lights. Set to false if each light has a different starting rgb/bri for the transition</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static IEnumerable<EntertainmentLight> SetColor(this IEnumerable<EntertainmentLight> group,
CancellationToken cancellationToken,
RGBColor rgb, TimeSpan transitionTime = default(TimeSpan), bool inSync = true)
{
group.SetState(cancellationToken, rgb, null, transitionTime, inSync);
return group;
}
/// <summary>
///
/// </summary>
/// <param name="group"></param>
/// <param name="rgb"></param>
/// <param name="brightness"></param>
/// <param name="transitionTime"></param>
/// <param name="inSync">Syncs the transition over all lights. Set to false if each light has a different starting rgb/bri for the transition</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static IEnumerable<EntertainmentLight> SetState(this IEnumerable<EntertainmentLight> group,
CancellationToken cancellationToken,
RGBColor? rgb = null, double? brightness = null, TimeSpan transitionTime = default, bool inSync = true)
{
if (!group.Any())
return group;
//Re-use the same transition for all lights so transition is in sync. The transition will use the start rgb/bri from the first light in the group.
if (inSync)
{
//Create a new transition
Transition transition = new Transition(rgb, brightness, transitionTime);
//Add the same transition to all lights in this group
foreach (var light in group)
{
if(!cancellationToken.IsCancellationRequested)
light.Transition = transition;
}
//Start the transition
var firstLight = group.First();
transition.Start(firstLight.State.RGBColor, firstLight.State.Brightness, cancellationToken);
}
else
{
foreach (var light in group)
{
if (!cancellationToken.IsCancellationRequested)
light.SetState(cancellationToken, rgb, brightness, transitionTime);
}
}
return group;
}
public static IEnumerable<EntertainmentLight> SetState(this IEnumerable<EntertainmentLight> group, CancellationToken cancellationToken, RGBColor? rgb = null, TimeSpan rgbTimeSpan = default, double? brightness = null, TimeSpan briTimeSpan = default, bool overwriteExistingTransition = true)
{
if (!group.Any())
return group;
foreach (var light in group)
{
if (!cancellationToken.IsCancellationRequested)
light.SetState(cancellationToken, rgb, rgbTimeSpan, brightness, briTimeSpan, overwriteExistingTransition);
}
return group;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Deedle;
using NUnit.Framework;
using QuantConnect.Algorithm.CSharp;
using QuantConnect.Configuration;
using QuantConnect.Lean.Engine.Results;
using QuantConnect.Logging;
using QuantConnect.Report;
using System;
using System.Collections.Generic;
using System.Linq;
namespace QuantConnect.Tests.Engine.Results
{
[TestFixture]
public class BacktestingResultHandlerTests
{
public BacktestingResultHandler GetResults(string algorithm, DateTime algoStart, DateTime algoEnd)
{
// Required, otherwise LocalObjectStoreTests overwrites the "object-store-root" config value
// and causes the algorithm to error out.
Config.Reset();
var parameter = new RegressionTests.AlgorithmStatisticsTestParameters(algorithm,
new Dictionary<string, string>(),
Language.CSharp,
AlgorithmStatus.Completed);
// The AlgorithmRunner uses the `RegressionResultHandler` but doesn't do any sampling.
// It defaults to the behavior of the `BacktestingResultHandler` class in `results.ProcessSynchronousEvents()`
var backtestResults = AlgorithmRunner.RunLocalBacktest(parameter.Algorithm,
parameter.Statistics,
parameter.AlphaStatistics,
parameter.Language,
parameter.ExpectedFinalStatus,
startDate: algoStart,
endDate: algoEnd);
return backtestResults.Results;
}
[TestCase(nameof(BasicTemplateAlgorithm), true)]
[TestCase(nameof(BasicTemplateDailyAlgorithm), true)]
[TestCase(nameof(ResolutionSwitchingAlgorithm), false)]
public void SamplesNotMisalignedRelative(string algorithm, bool shouldSucceed)
{
// After PR #4003 is merged (https://github.com/QuantConnect/Lean/pull/4003),
// this test will fail with any daily algorithm, such as BasicTemplateDailyAlgorithm.
var backtestResults = GetResults(algorithm, new DateTime(2013, 10, 7), new DateTime(2013, 10, 11));
var benchmarkSeries = backtestResults.Charts["Benchmark"].Series["Benchmark"];
var equitySeries = backtestResults.Charts["Strategy Equity"].Series["Equity"];
var performanceSeries = backtestResults.Charts["Strategy Equity"].Series["Daily Performance"];
var benchmark = ToDeedleSeries(benchmarkSeries);
var equity = ToDeedleSeries(equitySeries);
var performance = ToDeedleSeries(performanceSeries).SelectValues(x => x / 100);
var equityPerformance = equity.ResampleEquivalence(dt => dt.Date, s => s.FirstValue()).PercentChange();
var benchmarkPerformance = benchmark.ResampleEquivalence(dt => dt.Date, s => s.FirstValue()).PercentChange();
performance = performance.ResampleEquivalence(dt => dt.Date, s => s.FirstValue());
// Uncomment the lines below to simulate a (naive) data cleaning attempt.
// Remarks: during the development of PR #3979, this was thought to be a solution for misaligned values.
// however, because the lowest resolution of an algorithm can affect the result of the performance series, we quickly
// discovered that this was not an apt solution. You can view the misalignment with non-daily data
// by uncommenting the lines below. The test should fail on the "diverging values" test for any algorithm that makes use of minutely data.
// However, the test will pass for algorithms that only make use of daily resolution because the benchmark
// is added in daily resolution in 'Engine/DataFeeds/UniverseSelection.cs#L384', which causes the sampling
// of the two series to be aligned with each other (sampling at the previous close, which is 2 days ago w/ daily data vs. yesterday's close w/ non-daily).
// --------------------------------------------------------------
//performanceSeries.Values.RemoveAt(0);
//performanceSeries.Values.RemoveAt(0);
//equityPerformance = equityPerformance.After(equityPerformance.GetKeyAt(1));
//benchmarkPerformance = benchmarkPerformance.After(benchmarkPerformance.GetKeyAt(1));
//---------------------------------------------------------------
//Frame.CreateEmpty<DateTime, string>().Join("equity", equityPerformance).Join("bench", benchmarkPerformance).Join("perf", performance).Print();
// Before 2020-01-10, by uncommenting the line above, it produces this Frame in master for `BasicTemplateDailyAlgorithm`:
// ====================================================================================
// | equity bench perf |
// | 10/7/2013 12:00:00 AM -> <missing> <missing> 0 |
// | 10/8/2013 12:00:00 AM -> 0 -0.00835040609378598 0 |
// | 10/9/2013 12:00:00 AM -> -0.0114689260000001 -0.0117646820298673 -0.01145515 |
// | 10/10/2013 12:00:00 AM -> 0.000602494970229067 0.000604537450206063 0.000601821 |
// | 10/11/2013 12:00:00 AM -> 0.0215322302204622 0.0216210268330373 0.02153223 |
// | 10/12/2013 12:00:00 AM -> 0.0063588373516552 0.00638415728187288 0.006358837 |
// ====================================================================================
//
// And it produces this Frame in master for `BasicTemplateAlgorithm` (minute resolution):
// ====================================================================================
// | equity bench perf |
// | 10/7/2013 12:00:00 AM -> <missing> <missing> 2.69427E-05 |
// | 10/8/2013 12:00:00 AM -> -0.0117197546154655 -0.00835040609378598 -0.01171975 |
// | 10/9/2013 12:00:00 AM -> 0.000602640205305941 -0.0117646820298673 0.0006019659 |
// | 10/10/2013 12:00:00 AM -> 0.0215615143841935 0.000604537450206063 0.02156151 |
// | 10/11/2013 12:00:00 AM -> 0.0063673015777644 0.0216210268330373 0.006367302 |
// | 10/12/2013 12:00:00 AM -> 0 0.00638415728187288 0 |
// ====================================================================================
//
// Note: The `<missing>` values at the start of the "bench" series (10/7/2013 12:00:00 AM) would
// be represented as a `0` due to the `CreateBenchmarkDifferences(...)` method in StatisticsBuilder.
// The `EnsureSameLength(...)` method in StatisticsBuilder pads the result with
// additional zeroes by appending if the length of the two series are not equal, but that is not the case here.
//
// We'll be calculating statistics for the daily algorithm using these two series:
// Bench, Performance
// [[ 0, 0], // Invalid, this is the first time step of the algorithm. No data has been pumped in yet nor have the securities' prices been initialized. This value shouldn't exist.
// [-0.0083504, 0], // Invalid, no data should exist for this day in "Bench" because we don't calculate the percentage change from open to close. This value should exist, but we should drop it for the time being.
// [-0.0117646, -0.0114689],
// [0.00060453, 0.00060249],
// [0.02162102, 0.02153223],
// [0.00638415, 0.00636580]]
//
// If we manually calculate the beta with the series put above, we get the beta: 0.8757695
// If we manually calculate the beta without the invalid values, we get the beta: 0.9892104
TestSampleAlignmentsRelative(equityPerformance, benchmarkPerformance, performance, shouldSucceed);
}
[Test]
public void BasicTemplateAlgorithmSamplesNotMisalignedAbsolute()
{
var backtestResults = GetResults(nameof(BasicTemplateAlgorithm), new DateTime(2013, 10, 7), new DateTime(2013, 10, 11));
var benchmarkSeries = backtestResults.Charts["Benchmark"].Series["Benchmark"];
var equitySeries = backtestResults.Charts["Strategy Equity"].Series["Equity"];
var performanceSeries = backtestResults.Charts["Strategy Equity"].Series["Daily Performance"];
var benchmark = ToDeedleSeries(benchmarkSeries);
var equity = ToDeedleSeries(equitySeries);
var performance = ToDeedleSeries(performanceSeries).SelectValues(x => x / 100);
// Lineup all our samples
// Equity and benchmark will need to be converted into performance values
var equityPerformance = equity.ResampleEquivalence(dt => dt.Date, s => s.FirstValue()).PercentChange();
var benchmarkPerformance = benchmark.PercentChange();
// Before 2020-9-30 on master, the following Frame is created:
// ====================================================================================
// | equity bench perf |
// | 2013-10-07 20:00:00 -> <missing> <missing> -9.20427E-05 |
// | 2013-10-08 00:00:00 -> -0.0116913921108040 -0.0116470501350577 <missing> |
// | 2013-10-08 20:00:00 -> <missing> <missing> -0.01169139 |
// | 2013-10-09 00:00:00 -> 0.000602020218337738 0.000604391026446547 <missing> |
// | 2013-10-09 20:00:00 -> <missing> <missing> 0.0006020202 |
// | 2013-10-10 00:00:00 -> 0.02156944065055612 0.0216814919573348 <missing> |
// | 2013-10-10 20:00:00 -> <missing> <missing> 0.02156944 |
// | 2013-10-11 00:00:00 -> 0.00641960569172269 0.00644312892467460 <missing> |
// | 2013-10-11 20:00:00 -> <missing> <missing> 0.006419605 |
// ===================================================================================|
//
// After new adjustments
// ====================================================================================
// | equity bench perf |
// | 10/7/2013 12:00:00 AM -> <missing> <missing> 0 |
// | 10/8/2013 12:00:00 AM -> -0.0002128590 -0.00870388175321252 -0.0002128589 |
// | 10/9/2013 12:00:00 AM -> -0.0115428009 -0.01158779130093582 -0.0115427999 |
// | 10/10/2013 12:00:00 AM -> 0.00054174422 0.000543757827876358 0.00054174399 |
// | 10/11/2013 12:00:00 AM -> 0.02207915613 0.022165997700413814 0.02207916 |
// | 10/11/2013 08:00:00 PM -> <missing> 0.006263266301918913 0.006239327 | <- Only missing equity because converted to daily values, doesn't have an 8pm point
// ====================================================================================
// Verify Benchmark values
Assert.AreEqual(new DateTime(2013, 10, 8), benchmarkPerformance.DropMissing().FirstKey().Date);
Assert.AreEqual(new DateTime(2013, 10, 11), benchmarkPerformance.LastKey().Date);
Assert.AreEqual(6, benchmarkPerformance.KeyCount);
Assert.AreEqual(5, benchmarkPerformance.ValueCount); // Is 5 because first point is missing
var expectedBenchmarkPerformance = new List<double>
{
0, // First sample at start, seen as missing since percent change won't exists for that day
-0.0087038817532125255, // 10/7 - 10/8
-0.011587791300935823, // 10/8 - 10/9
0.00054375782787635836, // 10/9 - 10/10
0.022165997700413814, // 10/10 - 10/11
0.0062632663019189135 // 10/11 12AM - 10/11 8PM
};
Assert.AreEqual(expectedBenchmarkPerformance, benchmarkPerformance.ValuesAll.ToList());
// Verify Daily Performance values
Assert.AreEqual(new DateTime(2013, 10, 7), performance.FirstKey().Date);
Assert.AreEqual(new DateTime(2013, 10, 11), performance.LastKey().Date);
Assert.AreEqual(6, performance.ValueCount);
Assert.AreEqual(6, performance.KeyCount);
var expectedPerformance = new List<double>
{
0, // First sample at start, zero because no change has occurred yet
-0.0002128589, // 10/7 - 10/8 <- we buy at open here
-0.011542799999999999, // 10/8 - 10/9
0.00054174399999999993, // 10/9 - 10/10
0.02207916, // 10/10 - 10/11
0.006239327 // 10/11 12AM - 10/11 8PM
};
Assert.AreEqual(expectedPerformance, performance.Values.ToList());
// Verify equity performance
Assert.AreEqual(4, equityPerformance.ValueCount);
Assert.AreEqual(new DateTime(2013, 10, 8), equityPerformance.DropMissing().FirstKey());
Assert.AreEqual(new DateTime(2013, 10, 11), equityPerformance.LastKey());
var expectedEquityPerformance = new List<double>
{
0, // First sample at start, seen as missing since percent change won't exists for that day
-0.00021285900000002583, // 10/7 - 10/8 <- we buy at open here
-0.011542800989075775, // 10/8 - 10/9
0.00054174422990819744, // 10/9 - 10/10
0.022079156131712498 // 10/10 - 10/11
};
Assert.AreEqual(expectedEquityPerformance, equityPerformance.ValuesAll.ToList());
}
[Test]
public void BasicTemplateDailyAlgorithmSamplesNotMisalignedAbsolute()
{
// This test will produce incorrect results, but is here to detect if any changes occur to the Sampling.
var backtestResults = GetResults(nameof(BasicTemplateDailyAlgorithm), new DateTime(2013, 10, 7), new DateTime(2013, 10, 11));
var benchmarkSeries = backtestResults.Charts["Benchmark"].Series["Benchmark"];
var equitySeries = backtestResults.Charts["Strategy Equity"].Series["Equity"];
var performanceSeries = backtestResults.Charts["Strategy Equity"].Series["Daily Performance"];
var benchmark = ToDeedleSeries(benchmarkSeries);
var equity = ToDeedleSeries(equitySeries);
var performance = ToDeedleSeries(performanceSeries).SelectValues(x => x / 100);
// Lineup all our samples
// Equity and benchmark will need to be converted into performance values
var equityPerformance = equity.ResampleEquivalence(dt => dt.Date, s => s.FirstValue()).PercentChange();
var benchmarkPerformance = benchmark.PercentChange();
// Before 2020-01-10 on master, the following Frame is created:
// ====================================================================================
// | equity bench perf |
// | 10/7/2013 12:00:00 AM -> <missing> <missing> 0 |
// | 10/8/2013 12:00:00 AM -> 0 -0.00835040609378598 0 |
// | 10/9/2013 12:00:00 AM -> -0.0114689260000001 -0.0117646820298673 -0.01145515 |
// | 10/10/2013 12:00:00 AM -> 0.000602494970229067 0.000604537450206063 0.000601821 |
// | 10/11/2013 12:00:00 AM -> 0.0215322302204622 0.0216210268330373 0.02153223 |
// | 10/12/2013 12:00:00 AM -> 0.0063588373516552 0.00638415728187288 0.006358837 |
// ====================================================================================
//
// Samples were aligned since both benchmark and strategy only use daily data.
Assert.AreEqual(new DateTime(2013, 10, 8), benchmarkPerformance.DropMissing().FirstKey().Date);
Assert.AreEqual(new DateTime(2013, 10, 12), benchmarkPerformance.LastKey().Date);
Assert.AreEqual(6, benchmarkPerformance.KeyCount);
Assert.AreEqual(5, benchmarkPerformance.ValueCount);
var expectedBenchmarkPerformance = new List<double>
{
0, // First sample at start 10/7 12AM, seen as missing since percent change won't exists for that day
-0.0087038817532125255, // 10/7 - 10/8
-0.011587791300935823, // 10/8 - 10/9
0.00054375782787635836, // 10/9 - 10/10
0.022165997700413814, // 10/10 - 10/11
0.0062632663019189135 // 10/11 12AM - 10/11 8PM
};
Assert.AreEqual(expectedBenchmarkPerformance, benchmarkPerformance.ValuesAll.ToList());
// Verify daily performance
Assert.AreEqual(new DateTime(2013, 10, 7), performance.FirstKey().Date);
Assert.AreEqual(new DateTime(2013, 10, 12), performance.LastKey().Date);
Assert.AreEqual(6, performance.ValueCount);
Assert.AreEqual(6, performance.KeyCount);
var expectedPerformance = new List<double>
{
0, // First sample at start 10/7 12AM, zero because no change has occurred yet
0, // 10/7 - 10/8 <- We get first data at 12AM on 10/8
-0.011770290000000001, // 10/8 - 10/9 <- We buy at with OnMarketOpen order
0.0005425408, // 10/9 - 10/10
0.02211161, // 10/10 - 10/11
0.0062483 // 10/11 12AM - 10/11 8PM
};
Assert.AreEqual(expectedPerformance, performance.Values.ToList());
// Verify equity performance
Assert.AreEqual(5, equityPerformance.ValueCount);
Assert.AreEqual(new DateTime(2013, 10, 8), equityPerformance.DropMissing().FirstKey());
Assert.AreEqual(new DateTime(2013, 10, 12), equityPerformance.LastKey());
var expectedEquityPerformance = new List<double>
{
0, // First sample at start 10/7 12AM, seen as missing since percent change won't exists for that day
0, // 10/7 - 10/8 <- We get first data at 12AM on 10/8
-0.011770286000000052, // 10/8 - 10/9 <- We buy at with OnMarketOpen order
0.000542540861101854, // 10/9 - 10/10
0.022111611742941455, // 10/10 - 10/11
0.0062483003408066885 // 10/11 - 10/12
};
Assert.AreEqual(expectedEquityPerformance, equityPerformance.ValuesAll.ToList());
}
[Test]
public void BasicTemplateFrameworkAlgorithmSamplesNotMisalignedAbsolute()
{
var backtestResults = GetResults(nameof(BasicTemplateFrameworkAlgorithm), new DateTime(2013, 10, 7), new DateTime(2013, 10, 11));
var benchmarkSeries = backtestResults.Charts["Benchmark"].Series["Benchmark"];
var equitySeries = backtestResults.Charts["Strategy Equity"].Series["Equity"];
var performanceSeries = backtestResults.Charts["Strategy Equity"].Series["Daily Performance"];
var benchmark = ToDeedleSeries(benchmarkSeries);
var equity = ToDeedleSeries(equitySeries);
var performance = ToDeedleSeries(performanceSeries).SelectValues(x => x / 100);
var equityPerformance = equity.ResampleEquivalence(dt => dt.Date, s => s.FirstValue()).PercentChange();
var benchmarkPerformance = benchmark.PercentChange();
// Before 2020-01-10 on master, the following Frame is created:
// ====================================================================================
// | equity bench perf |
// | 10/7/2013 12:00:00 AM -> <missing> <missing> 2.69427E-05 |
// | 10/8/2013 12:00:00 AM -> -0.012379760 -0.00835040609378598 -0.01237976 |
// | 10/9/2013 12:00:00 AM -> 0.0006023682 -0.0117646820298673 0.0006023682 |
// | 10/10/2013 12:00:00 AM -> 0.0215518000 0.000604537450206063 0.02155180 |
// | 10/11/2013 12:00:00 AM -> 0.0063644940 0.0216210268330373 0.006364494 |
// | 10/12/2013 12:00:00 AM -> 0 0.00638415728187288 0 |
// ====================================================================================
//
// Since benchmark is set at daily resolution, the benchmark data gets shifted forward by one day, causing misalignment.
// Verify benchmark performance
Assert.AreEqual(new DateTime(2013, 10, 8), benchmarkPerformance.DropMissing().FirstKey().Date);
Assert.AreEqual(new DateTime(2013, 10, 11), benchmarkPerformance.LastKey().Date);
Assert.AreEqual(6, benchmarkPerformance.KeyCount);
Assert.AreEqual(5, benchmarkPerformance.ValueCount);
var expectedBenchmarkPerformance = new List<double>
{
0, // First sample at start 10/7 12AM, seen as missing since percent change won't exists for that day
-0.0087038817532125255, // 10/7 - 10/8
-0.011587791300935823, // 10/8 - 10/9
0.00054375782787635836, // 10/9 - 10/10
0.022165997700413814, // 10/10 - 10/11
0.0062632663019189135 // 10/11 12AM - 10/11 8PM
};
Assert.AreEqual(expectedBenchmarkPerformance, benchmarkPerformance.ValuesAll.ToList());
// Verify daily performance
Assert.AreEqual(new DateTime(2013, 10, 7), performance.FirstKey().Date);
Assert.AreEqual(new DateTime(2013, 10, 11), performance.LastKey().Date);
Assert.AreEqual(6, performance.ValueCount);
Assert.AreEqual(6, performance.KeyCount);
var expectedPerformance = new List<double>
{
0, // First sample at start, zero because no change has occurred yet
-0.0002128589, // 10/7 - 10/8 <- we buy at open here
-0.01190911, // 10/8 - 10/9
0.0005419449, // 10/9 - 10/10
0.02208734, // 10/10 - 10/11
0.006241589 // 10/11 12AM - 10/11 8PM
};
Assert.AreEqual(expectedPerformance, performance.Values.ToList());
// Verify equity performance
Assert.AreEqual(4, equityPerformance.ValueCount);
Assert.AreEqual(new DateTime(2013, 10, 8), equityPerformance.DropMissing().FirstKey());
Assert.AreEqual(new DateTime(2013, 10, 11), equityPerformance.LastKey());
var expectedEquityPerformance = new List<double>
{
0, // First sample at start, seen as missing since percent change won't exists for that day
-0.00021285900000002583, // 10/7 - 10/8 <- we buy at open here
-0.011909110961450057, // 10/8 - 10/9
0.00054194506802551345, // 10/9 - 10/10
0.022087336992789988 // 10/10 - 10/11
};
Assert.AreEqual(expectedEquityPerformance, equityPerformance.ValuesAll.ToList());
}
[Test]
public void ResolutionSwitchingAlgorithmSamplesNotMisalignedAbsolute()
{
// This test will produce incorrect results, but is here to detect if any changes occur to the Sampling.
var backtestResults = GetResults(nameof(ResolutionSwitchingAlgorithm), new DateTime(2013, 10, 7), new DateTime(2013, 10, 11));
var benchmarkSeries = backtestResults.Charts["Benchmark"].Series["Benchmark"];
var equitySeries = backtestResults.Charts["Strategy Equity"].Series["Equity"];
var performanceSeries = backtestResults.Charts["Strategy Equity"].Series["Daily Performance"];
var benchmark = ToDeedleSeries(benchmarkSeries);
var equity = ToDeedleSeries(equitySeries);
var performance = ToDeedleSeries(performanceSeries).SelectValues(x => x / 100);
var equityPerformance = equity.ResampleEquivalence(dt => dt.Date, s => s.FirstValue()).PercentChange();
var benchmarkPerformance = benchmark.PercentChange();
// Before 2020-01-10, the following Frame is created:
// ==================================================================================
// | equity bench perf |
// | 10/7/2013 12:00:00 AM -> <missing> <missing> 0 |
// | 10/8/2013 12:00:00 AM -> 0 -0.00835040609378598 0 |
// | 10/9/2013 12:00:00 AM -> -0.0114877029999999 -0.0117646820298673 -0.0114877 |
// | 10/10/2013 12:00:00 AM -> 0.0111613132728369 0.000604537450206063 0.01116131 | <- (perf): This is the date we changed to minutely data.
// | 10/11/2013 12:00:00 AM -> 0.00642813429004656 0.0216210268330373 0.006428134 | <- If we were still using daily data, this value would be here: |
// | 10/12/2013 12:00:00 AM -> 0 0.00638415728187288 0 | <----------------------------------------------------------------
// ==================================================================================
//
// On 2013-10-10, we switch from Daily Resolution to Minute. From here onwards, our performance values
// are shifted backwards by 1 with the exception of the value on 10/10/2013 12:00:00 AM.
Frame.CreateEmpty<DateTime, string>().Join("equity", equityPerformance).Join("bench", benchmarkPerformance).Join("perf", performance).Print();
// Verify benchmark performance
Assert.AreEqual(new DateTime(2013, 10, 8), benchmarkPerformance.DropMissing().FirstKey().Date);
Assert.AreEqual(new DateTime(2013, 10, 11), benchmarkPerformance.LastKey().Date);
Assert.AreEqual(6, benchmarkPerformance.KeyCount);
Assert.AreEqual(5, benchmarkPerformance.ValueCount);
var expectedBenchmarkPerformance = new List<double>
{
0, // First sample at start 10/7 12AM, seen as missing since percent change won't exists for that day
-0.0087038817532125255, // 10/7 - 10/8
-0.011587791300935823, // 10/8 - 10/9
0.00054375782787635836, // 10/9 - 10/10
0.022165997700413814, // 10/10 - 10/11
0.0062632663019189135 // 10/11 12AM - 10/11 8PM
};
Assert.AreEqual(expectedBenchmarkPerformance, benchmarkPerformance.ValuesAll.ToList());
// Verify daily performance
Assert.AreEqual(new DateTime(2013, 10, 7), performance.FirstKey().Date);
Assert.AreEqual(new DateTime(2013, 10, 11), performance.LastKey().Date);
Assert.AreEqual(6, performance.ValueCount);
Assert.AreEqual(6, performance.KeyCount);
var expectedPerformance = new List<double>
{
0, // First sample at start 10/7 12AM, zero because no change has occurred yet
0, // 10/7 - 10/8 <- We get first data at 12AM on 10/8
-0.01112113, // 10/8 - 10/9 <- We buy at with OnMarketOpen order
-3.291606E-05, // 10/9 - 10/10
0.01100997, // 10/10 - 10/11
0.005968033 // 10/11 12AM - 10/11 8PM
};
Assert.AreEqual(expectedPerformance, performance.Values.ToList());
// Verify equity performance
Assert.AreEqual(4, equityPerformance.ValueCount);
Assert.AreEqual(new DateTime(2013, 10, 8), equityPerformance.DropMissing().FirstKey().Date);
Assert.AreEqual(new DateTime(2013, 10, 11), equityPerformance.LastKey().Date);
var expectedEquityPerformance = new List<double>
{
0, // First sample at start 10/7 12AM, seen as missing since percent change won't exists for that day
0, // 10/7 - 10/8 <- We get first data at 12AM on 10/8
-0.011121126999999979, // 10/8 - 10/9 <- We buy at with OnMarketOpen order
-3.29160637250732E-05, // 10/9 - 10/10
0.011009966611364035, // 10/10 - 10/11
};
Assert.AreEqual(expectedEquityPerformance, equityPerformance.ValuesAll.ToList());
}
private void TestSampleAlignmentsRelative(
Series<DateTime, double> equityPerformance,
Series<DateTime, double> benchmarkPerformance,
Series<DateTime, double> performance,
bool shouldSucceed)
{
// Fill our missing values before comparing
equityPerformance = equityPerformance.FillMissing(0.0d);
benchmarkPerformance = benchmarkPerformance.FillMissing(0.0d);
performance = performance.FillMissing(0.0d);
var equityPerformanceContainsExpectedCount = equityPerformance.ValueCount == performance.ValueCount;
var equityPerformanceContainsExpectedCountMessage = "Calculated equity performance series or performance series contains more values than expected";
var equityPerformanceMatchesPerformance = equityPerformance.Values.Select(x => Math.Round(x, 5)).ToList().SequenceEqual(performance.Values.Select(x => Math.Round(x, 5)).ToList());
var equityPerformanceMatchesPerformanceMessage = "Calculated equity performance value does not match performance series value. This most likely means that the performance series has been sampled more than it should have and is misaligned as a result.";
var benchmarkPerformanceAndPerformanceAreAligned = benchmarkPerformance.ValueCount == performance.ValueCount;
var benchmarkPerformanceAndPerformanceAreAlignedMessage = "Performance and benchmark performance series are misaligned";
// Skip the first 3 because [1] = start of algorithm samples always 0, [2] = first data comes in during this first day, we place our orders for open
var benchmarkPerformanceAndPerformanceDoNotDiverge = (performance - benchmarkPerformance).Values.Skip(2).All(x => x <= 0.0005 && x >= -0.0005);
var benchmarkPerformanceAndPerformanceDoNotDivergeMessage = "Equity performance and benchmark performance have diverging values. This most likely means that the performance and calculated benchmark performance series are misaligned.";
if (!shouldSucceed)
{
// All tests are passing, though we aren't expecting that.
if (equityPerformanceContainsExpectedCount && equityPerformanceMatchesPerformance &&
benchmarkPerformanceAndPerformanceAreAligned && benchmarkPerformanceAndPerformanceDoNotDiverge)
{
Assert.Fail("All checks are passing on a test that should be failing.");
}
if (!equityPerformanceContainsExpectedCount)
{
Log.Trace($"TestSampleAlignmentsRelative(): Test failed, but it was expected. Message: {equityPerformanceContainsExpectedCountMessage}");
}
if (!equityPerformanceMatchesPerformance)
{
Log.Trace($"TestSampleAlignmentsRelative(): Test failed, but it was expected. Message: {equityPerformanceMatchesPerformanceMessage}");
}
if (!benchmarkPerformanceAndPerformanceAreAligned)
{
Log.Trace($"TestSampleAlignmentsRelative(): Test failed, but it was expected. Message: {benchmarkPerformanceAndPerformanceAreAlignedMessage}");
}
if (!benchmarkPerformanceAndPerformanceDoNotDiverge)
{
Log.Trace($"TestSampleAlignmentsRelative(): Test failed, but it was expected. Message: {benchmarkPerformanceAndPerformanceDoNotDivergeMessage}");
}
return;
}
Assert.IsTrue(equityPerformanceContainsExpectedCount, equityPerformanceContainsExpectedCountMessage);
Assert.IsTrue(equityPerformanceMatchesPerformance, equityPerformanceMatchesPerformanceMessage);
Assert.IsTrue(benchmarkPerformanceAndPerformanceAreAligned, benchmarkPerformanceAndPerformanceAreAlignedMessage);
Assert.IsTrue(benchmarkPerformanceAndPerformanceDoNotDiverge, benchmarkPerformanceAndPerformanceDoNotDivergeMessage);
}
private static Series<DateTime, double> ToDeedleSeries(Series series)
{
return new Series<DateTime, double>(series.Values.Select(x => new KeyValuePair<DateTime, double>(Time.UnixTimeStampToDateTime(x.x), (double)x.y)));
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
using Microsoft.Build.Construction;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Logging;
using Microsoft.PythonTools.BuildTasks;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Navigation;
using Microsoft.PythonTools.Repl;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudioTools.Project;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.PythonTools.Project {
sealed class CustomCommand : IAsyncCommand, IDisposable {
private readonly PythonProjectNode _project;
private readonly string _target;
private readonly string _label;
private readonly ErrorListProvider _errorListProvider;
private bool _isDisposed, _canExecute;
internal readonly string Verb;
internal readonly uint AlternateCmdId;
public const string ReplId = "2E918F01-ABA9-41A6-8345-5189FB4B5ABF";
public const string PythonCommands = "PythonCommands";
private static readonly Regex _customCommandLabelRegex = new Regex(
@"resource\:
(?<assembly>.+?);
(?<namespace>.+?);
(?<key>.+)
$",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace
);
private CustomCommand(
PythonProjectNode project,
string target,
string label
) {
_project = project;
_target = target;
_label = string.IsNullOrWhiteSpace(label) ? target : label;
var match = _customCommandLabelRegex.Match(label);
if (match.Success) {
DisplayLabel = LoadResourceFromAssembly(
match.Groups["assembly"].Value,
match.Groups["namespace"].Value,
match.Groups["key"].Value
);
} else {
DisplayLabel = _label;
}
DisplayLabel = PerformSubstitutions(project, DisplayLabel);
_canExecute = !string.IsNullOrEmpty(target);
Verb = "Project." + Regex.Replace(
DisplayLabelWithoutAccessKeys,
"[^a-z0-9]+",
"",
RegexOptions.CultureInvariant | RegexOptions.IgnoreCase
);
AlternateCmdId = AddNamedCommand(project.Site, Verb);
_errorListProvider = new ErrorListProvider(_project.Site);
}
public void Dispose() {
if (!_isDisposed) {
_isDisposed = true;
if (!string.IsNullOrEmpty(Verb) && AlternateCmdId > 0) {
RemoveNamedCommand(ServiceProvider.GlobalProvider, Verb);
}
if (_errorListProvider != null) {
_errorListProvider.Dispose();
}
}
}
private static uint AddNamedCommand(IServiceProvider provider, string name, string tooltipText = null) {
var commands = provider.GetService(typeof(SVsProfferCommands)) as IVsProfferCommands3;
if (commands == null) {
return 0;
}
var package = typeof(PythonToolsPackage).GUID;
var cmdSet = GuidList.guidPythonToolsCmdSet;
uint cmdId;
ErrorHandler.ThrowOnFailure(commands.AddNamedCommand(
ref package,
ref cmdSet,
name,
out cmdId,
name,
name,
tooltipText,
null, 0, 0, // no image, image id or image index
0, // default flags
0, new Guid[0] // new [] { VSConstants.UICONTEXT.SolutionExists_guid }
));
return cmdId;
}
private static void RemoveNamedCommand(IServiceProvider provider, string name) {
var commands = provider.GetService(typeof(SVsProfferCommands)) as IVsProfferCommands3;
if (commands != null) {
ErrorHandler.ThrowOnFailure(commands.RemoveNamedCommand(name));
}
}
private static string PerformSubstitutions(IPythonProject project, string label) {
return Regex.Replace(label, @"\{(?<key>\w+)\}", m => {
var key = m.Groups["key"].Value;
if ("projectname".Equals(key, StringComparison.InvariantCultureIgnoreCase)) {
return Path.ChangeExtension(project.ProjectFile, null);
} else if ("projectfile".Equals(key, StringComparison.InvariantCultureIgnoreCase)) {
return project.ProjectFile;
}
var instance = project.GetMSBuildProjectInstance();
if (instance != null) {
var value = instance.GetPropertyValue(key);
if (!string.IsNullOrEmpty(value)) {
return value;
}
}
return m.Value;
});
}
private static string LoadResourceFromAssembly(string assembly, string ns, string key) {
try {
var asmName = new System.Reflection.AssemblyName(assembly);
System.Reflection.Assembly asm = null;
if (asmName.FullName == asmName.Name) {
// A partial name was provided. If there is an assembly with
// matching name in the current AppDomain, assume that is
// the intended one.
asm = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => assembly == a.GetName().Name);
}
asm = asm ?? System.Reflection.Assembly.Load(asmName);
var rm = new System.Resources.ResourceManager(ns, asm);
return rm.GetString(key, CultureInfo.CurrentUICulture) ?? key;
} catch (Exception ex) {
ActivityLog.LogError(Strings.ProductTitle, Strings.FailedToReadResource.FormatUI(assembly, ns, key, ex));
return key;
}
}
public static IEnumerable<CustomCommand> GetCommands(
Microsoft.Build.Evaluation.Project project,
PythonProjectNode projectNode
) {
var commandNames = project.GetPropertyValue(PythonCommands);
if (!string.IsNullOrEmpty(commandNames)) {
foreach (var name in commandNames.Split(';').Select(s => s.Trim()).Where(n => !string.IsNullOrEmpty(n)).Distinct()) {
ProjectTargetInstance targetInstance;
if (!project.Targets.TryGetValue(name, out targetInstance)) {
continue;
}
var targetXml = (targetInstance.Location.File == project.FullPath) ?
project.Xml :
// TryOpen will only return targets that were already
// loaded in the current collection; otherwise, null.
ProjectRootElement.TryOpen(targetInstance.Location.File, project.ProjectCollection);
if (targetXml == null) {
continue;
}
var target = targetXml.Targets.FirstOrDefault(t => name.Equals(t.Name, StringComparison.OrdinalIgnoreCase));
if (target != null) {
yield return new CustomCommand(projectNode, target.Name, target.Label);
}
}
}
}
public static string GetCommandsDisplayLabel(
Microsoft.Build.Evaluation.Project project,
IPythonProject projectNode
) {
var label = project.GetPropertyValue("PythonCommandsDisplayLabel") ?? string.Empty;
var match = _customCommandLabelRegex.Match(label);
if (match.Success) {
label = LoadResourceFromAssembly(
match.Groups["assembly"].Value,
match.Groups["namespace"].Value,
match.Groups["key"].Value
);
}
if (string.IsNullOrEmpty(label)) {
return Strings.PythonMenuLabel;
}
return PerformSubstitutions(projectNode, label);
}
public string Target { get { return _target; } }
public string Label { get { return _label; } }
public string DisplayLabel { get; private set; }
public string DisplayLabelWithoutAccessKeys {
get {
// Changes "My &Command" into "My Command" while ensuring that
// "C1 && C2" becomes "C1 & C2"
return Regex.Replace(DisplayLabel, "&(.)", "$1");
}
}
public bool CanExecute(object parameter) {
if (!_canExecute) {
return false;
}
return parameter == null ||
parameter is IPythonProject;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter) {
var task = ExecuteAsync(parameter);
var nestedFrame = new DispatcherFrame();
task.ContinueWith(_ => nestedFrame.Continue = false);
Dispatcher.PushFrame(nestedFrame);
task.Wait();
}
public Task ExecuteAsync(object parameter) {
var task = ExecuteWorker((parameter as PythonProjectNode) ?? _project);
// Ensure the exception is observed.
// The caller can check task.Exception to do their own reporting.
task.ContinueWith(t => {
try {
t.Wait();
} catch (AggregateException ex) {
var exception = ex.InnerException;
if (exception is NoInterpretersException ||
exception is MissingInterpreterException ||
exception is TaskCanceledException) {
// No need to log this exception or disable the command.
return;
}
// Prevent the command from executing again until the project is
// reloaded.
_canExecute = false;
var evt = CanExecuteChanged;
if (evt != null) {
evt(this, EventArgs.Empty);
}
// Log error to the ActivityLog.
ActivityLog.LogError(Strings.ProductTitle, Strings.ErrorRunningCustomCommand.FormatUI(_target, ex));
}
});
return task;
}
private class ErrorListRedirector : Redirector {
private const string
MessageGroupKey = "message",
CodeGroupKey = "code",
FileNameGroupKey = "filename",
LineGroupKey = "line",
ColumnGroupKey = "column";
private readonly IVsHierarchy _hierarchy;
private readonly string _workingDirectory;
private readonly ErrorListProvider _errorListProvider;
private readonly Regex _errorRegex, _warningRegex;
private readonly IServiceProvider _serviceProvider;
public ErrorListRedirector(IServiceProvider serviceProvider, IVsHierarchy hierarchy, string workingDirectory, ErrorListProvider errorListProvider, Regex errorRegex, Regex warningRegex) {
_serviceProvider = serviceProvider;
_hierarchy = hierarchy;
_workingDirectory = workingDirectory;
_errorListProvider = errorListProvider;
_errorRegex = errorRegex;
_warningRegex = warningRegex;
}
public override void WriteErrorLine(string s) {
WriteLine(s);
}
public override void WriteLine(string s) {
var errorCategory = TaskErrorCategory.Error;
foreach (var regex in new[] { _errorRegex, _warningRegex }) {
if (regex != null) {
var m = regex.Match(s);
if (m.Success) {
int line, column;
int.TryParse(m.Groups[LineGroupKey].ToString(), out line);
int.TryParse(m.Groups[ColumnGroupKey].ToString(), out column);
string document = m.Groups[FileNameGroupKey].ToString();
var task = new ErrorTask {
Document = document,
HierarchyItem = _hierarchy,
Line = line - 1,
Column = column - 1,
ErrorCategory = errorCategory,
Text = m.Groups[MessageGroupKey].ToString()
};
task.Navigate += OnNavigate;
_errorListProvider.Tasks.Add(task);
}
}
errorCategory = TaskErrorCategory.Warning;
}
}
public override void Show() {
_errorListProvider.Show();
}
public override void ShowAndActivate() {
_errorListProvider.Show();
_errorListProvider.BringToFront();
}
private void OnNavigate(object sender, EventArgs e) {
var task = sender as ErrorTask;
if (task != null) {
string document;
try {
document = PathUtils.GetAbsoluteFilePath(_workingDirectory, task.Document);
} catch (ArgumentException) {
// If it's not a valid path, then it's not a navigable error item.
return;
}
PythonToolsPackage.NavigateTo(_serviceProvider, document, Guid.Empty, task.Line, task.Column < 0 ? 0 : task.Column);
}
}
}
private async Task ExecuteWorker(PythonProjectNode project) {
_errorListProvider.Tasks.Clear();
var interpFactory = project.GetInterpreterFactoryOrThrow();
var startInfo = GetStartInfo(project);
var packagesToInstall = new List<string>();
var pm = interpFactory.PackageManager;
if (pm != null) {
foreach (var pkg in startInfo.RequiredPackages) {
if (!(await pm.GetInstalledPackageAsync(new PackageSpec(pkg), CancellationToken.None)).IsValid) {
packagesToInstall.Add(pkg);
}
}
}
if (packagesToInstall.Any()) {
var installMissingButton = new TaskDialogButton(
Strings.CustomCommandPrerequisitesInstallMissing,
Strings.CustomCommandPrerequisitesInstallMissingSubtext + "\r\n\r\n" + string.Join("\r\n", packagesToInstall));
var runAnywayButton = new TaskDialogButton(Strings.CustomCommandPrerequisitesRunAnyway);
var doNotRunButton = new TaskDialogButton(Strings.CustomCommandPrerequisitesDoNotRun);
var taskDialog = new TaskDialog(project.Site) {
Title = Strings.ProductTitle,
MainInstruction = Strings.CustomCommandPrerequisitesInstruction,
Content = Strings.CustomCommandPrerequisitesContent.FormatUI(DisplayLabelWithoutAccessKeys),
AllowCancellation = true,
Buttons = { installMissingButton, runAnywayButton, doNotRunButton, TaskDialogButton.Cancel }
};
var selectedButton = taskDialog.ShowModal();
if (selectedButton == installMissingButton) {
var ui = new VsPackageManagerUI(project.Site);
if (!pm.IsReady) {
await pm.PrepareAsync(ui, CancellationToken.None);
}
await pm.InstallAsync(PackageSpec.FromArguments(string.Join(" ", packagesToInstall)), ui, CancellationToken.None);
} else if (selectedButton == runAnywayButton) {
} else {
throw new TaskCanceledException();
}
}
if (startInfo.TargetType == PythonCommandTask.TargetTypePip) {
if (startInfo.ExecuteInOutput && pm != null) {
var ui = new VsPackageManagerUI(project.Site);
if (!pm.IsReady) {
await pm.PrepareAsync(ui, CancellationToken.None);
}
await pm.InstallAsync(
PackageSpec.FromArguments(string.IsNullOrEmpty(startInfo.Arguments) ? startInfo.Filename : "{0} {1}".FormatUI(startInfo.Filename, startInfo.Arguments)),
ui,
CancellationToken.None
);
return;
}
// Rewrite start info to execute
startInfo.TargetType = PythonCommandTask.TargetTypeModule;
startInfo.AddArgumentAtStart(startInfo.Filename);
startInfo.Filename = "pip";
}
if (startInfo.ExecuteInRepl) {
if (await RunInRepl(project, startInfo)) {
return;
}
}
startInfo.AdjustArgumentsForProcessStartInfo(GetInterpreterPath(project, false));
if (startInfo.ExecuteInOutput) {
RunInOutput(project, startInfo);
} else {
RunInConsole(project, startInfo);
}
}
#if DEBUG
class TraceLogger : Microsoft.Build.Logging.ConsoleLogger {
public TraceLogger()
: base(Build.Framework.LoggerVerbosity.Detailed) {
WriteHandler = s => Debug.Write(s);
}
}
#endif
class StringLogger : Microsoft.Build.Logging.ConsoleLogger {
public readonly List<string> Lines = new List<string>();
public StringLogger()
: base(Build.Framework.LoggerVerbosity.Normal) {
WriteHandler = Lines.Add;
}
}
internal static IDictionary<string, TargetResult> BuildTarget(IPythonProject project, string target) {
var config = project.GetMSBuildProjectInstance();
if (config == null) {
throw new ArgumentException("Project does not support MSBuild", "project");
}
IDictionary<string, TargetResult> outputs;
var logger = new StringLogger();
#if DEBUG
var loggers = new ILogger[] { new TraceLogger(), logger };
#else
var loggers = new ILogger[] { logger };
#endif
if (!config.Build(new[] { target }, loggers, Enumerable.Empty<ForwardingLoggerRecord>(), out outputs)) {
var outputWindow = OutputWindowRedirector.Get(
project.Site,
VSConstants.OutputWindowPaneGuid.BuildOutputPane_guid,
"Build"
);
outputWindow.WriteErrorLine(Strings.ErrorBuildingCustomCommand.FormatUI(target));
foreach (var line in logger.Lines) {
outputWindow.WriteErrorLine(line.TrimEnd('\r', '\n'));
}
throw new InvalidOperationException(Strings.ErrorBuildingCustomCommand.FormatUI(target));
}
return outputs;
}
public CommandStartInfo GetStartInfo(IPythonProject project) {
var outputs = BuildTarget(project, _target);
var config = project.GetLaunchConfigurationOrThrow();
var item = outputs.Values
.SelectMany(result => result.Items)
.FirstOrDefault(i =>
!string.IsNullOrEmpty(i.ItemSpec) &&
!string.IsNullOrEmpty(i.GetMetadata(CreatePythonCommandItem.TargetTypeKey))
);
if (item == null) {
throw new InvalidOperationException(Strings.ErrorBuildingCustomCommand.FormatUI(_target));
}
var startInfo = new CommandStartInfo(config.Interpreter) {
Filename = item.ItemSpec,
Arguments = item.GetMetadata(CreatePythonCommandItem.ArgumentsKey),
WorkingDirectory = item.GetMetadata(CreatePythonCommandItem.WorkingDirectoryKey),
TargetType = item.GetMetadata(CreatePythonCommandItem.TargetTypeKey),
ExecuteIn = item.GetMetadata(CreatePythonCommandItem.ExecuteInKey),
RequiredPackages = item.GetMetadata(CreatePythonCommandItem.RequiredPackagesKey).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
};
var pathVar = config.Interpreter.PathEnvironmentVariable;
var env = new Dictionary<string, string> {
{ pathVar, PathUtils.JoinPathList(config.SearchPaths) }
};
startInfo.EnvironmentVariables = PathUtils.MergeEnvironments(
PathUtils.MergeEnvironments(env, config.Environment, pathVar),
PathUtils.ParseEnvironment(item.GetMetadata(CreatePythonCommandItem.EnvironmentKey)),
"Path", config.Interpreter.PathEnvironmentVariable
);
try {
startInfo.WorkingDirectory = PathUtils.GetAbsoluteFilePath(project.ProjectHome, startInfo.WorkingDirectory);
} catch (ArgumentException) {
}
string errorRegex = item.GetMetadata(CreatePythonCommandItem.ErrorRegexKey);
if (!string.IsNullOrEmpty(errorRegex)) {
startInfo.ErrorRegex = new Regex(errorRegex);
}
string warningRegex = item.GetMetadata(CreatePythonCommandItem.WarningRegexKey);
if (!string.IsNullOrEmpty(warningRegex)) {
startInfo.WarningRegex = new Regex(warningRegex);
}
startInfo.EnvironmentVariables["PYTHONUNBUFFERED"] = "1";
Debug.Assert(!string.IsNullOrEmpty(startInfo.WorkingDirectory));
Debug.Assert(Path.IsPathRooted(startInfo.WorkingDirectory));
return startInfo;
}
internal static string GetInterpreterPath(PythonProjectNode project, bool isWindows) {
var factory = project.GetInterpreterFactoryOrThrow();
return isWindows ?
factory.Configuration.WindowsInterpreterPath :
factory.Configuration.InterpreterPath;
}
private async Task<bool> RunInRepl(IPythonProject project, CommandStartInfo startInfo) {
var executeIn = string.IsNullOrEmpty(startInfo.ExecuteIn) ? CreatePythonCommandItem.ExecuteInRepl : startInfo.ExecuteIn;
bool resetRepl = executeIn.StartsWith("R", StringComparison.InvariantCulture);
var replTitle = executeIn.Substring(4).TrimStart(' ', ':');
if (string.IsNullOrEmpty(replTitle)) {
replTitle = Strings.CustomCommandReplTitle.FormatUI(DisplayLabelWithoutAccessKeys);
} else {
var match = _customCommandLabelRegex.Match(replTitle);
if (match.Success) {
replTitle = LoadResourceFromAssembly(
match.Groups["assembly"].Value,
match.Groups["namespace"].Value,
match.Groups["key"].Value
);
}
}
replTitle = PerformSubstitutions(project, replTitle);
var replWindowId = PythonReplEvaluatorProvider.GetTemporaryId(
ReplId + executeIn.Substring(4),
_project.GetInterpreterFactory().Configuration
);
var model = _project.Site.GetComponentModel();
var replProvider = model.GetService<InteractiveWindowProvider>();
if (replProvider == null) {
return false;
}
bool created;
var replWindow = replProvider.OpenOrCreateTemporary(replWindowId, replTitle, out created);
// TODO: Find alternative way of closing repl window on Dev15
var replFrame = (replWindow as ToolWindowPane)?.Frame as IVsWindowFrame;
var interactive = replWindow.InteractiveWindow;
var pyEvaluator = replWindow.InteractiveWindow.Evaluator as PythonInteractiveEvaluator;
if (pyEvaluator == null) {
if (created && replFrame != null) {
// We created the window, but it isn't valid, so we'll close
// it again immediately.
replFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);
}
return false;
}
if (pyEvaluator.IsExecuting) {
throw new InvalidOperationException(Strings.ErrorCommandAlreadyRunning);
}
pyEvaluator.ProjectMoniker = _project.GetMkDocument();
pyEvaluator.Configuration = new LaunchConfiguration(startInfo.Interpreter) {
WorkingDirectory = startInfo.WorkingDirectory,
Environment = startInfo.EnvironmentVariables.ToDictionary(kv => kv.Key, kv => kv.Value)
};
project.AddActionOnClose((object)replWindow, InteractiveWindowProvider.Close);
replWindow.Show(true);
var result = await pyEvaluator.ResetAsync(false, quiet: true);
if (result.IsSuccessful) {
try {
var filename = startInfo.Filename;
var arguments = startInfo.Arguments ?? string.Empty;
if (startInfo.IsScript) {
interactive.WriteLine(string.Format("Executing {0} {1}", Path.GetFileName(filename), arguments));
Debug.WriteLine("Executing {0} {1}", filename, arguments);
await pyEvaluator.ExecuteFileAsync(filename, arguments);
} else if (startInfo.IsModule) {
interactive.WriteLine(string.Format("Executing -m {0} {1}", filename, arguments));
Debug.WriteLine("Executing -m {0} {1}", filename, arguments);
await pyEvaluator.ExecuteModuleAsync(filename, arguments);
} else if (startInfo.IsCode) {
Debug.WriteLine("Executing -c \"{0}\"", filename, arguments);
await pyEvaluator.ExecuteCodeAsync(filename);
} else {
interactive.WriteLine(string.Format("Executing {0} {1}", Path.GetFileName(filename), arguments));
Debug.WriteLine("Executing {0} {1}", filename, arguments);
await pyEvaluator.ExecuteProcessAsync(filename, arguments);
}
if (resetRepl) {
// We really close the backend, rather than resetting.
pyEvaluator.Dispose();
}
} catch (Exception ex) {
ActivityLog.LogError(Strings.ProductTitle, Strings.ErrorRunningCustomCommand.FormatUI(_label, ex));
var outWindow = OutputWindowRedirector.GetGeneral(project.Site);
if (outWindow != null) {
outWindow.WriteErrorLine(Strings.ErrorRunningCustomCommand.FormatUI(_label, ex));
outWindow.Show();
}
}
return true;
}
return false;
}
private async void RunInOutput(IPythonProject project, CommandStartInfo startInfo) {
Redirector redirector = OutputWindowRedirector.GetGeneral(project.Site);
if (startInfo.ErrorRegex != null || startInfo.WarningRegex != null) {
redirector = new TeeRedirector(redirector, new ErrorListRedirector(_project.Site, project as IVsHierarchy, startInfo.WorkingDirectory, _errorListProvider, startInfo.ErrorRegex, startInfo.WarningRegex));
}
redirector.ShowAndActivate();
using (var process = ProcessOutput.Run(
startInfo.Filename,
new[] { startInfo.Arguments },
startInfo.WorkingDirectory,
startInfo.EnvironmentVariables,
false,
redirector,
quoteArgs: false
)) {
await process;
}
}
private async void RunInConsole(IPythonProject project, CommandStartInfo startInfo) {
using (var process = ProcessOutput.Run(
startInfo.Filename,
new[] { startInfo.Arguments },
startInfo.WorkingDirectory,
startInfo.EnvironmentVariables,
true,
null,
quoteArgs: false
)) {
await process;
}
}
}
class CommandStartInfo {
public readonly InterpreterConfiguration Interpreter;
public string Filename;
public string Arguments;
public string WorkingDirectory;
public IDictionary<string, string> EnvironmentVariables;
public string ExecuteIn;
public string TargetType;
public Regex ErrorRegex, WarningRegex;
public string[] RequiredPackages;
public CommandStartInfo(InterpreterConfiguration interpreter) {
Interpreter = interpreter;
}
public void AddArgumentAtStart(string argument) {
if (string.IsNullOrEmpty(Arguments)) {
Arguments = ProcessOutput.QuoteSingleArgument(argument);
} else {
Arguments = ProcessOutput.QuoteSingleArgument(argument) + " " + Arguments;
}
}
public void AddArgumentAtEnd(string argument) {
if (string.IsNullOrEmpty(Arguments)) {
Arguments = ProcessOutput.QuoteSingleArgument(argument);
} else {
Arguments += " " + ProcessOutput.QuoteSingleArgument(argument);
}
}
public bool ExecuteInRepl {
get {
return !string.IsNullOrEmpty(ExecuteIn) &&
ExecuteIn.StartsWith(CreatePythonCommandItem.ExecuteInRepl, StringComparison.InvariantCultureIgnoreCase);
}
}
public bool ExecuteInOutput {
get {
return CreatePythonCommandItem.ExecuteInOutput.Equals(ExecuteIn, StringComparison.InvariantCultureIgnoreCase);
}
}
public bool ExecuteInConsole {
get {
return PythonCommandTask.ExecuteInConsole.Equals(ExecuteIn, StringComparison.InvariantCultureIgnoreCase);
}
}
public bool ExecuteInConsoleAndPause {
get {
return PythonCommandTask.ExecuteInConsolePause.Equals(ExecuteIn, StringComparison.InvariantCultureIgnoreCase);
}
}
public bool ExecuteHidden {
get {
return PythonCommandTask.ExecuteInNone.Equals(ExecuteIn, StringComparison.InvariantCultureIgnoreCase);
}
}
public bool IsScript {
get {
return PythonCommandTask.TargetTypeScript.Equals(TargetType, StringComparison.InvariantCultureIgnoreCase);
}
}
public bool IsModule {
get {
return PythonCommandTask.TargetTypeModule.Equals(TargetType, StringComparison.InvariantCultureIgnoreCase);
}
}
public bool IsCode {
get {
return PythonCommandTask.TargetTypeCode.Equals(TargetType, StringComparison.InvariantCultureIgnoreCase);
}
}
public bool IsExecuable {
get {
return PythonCommandTask.TargetTypeExecutable.Equals(TargetType, StringComparison.InvariantCultureIgnoreCase);
}
}
public bool IsPip {
get {
return PythonCommandTask.TargetTypePip.Equals(TargetType, StringComparison.InvariantCultureIgnoreCase);
}
}
/// <summary>
/// Adjusts the options in this instance to be easily executed as an
/// external process.
///
/// After this method returns, the following changes have been made:
/// <list type="unordered">
/// <item><see cref="Filename"/> is now an executable file.</item>
/// <item><see cref="TargetType"/> is now <c>process</c>.</item>
/// <item><see cref="ExecuteIn"/> is now either <c>console</c> or
/// <c>output</c>.</item>
/// </list>
/// </summary>
/// <param name="interpreterPath">Full path to the interpreter.</param>
/// <param name="handleConsoleAndPause">
/// If this and <see cref="ExecuteInConsoleAndPause"/> are true, changes
/// <see cref="ExecuteIn"/> to <c>console</c> and updates
/// <see cref="Filename"/> and <see cref="Arguments"/> to handle the
/// pause.
/// </param>
public void AdjustArgumentsForProcessStartInfo(
string interpreterPath,
bool handleConsoleAndPause = true,
bool inheritGlobalEnvironmentVariables = true
) {
if (inheritGlobalEnvironmentVariables) {
var env = new Dictionary<string, string>();
var globalEnv = Environment.GetEnvironmentVariables();
foreach (var key in globalEnv.Keys) {
env[key.ToString()] = globalEnv[key].ToString();
}
if (EnvironmentVariables != null) {
foreach (var entry in EnvironmentVariables) {
env[entry.Key] = entry.Value;
}
}
EnvironmentVariables = env;
}
if (IsScript) {
AddArgumentAtStart(Filename);
Filename = interpreterPath;
} else if (IsModule) {
AddArgumentAtStart(Filename);
AddArgumentAtStart("-m");
Filename = interpreterPath;
} else if (IsCode) {
AddArgumentAtStart(Filename.Replace("\r\n", "\n"));
AddArgumentAtStart("-c");
Filename = interpreterPath;
}
TargetType = PythonCommandTask.TargetTypeExecutable;
if (ExecuteInRepl) {
ExecuteIn = CreatePythonCommandItem.ExecuteInOutput;
} else if (ExecuteInConsole) {
if (handleConsoleAndPause) {
Arguments = string.Format(
"/C \"{0}{1}{2}\" & if errorlevel 1 pause",
ProcessOutput.QuoteSingleArgument(Filename),
string.IsNullOrEmpty(Arguments) ? string.Empty : " ",
Arguments ?? string.Empty
);
Filename = Path.Combine(Environment.SystemDirectory, "cmd.exe");
ExecuteIn = PythonCommandTask.ExecuteInConsole;
}
} else if (ExecuteInConsoleAndPause) {
if (handleConsoleAndPause) {
Arguments = string.Format(
"/C \"{0}{1}{2}\" & pause",
ProcessOutput.QuoteSingleArgument(Filename),
string.IsNullOrEmpty(Arguments) ? string.Empty : " ",
Arguments ?? string.Empty
);
Filename = Path.Combine(Environment.SystemDirectory, "cmd.exe");
ExecuteIn = PythonCommandTask.ExecuteInConsole;
}
}
if (EnvironmentVariables != null && !string.IsNullOrEmpty(Arguments)) {
Arguments = Regex.Replace(Arguments, @"%(\w+)%", m => {
string envVar;
return EnvironmentVariables.TryGetValue(m.Groups[1].Value, out envVar) ? envVar : string.Empty;
});
}
}
private static string ChooseFirst(string x, string y) {
if (string.IsNullOrEmpty(x)) {
return y ?? string.Empty;
}
return x;
}
internal void AddPropertiesAfter(LaunchConfiguration config) {
AddArgumentAtEnd(config.ScriptArguments);
WorkingDirectory = ChooseFirst(WorkingDirectory, config.WorkingDirectory);
EnvironmentVariables = PathUtils.MergeEnvironments(
EnvironmentVariables.MaybeEnumerate(),
config.Environment.MaybeEnumerate(),
"PATH", config.Interpreter.PathEnvironmentVariable
);
}
}
}
| |
using System;
using System.Globalization;
using Lucene.Net.Documents;
namespace Lucene.Net.Search
{
using Lucene.Net.Index;
using NUnit.Framework;
using Analyzer = Lucene.Net.Analysis.Analyzer;
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity;
using Directory = Lucene.Net.Store.Directory;
using DirectoryReader = Lucene.Net.Index.DirectoryReader;
using Document = Documents.Document;
/*
* 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 Field = Field;
using FieldInvertState = Lucene.Net.Index.FieldInvertState;
using FieldType = FieldType;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using IndexWriterConfig = Lucene.Net.Index.IndexWriterConfig;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using Similarity = Lucene.Net.Search.Similarities.Similarity;
using SlowCompositeReaderWrapper = Lucene.Net.Index.SlowCompositeReaderWrapper;
using SpanQuery = Lucene.Net.Search.Spans.SpanQuery;
using SpanTermQuery = Lucene.Net.Search.Spans.SpanTermQuery;
using Term = Lucene.Net.Index.Term;
using TextField = TextField;
/// <summary>
/// Test of the DisjunctionMaxQuery.
///
/// </summary>
[TestFixture]
public class TestDisjunctionMaxQuery : LuceneTestCase
{
/// <summary>
/// threshold for comparing floats </summary>
public static readonly float SCORE_COMP_THRESH = 0.0000f;
/// <summary>
/// Similarity to eliminate tf, idf and lengthNorm effects to isolate test
/// case.
///
/// <p>
/// same as TestRankingSimilarity in TestRanking.zip from
/// http://issues.apache.org/jira/browse/LUCENE-323
/// </p>
/// </summary>
private class TestSimilarity : DefaultSimilarity
{
public TestSimilarity()
{
}
public override float Tf(float freq)
{
if (freq > 0.0f)
{
return 1.0f;
}
else
{
return 0.0f;
}
}
public override float LengthNorm(FieldInvertState state)
{
// Disable length norm
return state.Boost;
}
public override float Idf(long docFreq, long numDocs)
{
return 1.0f;
}
}
public Similarity Sim = new TestSimilarity();
public Directory Index;
public IndexReader r;
public IndexSearcher s;
private static readonly FieldType NonAnalyzedType = new FieldType(TextField.TYPE_STORED);
static TestDisjunctionMaxQuery()
{
NonAnalyzedType.Tokenized = false;
}
[SetUp]
public override void SetUp()
{
base.SetUp();
Index = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), Index, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetSimilarity(Sim).SetMergePolicy(NewLogMergePolicy()));
// hed is the most important field, dek is secondary
// d1 is an "ok" match for: albino elephant
{
Document d1 = new Document();
d1.Add(NewField("id", "d1", NonAnalyzedType)); // Field.Keyword("id",
// "d1"));
d1.Add(NewTextField("hed", "elephant", Field.Store.YES)); // Field.Text("hed", "elephant"));
d1.Add(NewTextField("dek", "elephant", Field.Store.YES)); // Field.Text("dek", "elephant"));
writer.AddDocument(d1);
}
// d2 is a "good" match for: albino elephant
{
Document d2 = new Document();
d2.Add(NewField("id", "d2", NonAnalyzedType)); // Field.Keyword("id",
// "d2"));
d2.Add(NewTextField("hed", "elephant", Field.Store.YES)); // Field.Text("hed", "elephant"));
d2.Add(NewTextField("dek", "albino", Field.Store.YES)); // Field.Text("dek",
// "albino"));
d2.Add(NewTextField("dek", "elephant", Field.Store.YES)); // Field.Text("dek", "elephant"));
writer.AddDocument(d2);
}
// d3 is a "better" match for: albino elephant
{
Document d3 = new Document();
d3.Add(NewField("id", "d3", NonAnalyzedType)); // Field.Keyword("id",
// "d3"));
d3.Add(NewTextField("hed", "albino", Field.Store.YES)); // Field.Text("hed",
// "albino"));
d3.Add(NewTextField("hed", "elephant", Field.Store.YES)); // Field.Text("hed", "elephant"));
writer.AddDocument(d3);
}
// d4 is the "best" match for: albino elephant
{
Document d4 = new Document();
d4.Add(NewField("id", "d4", NonAnalyzedType)); // Field.Keyword("id",
// "d4"));
d4.Add(NewTextField("hed", "albino", Field.Store.YES)); // Field.Text("hed",
// "albino"));
d4.Add(NewField("hed", "elephant", NonAnalyzedType)); // Field.Text("hed", "elephant"));
d4.Add(NewTextField("dek", "albino", Field.Store.YES)); // Field.Text("dek",
// "albino"));
writer.AddDocument(d4);
}
r = SlowCompositeReaderWrapper.Wrap(writer.Reader);
writer.Dispose();
s = NewSearcher(r);
s.Similarity = Sim;
}
[TearDown]
public override void TearDown()
{
r.Dispose();
Index.Dispose();
base.TearDown();
}
[Test]
public virtual void TestSkipToFirsttimeMiss()
{
DisjunctionMaxQuery dq = new DisjunctionMaxQuery(0.0f);
dq.Add(Tq("id", "d1"));
dq.Add(Tq("dek", "DOES_NOT_EXIST"));
QueryUtils.Check(Random(), dq, s);
Assert.IsTrue(s.TopReaderContext is AtomicReaderContext);
Weight dw = s.CreateNormalizedWeight(dq);
AtomicReaderContext context = (AtomicReaderContext)s.TopReaderContext;
Scorer ds = dw.Scorer(context, (context.AtomicReader).LiveDocs);
bool skipOk = ds.Advance(3) != DocIdSetIterator.NO_MORE_DOCS;
if (skipOk)
{
Assert.Fail("firsttime skipTo found a match? ... " + r.Document(ds.DocID()).Get("id"));
}
}
[Test]
public virtual void TestSkipToFirsttimeHit()
{
DisjunctionMaxQuery dq = new DisjunctionMaxQuery(0.0f);
dq.Add(Tq("dek", "albino"));
dq.Add(Tq("dek", "DOES_NOT_EXIST"));
Assert.IsTrue(s.TopReaderContext is AtomicReaderContext);
QueryUtils.Check(Random(), dq, s);
Weight dw = s.CreateNormalizedWeight(dq);
AtomicReaderContext context = (AtomicReaderContext)s.TopReaderContext;
Scorer ds = dw.Scorer(context, (context.AtomicReader).LiveDocs);
Assert.IsTrue(ds.Advance(3) != DocIdSetIterator.NO_MORE_DOCS, "firsttime skipTo found no match");
Assert.AreEqual("d4", r.Document(ds.DocID()).Get("id"), "found wrong docid");
}
[Test]
public virtual void TestSimpleEqualScores1()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.0f);
q.Add(Tq("hed", "albino"));
q.Add(Tq("hed", "elephant"));
QueryUtils.Check(Random(), q, s);
ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs;
try
{
Assert.AreEqual(4, h.Length, "all docs should match " + q.ToString());
float score = h[0].Score;
for (int i = 1; i < h.Length; i++)
{
Assert.AreEqual(score, h[i].Score, SCORE_COMP_THRESH, "score #" + i + " is not the same");
}
}
catch (Exception e)
{
PrintHits("testSimpleEqualScores1", h, s);
throw e;
}
}
[Test]
public virtual void TestSimpleEqualScores2()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.0f);
q.Add(Tq("dek", "albino"));
q.Add(Tq("dek", "elephant"));
QueryUtils.Check(Random(), q, s);
ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs;
try
{
Assert.AreEqual(3, h.Length, "3 docs should match " + q.ToString());
float score = h[0].Score;
for (int i = 1; i < h.Length; i++)
{
Assert.AreEqual(score, h[i].Score, SCORE_COMP_THRESH, "score #" + i + " is not the same");
}
}
catch (Exception e)
{
PrintHits("testSimpleEqualScores2", h, s);
throw e;
}
}
[Test]
public virtual void TestSimpleEqualScores3()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.0f);
q.Add(Tq("hed", "albino"));
q.Add(Tq("hed", "elephant"));
q.Add(Tq("dek", "albino"));
q.Add(Tq("dek", "elephant"));
QueryUtils.Check(Random(), q, s);
ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs;
try
{
Assert.AreEqual(4, h.Length, "all docs should match " + q.ToString());
float score = h[0].Score;
for (int i = 1; i < h.Length; i++)
{
Assert.AreEqual(score, h[i].Score, SCORE_COMP_THRESH, "score #" + i + " is not the same");
}
}
catch (Exception e)
{
PrintHits("testSimpleEqualScores3", h, s);
throw e;
}
}
[Test]
public virtual void TestSimpleTiebreaker()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.01f);
q.Add(Tq("dek", "albino"));
q.Add(Tq("dek", "elephant"));
QueryUtils.Check(Random(), q, s);
ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs;
try
{
Assert.AreEqual(3, h.Length, "3 docs should match " + q.ToString());
Assert.AreEqual("d2", s.Doc(h[0].Doc).Get("id"), "wrong first");
float score0 = h[0].Score;
float score1 = h[1].Score;
float score2 = h[2].Score;
Assert.IsTrue(score0 > score1, "d2 does not have better score then others: " + score0 + " >? " + score1);
Assert.AreEqual(score1, score2, SCORE_COMP_THRESH, "d4 and d1 don't have equal scores");
}
catch (Exception e)
{
PrintHits("testSimpleTiebreaker", h, s);
throw e;
}
}
[Test]
public virtual void TestBooleanRequiredEqualScores()
{
BooleanQuery q = new BooleanQuery();
{
DisjunctionMaxQuery q1 = new DisjunctionMaxQuery(0.0f);
q1.Add(Tq("hed", "albino"));
q1.Add(Tq("dek", "albino"));
q.Add(q1, BooleanClause.Occur.MUST); // true,false);
QueryUtils.Check(Random(), q1, s);
}
{
DisjunctionMaxQuery q2 = new DisjunctionMaxQuery(0.0f);
q2.Add(Tq("hed", "elephant"));
q2.Add(Tq("dek", "elephant"));
q.Add(q2, BooleanClause.Occur.MUST); // true,false);
QueryUtils.Check(Random(), q2, s);
}
QueryUtils.Check(Random(), q, s);
ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs;
try
{
Assert.AreEqual(3, h.Length, "3 docs should match " + q.ToString());
float score = h[0].Score;
for (int i = 1; i < h.Length; i++)
{
Assert.AreEqual(score, h[i].Score, SCORE_COMP_THRESH, "score #" + i + " is not the same");
}
}
catch (Exception e)
{
PrintHits("testBooleanRequiredEqualScores1", h, s);
throw e;
}
}
[Test]
public virtual void TestBooleanOptionalNoTiebreaker()
{
BooleanQuery q = new BooleanQuery();
{
DisjunctionMaxQuery q1 = new DisjunctionMaxQuery(0.0f);
q1.Add(Tq("hed", "albino"));
q1.Add(Tq("dek", "albino"));
q.Add(q1, BooleanClause.Occur.SHOULD); // false,false);
}
{
DisjunctionMaxQuery q2 = new DisjunctionMaxQuery(0.0f);
q2.Add(Tq("hed", "elephant"));
q2.Add(Tq("dek", "elephant"));
q.Add(q2, BooleanClause.Occur.SHOULD); // false,false);
}
QueryUtils.Check(Random(), q, s);
ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs;
try
{
Assert.AreEqual(4, h.Length, "4 docs should match " + q.ToString());
float score = h[0].Score;
for (int i = 1; i < h.Length - 1; i++) // note: -1
{
Assert.AreEqual(score, h[i].Score, SCORE_COMP_THRESH, "score #" + i + " is not the same");
}
Assert.AreEqual("d1", s.Doc(h[h.Length - 1].Doc).Get("id"), "wrong last");
float score1 = h[h.Length - 1].Score;
Assert.IsTrue(score > score1, "d1 does not have worse score then others: " + score + " >? " + score1);
}
catch (Exception e)
{
PrintHits("testBooleanOptionalNoTiebreaker", h, s);
throw e;
}
}
[Test]
public virtual void TestBooleanOptionalWithTiebreaker()
{
BooleanQuery q = new BooleanQuery();
{
DisjunctionMaxQuery q1 = new DisjunctionMaxQuery(0.01f);
q1.Add(Tq("hed", "albino"));
q1.Add(Tq("dek", "albino"));
q.Add(q1, BooleanClause.Occur.SHOULD); // false,false);
}
{
DisjunctionMaxQuery q2 = new DisjunctionMaxQuery(0.01f);
q2.Add(Tq("hed", "elephant"));
q2.Add(Tq("dek", "elephant"));
q.Add(q2, BooleanClause.Occur.SHOULD); // false,false);
}
QueryUtils.Check(Random(), q, s);
ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs;
try
{
Assert.AreEqual(4, h.Length, "4 docs should match " + q.ToString());
float score0 = h[0].Score;
float score1 = h[1].Score;
float score2 = h[2].Score;
float score3 = h[3].Score;
string doc0 = s.Doc(h[0].Doc).Get("id");
string doc1 = s.Doc(h[1].Doc).Get("id");
string doc2 = s.Doc(h[2].Doc).Get("id");
string doc3 = s.Doc(h[3].Doc).Get("id");
Assert.IsTrue(doc0.Equals("d2") || doc0.Equals("d4"), "doc0 should be d2 or d4: " + doc0);
Assert.IsTrue(doc1.Equals("d2") || doc1.Equals("d4"), "doc1 should be d2 or d4: " + doc0);
Assert.AreEqual(score0, score1, SCORE_COMP_THRESH, "score0 and score1 should match");
Assert.AreEqual("d3", doc2, "wrong third");
Assert.IsTrue(score1 > score2, "d3 does not have worse score then d2 and d4: " + score1 + " >? " + score2);
Assert.AreEqual("d1", doc3, "wrong fourth");
Assert.IsTrue(score2 > score3, "d1 does not have worse score then d3: " + score2 + " >? " + score3);
}
catch (Exception e)
{
PrintHits("testBooleanOptionalWithTiebreaker", h, s);
throw e;
}
}
[Test]
public virtual void TestBooleanOptionalWithTiebreakerAndBoost()
{
BooleanQuery q = new BooleanQuery();
{
DisjunctionMaxQuery q1 = new DisjunctionMaxQuery(0.01f);
q1.Add(Tq("hed", "albino", 1.5f));
q1.Add(Tq("dek", "albino"));
q.Add(q1, BooleanClause.Occur.SHOULD); // false,false);
}
{
DisjunctionMaxQuery q2 = new DisjunctionMaxQuery(0.01f);
q2.Add(Tq("hed", "elephant", 1.5f));
q2.Add(Tq("dek", "elephant"));
q.Add(q2, BooleanClause.Occur.SHOULD); // false,false);
}
QueryUtils.Check(Random(), q, s);
ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs;
try
{
Assert.AreEqual(4, h.Length, "4 docs should match " + q.ToString());
float score0 = h[0].Score;
float score1 = h[1].Score;
float score2 = h[2].Score;
float score3 = h[3].Score;
string doc0 = s.Doc(h[0].Doc).Get("id");
string doc1 = s.Doc(h[1].Doc).Get("id");
string doc2 = s.Doc(h[2].Doc).Get("id");
string doc3 = s.Doc(h[3].Doc).Get("id");
Assert.AreEqual("d4", doc0, "doc0 should be d4: ");
Assert.AreEqual("d3", doc1, "doc1 should be d3: ");
Assert.AreEqual("d2", doc2, "doc2 should be d2: ");
Assert.AreEqual("d1", doc3, "doc3 should be d1: ");
Assert.IsTrue(score0 > score1, "d4 does not have a better score then d3: " + score0 + " >? " + score1);
Assert.IsTrue(score1 > score2, "d3 does not have a better score then d2: " + score1 + " >? " + score2);
Assert.IsTrue(score2 > score3, "d3 does not have a better score then d1: " + score2 + " >? " + score3);
}
catch (Exception e)
{
PrintHits("TestBooleanOptionalWithTiebreakerAndBoost", h, s);
throw e;
}
}
// LUCENE-4477 / LUCENE-4401:
[Test]
public virtual void TestBooleanSpanQuery()
{
int hits = 0;
Directory directory = NewDirectory();
Analyzer indexerAnalyzer = new MockAnalyzer(Random());
IndexWriterConfig config = new IndexWriterConfig(TEST_VERSION_CURRENT, indexerAnalyzer);
IndexWriter writer = new IndexWriter(directory, config);
string FIELD = "content";
Document d = new Document();
d.Add(new TextField(FIELD, "clockwork orange", Field.Store.YES));
writer.AddDocument(d);
writer.Dispose();
IndexReader indexReader = DirectoryReader.Open(directory);
IndexSearcher searcher = NewSearcher(indexReader);
DisjunctionMaxQuery query = new DisjunctionMaxQuery(1.0f);
SpanQuery sq1 = new SpanTermQuery(new Term(FIELD, "clockwork"));
SpanQuery sq2 = new SpanTermQuery(new Term(FIELD, "clckwork"));
query.Add(sq1);
query.Add(sq2);
TopScoreDocCollector collector = TopScoreDocCollector.Create(1000, true);
searcher.Search(query, collector);
hits = collector.TopDocs().ScoreDocs.Length;
foreach (ScoreDoc scoreDoc in collector.TopDocs().ScoreDocs)
{
Console.WriteLine(scoreDoc.Doc);
}
indexReader.Dispose();
Assert.AreEqual(hits, 1);
directory.Dispose();
}
/// <summary>
/// macro </summary>
protected internal virtual Query Tq(string f, string t)
{
return new TermQuery(new Term(f, t));
}
/// <summary>
/// macro </summary>
protected internal virtual Query Tq(string f, string t, float b)
{
Query q = Tq(f, t);
q.Boost = b;
return q;
}
protected internal virtual void PrintHits(string test, ScoreDoc[] h, IndexSearcher searcher)
{
Console.Error.WriteLine("------- " + test + " -------");
//DecimalFormat f = new DecimalFormat("0.000000000", DecimalFormatSymbols.getInstance(Locale.ROOT));
NumberFormatInfo f = new NumberFormatInfo();
f.NumberDecimalSeparator = ".";
for (int i = 0; i < h.Length; i++)
{
Document d = searcher.Doc(h[i].Doc);
decimal score = (decimal)h[i].Score;
Console.Error.WriteLine("#" + i + ": " + score.ToString(f) + " - " + d.Get("id"));
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
namespace tk2dEditor.SpriteCollectionEditor
{
public class SettingsView
{
public bool show = false;
Vector2 settingsScrollbar = Vector2.zero;
int[] padAmountValues = null;
string[] padAmountLabels = null;
IEditorHost host;
public SettingsView(IEditorHost host)
{
this.host = host;
}
SpriteCollectionProxy SpriteCollection { get { return host.SpriteCollection; } }
Material DuplicateMaterial(Material source)
{
string sourcePath = AssetDatabase.GetAssetPath(source);
string targetPath = AssetDatabase.GenerateUniqueAssetPath(sourcePath);
AssetDatabase.CopyAsset(sourcePath, targetPath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
return AssetDatabase.LoadAssetAtPath(targetPath, typeof(Material)) as Material;
}
void DrawMaterialEditor()
{
// Upgrade
int numAltMaterials = 0;
foreach (var v in SpriteCollection.altMaterials)
if (v != null) numAltMaterials++;
if ((SpriteCollection.altMaterials.Length == 0 || numAltMaterials == 0) && SpriteCollection.atlasMaterials.Length != 0)
SpriteCollection.altMaterials = new Material[1] { SpriteCollection.atlasMaterials[0] };
if (SpriteCollection.altMaterials.Length > 0)
{
GUILayout.BeginHorizontal();
DrawHeaderLabel("Materials");
GUILayout.FlexibleSpace();
if (GUILayout.Button("+", EditorStyles.miniButton))
{
int sourceIndex = -1;
int i;
for (i = 0; i < SpriteCollection.altMaterials.Length; ++i)
{
if (SpriteCollection.altMaterials[i] != null)
{
sourceIndex = i;
break;
}
}
for (i = 0; i < SpriteCollection.altMaterials.Length; ++i)
{
if (SpriteCollection.altMaterials[i] == null)
break;
}
if (i == SpriteCollection.altMaterials.Length)
System.Array.Resize(ref SpriteCollection.altMaterials, SpriteCollection.altMaterials.Length + 1);
Material mtl = null;
if (sourceIndex == -1)
{
Debug.LogError("Sprite collection has null materials. Fix this in the debug inspector.");
}
else
{
mtl = DuplicateMaterial(SpriteCollection.altMaterials[sourceIndex]);
}
SpriteCollection.altMaterials[i] = mtl;
SpriteCollection.Trim();
if (SpriteCollection.platforms.Count > 1)
{
SpriteCollection.platforms[0].spriteCollection.altMaterials = SpriteCollection.altMaterials;
EditorUtility.SetDirty(SpriteCollection.platforms[0].spriteCollection);
for (int j = 1; j < SpriteCollection.platforms.Count; ++j)
{
if (!SpriteCollection.platforms[j].Valid) continue;
tk2dSpriteCollection data = SpriteCollection.platforms[j].spriteCollection;
System.Array.Resize(ref data.altMaterials, SpriteCollection.altMaterials.Length);
data.altMaterials[i] = DuplicateMaterial(data.altMaterials[sourceIndex]);
EditorUtility.SetDirty(data);
}
}
host.Commit();
}
GUILayout.EndHorizontal();
if (SpriteCollection.altMaterials != null)
{
EditorGUI.indentLevel++;
for (int i = 0; i < SpriteCollection.altMaterials.Length; ++i)
{
if (SpriteCollection.altMaterials[i] == null)
continue;
bool deleteMaterial = false;
Material newMaterial = EditorGUILayout.ObjectField(SpriteCollection.altMaterials[i], typeof(Material), false) as Material;
if (newMaterial == null)
{
// Can't delete the last one
if (numAltMaterials > 1)
{
bool inUse = false;
foreach (var v in SpriteCollection.textureParams)
{
if (v.materialId == i)
{
inUse = true;
break;
}
}
foreach (var v in SpriteCollection.fonts)
{
if (v.materialId == i)
{
inUse = true;
break;
}
}
if (inUse)
{
if (EditorUtility.DisplayDialog("Delete material",
"This material is in use. Deleting it will reset materials on " +
"sprites that use this material.\n" +
"Do you wish to proceed?", "Yes", "Cancel"))
{
deleteMaterial = true;
}
}
else
{
deleteMaterial = true;
}
}
}
else
{
SpriteCollection.altMaterials[i] = newMaterial;
}
if (deleteMaterial)
{
SpriteCollection.altMaterials[i] = null;
// fix up all existing materials
int targetMaterialId;
for (targetMaterialId = 0; targetMaterialId < SpriteCollection.altMaterials.Length; ++targetMaterialId)
if (SpriteCollection.altMaterials[targetMaterialId] != null)
break;
foreach (var sprite in SpriteCollection.textureParams)
{
if (sprite.materialId == i)
sprite.materialId = targetMaterialId;
}
foreach (var font in SpriteCollection.fonts)
{
if (font.materialId == i)
font.materialId = targetMaterialId;
}
SpriteCollection.Trim();
// Do the same on inherited sprite collections
for (int j = 0; j < SpriteCollection.platforms.Count; ++j)
{
if (!SpriteCollection.platforms[j].Valid) continue;
tk2dSpriteCollection data = SpriteCollection.platforms[j].spriteCollection;
data.altMaterials[i] = null;
for (int lastIndex = data.altMaterials.Length - 1; lastIndex >= 0; --lastIndex)
{
if (data.altMaterials[lastIndex] != null)
{
int count = data.altMaterials.Length - 1 - lastIndex;
if (count > 0)
System.Array.Resize(ref data.altMaterials, lastIndex + 1);
break;
}
}
EditorUtility.SetDirty(data);
}
host.Commit();
}
}
EditorGUI.indentLevel--;
}
}
}
void DrawHeaderLabel(string name)
{
GUILayout.Label(name, EditorStyles.boldLabel);
}
void BeginHeader(string name)
{
DrawHeaderLabel(name);
GUILayout.Space(2);
EditorGUI.indentLevel++;
}
void EndHeader()
{
EditorGUI.indentLevel--;
GUILayout.Space(8);
}
void DrawSystemSettings()
{
BeginHeader("System");
// Loadable
bool allowSwitch = SpriteCollection.spriteCollection != null;
bool loadable = SpriteCollection.spriteCollection?SpriteCollection.loadable:false;
bool newLoadable = EditorGUILayout.Toggle("Loadable asset", loadable);
if (newLoadable != loadable)
{
if (!allowSwitch)
{
EditorUtility.DisplayDialog("Please commit the sprite collection before attempting to make it loadable.", "Make loadable.", "Ok");
}
else
{
if (newLoadable)
{
if (SpriteCollection.assetName.Length == 0)
SpriteCollection.assetName = SpriteCollection.spriteCollection.spriteCollectionName; // guess something
tk2dSystemUtility.MakeLoadableAsset(SpriteCollection.spriteCollection, SpriteCollection.assetName);
}
else
{
if (tk2dSystemUtility.IsLoadableAsset(SpriteCollection.spriteCollection))
tk2dSystemUtility.UnmakeLoadableAsset(SpriteCollection.spriteCollection);
}
loadable = newLoadable;
SpriteCollection.loadable = loadable;
}
}
if (loadable)
{
SpriteCollection.assetName = EditorGUILayout.TextField("Asset Name/Path", SpriteCollection.assetName);
}
// Clear data
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("References");
if (GUILayout.Button("Clear References", EditorStyles.miniButton))
{
if (EditorUtility.DisplayDialog("Clear references",
"Clearing references will clear references to data (atlases, materials) owned by this sprite collection. " +
"This will only remove references, and will not delete the data or textures. " +
"Use after duplicating a sprite collection to sever links with the original.\n\n" +
"Are you sure you want to do this?"
, "Yes", "No"))
{
SpriteCollection.altMaterials = new Material[0];
SpriteCollection.atlasMaterials = new Material[0];
SpriteCollection.atlasTextures = new Texture2D[0];
SpriteCollection.spriteCollection = null;
foreach (tk2dSpriteCollectionPlatform plat in SpriteCollection.platforms)
plat.spriteCollection = null;
}
}
GUILayout.EndHorizontal();
EndHeader();
}
void DrawPlatforms()
{
// Asset Platform
BeginHeader("Platforms");
tk2dSystem system = tk2dSystem.inst_NoCreate;
if (system == null && GUILayout.Button("Add Platform Support"))
system = tk2dSystem.inst; // force creation
if (system)
{
int toDelete = -1;
for (int i = 0; i < SpriteCollection.platforms.Count; ++i)
{
tk2dSpriteCollectionPlatform currentPlatform = SpriteCollection.platforms[i];
GUILayout.BeginHorizontal();
string label = (i==0)?"Current platform":"Platform";
currentPlatform.name = tk2dGuiUtility.PlatformPopup(system, label, currentPlatform.name);
bool displayDelete = ((SpriteCollection.platforms.Count == 1 && SpriteCollection.platforms[0].name.Length > 0) ||
(SpriteCollection.platforms.Count > 1 && i > 0));
if (displayDelete && GUILayout.Button("Delete", EditorStyles.miniButton, GUILayout.MaxWidth(50))) toDelete = i;
GUILayout.EndHorizontal();
}
if (toDelete != -1)
{
tk2dSpriteCollection deletedSpriteCollection = null;
if (SpriteCollection.platforms.Count == 1)
{
if (SpriteCollection.platforms[0].spriteCollection != null && SpriteCollection.platforms[0].spriteCollection.spriteCollection != null)
deletedSpriteCollection = SpriteCollection.platforms[0].spriteCollection;
SpriteCollection.platforms[0].name = "";
SpriteCollection.platforms[0].spriteCollection = null;
}
else
{
if (SpriteCollection.platforms[toDelete].spriteCollection != null && SpriteCollection.platforms[toDelete].spriteCollection.spriteCollection != null)
deletedSpriteCollection = SpriteCollection.platforms[toDelete].spriteCollection;
SpriteCollection.platforms.RemoveAt(toDelete);
}
if (deletedSpriteCollection != null)
{
foreach (tk2dSpriteCollectionFont f in deletedSpriteCollection.fonts)
tk2dSystemUtility.UnmakeLoadableAsset(f.data);
tk2dSystemUtility.UnmakeLoadableAsset(deletedSpriteCollection.spriteCollection);
}
}
if (SpriteCollection.platforms.Count > 1 ||
(SpriteCollection.platforms.Count == 1 && SpriteCollection.platforms[0].name.Length > 0))
{
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel(" ");
if (GUILayout.Button("Add new platform", EditorStyles.miniButton))
SpriteCollection.platforms.Add(new tk2dSpriteCollectionPlatform());
GUILayout.EndHorizontal();
}
}
EndHeader();
}
void DrawTextureSettings()
{
BeginHeader("Texture Settings");
SpriteCollection.filterMode = (FilterMode)EditorGUILayout.EnumPopup("Filter Mode", SpriteCollection.filterMode);
SpriteCollection.textureCompression = (tk2dSpriteCollection.TextureCompression)EditorGUILayout.EnumPopup("Compression", SpriteCollection.textureCompression);
SpriteCollection.userDefinedTextureSettings = EditorGUILayout.Toggle("User Defined", SpriteCollection.userDefinedTextureSettings);
if (SpriteCollection.userDefinedTextureSettings) GUI.enabled = false;
SpriteCollection.wrapMode = (TextureWrapMode)EditorGUILayout.EnumPopup("Wrap Mode", SpriteCollection.wrapMode);
SpriteCollection.anisoLevel = (int)EditorGUILayout.IntSlider("Aniso Level", SpriteCollection.anisoLevel, 0, 9);
SpriteCollection.mipmapEnabled = EditorGUILayout.Toggle("Mip Maps", SpriteCollection.mipmapEnabled);
GUI.enabled = true;
EndHeader();
}
void DrawSpriteCollectionSettings()
{
BeginHeader("Sprite Collection Settings");
SpriteCollection.padAmount = EditorGUILayout.IntPopup("Pad Amount", SpriteCollection.padAmount, padAmountLabels, padAmountValues);
if (SpriteCollection.padAmount == 0 && SpriteCollection.filterMode != FilterMode.Point)
{
tk2dGuiUtility.InfoBox("Filter mode is not set to Point." +
" Some bleeding will occur at sprite edges.",
tk2dGuiUtility.WarningLevel.Info);
}
SpriteCollection.premultipliedAlpha = EditorGUILayout.Toggle("Premultiplied Alpha", SpriteCollection.premultipliedAlpha);
SpriteCollection.physicsDepth = EditorGUILayout.FloatField("Collider depth", SpriteCollection.physicsDepth);
SpriteCollection.disableTrimming = EditorGUILayout.Toggle("Disable Trimming", SpriteCollection.disableTrimming);
SpriteCollection.normalGenerationMode = (tk2dSpriteCollection.NormalGenerationMode)EditorGUILayout.EnumPopup("Normal Generation", SpriteCollection.normalGenerationMode);
SpriteCollection.useTk2dCamera = EditorGUILayout.Toggle("Use tk2dCamera", SpriteCollection.useTk2dCamera);
if (!SpriteCollection.useTk2dCamera)
{
EditorGUI.indentLevel = EditorGUI.indentLevel + 1;
SpriteCollection.targetHeight = EditorGUILayout.IntField("Target Height", SpriteCollection.targetHeight);
SpriteCollection.targetOrthoSize = EditorGUILayout.FloatField("Target Ortho Size", SpriteCollection.targetOrthoSize);
EditorGUI.indentLevel = EditorGUI.indentLevel - 1;
}
EndHeader();
}
void DrawAtlasSettings()
{
BeginHeader("Atlas Settings");
int[] allowedAtlasSizes = { 64, 128, 256, 512, 1024, 2048, 4096 };
string[] allowedAtlasSizesString = new string[allowedAtlasSizes.Length];
for (int i = 0; i < allowedAtlasSizes.Length; ++i)
allowedAtlasSizesString[i] = allowedAtlasSizes[i].ToString();
SpriteCollection.forceTextureSize = EditorGUILayout.Toggle("Force Atlas Size", SpriteCollection.forceTextureSize);
EditorGUI.indentLevel++;
if (SpriteCollection.forceTextureSize)
{
SpriteCollection.forcedTextureWidth = EditorGUILayout.IntPopup("Width", SpriteCollection.forcedTextureWidth, allowedAtlasSizesString, allowedAtlasSizes);
SpriteCollection.forcedTextureHeight = EditorGUILayout.IntPopup("Height", SpriteCollection.forcedTextureHeight, allowedAtlasSizesString, allowedAtlasSizes);
}
else
{
SpriteCollection.maxTextureSize = EditorGUILayout.IntPopup("Max Size", SpriteCollection.maxTextureSize, allowedAtlasSizesString, allowedAtlasSizes);
SpriteCollection.forceSquareAtlas = EditorGUILayout.Toggle("Force Square", SpriteCollection.forceSquareAtlas);
}
EditorGUI.indentLevel--;
bool allowMultipleAtlases = EditorGUILayout.Toggle("Multiple Atlases", SpriteCollection.allowMultipleAtlases);
if (allowMultipleAtlases != SpriteCollection.allowMultipleAtlases)
{
// Disallow switching if using unsupported features
if (allowMultipleAtlases == true)
{
bool hasDicing = false;
for (int i = 0; i < SpriteCollection.textureParams.Count; ++i)
{
if (SpriteCollection.textureParams[i].texture != null &
SpriteCollection.textureParams[i].dice)
{
hasDicing = true;
break;
}
}
if (SpriteCollection.fonts.Count > 0 || hasDicing)
{
EditorUtility.DisplayDialog("Multiple atlases",
"Multiple atlases not allowed. This sprite collection contains fonts and/or " +
"contains diced sprites.", "Ok");
allowMultipleAtlases = false;
}
}
SpriteCollection.allowMultipleAtlases = allowMultipleAtlases;
}
if (SpriteCollection.allowMultipleAtlases)
{
tk2dGuiUtility.InfoBox("Sprite collections with multiple atlas spanning enabled cannot be used with the Static Sprite" +
" Batcher, Fonts, the TileMap Editor and doesn't support Sprite Dicing and material level optimizations.\n\n" +
"Avoid using it unless you are simply importing a" +
" large sequence of sprites for an animation.", tk2dGuiUtility.WarningLevel.Info);
}
if (SpriteCollection.allowMultipleAtlases)
{
EditorGUILayout.LabelField("Num Atlases", SpriteCollection.atlasTextures.Length.ToString());
}
else
{
EditorGUILayout.LabelField("Atlas Width", SpriteCollection.atlasWidth.ToString());
EditorGUILayout.LabelField("Atlas Height", SpriteCollection.atlasHeight.ToString());
EditorGUILayout.LabelField("Atlas Wastage", SpriteCollection.atlasWastage.ToString("0.00") + "%");
}
EndHeader();
}
public void Draw()
{
if (SpriteCollection == null)
return;
// initialize internal stuff
if (padAmountValues == null || padAmountValues.Length == 0)
{
int MAX_PAD_AMOUNT = 18;
padAmountValues = new int[MAX_PAD_AMOUNT];
padAmountLabels = new string[MAX_PAD_AMOUNT];
for (int i = 0; i < MAX_PAD_AMOUNT; ++i)
{
padAmountValues[i] = -1 + i;
padAmountLabels[i] = (i==0)?"Default":((i-1).ToString());
}
}
GUILayout.BeginHorizontal();
GUILayout.BeginVertical(tk2dEditorSkin.SC_BodyBackground, GUILayout.ExpandHeight(true), GUILayout.ExpandWidth(true));
GUILayout.EndVertical();
Rect rect = GUILayoutUtility.GetLastRect();
tk2dGrid.Draw(rect);
int inspectorWidth = host.InspectorWidth;
EditorGUIUtility.LookLikeControls(130.0f, 40.0f);
settingsScrollbar = GUILayout.BeginScrollView(settingsScrollbar, GUILayout.ExpandHeight(true), GUILayout.Width(inspectorWidth));
GUILayout.BeginVertical(tk2dEditorSkin.SC_InspectorHeaderBG, GUILayout.ExpandWidth(true));
GUILayout.Label("Settings", EditorStyles.largeLabel);
SpriteCollection.spriteCollection = EditorGUILayout.ObjectField("Data object", SpriteCollection.spriteCollection, typeof(tk2dSpriteCollectionData), false) as tk2dSpriteCollectionData;
GUILayout.EndVertical();
GUILayout.BeginVertical(tk2dEditorSkin.SC_InspectorBG, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
DrawSpriteCollectionSettings();
DrawTextureSettings();
DrawAtlasSettings();
DrawSystemSettings();
DrawPlatforms();
// Materials
if (!SpriteCollection.allowMultipleAtlases)
{
DrawMaterialEditor();
}
GUILayout.Space(8);
GUILayout.EndVertical();
GUILayout.EndScrollView();
// make dragable
tk2dPreferences.inst.spriteCollectionInspectorWidth -= (int)tk2dGuiUtility.DragableHandle(4819284, GUILayoutUtility.GetLastRect(), 0, tk2dGuiUtility.DragDirection.Horizontal);
GUILayout.EndHorizontal();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Text;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Types;
using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute;
namespace IronPython.Runtime.Operations {
public static partial class Int32Ops {
private static object FastNew(CodeContext/*!*/ context, object o, int @base = 10) {
object result;
switch (o) {
case double d:
return DoubleOps.__int__(d);
case bool b:
return BoolOps.__int__(b);
case int _:
return o;
case BigInteger val:
return val.IsInt32() ? (object)(int)val : o;
case Extensible<BigInteger> ebi:
return TryInvokeInt(context, o, out result) ? result : ebi.Value.IsInt32() ? (object)(int)ebi.Value : ebi.Value;
case float f:
return DoubleOps.__int__(f);
case long val:
return int.MinValue <= val && val <= int.MaxValue ? (object)(int)val : (BigInteger)val;
case uint val:
return val <= int.MaxValue ? (object)(int)val : (BigInteger)val;
case ulong val:
return val <= int.MaxValue ? (object)(int)val : (BigInteger)val;
case decimal val:
return int.MinValue <= val && val <= int.MaxValue ? (object)(int)val : (BigInteger)val;
case Enum e:
return ((IConvertible)e).ToInt32(null);
case string s:
return LiteralParser.ParseIntegerSign(s, @base, FindStart(s, @base));
case Extensible<string> es:
return TryInvokeInt(context, o, out result) ? result : LiteralParser.ParseIntegerSign(es.Value, @base, FindStart(es.Value, @base));
default:
break;
}
if (TryInvokeInt(context, o, out result)) {
return result;
} else if (PythonTypeOps.TryInvokeUnaryOperator(context, o, "__trunc__", out result)) {
switch (result) {
case int _:
return result;
case BigInteger bi:
return bi.IsInt32() ? (object)(int)bi : result;
case bool b:
return BoolOps.__int__(b); // Python 3.6: return the int value
case Extensible<BigInteger> ebi:
return ebi.Value.IsInt32() ? (object)(int)ebi.Value : ebi.Value; // Python 3.6: return the int value
default: {
if (TryInvokeInt(context, result, out var intResult)) {
return intResult;
}
throw PythonOps.TypeError("__trunc__ returned non-Integral (type {0})", PythonOps.GetPythonTypeName(result));
}
}
}
throw PythonOps.TypeError("int() argument must be a string, a bytes-like object or a number, not '{0}'", PythonOps.GetPythonTypeName(o));
static bool TryInvokeInt(CodeContext context, object o, out object result) {
if (PythonTypeOps.TryInvokeUnaryOperator(context, o, "__int__", out result)) {
switch (result) {
case int _:
return true;
case BigInteger bi:
if (bi.IsInt32()) result = (int)bi;
return true;
case bool b:
Warn(context, result);
result = BoolOps.__int__(b); // Python 3.6: return the int value
return true;
case Extensible<BigInteger> ebi:
Warn(context, result);
result = ebi.Value.IsInt32() ? (object)(int)ebi.Value : ebi.Value; // Python 3.6: return the int value
return true;
default:
throw PythonOps.TypeError("__int__ returned non-int (type {0})", PythonOps.GetPythonTypeName(result));
}
static void Warn(CodeContext context, object result) {
PythonOps.Warn(context, PythonExceptions.DeprecationWarning, $"__int__ returned non-int (type {PythonOps.GetPythonTypeName(result)}). The ability to return an instance of a strict subclass of int is deprecated, and may be removed in a future version of Python.");
}
}
return false;
}
}
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType cls, object x, object @base) {
ValidateType(cls);
var b = BaseFromObject(@base);
if (!(x is string || x is Extensible<string>))
throw PythonOps.TypeError("int() can't convert non-string with explicit base");
return ReturnObject(context, cls, FastNew(context, x, b));
}
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType cls, object x) {
ValidateType(cls);
return ReturnObject(context, cls, FastNew(context, x));
}
// "int()" calls ReflectedType.Call(), which calls "Activator.CreateInstance" and return directly.
// this is for derived int creation or direct calls to __new__...
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType cls)
=> __new__(context, cls, ScriptingRuntimeHelpers.Int32ToObject(0));
[StaticExtensionMethod]
public static object __new__(CodeContext/*!*/ context, PythonType cls, [NotNull] IBufferProtocol x, int @base = 10) {
ValidateType(cls);
object value;
if (!(x is IPythonObject po) || !PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, po, "__int__", out value)) {
using IPythonBuffer buf = x.GetBufferNoThrow()
?? throw PythonOps.TypeErrorForBadInstance("int() argument must be a string, a bytes-like object or a number, not '{0}'", x);
var text = buf.AsReadOnlySpan().MakeString();
if (!LiteralParser.TryParseIntegerSign(text, @base, FindStart(text, @base), out value))
throw PythonOps.ValueError($"invalid literal for int() with base {@base}: {new Bytes(x).__repr__(context)}");
}
return ReturnObject(context, cls, value);
}
[StaticExtensionMethod]
public static object __new__(CodeContext/*!*/ context, PythonType cls, [NotNull] IBufferProtocol x, object @base)
=> __new__(context, cls, x, BaseFromObject(@base));
private static void ValidateType(PythonType cls) {
if (cls == TypeCache.Boolean)
throw PythonOps.TypeError("int.__new__(bool) is not safe, use bool.__new__()");
}
private static int BaseFromObject(object @base) {
switch (PythonOps.Index(@base)) {
case int i:
return i;
case BigInteger bi:
try {
return (int)bi;
} catch (OverflowException) {
return int.MaxValue;
}
default:
throw new InvalidOperationException();
}
}
private static object ReturnObject(CodeContext context, PythonType cls, object value)
=> cls == TypeCache.Int32 ? value : cls.CreateInstance(context, value);
internal static int FindStart(string s, int radix) {
int i = 0;
// skip whitespace
while (i < s.Length && char.IsWhiteSpace(s, i)) i++;
// skip possible radix prefix
if (i + 1 < s.Length && s[i] == '0') {
switch (radix) {
case 16:
if (s[i + 1] == 'x' || s[i + 1] == 'X')
i += 2;
break;
case 8:
if (s[i + 1] == 'o' || s[i + 1] == 'O')
i += 2;
break;
case 2:
if (s[i + 1] == 'b' || s[i + 1] == 'B')
i += 2;
break;
default:
break;
}
}
return i;
}
private static bool IsInt32(this BigInteger self)
=> int.MinValue <= self && self <= int.MaxValue;
#region Binary Operators
[SpecialName]
public static object FloorDivide(int x, int y) {
if (y == -1 && x == Int32.MinValue) {
return -(BigInteger)Int32.MinValue;
}
return ScriptingRuntimeHelpers.Int32ToObject(MathUtils.FloorDivideUnchecked(x, y));
}
[SpecialName]
public static int Mod(int x, int y) {
return MathUtils.FloorRemainder(x, y);
}
[SpecialName]
public static object Power(int x, BigInteger power, BigInteger qmod) {
return BigIntegerOps.Power((BigInteger)x, power, qmod);
}
[SpecialName]
public static object Power(int x, double power, double qmod) {
return NotImplementedType.Value;
}
[SpecialName]
public static object Power(int x, int power, int? qmod) {
if (qmod == null) return Power(x, power);
int mod = (int)qmod;
if (power < 0) throw PythonOps.ValueError("power must be >= 0");
if (mod == 0) {
throw PythonOps.ZeroDivisionError();
}
// This is "exponentiation by squaring" (described in Applied Cryptography; a log-time algorithm)
long result = 1 % mod; // Handle special case of power=0, mod=1
long factor = x;
while (power != 0) {
if ((power & 1) != 0) result = (result * factor) % mod;
factor = (factor * factor) % mod;
power >>= 1;
}
// fix the sign for negative moduli or negative mantissas
if ((mod < 0 && result > 0) || (mod > 0 && result < 0)) {
result += mod;
}
return (int)result;
}
[SpecialName]
public static object Power(int x, int power) {
if (power == 0) return 1;
if (power < 0) {
if (x == 0)
throw PythonOps.ZeroDivisionError("0.0 cannot be raised to a negative power");
return DoubleOps.Power(x, power);
}
int factor = x;
int result = 1;
int savePower = power;
try {
checked {
while (power != 0) {
if ((power & 1) != 0) result = result * factor;
if (power == 1) break; // prevent overflow
factor = factor * factor;
power >>= 1;
}
return result;
}
} catch (OverflowException) {
return BigIntegerOps.Power(x, savePower);
}
}
[SpecialName]
public static object LeftShift(int x, int y) {
if (y < 0) {
throw PythonOps.ValueError("negative shift count");
}
if (y > 31 ||
(x > 0 && x > (Int32.MaxValue >> y)) ||
(x < 0 && x < (Int32.MinValue >> y))) {
return Int64Ops.LeftShift((long)x, y);
}
return ScriptingRuntimeHelpers.Int32ToObject(x << y);
}
[SpecialName]
public static int RightShift(int x, int y) {
if (y < 0) {
throw PythonOps.ValueError("negative shift count");
}
if (y > 31) {
return x >= 0 ? 0 : -1;
}
int q;
if (x >= 0) {
q = x >> y;
} else {
q = (x + ((1 << y) - 1)) >> y;
int r = x - (q << y);
if (r != 0) q--;
}
return q;
}
#endregion
public static PythonTuple __divmod__(int x, int y) {
return PythonTuple.MakeTuple(FloorDivide(x, y), Mod(x, y));
}
[return: MaybeNotImplemented]
public static object __divmod__(int x, object y) {
return NotImplementedType.Value;
}
public static object __getnewargs__(CodeContext context, int self) {
return PythonTuple.MakeTuple(Int32Ops.__new__(context, TypeCache.Int32, self));
}
public static object __rdivmod__(int x, int y) {
return __divmod__(y, x);
}
public static int __int__(int self) {
return self;
}
public static double __float__(int self) {
return (double)self;
}
public static int __abs__(int self) {
return Math.Abs(self);
}
public static string __format__(CodeContext/*!*/ context, int self, [NotNull]string/*!*/ formatSpec) {
StringFormatSpec spec = StringFormatSpec.FromString(formatSpec);
if (spec.Precision != null) {
throw PythonOps.ValueError("Precision not allowed in integer format specifier");
}
string digits;
int width = 0;
switch (spec.Type) {
case 'n':
CultureInfo culture = context.LanguageContext.NumericCulture;
if (culture == CultureInfo.InvariantCulture) {
// invariant culture maps to CPython's C culture, which doesn't
// include any formatting info.
goto case 'd';
}
width = spec.Width ?? 0;
// If we're padding with leading zeros and we might be inserting
// culture sensitive number group separators. (i.e. commas)
// So use FormattingHelper.ToCultureString for that support.
if (spec.Fill.HasValue && spec.Fill.Value == '0' && width > 1) {
digits = FormattingHelper.ToCultureString(self, culture.NumberFormat, spec);
}
else {
digits = self.ToString("N0", culture);
}
break;
case null:
case 'd':
if (spec.ThousandsComma) {
width = spec.Width ?? 0;
// If we're inserting commas, and we're padding with leading zeros.
// AlignNumericText won't know where to place the commas,
// so use FormattingHelper.ToCultureString for that support.
if (spec.Fill.HasValue && spec.Fill.Value == '0' && width > 1) {
digits = FormattingHelper.ToCultureString(self, FormattingHelper.InvariantCommaNumberInfo, spec);
}
else {
digits = self.ToString("#,0", CultureInfo.InvariantCulture);
}
} else {
digits = self.ToString("D", CultureInfo.InvariantCulture);
}
break;
case '%':
if (spec.ThousandsComma) {
digits = self.ToString("#,0.000000%", CultureInfo.InvariantCulture);
} else {
digits = self.ToString("0.000000%", CultureInfo.InvariantCulture);
}
break;
case 'e':
if (spec.ThousandsComma) {
digits = self.ToString("#,0.000000e+00", CultureInfo.InvariantCulture);
} else {
digits = self.ToString("0.000000e+00", CultureInfo.InvariantCulture);
}
break;
case 'E':
if (spec.ThousandsComma) {
digits = self.ToString("#,0.000000E+00", CultureInfo.InvariantCulture);
} else {
digits = self.ToString("0.000000E+00", CultureInfo.InvariantCulture);
}
break;
case 'f':
case 'F':
if (spec.ThousandsComma) {
digits = self.ToString("#,########0.000000", CultureInfo.InvariantCulture);
} else {
digits = self.ToString("#########0.000000", CultureInfo.InvariantCulture);
}
break;
case 'g':
if (self >= 1000000 || self <= -1000000) {
digits = self.ToString("0.#####e+00", CultureInfo.InvariantCulture);
} else if (spec.ThousandsComma) {
// Handle the common case in 'd'.
goto case 'd';
} else {
digits = self.ToString(CultureInfo.InvariantCulture);
}
break;
case 'G':
if (self >= 1000000 || self <= -1000000) {
digits = self.ToString("0.#####E+00", CultureInfo.InvariantCulture);
} else if (spec.ThousandsComma) {
// Handle the common case in 'd'.
goto case 'd';
}
else {
digits = self.ToString(CultureInfo.InvariantCulture);
}
break;
case 'X':
digits = ToHex(self, false);
break;
case 'x':
digits = ToHex(self, true);
break;
case 'o': // octal
digits = ToOctal(self, true);
break;
case 'b': // binary
digits = ToBinary(self, false);
break;
case 'c': // single char
if (spec.Sign != null) {
throw PythonOps.ValueError("Sign not allowed with integer format specifier 'c'");
}
if (self < 0 || self > 0x10ffff) {
throw PythonOps.OverflowError("%c arg not in range(0x110000)");
}
digits = (self > char.MaxValue) ? char.ConvertFromUtf32(self) : ScriptingRuntimeHelpers.CharToString((char)self);
break;
default:
throw PythonOps.ValueError("Unknown format code '{0}' for object of type 'int'", spec.TypeRepr);
}
if (self < 0 && digits[0] == '-') {
digits = digits.Substring(1);
}
return spec.AlignNumericText(digits, self == 0, self > 0);
}
public static Bytes to_bytes(Int32 value, int length, string byteorder, bool signed=false) {
// TODO: signed should be a keyword only argument
// TODO: should probably be moved to IntOps.Generated and included in all types
if (length < 0) throw PythonOps.ValueError("length argument must be non-negative");
if (!signed && value < 0) throw PythonOps.OverflowError("can't convert negative int to unsigned");
bool isLittle = byteorder == "little";
if (!isLittle && byteorder != "big") throw PythonOps.ValueError("byteorder must be either 'little' or 'big'");
var reqLength = (bit_length(value) + (value > 0 && signed ? 1 : 0) + 7) / 8;
if (reqLength > length) throw PythonOps.OverflowError("int too big to convert");
var bytes = new BigInteger(value).ToByteArray();
IEnumerable<byte> res = bytes;
if (length > bytes.Length) res = res.Concat(Enumerable.Repeat<byte>((value < 0) ? (byte)0xff : (byte)0, length - bytes.Length));
else if (length < bytes.Length) res = res.Take(length);
if (!isLittle) res = res.Reverse();
return Bytes.Make(res.ToArray());
}
[ClassMethod, StaticExtensionMethod]
public static object from_bytes(CodeContext context, PythonType type, object bytes, [NotNull] string byteorder, bool signed = false) {
// TODO: signed should be a keyword only argument
// TODO: merge with BigIntegerOps.from_bytes
bool isLittle = byteorder == "little";
if (!isLittle && byteorder != "big") throw PythonOps.ValueError("byteorder must be either 'little' or 'big'");
byte[] bytesArr = Bytes.FromObject(context, bytes).UnsafeByteArray;
if (bytesArr.Length == 0) return 0;
#if NETCOREAPP
var val = new BigInteger(bytesArr.AsSpan(), isUnsigned: !signed, isBigEndian: !isLittle);
#else
if (!isLittle) bytesArr = bytesArr.Reverse();
if (!signed && (bytesArr[bytesArr.Length - 1] & 0x80) == 0x80) Array.Resize(ref bytesArr, bytesArr.Length + 1);
var val = new BigInteger(bytesArr);
#endif
// prevents a TypeError: int.__new__(bool) is not safe
if (type == TypeCache.Boolean) return val == 0 ? ScriptingRuntimeHelpers.False : ScriptingRuntimeHelpers.True;
return __new__(context, type, val);
}
public static int __round__(int self) {
return self;
}
public static object __round__(int number, BigInteger ndigits) {
var result = BigIntegerOps.__round__(new BigInteger(number), ndigits);
if (result.AsInt32(out var ret)) {
return ret;
}
// this path can be hit when number is close to int.MaxValue and ndigits is negative,
// causing number to be rounded up and over int.MaxValue
return result;
}
public static object __round__(int self, object ndigits) {
var index = PythonOps.Index(ndigits);
switch (index) {
case int i:
return __round__(self, i);
case BigInteger bi:
return __round__(self, bi);
}
throw PythonOps.RuntimeError(
"Unreachable code was reached. "
+ "PythonOps.Index is guaranteed to either throw or return an integral value.");
}
[PythonHidden]
public static BigInteger ToBigInteger(this int self) {
return self;
}
private static string ToHex(int self, bool lowercase) {
string digits;
if (self != Int32.MinValue) {
int val = self;
if (self < 0) {
val = -self;
}
digits = val.ToString(lowercase ? "x" : "X", CultureInfo.InvariantCulture);
} else {
digits = "80000000";
}
return digits;
}
private static string ToOctal(int self, bool lowercase) {
string digits;
if (self == 0) {
digits = "0";
} else if (self != Int32.MinValue) {
int val = self;
if (self < 0) {
val = -self;
}
StringBuilder sbo = new StringBuilder();
for (int i = 30; i >= 0; i -= 3) {
char value = (char)('0' + (val >> i & 0x07));
if (value != '0' || sbo.Length > 0) {
sbo.Append(value);
}
}
digits = sbo.ToString();
} else {
digits = "20000000000";
}
return digits;
}
internal static string ToBinary(int self) {
if (self == Int32.MinValue) {
return "-0b10000000000000000000000000000000";
}
string res = ToBinary(self, true);
if (self < 0) {
res = "-" + res;
}
return res;
}
private static string ToBinary(int self, bool includeType) {
string digits;
if (self == 0) {
digits = "0";
} else if (self != Int32.MinValue) {
StringBuilder sbb = new StringBuilder();
int val = self;
if (self < 0) {
val = -self;
}
for (int i = 31; i >= 0; i--) {
if ((val & (1 << i)) != 0) {
sbb.Append('1');
} else if (sbb.Length != 0) {
sbb.Append('0');
}
}
digits = sbb.ToString();
} else {
digits = "10000000000000000000000000000000";
}
if (includeType) {
digits = "0b" + digits;
}
return digits;
}
}
}
| |
using Signum.Entities.Authorization;
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq.Expressions;
using Signum.Entities.Dynamic;
using Signum.Entities.Scheduler;
using Signum.Entities.Processes;
namespace Signum.Entities.Workflow
{
[Serializable, EntityKind(EntityKind.System, EntityData.Transactional), InTypeScript(Undefined = false)]
public class CaseActivityEntity : Entity
{
public CaseEntity Case { get; set; }
[ImplementedBy(typeof(WorkflowActivityEntity), typeof(WorkflowEventEntity))]
public IWorkflowNodeEntity WorkflowActivity { get; set; }
[StringLengthValidator(Min = 3, Max = 255)]
public string OriginalWorkflowActivityName { get; set; }
public DateTime StartDate { get; set; } = TimeZoneManager.Now;
public Lite<CaseActivityEntity>? Previous { get; set; }
[StringLengthValidator(MultiLine = true)]
public string? Note { get; set; }
public DateTime? DoneDate { get; set; }
[Unit("min")]
public double? Duration { get; set; }
[AutoExpressionField]
public double? DurationRealTime => As.Expression(() => Duration ?? (double?)(TimeZoneManager.Now - StartDate).TotalMinutes);
[AutoExpressionField]
public double? DurationRatio => As.Expression(() => Duration / ((WorkflowActivityEntity)WorkflowActivity).EstimatedDuration);
[AutoExpressionField]
public double? DurationRealTimeRatio => As.Expression(() => DurationRealTime / ((WorkflowActivityEntity)WorkflowActivity).EstimatedDuration);
public Lite<UserEntity>? DoneBy { get; set; }
public DoneType? DoneType { get; set; }
public ScriptExecutionEmbedded? ScriptExecution { get; set; }
static Expression<Func<CaseActivityEntity, CaseActivityState>> StateExpression =
@this => @this.DoneDate.HasValue ? CaseActivityState.Done :
(@this.WorkflowActivity is WorkflowEventEntity) ? CaseActivityState.PendingNext :
((WorkflowActivityEntity)@this.WorkflowActivity).Type == WorkflowActivityType.Decision ? CaseActivityState.PendingDecision :
CaseActivityState.PendingNext;
[ExpressionField("StateExpression")]
public CaseActivityState State
{
get
{
if (this.IsNew)
return CaseActivityState.New;
return StateExpression.Evaluate(this);
}
}
[AutoExpressionField]
public override string ToString() => As.Expression(() => WorkflowActivity + " " + DoneBy);
protected override void PreSaving(PreSavingContext ctx)
{
base.PreSaving(ctx);
this.Duration = this.DoneDate == null ? (double?)null :
(this.DoneDate.Value - this.StartDate).TotalMinutes;
}
}
[Serializable]
public class ScriptExecutionEmbedded : EmbeddedEntity
{
public DateTime NextExecution { get; set; }
public int RetryCount { get; set; }
public Guid? ProcessIdentifier { get; set; }
}
public enum DoneType
{
Next,
Approve,
Decline,
Jump,
Timeout,
ScriptSuccess,
ScriptFailure,
Recompose,
}
public enum CaseActivityState
{
[Ignore]
New,
PendingNext,
PendingDecision,
Done,
}
[AutoInit]
public static class CaseActivityOperation
{
public static readonly ConstructSymbol<CaseActivityEntity>.From<WorkflowEntity> CreateCaseActivityFromWorkflow;
public static readonly ConstructSymbol<CaseEntity>.From<WorkflowEventTaskEntity> CreateCaseFromWorkflowEventTask;
public static readonly ExecuteSymbol<CaseActivityEntity> Register;
public static readonly DeleteSymbol<CaseActivityEntity> Delete;
public static readonly ExecuteSymbol<CaseActivityEntity> Next;
public static readonly ExecuteSymbol<CaseActivityEntity> Approve;
public static readonly ExecuteSymbol<CaseActivityEntity> Decline;
public static readonly ExecuteSymbol<CaseActivityEntity> Jump;
public static readonly ExecuteSymbol<CaseActivityEntity> Timer;
public static readonly ExecuteSymbol<CaseActivityEntity> MarkAsUnread;
public static readonly ExecuteSymbol<CaseActivityEntity> Undo;
public static readonly ExecuteSymbol<CaseActivityEntity> ScriptExecute;
public static readonly ExecuteSymbol<CaseActivityEntity> ScriptScheduleRetry;
public static readonly ExecuteSymbol<CaseActivityEntity> ScriptFailureJump;
public static readonly ExecuteSymbol<DynamicTypeEntity> FixCaseDescriptions;
}
[AutoInit]
public static class CaseActivityTask
{
public static readonly SimpleTaskSymbol Timeout;
}
[AutoInit]
public static class CaseActivityProcessAlgorithm
{
public static readonly ProcessAlgorithmSymbol Timeout;
}
public enum CaseActivityMessage
{
CaseContainsOtherActivities,
NoNextConnectionThatSatisfiesTheConditionsFound,
[Description("Case is a decomposition of {0}")]
CaseIsADecompositionOf0,
[Description("From {0} on {1}")]
From0On1,
[Description("Done by {0} on {1}")]
DoneBy0On1,
PersonalRemarksForThisNotification,
[Description("The activity '{0}' requires to be opened")]
TheActivity0RequiresToBeOpened,
NoOpenedOrInProgressNotificationsFound,
NextActivityAlreadyInProgress,
NextActivityOfDecompositionSurrogateAlreadyInProgress,
[Description("Only '{0}' can undo this operation")]
Only0CanUndoThisOperation,
[Description("Activity '{0}' has no jumps")]
Activity0HasNoJumps,
[Description("Activity '{0}' has no timeout")]
Activity0HasNoTimers,
ThereIsNoPreviousActivity,
OnlyForScriptWorkflowActivities,
Pending,
NoWorkflowActivity,
[Description("Impossible to delete Case Activity {0} (on Workflow Activity '{1}') because has no previouos activity")]
ImpossibleToDeleteCaseActivity0OnWorkflowActivity1BecauseHasNoPreviousActivity,
LastCaseActivity,
CurrentUserHasNotification,
NoNewOrOpenedOrInProgressNotificationsFound,
NoActorsFoundToInsertCaseActivityNotifications,
ThereAreInprogressActivities,
}
public enum CaseActivityQuery
{
Inbox
}
[Serializable]
public class ActivityWithRemarks : ModelEntity
{
public Lite<WorkflowActivityEntity>? WorkflowActivity { get; set; }
public Lite<CaseEntity> Case { get; set; }
public Lite<CaseActivityEntity>? CaseActivity { get; set; }
public Lite<CaseNotificationEntity>? Notification { get; set; }
public string? Remarks { get; set; }
public int Alerts { get; set; }
public List<CaseTagTypeEntity> Tags { get; set; }
}
[Serializable, EntityKind(EntityKind.System, EntityData.Transactional)]
public class CaseActivityExecutedTimerEntity : Entity
{
public DateTime CreationDate { get; private set; } = TimeZoneManager.Now;
public Lite<CaseActivityEntity> CaseActivity { get; set; }
public Lite<WorkflowEventEntity> BoundaryEvent { get; set; }
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlSerializationGeneratedCode.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Serialization {
using System;
using System.IO;
using System.Collections;
using System.ComponentModel;
using System.Threading;
using System.Reflection;
using System.Security;
using System.Globalization;
/// <include file='doc\XmlSerializationGeneratedCode.uex' path='docs/doc[@for="XmlSerializationGeneratedCode"]/*' />
///<internalonly/>
public abstract class XmlSerializationGeneratedCode {
TempAssembly tempAssembly;
int threadCode;
ResolveEventHandler assemblyResolver;
internal void Init(TempAssembly tempAssembly) {
this.tempAssembly = tempAssembly;
// only hook the assembly resolver if we have something to help us do the resolution
if (tempAssembly != null && tempAssembly.NeedAssembyResolve) {
// we save the threadcode to make sure we don't handle any resolve events for any other threads
threadCode = Thread.CurrentThread.GetHashCode();
assemblyResolver = new ResolveEventHandler(OnAssemblyResolve);
AppDomain.CurrentDomain.AssemblyResolve += assemblyResolver;
}
}
// this method must be called at the end of serialization
internal void Dispose() {
if (assemblyResolver != null)
AppDomain.CurrentDomain.AssemblyResolve -= assemblyResolver;
assemblyResolver = null;
}
internal Assembly OnAssemblyResolve(object sender, ResolveEventArgs args) {
if (tempAssembly != null && Thread.CurrentThread.GetHashCode() == threadCode)
return tempAssembly.GetReferencedAssembly(args.Name);
return null;
}
}
internal class XmlSerializationCodeGen {
IndentedWriter writer;
int nextMethodNumber = 0;
Hashtable methodNames = new Hashtable();
ReflectionAwareCodeGen raCodeGen;
TypeScope[] scopes;
TypeDesc stringTypeDesc = null;
TypeDesc qnameTypeDesc = null;
string access;
string className;
TypeMapping[] referencedMethods;
int references = 0;
Hashtable generatedMethods = new Hashtable();
internal XmlSerializationCodeGen(IndentedWriter writer, TypeScope[] scopes, string access, string className) {
this.writer = writer;
this.scopes = scopes;
if (scopes.Length > 0) {
stringTypeDesc = scopes[0].GetTypeDesc(typeof(string));
qnameTypeDesc = scopes[0].GetTypeDesc(typeof(XmlQualifiedName));
}
this.raCodeGen = new ReflectionAwareCodeGen(writer);
this.className = className;
this.access = access;
}
internal IndentedWriter Writer { get { return writer; } }
internal int NextMethodNumber { get { return nextMethodNumber; } set { nextMethodNumber = value; } }
internal ReflectionAwareCodeGen RaCodeGen { get { return raCodeGen; } }
internal TypeDesc StringTypeDesc { get { return stringTypeDesc; } }
internal TypeDesc QnameTypeDesc { get { return qnameTypeDesc; } }
internal string ClassName { get { return className; } }
internal string Access { get { return access; } }
internal TypeScope[] Scopes { get { return scopes; } }
internal Hashtable MethodNames { get { return methodNames; } }
internal Hashtable GeneratedMethods { get { return generatedMethods; } }
internal virtual void GenerateMethod(TypeMapping mapping){}
internal void GenerateReferencedMethods() {
while(references > 0) {
TypeMapping mapping = referencedMethods[--references];
GenerateMethod(mapping);
}
}
internal string ReferenceMapping(TypeMapping mapping) {
if (!mapping.IsSoap) {
if (generatedMethods[mapping] == null) {
referencedMethods = EnsureArrayIndex(referencedMethods, references);
referencedMethods[references++] = mapping;
}
}
return (string)methodNames[mapping];
}
TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index) {
if (a == null) return new TypeMapping[32];
if (index < a.Length) return a;
TypeMapping[] b = new TypeMapping[a.Length + 32];
Array.Copy(a, b, index);
return b;
}
internal void WriteQuotedCSharpString(string value) {
raCodeGen.WriteQuotedCSharpString(value);
}
internal void GenerateHashtableGetBegin(string privateName, string publicName) {
writer.Write(typeof(Hashtable).FullName);
writer.Write(" ");
writer.Write(privateName);
writer.WriteLine(" = null;");
writer.Write("public override ");
writer.Write(typeof(Hashtable).FullName);
writer.Write(" ");
writer.Write(publicName);
writer.WriteLine(" {");
writer.Indent++;
writer.WriteLine("get {");
writer.Indent++;
writer.Write("if (");
writer.Write(privateName);
writer.WriteLine(" == null) {");
writer.Indent++;
writer.Write(typeof(Hashtable).FullName);
writer.Write(" _tmp = new ");
writer.Write(typeof(Hashtable).FullName);
writer.WriteLine("();");
}
internal void GenerateHashtableGetEnd(string privateName) {
writer.Write("if (");
writer.Write(privateName);
writer.Write(" == null) ");
writer.Write(privateName);
writer.WriteLine(" = _tmp;");
writer.Indent--;
writer.WriteLine("}");
writer.Write("return ");
writer.Write(privateName);
writer.WriteLine(";");
writer.Indent--;
writer.WriteLine("}");
writer.Indent--;
writer.WriteLine("}");
}
internal void GeneratePublicMethods(string privateName, string publicName, string[] methods, XmlMapping[] xmlMappings) {
GenerateHashtableGetBegin(privateName, publicName);
if (methods != null && methods.Length != 0 && xmlMappings != null && xmlMappings.Length == methods.Length) {
for (int i = 0; i < methods.Length; i++) {
if (methods[i] == null)
continue;
writer.Write("_tmp[");
WriteQuotedCSharpString(xmlMappings[i].Key);
writer.Write("] = ");
WriteQuotedCSharpString(methods[i]);
writer.WriteLine(";");
}
}
GenerateHashtableGetEnd(privateName);
}
internal void GenerateSupportedTypes(Type[] types) {
writer.Write("public override ");
writer.Write(typeof(bool).FullName);
writer.Write(" CanSerialize(");
writer.Write(typeof(Type).FullName);
writer.WriteLine(" type) {");
writer.Indent++;
Hashtable uniqueTypes = new Hashtable();
for (int i = 0; i < types.Length; i++) {
Type type = types[i];
if (type == null)
continue;
if (!type.IsPublic && !type.IsNestedPublic)
continue;
if (uniqueTypes[type] != null)
continue;
if (DynamicAssemblies.IsTypeDynamic(type))
continue;
if (type.IsGenericType || type.ContainsGenericParameters && DynamicAssemblies.IsTypeDynamic(type.GetGenericArguments()))
continue;
uniqueTypes[type] = type;
writer.Write("if (type == typeof(");
writer.Write(CodeIdentifier.GetCSharpName(type));
writer.WriteLine(")) return true;");
}
writer.WriteLine("return false;");
writer.Indent--;
writer.WriteLine("}");
}
internal string GenerateBaseSerializer(string baseSerializer, string readerClass, string writerClass, CodeIdentifiers classes) {
baseSerializer = CodeIdentifier.MakeValid(baseSerializer);
baseSerializer = classes.AddUnique(baseSerializer, baseSerializer);
writer.WriteLine();
writer.Write("public abstract class ");
writer.Write(CodeIdentifier.GetCSharpName(baseSerializer));
writer.Write(" : ");
writer.Write(typeof(XmlSerializer).FullName);
writer.WriteLine(" {");
writer.Indent++;
writer.Write("protected override ");
writer.Write(typeof(XmlSerializationReader).FullName);
writer.WriteLine(" CreateReader() {");
writer.Indent++;
writer.Write("return new ");
writer.Write(readerClass);
writer.WriteLine("();");
writer.Indent--;
writer.WriteLine("}");
writer.Write("protected override ");
writer.Write(typeof(XmlSerializationWriter).FullName);
writer.WriteLine(" CreateWriter() {");
writer.Indent++;
writer.Write("return new ");
writer.Write(writerClass);
writer.WriteLine("();");
writer.Indent--;
writer.WriteLine("}");
writer.Indent--;
writer.WriteLine("}");
return baseSerializer;
}
internal string GenerateTypedSerializer(string readMethod, string writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass) {
string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping.TypeDesc.Name));
serializerName = classes.AddUnique(serializerName + "Serializer", mapping);
writer.WriteLine();
writer.Write("public sealed class ");
writer.Write(CodeIdentifier.GetCSharpName(serializerName));
writer.Write(" : ");
writer.Write(baseSerializer);
writer.WriteLine(" {");
writer.Indent++;
writer.WriteLine();
writer.Write("public override ");
writer.Write(typeof(bool).FullName);
writer.Write(" CanDeserialize(");
writer.Write(typeof(XmlReader).FullName);
writer.WriteLine(" xmlReader) {");
writer.Indent++;
if (mapping.Accessor.Any) {
writer.WriteLine("return true;");
}
else {
writer.Write("return xmlReader.IsStartElement(");
WriteQuotedCSharpString(mapping.Accessor.Name);
writer.Write(", ");
WriteQuotedCSharpString(mapping.Accessor.Namespace);
writer.WriteLine(");");
}
writer.Indent--;
writer.WriteLine("}");
if (writeMethod != null) {
writer.WriteLine();
writer.Write("protected override void Serialize(object objectToSerialize, ");
writer.Write(typeof(XmlSerializationWriter).FullName);
writer.WriteLine(" writer) {");
writer.Indent++;
writer.Write("((");
writer.Write(writerClass);
writer.Write(")writer).");
writer.Write(writeMethod);
writer.Write("(");
if (mapping is XmlMembersMapping) {
writer.Write("(object[])");
}
writer.WriteLine("objectToSerialize);");
writer.Indent--;
writer.WriteLine("}");
}
if (readMethod != null) {
writer.WriteLine();
writer.Write("protected override object Deserialize(");
writer.Write(typeof(XmlSerializationReader).FullName);
writer.WriteLine(" reader) {");
writer.Indent++;
writer.Write("return ((");
writer.Write(readerClass);
writer.Write(")reader).");
writer.Write(readMethod);
writer.WriteLine("();");
writer.Indent--;
writer.WriteLine("}");
}
writer.Indent--;
writer.WriteLine("}");
return serializerName;
}
void GenerateTypedSerializers(Hashtable serializers) {
string privateName = "typedSerializers";
GenerateHashtableGetBegin(privateName, "TypedSerializers");
foreach (string key in serializers.Keys) {
writer.Write("_tmp.Add(");
WriteQuotedCSharpString(key);
writer.Write(", new ");
writer.Write((string)serializers[key]);
writer.WriteLine("());");
}
GenerateHashtableGetEnd("typedSerializers");
}
//GenerateGetSerializer(serializers, xmlMappings);
void GenerateGetSerializer(Hashtable serializers, XmlMapping[] xmlMappings) {
writer.Write("public override ");
writer.Write(typeof(XmlSerializer).FullName);
writer.Write(" GetSerializer(");
writer.Write(typeof(Type).FullName);
writer.WriteLine(" type) {");
writer.Indent++;
for (int i = 0; i < xmlMappings.Length; i++) {
if (xmlMappings[i] is XmlTypeMapping) {
Type type = xmlMappings[i].Accessor.Mapping.TypeDesc.Type;
if (type == null)
continue;
if (!type.IsPublic && !type.IsNestedPublic)
continue;
if (DynamicAssemblies.IsTypeDynamic(type))
continue;
if (type.IsGenericType || type.ContainsGenericParameters && DynamicAssemblies.IsTypeDynamic(type.GetGenericArguments()))
continue;
writer.Write("if (type == typeof(");
writer.Write(CodeIdentifier.GetCSharpName(type));
writer.Write(")) return new ");
writer.Write((string)serializers[xmlMappings[i].Key]);
writer.WriteLine("();");
}
}
writer.WriteLine("return null;");
writer.Indent--;
writer.WriteLine("}");
}
internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type[] types, string readerType, string[] readMethods, string writerType, string[] writerMethods, Hashtable serializers) {
writer.WriteLine();
writer.Write("public class XmlSerializerContract : global::");
writer.Write(typeof(XmlSerializerImplementation).FullName);
writer.WriteLine(" {");
writer.Indent++;
writer.Write("public override global::");
writer.Write(typeof(XmlSerializationReader).FullName);
writer.Write(" Reader { get { return new ");
writer.Write(readerType);
writer.WriteLine("(); } }");
writer.Write("public override global::");
writer.Write(typeof(XmlSerializationWriter).FullName);
writer.Write(" Writer { get { return new ");
writer.Write(writerType);
writer.WriteLine("(); } }");
GeneratePublicMethods("readMethods", "ReadMethods", readMethods, xmlMappings);
GeneratePublicMethods("writeMethods", "WriteMethods", writerMethods, xmlMappings);
GenerateTypedSerializers(serializers);
GenerateSupportedTypes(types);
GenerateGetSerializer(serializers, xmlMappings);
writer.Indent--;
writer.WriteLine("}");
}
internal static bool IsWildcard(SpecialMapping mapping) {
if (mapping is SerializableMapping)
return ((SerializableMapping)mapping).IsAny;
return mapping.TypeDesc.CanBeElementValue;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using NUnit.Framework;
namespace SequelocityDotNet.Tests.SQLite.DatabaseCommandExtensionsTests
{
[TestFixture]
public class ExecuteReaderTests
{
[Test]
public void Should_Call_The_DataRecordCall_Action_For_Each_Record_In_The_Result_Set()
{
// Arrange
const string sql = @"
CREATE TABLE IF NOT EXISTS SuperHero
(
SuperHeroId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
SuperHeroName NVARCHAR(120) NOT NULL,
UNIQUE(SuperHeroName)
);
INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Superman' );
INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Batman' );
SELECT SuperHeroId,
SuperHeroName
FROM SuperHero;
";
var list = new List<object>();
// Act
Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString )
.SetCommandText( sql )
.ExecuteReader( record =>
{
var obj = new
{
SuperHeroId = record.GetValue( 0 ),
SuperHeroName = record.GetValue( 1 )
};
list.Add( obj );
} );
// Assert
Assert.That( list.Count == 2 );
}
[Test]
public void Should_Null_The_DbCommand_By_Default()
{
// Arrange
const string sql = @"
CREATE TABLE IF NOT EXISTS SuperHero
(
SuperHeroId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
SuperHeroName NVARCHAR(120) NOT NULL,
UNIQUE(SuperHeroName)
);
INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Superman' );
INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Batman' );
SELECT SuperHeroId,
SuperHeroName
FROM SuperHero;
";
var databaseCommand = Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString )
.SetCommandText( sql );
var list = new List<object>();
// Act
databaseCommand.ExecuteReader( record =>
{
var obj = new
{
SuperHeroId = record.GetValue( 0 ),
SuperHeroName = record.GetValue( 1 )
};
list.Add( obj );
} );
// Assert
Assert.IsNull( databaseCommand.DbCommand );
}
[Test]
public void Should_Keep_The_Database_Connection_Open_If_keepConnectionOpen_Parameter_Was_True()
{
// Arrange
const string sql = @"
CREATE TABLE IF NOT EXISTS SuperHero
(
SuperHeroId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
SuperHeroName NVARCHAR(120) NOT NULL,
UNIQUE(SuperHeroName)
);
INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Superman' );
INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Batman' );
SELECT SuperHeroId,
SuperHeroName
FROM SuperHero;
";
var databaseCommand = Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString )
.SetCommandText( sql );
var list = new List<object>();
// Act
databaseCommand.ExecuteReader( record =>
{
var obj = new
{
SuperHeroId = record.GetValue( 0 ),
SuperHeroName = record.GetValue( 1 )
};
list.Add( obj );
}, true );
// Assert
Assert.That( databaseCommand.DbCommand.Connection.State == ConnectionState.Open );
// Cleanup
databaseCommand.Dispose();
}
[Test]
public void Should_Call_The_DatabaseCommandPreExecuteEventHandler()
{
// Arrange
bool wasPreExecuteEventHandlerCalled = false;
Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandPreExecuteEventHandlers.Add( command => wasPreExecuteEventHandlerCalled = true );
// Act
Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString )
.SetCommandText( "SELECT 1" )
.ExecuteReader( record => { } );
// Assert
Assert.IsTrue( wasPreExecuteEventHandlerCalled );
}
[Test]
public void Should_Call_The_DatabaseCommandPostExecuteEventHandler()
{
// Arrange
bool wasPostExecuteEventHandlerCalled = false;
Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandPostExecuteEventHandlers.Add( command => wasPostExecuteEventHandlerCalled = true );
// Act
Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString )
.SetCommandText( "SELECT 1" )
.ExecuteReader( record => { } );
// Assert
Assert.IsTrue( wasPostExecuteEventHandlerCalled );
}
[Test]
public void Should_Call_The_DatabaseCommandUnhandledExceptionEventHandler()
{
// Arrange
bool wasUnhandledExceptionEventHandlerCalled = false;
Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandUnhandledExceptionEventHandlers.Add( ( exception, command ) =>
{
wasUnhandledExceptionEventHandlerCalled = true;
} );
// Act
TestDelegate action = () => Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString )
.SetCommandText( "asdf;lkj" )
.ExecuteReader( record => { } );
// Assert
Assert.Throws<System.Data.SQLite.SQLiteException>( action );
Assert.IsTrue( wasUnhandledExceptionEventHandlerCalled );
}
}
[TestFixture]
public class ExecuteReader_Of_Type_T_Tests
{
[Test]
public void Should_Call_The_DataRecordCall_Func_For_Each_Record_In_The_Result_Set()
{
// Arrange
const string sql = @"
CREATE TABLE IF NOT EXISTS SuperHero
(
SuperHeroId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
SuperHeroName NVARCHAR(120) NOT NULL,
UNIQUE(SuperHeroName)
);
INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Superman' );
INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Batman' );
SELECT SuperHeroId,
SuperHeroName
FROM SuperHero;
";
List<object> list;
// Act
list = Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString )
.SetCommandText( sql )
.ExecuteReader<object>( record => new
{
SuperHeroId = record.GetValue( 0 ),
SuperHeroName = record.GetValue( 1 )
} )
.ToList();
// Assert
Assert.That( list.Count == 2 );
}
[Test]
public void Should_Null_The_DbCommand_By_Default()
{
// Arrange
const string sql = @"
CREATE TABLE IF NOT EXISTS SuperHero
(
SuperHeroId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
SuperHeroName NVARCHAR(120) NOT NULL,
UNIQUE(SuperHeroName)
);
INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Superman' );
INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Batman' );
SELECT SuperHeroId,
SuperHeroName
FROM SuperHero;
";
var databaseCommand = Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString )
.SetCommandText( sql );
List<object> list;
// Act
list = databaseCommand
.ExecuteReader<object>( record => new
{
SuperHeroId = record.GetValue( 0 ),
SuperHeroName = record.GetValue( 1 )
} )
.ToList();
// Assert
Assert.IsNull( databaseCommand.DbCommand );
}
[Test]
public void Should_Keep_The_Database_Connection_Open_If_keepConnectionOpen_Parameter_Was_True()
{
// Arrange
const string sql = @"
CREATE TABLE IF NOT EXISTS SuperHero
(
SuperHeroId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
SuperHeroName NVARCHAR(120) NOT NULL,
UNIQUE(SuperHeroName)
);
INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Superman' );
INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Batman' );
SELECT SuperHeroId,
SuperHeroName
FROM SuperHero;
";
var databaseCommand = Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString )
.SetCommandText( sql );
List<object> list;
// Act
list = databaseCommand
.ExecuteReader<object>( record => new
{
SuperHeroId = record.GetValue( 0 ),
SuperHeroName = record.GetValue( 1 )
}, true )
.ToList();
// Assert
Assert.That( databaseCommand.DbCommand.Connection.State == ConnectionState.Open );
// Cleanup
databaseCommand.Dispose();
}
[Test]
public void Should_Call_The_DatabaseCommandPreExecuteEventHandler()
{
// Arrange
bool wasPreExecuteEventHandlerCalled = false;
Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandPreExecuteEventHandlers.Add( command => wasPreExecuteEventHandlerCalled = true );
// Act
Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString )
.SetCommandText( "SELECT 1" )
.ExecuteReader<object>( record => new { } )
.ToList();
// Assert
Assert.IsTrue( wasPreExecuteEventHandlerCalled );
}
[Test]
public void Should_Call_The_DatabaseCommandPostExecuteEventHandler()
{
// Arrange
bool wasPostExecuteEventHandlerCalled = false;
Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandPostExecuteEventHandlers.Add( command => wasPostExecuteEventHandlerCalled = true );
// Act
Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString )
.SetCommandText( "SELECT 1" )
.ExecuteReader<object>( record => new { } )
.ToList();
// Assert
Assert.IsTrue( wasPostExecuteEventHandlerCalled );
}
[Test]
public void Should_Call_The_DatabaseCommandUnhandledExceptionEventHandler()
{
// Arrange
bool wasUnhandledExceptionEventHandlerCalled = false;
Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandUnhandledExceptionEventHandlers.Add( ( exception, command ) =>
{
wasUnhandledExceptionEventHandlerCalled = true;
} );
// Act
TestDelegate action = () => Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString )
.SetCommandText( "asdf;lkj" )
.ExecuteReader<object>( record => new { } )
.ToList();
// Assert
Assert.Throws<System.Data.SQLite.SQLiteException>( action );
Assert.IsTrue( wasUnhandledExceptionEventHandlerCalled );
}
[Test]
public void Should_Null_The_DbCommand_If_Iteration_Ends_Before_Full_Enumeration()
{
// Arrange
const string sql = @"
CREATE TABLE IF NOT EXISTS SuperHero
(
SuperHeroId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
SuperHeroName NVARCHAR(120) NOT NULL,
UNIQUE(SuperHeroName)
);
INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Superman' );
INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Batman' );
SELECT SuperHeroId,
SuperHeroName
FROM SuperHero;
";
var databaseCommand = Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString )
.SetCommandText( sql );
// Act
databaseCommand
.ExecuteReader( record => new
{
SuperHeroId = record.GetValue( 0 ),
SuperHeroName = record.GetValue( 1 )
} )
.First();
// Assert
Assert.IsNull( databaseCommand.DbCommand );
}
[Test]
public void Should_Null_The_DbCommand_If_Exception_Occurs_During_Iteration()
{
// Arrange
const string sql = @"
CREATE TABLE IF NOT EXISTS SuperHero
(
SuperHeroId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
SuperHeroName NVARCHAR(120) NOT NULL,
UNIQUE(SuperHeroName)
);
INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Superman' );
INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Batman' );
SELECT SuperHeroId,
SuperHeroName
FROM SuperHero;
";
var databaseCommand = Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString )
.SetCommandText( sql );
var iter = databaseCommand.ExecuteReader( record => new
{
SuperHeroId = record.GetValue( 0 ),
SuperHeroName = record.GetValue( 1 )
} );
// Act
try
{
foreach ( var item in iter )
{
throw new Exception( "Exception occured during iteration." );
}
}
catch { }
// Assert
Assert.IsNull( databaseCommand.DbCommand );
}
}
}
| |
/*
* 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.Reflection;
using System.Threading;
using log4net;
namespace OpenSim.Framework.Monitoring
{
/// <summary>
/// Manages various work items in the simulator.
/// </summary>
/// <remarks>
/// Currently, here work can be started
/// * As a long-running and monitored thread.
/// * In a thread that will never timeout but where the job is expected to eventually complete.
/// * In a threadpool thread that will timeout if it takes a very long time to complete (> 10 mins).
/// * As a job which will be run in a single-threaded job engine. Such jobs must not incorporate delays (sleeps,
/// network waits, etc.).
///
/// This is an evolving approach to better manage the work that OpenSimulator is asked to do from a very diverse
/// range of sources (client actions, incoming network, outgoing network calls, etc.).
///
/// Util.FireAndForget is still available to insert jobs in the threadpool, though this is equivalent to
/// WorkManager.RunInThreadPool().
/// </remarks>
public static class WorkManager
{
private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public static JobEngine JobEngine { get; private set; }
static WorkManager()
{
JobEngine = new JobEngine("Non-blocking non-critical job engine", "JOB ENGINE");
StatsManager.RegisterStat(
new Stat(
"JobsWaiting",
"Number of jobs waiting for processing.",
"",
"",
"server",
"jobengine",
StatType.Pull,
MeasuresOfInterest.None,
stat => stat.Value = JobEngine.JobsWaiting,
StatVerbosity.Debug));
MainConsole.Instance.Commands.AddCommand(
"Debug",
false,
"debug jobengine",
"debug jobengine <start|stop|status|log>",
"Start, stop, get status or set logging level of the job engine.",
"If stopped then all outstanding jobs are processed immediately.",
HandleControlCommand);
}
/// <summary>
/// Start a new long-lived thread.
/// </summary>
/// <param name="start">The method that will be executed in a new thread</param>
/// <param name="name">A name to give to the new thread</param>
/// <param name="priority">Priority to run the thread at</param>
/// <param name="isBackground">True to run this thread as a background thread, otherwise false</param>
/// <param name="alarmIfTimeout">Trigger an alarm function is we have timed out</param>
/// <param name="log">If true then creation of thread is logged.</param>
/// <returns>The newly created Thread object</returns>
public static Thread StartThread(
ThreadStart start, string name, ThreadPriority priority, bool isBackground, bool alarmIfTimeout, bool log = true)
{
return StartThread(start, name, priority, isBackground, alarmIfTimeout, null, Watchdog.DEFAULT_WATCHDOG_TIMEOUT_MS, log);
}
/// <summary>
/// Start a new thread that is tracked by the watchdog
/// </summary>
/// <param name="start">The method that will be executed in a new thread</param>
/// <param name="name">A name to give to the new thread</param>
/// <param name="priority">Priority to run the thread at</param>
/// <param name="isBackground">True to run this thread as a background
/// thread, otherwise false</param>
/// <param name="alarmIfTimeout">Trigger an alarm function is we have timed out</param>
/// <param name="alarmMethod">
/// Alarm method to call if alarmIfTimeout is true and there is a timeout.
/// Normally, this will just return some useful debugging information.
/// </param>
/// <param name="timeout">Number of milliseconds to wait until we issue a warning about timeout.</param>
/// <param name="log">If true then creation of thread is logged.</param>
/// <returns>The newly created Thread object</returns>
public static Thread StartThread(
ThreadStart start, string name, ThreadPriority priority, bool isBackground,
bool alarmIfTimeout, Func<string> alarmMethod, int timeout, bool log = true)
{
Thread thread = new Thread(start);
thread.Priority = priority;
thread.IsBackground = isBackground;
Watchdog.ThreadWatchdogInfo twi
= new Watchdog.ThreadWatchdogInfo(thread, timeout, name)
{ AlarmIfTimeout = alarmIfTimeout, AlarmMethod = alarmMethod };
Watchdog.AddThread(twi, name, log:log);
thread.Start();
thread.Name = name;
return thread;
}
/// <summary>
/// Run the callback in a new thread immediately. If the thread exits with an exception log it but do
/// not propogate it.
/// </summary>
/// <param name="callback">Code for the thread to execute.</param>
/// <param name="obj">Object to pass to the thread.</param>
/// <param name="name">Name of the thread</param>
public static void RunInThread(WaitCallback callback, object obj, string name, bool log = false)
{
if (Util.FireAndForgetMethod == FireAndForgetMethod.RegressionTest)
{
Culture.SetCurrentCulture();
callback(obj);
return;
}
ThreadStart ts = new ThreadStart(delegate()
{
try
{
Culture.SetCurrentCulture();
callback(obj);
Watchdog.RemoveThread(log:false);
}
catch (Exception e)
{
m_log.Error(string.Format("[WATCHDOG]: Exception in thread {0}.", name), e);
}
});
StartThread(ts, name, ThreadPriority.Normal, true, false, log:log);
}
/// <summary>
/// Run the callback via a threadpool thread.
/// </summary>
/// <remarks>
/// Such jobs may run after some delay but must always complete.
/// </remarks>
/// <param name="callback"></param>
/// <param name="obj"></param>
/// <param name="name">The name of the job. This is used in monitoring and debugging.</param>
public static void RunInThreadPool(System.Threading.WaitCallback callback, object obj, string name)
{
Util.FireAndForget(callback, obj, name);
}
/// <summary>
/// Run a job.
/// </summary>
/// <remarks>
/// This differs from direct scheduling (e.g. Util.FireAndForget) in that a job can be run in the job
/// engine if it is running, where all jobs are currently performed in sequence on a single thread. This is
/// to prevent observed overload and server freeze problems when there are hundreds of connections which all attempt to
/// perform work at once (e.g. in conference situations). With lower numbers of connections, the small
/// delay in performing jobs in sequence rather than concurrently has not been notiecable in testing, though a future more
/// sophisticated implementation could perform jobs concurrently when the server is under low load.
///
/// However, be advised that some callers of this function rely on all jobs being performed in sequence if any
/// jobs are performed in sequence (i.e. if jobengine is active or not). Therefore, expanding the jobengine
/// beyond a single thread will require considerable thought.
///
/// Also, any jobs submitted must be guaranteed to complete within a reasonable timeframe (e.g. they cannot
/// incorporate a network delay with a long timeout). At the moment, work that could suffer such issues
/// should still be run directly with RunInThread(), Util.FireAndForget(), etc. This is another area where
/// the job engine could be improved and so CPU utilization improved by better management of concurrency within
/// OpenSimulator.
/// </remarks>
/// <param name="jobType">General classification for the job (e.g. "RezAttachments").</param>
/// <param name="callback">Callback for job.</param>
/// <param name="obj">Object to pass to callback when run</param>
/// <param name="name">Specific name of job (e.g. "RezAttachments for Joe Bloggs"</param>
/// <param name="canRunInThisThread">If set to true then the job may be run in ths calling thread.</param>
/// <param name="mustNotTimeout">If the true then the job must never timeout.</param>
/// <param name="log">If set to true then extra logging is performed.</param>
public static void RunJob(
string jobType, WaitCallback callback, object obj, string name,
bool canRunInThisThread = false, bool mustNotTimeout = false,
bool log = false)
{
if (Util.FireAndForgetMethod == FireAndForgetMethod.RegressionTest)
{
Culture.SetCurrentCulture();
callback(obj);
return;
}
if (JobEngine.IsRunning)
JobEngine.QueueJob(name, () => callback(obj));
else if (canRunInThisThread)
callback(obj);
else if (mustNotTimeout)
RunInThread(callback, obj, name, log);
else
Util.FireAndForget(callback, obj, name);
}
private static void HandleControlCommand(string module, string[] args)
{
// if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene)
// return;
if (args.Length < 3)
{
MainConsole.Instance.Output("Usage: debug jobengine <stop|start|status|log>");
return;
}
string subCommand = args[2];
if (subCommand == "stop")
{
JobEngine.Stop();
MainConsole.Instance.OutputFormat("Stopped job engine.");
}
else if (subCommand == "start")
{
JobEngine.Start();
MainConsole.Instance.OutputFormat("Started job engine.");
}
else if (subCommand == "status")
{
MainConsole.Instance.OutputFormat("Job engine running: {0}", JobEngine.IsRunning);
JobEngine.Job job = JobEngine.CurrentJob;
MainConsole.Instance.OutputFormat("Current job {0}", job != null ? job.Name : "none");
MainConsole.Instance.OutputFormat(
"Jobs waiting: {0}", JobEngine.IsRunning ? JobEngine.JobsWaiting.ToString() : "n/a");
MainConsole.Instance.OutputFormat("Log Level: {0}", JobEngine.LogLevel);
}
else if (subCommand == "log")
{
if (args.Length < 4)
{
MainConsole.Instance.Output("Usage: debug jobengine log <level>");
return;
}
// int logLevel;
int logLevel = int.Parse(args[3]);
// if (ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, args[4], out logLevel))
// {
JobEngine.LogLevel = logLevel;
MainConsole.Instance.OutputFormat("Set debug log level to {0}", JobEngine.LogLevel);
// }
}
else
{
MainConsole.Instance.OutputFormat("Unrecognized job engine subcommand {0}", subCommand);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.DirectoryServices.ActiveDirectory
{
using System;
using System.Net;
using System.Security.Principal;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Security.Permissions;
using System.IO;
public enum DirectoryContextType
{
Domain = 0,
Forest = 1,
DirectoryServer = 2,
ConfigurationSet = 3,
ApplicationPartition = 4
}
public class DirectoryContext
{
private string _name = null;
private DirectoryContextType _contextType;
private NetworkCredential _credential = null;
internal string serverName = null;
internal bool usernameIsNull = false;
internal bool passwordIsNull = false;
private bool _validated = false;
private bool _contextIsValid = false;
internal static LoadLibrarySafeHandle ADHandle;
internal static LoadLibrarySafeHandle ADAMHandle;
#region constructors
[EnvironmentPermission(SecurityAction.Assert, Unrestricted = true)]
static DirectoryContext()
{
// load ntdsapi.dll for AD and ADAM
GetLibraryHandle();
}
// Internal Constructors
internal void InitializeDirectoryContext(DirectoryContextType contextType, string name, string username, string password)
{
_name = name;
_contextType = contextType;
_credential = new NetworkCredential(username, password);
if (username == null)
{
usernameIsNull = true;
}
if (password == null)
{
passwordIsNull = true;
}
}
internal DirectoryContext(DirectoryContextType contextType, string name, DirectoryContext context)
{
_name = name;
_contextType = contextType;
if (context != null)
{
_credential = context.Credential;
this.usernameIsNull = context.usernameIsNull;
this.passwordIsNull = context.passwordIsNull;
}
else
{
_credential = new NetworkCredential(null, "", null);
this.usernameIsNull = true;
this.passwordIsNull = true;
}
}
internal DirectoryContext(DirectoryContext context)
{
_name = context.Name;
_contextType = context.ContextType;
_credential = context.Credential;
this.usernameIsNull = context.usernameIsNull;
this.passwordIsNull = context.passwordIsNull;
if (context.ContextType != DirectoryContextType.ConfigurationSet)
{
//
// only for configurationset, we select a server, so we should not copy over that
// information, for all other types, this is either the same as name of the target or if the target is netbios name
// (for domain and forest) it could be the dns name. We should copy over this information.
//
this.serverName = context.serverName;
}
}
#endregion constructors
#region public constructors
public DirectoryContext(DirectoryContextType contextType)
{
//
// this constructor can only be called for DirectoryContextType.Forest or DirectoryContextType.Domain
// since all other types require the name to be specified
//
if (contextType != DirectoryContextType.Domain && contextType != DirectoryContextType.Forest)
{
throw new ArgumentException(SR.OnlyDomainOrForest, "contextType");
}
InitializeDirectoryContext(contextType, null, null, null);
}
public DirectoryContext(DirectoryContextType contextType, string name)
{
if (contextType < DirectoryContextType.Domain || contextType > DirectoryContextType.ApplicationPartition)
{
throw new InvalidEnumArgumentException("contextType", (int)contextType, typeof(DirectoryContextType));
}
if (name == null)
{
throw new ArgumentNullException("name");
}
if (name.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, "name");
}
InitializeDirectoryContext(contextType, name, null, null);
}
public DirectoryContext(DirectoryContextType contextType, string username, string password)
{
//
// this constructor can only be called for DirectoryContextType.Forest or DirectoryContextType.Domain
// since all other types require the name to be specified
//
if (contextType != DirectoryContextType.Domain && contextType != DirectoryContextType.Forest)
{
throw new ArgumentException(SR.OnlyDomainOrForest, "contextType");
}
InitializeDirectoryContext(contextType, null, username, password);
}
public DirectoryContext(DirectoryContextType contextType, string name, string username, string password)
{
if (contextType < DirectoryContextType.Domain || contextType > DirectoryContextType.ApplicationPartition)
{
throw new InvalidEnumArgumentException("contextType", (int)contextType, typeof(DirectoryContextType));
}
if (name == null)
{
throw new ArgumentNullException("name");
}
if (name.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, "name");
}
InitializeDirectoryContext(contextType, name, username, password);
}
#endregion public methods
#region public properties
public string Name
{
get
{
return _name;
}
}
public string UserName
{
get
{
if (usernameIsNull)
{
return null;
}
else
{
return _credential.UserName;
}
}
}
internal string Password
{
[SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
get
{
if (passwordIsNull)
{
return null;
}
else
{
return _credential.Password;
}
}
}
public DirectoryContextType ContextType
{
get
{
return _contextType;
}
}
internal NetworkCredential Credential
{
get
{
return _credential;
}
}
#endregion public properties
#region private methods
internal static bool IsContextValid(DirectoryContext context, DirectoryContextType contextType)
{
bool contextIsValid = false;
if ((contextType == DirectoryContextType.Domain) || ((contextType == DirectoryContextType.Forest) && (context.Name == null)))
{
string tmpTarget = context.Name;
if (tmpTarget == null)
{
// GetLoggedOnDomain returns the dns name of the logged on user's domain
context.serverName = GetLoggedOnDomain();
contextIsValid = true;
}
else
{
// check for domain
int errorCode = 0;
DomainControllerInfo domainControllerInfo;
errorCode = Locator.DsGetDcNameWrapper(null, tmpTarget, null, (long)PrivateLocatorFlags.DirectoryServicesRequired, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
// try with force rediscovery
errorCode = Locator.DsGetDcNameWrapper(null, tmpTarget, null, (long)PrivateLocatorFlags.DirectoryServicesRequired | (long)LocatorOptions.ForceRediscovery, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
contextIsValid = false;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
else
{
Debug.Assert(domainControllerInfo != null);
Debug.Assert(domainControllerInfo.DomainName != null);
context.serverName = domainControllerInfo.DomainName;
contextIsValid = true;
}
}
else if (errorCode == NativeMethods.ERROR_INVALID_DOMAIN_NAME_FORMAT)
{
// we can get this error if the target it server:port (not a valid domain)
contextIsValid = false;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
else
{
Debug.Assert(domainControllerInfo != null);
Debug.Assert(domainControllerInfo.DomainName != null);
context.serverName = domainControllerInfo.DomainName;
contextIsValid = true;
}
}
}
else if (contextType == DirectoryContextType.Forest)
{
Debug.Assert(context.Name != null);
// check for forest
int errorCode = 0;
DomainControllerInfo domainControllerInfo;
errorCode = Locator.DsGetDcNameWrapper(null, context.Name, null, (long)(PrivateLocatorFlags.GCRequired | PrivateLocatorFlags.DirectoryServicesRequired), out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
// try with force rediscovery
errorCode = Locator.DsGetDcNameWrapper(null, context.Name, null, (long)((PrivateLocatorFlags.GCRequired | PrivateLocatorFlags.DirectoryServicesRequired)) | (long)LocatorOptions.ForceRediscovery, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
contextIsValid = false;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
else
{
Debug.Assert(domainControllerInfo != null);
Debug.Assert(domainControllerInfo.DnsForestName != null);
context.serverName = domainControllerInfo.DnsForestName;
contextIsValid = true;
}
}
else if (errorCode == NativeMethods.ERROR_INVALID_DOMAIN_NAME_FORMAT)
{
// we can get this error if the target it server:port (not a valid forest)
contextIsValid = false;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
else
{
Debug.Assert(domainControllerInfo != null);
Debug.Assert(domainControllerInfo.DnsForestName != null);
context.serverName = domainControllerInfo.DnsForestName;
contextIsValid = true;
}
}
else if (contextType == DirectoryContextType.ApplicationPartition)
{
Debug.Assert(context.Name != null);
// check for application partition
int errorCode = 0;
DomainControllerInfo domainControllerInfo;
errorCode = Locator.DsGetDcNameWrapper(null, context.Name, null, (long)PrivateLocatorFlags.OnlyLDAPNeeded, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
// try with force rediscovery
errorCode = Locator.DsGetDcNameWrapper(null, context.Name, null, (long)PrivateLocatorFlags.OnlyLDAPNeeded | (long)LocatorOptions.ForceRediscovery, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
contextIsValid = false;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
else
{
contextIsValid = true;
}
}
else if (errorCode == NativeMethods.ERROR_INVALID_DOMAIN_NAME_FORMAT)
{
// we can get this error if the target it server:port (not a valid application partition)
contextIsValid = false;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
else
{
contextIsValid = true;
}
}
else if (contextType == DirectoryContextType.DirectoryServer)
{
//
// if the servername contains a port number, then remove that
//
string tempServerName = null;
string portNumber;
tempServerName = Utils.SplitServerNameAndPortNumber(context.Name, out portNumber);
//
// this will validate that the name specified in the context is truely the name of a machine (and not of a domain)
//
DirectoryEntry de = new DirectoryEntry("WinNT://" + tempServerName + ",computer", context.UserName, context.Password, Utils.DefaultAuthType);
try
{
de.Bind(true);
contextIsValid = true;
}
catch (COMException e)
{
if ((e.ErrorCode == unchecked((int)0x80070035)) || (e.ErrorCode == unchecked((int)0x80070033)) || (e.ErrorCode == unchecked((int)0x80005000)))
{
// if this returns bad network path
contextIsValid = false;
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
finally
{
de.Dispose();
}
}
else
{
// no special validation for ConfigurationSet
contextIsValid = true;
}
return contextIsValid;
}
internal bool isRootDomain()
{
if (_contextType != DirectoryContextType.Forest)
return false;
if (!_validated)
{
_contextIsValid = IsContextValid(this, DirectoryContextType.Forest);
_validated = true;
}
return _contextIsValid;
}
internal bool isDomain()
{
if (_contextType != DirectoryContextType.Domain)
return false;
if (!_validated)
{
_contextIsValid = IsContextValid(this, DirectoryContextType.Domain);
_validated = true;
}
return _contextIsValid;
}
internal bool isNdnc()
{
if (_contextType != DirectoryContextType.ApplicationPartition)
return false;
if (!_validated)
{
_contextIsValid = IsContextValid(this, DirectoryContextType.ApplicationPartition);
_validated = true;
}
return _contextIsValid;
}
internal bool isServer()
{
if (_contextType != DirectoryContextType.DirectoryServer)
return false;
if (!_validated)
{
_contextIsValid = IsContextValid(this, DirectoryContextType.DirectoryServer);
_validated = true;
}
return _contextIsValid;
}
internal bool isADAMConfigSet()
{
if (_contextType != DirectoryContextType.ConfigurationSet)
return false;
if (!_validated)
{
_contextIsValid = IsContextValid(this, DirectoryContextType.ConfigurationSet);
_validated = true;
}
return _contextIsValid;
}
//
// this method is called when the forest name is explicitly specified
// and we want to check if that matches the current logged on forest
//
internal bool isCurrentForest()
{
bool result = false;
Debug.Assert(_name != null);
DomainControllerInfo domainControllerInfo = Locator.GetDomainControllerInfo(null, _name, null, (long)(PrivateLocatorFlags.DirectoryServicesRequired | PrivateLocatorFlags.ReturnDNSName));
DomainControllerInfo currentDomainControllerInfo;
string loggedOnDomain = GetLoggedOnDomain();
int errorCode = Locator.DsGetDcNameWrapper(null, loggedOnDomain, null, (long)(PrivateLocatorFlags.DirectoryServicesRequired | PrivateLocatorFlags.ReturnDNSName), out currentDomainControllerInfo);
if (errorCode == 0)
{
Debug.Assert(domainControllerInfo.DnsForestName != null);
Debug.Assert(currentDomainControllerInfo.DnsForestName != null);
result = (Utils.Compare(domainControllerInfo.DnsForestName, currentDomainControllerInfo.DnsForestName) == 0);
}
//
// if there is no forest associated with the logged on domain, then we return false
//
else if (errorCode != NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
return result;
}
internal bool useServerBind()
{
return ((ContextType == DirectoryContextType.DirectoryServer) || (ContextType == DirectoryContextType.ConfigurationSet));
}
internal string GetServerName()
{
if (serverName == null)
{
switch (_contextType)
{
case DirectoryContextType.ConfigurationSet:
{
AdamInstance adamInst = ConfigurationSet.FindAnyAdamInstance(this);
try
{
serverName = adamInst.Name;
}
finally
{
adamInst.Dispose();
}
break;
}
case DirectoryContextType.Domain:
case DirectoryContextType.Forest:
{
//
// if the target is not specified OR
// if the forest name was explicitly specified and the forest is the same as the current forest
// we want to find a DC in the current domain
//
if ((_name == null) || ((_contextType == DirectoryContextType.Forest) && (isCurrentForest())))
{
serverName = GetLoggedOnDomain();
}
else
{
serverName = GetDnsDomainName(_name);
}
break;
}
case DirectoryContextType.ApplicationPartition:
{
// if this is an appNC the target should not be null
Debug.Assert(_name != null);
serverName = _name;
break;
}
case DirectoryContextType.DirectoryServer:
{
// this should not happen (We should have checks for this earlier itself)
Debug.Assert(_name != null);
serverName = _name;
break;
}
default:
{
Debug.Fail("DirectoryContext::GetServerName - Unknown contextType");
break;
}
}
}
return serverName;
}
internal static string GetLoggedOnDomain()
{
string domainName = null;
NegotiateCallerNameRequest requestBuffer = new NegotiateCallerNameRequest();
int requestBufferLength = (int)Marshal.SizeOf(requestBuffer);
IntPtr pResponseBuffer = IntPtr.Zero;
NegotiateCallerNameResponse responseBuffer = new NegotiateCallerNameResponse();
int responseBufferLength;
int protocolStatus;
int result;
LsaLogonProcessSafeHandle lsaHandle;
//
// since we are using safe handles, we don't need to explicitly call NativeMethods.LsaDeregisterLogonProcess(lsaHandle)
//
result = NativeMethods.LsaConnectUntrusted(out lsaHandle);
if (result == 0)
{
//
// initialize the request buffer
//
requestBuffer.messageType = NativeMethods.NegGetCallerName;
result = NativeMethods.LsaCallAuthenticationPackage(lsaHandle, 0, requestBuffer, requestBufferLength, out pResponseBuffer, out responseBufferLength, out protocolStatus);
try
{
if (result == 0 && protocolStatus == 0)
{
Marshal.PtrToStructure(pResponseBuffer, responseBuffer);
//
// callerName is of the form domain\username
//
Debug.Assert((responseBuffer.callerName != null), "NativeMethods.LsaCallAuthenticationPackage returned null callerName.");
int index = responseBuffer.callerName.IndexOf('\\');
Debug.Assert((index != -1), "NativeMethods.LsaCallAuthenticationPackage returned callerName not in domain\\username format.");
domainName = responseBuffer.callerName.Substring(0, index);
}
else
{
if (result == NativeMethods.STATUS_QUOTA_EXCEEDED)
{
throw new OutOfMemoryException();
}
else if ((result == 0) && (UnsafeNativeMethods.LsaNtStatusToWinError(protocolStatus) == NativeMethods.ERROR_NO_SUCH_LOGON_SESSION))
{
// If this is a directory user, extract domain info from username
if (!Utils.IsSamUser())
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
int index = identity.Name.IndexOf('\\');
Debug.Assert(index != -1);
domainName = identity.Name.Substring(0, index);
}
}
else
{
throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError((result != 0) ? result : protocolStatus));
}
}
}
finally
{
if (pResponseBuffer != IntPtr.Zero)
{
NativeMethods.LsaFreeReturnBuffer(pResponseBuffer);
}
}
}
else if (result == NativeMethods.STATUS_QUOTA_EXCEEDED)
{
throw new OutOfMemoryException();
}
else
{
throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result));
}
// If we're running as a local user (i.e. NT AUTHORITY\LOCAL SYSTEM, IIS APPPOOL\APPPoolIdentity, etc.),
// domainName will be null and we fall back to the machine's domain
domainName = GetDnsDomainName(domainName);
if (domainName == null)
{
//
// we should never get to this point here since we should have already verified that the context is valid
// by the time we get to this point
//
throw new ActiveDirectoryOperationException(SR.ContextNotAssociatedWithDomain);
}
return domainName;
}
internal static string GetDnsDomainName(string domainName)
{
DomainControllerInfo domainControllerInfo;
int errorCode = 0;
//
// Locator.DsGetDcNameWrapper internally passes the ReturnDNSName flag when calling DsGetDcName
//
errorCode = Locator.DsGetDcNameWrapper(null, domainName, null, (long)PrivateLocatorFlags.DirectoryServicesRequired, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
// try again with force rediscovery
errorCode = Locator.DsGetDcNameWrapper(null, domainName, null, (long)((long)PrivateLocatorFlags.DirectoryServicesRequired | (long)LocatorOptions.ForceRediscovery), out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
return null;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
Debug.Assert(domainControllerInfo != null);
Debug.Assert(domainControllerInfo.DomainName != null);
return domainControllerInfo.DomainName;
}
[EnvironmentPermission(SecurityAction.Assert, Unrestricted = true)]
private static void GetLibraryHandle()
{
// first get AD handle
string systemPath = Environment.SystemDirectory;
IntPtr tempHandle = UnsafeNativeMethods.LoadLibrary(systemPath + "\\ntdsapi.dll");
if (tempHandle == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
else
{
ADHandle = new LoadLibrarySafeHandle(tempHandle);
}
// not get the ADAM handle
// got to the windows\adam directory
DirectoryInfo windowsDirectory = Directory.GetParent(systemPath);
tempHandle = UnsafeNativeMethods.LoadLibrary(windowsDirectory.FullName + "\\ADAM\\ntdsapi.dll");
if (tempHandle == (IntPtr)0)
{
ADAMHandle = ADHandle;
}
else
{
ADAMHandle = new LoadLibrarySafeHandle(tempHandle);
}
}
#endregion private methods
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Net.Test.Common;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Security.Tests
{
[PlatformSpecific(PlatformID.Windows)] // NegotiateStream only supports client-side functionality on Unix
public abstract class NegotiateStreamStreamToStreamTest
{
private readonly byte[] _sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message");
protected abstract Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName);
protected abstract Task AuthenticateAsServerAsync(NegotiateStream server);
[OuterLoop] // TODO: Issue #11345
[Fact]
public void NegotiateStream_StreamToStream_Authentication_Success()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty);
auth[1] = AuthenticateAsServerAsync(server);
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(false, serverIdentity.IsAuthenticated);
Assert.Equal("", serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertIsCurrentIdentity(clientIdentity);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void NegotiateStream_StreamToStream_Authentication_TargetName_Success()
{
string targetName = "testTargetName";
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, targetName);
auth[1] = AuthenticateAsServerAsync(server);
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(true, serverIdentity.IsAuthenticated);
Assert.Equal(targetName, serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertIsCurrentIdentity(clientIdentity);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void NegotiateStream_StreamToStream_Authentication_EmptyCredentials_Fails()
{
string targetName = "testTargetName";
// Ensure there is no confusion between DefaultCredentials / DefaultNetworkCredentials and a
// NetworkCredential object with empty user, password and domain.
NetworkCredential emptyNetworkCredential = new NetworkCredential("", "", "");
Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultCredentials);
Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultNetworkCredentials);
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, emptyNetworkCredential, targetName);
auth[1] = AuthenticateAsServerAsync(server);
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(true, serverIdentity.IsAuthenticated);
Assert.Equal(targetName, serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
// TODO #5241: Behavior difference:
Assert.Equal(false, clientIdentity.IsAuthenticated);
// On .Net Desktop: Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertHasName(clientIdentity, @"NT AUTHORITY\ANONYMOUS LOGON");
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void NegotiateStream_StreamToStream_Successive_ClientWrite_Sync_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty);
auth[1] = AuthenticateAsServerAsync(server);
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
client.Write(_sampleMsg, 0, _sampleMsg.Length);
server.Read(recvBuf, 0, _sampleMsg.Length);
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
client.Write(_sampleMsg, 0, _sampleMsg.Length);
server.Read(recvBuf, 0, _sampleMsg.Length);
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void NegotiateStream_StreamToStream_Successive_ClientWrite_Async_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty);
auth[1] = AuthenticateAsServerAsync(server);
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
auth[0] = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
auth[1] = server.ReadAsync(recvBuf, 0, _sampleMsg.Length);
finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Send/receive completed in the allotted time");
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
auth[0] = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
auth[1] = server.ReadAsync(recvBuf, 0, _sampleMsg.Length);
finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Send/receive completed in the allotted time");
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
}
}
}
public sealed class NegotiateStreamStreamToStreamTest_Async : NegotiateStreamStreamToStreamTest
{
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) =>
client.AuthenticateAsClientAsync(credential, targetName);
protected override Task AuthenticateAsServerAsync(NegotiateStream server) =>
server.AuthenticateAsServerAsync();
}
public sealed class NegotiateStreamStreamToStreamTest_BeginEnd : NegotiateStreamStreamToStreamTest
{
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) =>
Task.Factory.FromAsync(client.BeginAuthenticateAsClient, client.EndAuthenticateAsClient, credential, targetName, null);
protected override Task AuthenticateAsServerAsync(NegotiateStream server) =>
Task.Factory.FromAsync(server.BeginAuthenticateAsServer, server.EndAuthenticateAsServer, null);
}
public sealed class NegotiateStreamStreamToStreamTest_Sync : NegotiateStreamStreamToStreamTest
{
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) =>
Task.Run(() => client.AuthenticateAsClient(credential, targetName));
protected override Task AuthenticateAsServerAsync(NegotiateStream server) =>
Task.Run(() => server.AuthenticateAsServerAsync());
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Axiom.Core;
using Axiom.Utility;
namespace Axiom.Graphics {
/// <summary>
/// Class representing an approach to rendering a particular Material.
/// </summary>
/// <remarks>
/// The engine will attempt to use the best technique supported by the active hardware,
/// unless you specifically request a lower detail technique (say for distant rendering)
/// </remarks>
public class Technique {
#region Fields
/// <summary>
/// The material that owns this technique.
/// </summary>
protected Material parent;
/// <summary>
/// The list of passes (fixed function or programmable) contained in this technique.
/// </summary>
protected PassList passes = new PassList();
/// <summary>
/// List of derived passes, categorized (and ordered) into illumination stages.
/// </summary>
protected ArrayList illuminationPasses = new ArrayList();
/// <summary>
/// Flag that states whether or not this technique is supported on the current hardware.
/// </summary>
protected bool isSupported;
/// <summary>
/// Name of this technique.
/// </summary>
protected string name;
/// <summary>
/// Level of detail index for this technique.
/// </summary>
protected int lodIndex;
/// <summary>
/// Scheme index, derived from scheme name but the names are held on
/// MaterialManager, for speed an index is used here.
/// </summary>
protected int schemeIndex;
/// <summary>
/// Compilation state for illumination passes
/// </summary>
protected IlluminationPassesState illuminationPassesCompilationPhase;
#endregion
#region Constructors
public Technique(Material parent) {
this.parent = parent;
this.illuminationPassesCompilationPhase = IlluminationPassesState.NotCompiled;
this.schemeIndex = 0;
}
#endregion
#region Methods
/// <summary>
/// Internal method for clearing the illumination pass list.
/// </summary>
protected void ClearIlluminationPasses() {
for(int i = 0; i < illuminationPasses.Count; i++) {
IlluminationPass iPass = (IlluminationPass)illuminationPasses[i];
if(iPass.DestroyOnShutdown) {
iPass.Pass.QueueForDeletion();
}
}
illuminationPasses.Clear();
}
/// <summary>
/// Clones this Technique.
/// </summary>
/// <param name="parent">Material that will own this technique.</param>
/// <returns></returns>
public Technique Clone(Material parent) {
Technique newTechnique = new Technique(parent);
CopyTo(newTechnique);
return newTechnique;
}
/// <summary>
/// Copy the details of this Technique to another.
/// </summary>
/// <param name="target"></param>
public void CopyTo(Technique target) {
target.name = name;
target.isSupported = isSupported;
target.lodIndex = lodIndex;
target.schemeIndex = schemeIndex;
target.RemoveAllPasses();
// clone each pass and add that to the new technique
for(int i = 0; i < passes.Count; i++) {
Pass pass = (Pass)passes[i];
Pass newPass = pass.Clone(target, pass.Index);
target.passes.Add(newPass);
}
// Compile for categorised illumination on demand
target.ClearIlluminationPasses();
target.illuminationPassesCompilationPhase = IlluminationPassesState.NotCompiled;
}
/// <summary>
/// Compilation method for Techniques. See <see cref="Axiom.Core.Material"/>
/// </summary>
/// <param name="autoManageTextureUnits">
/// Determines whether or not the engine should split up extra texture unit requests
/// into extra passes if the hardware does not have enough available units.
/// </param>
internal string Compile(bool autoManageTextureUnits) {
string compileErrors;
// assume not supported unless it proves otherwise
isSupported = false;
// grab a ref to the current hardware caps
HardwareCaps caps = Root.Instance.RenderSystem.Caps;
int numAvailTexUnits = caps.TextureUnitCount;
// check requirements for each pass
for(int i = 0; i < passes.Count; i++) {
Pass pass = (Pass)passes[i];
bool tooManyTextures = false;
int numTexUnitsRequested = pass.NumTextureUnitStages;
if(pass.HasFragmentProgram) {
// check texture units
// check fragment program version
if (!pass.FragmentProgram.IsSupported)
{
// can't do this one
tooManyTextures = true;
}
else
{
numAvailTexUnits = pass.FragmentProgram.SamplerCount;
if (numTexUnitsRequested > numAvailTexUnits)
{
// can't do this, since programmable passes cannot be split automatically
tooManyTextures = true;
}
}
}
else {
if(numTexUnitsRequested > numAvailTexUnits) {
if (!autoManageTextureUnits)
tooManyTextures = true;
else if (pass.HasVertexProgram) {
tooManyTextures = true;
}
}
if (tooManyTextures) {
// Can't do this one
compileErrors = "Pass " + i +
": Too many texture units for the current hardware and " +
"cannot split programmable passes.";
return compileErrors;
}
}
if (pass.HasVertexProgram) {
// Check vertex program version
if (!pass.VertexProgram.IsSupported) {
// Can't do this one
compileErrors = "Pass " + i +
": Vertex program " + pass.VertexProgram.Name +
" cannot be used - ";
if (pass.VertexProgram.HasCompileError)
compileErrors += "compile error.";
else
compileErrors += "not supported.";
return compileErrors;
}
}
if(pass.HasFragmentProgram) {
// check texture units
// check fragment program version
if (!pass.FragmentProgram.IsSupported)
{
// can't do this one
compileErrors = "Pass " + i +
": Fragment program " + pass.FragmentProgram.Name +
" cannot be used - ";
if (pass.FragmentProgram.HasCompileError)
compileErrors += "compile error.";
else
compileErrors += "not supported.";
return compileErrors;
}
}
else {
// check support for a few fixed function options while we are here
for(int j = 0; j < pass.NumTextureUnitStages; j++) {
TextureUnitState texUnit = pass.GetTextureUnitState(j);
// check to make sure we have some cube mapping support
if(texUnit.Is3D && !caps.CheckCap(Capabilities.CubeMapping)) {
compileErrors = "Pass " + i + " Tex " + texUnit +
": Cube maps not supported by current environment.";
return compileErrors;
}
// Any 3D textures? NB we make the assumption that any
// card capable of running fragment programs can support
// 3D textures, which has to be true, surely?
if (texUnit.TextureType == TextureType.ThreeD && !caps.CheckCap(Capabilities.Texture3D)) {
// Fail
compileErrors = "Pass " + i + " Tex " + texUnit +
": Volume textures not supported by current environment.";
return compileErrors;
}
// if this is a Dot3 blending layer, make sure we can support it
if(texUnit.ColorBlendMode.operation == LayerBlendOperationEx.DotProduct && !caps.CheckCap(Capabilities.Dot3)) {
compileErrors = "Pass " + i + " Tex " + texUnit +
": DOT3 blending not supported by current environment.";
return compileErrors;
}
}
// keep splitting until the texture units required for this pass are available
// Note: Split will call Technique.CreatePass,
// which adds the new pass to the end of the list
// of passes. Is that always the right behavior?
while(numTexUnitsRequested > numAvailTexUnits) {
// split this pass up into more passes
pass = pass.Split(numAvailTexUnits);
numTexUnitsRequested = pass.NumTextureUnitStages;
}
}
} // for
// if we made it this far, we are good to go!
isSupported = true;
// CompileIlluminationPasses() used to be called here, but it is now done on
// demand since it the illumination passes are only needed for additive shadows
// and we (multiverse) don't use them.
// Now compile for categorised illumination, in case we need it later
// Compile for categorised illumination on demand
ClearIlluminationPasses();
illuminationPassesCompilationPhase = IlluminationPassesState.NotCompiled;
return "";
}
/// <summary>
/// Compile the illumination states if necessary
/// </summary>
protected void AssureIlluminationPassesCompiled() {
IlluminationPassesState targetState = IlluminationPassesState.Compiled;
if (illuminationPassesCompilationPhase != targetState) {
// prevents parent.NotifyNeedsRecompile() call during compile
illuminationPassesCompilationPhase = IlluminationPassesState.CompileDisabled;
// Splitting the passes into illumination passes
CompileIlluminationPasses();
// Mark that illumination passes compilation finished
illuminationPassesCompilationPhase = targetState;
}
}
/// <summary>
/// Internal method for splitting the passes into illumination passes.
/// </summary>
public void CompileIlluminationPasses() {
ClearIlluminationPasses();
// don't need to split transparent passes since they are rendered seperately
if(this.IsTransparent) {
return;
}
// start off with ambient passes
IlluminationStage stage = IlluminationStage.Ambient;
bool hasAmbient = false;
for(int i = 0; i < passes.Count; /* increment in logic */) {
Pass pass = (Pass)passes[i];
IlluminationPass iPass;
switch(stage) {
case IlluminationStage.Ambient:
// keep looking for ambient only
if(pass.IsAmbientOnly) {
iPass = new IlluminationPass();
iPass.OriginalPass = pass;
iPass.Pass = pass;
iPass.Stage = stage;
illuminationPasses.Add(iPass);
hasAmbient = true;
// progress to the next pass
i++;
}
else {
// split off any ambient part
if(pass.Ambient.CompareTo(ColorEx.Black) != 0 ||
pass.Emissive.CompareTo(ColorEx.Black) != 0 ||
pass.AlphaRejectFunction != CompareFunction.AlwaysPass) {
Pass newPass = new Pass(this, pass.Index);
pass.CopyTo(newPass);
if (newPass.AlphaRejectFunction != CompareFunction.AlwaysPass) {
// Alpha rejection passes must retain their transparency, so
// we allow the texture units, but override the colour functions
for (int tindex = 0; tindex < newPass.NumTextureUnitStages; tindex++)
{
TextureUnitState tus = newPass.GetTextureUnitState(tindex);
tus.SetColorOperationEx(LayerBlendOperationEx.Source1, LayerBlendSource.Current, LayerBlendSource.Current);
}
}
else
// remove any texture units
newPass.RemoveAllTextureUnitStates();
// also remove any fragment program
if(newPass.HasFragmentProgram) {
newPass.SetFragmentProgram("");
}
// We have to leave vertex program alone (if any) and
// just trust that the author is using light bindings, which
// we will ensure there are none in the ambient pass
newPass.Diffuse = new ColorEx(newPass.Diffuse.a, 0f, 0f, 0f); // Preserving alpha
newPass.Specular = ColorEx.Black;
// Calculate hash value for new pass, because we are compiling
// illumination passes on demand, which will loss hash calculate
// before it add to render queue first time.
newPass.RecalculateHash();
iPass = new IlluminationPass();
iPass.DestroyOnShutdown = true;
iPass.OriginalPass = pass;
iPass.Pass = newPass;
iPass.Stage = stage;
illuminationPasses.Add(iPass);
hasAmbient = true;
}
if(!hasAmbient) {
// make up a new basic pass
Pass newPass = new Pass(this, pass.Index);
pass.CopyTo(newPass);
newPass.Ambient = ColorEx.Black;
newPass.Diffuse = ColorEx.Black;
// Calculate hash value for new pass, because we are compiling
// illumination passes on demand, which will loss hash calculate
// before it add to render queue first time.
newPass.RecalculateHash();
iPass = new IlluminationPass();
iPass.DestroyOnShutdown = true;
iPass.OriginalPass = pass;
iPass.Pass = newPass;
iPass.Stage = stage;
illuminationPasses.Add(iPass);
hasAmbient = true;
}
// this means we are done with ambients, progress to per-light
stage = IlluminationStage.PerLight;
}
break;
case IlluminationStage.PerLight:
if(pass.RunOncePerLight) {
// if this is per-light already, use it directly
iPass = new IlluminationPass();
iPass.DestroyOnShutdown = false;
iPass.OriginalPass = pass;
iPass.Pass = pass;
iPass.Stage = stage;
illuminationPasses.Add(iPass);
// progress to the next pass
i++;
}
else {
// split off per-light details (can only be done for one)
if(pass.LightingEnabled &&
(pass.Diffuse.CompareTo(ColorEx.Black) != 0 ||
pass.Specular.CompareTo(ColorEx.Black) != 0)) {
// copy existing pass
Pass newPass = new Pass(this, pass.Index);
pass.CopyTo(newPass);
if (newPass.AlphaRejectFunction != CompareFunction.AlwaysPass) {
// Alpha rejection passes must retain their transparency, so
// we allow the texture units, but override the colour functions
for (int tindex = 0; tindex < newPass.NumTextureUnitStages; tindex++)
{
TextureUnitState tus = newPass.GetTextureUnitState(tindex);
tus.SetColorOperationEx(LayerBlendOperationEx.Source1, LayerBlendSource.Current, LayerBlendSource.Current);
}
}
else
// remove any texture units
newPass.RemoveAllTextureUnitStates();
// also remove any fragment program
if(newPass.HasFragmentProgram) {
newPass.SetFragmentProgram("");
}
// Cannot remove vertex program, have to assume that
// it will process diffuse lights, ambient will be turned off
newPass.Ambient = ColorEx.Black;
newPass.Emissive = ColorEx.Black;
// must be additive
newPass.SetSceneBlending(SceneBlendFactor.One, SceneBlendFactor.One);
iPass = new IlluminationPass();
iPass.DestroyOnShutdown = true;
iPass.OriginalPass = pass;
iPass.Pass = newPass;
iPass.Stage = stage;
illuminationPasses.Add(iPass);
}
// This means the end of per-light passes
stage = IlluminationStage.Decal;
}
break;
case IlluminationStage.Decal:
// We just want a 'lighting off' pass to finish off
// and only if there are texture units
if(pass.NumTextureUnitStages > 0) {
if(!pass.LightingEnabled) {
// we assume this pass already combines as required with the scene
iPass = new IlluminationPass();
iPass.DestroyOnShutdown = false;
iPass.OriginalPass = pass;
iPass.Pass = pass;
iPass.Stage = stage;
illuminationPasses.Add(iPass);
}
else {
// Copy the pass and tweak away the lighting parts
Pass newPass = new Pass(this, pass.Index);
pass.CopyTo(newPass);
newPass.Ambient = ColorEx.Black;
newPass.Diffuse = new ColorEx(newPass.Diffuse.a, 0f, 0f, 0f); // Preserving alpha
newPass.Specular = ColorEx.Black;
newPass.Emissive = ColorEx.Black;
newPass.LightingEnabled = false;
// modulate
newPass.SetSceneBlending(SceneBlendFactor.DestColor, SceneBlendFactor.Zero);
// Calculate hash value for new pass, because we are compiling
// illumination passes on demand, which will loss hash calculate
// before it add to render queue first time.
newPass.RecalculateHash();
// there is nothing we can do about vertex & fragment
// programs here, so people will just have to make their
// programs friendly-like if they want to use this technique
iPass = new IlluminationPass();
iPass.DestroyOnShutdown = true;
iPass.OriginalPass = pass;
iPass.Pass = newPass;
iPass.Stage = stage;
illuminationPasses.Add(iPass);
}
}
// always increment on decal, since nothing more to do with this pass
i++;
break;
}
}
}
/// <summary>
/// Creates a new Pass for this technique.
/// </summary>
/// <remarks>
/// A Pass is a single rendering pass, ie a single draw of the given material.
/// Note that if you create a non-programmable pass, during compilation of the
/// material the pass may be split into multiple passes if the graphics card cannot
/// handle the number of texture units requested. For programmable passes, however,
/// the number of passes you create will never be altered, so you have to make sure
/// that you create an alternative fallback Technique for if a card does not have
/// enough facilities for what you're asking for.
/// </remarks>
/// <param name="programmable">
/// True if programmable via vertex or fragment programs, false if fixed function.
/// </param>
/// <returns>A new Pass object reference.</returns>
public Pass CreatePass() {
Pass pass = new Pass(this, passes.Count);
passes.Add(pass);
return pass;
}
/// <summary>
/// Retreives the Pass by name.
/// </summary>
/// <param name="passName">Name of the Pass to retreive.</param>
public Pass GetPass(string passName) {
foreach (Pass pass in passes) {
if (pass.Name == passName)
return pass;
}
return null;
}
/// <summary>
/// Retreives the Pass at the specified index.
/// </summary>
/// <param name="index">Index of the Pass to retreive.</param>
public Pass GetPass(int index) {
Debug.Assert(index < passes.Count, "index < passes.Count");
return (Pass)passes[index];
}
/// <summary>
/// Retreives the IlluminationPass at the specified index.
/// </summary>
/// <param name="index">Index of the IlluminationPass to retreive.</param>
public IlluminationPass GetIlluminationPass(int index) {
AssureIlluminationPassesCompiled();
Debug.Assert(index < illuminationPasses.Count, "index < illuminationPasses.Count");
return (IlluminationPass)illuminationPasses[index];
}
/// <summary>
/// Preloads resources required by this Technique. This is the
/// portion that is safe to do from a thread other than the
/// main render thread.
/// </summary>
public void Preload() {
Load();
}
/// <summary>
/// Loads resources required by this Technique.
/// </summary>
public void Load() {
Debug.Assert(isSupported, "This technique is not supported.");
// load each pass
for (int i = 0; i < passes.Count; i++) {
((Pass)passes[i]).Load();
}
// load each illumination pass
for (int i = 0; i < illuminationPasses.Count; i++) {
IlluminationPass pass = (IlluminationPass)illuminationPasses[i];
if (pass.Pass != pass.OriginalPass)
pass.Pass.Load();
}
}
/// <summary>
/// Forces this Technique to recompile.
/// </summary>
/// <remarks>
/// The parent Material is asked to recompile to accomplish this.
/// </remarks>
internal void NotifyNeedsRecompile() {
// Disable require to recompile when splitting illumination passes
if (illuminationPassesCompilationPhase != IlluminationPassesState.CompileDisabled)
parent.NotifyNeedsRecompile();
}
/// <summary>
/// Removes the specified Pass from this Technique.
/// </summary>
/// <param name="pass">A reference to the Pass to be removed.</param>
public void RemovePass(Pass pass) {
Debug.Assert(pass != null, "pass != null");
pass.QueueForDeletion();
passes.Remove(pass);
}
/// <summary>
/// Removes all passes from this technique and queues them for deletion.
/// </summary>
public void RemoveAllPasses() {
// load each pass
for(int i = 0; i < passes.Count; i++) {
Pass pass = (Pass)passes[i];
pass.QueueForDeletion();
}
passes.Clear();
}
public void SetSceneBlending(SceneBlendType blendType) {
// load each pass
for(int i = 0; i < passes.Count; i++) {
((Pass)passes[i]).SetSceneBlending(blendType);
}
}
public void SetSceneBlending(SceneBlendFactor src, SceneBlendFactor dest) {
// load each pass
for(int i = 0; i < passes.Count; i++) {
((Pass)passes[i]).SetSceneBlending(src, dest);
}
}
/// <summary>
/// Unloads resources used by this Technique.
/// </summary>
public void Unload() {
// load each pass
for(int i = 0; i < passes.Count; i++) {
((Pass)passes[i]).Unload();
}
}
/// <summary>
/// Applies texture names to Texture Unit State with matching texture name aliases.
/// All techniques, passes, and Texture Unit States within the material are checked.
/// If matching texture aliases are found then true is returned.
/// </summary>
/// <param name="aliasList">A map container of texture alias, texture name pairs.</param>
/// <param name="apply">Set to true to apply the texture aliases else just test to see if texture alias matches are found.</param>
/// <returns>True if matching texture aliases were found in the material.</returns>
public bool ApplyTextureAliases(Dictionary<string, string> aliasList, bool apply) {
bool testResult = false;
// iterate through passes and apply texture alias
for(int i=0; i<passes.Count; i++) {
Pass pass = (Pass)passes[i];
if (pass.ApplyTextureAliases(aliasList, apply))
testResult = true;
}
return testResult;
}
/// <summary>
/// Overloading that defaults apply to true
/// </summary>
public bool ApplyTextureAliases(Dictionary<string, string> aliasList) {
return ApplyTextureAliases(aliasList, true);
}
#endregion
#region Properties
public ColorEx Ambient {
set {
for(int i = 0; i < passes.Count; i++) {
((Pass)passes[i]).Ambient = value;
}
}
}
public CullingMode CullingMode {
set {
for(int i = 0; i < passes.Count; i++) {
((Pass)passes[i]).CullMode = value;
}
}
}
public ManualCullingMode ManualCullingMode {
set {
for(int i = 0; i < passes.Count; i++) {
((Pass)passes[i]).ManualCullMode = value;
}
}
}
public bool DepthCheck {
set {
for(int i = 0; i < passes.Count; i++) {
((Pass)passes[i]).DepthCheck = value;
}
}
get {
if (passes.Count == 0) {
return false;
}
else {
// Base decision on the depth settings of the first pass
return ((Pass)passes[0]).DepthCheck;
}
}
}
public bool DepthWrite {
set {
for(int i = 0; i < passes.Count; i++) {
((Pass)passes[i]).DepthWrite = value;
}
}
get {
if (passes.Count == 0) {
return false;
}
else {
// Base decision on the depth settings of the first pass
return ((Pass)passes[0]).DepthWrite;
}
}
}
public void SetDepthBias(float constantBias, float slopeScaleBias) {
for(int i = 0; i < passes.Count; i++)
((Pass)passes[i]).SetDepthBias(constantBias, slopeScaleBias);
}
public ColorEx Diffuse {
set {
for (int i = 0; i < passes.Count; i++) {
((Pass)passes[i]).Diffuse = value;
}
}
}
public ColorEx Specular {
set {
for (int i = 0; i < passes.Count; i++) {
((Pass)passes[i]).Specular = value;
}
}
}
public ColorEx Emissive {
set {
for (int i = 0; i < passes.Count; i++) {
((Pass)passes[i]).Emissive = value;
}
}
}
/// <summary>
/// Returns true if this Technique has already been loaded.
/// </summary>
public bool IsLoaded {
get {
return parent.IsLoaded;
}
}
/// <summary>
/// Flag that states whether or not this technique is supported on the current hardware.
/// </summary>
/// <remarks>
/// This will only be correct after the Technique has been compiled, which is
/// usually triggered in Material.Compile.
/// </remarks>
public bool IsSupported {
get {
return isSupported;
}
}
/// <summary>
/// Returns true if this Technique involves transparency.
/// </summary>
/// <remarks>
/// This basically boils down to whether the first pass
/// has a scene blending factor. Even if the other passes
/// do not, the base color, including parts of the original
/// scene, may be used for blending, therefore we have to treat
/// the whole Technique as transparent.
/// </remarks>
public bool IsTransparent {
get {
if(passes.Count == 0) {
return false;
}
else {
// based on the transparency of the first pass
return ((Pass)passes[0]).IsTransparent;
}
}
}
/// <summary>
///
/// </summary>
public bool Lighting {
set {
for(int i = 0; i < passes.Count; i++) {
((Pass)passes[i]).LightingEnabled = value;
}
}
}
/// <summary>
/// Assigns a level-of-detail (LOD) index to this Technique.
/// </summary>
/// <remarks>
/// As noted previously, as well as providing fallback support for various
/// graphics cards, multiple Technique objects can also be used to implement
/// material LOD, where the detail of the material diminishes with distance to
/// save rendering power.
/// <p/>
/// By default, all Techniques have a LOD index of 0, which means they are the highest
/// level of detail. Increasing LOD indexes are lower levels of detail. You can
/// assign more than one Technique to the same LOD index, meaning that the best
/// Technique that is supported at that LOD index is used.
/// <p/>
/// You should not leave gaps in the LOD sequence; the engine will allow you to do this
/// and will continue to function as if the LODs were sequential, but it will
/// confuse matters.
/// </remarks>
public int LodIndex {
get {
return lodIndex;
}
set {
lodIndex = value;
NotifyNeedsRecompile();
}
}
public int SchemeIndex {
get {
return schemeIndex;
}
}
public string SchemeName {
get {
return MaterialManager.Instance.GetSchemeName(schemeIndex);
}
set {
schemeIndex = MaterialManager.Instance.GetSchemeIndex(value);
NotifyNeedsRecompile();
}
}
/// <summary>
/// Gets/Sets the name of this technique.
/// </summary>
public string Name {
get {
return name;
}
set {
name = value;
}
}
/// <summary>
/// Gets the number of passes within this Technique.
/// </summary>
public int NumPasses {
get {
return passes.Count;
}
}
/// <summary>
/// Gets the number of illumination passes compiled from this technique.
/// </summary>
public int IlluminationPassCount {
get {
AssureIlluminationPassesCompiled();
return illuminationPasses.Count;
}
}
/// <summary>
/// Gets a reference to the Material that owns this Technique.
/// </summary>
public Material Parent {
get {
return parent;
}
}
public TextureFiltering TextureFiltering {
set {
for(int i = 0; i < passes.Count; i++) {
((Pass)passes[i]).TextureFiltering = value;
}
}
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.VFX;
namespace UnityEditor.VFX
{
static class VFXOperatorUtility
{
public static Dictionary<VFXValueType, VFXExpression> GenerateExpressionConstant(float baseValue)
{
return new Dictionary<VFXValueType, VFXExpression>()
{
{ VFXValueType.Float, VFXValue.Constant(baseValue) },
{ VFXValueType.Float2, VFXValue.Constant(Vector2.one * baseValue) },
{ VFXValueType.Float3, VFXValue.Constant(Vector3.one * baseValue) },
{ VFXValueType.Float4, VFXValue.Constant(Vector4.one * baseValue) },
{ VFXValueType.Int32, VFXValue.Constant((int)baseValue) },
{ VFXValueType.Uint32, VFXValue.Constant((uint)baseValue) }
};
}
public static readonly Dictionary<VFXValueType, VFXExpression> OneExpression = GenerateExpressionConstant(1.0f);
public static readonly Dictionary<VFXValueType, VFXExpression> MinusOneExpression = GenerateExpressionConstant(-1.0f);
public static readonly Dictionary<VFXValueType, VFXExpression> HalfExpression = GenerateExpressionConstant(0.5f);
public static readonly Dictionary<VFXValueType, VFXExpression> ZeroExpression = GenerateExpressionConstant(0.0f);
public static readonly Dictionary<VFXValueType, VFXExpression> TwoExpression = GenerateExpressionConstant(2.0f);
public static readonly Dictionary<VFXValueType, VFXExpression> ThreeExpression = GenerateExpressionConstant(3.0f);
public static readonly Dictionary<VFXValueType, VFXExpression> PiExpression = GenerateExpressionConstant(Mathf.PI);
public static readonly Dictionary<VFXValueType, VFXExpression> TauExpression = GenerateExpressionConstant(2.0f * Mathf.PI);
public static readonly Dictionary<VFXValueType, VFXExpression> E_NapierConstantExpression = GenerateExpressionConstant(Mathf.Exp(1));
public static readonly Dictionary<VFXValueType, VFXExpression> EpsilonExpression = GenerateExpressionConstant(1e-5f);
static public VFXExpression Negate(VFXExpression input)
{
var minusOne = MinusOneExpression[input.valueType];
return (minusOne * input);
}
static public VFXExpression Reciprocal(VFXExpression input)
{
return OneExpression[input.valueType] / input;
}
static public VFXExpression Mad(VFXExpression input, VFXExpression scale, VFXExpression bias)
{
return input * scale + bias;
}
static public VFXExpression Clamp(VFXExpression input, VFXExpression min, VFXExpression max)
{
return Clamp(input, min, max, true);
}
static public VFXExpression Clamp(VFXExpression input, VFXExpression min, VFXExpression max, bool autoCast)
{
//Max(Min(x, max), min))
if (autoCast)
{
min = CastFloat(min, input.valueType);
max = CastFloat(max, input.valueType);
}
var maxExp = new VFXExpressionMax(input, min);
return new VFXExpressionMin(maxExp, max);
}
static public VFXExpression Saturate(VFXExpression input)
{
//Max(Min(x, 1.0f), 0.0f))
return new VFXExpressionSaturate(input);
}
static public VFXExpression Frac(VFXExpression input)
{
//x - floor(x)
return new VFXExpressionFrac(input);
}
static public VFXExpression Ceil(VFXExpression input)
{
// ceil(x) = -floor(-x)
return new VFXExpressionCeil(input);
}
static public VFXExpression Round(VFXExpression input)
{
//x = floor(x + 0.5)
return new VFXExpressionRound(input);
}
static public VFXExpression Log(VFXExpression input, VFXExpression _base)
{
//log2(x)/log2(b)
return new VFXExpressionLog2(input) / new VFXExpressionLog2(_base);
}
static public VFXExpression Atanh(VFXExpression input)
{
//0.5*Log((1+x)/(1-x), e)
var half = HalfExpression[input.valueType];
var one = OneExpression[input.valueType];
var e = E_NapierConstantExpression[input.valueType];
return half * Log((one + input) / (one - input), e);
}
static public VFXExpression SinH(VFXExpression input)
{
//0.5*(e^x - e^-x)
var half = HalfExpression[input.valueType];
var minusOne = MinusOneExpression[input.valueType];
var e = E_NapierConstantExpression[input.valueType];
return half * (new VFXExpressionPow(e, input) - new VFXExpressionPow(e, minusOne * input));
}
static public VFXExpression CosH(VFXExpression input)
{
//0.5*(e^x + e^-x)
var half = HalfExpression[input.valueType];
var minusOne = MinusOneExpression[input.valueType];
var e = E_NapierConstantExpression[input.valueType];
return half * (new VFXExpressionPow(e, input) + new VFXExpressionPow(e, minusOne * input));
}
static public VFXExpression TanH(VFXExpression input)
{
//(1-e^2x)/(1+e^2x)
var two = TwoExpression[input.valueType];
var one = OneExpression[input.valueType];
var minusOne = MinusOneExpression[input.valueType];
var e = E_NapierConstantExpression[input.valueType];
var E_minusTwoX = new VFXExpressionPow(e, minusOne * two * input);
return (one - E_minusTwoX) / (one + E_minusTwoX);
}
static public VFXExpression VanDerCorputSequence(VFXExpression bits) //expect an uint return a float
{
bits = bits << 16 | bits >> 16;
bits = ((bits & 0x55555555u) << 1) | ((bits & 0xAAAAAAAA) >> 1);
bits = ((bits & 0x33333333u) << 2) | ((bits & 0xCCCCCCCC) >> 2);
bits = ((bits & 0x0F0F0F0Fu) << 4) | ((bits & 0xF0F0F0F0) >> 4);
bits = ((bits & 0x00FF00FFu) << 8) | ((bits & 0xFF00FF00) >> 8);
return new VFXExpressionCastUintToFloat(bits) * new VFXValue<float>(2.3283064365386963e-10f); // / 0x100000000;
}
static public VFXExpression Sqrt(VFXExpression input)
{
//pow(x, 0.5f)
return new VFXExpressionPow(input, HalfExpression[input.valueType]);
}
static public VFXExpression Dot(VFXExpression a, VFXExpression b)
{
//a.x*b.x + a.y*b.y + ...
var size = VFXExpression.TypeToSize(a.valueType);
if (a.valueType != b.valueType)
{
throw new ArgumentException(string.Format("Invalid Dot type input : {0} and {1}", a.valueType, b.valueType));
}
var mul = (a * b);
var sum = new Stack<VFXExpression>();
if (size == 1)
{
sum.Push(mul);
}
else
{
for (int iChannel = 0; iChannel < size; ++iChannel)
{
sum.Push(mul[iChannel]);
}
}
while (sum.Count > 1)
{
var top = sum.Pop();
var bottom = sum.Pop();
sum.Push(top + bottom);
}
return sum.Pop();
}
static public VFXExpression Cross(VFXExpression lhs, VFXExpression rhs)
{
Func<VFXExpression, VFXExpression, VFXExpression, VFXExpression, VFXExpression> ab_Minus_cd = delegate(VFXExpression a, VFXExpression b, VFXExpression c, VFXExpression d)
{
return (a * b - c * d);
};
return new VFXExpressionCombine(new[]
{
ab_Minus_cd(lhs.y, rhs.z, lhs.z, rhs.y),
ab_Minus_cd(lhs.z, rhs.x, lhs.x, rhs.z),
ab_Minus_cd(lhs.x, rhs.y, lhs.y, rhs.x),
});
}
static public VFXExpression Distance(VFXExpression x, VFXExpression y)
{
//length(a - b)
return Length(x - y);
}
static public VFXExpression SqrDistance(VFXExpression x, VFXExpression y)
{
//dot(a - b)
var delta = (x - y);
return Dot(delta, delta);
}
static public VFXExpression InverseLerp(VFXExpression x, VFXExpression y, VFXExpression s)
{
//(s - x)/(y - x)
return (s - x) / (y - x);
}
static public VFXExpression Lerp(VFXExpression x, VFXExpression y, VFXExpression s)
{
//x + s(y - x)
return (x + s * (y - x));
}
static public VFXExpression Length(VFXExpression v)
{
//sqrt(dot(v, v))
var dot = Dot(v, v);
return Sqrt(dot);
}
static public VFXExpression Normalize(VFXExpression v)
{
var invLength = (OneExpression[VFXValueType.Float] / Length(v));
var invLengthVector = CastFloat(invLength, v.valueType);
return (v * invLengthVector);
}
static public VFXExpression Modulo(VFXExpression x, VFXExpression y)
{
if (VFXExpression.IsFloatValueType(x.valueType))
{
//fmod : frac(x / y) * y
return Frac(x / y) * y;
}
else
{
//Std 1152 If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.
return x - (x / y) * y;
}
}
static public VFXExpression Fit(VFXExpression value, VFXExpression oldRangeMin, VFXExpression oldRangeMax, VFXExpression newRangeMin, VFXExpression newRangeMax)
{
//percent = (value - oldRangeMin) / (oldRangeMax - oldRangeMin)
//lerp(newRangeMin, newRangeMax, percent)
VFXExpression percent = (value - oldRangeMin) / (oldRangeMax - oldRangeMin);
return Lerp(newRangeMin, newRangeMax, percent);
}
static public VFXExpression Smoothstep(VFXExpression x, VFXExpression y, VFXExpression s)
{
var type = x.valueType;
var t = (s - x) / (y - x);
t = Clamp(t, ZeroExpression[type], OneExpression[type]);
var result = (ThreeExpression[type] - TwoExpression[type] * t);
result = (result * t);
result = (result * t);
return result;
}
static public VFXExpression Discretize(VFXExpression value, VFXExpression granularity)
{
return new VFXExpressionFloor(value / granularity) * granularity;
}
static public VFXExpression ColorLuma(VFXExpression color)
{
//(0.299*R + 0.587*G + 0.114*B)
var coefficients = VFXValue.Constant(new Vector4(0.299f, 0.587f, 0.114f, 0.0f));
return Dot(color, coefficients);
}
static public VFXExpression DegToRad(VFXExpression degrees)
{
return (degrees * CastFloat(VFXValue.Constant(Mathf.PI / 180.0f), degrees.valueType));
}
static public VFXExpression RadToDeg(VFXExpression radians)
{
return (radians * CastFloat(VFXValue.Constant(180.0f / Mathf.PI), radians.valueType));
}
static public VFXExpression PolarToRectangular(VFXExpression theta, VFXExpression distance)
{
//x = cos(angle) * distance
//y = sin(angle) * distance
var result = new VFXExpressionCombine(new VFXExpression[] { new VFXExpressionCos(theta), new VFXExpressionSin(theta) });
return (result * CastFloat(distance, VFXValueType.Float2));
}
static public VFXExpression[] RectangularToPolar(VFXExpression coord)
{
//theta = atan2(coord.y, coord.x)
//distance = length(coord)
var components = ExtractComponents(coord).ToArray();
var theta = new VFXExpressionATan2(components[1], components[0]);
var distance = Length(coord);
return new VFXExpression[] { theta, distance };
}
static public VFXExpression SphericalToRectangular(VFXExpression theta, VFXExpression phi, VFXExpression distance)
{
//x = cos(theta) * cos(phi) * distance
//y = sin(theta) * cos(phi) * distance
//z = sin(phi) * distance
var cosTheta = new VFXExpressionCos(theta);
var cosPhi = new VFXExpressionCos(phi);
var sinTheta = new VFXExpressionSin(theta);
var sinPhi = new VFXExpressionSin(phi);
var x = (cosTheta * cosPhi);
var y = sinPhi;
var z = (sinTheta * cosPhi);
var result = new VFXExpressionCombine(new VFXExpression[] { x, y, z });
return (result * CastFloat(distance, VFXValueType.Float3));
}
static public VFXExpression[] RectangularToSpherical(VFXExpression coord)
{
//distance = length(coord)
//theta = atan2(z, x)
//phi = asin(y / distance)
var components = ExtractComponents(coord).ToArray();
var distance = Length(coord);
var theta = new VFXExpressionATan2(components[2], components[0]);
var phi = new VFXExpressionASin(components[1] / distance);
return new VFXExpression[] { theta, phi, distance };
}
static public VFXExpression CircleArea(VFXExpression radius)
{
//pi * r * r
var pi = VFXValue.Constant(Mathf.PI);
return (pi * radius * radius);
}
static public VFXExpression CircleCircumference(VFXExpression radius)
{
//2 * pi * r
var two = VFXValue.Constant(2.0f);
var pi = VFXValue.Constant(Mathf.PI);
return (two * pi * radius);
}
static public VFXExpression BoxVolume(VFXExpression dimensions)
{
//x * y * z
var components = ExtractComponents(dimensions).ToArray();
return (components[0] * components[1] * components[2]);
}
static public VFXExpression SphereVolume(VFXExpression radius)
{
//(4 / 3) * pi * r * r * r
var multiplier = VFXValue.Constant((4.0f / 3.0f) * Mathf.PI);
return (multiplier * radius * radius * radius);
}
static public VFXExpression CylinderVolume(VFXExpression radius, VFXExpression height)
{
//pi * r * r * h
var pi = VFXValue.Constant(Mathf.PI);
return (pi * radius * radius * height);
}
static public VFXExpression ConeVolume(VFXExpression radius0, VFXExpression radius1, VFXExpression height)
{
//pi/3 * (r0 * r0 + r0 * r1 + r1 * r1) * h
var piOver3 = VFXValue.Constant(Mathf.PI / 3.0f);
VFXExpression r0r0 = (radius0 * radius0);
VFXExpression r0r1 = (radius0 * radius1);
VFXExpression r1r1 = (radius1 * radius1);
VFXExpression result = (r0r0 + r0r1 + r1r1);
return (piOver3 * result * height);
}
static public VFXExpression TorusVolume(VFXExpression majorRadius, VFXExpression minorRadius)
{
//(pi * r * r) * (2 * pi * R)
return CircleArea(minorRadius) * CircleCircumference(majorRadius);
}
static public VFXExpression SignedDistanceToPlane(VFXExpression planePosition, VFXExpression planeNormal, VFXExpression position)
{
VFXExpression d = Dot(planePosition, planeNormal);
return Dot(position, planeNormal) - d;
}
static public VFXExpression GammaToLinear(VFXExpression gamma)
{
var components = ExtractComponents(gamma).ToArray();
if (components.Length != 3 && components.Length != 4)
throw new ArgumentException("input expression must be a 3 or 4 components vector");
VFXExpression exp = VFXValue.Constant(2.2f);
for (int i = 0; i < 3; ++i)
components[i] = new VFXExpressionPow(components[i], exp);
return new VFXExpressionCombine(components);
}
static public VFXExpression LinearToGamma(VFXExpression linear)
{
var components = ExtractComponents(linear).ToArray();
if (components.Length != 3 && components.Length != 4)
throw new ArgumentException("input expression must be a 3 or 4 components vector");
VFXExpression exp = VFXValue.Constant(1.0f / 2.2f);
for (int i = 0; i < 3; ++i)
components[i] = new VFXExpressionPow(components[i], exp);
return new VFXExpressionCombine(components);
}
static public IEnumerable<VFXExpression> ExtractComponents(VFXExpression expression)
{
if (expression.valueType == VFXValueType.Float)
{
return new[] { expression };
}
var components = new List<VFXExpression>();
for (int i = 0; i < VFXExpression.TypeToSize(expression.valueType); ++i)
{
components.Add(expression[i]);
}
return components;
}
static public VFXExpression CastFloat(VFXExpression from, VFXValueType toValueType, float defaultValue = 0.0f)
{
if (!VFXExpressionNumericOperation.IsFloatValueType(from.valueType) || !VFXExpressionNumericOperation.IsFloatValueType(toValueType))
{
throw new ArgumentException(string.Format("Invalid CastFloat : {0} to {1}", from, toValueType));
}
if (from.valueType == toValueType)
{
return from;
}
var fromValueType = from.valueType;
var fromValueTypeSize = VFXExpression.TypeToSize(fromValueType);
var toValueTypeSize = VFXExpression.TypeToSize(toValueType);
var inputComponent = new VFXExpression[fromValueTypeSize];
var outputComponent = new VFXExpression[toValueTypeSize];
if (inputComponent.Length == 1)
{
inputComponent[0] = from;
}
else
{
for (int iChannel = 0; iChannel < fromValueTypeSize; ++iChannel)
{
inputComponent[iChannel] = from[iChannel];
}
}
for (int iChannel = 0; iChannel < toValueTypeSize; ++iChannel)
{
if (iChannel < fromValueTypeSize)
{
outputComponent[iChannel] = inputComponent[iChannel];
}
else if (fromValueTypeSize == 1)
{
//Manage same logic behavior for float => floatN in HLSL
outputComponent[iChannel] = inputComponent[0];
}
else
{
outputComponent[iChannel] = VFXValue.Constant(defaultValue);
}
}
if (toValueTypeSize == 1)
{
return outputComponent[0];
}
var combine = new VFXExpressionCombine(outputComponent);
return combine;
}
static public VFXExpression FixedRandom(uint hash, bool perElement)
{
return FixedRandom(VFXValue.Constant<uint>(hash), perElement);
}
static public VFXExpression FixedRandom(VFXExpression hash, bool perElement)
{
VFXExpression seed = new VFXExpressionBitwiseXor(hash, VFXBuiltInExpression.SystemSeed);
if (perElement)
seed = new VFXExpressionBitwiseXor(new VFXAttributeExpression(VFXAttribute.ParticleId), seed);
return new VFXExpressionFixedRandom(seed);
}
public enum SequentialAddressingMode
{
Wrap,
Clamp,
Mirror
};
static private VFXExpression ApplyAddressingMode(VFXExpression index, VFXExpression count, SequentialAddressingMode mode)
{
VFXExpression r = null;
if (mode == SequentialAddressingMode.Wrap)
{
r = VFXOperatorUtility.Modulo(index, count);
}
else if (mode == SequentialAddressingMode.Clamp)
{
r = VFXOperatorUtility.Clamp(index, ZeroExpression[VFXValueType.Uint32], count, false);
}
else if (mode == SequentialAddressingMode.Mirror)
{
var direction = VFXOperatorUtility.Modulo(index / count, VFXOperatorUtility.TwoExpression[VFXValueType.Uint32]);
var modulo = VFXOperatorUtility.Modulo(index, count);
r = VFXOperatorUtility.Lerp(modulo, count - modulo, direction);
}
return r;
}
static public VFXExpression SequentialLine(VFXExpression start, VFXExpression end, VFXExpression index, VFXExpression count, SequentialAddressingMode mode)
{
VFXExpression dt = ApplyAddressingMode(index, count, mode);
dt = new VFXExpressionCastUintToFloat(dt);
var size = new VFXExpressionCastUintToFloat(count) - VFXOperatorUtility.OneExpression[VFXValueType.Float];
size = new VFXExpressionMax(size, VFXOperatorUtility.OneExpression[VFXValueType.Float]);
dt = dt / size ;
dt = new VFXExpressionCombine(dt, dt, dt);
return VFXOperatorUtility.Lerp(start, end, dt);
}
static public VFXExpression SequentialCircle(VFXExpression center, VFXExpression radius, VFXExpression normal, VFXExpression up, VFXExpression index, VFXExpression count, SequentialAddressingMode mode)
{
VFXExpression dt = ApplyAddressingMode(index, count, mode);
dt = new VFXExpressionCastUintToFloat(dt);
dt = dt / new VFXExpressionCastUintToFloat(count);
var cos = new VFXExpressionCos(dt * VFXOperatorUtility.TauExpression[VFXValueType.Float]) as VFXExpression;
var sin = new VFXExpressionSin(dt * VFXOperatorUtility.TauExpression[VFXValueType.Float]) as VFXExpression;
var left = VFXOperatorUtility.Normalize(VFXOperatorUtility.Cross(normal, up));
radius = new VFXExpressionCombine(radius, radius, radius);
sin = new VFXExpressionCombine(sin, sin, sin);
cos = new VFXExpressionCombine(cos, cos, cos);
return center + (cos * up + sin * left) * radius;
}
static public VFXExpression Sequential3D(VFXExpression origin, VFXExpression axisX, VFXExpression axisY, VFXExpression axisZ, VFXExpression index, VFXExpression countX, VFXExpression countY, VFXExpression countZ, SequentialAddressingMode mode)
{
index = ApplyAddressingMode(index, countX * countY * countZ, mode);
var z = new VFXExpressionCastUintToFloat(VFXOperatorUtility.Modulo(index, countZ));
var y = new VFXExpressionCastUintToFloat(VFXOperatorUtility.Modulo(index / countZ, countY));
var x = new VFXExpressionCastUintToFloat(index / (countY * countZ));
VFXExpression volumeSize = new VFXExpressionCombine(new VFXExpressionCastUintToFloat(countX), new VFXExpressionCastUintToFloat(countY), new VFXExpressionCastUintToFloat(countZ));
volumeSize = volumeSize - VFXOperatorUtility.OneExpression[VFXValueType.Float3];
var scaleAxisZero = Saturate(volumeSize); //Handle special case for one count => lead to be centered on origin (instead of -axis)
volumeSize = new VFXExpressionMax(volumeSize, VFXOperatorUtility.OneExpression[VFXValueType.Float3]);
var dt = new VFXExpressionCombine(x, y, z) / volumeSize;
dt = dt * VFXOperatorUtility.TwoExpression[VFXValueType.Float3] - VFXOperatorUtility.OneExpression[VFXValueType.Float3];
var r = origin;
r += dt.xxx * scaleAxisZero.xxx * axisX;
r += dt.yyy * scaleAxisZero.yyy * axisY;
r += dt.zzz * scaleAxisZero.zzz * axisZ;
return r;
}
static public VFXExpression GetPerspectiveMatrix(VFXExpression fov, VFXExpression aspect, VFXExpression zNear, VFXExpression zFar)
{
var fovHalf = fov / TwoExpression[VFXValueType.Float];
var cotangent = new VFXExpressionCos(fovHalf) / new VFXExpressionSin(fovHalf);
var deltaZ = zNear - zFar;
var zero = ZeroExpression[VFXValueType.Float];
var m0 = new VFXExpressionCombine(cotangent / aspect, zero, zero, zero);
var m1 = new VFXExpressionCombine(zero, cotangent, zero, zero);
var m2 = new VFXExpressionCombine(zero, zero, MinusOneExpression[VFXValueType.Float] * (zFar + zNear) / deltaZ, OneExpression[VFXValueType.Float]);
var m3 = new VFXExpressionCombine(zero, zero, TwoExpression[VFXValueType.Float] * zNear * zFar / deltaZ, zero);
return new VFXExpressionVector4sToMatrix(m0, m1, m2, m3);
}
}
}
| |
using System;
using System.Collections;
using System.Configuration;
using System.IO;
using System.Web;
using System.Xml;
using BlogServer.Config;
using BlogServer.Model;
using BlogServer.WebServer;
using BlogServer.XmlRpc;
namespace BlogServer.RequestHandlers
{
/// <summary>
/// Implements a functional MovableType API endpoint.
///
/// Config:
/// Requires a blogProperty attribute whose value is the name of a server
/// property that contains a BlogConfig.
/// </summary>
public class BlogServerHandler : XmlRpcHttpRequestHandler
{
private readonly BlogConfig _blogConfig;
public BlogServerHandler(XmlElement configEl) : base(true)
{
string blogProperty = XmlUtil.ReadString(configEl, "@blogProperty", null);
if (blogProperty == null)
throw new ConfigurationException("BlogServerHandler requires a 'blogProperty' attribute");
_blogConfig = ConfigProperties.Instance[blogProperty] as BlogConfig;
if (_blogConfig == null)
throw new ConfigurationException("Property '" + blogProperty + "' was missing or invalid");
}
// blogger.getUsersBlogs (appkey, username, password) returns array of struct [url, blogid, blogName]
[XmlRpcMethod("blogger.getUsersBlogs")]
public IDictionary[] GetUsersBlogs(string appkey, string username, string password)
{
return new IDictionary[] { Util.MakeDictionary(
"url", _blogConfig.HomepageUrl,
"blogid", _blogConfig.BlogId,
"blogName", _blogConfig.BlogName
) };
}
// blogger.deletePost (appkey, postid, username, password, publish) returns true
[XmlRpcMethod("blogger.deletePost")]
public bool DeletePost(string appkey, string postid, string username, string password, bool publish)
{
CheckCredentials(username, password);
if (!_blogConfig.Blog.DeleteBlogPost(postid))
throw new XmlRpcServerException(404, "Post '" + postid + "' was not found");
return true;
}
// metaWeblog.newPost (blogid, username, password, struct, publish) returns string
[XmlRpcMethod("metaWeblog.newPost")]
public string NewPost(string blogid, string username, string password, BlogPost post, bool publish)
{
CheckBlogId(blogid);
CheckCredentials(username, password);
post.Published = publish;
if (post.Date == DateTime.MinValue)
post.Date = DateTime.UtcNow;
return _blogConfig.Blog.CreateBlogPost(post);
}
// metaWeblog.editPost (postid, username, password, struct, publish) returns true
[XmlRpcMethod("metaWeblog.editPost")]
public bool EditPost(string postid, string username, string password, BlogPost post, bool publish)
{
CheckCredentials(username, password);
if (_blogConfig.Blog.Contains(postid))
{
BlogPost existingPost = _blogConfig.Blog[postid];
existingPost.Title = post.Title;
existingPost.Description = post.Description;
existingPost.Excerpt = post.Excerpt;
existingPost.ExtendedDescription = post.ExtendedDescription;
existingPost.Keywords = post.Keywords;
existingPost.AllowComments = post.AllowComments;
existingPost.AllowPings = post.AllowPings;
if (post.Date != DateTime.MinValue)
existingPost.Date = post.Date;
if (post.Categories.Length > 0)
existingPost.Categories = post.Categories;
// ignore post.PingUrls, for now
existingPost.Published = publish;
_blogConfig.Blog.UpdateBlogPost(existingPost);
return true;
}
else
{
throw new XmlRpcServerException(404, "BlogConfig post with id " + postid + "was not found");
}
}
// metaWeblog.getPost (postid, username, password) returns struct
[XmlRpcMethod("metaWeblog.getPost")]
public BlogPost GetPost(string postid, string username, string password)
{
CheckCredentials(username, password);
if (_blogConfig.Blog.Contains(postid))
return _blogConfig.Blog[postid];
else
throw new XmlRpcServerException(404, "BlogConfig post with id " + postid + "was not found");
}
// metaWeblog.getRecentPosts (blogid, username, password, numberOfPosts) returns array of structs
[XmlRpcMethod("metaWeblog.getRecentPosts")]
public BlogPost[] GetRecentPosts(string blogid, string username, string password, int numberOfPosts)
{
CheckBlogId(blogid);
CheckCredentials(username, password);
return _blogConfig.Blog.GetRecentPosts(numberOfPosts);
}
// metaWeblog.newMediaObject (blogid, username, password, struct) returns struct
[XmlRpcMethod("metaWeblog.newMediaObject")]
public IDictionary NewMediaObject(string blogid, string username, string password, NewMediaObjectArgs args)
{
CheckBlogId(blogid);
CheckCredentials(username, password);
string dir = _blogConfig.UploadDir;
string path = _blogConfig.UploadPath;
if (dir == null || path == null)
throw new XmlRpcServerException(403, "This server is not configured for newMediaObject support.");
if (path != null && !path.EndsWith("/"))
path += "/";
if (!Directory.Exists(dir))
throw new XmlRpcServerException(500, "The newMediaObject upload directory does not exist");
string fileExt = Util.GetExtensionForContentType(args.Type);
if (fileExt == null)
throw new XmlRpcServerException(403, "Couldn't determine an extension for the given content type");
string fileName = Guid.NewGuid().ToString("d") + fileExt;
string fullFileName = Path.Combine(dir, fileName);
using (Stream s = new FileStream(fullFileName, FileMode.CreateNew, FileAccess.Write, FileShare.Write, 8192))
{
StreamHelper.Transfer(new MemoryStream(args.Bits), s);
}
return Util.MakeDictionary("url", path + HttpUtility.UrlPathEncode(fileName));
}
[XmlRpcSerializable]
public class NewMediaObjectArgs
{
private string _name;
private string _type;
private byte[] _bits;
[XmlRpcStructMember("name")]
public string Name
{
get { return _name; }
set { _name = value;}
}
[XmlRpcStructMember("type")]
public string Type
{
get { return _type; }
set { _type = value; }
}
[XmlRpcStructMember("bits")]
public byte[] Bits
{
get { return _bits; }
set { _bits = value; }
}
}
// mt.getRecentPostTitles (blogid, username, password, numberOfPosts) returns array of structs
[XmlRpcMethod("mt.getRecentPostTitles")]
public IDictionary[] GetRecentPostTitles(string blogid, string username, string password, int numberOfPosts)
{
CheckBlogId(blogid);
CheckCredentials(username, password);
BlogPost[] posts = _blogConfig.Blog.GetRecentPosts(numberOfPosts);
ArrayList results = new ArrayList();
foreach (BlogPost post in posts)
{
results.Add(Util.MakeDictionary(
"dateCreated", post.Date,
"userid", _blogConfig.BlogId,
"postid", post.Id,
"title", post.Title
));
}
return (IDictionary[]) results.ToArray(typeof (IDictionary));
}
// mt.getCategoryList
[XmlRpcMethod("mt.getCategoryList")]
public Category[] GetCategoryList(string blogid, string username, string password)
{
CheckBlogId(blogid);
CheckCredentials(username, password);
Hashtable categories = new Hashtable();
foreach (BlogPost post in _blogConfig.Blog.GetRecentPosts(int.MaxValue))
{
foreach (Category category in post.Categories)
{
categories[category.Id] = category;
}
}
ArrayList catList = new ArrayList(categories.Values);
catList.Sort();
return (Category[]) catList.ToArray(typeof (Category));
}
// mt.getPostCategories
[XmlRpcMethod("mt.getPostCategories")]
public Category[] GetPostCategories(string postid, string username, string password)
{
BlogPost post = _blogConfig.Blog[postid];
if (post == null)
throw new XmlRpcServerException(404, "BlogConfig post with id '" + postid + "' does not exist or was deleted");
return post.Categories;
}
// mt.setPostCategories
[XmlRpcMethod("mt.setPostCategories")]
public bool SetPostCategories(string postid, string username, string password, Category[] categories)
{
BlogPost post = _blogConfig.Blog[postid];
if (post == null)
throw new XmlRpcServerException(404, "BlogConfig post with id '" + postid + "' does not exist or was deleted");
post.Categories = categories;
_blogConfig.Blog.UpdateBlogPost(post);
return true;
}
// mt.supportedMethods
// mt.supportedTextFilters
// mt.getTrackbackPings
// mt.publishPost
private void CheckBlogId(string blogid)
{
if (blogid != _blogConfig.BlogId)
throw new XmlRpcServerException(404, "Unknown blog id '" + blogid + "'");
}
private void CheckCredentials(string username, string password)
{
if (!_blogConfig.CheckUsername(username))
throw new XmlRpcServerException(401, "Unknown username");
if (!_blogConfig.CheckPassword(password))
throw new XmlRpcServerException(401, "Incorrect password");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.