context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.Practices.WizardFramework;
namespace SPALM.SPSF.Library.CustomWizardPages
{
partial class FeatureSelectionPage : SPSFBaseWizardPage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 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.panel1 = new System.Windows.Forms.Panel();
this.panel2 = new System.Windows.Forms.Panel();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.checkBox_Hidden = new System.Windows.Forms.CheckBox();
this.textBox_FeatureTitle = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.checkBox_CreateReceiver = new System.Windows.Forms.CheckBox();
this.comboBox_Scopes = new System.Windows.Forms.ComboBox();
this.textBox_FeatureName = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.textBox_FeatureDescription = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.infoPanel.SuspendLayout();
this.panel2.SuspendLayout();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
this.SuspendLayout();
//
// infoPanel
//
this.infoPanel.Controls.Add(this.panel1);
this.infoPanel.Location = new System.Drawing.Point(0, 41);
this.infoPanel.Size = new System.Drawing.Size(500, 309);
this.infoPanel.Controls.SetChildIndex(this.panel1, 0);
//
// panel1
//
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(500, 205);
this.panel1.TabIndex = 9;
//
// panel2
//
this.panel2.Controls.Add(this.groupBox1);
this.panel2.Controls.Add(this.comboBox1);
this.panel2.Controls.Add(this.label1);
this.panel2.Location = new System.Drawing.Point(0, 0);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(495, 298);
this.panel2.TabIndex = 0;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.checkBox_Hidden);
this.groupBox1.Controls.Add(this.textBox_FeatureTitle);
this.groupBox1.Controls.Add(this.label5);
this.groupBox1.Controls.Add(this.checkBox_CreateReceiver);
this.groupBox1.Controls.Add(this.comboBox_Scopes);
this.groupBox1.Controls.Add(this.textBox_FeatureName);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.textBox_FeatureDescription);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Location = new System.Drawing.Point(3, 54);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(489, 236);
this.groupBox1.TabIndex = 8;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "New feature settings";
this.groupBox1.Enter += new System.EventHandler(this.groupBox1_Enter);
//
// checkBox_Hidden
//
this.checkBox_Hidden.AutoSize = true;
this.checkBox_Hidden.Location = new System.Drawing.Point(10, 203);
this.checkBox_Hidden.Name = "checkBox_Hidden";
this.checkBox_Hidden.Size = new System.Drawing.Size(96, 17);
this.checkBox_Hidden.TabIndex = 12;
this.checkBox_Hidden.Text = "Hidden feature";
this.checkBox_Hidden.UseVisualStyleBackColor = true;
this.checkBox_Hidden.CheckedChanged += new System.EventHandler(this.checkBox_CreateReceiver_CheckedChanged);
//
// textBox_FeatureTitle
//
this.textBox_FeatureTitle.Location = new System.Drawing.Point(10, 74);
this.textBox_FeatureTitle.Name = "textBox_FeatureTitle";
this.textBox_FeatureTitle.Size = new System.Drawing.Size(469, 20);
this.textBox_FeatureTitle.TabIndex = 11;
this.textBox_FeatureTitle.TextChanged += new System.EventHandler(this.textBox_FeatureDescription_TextChanged);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(7, 58);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(27, 13);
this.label5.TabIndex = 10;
this.label5.Text = "Title";
//
// checkBox_CreateReceiver
//
this.checkBox_CreateReceiver.AutoSize = true;
this.checkBox_CreateReceiver.Location = new System.Drawing.Point(10, 180);
this.checkBox_CreateReceiver.Name = "checkBox_CreateReceiver";
this.checkBox_CreateReceiver.Size = new System.Drawing.Size(139, 17);
this.checkBox_CreateReceiver.TabIndex = 9;
this.checkBox_CreateReceiver.Text = "Create FeatureReceiver";
this.checkBox_CreateReceiver.UseVisualStyleBackColor = true;
this.checkBox_CreateReceiver.CheckedChanged += new System.EventHandler(this.checkBox_CreateReceiver_CheckedChanged);
//
// comboBox_Scopes
//
this.comboBox_Scopes.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox_Scopes.FormattingEnabled = true;
this.comboBox_Scopes.Location = new System.Drawing.Point(10, 153);
this.comboBox_Scopes.Name = "comboBox_Scopes";
this.comboBox_Scopes.Size = new System.Drawing.Size(469, 21);
this.comboBox_Scopes.TabIndex = 7;
this.comboBox_Scopes.SelectedIndexChanged += new System.EventHandler(this.comboBox_Scopes_SelectedIndexChanged);
//
// textBox_FeatureName
//
this.textBox_FeatureName.Location = new System.Drawing.Point(10, 33);
this.textBox_FeatureName.Name = "textBox_FeatureName";
this.textBox_FeatureName.Size = new System.Drawing.Size(469, 20);
this.textBox_FeatureName.TabIndex = 5;
this.textBox_FeatureName.TextChanged += new System.EventHandler(this.textBox_FeatureDescription_TextChanged);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(7, 17);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(35, 13);
this.label2.TabIndex = 2;
this.label2.Text = "Name";
//
// textBox_FeatureDescription
//
this.textBox_FeatureDescription.Location = new System.Drawing.Point(10, 113);
this.textBox_FeatureDescription.Name = "textBox_FeatureDescription";
this.textBox_FeatureDescription.Size = new System.Drawing.Size(469, 20);
this.textBox_FeatureDescription.TabIndex = 6;
this.textBox_FeatureDescription.TextChanged += new System.EventHandler(this.textBox_FeatureDescription_TextChanged);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(7, 97);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(60, 13);
this.label3.TabIndex = 3;
this.label3.Text = "Description";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(7, 136);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(38, 13);
this.label4.TabIndex = 4;
this.label4.Text = "Scope";
//
// comboBox1
//
this.comboBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.comboBox1.BackColor = System.Drawing.SystemColors.Window;
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(2, 19);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(490, 21);
this.comboBox1.TabIndex = 1;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(-1, 2);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(106, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Select parent feature";
//
// FeatureSelectionPage
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.Controls.Add(this.panel2);
this.Headline = "Parent Feature";
this.InfoRTBoxSize = new System.Drawing.Size(550, 50);
this.InfoRTBoxText = "Select an existing feature or create a new feature.";
this.Name = "FeatureSelectionPage";
this.Size = new System.Drawing.Size(500, 350);
this.StepTitle = "Parent Feature";
this.Controls.SetChildIndex(this.infoPanel, 0);
this.Controls.SetChildIndex(this.panel2, 0);
this.infoPanel.ResumeLayout(false);
this.infoPanel.PerformLayout();
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Panel panel1;
private Panel panel2;
private ComboBox comboBox1;
private Label label1;
private Label label2;
private TextBox textBox_FeatureDescription;
private TextBox textBox_FeatureName;
private Label label4;
private Label label3;
private GroupBox groupBox1;
private ComboBox comboBox_Scopes;
private CheckBox checkBox_CreateReceiver;
private TextBox textBox_FeatureTitle;
private Label label5;
private CheckBox checkBox_Hidden;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A matrix of type Complex with 2 columns and 4 rows.
/// </summary>
[Serializable]
[DataContract(Namespace = "mat")]
[StructLayout(LayoutKind.Sequential)]
public struct cmat2x4 : IReadOnlyList<Complex>, IEquatable<cmat2x4>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
[DataMember]
public Complex m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
[DataMember]
public Complex m01;
/// <summary>
/// Column 0, Rows 2
/// </summary>
[DataMember]
public Complex m02;
/// <summary>
/// Column 0, Rows 3
/// </summary>
[DataMember]
public Complex m03;
/// <summary>
/// Column 1, Rows 0
/// </summary>
[DataMember]
public Complex m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
[DataMember]
public Complex m11;
/// <summary>
/// Column 1, Rows 2
/// </summary>
[DataMember]
public Complex m12;
/// <summary>
/// Column 1, Rows 3
/// </summary>
[DataMember]
public Complex m13;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public cmat2x4(Complex m00, Complex m01, Complex m02, Complex m03, Complex m10, Complex m11, Complex m12, Complex m13)
{
this.m00 = m00;
this.m01 = m01;
this.m02 = m02;
this.m03 = m03;
this.m10 = m10;
this.m11 = m11;
this.m12 = m12;
this.m13 = m13;
}
/// <summary>
/// Constructs this matrix from a cmat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x4(cmat2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = Complex.Zero;
this.m03 = Complex.Zero;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = Complex.Zero;
this.m13 = Complex.Zero;
}
/// <summary>
/// Constructs this matrix from a cmat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x4(cmat3x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = Complex.Zero;
this.m03 = Complex.Zero;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = Complex.Zero;
this.m13 = Complex.Zero;
}
/// <summary>
/// Constructs this matrix from a cmat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x4(cmat4x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = Complex.Zero;
this.m03 = Complex.Zero;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = Complex.Zero;
this.m13 = Complex.Zero;
}
/// <summary>
/// Constructs this matrix from a cmat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x4(cmat2x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = Complex.Zero;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = Complex.Zero;
}
/// <summary>
/// Constructs this matrix from a cmat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x4(cmat3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = Complex.Zero;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = Complex.Zero;
}
/// <summary>
/// Constructs this matrix from a cmat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x4(cmat4x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = Complex.Zero;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = Complex.Zero;
}
/// <summary>
/// Constructs this matrix from a cmat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x4(cmat2x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a cmat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x4(cmat3x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a cmat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x4(cmat4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x4(cvec2 c0, cvec2 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = Complex.Zero;
this.m03 = Complex.Zero;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = Complex.Zero;
this.m13 = Complex.Zero;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x4(cvec3 c0, cvec3 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m03 = Complex.Zero;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m13 = Complex.Zero;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x4(cvec4 c0, cvec4 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m03 = c0.w;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m13 = c1.w;
}
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public Complex[,] Values => new[,] { { m00, m01, m02, m03 }, { m10, m11, m12, m13 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public Complex[] Values1D => new[] { m00, m01, m02, m03, m10, m11, m12, m13 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public cvec4 Column0
{
get
{
return new cvec4(m00, m01, m02, m03);
}
set
{
m00 = value.x;
m01 = value.y;
m02 = value.z;
m03 = value.w;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public cvec4 Column1
{
get
{
return new cvec4(m10, m11, m12, m13);
}
set
{
m10 = value.x;
m11 = value.y;
m12 = value.z;
m13 = value.w;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public cvec2 Row0
{
get
{
return new cvec2(m00, m10);
}
set
{
m00 = value.x;
m10 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public cvec2 Row1
{
get
{
return new cvec2(m01, m11);
}
set
{
m01 = value.x;
m11 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 2
/// </summary>
public cvec2 Row2
{
get
{
return new cvec2(m02, m12);
}
set
{
m02 = value.x;
m12 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 3
/// </summary>
public cvec2 Row3
{
get
{
return new cvec2(m03, m13);
}
set
{
m03 = value.x;
m13 = value.y;
}
}
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static cmat2x4 Zero { get; } = new cmat2x4(Complex.Zero, Complex.Zero, Complex.Zero, Complex.Zero, Complex.Zero, Complex.Zero, Complex.Zero, Complex.Zero);
/// <summary>
/// Predefined all-ones matrix
/// </summary>
public static cmat2x4 Ones { get; } = new cmat2x4(Complex.One, Complex.One, Complex.One, Complex.One, Complex.One, Complex.One, Complex.One, Complex.One);
/// <summary>
/// Predefined identity matrix
/// </summary>
public static cmat2x4 Identity { get; } = new cmat2x4(Complex.One, Complex.Zero, Complex.Zero, Complex.Zero, Complex.Zero, Complex.One, Complex.Zero, Complex.Zero);
/// <summary>
/// Predefined all-imaginary-ones matrix
/// </summary>
public static cmat2x4 ImaginaryOnes { get; } = new cmat2x4(Complex.ImaginaryOne, Complex.ImaginaryOne, Complex.ImaginaryOne, Complex.ImaginaryOne, Complex.ImaginaryOne, Complex.ImaginaryOne, Complex.ImaginaryOne, Complex.ImaginaryOne);
/// <summary>
/// Predefined diagonal-imaginary-one matrix
/// </summary>
public static cmat2x4 ImaginaryIdentity { get; } = new cmat2x4(Complex.ImaginaryOne, Complex.Zero, Complex.Zero, Complex.Zero, Complex.Zero, Complex.ImaginaryOne, Complex.Zero, Complex.Zero);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<Complex> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m02;
yield return m03;
yield return m10;
yield return m11;
yield return m12;
yield return m13;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (2 x 4 = 8).
/// </summary>
public int Count => 8;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public Complex this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m02;
case 3: return m03;
case 4: return m10;
case 5: return m11;
case 6: return m12;
case 7: return m13;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m02 = value; break;
case 3: this.m03 = value; break;
case 4: this.m10 = value; break;
case 5: this.m11 = value; break;
case 6: this.m12 = value; break;
case 7: this.m13 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public Complex this[int col, int row]
{
get
{
return this[col * 4 + row];
}
set
{
this[col * 4 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(cmat2x4 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m02.Equals(rhs.m02) && m03.Equals(rhs.m03))) && ((m10.Equals(rhs.m10) && m11.Equals(rhs.m11)) && (m12.Equals(rhs.m12) && m13.Equals(rhs.m13))));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is cmat2x4 && Equals((cmat2x4) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(cmat2x4 lhs, cmat2x4 rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(cmat2x4 lhs, cmat2x4 rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m02.GetHashCode()) * 397) ^ m03.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m12.GetHashCode()) * 397) ^ m13.GetHashCode();
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public cmat4x2 Transposed => new cmat4x2(m00, m10, m01, m11, m02, m12, m03, m13);
/// <summary>
/// Returns the euclidean length of this matrix.
/// </summary>
public double Length => (double)Math.Sqrt((((m00.LengthSqr() + m01.LengthSqr()) + (m02.LengthSqr() + m03.LengthSqr())) + ((m10.LengthSqr() + m11.LengthSqr()) + (m12.LengthSqr() + m13.LengthSqr()))));
/// <summary>
/// Returns the squared euclidean length of this matrix.
/// </summary>
public double LengthSqr => (((m00.LengthSqr() + m01.LengthSqr()) + (m02.LengthSqr() + m03.LengthSqr())) + ((m10.LengthSqr() + m11.LengthSqr()) + (m12.LengthSqr() + m13.LengthSqr())));
/// <summary>
/// Returns the sum of all fields.
/// </summary>
public Complex Sum => (((m00 + m01) + (m02 + m03)) + ((m10 + m11) + (m12 + m13)));
/// <summary>
/// Returns the euclidean norm of this matrix.
/// </summary>
public double Norm => (double)Math.Sqrt((((m00.LengthSqr() + m01.LengthSqr()) + (m02.LengthSqr() + m03.LengthSqr())) + ((m10.LengthSqr() + m11.LengthSqr()) + (m12.LengthSqr() + m13.LengthSqr()))));
/// <summary>
/// Returns the one-norm of this matrix.
/// </summary>
public double Norm1 => (((m00.Magnitude + m01.Magnitude) + (m02.Magnitude + m03.Magnitude)) + ((m10.Magnitude + m11.Magnitude) + (m12.Magnitude + m13.Magnitude)));
/// <summary>
/// Returns the two-norm of this matrix.
/// </summary>
public double Norm2 => (double)Math.Sqrt((((m00.LengthSqr() + m01.LengthSqr()) + (m02.LengthSqr() + m03.LengthSqr())) + ((m10.LengthSqr() + m11.LengthSqr()) + (m12.LengthSqr() + m13.LengthSqr()))));
/// <summary>
/// Returns the max-norm of this matrix.
/// </summary>
public Complex NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00.Magnitude, m01.Magnitude), m02.Magnitude), m03.Magnitude), m10.Magnitude), m11.Magnitude), m12.Magnitude), m13.Magnitude);
/// <summary>
/// Returns the p-norm of this matrix.
/// </summary>
public double NormP(double p) => Math.Pow((((Math.Pow((double)m00.Magnitude, p) + Math.Pow((double)m01.Magnitude, p)) + (Math.Pow((double)m02.Magnitude, p) + Math.Pow((double)m03.Magnitude, p))) + ((Math.Pow((double)m10.Magnitude, p) + Math.Pow((double)m11.Magnitude, p)) + (Math.Pow((double)m12.Magnitude, p) + Math.Pow((double)m13.Magnitude, p)))), 1 / p);
/// <summary>
/// Executes a matrix-matrix-multiplication cmat2x4 * cmat2 -> cmat2x4.
/// </summary>
public static cmat2x4 operator*(cmat2x4 lhs, cmat2 rhs) => new cmat2x4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11));
/// <summary>
/// Executes a matrix-matrix-multiplication cmat2x4 * cmat3x2 -> cmat3x4.
/// </summary>
public static cmat3x4 operator*(cmat2x4 lhs, cmat3x2 rhs) => new cmat3x4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m03 * rhs.m20 + lhs.m13 * rhs.m21));
/// <summary>
/// Executes a matrix-matrix-multiplication cmat2x4 * cmat4x2 -> cmat4.
/// </summary>
public static cmat4 operator*(cmat2x4 lhs, cmat4x2 rhs) => new cmat4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m03 * rhs.m20 + lhs.m13 * rhs.m21), (lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31), (lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31), (lhs.m02 * rhs.m30 + lhs.m12 * rhs.m31), (lhs.m03 * rhs.m30 + lhs.m13 * rhs.m31));
/// <summary>
/// Executes a matrix-vector-multiplication.
/// </summary>
public static cvec4 operator*(cmat2x4 m, cvec2 v) => new cvec4((m.m00 * v.x + m.m10 * v.y), (m.m01 * v.x + m.m11 * v.y), (m.m02 * v.x + m.m12 * v.y), (m.m03 * v.x + m.m13 * v.y));
/// <summary>
/// Executes a component-wise * (multiply).
/// </summary>
public static cmat2x4 CompMul(cmat2x4 A, cmat2x4 B) => new cmat2x4(A.m00 * B.m00, A.m01 * B.m01, A.m02 * B.m02, A.m03 * B.m03, A.m10 * B.m10, A.m11 * B.m11, A.m12 * B.m12, A.m13 * B.m13);
/// <summary>
/// Executes a component-wise / (divide).
/// </summary>
public static cmat2x4 CompDiv(cmat2x4 A, cmat2x4 B) => new cmat2x4(A.m00 / B.m00, A.m01 / B.m01, A.m02 / B.m02, A.m03 / B.m03, A.m10 / B.m10, A.m11 / B.m11, A.m12 / B.m12, A.m13 / B.m13);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static cmat2x4 CompAdd(cmat2x4 A, cmat2x4 B) => new cmat2x4(A.m00 + B.m00, A.m01 + B.m01, A.m02 + B.m02, A.m03 + B.m03, A.m10 + B.m10, A.m11 + B.m11, A.m12 + B.m12, A.m13 + B.m13);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static cmat2x4 CompSub(cmat2x4 A, cmat2x4 B) => new cmat2x4(A.m00 - B.m00, A.m01 - B.m01, A.m02 - B.m02, A.m03 - B.m03, A.m10 - B.m10, A.m11 - B.m11, A.m12 - B.m12, A.m13 - B.m13);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static cmat2x4 operator+(cmat2x4 lhs, cmat2x4 rhs) => new cmat2x4(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m02 + rhs.m02, lhs.m03 + rhs.m03, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m12 + rhs.m12, lhs.m13 + rhs.m13);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static cmat2x4 operator+(cmat2x4 lhs, Complex rhs) => new cmat2x4(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m02 + rhs, lhs.m03 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m12 + rhs, lhs.m13 + rhs);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static cmat2x4 operator+(Complex lhs, cmat2x4 rhs) => new cmat2x4(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m02, lhs + rhs.m03, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m12, lhs + rhs.m13);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static cmat2x4 operator-(cmat2x4 lhs, cmat2x4 rhs) => new cmat2x4(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m02 - rhs.m02, lhs.m03 - rhs.m03, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m12 - rhs.m12, lhs.m13 - rhs.m13);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static cmat2x4 operator-(cmat2x4 lhs, Complex rhs) => new cmat2x4(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m02 - rhs, lhs.m03 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m12 - rhs, lhs.m13 - rhs);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static cmat2x4 operator-(Complex lhs, cmat2x4 rhs) => new cmat2x4(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m02, lhs - rhs.m03, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m12, lhs - rhs.m13);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static cmat2x4 operator/(cmat2x4 lhs, Complex rhs) => new cmat2x4(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m02 / rhs, lhs.m03 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m12 / rhs, lhs.m13 / rhs);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static cmat2x4 operator/(Complex lhs, cmat2x4 rhs) => new cmat2x4(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m02, lhs / rhs.m03, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m12, lhs / rhs.m13);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static cmat2x4 operator*(cmat2x4 lhs, Complex rhs) => new cmat2x4(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m02 * rhs, lhs.m03 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m12 * rhs, lhs.m13 * rhs);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static cmat2x4 operator*(Complex lhs, cmat2x4 rhs) => new cmat2x4(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m02, lhs * rhs.m03, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m12, lhs * rhs.m13);
}
}
| |
// Copyright 2017, Google LLC All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.ErrorReporting.V1Beta1
{
/// <summary>
/// Settings for a <see cref="ErrorGroupServiceClient"/>.
/// </summary>
public sealed partial class ErrorGroupServiceSettings : ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="ErrorGroupServiceSettings"/>.
/// </summary>
/// <returns>
/// A new instance of the default <see cref="ErrorGroupServiceSettings"/>.
/// </returns>
public static ErrorGroupServiceSettings GetDefault() => new ErrorGroupServiceSettings();
/// <summary>
/// Constructs a new <see cref="ErrorGroupServiceSettings"/> object with default settings.
/// </summary>
public ErrorGroupServiceSettings() { }
private ErrorGroupServiceSettings(ErrorGroupServiceSettings existing) : base(existing)
{
GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetGroupSettings = existing.GetGroupSettings;
UpdateGroupSettings = existing.UpdateGroupSettings;
OnCopy(existing);
}
partial void OnCopy(ErrorGroupServiceSettings existing);
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "Idempotent" <see cref="ErrorGroupServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are:
/// <list type="bullet">
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// </remarks>
public static Predicate<RpcException> IdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable);
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "NonIdempotent" <see cref="ErrorGroupServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// There are no RPC <see cref="StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods.
/// </remarks>
public static Predicate<RpcException> NonIdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes();
/// <summary>
/// "Default" retry backoff for <see cref="ErrorGroupServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" retry backoff for <see cref="ErrorGroupServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" retry backoff for <see cref="ErrorGroupServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial delay: 100 milliseconds</description></item>
/// <item><description>Maximum delay: 60000 milliseconds</description></item>
/// <item><description>Delay multiplier: 1.3</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(100),
maxDelay: TimeSpan.FromMilliseconds(60000),
delayMultiplier: 1.3
);
/// <summary>
/// "Default" timeout backoff for <see cref="ErrorGroupServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" timeout backoff for <see cref="ErrorGroupServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" timeout backoff for <see cref="ErrorGroupServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Maximum timeout: 20000 milliseconds</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(20000),
maxDelay: TimeSpan.FromMilliseconds(20000),
delayMultiplier: 1.0
);
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>ErrorGroupServiceClient.GetGroup</c> and <c>ErrorGroupServiceClient.GetGroupAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>ErrorGroupServiceClient.GetGroup</c> and
/// <c>ErrorGroupServiceClient.GetGroupAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 20000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings GetGroupSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>ErrorGroupServiceClient.UpdateGroup</c> and <c>ErrorGroupServiceClient.UpdateGroupAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>ErrorGroupServiceClient.UpdateGroup</c> and
/// <c>ErrorGroupServiceClient.UpdateGroupAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 20000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings UpdateGroupSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// Creates a deep clone of this object, with all the same property values.
/// </summary>
/// <returns>A deep clone of this <see cref="ErrorGroupServiceSettings"/> object.</returns>
public ErrorGroupServiceSettings Clone() => new ErrorGroupServiceSettings(this);
}
/// <summary>
/// ErrorGroupService client wrapper, for convenient use.
/// </summary>
public abstract partial class ErrorGroupServiceClient
{
/// <summary>
/// The default endpoint for the ErrorGroupService service, which is a host of "clouderrorreporting.googleapis.com" and a port of 443.
/// </summary>
public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("clouderrorreporting.googleapis.com", 443);
/// <summary>
/// The default ErrorGroupService scopes.
/// </summary>
/// <remarks>
/// The default ErrorGroupService scopes are:
/// <list type="bullet">
/// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item>
/// </list>
/// </remarks>
public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] {
"https://www.googleapis.com/auth/cloud-platform",
});
private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes);
// Note: we could have parameterless overloads of Create and CreateAsync,
// documented to just use the default endpoint, settings and credentials.
// Pros:
// - Might be more reassuring on first use
// - Allows method group conversions
// Con: overloads!
/// <summary>
/// Asynchronously creates a <see cref="ErrorGroupServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="ErrorGroupServiceSettings"/>.</param>
/// <returns>The task representing the created <see cref="ErrorGroupServiceClient"/>.</returns>
public static async Task<ErrorGroupServiceClient> CreateAsync(ServiceEndpoint endpoint = null, ErrorGroupServiceSettings settings = null)
{
Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false);
return Create(channel, settings);
}
/// <summary>
/// Synchronously creates a <see cref="ErrorGroupServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="ErrorGroupServiceSettings"/>.</param>
/// <returns>The created <see cref="ErrorGroupServiceClient"/>.</returns>
public static ErrorGroupServiceClient Create(ServiceEndpoint endpoint = null, ErrorGroupServiceSettings settings = null)
{
Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint);
return Create(channel, settings);
}
/// <summary>
/// Creates a <see cref="ErrorGroupServiceClient"/> which uses the specified channel for remote operations.
/// </summary>
/// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param>
/// <param name="settings">Optional <see cref="ErrorGroupServiceSettings"/>.</param>
/// <returns>The created <see cref="ErrorGroupServiceClient"/>.</returns>
public static ErrorGroupServiceClient Create(Channel channel, ErrorGroupServiceSettings settings = null)
{
GaxPreconditions.CheckNotNull(channel, nameof(channel));
ErrorGroupService.ErrorGroupServiceClient grpcClient = new ErrorGroupService.ErrorGroupServiceClient(channel);
return new ErrorGroupServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, ErrorGroupServiceSettings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, ErrorGroupServiceSettings)"/>. Channels which weren't automatically
/// created are not affected.
/// </summary>
/// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, ErrorGroupServiceSettings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, ErrorGroupServiceSettings)"/> 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 Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync();
/// <summary>
/// The underlying gRPC ErrorGroupService client.
/// </summary>
public virtual ErrorGroupService.ErrorGroupServiceClient GrpcClient
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Get the specified group.
/// </summary>
/// <param name="groupName">
/// [Required] The group resource name. Written as
/// <code>projects/<var>projectID</var>/groups/<var>group_name</var></code>.
/// Call
/// <a href="/error-reporting/reference/rest/v1beta1/projects.groupStats/list">
/// <code>groupStats.list</code></a> to return a list of groups belonging to
/// this project.
///
/// Example: <code>projects/my-project-123/groups/my-group</code>
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<ErrorGroup> GetGroupAsync(
GroupName groupName,
CallSettings callSettings = null) => GetGroupAsync(
new GetGroupRequest
{
GroupNameAsGroupName = GaxPreconditions.CheckNotNull(groupName, nameof(groupName)),
},
callSettings);
/// <summary>
/// Get the specified group.
/// </summary>
/// <param name="groupName">
/// [Required] The group resource name. Written as
/// <code>projects/<var>projectID</var>/groups/<var>group_name</var></code>.
/// Call
/// <a href="/error-reporting/reference/rest/v1beta1/projects.groupStats/list">
/// <code>groupStats.list</code></a> to return a list of groups belonging to
/// this project.
///
/// Example: <code>projects/my-project-123/groups/my-group</code>
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<ErrorGroup> GetGroupAsync(
GroupName groupName,
CancellationToken cancellationToken) => GetGroupAsync(
groupName,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Get the specified group.
/// </summary>
/// <param name="groupName">
/// [Required] The group resource name. Written as
/// <code>projects/<var>projectID</var>/groups/<var>group_name</var></code>.
/// Call
/// <a href="/error-reporting/reference/rest/v1beta1/projects.groupStats/list">
/// <code>groupStats.list</code></a> to return a list of groups belonging to
/// this project.
///
/// Example: <code>projects/my-project-123/groups/my-group</code>
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual ErrorGroup GetGroup(
GroupName groupName,
CallSettings callSettings = null) => GetGroup(
new GetGroupRequest
{
GroupNameAsGroupName = GaxPreconditions.CheckNotNull(groupName, nameof(groupName)),
},
callSettings);
/// <summary>
/// Get the specified group.
/// </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 Task<ErrorGroup> GetGroupAsync(
GetGroupRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Get the specified group.
/// </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 ErrorGroup GetGroup(
GetGroupRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Replace the data for the specified group.
/// Fails if the group does not exist.
/// </summary>
/// <param name="group">
/// [Required] The group which replaces the resource on the server.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<ErrorGroup> UpdateGroupAsync(
ErrorGroup group,
CallSettings callSettings = null) => UpdateGroupAsync(
new UpdateGroupRequest
{
Group = GaxPreconditions.CheckNotNull(group, nameof(group)),
},
callSettings);
/// <summary>
/// Replace the data for the specified group.
/// Fails if the group does not exist.
/// </summary>
/// <param name="group">
/// [Required] The group which replaces the resource on the server.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<ErrorGroup> UpdateGroupAsync(
ErrorGroup group,
CancellationToken cancellationToken) => UpdateGroupAsync(
group,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Replace the data for the specified group.
/// Fails if the group does not exist.
/// </summary>
/// <param name="group">
/// [Required] The group which replaces the resource on the server.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual ErrorGroup UpdateGroup(
ErrorGroup group,
CallSettings callSettings = null) => UpdateGroup(
new UpdateGroupRequest
{
Group = GaxPreconditions.CheckNotNull(group, nameof(group)),
},
callSettings);
/// <summary>
/// Replace the data for the specified group.
/// Fails if the group does not exist.
/// </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 Task<ErrorGroup> UpdateGroupAsync(
UpdateGroupRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Replace the data for the specified group.
/// Fails if the group does not exist.
/// </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 ErrorGroup UpdateGroup(
UpdateGroupRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
}
/// <summary>
/// ErrorGroupService client wrapper implementation, for convenient use.
/// </summary>
public sealed partial class ErrorGroupServiceClientImpl : ErrorGroupServiceClient
{
private readonly ApiCall<GetGroupRequest, ErrorGroup> _callGetGroup;
private readonly ApiCall<UpdateGroupRequest, ErrorGroup> _callUpdateGroup;
/// <summary>
/// Constructs a client wrapper for the ErrorGroupService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="ErrorGroupServiceSettings"/> used within this client </param>
public ErrorGroupServiceClientImpl(ErrorGroupService.ErrorGroupServiceClient grpcClient, ErrorGroupServiceSettings settings)
{
GrpcClient = grpcClient;
ErrorGroupServiceSettings effectiveSettings = settings ?? ErrorGroupServiceSettings.GetDefault();
ClientHelper clientHelper = new ClientHelper(effectiveSettings);
_callGetGroup = clientHelper.BuildApiCall<GetGroupRequest, ErrorGroup>(
GrpcClient.GetGroupAsync, GrpcClient.GetGroup, effectiveSettings.GetGroupSettings);
_callUpdateGroup = clientHelper.BuildApiCall<UpdateGroupRequest, ErrorGroup>(
GrpcClient.UpdateGroupAsync, GrpcClient.UpdateGroup, effectiveSettings.UpdateGroupSettings);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void OnConstruction(ErrorGroupService.ErrorGroupServiceClient grpcClient, ErrorGroupServiceSettings effectiveSettings, ClientHelper clientHelper);
/// <summary>
/// The underlying gRPC ErrorGroupService client.
/// </summary>
public override ErrorGroupService.ErrorGroupServiceClient GrpcClient { get; }
// Partial modifier methods contain '_' to ensure no name conflicts with RPC methods.
partial void Modify_GetGroupRequest(ref GetGroupRequest request, ref CallSettings settings);
partial void Modify_UpdateGroupRequest(ref UpdateGroupRequest request, ref CallSettings settings);
/// <summary>
/// Get the specified group.
/// </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 Task<ErrorGroup> GetGroupAsync(
GetGroupRequest request,
CallSettings callSettings = null)
{
Modify_GetGroupRequest(ref request, ref callSettings);
return _callGetGroup.Async(request, callSettings);
}
/// <summary>
/// Get the specified group.
/// </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 ErrorGroup GetGroup(
GetGroupRequest request,
CallSettings callSettings = null)
{
Modify_GetGroupRequest(ref request, ref callSettings);
return _callGetGroup.Sync(request, callSettings);
}
/// <summary>
/// Replace the data for the specified group.
/// Fails if the group does not exist.
/// </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 Task<ErrorGroup> UpdateGroupAsync(
UpdateGroupRequest request,
CallSettings callSettings = null)
{
Modify_UpdateGroupRequest(ref request, ref callSettings);
return _callUpdateGroup.Async(request, callSettings);
}
/// <summary>
/// Replace the data for the specified group.
/// Fails if the group does not exist.
/// </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 ErrorGroup UpdateGroup(
UpdateGroupRequest request,
CallSettings callSettings = null)
{
Modify_UpdateGroupRequest(ref request, ref callSettings);
return _callUpdateGroup.Sync(request, callSettings);
}
}
// Partial classes to enable page-streaming
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureResource
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Resource Flattening for AutoRest
/// </summary>
public partial class AutoRestResourceFlatteningTestService : Microsoft.Rest.ServiceClient<AutoRestResourceFlatteningTestService>, IAutoRestResourceFlatteningTestService, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public Microsoft.Rest.ServiceClientCredentials Credentials { 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>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestResourceFlatteningTestService(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService 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 AutoRestResourceFlatteningTestService(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestResourceFlatteningTestService(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestResourceFlatteningTestService(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestResourceFlatteningTestService(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestResourceFlatteningTestService(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestResourceFlatteningTestService(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestResourceFlatteningTestService(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new System.Uri("http://localhost");
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter());
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter());
DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter());
}
/// <summary>
/// Put External Resource as an Array
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='resourceArray'>
/// External Resource as an Array to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutArrayWithHttpMessagesAsync(System.Collections.Generic.IList<Resource> resourceArray = default(System.Collections.Generic.IList<Resource>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("resourceArray", resourceArray);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutArray", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/array").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(resourceArray != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(resourceArray, this.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get External Resource as an Array
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IList<FlattenedProduct>>> GetArrayWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetArray", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/array").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IList<FlattenedProduct>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IList<FlattenedProduct>>(_responseContent, this.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put External Resource as a Dictionary
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='resourceDictionary'>
/// External Resource as a Dictionary to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutDictionaryWithHttpMessagesAsync(System.Collections.Generic.IDictionary<string, FlattenedProduct> resourceDictionary = default(System.Collections.Generic.IDictionary<string, FlattenedProduct>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("resourceDictionary", resourceDictionary);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutDictionary", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/dictionary").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(resourceDictionary != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(resourceDictionary, this.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get External Resource as a Dictionary
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IDictionary<string, FlattenedProduct>>> GetDictionaryWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetDictionary", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/dictionary").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IDictionary<string, FlattenedProduct>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IDictionary<string, FlattenedProduct>>(_responseContent, this.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put External Resource as a ResourceCollection
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='resourceComplexObject'>
/// External Resource as a ResourceCollection to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutResourceCollectionWithHttpMessagesAsync(ResourceCollection resourceComplexObject = default(ResourceCollection), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("resourceComplexObject", resourceComplexObject);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutResourceCollection", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/resourcecollection").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(resourceComplexObject != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(resourceComplexObject, this.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get External Resource as a ResourceCollection
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ResourceCollection>> GetResourceCollectionWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetResourceCollection", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/resourcecollection").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<ResourceCollection>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ResourceCollection>(_responseContent, this.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using Microsoft.CSharp.RuntimeBinder.Semantics;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Errors
{
internal class UserStringBuilder
{
protected bool fHadUndisplayableStringInError;
protected bool m_buildingInProgress;
protected GlobalSymbolContext m_globalSymbols;
protected StringBuilder m_strBuilder;
public UserStringBuilder(
GlobalSymbolContext globalSymbols)
{
Debug.Assert(globalSymbols != null);
fHadUndisplayableStringInError = false;
m_buildingInProgress = false;
m_globalSymbols = globalSymbols;
}
protected void BeginString()
{
Debug.Assert(!m_buildingInProgress);
m_buildingInProgress = true;
m_strBuilder = new StringBuilder();
}
protected void EndString(out string s)
{
Debug.Assert(m_buildingInProgress);
m_buildingInProgress = false;
s = m_strBuilder.ToString();
m_strBuilder = null;
}
public bool HadUndisplayableString()
{
return fHadUndisplayableStringInError;
}
public void ResetUndisplayableStringFlag()
{
fHadUndisplayableStringInError = false;
}
protected void ErrSK(out string psz, SYMKIND sk)
{
MessageID id;
switch (sk)
{
case SYMKIND.SK_MethodSymbol:
id = MessageID.SK_METHOD;
break;
case SYMKIND.SK_AggregateSymbol:
id = MessageID.SK_CLASS;
break;
case SYMKIND.SK_NamespaceSymbol:
id = MessageID.SK_NAMESPACE;
break;
case SYMKIND.SK_FieldSymbol:
id = MessageID.SK_FIELD;
break;
case SYMKIND.SK_LocalVariableSymbol:
id = MessageID.SK_VARIABLE;
break;
case SYMKIND.SK_PropertySymbol:
id = MessageID.SK_PROPERTY;
break;
case SYMKIND.SK_EventSymbol:
id = MessageID.SK_EVENT;
break;
case SYMKIND.SK_TypeParameterSymbol:
id = MessageID.SK_TYVAR;
break;
case SYMKIND.SK_AssemblyQualifiedNamespaceSymbol:
Debug.Assert(false, "Illegal sk");
id = MessageID.SK_ALIAS;
break;
default:
Debug.Assert(false, "impossible sk");
id = MessageID.SK_UNKNOWN;
break;
}
ErrId(out psz, id);
}
/*
* Create a fill-in string describing a parameter list.
* Does NOT include ()
*/
protected void ErrAppendParamList(TypeArray @params, bool isVarargs, bool isParamArray)
{
if (null == @params)
return;
for (int i = 0; i < @params.size; i++)
{
if (i > 0)
{
ErrAppendString(", ");
}
if (isParamArray && i == @params.size - 1)
{
ErrAppendString("params ");
}
// parameter type name
ErrAppendType(@params.Item(i), null);
}
if (isVarargs)
{
if (@params.size != 0)
{
ErrAppendString(", ");
}
ErrAppendString("...");
}
}
public void ErrAppendString(string str)
{
m_strBuilder.Append(str);
}
public void ErrAppendChar(char ch)
{
m_strBuilder.Append(ch);
}
public void ErrAppendPrintf(string format, params object[] args)
{
ErrAppendString(String.Format(CultureInfo.InvariantCulture, format, args));
}
public void ErrAppendName(Name name)
{
CheckDisplayableName(name);
if (name == GetNameManager().GetPredefName(PredefinedName.PN_INDEXERINTERNAL))
{
ErrAppendString("this");
}
else
{
ErrAppendString(name.Text);
}
}
protected void ErrAppendMethodParentSym(MethodSymbol sym, SubstContext pcxt, out TypeArray substMethTyParams)
{
substMethTyParams = null;
ErrAppendParentSym(sym, pcxt);
}
protected void ErrAppendParentSym(Symbol sym, SubstContext pctx)
{
ErrAppendParentCore(sym.parent, pctx);
}
protected void ErrAppendParentType(CType pType, SubstContext pctx)
{
if (pType.IsErrorType())
{
if (pType.AsErrorType().HasTypeParent())
{
ErrAppendType(pType.AsErrorType().GetTypeParent(), null);
ErrAppendChar('.');
}
else
{
ErrAppendParentCore(pType.AsErrorType().GetNSParent(), pctx);
}
}
else if (pType.IsAggregateType())
{
ErrAppendParentCore(pType.AsAggregateType().GetOwningAggregate(), pctx);
}
else if (pType.GetBaseOrParameterOrElementType() != null)
{
ErrAppendType(pType.GetBaseOrParameterOrElementType(), null);
ErrAppendChar('.');
}
}
protected void ErrAppendParentCore(Symbol parent, SubstContext pctx)
{
if (null == parent)
return;
if (parent == getBSymmgr().GetRootNS())
return;
if (pctx != null && !pctx.FNop() && parent.IsAggregateSymbol() && 0 != parent.AsAggregateSymbol().GetTypeVarsAll().size)
{
CType pType = GetTypeManager().SubstType(parent.AsAggregateSymbol().getThisType(), pctx);
ErrAppendType(pType, null);
}
else
{
ErrAppendSym(parent, null);
}
ErrAppendChar('.');
}
protected void ErrAppendTypeParameters(TypeArray @params, SubstContext pctx, bool forClass)
{
if (@params != null && @params.size != 0)
{
ErrAppendChar('<');
ErrAppendType(@params.Item(0), pctx);
for (int i = 1; i < @params.size; i++)
{
ErrAppendString(",");
ErrAppendType(@params.Item(i), pctx);
}
ErrAppendChar('>');
}
}
protected void ErrAppendMethod(MethodSymbol meth, SubstContext pctx, bool fArgs)
{
if (meth.IsExpImpl() && meth.swtSlot)
{
ErrAppendParentSym(meth, pctx);
// Get the type args from the explicit impl type and substitute using pctx (if there is one).
SubstContext ctx = new SubstContext(GetTypeManager().SubstType(meth.swtSlot.GetType(), pctx).AsAggregateType());
ErrAppendSym(meth.swtSlot.Sym, ctx, fArgs);
// args already added
return;
}
if (meth.isPropertyAccessor())
{
PropertySymbol prop = meth.getProperty();
// this includes the parent class
ErrAppendSym(prop, pctx);
// add accessor name
if (prop.methGet == meth)
{
ErrAppendString(".get");
}
else
{
Debug.Assert(meth == prop.methSet);
ErrAppendString(".set");
}
// args already added
return;
}
if (meth.isEventAccessor())
{
EventSymbol @event = meth.getEvent();
// this includes the parent class
ErrAppendSym(@event, pctx);
// add accessor name
if (@event.methAdd == meth)
{
ErrAppendString(".add");
}
else
{
Debug.Assert(meth == @event.methRemove);
ErrAppendString(".remove");
}
// args already added
return;
}
TypeArray replacementTypeArray = null;
ErrAppendMethodParentSym(meth, pctx, out replacementTypeArray);
if (meth.IsConstructor())
{
// Use the name of the parent class instead of the name "<ctor>".
ErrAppendName(meth.getClass().name);
}
else if (meth.IsDestructor())
{
// Use the name of the parent class instead of the name "Finalize".
ErrAppendChar('~');
ErrAppendName(meth.getClass().name);
}
else if (meth.isConversionOperator())
{
// implicit/explicit
ErrAppendString(meth.isImplicit() ? "implicit" : "explicit");
ErrAppendString(" operator ");
// destination type name
ErrAppendType(meth.RetType, pctx);
}
else if (meth.isOperator)
{
// handle user defined operators
// map from CLS predefined names to "operator <X>"
ErrAppendString("operator ");
//
// This is kinda slow, but the alternative is to add bits to methsym.
//
string operatorName;
OperatorKind op = Operators.OperatorOfMethodName(GetNameManager(), meth.name);
if (Operators.HasDisplayName(op))
{
operatorName = Operators.GetDisplayName(op);
}
else
{
//
// either equals or compare
//
if (meth.name == GetNameManager().GetPredefName(PredefinedName.PN_OPEQUALS))
{
operatorName = "equals";
}
else
{
Debug.Assert(meth.name == GetNameManager().GetPredefName(PredefinedName.PN_OPCOMPARE));
operatorName = "compare";
}
}
ErrAppendString(operatorName);
}
else if (meth.IsExpImpl())
{
if (meth.errExpImpl != null)
ErrAppendType(meth.errExpImpl, pctx, fArgs);
}
else
{
// regular method
ErrAppendName(meth.name);
}
if (null == replacementTypeArray)
{
ErrAppendTypeParameters(meth.typeVars, pctx, false);
}
if (fArgs)
{
// append argument types
ErrAppendChar('(');
if (!meth.computeCurrentBogusState())
{
ErrAppendParamList(GetTypeManager().SubstTypeArray(meth.Params, pctx), meth.isVarargs, meth.isParamArray);
}
ErrAppendChar(')');
}
}
protected void ErrAppendIndexer(IndexerSymbol indexer, SubstContext pctx)
{
ErrAppendString("this[");
ErrAppendParamList(GetTypeManager().SubstTypeArray(indexer.Params, pctx), false, indexer.isParamArray);
ErrAppendChar(']');
}
protected void ErrAppendProperty(PropertySymbol prop, SubstContext pctx)
{
ErrAppendParentSym(prop, pctx);
if (prop.IsExpImpl() && prop.swtSlot.Sym != null)
{
SubstContext ctx = new SubstContext(GetTypeManager().SubstType(prop.swtSlot.GetType(), pctx).AsAggregateType());
ErrAppendSym(prop.swtSlot.Sym, ctx);
}
else if (prop.IsExpImpl())
{
if (prop.errExpImpl != null)
ErrAppendType(prop.errExpImpl, pctx, false);
if (prop.isIndexer())
{
ErrAppendChar('.');
ErrAppendIndexer(prop.AsIndexerSymbol(), pctx);
}
}
else if (prop.isIndexer())
{
ErrAppendIndexer(prop.AsIndexerSymbol(), pctx);
}
else
{
ErrAppendName(prop.name);
}
}
protected void ErrAppendEvent(EventSymbol @event, SubstContext pctx)
{
}
public void ErrAppendId(MessageID id)
{
string str;
ErrId(out str, id);
ErrAppendString(str);
}
/*
* Create a fill-in string describing a symbol.
*/
public void ErrAppendSym(Symbol sym, SubstContext pctx)
{
ErrAppendSym(sym, pctx, true);
}
public void ErrAppendSym(Symbol sym, SubstContext pctx, bool fArgs)
{
switch (sym.getKind())
{
case SYMKIND.SK_NamespaceDeclaration:
// for namespace declarations just convert the namespace
ErrAppendSym(sym.AsNamespaceDeclaration().NameSpace(), null);
break;
case SYMKIND.SK_GlobalAttributeDeclaration:
ErrAppendName(sym.name);
break;
case SYMKIND.SK_AggregateDeclaration:
ErrAppendSym(sym.AsAggregateDeclaration().Agg(), pctx);
break;
case SYMKIND.SK_AggregateSymbol:
{
// Check for a predefined class with a special "nice" name for
// error reported.
string text = PredefinedTypes.GetNiceName(sym.AsAggregateSymbol());
if (text != null)
{
// Found a nice name.
ErrAppendString(text);
}
else if (sym.AsAggregateSymbol().IsAnonymousType())
{
ErrAppendId(MessageID.AnonymousType);
break;
}
else
{
ErrAppendParentSym(sym, pctx);
ErrAppendName(sym.name);
ErrAppendTypeParameters(sym.AsAggregateSymbol().GetTypeVars(), pctx, true);
}
break;
}
case SYMKIND.SK_MethodSymbol:
ErrAppendMethod(sym.AsMethodSymbol(), pctx, fArgs);
break;
case SYMKIND.SK_PropertySymbol:
ErrAppendProperty(sym.AsPropertySymbol(), pctx);
break;
case SYMKIND.SK_EventSymbol:
ErrAppendEvent(sym.AsEventSymbol(), pctx);
break;
case SYMKIND.SK_AssemblyQualifiedNamespaceSymbol:
case SYMKIND.SK_NamespaceSymbol:
if (sym == getBSymmgr().GetRootNS())
{
ErrAppendId(MessageID.GlobalNamespace);
}
else
{
ErrAppendParentSym(sym, null);
ErrAppendName(sym.name);
}
break;
case SYMKIND.SK_FieldSymbol:
ErrAppendParentSym(sym, pctx);
ErrAppendName(sym.name);
break;
case SYMKIND.SK_TypeParameterSymbol:
if (null == sym.name)
{
// It's a standard type variable.
if (sym.AsTypeParameterSymbol().IsMethodTypeParameter())
ErrAppendChar('!');
ErrAppendChar('!');
ErrAppendPrintf("{0}", sym.AsTypeParameterSymbol().GetIndexInTotalParameters());
}
else
ErrAppendName(sym.name);
break;
case SYMKIND.SK_LocalVariableSymbol:
case SYMKIND.SK_LabelSymbol:
case SYMKIND.SK_TransparentIdentifierMemberSymbol:
// Generate symbol name.
ErrAppendName(sym.name);
break;
case SYMKIND.SK_Scope:
case SYMKIND.SK_LambdaScope:
default:
// Shouldn't happen.
Debug.Assert(false, "Bad symbol kind");
break;
}
}
public void ErrAppendType(CType pType, SubstContext pCtx)
{
ErrAppendType(pType, pCtx, true);
}
public void ErrAppendType(CType pType, SubstContext pctx, bool fArgs)
{
if (pctx != null)
{
if (!pctx.FNop())
{
pType = GetTypeManager().SubstType(pType, pctx);
}
// We shouldn't use the SubstContext again so set it to NULL.
pctx = null;
}
switch (pType.GetTypeKind())
{
case TypeKind.TK_AggregateType:
{
AggregateType pAggType = pType.AsAggregateType();
// Check for a predefined class with a special "nice" name for
// error reported.
string text = PredefinedTypes.GetNiceName(pAggType.getAggregate());
if (text != null)
{
// Found a nice name.
ErrAppendString(text);
}
else if (pAggType.getAggregate().IsAnonymousType())
{
ErrAppendPrintf("AnonymousType#{0}", GetTypeID(pAggType));
break;
}
else
{
if (pAggType.outerType != null)
{
ErrAppendType(pAggType.outerType, pctx);
ErrAppendChar('.');
}
else
{
// In a namespace.
ErrAppendParentSym(pAggType.getAggregate(), pctx);
}
ErrAppendName(pAggType.getAggregate().name);
}
ErrAppendTypeParameters(pAggType.GetTypeArgsThis(), pctx, true);
break;
}
case TypeKind.TK_TypeParameterType:
if (null == pType.GetName())
{
// It's a standard type variable.
if (pType.AsTypeParameterType().IsMethodTypeParameter())
{
ErrAppendChar('!');
}
ErrAppendChar('!');
ErrAppendPrintf("{0}", pType.AsTypeParameterType().GetIndexInTotalParameters());
}
else
{
ErrAppendName(pType.GetName());
}
break;
case TypeKind.TK_ErrorType:
if (pType.AsErrorType().HasParent())
{
Debug.Assert(pType.AsErrorType().nameText != null && pType.AsErrorType().typeArgs != null);
ErrAppendParentType(pType, pctx);
ErrAppendName(pType.AsErrorType().nameText);
ErrAppendTypeParameters(pType.AsErrorType().typeArgs, pctx, true);
}
else
{
// Load the string "<error>".
Debug.Assert(null == pType.AsErrorType().typeArgs);
ErrAppendId(MessageID.ERRORSYM);
}
break;
case TypeKind.TK_NullType:
// Load the string "<null>".
ErrAppendId(MessageID.NULL);
break;
case TypeKind.TK_OpenTypePlaceholderType:
// Leave blank.
break;
case TypeKind.TK_BoundLambdaType:
ErrAppendId(MessageID.AnonMethod);
break;
case TypeKind.TK_UnboundLambdaType:
ErrAppendId(MessageID.Lambda);
break;
case TypeKind.TK_MethodGroupType:
ErrAppendId(MessageID.MethodGroup);
break;
case TypeKind.TK_ArgumentListType:
ErrAppendString(TokenFacts.GetText(TokenKind.ArgList));
break;
case TypeKind.TK_ArrayType:
{
CType elementType = pType.AsArrayType().GetBaseElementType();
int rank;
if (null == elementType)
{
Debug.Assert(false, "No element type");
break;
}
ErrAppendType(elementType, pctx);
for (elementType = pType;
elementType != null && elementType.IsArrayType();
elementType = elementType.AsArrayType().GetElementType())
{
rank = elementType.AsArrayType().rank;
// Add [] with (rank-1) commas inside
ErrAppendChar('[');
#if ! CSEE
// known rank.
if (rank > 1)
{
ErrAppendChar('*');
}
#endif
for (int i = rank; i > 1; --i)
{
ErrAppendChar(',');
#if ! CSEE
ErrAppendChar('*');
#endif
}
ErrAppendChar(']');
}
break;
}
case TypeKind.TK_VoidType:
ErrAppendName(GetNameManager().Lookup(TokenFacts.GetText(TokenKind.Void)));
break;
case TypeKind.TK_ParameterModifierType:
// add ref or out
ErrAppendString(pType.AsParameterModifierType().isOut ? "out " : "ref ");
// add base type name
ErrAppendType(pType.AsParameterModifierType().GetParameterType(), pctx);
break;
case TypeKind.TK_PointerType:
// Generate the base type.
ErrAppendType(pType.AsPointerType().GetReferentType(), pctx);
{
// add the trailing *
ErrAppendChar('*');
}
break;
case TypeKind.TK_NullableType:
ErrAppendType(pType.AsNullableType().GetUnderlyingType(), pctx);
ErrAppendChar('?');
break;
case TypeKind.TK_NaturalIntegerType:
default:
// Shouldn't happen.
Debug.Assert(false, "Bad type kind");
break;
}
}
// Returns true if the argument could be converted to a string.
public bool ErrArgToString(out string psz, ErrArg parg, out bool fUserStrings)
{
fUserStrings = false;
psz = null;
bool result = true;
switch (parg.eak)
{
case ErrArgKind.Ids:
ErrId(out psz, parg.ids);
break;
case ErrArgKind.SymKind:
ErrSK(out psz, parg.sk);
break;
case ErrArgKind.Type:
BeginString();
ErrAppendType(parg.pType, null);
EndString(out psz);
fUserStrings = true;
break;
case ErrArgKind.Sym:
BeginString();
ErrAppendSym(parg.sym, null);
EndString(out psz);
fUserStrings = true;
break;
case ErrArgKind.Name:
if (parg.name == GetNameManager().GetPredefinedName(PredefinedName.PN_INDEXERINTERNAL))
{
psz = "this";
}
else
{
psz = parg.name.Text;
}
break;
case ErrArgKind.Str:
psz = parg.psz;
break;
case ErrArgKind.PredefName:
BeginString();
ErrAppendName(GetNameManager().GetPredefName(parg.pdn));
EndString(out psz);
break;
case ErrArgKind.SymWithType:
{
SubstContext ctx = new SubstContext(parg.swtMemo.ats, null);
BeginString();
ErrAppendSym(parg.swtMemo.sym, ctx, true);
EndString(out psz);
fUserStrings = true;
break;
}
case ErrArgKind.MethWithInst:
{
SubstContext ctx = new SubstContext(parg.mpwiMemo.ats, parg.mpwiMemo.typeArgs);
BeginString();
ErrAppendSym(parg.mpwiMemo.sym, ctx, true);
EndString(out psz);
fUserStrings = true;
break;
}
default:
result = false;
break;
}
return result;
}
protected bool IsDisplayableName(Name name)
{
return name != GetNameManager().GetPredefName(PredefinedName.PN_MISSING);
}
protected void CheckDisplayableName(Name name)
{
if (!IsDisplayableName(name))
{
fHadUndisplayableStringInError = true;
}
}
protected NameManager GetNameManager()
{
return m_globalSymbols.GetNameManager();
}
protected TypeManager GetTypeManager()
{
return m_globalSymbols.GetTypes();
}
protected BSYMMGR getBSymmgr()
{
return m_globalSymbols.GetGlobalSymbols();
}
protected int GetTypeID(CType type)
{
return 0;
}
public void ErrId(out string s, MessageID id)
{
s = ErrorFacts.GetMessage(id);
}
}
}
| |
//------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
namespace Microsoft.Tools.ServiceModel.WsatConfig
{
using System;
using System.IO;
using System.Management;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.AccessControl;
using System.Security.Principal;
using Microsoft.Win32;
class StdRegProviderWrapper : IDisposable
{
ManagementClass regClassInstance;
string subKey;
uint hiveValue;
bool ensuredSubKeyExists;
bool ensuredReadAccess;
bool ensuredWriteAccess;
RegistryExceptionHelper registryExceptionHelper;
static class StdRegProvMethods
{
public const string GetDwordValue = "GetDWORDValue";
public const string GetStringValue = "GetStringValue";
public const string GetMultiStringValue = "GetMultiStringValue";
public const string SetDwordValue = "SetDWORDValue";
public const string SetStringValue = "SetStringValue";
public const string SetMultiStringValue = "SetMultiStringValue";
public const string EnumKey = "EnumKey";
public const string CreateRegistryKey = "CreateKey";
public const string CheckAccess = "CheckAccess";
}
static class InputParameters
{
public const string DefKey = "hDefKey";
public const string SubKeyName = "sSubKeyName";
public const string ValueName = "sValueName";
public const string AccessPermission = "uRequired";
public const string DwordValueKey = "uValue";
public const string StringValueKey = "sValue";
}
static class OutputParameters
{
public const string IsAccessGranted = "bGranted";
public const string SubKeyNames = "sNames";
public const string ReturnValue = "ReturnValue";
}
public StdRegProviderWrapper(RegistryHive registryHive, string subKey, string machineName)
{
switch (registryHive)
{
case RegistryHive.ClassesRoot:
this.hiveValue = 0x80000000;
break;
case RegistryHive.CurrentUser:
this.hiveValue = 0x80000001;
break;
case RegistryHive.LocalMachine:
this.hiveValue = 0x80000002;
break;
default:
// We do not support other values here
throw new ArgumentException("remoteHive");
}
registryExceptionHelper = new RegistryExceptionHelper(machineName, registryHive, subKey);
try
{
ConnectionOptions co = null;
if (Utilities.IsLocalMachineName(machineName))
{
machineName = "localhost";
}
else
{
co = new ConnectionOptions();
co.Authentication = AuthenticationLevel.PacketPrivacy;
co.Impersonation = ImpersonationLevel.Impersonate;
}
ManagementScope managementScope = new ManagementScope("\\\\" + machineName + "\\root\\DEFAULT", co);
ManagementPath managementPath = new ManagementPath("StdRegProv");
ObjectGetOptions options = new ObjectGetOptions(new ManagementNamedValueCollection(), TimeSpan.FromSeconds(15), false);
this.regClassInstance = new ManagementClass(managementScope, managementPath, options);
this.subKey = subKey;
}
catch (ManagementException e)
{
throw registryExceptionHelper.CreateRegistryAccessException(e);
}
catch (COMException e) // for RPC_S_SERVER_UNAVAILABLE sort of errors
{
throw registryExceptionHelper.CreateRegistryAccessException(e);
}
}
StdRegProviderWrapper(uint hiveValue, string subKey, ManagementClass regClassInstance)
{
this.hiveValue = hiveValue;
this.subKey = subKey;
this.registryExceptionHelper = new RegistryExceptionHelper(subKey);
this.regClassInstance = new ManagementClass(regClassInstance.Path, regClassInstance.Options);
}
internal StdRegProviderWrapper OpenKey(string subKey)
{
string s = this.subKey;
RegistryExceptionHelper.EnsureEndsWithSlash(ref s);
s += subKey;
return new StdRegProviderWrapper(this.hiveValue, s, regClassInstance);
}
internal uint ReadUInt32(string name, uint defaultValue)
{
return (uint)DoReadData(name, InputParameters.DwordValueKey, defaultValue, StdRegProvMethods.GetDwordValue);
}
internal string ReadString(string name, string defaultValue)
{
return (string)DoReadData(name, InputParameters.StringValueKey, defaultValue, StdRegProvMethods.GetStringValue);
}
internal string[] ReadMultiString(string name, string[] defaultValue)
{
return (string[])DoReadData(name, InputParameters.StringValueKey, defaultValue, StdRegProvMethods.GetMultiStringValue);
}
internal void WriteUInt32(string name, uint value)
{
DoWriteData(name, InputParameters.DwordValueKey, value, StdRegProvMethods.SetDwordValue);
}
internal void WriteString(string name, string value)
{
DoWriteData(name, InputParameters.StringValueKey, value, StdRegProvMethods.SetStringValue);
}
internal void WriteMultiString(string name, string[] value)
{
DoWriteData(name, InputParameters.StringValueKey, value, StdRegProvMethods.SetMultiStringValue);
}
object DoReadData(string name, string valueKey, object defaultValue, string readMethod)
{
EnsureReadAccess();
try
{
ManagementBaseObject inParams = regClassInstance.GetMethodParameters(readMethod);
inParams[InputParameters.DefKey] = this.hiveValue;
inParams[InputParameters.SubKeyName] = subKey;
inParams[InputParameters.ValueName] = name;
ManagementBaseObject outParams = regClassInstance.InvokeMethod(readMethod,
inParams, null);
uint ret = (uint)outParams[OutputParameters.ReturnValue];
if (ret == 0) // zero means success
{
return outParams[valueKey];
}
return defaultValue;
}
#pragma warning suppress 56500
catch (Exception e)
{
// MSDN does not have a spec of possible exceptions for the APIs used above.
// To be safe, we should be a bit more generic in catching exceptions
if (Utilities.IsCriticalException(e))
{
throw;
}
throw registryExceptionHelper.CreateRegistryAccessException(name, e);
}
}
void DoWriteData(string name, string valueKey, object value, string writeMethod)
{
EnsureSubKeyExists();
EnsureWriteAccess();
try
{
ManagementBaseObject inParams = regClassInstance.GetMethodParameters(writeMethod);
inParams[InputParameters.DefKey] = this.hiveValue;
inParams[InputParameters.SubKeyName] = subKey;
inParams[InputParameters.ValueName] = name;
inParams[valueKey] = value;
ManagementBaseObject outParams = regClassInstance.InvokeMethod(writeMethod,
inParams, null);
uint ret = (uint)outParams[OutputParameters.ReturnValue];
if (ret != 0) // zero means success
{
string registryKey = this.subKey;
RegistryExceptionHelper.EnsureEndsWithSlash(ref registryKey);
registryKey += name;
registryExceptionHelper.CreateRegistryWriteException(registryKey, null);
}
}
#pragma warning suppress 56500
catch (Exception e)
{
// MSDN does not have a spec of possible exceptions for the APIs used above.
// To be safe, we should be a bit more generic in catching exceptions
if (Utilities.IsCriticalException(e))
{
throw;
}
throw registryExceptionHelper.CreateRegistryAccessException(name, e);
}
}
void EnsureSubKeyExists()
{
try
{
if (!ensuredSubKeyExists)
{
ManagementBaseObject inParams = regClassInstance.GetMethodParameters(StdRegProvMethods.CreateRegistryKey);
inParams[InputParameters.DefKey] = this.hiveValue;
inParams[InputParameters.SubKeyName] = this.subKey;
ManagementBaseObject outParams = regClassInstance.InvokeMethod(StdRegProvMethods.CreateRegistryKey, inParams, null);
uint ret = (uint)outParams[OutputParameters.ReturnValue];
if (ret != 0) // zero means success
{
throw registryExceptionHelper.CreateRegistryAccessException(ret);
}
ensuredSubKeyExists = true;
}
}
#pragma warning suppress 56500
catch (Exception e)
{
// MSDN does not have a spec of possible exceptions for the APIs used above.
// To be safe, we should be a bit more generic in catching exceptions
if (Utilities.IsCriticalException(e))
{
throw;
}
throw registryExceptionHelper.CreateRegistryAccessException(e);
}
}
const uint ERROR_ACCESS_DENIED = 5;
bool CheckRegistryAccess(UInt32 accessPermission, out bool isAccessGranted)
{
ManagementBaseObject inParams = null;
try
{
inParams = regClassInstance.GetMethodParameters(StdRegProvMethods.CheckAccess);
}
#pragma warning suppress 56500
catch (Exception e)
{
// MSDN does not have a spec of possible exceptions for the APIs used above.
// To be safe, we should be a bit more generic in catching exceptions
if (Utilities.IsCriticalException(e))
{
throw;
}
throw registryExceptionHelper.CreateRegistryAccessException(e);
}
inParams[InputParameters.DefKey] = this.hiveValue;
inParams[InputParameters.SubKeyName] = this.subKey;
inParams[InputParameters.AccessPermission] = accessPermission;
ManagementBaseObject outParams = regClassInstance.InvokeMethod(StdRegProvMethods.CheckAccess, inParams, null);
uint ret = (uint)outParams[OutputParameters.ReturnValue];
isAccessGranted = (bool)outParams[OutputParameters.IsAccessGranted];
return ret == 0 || ret == ERROR_ACCESS_DENIED;
}
const UInt32 KEY_QUERY_VALUE = 0x01;
const UInt32 KEY_SET_VALUE = 0x02;
void EnsureReadAccess()
{
if (!ensuredReadAccess)
{
bool accessGranted = false;
if (CheckRegistryAccess(KEY_QUERY_VALUE, out accessGranted))
{
if (!accessGranted)
{
throw registryExceptionHelper.CreateRegistryAccessException(null);
}
ensuredReadAccess = true;
}
}
}
void EnsureWriteAccess()
{
if (!ensuredWriteAccess)
{
bool accessGranted = false;
if (CheckRegistryAccess(KEY_QUERY_VALUE | KEY_SET_VALUE, out accessGranted))
{
if (!accessGranted)
{
throw registryExceptionHelper.CreateRegistryWriteException(null);
}
ensuredWriteAccess = true;
}
}
}
internal void AdjustRegKeyPermission()
{
try
{
RegistryKey regKey;
regKey = Registry.LocalMachine.OpenSubKey(
WsatKeys.WsatRegKey,
RegistryKeyPermissionCheck.ReadWriteSubTree,
RegistryRights.FullControl);
if (regKey != null)
{
using (regKey)
{
// NetworkService always needs access to the WS-AT key
// On some platforms, it doesn't inherit this permission from the parent MSDTC key
RegistryAccessRule rule = new RegistryAccessRule(
new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null),
RegistryRights.ReadKey,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Allow);
// Ensure the authenticated users have read access to the WS-AT key
// there is a key under the WS-AT key named OleTxUpgradeEnabled that requires the permission
RegistryAccessRule rule2 = new RegistryAccessRule(
new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null),
RegistryRights.ReadKey,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Allow);
RegistrySecurity registrySecurity = regKey.GetAccessControl();
registrySecurity.AddAccessRule(rule);
registrySecurity.AddAccessRule(rule2);
regKey.SetAccessControl(registrySecurity);
}
}
}
catch (SecurityException e)
{
throw registryExceptionHelper.CreateRegistryWriteException(e);
}
catch (ObjectDisposedException e)
{
throw registryExceptionHelper.CreateRegistryWriteException(e);
}
catch (ArgumentNullException e)
{
throw registryExceptionHelper.CreateRegistryWriteException(e);
}
catch (ArgumentException e)
{
throw registryExceptionHelper.CreateRegistryWriteException(e);
}
catch (UnauthorizedAccessException e)
{
throw registryExceptionHelper.CreateRegistryWriteException(e);
}
}
public void Dispose()
{
if (regClassInstance != null)
{
regClassInstance.Dispose();
regClassInstance = null;
}
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
// The parts of a workspace that deal with open documents
public abstract partial class Workspace
{
// open documents
private readonly Dictionary<ProjectId, ISet<DocumentId>> _projectToOpenDocumentsMap = new Dictionary<ProjectId, ISet<DocumentId>>();
// text buffer maps
private readonly Dictionary<SourceTextContainer, DocumentId> _bufferToDocumentInCurrentContextMap = new Dictionary<SourceTextContainer, DocumentId>();
private readonly Dictionary<DocumentId, TextTracker> _textTrackers = new Dictionary<DocumentId, TextTracker>();
/// <summary>
/// True if this workspace supports manually opening and closing documents.
/// </summary>
public virtual bool CanOpenDocuments
{
get { return false; }
}
/// <summary>
/// True if this workspace supports manually changing the active context document of a text buffer.
/// </summary>
internal virtual bool CanChangeActiveContextDocument
{
get { return false; }
}
private static void RemoveIfEmpty<TKey, TValue>(IDictionary<TKey, ISet<TValue>> dictionary, TKey key)
{
ISet<TValue> values;
if (dictionary.TryGetValue(key, out values))
{
if (values.Count == 0)
{
dictionary.Remove(key);
}
}
}
private void ClearOpenDocuments()
{
List<DocumentId> docIds;
using (_stateLock.DisposableWait())
{
docIds = _projectToOpenDocumentsMap.Values.SelectMany(x => x).ToList();
}
foreach (var docId in docIds)
{
this.ClearOpenDocument(docId, isSolutionClosing: true);
}
}
private void ClearOpenDocuments(ProjectId projectId)
{
ISet<DocumentId> openDocs;
using (_stateLock.DisposableWait())
{
_projectToOpenDocumentsMap.TryGetValue(projectId, out openDocs);
}
if (openDocs != null)
{
// ClearOpenDocument will remove the document from the original set.
var copyOfOpenDocs = openDocs.ToList();
foreach (var docId in copyOfOpenDocs)
{
this.ClearOpenDocument(docId);
}
}
}
protected void ClearOpenDocument(DocumentId documentId, bool isSolutionClosing = false)
{
DocumentId currentContextDocumentId;
using (_stateLock.DisposableWait())
{
currentContextDocumentId = this.ClearOpenDocument_NoLock(documentId);
}
// If the solution is closing, then setting the updated document context can fail
// if the host documents are already closed.
if (!isSolutionClosing && this.CanChangeActiveContextDocument && currentContextDocumentId != null)
{
SetDocumentContext(currentContextDocumentId);
}
}
/// <returns>The DocumentId of the current context document for the buffer that was
/// previously attached to the given documentId, if any</returns>
private DocumentId ClearOpenDocument_NoLock(DocumentId documentId)
{
_stateLock.AssertHasLock();
ISet<DocumentId> openDocIds;
if (_projectToOpenDocumentsMap.TryGetValue(documentId.ProjectId, out openDocIds) && openDocIds != null)
{
openDocIds.Remove(documentId);
}
RemoveIfEmpty(_projectToOpenDocumentsMap, documentId.ProjectId);
// Stop tracking the buffer or update the documentId associated with the buffer.
TextTracker tracker;
if (_textTrackers.TryGetValue(documentId, out tracker))
{
tracker.Disconnect();
_textTrackers.Remove(documentId);
var currentContextDocumentId = UpdateCurrentContextMapping_NoLock(tracker.TextContainer, documentId);
if (currentContextDocumentId != null)
{
return currentContextDocumentId;
}
else
{
// No documentIds are attached to this buffer, so stop tracking it.
this.UnregisterText(tracker.TextContainer);
}
}
return null;
}
/// <summary>
/// Open the specified document in the host environment.
/// </summary>
public virtual void OpenDocument(DocumentId documentId, bool activate = true)
{
this.CheckCanOpenDocuments();
}
/// <summary>
/// Close the specified document in the host environment.
/// </summary>
public virtual void CloseDocument(DocumentId documentId)
{
this.CheckCanOpenDocuments();
}
/// <summary>
/// Open the specified additional document in the host environment.
/// </summary>
public virtual void OpenAdditionalDocument(DocumentId documentId, bool activate = true)
{
this.CheckCanOpenDocuments();
}
/// <summary>
/// Close the specified additional document in the host environment.
/// </summary>
public virtual void CloseAdditionalDocument(DocumentId documentId)
{
this.CheckCanOpenDocuments();
}
protected void CheckCanOpenDocuments()
{
if (!this.CanOpenDocuments)
{
throw new NotSupportedException(WorkspacesResources.This_workspace_does_not_support_opening_and_closing_documents);
}
}
protected void CheckProjectDoesNotContainOpenDocuments(ProjectId projectId)
{
if (ProjectHasOpenDocuments(projectId))
{
throw new ArgumentException(string.Format(WorkspacesResources._0_still_contains_open_documents, this.GetProjectName(projectId)));
}
}
private bool ProjectHasOpenDocuments(ProjectId projectId)
{
using (_stateLock.DisposableWait())
{
return _projectToOpenDocumentsMap.ContainsKey(projectId);
}
}
/// <summary>
/// Determines if the document is currently open in the host environment.
/// </summary>
public virtual bool IsDocumentOpen(DocumentId documentId)
{
using (_stateLock.DisposableWait())
{
var openDocuments = this.GetProjectOpenDocuments_NoLock(documentId.ProjectId);
return openDocuments != null && openDocuments.Contains(documentId);
}
}
/// <summary>
/// Gets a list of the currently opened documents.
/// </summary>
public virtual IEnumerable<DocumentId> GetOpenDocumentIds(ProjectId projectId = null)
{
using (_stateLock.DisposableWait())
{
if (_projectToOpenDocumentsMap.Count == 0)
{
return SpecializedCollections.EmptyEnumerable<DocumentId>();
}
if (projectId != null)
{
ISet<DocumentId> documentIds;
if (_projectToOpenDocumentsMap.TryGetValue(projectId, out documentIds))
{
return documentIds;
}
return SpecializedCollections.EmptyEnumerable<DocumentId>();
}
return _projectToOpenDocumentsMap.SelectMany(kvp => kvp.Value).ToImmutableArray();
}
}
/// <summary>
/// Gets the ids for documents associated with a text container.
/// Documents are normally associated with a text container when the documents are opened.
/// </summary>
public virtual IEnumerable<DocumentId> GetRelatedDocumentIds(SourceTextContainer container)
{
if (container == null)
{
throw new ArgumentNullException(nameof(container));
}
using (_stateLock.DisposableWait())
{
return GetRelatedDocumentIds_NoLock(container);
}
}
private ImmutableArray<DocumentId> GetRelatedDocumentIds_NoLock(SourceTextContainer container)
{
DocumentId documentId;
if (!_bufferToDocumentInCurrentContextMap.TryGetValue(container, out documentId))
{
// it is not an opened file
return ImmutableArray<DocumentId>.Empty;
}
return this.CurrentSolution.GetRelatedDocumentIds(documentId);
}
/// <summary>
/// Gets the id for the document associated with the given text container in its current context.
/// Documents are normally associated with a text container when the documents are opened.
/// </summary>
public virtual DocumentId GetDocumentIdInCurrentContext(SourceTextContainer container)
{
if (container == null)
{
throw new ArgumentNullException(nameof(container));
}
using (_stateLock.DisposableWait())
{
return GetDocumentIdInCurrentContext_NoLock(container);
}
}
/// <summary>
/// Finds the <see cref="DocumentId"/> related to the given <see cref="DocumentId"/> that
/// is in the current context. If the <see cref="DocumentId"/> is currently closed, then
/// it is returned directly. If it is open, then this returns the same result that
/// <see cref="GetDocumentIdInCurrentContext(SourceTextContainer)"/> would return for the
/// <see cref="SourceTextContainer"/>. Hosts can override this method to provide more
/// customized behaviors (e.g. special handling of documents in Shared Projects).
/// </summary>
internal virtual DocumentId GetDocumentIdInCurrentContext(DocumentId documentId)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
using (_stateLock.DisposableWait())
{
var container = GetOpenDocumentSourceTextContainer_NoLock(documentId);
return container != null ? GetDocumentIdInCurrentContext_NoLock(container) : documentId;
}
}
private SourceTextContainer GetOpenDocumentSourceTextContainer_NoLock(DocumentId documentId)
{
SourceTextContainer container;
var documentIds = this.CurrentSolution.GetRelatedDocumentIds(documentId);
container = _bufferToDocumentInCurrentContextMap.Where(kvp => documentIds.Contains(kvp.Value)).Select(kvp => kvp.Key).FirstOrDefault();
return container;
}
private DocumentId GetDocumentIdInCurrentContext_NoLock(SourceTextContainer container)
{
DocumentId docId;
bool foundValue = _bufferToDocumentInCurrentContextMap.TryGetValue(container, out docId);
if (foundValue)
{
return docId;
}
else
{
return null;
}
}
/// <summary>
///
/// </summary>
internal virtual void SetDocumentContext(DocumentId documentId)
{
throw new NotSupportedException();
}
/// <summary>
///
/// </summary>
protected void OnDocumentContextUpdated(DocumentId documentId)
{
// TODO: remove linear search
SourceTextContainer container = null;
using (_stateLock.DisposableWait())
{
container = GetOpenDocumentSourceTextContainer_NoLock(documentId);
}
if (container != null)
{
OnDocumentContextUpdated(documentId, container);
}
}
/// <summary>
///
/// </summary>
internal void OnDocumentContextUpdated(DocumentId documentId, SourceTextContainer container)
{
using (_serializationLock.DisposableWait())
{
using (_stateLock.DisposableWait())
{
_bufferToDocumentInCurrentContextMap[container] = documentId;
}
// fire and forget
this.RaiseDocumentActiveContextChangedEventAsync(this.CurrentSolution.GetDocument(documentId));
}
}
protected void CheckDocumentIsClosed(DocumentId documentId)
{
if (this.IsDocumentOpen(documentId))
{
throw new ArgumentException(
string.Format(WorkspacesResources._0_is_still_open,
this.GetDocumentName(documentId)));
}
}
protected void CheckDocumentIsOpen(DocumentId documentId)
{
if (!this.IsDocumentOpen(documentId))
{
throw new ArgumentException(string.Format(
WorkspacesResources._0_is_not_open,
this.GetDocumentName(documentId)));
}
}
private ISet<DocumentId> GetProjectOpenDocuments_NoLock(ProjectId project)
{
_stateLock.AssertHasLock();
ISet<DocumentId> openDocs;
_projectToOpenDocumentsMap.TryGetValue(project, out openDocs);
return openDocs;
}
protected internal void OnDocumentOpened(
DocumentId documentId, SourceTextContainer textContainer,
bool isCurrentContext = true)
{
CheckDocumentIsInCurrentSolution(documentId);
CheckDocumentIsClosed(documentId);
using (_serializationLock.DisposableWait())
{
var oldSolution = this.CurrentSolution;
var oldDocument = oldSolution.GetDocument(documentId);
var oldDocumentState = oldDocument.State;
AddToOpenDocumentMap(documentId);
var newText = textContainer.CurrentText;
Solution currentSolution;
SourceText oldText;
VersionStamp version;
if (oldDocument.TryGetText(out oldText) &&
oldDocument.TryGetTextVersion(out version))
{
// Optimize the case where we've already got the previous text and version.
var newTextAndVersion = GetProperTextAndVersion(oldText, newText, version, oldDocumentState.FilePath);
// keep open document text alive by using PreserveIdentity
currentSolution = oldSolution.WithDocumentText(documentId, newTextAndVersion, PreservationMode.PreserveIdentity);
}
else
{
// We don't have the old text or version. And we don't want to retrieve them
// just yet (as that would cause blocking in this synchronous method). So just
// make a simple loader to do that for us later when requested.
//
// keep open document text alive by using PreserveIdentity
//
// Note: we pass along the newText here so that clients can easily get the text
// of an opened document just by calling TryGetText without any blocking.
currentSolution = oldSolution.WithDocumentTextLoader(documentId,
new ReuseVersionLoader(oldDocument.State, newText), newText, PreservationMode.PreserveIdentity);
}
var newSolution = this.SetCurrentSolution(currentSolution);
SignupForTextChanges(documentId, textContainer, isCurrentContext, (w, id, text, mode) => w.OnDocumentTextChanged(id, text, mode));
var newDoc = newSolution.GetDocument(documentId);
this.OnDocumentTextChanged(newDoc);
// Fire and forget that the workspace is changing.
RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId: documentId);
this.RaiseDocumentOpenedEventAsync(newDoc);
}
this.RegisterText(textContainer);
}
private class ReuseVersionLoader : TextLoader
{
// Capture DocumentState instead of Document so that we don't hold onto the old solution.
private readonly DocumentState _oldDocumentState;
private readonly SourceText _newText;
public ReuseVersionLoader(DocumentState oldDocumentState, SourceText newText)
{
_oldDocumentState = oldDocumentState;
_newText = newText;
}
public override async Task<TextAndVersion> LoadTextAndVersionAsync(
Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
{
var oldText = await _oldDocumentState.GetTextAsync(cancellationToken).ConfigureAwait(false);
var version = await _oldDocumentState.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
return GetProperTextAndVersion(oldText, _newText, version, _oldDocumentState.FilePath);
}
}
private static TextAndVersion GetProperTextAndVersion(SourceText oldText, SourceText newText, VersionStamp version, string filePath)
{
// if the supplied text is the same as the previous text, then also use same version
// otherwise use new version
return oldText.ContentEquals(newText)
? TextAndVersion.Create(newText, version, filePath)
: TextAndVersion.Create(newText, version.GetNewerVersion(), filePath);
}
private void SignupForTextChanges(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext, Action<Workspace, DocumentId, SourceText, PreservationMode> onChangedHandler)
{
var tracker = new TextTracker(this, documentId, textContainer, onChangedHandler);
_textTrackers.Add(documentId, tracker);
this.UpdateCurrentContextMapping_NoLock(textContainer, documentId, isCurrentContext);
tracker.Connect();
}
private void AddToOpenDocumentMap(DocumentId documentId)
{
using (_stateLock.DisposableWait())
{
var openDocuments = GetProjectOpenDocuments_NoLock(documentId.ProjectId);
if (openDocuments != null)
{
openDocuments.Add(documentId);
}
else
{
_projectToOpenDocumentsMap.Add(documentId.ProjectId, new HashSet<DocumentId> { documentId });
}
}
}
protected internal void OnAdditionalDocumentOpened(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext = true)
{
CheckAdditionalDocumentIsInCurrentSolution(documentId);
CheckDocumentIsClosed(documentId);
using (_serializationLock.DisposableWait())
{
var oldSolution = this.CurrentSolution;
var oldDocument = oldSolution.GetAdditionalDocument(documentId);
var oldText = oldDocument.GetTextAsync(CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None);
// keep open document text alive by using PreserveIdentity
var newText = textContainer.CurrentText;
Solution currentSolution;
if (oldText == newText || oldText.ContentEquals(newText))
{
// if the supplied text is the same as the previous text, then also use same version
var version = oldDocument.GetTextVersionAsync(CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None);
var newTextAndVersion = TextAndVersion.Create(newText, version, oldDocument.FilePath);
currentSolution = oldSolution.WithAdditionalDocumentText(documentId, newTextAndVersion, PreservationMode.PreserveIdentity);
}
else
{
currentSolution = oldSolution.WithAdditionalDocumentText(documentId, newText, PreservationMode.PreserveIdentity);
}
var newSolution = this.SetCurrentSolution(currentSolution);
SignupForTextChanges(documentId, textContainer, isCurrentContext, (w, id, text, mode) => w.OnAdditionalDocumentTextChanged(id, text, mode));
// Fire and forget.
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.AdditionalDocumentChanged, oldSolution, newSolution, documentId: documentId);
}
this.RegisterText(textContainer);
}
protected internal void OnDocumentClosed(DocumentId documentId, TextLoader reloader, bool updateActiveContext = false)
{
this.CheckDocumentIsInCurrentSolution(documentId);
this.CheckDocumentIsOpen(documentId);
// When one file from a set of linked or shared documents is closed, we first update
// our data structures and then call SetDocumentContext to tell the project system
// what the new active context is. This can cause reentrancy, so we call
// SetDocumentContext after releasing the serializationLock.
DocumentId currentContextDocumentId;
using (_serializationLock.DisposableWait())
{
// forget any open document info
currentContextDocumentId = ForgetAnyOpenDocumentInfo(documentId);
var oldSolution = this.CurrentSolution;
var oldDocument = oldSolution.GetDocument(documentId);
this.OnDocumentClosing(documentId);
var newSolution = oldSolution.WithDocumentTextLoader(documentId, reloader, PreservationMode.PreserveValue);
newSolution = this.SetCurrentSolution(newSolution);
var newDoc = newSolution.GetDocument(documentId);
this.OnDocumentTextChanged(newDoc);
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId: documentId); // don't wait for this
this.RaiseDocumentClosedEventAsync(newDoc); // don't wait for this
}
if (updateActiveContext && currentContextDocumentId != null && this.CanChangeActiveContextDocument)
{
// Closing this document did not result in the buffer closing, so some
// document is now the current context of that buffer. Fire the appropriate
// events to set that document as the current context of that buffer.
SetDocumentContext(currentContextDocumentId);
}
}
private DocumentId ForgetAnyOpenDocumentInfo(DocumentId documentId)
{
using (_stateLock.DisposableWait())
{
return this.ClearOpenDocument_NoLock(documentId);
}
}
protected internal void OnAdditionalDocumentClosed(DocumentId documentId, TextLoader reloader)
{
this.CheckAdditionalDocumentIsInCurrentSolution(documentId);
using (_serializationLock.DisposableWait())
{
// forget any open document info
ForgetAnyOpenDocumentInfo(documentId);
var oldSolution = this.CurrentSolution;
var oldDocument = oldSolution.GetAdditionalDocument(documentId);
var newSolution = oldSolution.WithAdditionalDocumentTextLoader(documentId, reloader, PreservationMode.PreserveValue);
newSolution = this.SetCurrentSolution(newSolution);
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.AdditionalDocumentChanged, oldSolution, newSolution, documentId: documentId); // don't wait for this
}
}
private void UpdateCurrentContextMapping_NoLock(SourceTextContainer textContainer, DocumentId id, bool isCurrentContext)
{
if (isCurrentContext || !_bufferToDocumentInCurrentContextMap.ContainsKey(textContainer))
{
_bufferToDocumentInCurrentContextMap[textContainer] = id;
}
}
/// <returns>The DocumentId of the current context document attached to the textContainer, if any.</returns>
private DocumentId UpdateCurrentContextMapping_NoLock(SourceTextContainer textContainer, DocumentId id)
{
var documentIds = this.CurrentSolution.GetRelatedDocumentIds(id);
if (documentIds.Length == 0)
{
// no related document. remove map and return no context
_bufferToDocumentInCurrentContextMap.Remove(textContainer);
return null;
}
if (documentIds.Length == 1 && documentIds[0] == id)
{
// only related document is myself. remove map and return no context
_bufferToDocumentInCurrentContextMap.Remove(textContainer);
return null;
}
if (documentIds[0] != id)
{
// there are related documents, set first one as new context.
_bufferToDocumentInCurrentContextMap[textContainer] = documentIds[0];
return documentIds[0];
}
// there are multiple related documents, and first one is myself. return next one.
_bufferToDocumentInCurrentContextMap[textContainer] = documentIds[1];
return documentIds[1];
}
private SourceText GetOpenDocumentText(Solution solution, DocumentId documentId)
{
CheckDocumentIsOpen(documentId);
// text should always be preserved, so TryGetText will succeed.
SourceText text;
var doc = solution.GetDocument(documentId);
doc.TryGetText(out text);
return text;
}
/// <summary>
/// This method is called during OnSolutionReload. Override this method if you want to manipulate
/// the reloaded solution.
/// </summary>
protected virtual Solution AdjustReloadedSolution(Solution oldSolution, Solution reloadedSolution)
{
var newSolution = reloadedSolution;
// keep open documents using same text
foreach (var docId in this.GetOpenDocumentIds())
{
if (newSolution.ContainsDocument(docId))
{
newSolution = newSolution.WithDocumentText(docId, this.GetOpenDocumentText(oldSolution, docId), PreservationMode.PreserveIdentity);
}
}
return newSolution;
}
protected virtual Project AdjustReloadedProject(Project oldProject, Project reloadedProject)
{
var oldSolution = oldProject.Solution;
var newSolution = reloadedProject.Solution;
// keep open documents open using same text
foreach (var docId in this.GetOpenDocumentIds(oldProject.Id))
{
if (newSolution.ContainsDocument(docId))
{
newSolution = newSolution.WithDocumentText(docId, this.GetOpenDocumentText(oldSolution, docId), PreservationMode.PreserveIdentity);
}
}
return newSolution.GetProject(oldProject.Id);
}
}
}
| |
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
using OmniSharp.Models.Highlight;
using OmniSharp.Roslyn.CSharp.Services.Highlighting;
using TestUtility;
using Xunit;
using Xunit.Abstractions;
namespace OmniSharp.Roslyn.CSharp.Tests
{
public class HighlightFacts : AbstractSingleRequestHandlerTestFixture<HighlightingService>
{
public HighlightFacts(ITestOutputHelper output, SharedOmniSharpHostFixture sharedOmniSharpHostFixture)
: base(output, sharedOmniSharpHostFixture)
{
}
protected override string EndpointName => OmniSharpEndpoints.Highlight;
[Fact]
public async Task HighlightSingleLine()
{
var testFile = new TestFile("a.cs", @"
namespace N1
{
class C1 { int n = true; }
}
");
var highlights = await GetHighlightsAsync(testFile, line: 3);
AssertSyntax(highlights, testFile.Content.Code, 3,
Keyword("class"),
ClassName("C1"),
Punctuation("{"),
Keyword("int"),
Field("n"),
Operator("="),
Keyword("true"),
Punctuation(";"),
Punctuation("}"));
}
[Fact]
public async Task HighlightEntireFile()
{
var testFile = new TestFile("a.cs", @"
namespace N1
{
class C1 { int n = true; }
}
");
var highlights = await GetHighlightsAsync(testFile);
AssertSyntax(highlights, testFile.Content.Code, 0,
Keyword("namespace"),
NamespaceName("N1"),
Punctuation("{"),
Keyword("class"),
ClassName("C1"),
Punctuation("{"),
Keyword("int"),
Field("n"),
Operator("="),
Keyword("true"),
Punctuation(";"),
Punctuation("}"),
Punctuation("}")
);
}
[Fact]
public async Task HighlightStringInterpolation()
{
var testFile = new TestFile("a.cs", @"
class C1
{
string s = $""{5}"";
}
");
var highlights = await GetHighlightsAsync(testFile);
AssertSyntax(highlights, testFile.Content.Code, 0,
Keyword("class"),
ClassName("C1"),
Punctuation("{"),
Keyword("string"),
Field("s"),
Operator("="),
String("$\""),
Punctuation("{"),
Number("5"),
Punctuation("}"),
String("\""),
Punctuation(";"),
Punctuation("}")
);
}
[Fact]
public async Task HighlightExcludesUnwantedKeywords()
{
var testFile = new TestFile("a.cs", @"
namespace N1
{
class C1 { int n = true; }
}
");
var highlights = await GetHighlightsAsync(testFile, exclude: HighlightClassification.Keyword);
Assert.DoesNotContain(highlights, x => x.Kind == "keyword");
}
[Fact]
public async Task HighlightExcludesUnwantedPunctuation()
{
var testFile = new TestFile("a.cs", @"
namespace N1
{
class C1 { int n = true; }
}
");
var highlights = await GetHighlightsAsync(testFile, exclude: HighlightClassification.Punctuation);
Assert.DoesNotContain(highlights, x => x.Kind == "punctuation");
}
[Fact]
public async Task HighlightExcludesUnwantedOperators()
{
var testFile = new TestFile("a.cs", @"
namespace N1
{
class C1 { int n = true; }
}
");
var highlights = await GetHighlightsAsync(testFile, exclude: HighlightClassification.Operator);
Assert.DoesNotContain(highlights, x => x.Kind == "operator");
}
[Fact]
public async Task HighlightExcludesUnwantedIdentifiers()
{
var testFile = new TestFile("a.cs", @"
namespace N1
{
class C1 { int n = true; }
}
");
var highlights = await GetHighlightsAsync(testFile, exclude: HighlightClassification.Identifier);
Assert.DoesNotContain(highlights, x => x.Kind == "identifer");
}
[Fact]
public async Task HighlightExcludesUnwantedNames()
{
var testFile = new TestFile("a.cs", @"
namespace N1
{
class C1 { int n = true; }
}
");
var highlights = await GetHighlightsAsync(testFile, exclude: HighlightClassification.Name);
Assert.DoesNotContain(highlights, x => x.Kind.EndsWith("name"));
}
[Fact]
public async Task HighlightDoesNotContainAdditiveKinds()
{
var testFile = new TestFile("a.cs", @"
namespace N1
{
class C1
{
static void M1()
{
}
}
}
");
var highlights = await GetHighlightsAsync(testFile);
foreach (var additiveName in Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.AdditiveTypeNames)
{
Assert.DoesNotContain(highlights, x => x.Kind == additiveName);
}
}
private async Task<HighlightSpan[]> GetHighlightsAsync(TestFile testFile, int? line = null, HighlightClassification? exclude = null)
{
SharedOmniSharpTestHost.AddFilesToWorkspace(testFile);
var requestHandler = GetRequestHandler(SharedOmniSharpTestHost);
var request = new HighlightRequest
{
FileName = testFile.FileName,
Lines = line != null ? new[] { line.Value } : null,
ExcludeClassifications = exclude != null ? new[] { exclude.Value } : null
};
var response = await requestHandler.Handle(request);
return response.Highlights;
}
private static void AssertSyntax(HighlightSpan[] highlights, string code, int startLine, params (string kind, string text)[] expectedTokens)
{
var lineNo = startLine;
var lastIndex = 0;
var lines = SourceText.From(code).Lines;
for (var i = 0; i < highlights.Length; i++)
{
var (kind, text) = expectedTokens[i];
var highlight = highlights[i];
string line;
int start, end;
do
{
line = lines[lineNo].ToString();
start = line.IndexOf(text, lastIndex);
if (start == -1)
{
if (++lineNo >= lines.Count)
{
throw new Exception($"Could not find token {text} in the code");
}
lastIndex = 0;
}
}
while (start == -1);
end = start + text.Length;
lastIndex = end;
Assert.Equal(kind, highlight.Kind);
Assert.Equal(lineNo, highlight.StartLine);
Assert.Equal(lineNo, highlight.EndLine);
Assert.Equal(start, highlight.StartColumn);
Assert.Equal(end, highlight.EndColumn);
}
Assert.Equal(expectedTokens.Length, highlights.Length);
}
private static (string kind, string text) ClassName(string text) => ("class name", text);
private static (string kind, string text) Field(string text) => ("field name", text);
private static (string kind, string text) Identifier(string text) => ("identifier", text);
private static (string kind, string text) NamespaceName(string text) => ("namespace name", text);
private static (string kind, string text) Keyword(string text) => ("keyword", text);
private static (string kind, string text) Number(string text) => ("number", text);
private static (string kind, string text) Operator(string text) => ("operator", text);
private static (string kind, string text) Punctuation(string text) => ("punctuation", text);
private static (string kind, string text) String(string text) => ("string", text);
}
}
| |
#region Apache License, Version 2.0
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;
using log4net;
using NPanday.Model.Pom;
using NPanday.ProjectImporter.Digest.Model;
using NPanday.Utils;
namespace NPanday.ProjectImporter.Converter.Algorithms
{
public class AzurePomConverter : AbstractPomConverter
{
private static readonly ILog log = LogManager.GetLogger(typeof(AzurePomConverter));
public AzurePomConverter(ProjectDigest projectDigest, string mainPomFile, NPanday.Model.Pom.Model parent, string groupId)
: base(projectDigest,mainPomFile,parent, groupId)
{
}
public override void ConvertProjectToPomModel(bool writePom, string scmTag)
{
// relies on this being set everywhere - if it were set per project, this would need to be evaluated on the project references
if (!projectDigest.UseMsDeploy)
{
throw new Exception("You must use Web Deploy 2.0 to package web applications when using Azure projects");
}
GenerateHeader("azure-cloud-service");
//Add SCM Tag
if (scmTag != null && scmTag != string.Empty && Model.parent==null)
{
Scm scmHolder = new Scm();
scmHolder.connection = string.Format("scm:svn:{0}", scmTag);
scmHolder.developerConnection = string.Format("scm:svn:{0}", scmTag);
scmHolder.url = scmTag;
Model.scm = scmHolder;
}
// Add Com Reference Dependencies
if (projectDigest.ComReferenceList.Length > 0)
{
AddComReferenceDependency();
}
//Add Project WebReferences
AddWebReferences();
//Add EmbeddedResources maven-resgen-plugin
AddEmbeddedResources();
// Add Project Inter-dependencies
foreach (ProjectReference projectRef in projectDigest.ProjectReferences)
{
AddProjectReference(projectRef);
}
// Add Project Reference Dependencies
// override the one from the parent to add new types for Azure
AddProjectReferenceDependenciesToList(true);
Plugin plugin = AddPlugin("org.apache.npanday.plugins", "azure-maven-plugin");
if (!string.IsNullOrEmpty(projectDigest.TargetFramework))
AddPluginConfiguration(plugin, "frameworkVersion", projectDigest.TargetFramework);
else
{
// TODO: crude hack until the plugin doesn't require this and picks the right minimum default
AddPluginConfiguration(plugin, "frameworkVersion", "4.0");
}
if (!string.IsNullOrEmpty(projectDigest.ProductVersion) && projectDigest.ProductVersion != "1.6")
AddPluginConfiguration(plugin, "executableVersion", projectDigest.ProductVersion);
if (!string.IsNullOrEmpty(projectDigest.CloudConfig))
{
AddPluginConfiguration(plugin, "serviceConfigurationFile", projectDigest.CloudConfig);
}
Dictionary<string, string> extraRoleContent = new Dictionary<string,string>();
foreach (Content content in projectDigest.Contents)
{
Regex r = new Regex(@"(\w+)Content\\(.+)");
Match m = r.Match(content.IncludePath);
if (m.Success)
{
string role = m.Groups[1].Value;
string include = m.Groups[2].Value;
if (extraRoleContent.ContainsKey(role))
{
extraRoleContent[role] = extraRoleContent[role] + "," + include;
}
else
{
extraRoleContent.Add(role, include);
}
}
else
{
log.WarnFormat("Not copying content declared in project from an unknown path: {0}", content.IncludePath);
}
}
if (extraRoleContent.Count > 0)
{
Plugin antPlugin = AddPlugin("org.apache.maven.plugins", "maven-antrun-plugin", null, false);
Dictionary<string, string> configuration = new Dictionary<string, string>();
AddPluginExecution(antPlugin, "copy-files", new string[] { "run" }, "prepare-package");
XmlDocument xmlDocument = new XmlDocument();
string xmlns = @"http://maven.apache.org/POM/4.0.0";
XmlElement tasks = xmlDocument.CreateElement("tasks", xmlns);
foreach (string role in extraRoleContent.Keys)
{
XmlElement copyTask = xmlDocument.CreateElement("copy", xmlns);
copyTask.SetAttribute("todir", @"${project.build.directory}/packages/" + projectDigest.ProjectName + "/" + role);
XmlElement fileset = xmlDocument.CreateElement("fileset", xmlns);
fileset.SetAttribute("dir", role + "Content");
fileset.SetAttribute("includes", extraRoleContent[role]);
copyTask.AppendChild(fileset);
tasks.AppendChild(copyTask);
}
PluginExecutionConfiguration config = new PluginExecutionConfiguration();
config.Any = new XmlElement[] { tasks };
antPlugin.executions[0].configuration = config;
}
if (writePom)
{
PomHelperUtility.WriteModelToPom(new FileInfo(Path.Combine(projectDigest.FullDirectoryName, "pom.xml")), Model);
}
}
private void AddProjectReference(ProjectReference projectRef)
{
Dependency dependency = new Dependency();
dependency.artifactId = projectRef.Name;
dependency.groupId = !string.IsNullOrEmpty(groupId) ? groupId : projectRef.Name;
dependency.version = string.IsNullOrEmpty(version) ? "1.0-SNAPSHOT" : version;
dependency.type = "dotnet-library";
if (projectRef.ProjectReferenceDigest != null
&& !string.IsNullOrEmpty(projectRef.ProjectReferenceDigest.OutputType))
{
string type = projectRef.ProjectReferenceDigest.OutputType.ToLower();
if (npandayTypeMap.ContainsKey(type))
type = npandayTypeMap[type];
dependency.type = type;
}
if (projectRef.RoleType != null)
{
string targetFramework = projectDigest.TargetFramework;
// TODO: same hack as above - the Azure project doesn't need to target a framework, and instead we should support different ones (See also azure-maven-plugin roleproperties generation)
if (string.IsNullOrEmpty(targetFramework))
targetFramework = "4.0";
if (!projectRef.ProjectReferenceDigest.TargetFramework.Equals(targetFramework))
{
log.WarnFormat("Project reference '{0}' targets a different framework version ({1}) to the Azure project ({2}), and may not succeed when uploaded to Azure.",
projectRef.Name, projectRef.ProjectReferenceDigest.TargetFramework, targetFramework);
}
switch (projectRef.RoleType)
{
case "Web":
dependency.type = "msdeploy-package";
break;
case "Worker":
dependency.type = "dotnet-application";
break;
default:
log.Warn("Unknown role type '" + projectRef.RoleType + "' - treating as a dotnet-library");
break;
}
}
AddDependency(dependency);
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell
{
/// <summary>
///
/// Represents all of the outstanding progress activities received by the host, and includes methods to update that state
/// upon receipt of new ProgressRecords, and to render that state into an array of strings such that ProgressPane can
/// display it.
///
/// The set of activities that we're tracking is logically a binary tree, with siblings in one branch and children in
/// another. For ease of implementation, this tree is represented as lists of lists. We use ArrayList as out list type,
/// although List1 (generic List) would also have worked. I suspect that ArrayList is faster because there are fewer links
/// to twiddle, though I have not measured that.
///
/// This class uses lots of nearly identical helper functions to recursively traverse the tree. If I weren't so pressed
/// for time, I would see if generic methods could be used to collapse the number of traversers.
///
/// </summary>
internal
class PendingProgress
{
#region Updating Code
/// <summary>
///
/// Update the data structures that represent the outstanding progress records reported so far.
///
/// </summary>
/// <param name="sourceId">
///
/// Identifier of the source of the event. This is used as part of the "key" for matching newly received records with
/// records that have already been received. For a record to match (meaning that they refer to the same activity), both
/// the source and activity identifiers need to match.
///
/// </param>
/// <param name="record">
///
/// The ProgressRecord received that will either update the status of an activity which we are already tracking, or
/// represent a new activity that we need to track.
///
/// </param>
internal
void
Update(Int64 sourceId, ProgressRecord record)
{
Dbg.Assert(record != null, "record should not be null");
do
{
if (record.ParentActivityId == record.ActivityId)
{
// ignore malformed records.
break;
}
ArrayList listWhereFound = null;
int indexWhereFound = -1;
ProgressNode foundNode =
FindNodeById(sourceId, record.ActivityId, out listWhereFound, out indexWhereFound);
if (foundNode != null)
{
Dbg.Assert(listWhereFound != null, "node found, but list not identified");
Dbg.Assert(indexWhereFound >= 0, "node found, but index not returned");
if (record.RecordType == ProgressRecordType.Completed)
{
RemoveNodeAndPromoteChildren(listWhereFound, indexWhereFound);
break;
}
if (record.ParentActivityId == foundNode.ParentActivityId)
{
// record is an update to an existing activity. Copy the record data into the found node, and
// reset the age of the node.
foundNode.Activity = record.Activity;
foundNode.StatusDescription = record.StatusDescription;
foundNode.CurrentOperation = record.CurrentOperation;
foundNode.PercentComplete = Math.Min(record.PercentComplete, 100);
foundNode.SecondsRemaining = record.SecondsRemaining;
foundNode.Age = 0;
break;
}
else
{
// The record's parent Id mismatches with that of the found node's. We interpret
// this to mean that the activity represented by the record (and the found node) is
// being "re-parented" elsewhere. So we remove the found node and treat the record
// as a new activity.
RemoveNodeAndPromoteChildren(listWhereFound, indexWhereFound);
}
}
// At this point, the record's activity is not in the tree. So we need to add it.
if (record.RecordType == ProgressRecordType.Completed)
{
// We don't track completion records that don't correspond to activities we're not
// already tracking.
break;
}
ProgressNode newNode = new ProgressNode(sourceId, record);
// If we're adding a node, and we have no more space, then we need to pick a node to evict.
while (_nodeCount >= maxNodeCount)
{
EvictNode();
}
if (newNode.ParentActivityId >= 0)
{
ProgressNode parentNode = FindNodeById(newNode.SourceId, newNode.ParentActivityId);
if (parentNode != null)
{
if (parentNode.Children == null)
{
parentNode.Children = new ArrayList();
}
AddNode(parentNode.Children, newNode);
break;
}
// The parent node is not in the tree. Make the new node's parent the root,
// and add it to the tree. If the parent ever shows up, then the next time
// we receive a record for this activity, the parent id's won't match, and the
// activity will be properly re-parented.
newNode.ParentActivityId = -1;
}
AddNode(_topLevelNodes, newNode);
} while (false);
// At this point the tree is up-to-date. Make a pass to age all of the nodes
AgeNodesAndResetStyle();
}
private
void
EvictNode()
{
ArrayList listWhereFound = null;
int indexWhereFound = -1;
ProgressNode oldestNode = FindOldestLeafmostNode(out listWhereFound, out indexWhereFound);
if (oldestNode == null)
{
// Well that's a surprise. There's got to be at least one node there that's older than 0.
Dbg.Assert(false, "Must be an old node in the tree somewhere");
// We'll just pick the root node, then.
RemoveNode(_topLevelNodes, 0);
}
else
{
RemoveNode(listWhereFound, indexWhereFound);
}
}
/// <summary>
///
/// Removes a node from the tree.
///
/// </summary>
/// <param name="nodes">
///
/// List in the tree from which the node is to be removed.
///
/// </param>
/// <param name="indexToRemove">
///
/// Index into the list of the node to be removed.
///
/// </param>
private
void
RemoveNode(ArrayList nodes, int indexToRemove)
{
#if DEBUG || ASSERTIONS_TRACE
ProgressNode nodeToRemove = (ProgressNode)nodes[indexToRemove];
Dbg.Assert(nodes != null, "can't remove nodes from a null list");
Dbg.Assert(indexToRemove < nodes.Count, "index is not in list");
Dbg.Assert(nodes[indexToRemove] != null, "no node at specified index");
Dbg.Assert(nodeToRemove.Children == null || nodeToRemove.Children.Count == 0, "can't remove a node with children");
#endif
nodes.RemoveAt(indexToRemove);
--_nodeCount;
#if DEBUG || ASSERTIONS_ON
Dbg.Assert(_nodeCount == this.CountNodes(), "We've lost track of the number of nodes in the tree");
#endif
}
private
void
RemoveNodeAndPromoteChildren(ArrayList nodes, int indexToRemove)
{
ProgressNode nodeToRemove = (ProgressNode)nodes[indexToRemove];
Dbg.Assert(nodes != null, "can't remove nodes from a null list");
Dbg.Assert(indexToRemove < nodes.Count, "index is not in list");
Dbg.Assert(nodeToRemove != null, "no node at specified index");
if (nodeToRemove == null)
{
return;
}
if (nodeToRemove.Children != null)
{
// promote the children.
for (int i = 0; i < nodeToRemove.Children.Count; ++i)
{
// unparent the children. If the children are ever updated again, they will be reparented.
((ProgressNode)nodeToRemove.Children[i]).ParentActivityId = -1;
}
// add the children as siblings
nodes.RemoveAt(indexToRemove);
--_nodeCount;
nodes.InsertRange(indexToRemove, nodeToRemove.Children);
#if DEBUG || ASSERTIONS_TRACE
Dbg.Assert(_nodeCount == this.CountNodes(), "We've lost track of the number of nodes in the tree");
#endif
}
else
{
// nothing to promote
RemoveNode(nodes, indexToRemove);
return;
}
}
/// <summary>
///
/// Adds a node to the tree, first removing the oldest node if the tree is too large.
///
/// </summary>
/// <param name="nodes">
///
/// List in the tree where the node is to be added.
///
/// </param>
/// <param name="nodeToAdd">
///
/// Node to be added.
///
/// </param>
private
void
AddNode(ArrayList nodes, ProgressNode nodeToAdd)
{
nodes.Add(nodeToAdd);
++_nodeCount;
#if DEBUG || ASSERTIONS_TRACE
Dbg.Assert(_nodeCount == this.CountNodes(), "We've lost track of the number of nodes in the tree");
Dbg.Assert(_nodeCount <= maxNodeCount, "Too many nodes in tree!");
#endif
}
private
class FindOldestNodeVisitor : NodeVisitor
{
internal override
bool
Visit(ProgressNode node, ArrayList listWhereFound, int indexWhereFound)
{
if (node.Age >= _oldestSoFar)
{
_oldestSoFar = node.Age;
FoundNode = node;
this.ListWhereFound = listWhereFound;
this.IndexWhereFound = indexWhereFound;
}
return true;
}
internal
ProgressNode
FoundNode;
internal
ArrayList
ListWhereFound;
internal
int
IndexWhereFound = -1;
private int _oldestSoFar;
}
private
ProgressNode
FindOldestLeafmostNodeHelper(ArrayList treeToSearch, out ArrayList listWhereFound, out int indexWhereFound)
{
listWhereFound = null;
indexWhereFound = -1;
FindOldestNodeVisitor v = new FindOldestNodeVisitor();
NodeVisitor.VisitNodes(treeToSearch, v);
listWhereFound = v.ListWhereFound;
indexWhereFound = v.IndexWhereFound;
#if DEBUG || ASSERTIONS_TRACE
if (v.FoundNode == null)
{
Dbg.Assert(listWhereFound == null, "list should be null when no node found");
Dbg.Assert(indexWhereFound == -1, "index should indicate no node found");
Dbg.Assert(_topLevelNodes.Count == 0, "if there is no oldest node, then the tree must be empty");
Dbg.Assert(_nodeCount == 0, "if there is no oldest node, then the tree must be empty");
}
#endif
return v.FoundNode;
}
private
ProgressNode
FindOldestLeafmostNode(out ArrayList listWhereFound, out int indexWhereFound)
{
listWhereFound = null;
indexWhereFound = -1;
ProgressNode result = null;
ArrayList treeToSearch = _topLevelNodes;
do
{
result = FindOldestLeafmostNodeHelper(treeToSearch, out listWhereFound, out indexWhereFound);
if (result == null || result.Children == null || result.Children.Count == 0)
{
break;
}
// search the subtree for the oldest child
treeToSearch = result.Children;
} while (true);
return result;
}
/// <summary>
///
/// Convenience overload.
///
/// </summary>
private
ProgressNode
FindNodeById(Int64 sourceId, int activityId)
{
ArrayList listWhereFound = null;
int indexWhereFound = -1;
return
FindNodeById(sourceId, activityId, out listWhereFound, out indexWhereFound);
}
private
class FindByIdNodeVisitor : NodeVisitor
{
internal
FindByIdNodeVisitor(Int64 sourceIdToFind, int activityIdToFind)
{
_sourceIdToFind = sourceIdToFind;
_idToFind = activityIdToFind;
}
internal override
bool
Visit(ProgressNode node, ArrayList listWhereFound, int indexWhereFound)
{
if (node.ActivityId == _idToFind && node.SourceId == _sourceIdToFind)
{
this.FoundNode = node;
this.ListWhereFound = listWhereFound;
this.IndexWhereFound = indexWhereFound;
return false;
}
return true;
}
internal
ProgressNode
FoundNode;
internal
ArrayList
ListWhereFound;
internal
int
IndexWhereFound = -1;
private int _idToFind = -1;
private Int64 _sourceIdToFind;
}
/// <summary>
///
/// Finds a node with a given ActivityId in provided set of nodes. Recursively walks the set of nodes and their children.
///
/// </summary>
/// <param name="sourceId">
///
/// Identifier of the source of the record.
///
/// </param>
/// <param name="activityId">
///
/// ActivityId to search for.
///
/// </param>
/// <param name="listWhereFound">
///
/// Receives reference to the List where the found node was located, or null if no suitable node was found.
///
/// </param>
/// <param name="indexWhereFound">
///
/// Receives the index into listWhereFound that indicating where in the list the node was located, or -1 if
/// no suitable node was found.
///
/// </param>
/// <returns>
///
/// The found node, or null if no suitable node was located.
///
/// </returns>
private
ProgressNode
FindNodeById(Int64 sourceId, int activityId, out ArrayList listWhereFound, out int indexWhereFound)
{
listWhereFound = null;
indexWhereFound = -1;
FindByIdNodeVisitor v = new FindByIdNodeVisitor(sourceId, activityId);
NodeVisitor.VisitNodes(_topLevelNodes, v);
listWhereFound = v.ListWhereFound;
indexWhereFound = v.IndexWhereFound;
#if DEBUG || ASSERTIONS_TRACE
if (v.FoundNode == null)
{
Dbg.Assert(listWhereFound == null, "list should be null when no node found");
Dbg.Assert(indexWhereFound == -1, "index should indicate no node found");
}
#endif
return v.FoundNode;
}
/// <summary>
///
/// Finds the oldest node with a given rendering style that is at least as old as a given age.
///
/// </summary>
/// <param name="nodes">
///
/// List of nodes to search. Child lists of each node in this list will also be searched.
///
/// </param>
/// <param name="oldestSoFar"></param>
///
/// The minimum age of the node to be located. To find the oldest node, pass 0.
///
/// <param name="style">
///
/// The rendering style of the node to be located.
///
/// </param>
/// <returns>
///
/// The found node, or null if no suitable node was located.
///
/// </returns>
private
ProgressNode
FindOldestNodeOfGivenStyle(ArrayList nodes, int oldestSoFar, ProgressNode.RenderStyle style)
{
if (nodes == null)
{
return null;
}
ProgressNode found = null;
for (int i = 0; i < nodes.Count; ++i)
{
ProgressNode node = (ProgressNode)nodes[i];
Dbg.Assert(node != null, "nodes should not contain null elements");
if (node.Age >= oldestSoFar && node.Style == style)
{
found = node;
oldestSoFar = found.Age;
}
if (node.Children != null)
{
ProgressNode child = FindOldestNodeOfGivenStyle(node.Children, oldestSoFar, style);
if (child != null)
{
// In this universe, parents can be younger than their children. We found a child older than us.
found = child;
oldestSoFar = found.Age;
}
}
}
#if DEBUG || ASSERTIONS_TRACE
if (found != null)
{
Dbg.Assert(found.Style == style, "unexpected style");
Dbg.Assert(found.Age >= oldestSoFar, "unexpected age");
}
#endif
return found;
}
private
class AgeAndResetStyleVisitor : NodeVisitor
{
internal override
bool
Visit(ProgressNode node, ArrayList unused, int unusedToo)
{
node.Age = Math.Min(node.Age + 1, Int32.MaxValue - 1);
node.Style = ProgressNode.RenderStyle.FullPlus;
return true;
}
}
/// <summary>
///
/// Increments the age of each of the nodes in the given list, and all their children. Also sets the rendering
/// style of each node to "full."
///
/// All nodes are aged every time a new ProgressRecord is received.
///
/// </summary>
private
void
AgeNodesAndResetStyle()
{
AgeAndResetStyleVisitor arsv = new AgeAndResetStyleVisitor();
NodeVisitor.VisitNodes(_topLevelNodes, arsv);
}
#endregion // Updating Code
#region Rendering Code
/// <summary>
///
/// Generates an array of strings representing as much of the outstanding progress activties as possible within the given
/// space. As more outstanding activities are collected, nodes are "compressed" (i.e. rendered in an increasing terse
/// fashion) in order to display as many as possible. Ultimately, some nodes may be compressed to the point of
/// invisibility. The oldest nodes are compressed first.
///
/// </summary>
/// <param name="maxWidth">
///
/// The maximum width (in BufferCells) that the rendering may consume.
///
/// </param>
/// <param name="maxHeight">
///
/// The maximum height (in BufferCells) that the rendering may consume.
///
/// </param>
/// <param name="rawUI">
///
/// The PSHostRawUserInterface used to gauge string widths in the rendering.
///
/// </param>
/// <returns>
///
/// An array of strings containing the textual representation of the outstanding progress activities.
///
/// </returns>
internal
string[]
Render(int maxWidth, int maxHeight, PSHostRawUserInterface rawUI)
{
Dbg.Assert(_topLevelNodes != null, "Shouldn't need to render progress if no data exists");
Dbg.Assert(maxWidth > 0, "maxWidth is too small");
Dbg.Assert(maxHeight >= 3, "maxHeight is too small");
if (_topLevelNodes == null || _topLevelNodes.Count <= 0)
{
// we have nothing to render.
return null;
}
int invisible = 0;
if (TallyHeight(rawUI, maxHeight, maxWidth) > maxHeight)
{
// This will smash down nodes until the tree will fit into the alloted number of lines. If in the
// process some nodes were made invisible, we will add a line to the display to say so.
invisible = CompressToFit(rawUI, maxHeight, maxWidth);
}
ArrayList result = new ArrayList();
string border = new string(' ', maxWidth);
result.Add(border);
RenderHelper(result, _topLevelNodes, 0, maxWidth, rawUI);
if (invisible == 1)
{
result.Add(
" "
+ StringUtil.Format(
ProgressNodeStrings.InvisibleNodesMessageSingular,
invisible));
}
else if (invisible > 1)
{
result.Add(
" "
+ StringUtil.Format(
ProgressNodeStrings.InvisibleNodesMessagePlural,
invisible));
}
result.Add(border);
return (string[])result.ToArray(typeof(string));
}
/// <summary>
///
/// Helper function for Render(). Recursively renders nodes.
///
/// </summary>
/// <param name="strings">
///
/// The rendered strings so far. Additional rendering will be appended.
///
/// </param>
/// <param name="nodes">
///
/// The nodes to be rendered. All child nodes will also be rendered.
///
/// </param>
/// <param name="indentation">
///
/// The current indentation level (in BufferCells).
///
/// </param>
/// <param name="maxWidth">
///
/// The maximum number of BufferCells that the rendering can consume, horizontally.
///
/// </param>
/// <param name="rawUI">
///
/// The PSHostRawUserInterface used to gauge string widths in the rendering.
///
/// </param>
private
void
RenderHelper(ArrayList strings, ArrayList nodes, int indentation, int maxWidth, PSHostRawUserInterface rawUI)
{
Dbg.Assert(strings != null, "strings should not be null");
Dbg.Assert(nodes != null, "nodes should not be null");
if (nodes == null)
{
return;
}
foreach (ProgressNode node in nodes)
{
int lines = strings.Count;
node.Render(strings, indentation, maxWidth, rawUI);
if (node.Children != null)
{
// indent only if the rendering of node actually added lines to the strings.
int indentationIncrement = (strings.Count > lines) ? 2 : 0;
RenderHelper(strings, node.Children, indentation + indentationIncrement, maxWidth, rawUI);
}
}
}
private
class HeightTallyer : NodeVisitor
{
internal HeightTallyer(PSHostRawUserInterface rawUi, int maxHeight, int maxWidth)
{
_rawUi = rawUi;
_maxHeight = maxHeight;
_maxWidth = maxWidth;
}
internal override
bool
Visit(ProgressNode node, ArrayList unused, int unusedToo)
{
Tally += node.LinesRequiredMethod(_rawUi, _maxWidth);
// We don't need to walk all the nodes, once it's larger than the max height, we should stop
if (Tally > _maxHeight)
{
return false;
}
return true;
}
private PSHostRawUserInterface _rawUi;
private int _maxHeight;
private int _maxWidth;
internal int Tally;
}
/// <summary>
///
/// Tallies up the number of BufferCells vertically that will be required to show all the ProgressNodes in the given
/// list, and all of their children.
///
/// </summary>
/// <param name="maxHeight">
///
/// The maximum height (in BufferCells) that the rendering may consume.
///
/// </param>
/// <param name="rawUi">
///
/// The PSHostRawUserInterface used to gauge string widths in the rendering.
///
/// </param>
/// <returns>
///
/// The vertical height (in BufferCells) that will be required to show all of the nodes in the given list.
///
/// </returns>
/// <param name="maxWidth">
///
///
///
/// </param>
private int TallyHeight(PSHostRawUserInterface rawUi, int maxHeight, int maxWidth)
{
HeightTallyer ht = new HeightTallyer(rawUi, maxHeight, maxWidth);
NodeVisitor.VisitNodes(_topLevelNodes, ht);
return ht.Tally;
}
#if DEBUG || ASSERTIONS_TRACE
/// <summary>
///
/// Debugging code. Verifies that all of the nodes in the given list have the given style.
///
/// </summary>
/// <param name="nodes"></param>
/// <param name="style"></param>
/// <returns></returns>
private
bool
AllNodesHaveGivenStyle(ArrayList nodes, ProgressNode.RenderStyle style)
{
if (nodes == null)
{
return false;
}
for (int i = 0; i < nodes.Count; ++i)
{
ProgressNode node = (ProgressNode)nodes[i];
Dbg.Assert(node != null, "nodes should not contain null elements");
if (node.Style != style)
{
return false;
}
if (node.Children != null)
{
if (!AllNodesHaveGivenStyle(node.Children, style))
{
return false;
}
}
}
return true;
}
/// <summary>
///
/// Debugging code. NodeVisitor that counts up the number of nodes in the tree.
///
/// </summary>
private
class
CountingNodeVisitor : NodeVisitor
{
internal override
bool
Visit(ProgressNode unused, ArrayList unusedToo, int unusedThree)
{
++Count;
return true;
}
internal
int
Count;
}
/// <summary>
///
/// Debugging code. Counts the number of nodes in the tree of nodes.
///
/// </summary>
/// <returns>
///
/// The number of nodes in the tree.
///
/// </returns>
private
int
CountNodes()
{
CountingNodeVisitor cnv = new CountingNodeVisitor();
NodeVisitor.VisitNodes(_topLevelNodes, cnv);
return cnv.Count;
}
#endif
/// <summary>
///
/// Helper function to CompressToFit. Considers compressing nodes from one level to another.
///
/// </summary>
/// <param name="rawUi">
///
/// The PSHostRawUserInterface used to gauge string widths in the rendering.
///
/// </param>
/// <param name="maxHeight">
///
/// The maximum height (in BufferCells) that the rendering may consume.
///
/// </param>
/// <param name="maxWidth">
///
/// The maximum width (in BufferCells) that the rendering may consume.
///
/// </param>
/// <param name="nodesCompressed">
///
/// Receives the number of nodes that were compressed. If the result of the method is false, then this will be the total
/// number of nodes being tracked (i.e. all of them will have been compressed).
///
/// </param>
/// <param name="priorStyle">
///
/// The rendering style (e.g. "compression level") that the nodes are expected to currently have.
///
/// </param>
/// <param name="newStyle">
///
/// The new rendering style that a node will have when it is compressed. If the result of the method is false, then all
/// nodes will have this rendering style.
///
/// </param>
/// <returns>
///
/// true to indicate that the nodes are compressed to the point that their rendering will fit within the constraint, or
/// false to indicate that all of the nodes are compressed to a given level, but that the rendering still can't fit
/// within the constraint.
///
/// </returns>
private
bool
CompressToFitHelper(
PSHostRawUserInterface rawUi,
int maxHeight,
int maxWidth,
out int nodesCompressed,
ProgressNode.RenderStyle priorStyle,
ProgressNode.RenderStyle newStyle)
{
nodesCompressed = 0;
int age = 0;
do
{
ProgressNode node = FindOldestNodeOfGivenStyle(_topLevelNodes, age, priorStyle);
if (node == null)
{
// We've compressed every node of the prior style already.
break;
}
node.Style = newStyle;
++nodesCompressed;
if (TallyHeight(rawUi, maxHeight, maxWidth) <= maxHeight)
{
return true;
}
} while (true);
// If we get all the way to here, then we've compressed all the nodes and we still don't fit.
#if DEBUG || ASSERTIONS_TRACE
Dbg.Assert(
nodesCompressed == CountNodes(),
"We should have compressed every node in the tree.");
Dbg.Assert(
AllNodesHaveGivenStyle(_topLevelNodes, newStyle),
"We should have compressed every node in the tree.");
#endif
return false;
}
/// <summary>
///
/// "Compresses" the nodes representing the outstanding progress activities until their rendering will fit within a
/// "given height, or until they are compressed to a given level. The oldest nodes are compressed first.
///
/// This is a 4-stage process -- from least compressed to "invisible". At each stage we find the oldest nodes in the
/// tree and change their rendering style to a more compact style. As soon as the rendering of the nodes will fit within
/// the maxHeight, we stop. The result is that the most recent nodes will be the least compressed, the idea being that
/// the rendering should show the most recently updated activities with the most complete rendering for them possible.
///
/// </summary>
/// <param name="rawUi">
///
/// The PSHostRawUserInterface used to gauge string widths in the rendering.
///
/// </param>
/// <param name="maxHeight">
///
/// The maximum height (in BufferCells) that the rendering may consume.
///
/// </param>
/// <param name="maxWidth">
///
/// The maximum width (in BufferCells) that the rendering may consume.
///
/// </param>
/// <returns>
///
/// The number of nodes that were made invisible during the compression.
///
///</returns>
private
int
CompressToFit(PSHostRawUserInterface rawUi, int maxHeight, int maxWidth)
{
Dbg.Assert(_topLevelNodes != null, "Shouldn't need to compress if no data exists");
int nodesCompressed = 0;
// This algorithm potentially makes many, many passeses over the tree. It might be possible to optimize
// that some, but I'm not trying to be too clever just yet.
if (
CompressToFitHelper(
rawUi,
maxHeight,
maxWidth,
out nodesCompressed,
ProgressNode.RenderStyle.FullPlus,
ProgressNode.RenderStyle.Full))
{
return 0;
}
if (
CompressToFitHelper(
rawUi,
maxHeight,
maxWidth,
out nodesCompressed,
ProgressNode.RenderStyle.Full,
ProgressNode.RenderStyle.Compact))
{
return 0;
}
if (
CompressToFitHelper(
rawUi,
maxHeight,
maxWidth,
out nodesCompressed,
ProgressNode.RenderStyle.Compact,
ProgressNode.RenderStyle.Minimal))
{
return 0;
}
if (
CompressToFitHelper(
rawUi,
maxHeight,
maxWidth,
out nodesCompressed,
ProgressNode.RenderStyle.Minimal,
ProgressNode.RenderStyle.Invisible))
{
// The nodes that we compressed here are now invisible.
return nodesCompressed;
}
Dbg.Assert(false, "with all nodes invisible, we should never reach this point.");
return 0;
}
#endregion // Rendering Code
#region Utility Code
private abstract
class NodeVisitor
{
/// <summary>
///
/// Called for each node in the tree.
///
/// </summary>
/// <param name="node">
///
/// The node being visited.
///
/// </param>
/// <param name="listWhereFound">
///
/// The list in which the node resides.
///
/// </param>
/// <param name="indexWhereFound">
///
/// The index into listWhereFound of the node.
///
/// </param>
/// <returns>
///
/// true to continue visiting nodes, false if not.
///
/// </returns>
internal abstract
bool
Visit(ProgressNode node, ArrayList listWhereFound, int indexWhereFound);
internal static
void
VisitNodes(ArrayList nodes, NodeVisitor v)
{
if (nodes == null)
{
return;
}
for (int i = 0; i < nodes.Count; ++i)
{
ProgressNode node = (ProgressNode)nodes[i];
Dbg.Assert(node != null, "nodes should not contain null elements");
if (!v.Visit(node, nodes, i))
{
return;
}
if (node.Children != null)
{
VisitNodes(node.Children, v);
}
}
}
}
#endregion
private ArrayList _topLevelNodes = new ArrayList();
private int _nodeCount;
private const int maxNodeCount = 128;
}
} // namespace
| |
#region Apache Notice
/*****************************************************************************
* $Header: $
* $Revision: $
* $Date: $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2004 - Gilles Bayon
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
using System;
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Reflection;
using IBatisNet.Common.Exceptions;
namespace IBatisNet.Common.Utilities
{
/// <summary>
/// DBHelperParameterCache provides functions to leverage a
/// static cache of procedure parameters, and the
/// ability to discover parameters for stored procedures at run-time.
/// </summary>
public class DBHelperParameterCache
{
//Since this class provides only static methods, make the default constructor private to prevent
//instances from being created.
private DBHelperParameterCache() {}
#region Private fields
private static Hashtable _paramCache = Hashtable.Synchronized(new Hashtable());
#endregion
#region private methods
/// <summary>
/// Resolve at run time the appropriate set of Parameters for a stored procedure
/// </summary>
/// <param name="session">a valid session</param>
/// <param name="spName">the name of the stored procedure</param>
/// <param name="includeReturnValueParameter">whether or not to include their return value parameter</param>
/// <returns></returns>
private static IDataParameter[] DiscoverSpParameterSet(IDalSession session, string spName, bool includeReturnValueParameter)
{
using (IDbConnection connection = session.DataSource.Provider.GetConnection())
{
connection.ConnectionString = session.DataSource.ConnectionString;
connection.Open();
return InternalDiscoverSpParameterSet(session.DataSource.Provider, connection, spName, includeReturnValueParameter);
}
}
/// <summary>
/// resolve at run time the appropriate set of Parameters for a stored procedure
/// </summary>
/// <param name="provider"></param>
/// <param name="connection">a valid open IDbConnection</param>
/// <param name="spName">the name of the stored procedure</param>
/// <param name="includeReturnValueParameter">whether or not to include their return value parameter</param>
/// <returns></returns>
private static IDataParameter[] InternalDiscoverSpParameterSet(Provider provider,
IDbConnection connection, string spName, bool includeReturnValueParameter)
{
using (IDbCommand cmd = connection.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = spName;
DeriveParameters(provider, cmd);
if (cmd.Parameters.Count > 0) {
IDataParameter firstParameter = (IDataParameter)cmd.Parameters[0];
if (firstParameter.Direction == ParameterDirection.ReturnValue) {
if (!includeReturnValueParameter) {
cmd.Parameters.RemoveAt(0);
}
}
}
IDataParameter[] discoveredParameters = new IDataParameter[cmd.Parameters.Count];
cmd.Parameters.CopyTo(discoveredParameters, 0);
return discoveredParameters;
}
}
private static void DeriveParameters(Provider provider, IDbCommand command)
{
Type commandBuilderType;
// Find the CommandBuilder
if (provider == null)
throw new ArgumentNullException("provider");
if ((provider.CommandBuilderClass == null) || (provider.CommandBuilderClass.Length < 1))
throw new Exception(String.Format(
"CommandBuilderClass not defined for provider \"{0}\".",
provider.Name));
commandBuilderType = provider.GetCommandBuilderType();
// Invoke the static DeriveParameter method on the CommandBuilder class
// NOTE: OracleCommandBuilder has no DeriveParameter method
try
{
commandBuilderType.InvokeMember("DeriveParameters",
BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static, null, null,
new object[] {command});
}
catch(Exception ex)
{
throw new IBatisNetException("Could not retrieve parameters for the store procedure named "+command.CommandText, ex);
}
}
/// <summary>
/// Deep copy of cached IDataParameter array.
/// </summary>
/// <param name="originalParameters"></param>
/// <returns></returns>
private static IDataParameter[] CloneParameters(IDataParameter[] originalParameters)
{
IDataParameter[] clonedParameters = new IDataParameter[originalParameters.Length];
for (int i = 0, j = originalParameters.Length; i < j; i++)
{
clonedParameters[i] = (IDataParameter) ((ICloneable) originalParameters[i]).Clone();
}
return clonedParameters;
}
#endregion private methods, variables, and constructors
#region caching functions
/// <summary>
/// Add parameter array to the cache
/// </summary>
/// <param name="connectionString">a valid connection string for an IDbConnection</param>
/// <param name="commandText">the stored procedure name or SQL command</param>
/// <param name="commandParameters">an array of IDataParameters to be cached</param>
public static void CacheParameterSet(string connectionString, string commandText, params IDataParameter[] commandParameters)
{
string hashKey = connectionString + ":" + commandText;
_paramCache[hashKey] = commandParameters;
}
// FM Added
/// <summary>
/// Clear the parameter cache.
/// </summary>
public static void Clear()
{
_paramCache.Clear();
}
/// <summary>
/// retrieve a parameter array from the cache
/// </summary>
/// <param name="connectionString">a valid connection string for an IDbConnection</param>
/// <param name="commandText">the stored procedure name or SQL command</param>
/// <returns>an array of IDataParameters</returns>
public static IDataParameter[] GetCachedParameterSet(string connectionString, string commandText)
{
string hashKey = connectionString + ":" + commandText;
IDataParameter[] cachedParameters = (IDataParameter[]) _paramCache[hashKey];
if (cachedParameters == null)
{
return null;
}
else
{
return CloneParameters(cachedParameters);
}
}
#endregion caching functions
#region Parameter Discovery Functions
/// <summary>
/// Retrieves the set of IDataParameters appropriate for the stored procedure
/// </summary>
/// <remarks>
/// This method will query the database for this information, and then store it in a cache for future requests.
/// </remarks>
/// <param name="session">a valid session</param>
/// <param name="spName">the name of the stored procedure</param>
/// <returns>an array of IDataParameters</returns>
public static IDataParameter[] GetSpParameterSet(IDalSession session, string spName)
{
return GetSpParameterSet(session, spName, false);
}
/// <summary>
/// Retrieves the set of IDataParameters appropriate for the stored procedure
/// </summary>
/// <remarks>
/// This method will query the database for this information, and then store it in a cache for future requests.
/// </remarks>
/// <param name="session">a valid csession</param>
/// <param name="spName">the name of the stored procedure</param>
/// <param name="includeReturnValueParameter">a bool value indicating whether the return value parameter should be included in the results</param>
/// <returns>an array of IDataParameters</returns>
public static IDataParameter[] GetSpParameterSet(IDalSession session
, string spName, bool includeReturnValueParameter)
{
string hashKey = session.DataSource.ConnectionString + ":" + spName + (includeReturnValueParameter ? ":include ReturnValue Parameter":"");
IDataParameter[] cachedParameters;
cachedParameters = (IDataParameter[]) _paramCache[hashKey];
if (cachedParameters == null)
{
_paramCache[hashKey] = DiscoverSpParameterSet(session, spName, includeReturnValueParameter);
cachedParameters = (IDataParameter[]) _paramCache[hashKey];
}
return CloneParameters(cachedParameters);
}
#endregion Parameter Discovery Functions
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** File: AssemblyName
**
** <OWNER>[....]</OWNER>
** <OWNER>[....]</OWNER>
**
**
** Purpose: Used for binding and retrieving info about an assembly
**
**
===========================================================*/
namespace System.Reflection {
using System;
using System.IO;
using System.Configuration.Assemblies;
using System.Runtime.CompilerServices;
using CultureInfo = System.Globalization.CultureInfo;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_AssemblyName))]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyName : _AssemblyName, ICloneable, ISerializable, IDeserializationCallback
{
//
// READ ME
// If you modify any of these fields, you must also update the
// AssemblyBaseObject structure in object.h
//
private String _Name; // Name
private byte[] _PublicKey;
private byte[] _PublicKeyToken;
private CultureInfo _CultureInfo;
private String _CodeBase; // Potential location to get the file
private Version _Version;
private StrongNameKeyPair _StrongNameKeyPair;
#if FEATURE_SERIALIZATION
private SerializationInfo m_siInfo; //A temporary variable which we need during deserialization.
#endif
private byte[] _HashForControl;
private AssemblyHashAlgorithm _HashAlgorithm;
private AssemblyHashAlgorithm _HashAlgorithmForControl;
private AssemblyVersionCompatibility _VersionCompatibility;
private AssemblyNameFlags _Flags;
public AssemblyName()
{
_HashAlgorithm = AssemblyHashAlgorithm.None;
_VersionCompatibility = AssemblyVersionCompatibility.SameMachine;
_Flags = AssemblyNameFlags.None;
}
// Set and get the name of the assembly. If this is a weak Name
// then it optionally contains a site. For strong assembly names,
// the name partitions up the strong name's namespace
public String Name
{
get { return _Name; }
set { _Name = value; }
}
public Version Version
{
get {
return _Version;
}
set {
_Version = value;
}
}
// Locales, internally the LCID is used for the match.
public CultureInfo CultureInfo
{
get {
return _CultureInfo;
}
set {
_CultureInfo = value;
}
}
public String CultureName
{
get {
return (_CultureInfo == null) ? null : _CultureInfo.Name;
}
set {
_CultureInfo = (value == null) ? null : new CultureInfo(value);
}
}
public String CodeBase
{
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
[ResourceExposure(ResourceScope.Machine)]
get { return _CodeBase; }
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
[ResourceExposure(ResourceScope.Machine)]
set { _CodeBase = value; }
}
public String EscapedCodeBase
{
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
get
{
if (_CodeBase == null)
return null;
else
return EscapeCodeBase(_CodeBase);
}
}
public ProcessorArchitecture ProcessorArchitecture
{
get {
int x = (((int)_Flags) & 0x70) >> 4;
if(x > 5)
x = 0;
return (ProcessorArchitecture)x;
}
set {
int x = ((int)value) & 0x07;
if(x <= 5) {
_Flags = (AssemblyNameFlags)((int)_Flags & 0xFFFFFF0F);
_Flags |= (AssemblyNameFlags)(x << 4);
}
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public AssemblyContentType ContentType
{
get
{
int x = (((int)_Flags) & 0x00000E00) >> 9;
if (x > 1)
x = 0;
return (AssemblyContentType)x;
}
set
{
int x = ((int)value) & 0x07;
if (x <= 1)
{
_Flags = (AssemblyNameFlags)((int)_Flags & 0xFFFFF1FF);
_Flags |= (AssemblyNameFlags)(x << 9);
}
}
}
// Make a copy of this assembly name.
public Object Clone()
{
AssemblyName name = new AssemblyName();
name.Init(_Name,
_PublicKey,
_PublicKeyToken,
_Version,
_CultureInfo,
_HashAlgorithm,
_VersionCompatibility,
_CodeBase,
_Flags,
_StrongNameKeyPair);
name._HashForControl=_HashForControl;
name._HashAlgorithmForControl=_HashAlgorithmForControl;
return name;
}
/*
* Get the AssemblyName for a given file. This will only work
* if the file contains an assembly manifest. This method causes
* the file to be opened and closed.
*/
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
static public AssemblyName GetAssemblyName(String assemblyFile)
{
if(assemblyFile == null)
throw new ArgumentNullException("assemblyFile");
Contract.EndContractBlock();
// Assembly.GetNameInternal() will not demand path discovery
// permission, so do that first.
String fullPath = Path.GetFullPathInternal(assemblyFile);
new FileIOPermission( FileIOPermissionAccess.PathDiscovery, fullPath ).Demand();
return nGetFileInformation(fullPath);
}
internal void SetHashControl(byte[] hash, AssemblyHashAlgorithm hashAlgorithm)
{
_HashForControl=hash;
_HashAlgorithmForControl=hashAlgorithm;
}
// The public key that is used to verify an assemblies
// inclusion into the namespace. If the public key associated
// with the namespace cannot verify the assembly the assembly
// will fail to load.
public byte[] GetPublicKey()
{
#if FEATURE_LEGACYNETCF
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8 && _PublicKey == null)
return EmptyArray<Byte>.Value;
else
#endif
return _PublicKey;
}
public void SetPublicKey(byte[] publicKey)
{
_PublicKey = publicKey;
if (publicKey == null)
_Flags &= ~AssemblyNameFlags.PublicKey;
else
_Flags |= AssemblyNameFlags.PublicKey;
}
// The compressed version of the public key formed from a truncated hash.
// Will throw a SecurityException if _PublicKey is invalid
[System.Security.SecuritySafeCritical] // auto-generated
public byte[] GetPublicKeyToken()
{
if (_PublicKeyToken == null)
_PublicKeyToken = nGetPublicKeyToken();
return _PublicKeyToken;
}
public void SetPublicKeyToken(byte[] publicKeyToken)
{
_PublicKeyToken = publicKeyToken;
}
// Flags modifying the name. So far the only flag is PublicKey, which
// indicates that a full public key and not the compressed version is
// present.
// Processor Architecture flags are set only through ProcessorArchitecture
// property and can't be set or retrieved directly
// Content Type flags are set only through ContentType property and can't be
// set or retrieved directly
public AssemblyNameFlags Flags
{
get { return (AssemblyNameFlags)((uint)_Flags & 0xFFFFF10F); }
set {
_Flags &= unchecked((AssemblyNameFlags)0x00000EF0);
_Flags |= (value & unchecked((AssemblyNameFlags)0xFFFFF10F));
}
}
public AssemblyHashAlgorithm HashAlgorithm
{
get { return _HashAlgorithm; }
set { _HashAlgorithm = value; }
}
public AssemblyVersionCompatibility VersionCompatibility
{
get { return _VersionCompatibility; }
set { _VersionCompatibility = value; }
}
public StrongNameKeyPair KeyPair
{
get { return _StrongNameKeyPair; }
set { _StrongNameKeyPair = value; }
}
public String FullName
{
[System.Security.SecuritySafeCritical] // auto-generated
get {
String name = nToString();
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8 && string.IsNullOrEmpty(name))
return base.ToString();
return name;
}
}
// Returns the stringized version of the assembly name.
public override String ToString()
{
String s = FullName;
if(s == null)
return base.ToString();
else
return s;
}
#if FEATURE_SERIALIZATION
[System.Security.SecurityCritical] // auto-generated_required
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
//Allocate the serialization info and serialize our static data.
info.AddValue("_Name", _Name);
info.AddValue("_PublicKey", _PublicKey, typeof(byte[]));
info.AddValue("_PublicKeyToken", _PublicKeyToken, typeof(byte[]));
#if FEATURE_USE_LCID
info.AddValue("_CultureInfo", (_CultureInfo == null) ? -1 :_CultureInfo.LCID);
#endif
info.AddValue("_CodeBase", _CodeBase);
info.AddValue("_Version", _Version);
info.AddValue("_HashAlgorithm", _HashAlgorithm, typeof(AssemblyHashAlgorithm));
info.AddValue("_HashAlgorithmForControl", _HashAlgorithmForControl, typeof(AssemblyHashAlgorithm));
info.AddValue("_StrongNameKeyPair", _StrongNameKeyPair, typeof(StrongNameKeyPair));
info.AddValue("_VersionCompatibility", _VersionCompatibility, typeof(AssemblyVersionCompatibility));
info.AddValue("_Flags", _Flags, typeof(AssemblyNameFlags));
info.AddValue("_HashForControl",_HashForControl,typeof(byte[]));
}
public void OnDeserialization(Object sender)
{
// Deserialization has already been performed
if (m_siInfo == null)
return;
_Name = m_siInfo.GetString("_Name");
_PublicKey = (byte[]) m_siInfo.GetValue("_PublicKey", typeof(byte[]));
_PublicKeyToken = (byte[]) m_siInfo.GetValue("_PublicKeyToken", typeof(byte[]));
#if FEATURE_USE_LCID
int lcid = (int)m_siInfo.GetInt32("_CultureInfo");
if (lcid != -1)
_CultureInfo = new CultureInfo(lcid);
#endif
_CodeBase = m_siInfo.GetString("_CodeBase");
_Version = (Version) m_siInfo.GetValue("_Version", typeof(Version));
_HashAlgorithm = (AssemblyHashAlgorithm) m_siInfo.GetValue("_HashAlgorithm", typeof(AssemblyHashAlgorithm));
_StrongNameKeyPair = (StrongNameKeyPair) m_siInfo.GetValue("_StrongNameKeyPair", typeof(StrongNameKeyPair));
_VersionCompatibility = (AssemblyVersionCompatibility)m_siInfo.GetValue("_VersionCompatibility", typeof(AssemblyVersionCompatibility));
_Flags = (AssemblyNameFlags) m_siInfo.GetValue("_Flags", typeof(AssemblyNameFlags));
try {
_HashAlgorithmForControl = (AssemblyHashAlgorithm) m_siInfo.GetValue("_HashAlgorithmForControl", typeof(AssemblyHashAlgorithm));
_HashForControl = (byte[]) m_siInfo.GetValue("_HashForControl", typeof(byte[]));
}
catch (SerializationException) { // RTM did not have these defined
_HashAlgorithmForControl = AssemblyHashAlgorithm.None;
_HashForControl = null;
}
m_siInfo = null;
}
// Constructs a new AssemblyName during deserialization.
internal AssemblyName(SerializationInfo info, StreamingContext context)
{
//The graph is not valid until OnDeserialization() has been called.
m_siInfo = info;
}
#endif // FEATURE_SERIALIZATION
[System.Security.SecuritySafeCritical] // auto-generated
public AssemblyName(String assemblyName)
{
if (assemblyName == null)
throw new ArgumentNullException("assemblyName");
Contract.EndContractBlock();
if ((assemblyName.Length == 0) ||
(assemblyName[0] == '\0'))
throw new ArgumentException(Environment.GetResourceString("Format_StringZeroLength"));
_Name = assemblyName;
nInit();
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
static public bool ReferenceMatchesDefinition(AssemblyName reference,
AssemblyName definition)
{
// Optimization for common use case
if (Object.ReferenceEquals(reference, definition))
{
return true;
}
return ReferenceMatchesDefinitionInternal(reference, definition, true);
}
/// "parse" tells us to parse the simple name of the assembly as if it was the full name
/// almost never the right thing to do, but needed for compat
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern bool ReferenceMatchesDefinitionInternal(AssemblyName reference,
AssemblyName definition,
bool parse);
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void nInit(out RuntimeAssembly assembly, bool forIntrospection, bool raiseResolveEvent);
[System.Security.SecurityCritical] // auto-generated
internal void nInit()
{
RuntimeAssembly dummy = null;
nInit(out dummy, false, false);
}
internal void SetProcArchIndex(PortableExecutableKinds pek, ImageFileMachine ifm)
{
ProcessorArchitecture = CalculateProcArchIndex(pek, ifm, _Flags);
}
internal static ProcessorArchitecture CalculateProcArchIndex(PortableExecutableKinds pek, ImageFileMachine ifm, AssemblyNameFlags flags)
{
if (((uint)flags & 0xF0) == 0x70)
return ProcessorArchitecture.None;
if ((pek & System.Reflection.PortableExecutableKinds.PE32Plus) == System.Reflection.PortableExecutableKinds.PE32Plus)
{
switch (ifm)
{
case System.Reflection.ImageFileMachine.IA64:
return ProcessorArchitecture.IA64;
case System.Reflection.ImageFileMachine.AMD64:
return ProcessorArchitecture.Amd64;
case System.Reflection.ImageFileMachine.I386:
if ((pek & System.Reflection.PortableExecutableKinds.ILOnly) == System.Reflection.PortableExecutableKinds.ILOnly)
return ProcessorArchitecture.MSIL;
break;
}
}
else
{
if (ifm == System.Reflection.ImageFileMachine.I386)
{
if ((pek & System.Reflection.PortableExecutableKinds.Required32Bit) == System.Reflection.PortableExecutableKinds.Required32Bit)
return ProcessorArchitecture.X86;
if ((pek & System.Reflection.PortableExecutableKinds.ILOnly) == System.Reflection.PortableExecutableKinds.ILOnly)
return ProcessorArchitecture.MSIL;
return ProcessorArchitecture.X86;
}
if (ifm == System.Reflection.ImageFileMachine.ARM)
{
return ProcessorArchitecture.Arm;
}
}
return ProcessorArchitecture.None;
}
internal void Init(String name,
byte[] publicKey,
byte[] publicKeyToken,
Version version,
CultureInfo cultureInfo,
AssemblyHashAlgorithm hashAlgorithm,
AssemblyVersionCompatibility versionCompatibility,
String codeBase,
AssemblyNameFlags flags,
StrongNameKeyPair keyPair) // Null if ref, matching Assembly if def
{
_Name = name;
if (publicKey != null) {
_PublicKey = new byte[publicKey.Length];
Array.Copy(publicKey, _PublicKey, publicKey.Length);
}
if (publicKeyToken != null) {
_PublicKeyToken = new byte[publicKeyToken.Length];
Array.Copy(publicKeyToken, _PublicKeyToken, publicKeyToken.Length);
}
if (version != null)
_Version = (Version) version.Clone();
_CultureInfo = cultureInfo;
_HashAlgorithm = hashAlgorithm;
_VersionCompatibility = versionCompatibility;
_CodeBase = codeBase;
_Flags = flags;
_StrongNameKeyPair = keyPair;
}
#if !FEATURE_CORECLR
void _AssemblyName.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _AssemblyName.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _AssemblyName.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
void _AssemblyName.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
#if FEATURE_APTCA
internal string GetNameWithPublicKey()
{
byte[] key = GetPublicKey();
// The following string should not be localized because it is used in security decisions.
return Name + ", PublicKey=" + System.Security.Util.Hex.EncodeHexString(key);
}
#endif
// This call opens and closes the file, but does not add the
// assembly to the domain.
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern AssemblyName nGetFileInformation(String s);
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern String nToString();
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern byte[] nGetPublicKeyToken();
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern String EscapeCodeBase(String codeBase);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography.Apple;
using Internal.Cryptography;
namespace System.Security.Cryptography
{
#if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS
public partial class ECDsa : AsymmetricAlgorithm
{
/// <summary>
/// Creates an instance of the platform specific implementation of the cref="ECDsa" algorithm.
/// </summary>
public static new ECDsa Create()
{
return new ECDsaImplementation.ECDsaSecurityTransforms();
}
/// <summary>
/// Creates an instance of the platform specific implementation of the cref="ECDsa" algorithm.
/// </summary>
/// <param name="curve">
/// The <see cref="ECCurve"/> representing the elliptic curve.
/// </param>
public static ECDsa Create(ECCurve curve)
{
ECDsa ecdsa = Create();
ecdsa.GenerateKey(curve);
return ecdsa;
}
/// <summary>
/// Creates an instance of the platform specific implementation of the cref="ECDsa" algorithm.
/// </summary>
/// <param name="parameters">
/// The <see cref="ECParameters"/> representing the elliptic curve parameters.
/// </param>
public static ECDsa Create(ECParameters parameters)
{
ECDsa ecdsa = Create();
ecdsa.ImportParameters(parameters);
return ecdsa;
}
#endif
internal static partial class ECDsaImplementation
{
public sealed partial class ECDsaSecurityTransforms : ECDsa
{
private SecKeyPair _keys;
public ECDsaSecurityTransforms()
{
KeySize = 521;
}
internal ECDsaSecurityTransforms(SafeSecKeyRefHandle publicKey)
{
SetKey(SecKeyPair.PublicOnly(publicKey));
}
internal ECDsaSecurityTransforms(SafeSecKeyRefHandle publicKey, SafeSecKeyRefHandle privateKey)
{
SetKey(SecKeyPair.PublicPrivatePair(publicKey, privateKey));
}
public override KeySizes[] LegalKeySizes
{
get
{
// Return the three sizes that can be explicitly set (for backwards compatibility)
return new[] {
new KeySizes(minSize: 256, maxSize: 384, skipSize: 128),
new KeySizes(minSize: 521, maxSize: 521, skipSize: 0),
};
}
}
public override int KeySize
{
get
{
return base.KeySize;
}
set
{
if (KeySize == value)
return;
// Set the KeySize before freeing the key so that an invalid value doesn't throw away the key
base.KeySize = value;
if (_keys != null)
{
_keys.Dispose();
_keys = null;
}
}
}
public override byte[] SignHash(byte[] hash)
{
if (hash == null)
throw new ArgumentNullException(nameof(hash));
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
{
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
byte[] derFormatSignature = Interop.AppleCrypto.GenerateSignature(keys.PrivateKey, hash);
byte[] ieeeFormatSignature = AsymmetricAlgorithmHelpers.ConvertDerToIeee1363(
derFormatSignature,
0,
derFormatSignature.Length,
KeySize);
return ieeeFormatSignature;
}
public override bool VerifyHash(byte[] hash, byte[] signature)
{
if (hash == null)
throw new ArgumentNullException(nameof(hash));
if (signature == null)
throw new ArgumentNullException(nameof(signature));
byte[] derFormatSignature = AsymmetricAlgorithmHelpers.ConvertIeee1363ToDer(signature);
return Interop.AppleCrypto.VerifySignature(
GetKeys().PublicKey,
hash,
derFormatSignature);
}
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
return AsymmetricAlgorithmHelpers.HashData(data, offset, count, hashAlgorithm);
}
protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
{
return AsymmetricAlgorithmHelpers.HashData(data, hashAlgorithm);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_keys != null)
{
_keys.Dispose();
_keys = null;
}
}
base.Dispose(disposing);
}
public override ECParameters ExportExplicitParameters(bool includePrivateParameters)
{
throw new PlatformNotSupportedException(SR.Cryptography_ECC_NamedCurvesOnly);
}
public override ECParameters ExportParameters(bool includePrivateParameters)
{
SecKeyPair keys = GetKeys();
SafeSecKeyRefHandle keyHandle = includePrivateParameters ? keys.PrivateKey : keys.PublicKey;
if (keyHandle == null)
{
throw new CryptographicException(SR.Cryptography_OpenInvalidHandle);
}
DerSequenceReader keyReader = Interop.AppleCrypto.SecKeyExport(keyHandle, includePrivateParameters);
ECParameters parameters = new ECParameters();
if (includePrivateParameters)
{
keyReader.ReadPkcs8Blob(ref parameters);
}
else
{
keyReader.ReadSubjectPublicKeyInfo(ref parameters);
}
int size = AsymmetricAlgorithmHelpers.BitsToBytes(KeySize);
KeyBlobHelpers.PadOrTrim(ref parameters.Q.X, size);
KeyBlobHelpers.PadOrTrim(ref parameters.Q.Y, size);
if (includePrivateParameters)
{
KeyBlobHelpers.PadOrTrim(ref parameters.D, size);
}
return parameters;
}
public override void ImportParameters(ECParameters parameters)
{
parameters.Validate();
bool isPrivateKey = parameters.D != null;
if (isPrivateKey)
{
// Start with the private key, in case some of the private key fields don't
// match the public key fields and the system determines an integrity failure.
//
// Public import should go off without a hitch.
SafeSecKeyRefHandle privateKey = ImportKey(parameters);
ECParameters publicOnly = parameters;
publicOnly.D = null;
SafeSecKeyRefHandle publicKey;
try
{
publicKey = ImportKey(publicOnly);
}
catch
{
privateKey.Dispose();
throw;
}
SetKey(SecKeyPair.PublicPrivatePair(publicKey, privateKey));
}
else
{
SafeSecKeyRefHandle publicKey = ImportKey(parameters);
SetKey(SecKeyPair.PublicOnly(publicKey));
}
}
public override void GenerateKey(ECCurve curve)
{
curve.Validate();
if (!curve.IsNamed)
{
throw new PlatformNotSupportedException(SR.Cryptography_ECC_NamedCurvesOnly);
}
int keySize;
switch (curve.Oid.Value)
{
// secp256r1 / nistp256
case "1.2.840.10045.3.1.7":
keySize = 256;
break;
// secp384r1 / nistp384
case "1.3.132.0.34":
keySize = 384;
break;
// secp521r1 / nistp521
case "1.3.132.0.35":
keySize = 521;
break;
default:
throw new PlatformNotSupportedException(
SR.Format(SR.Cryptography_CurveNotSupported, curve.Oid.Value));
}
// Clear the current key, because GenerateKey on the same curve makes a new key,
// unlike setting the KeySize property to the current value.
SetKey(null);
KeySizeValue = keySize;
// Generate the keys immediately, because that's what the verb of this method is.
GetKeys();
}
private static SafeSecKeyRefHandle ImportKey(ECParameters parameters)
{
bool isPrivateKey = parameters.D != null;
byte[] blob = isPrivateKey ? parameters.ToPrivateKeyBlob() : parameters.ToSubjectPublicKeyInfo();
return Interop.AppleCrypto.ImportEphemeralKey(blob, isPrivateKey);
}
private void SetKey(SecKeyPair newKeyPair)
{
SecKeyPair current = _keys;
_keys = newKeyPair;
current?.Dispose();
if (newKeyPair != null)
{
long size = Interop.AppleCrypto.EccGetKeySizeInBits(newKeyPair.PublicKey);
Debug.Assert(size == 256 || size == 384 || size == 521, $"Unknown keysize ({size})");
KeySizeValue = (int)size;
}
}
internal SecKeyPair GetKeys()
{
SecKeyPair current = _keys;
if (current != null)
{
return current;
}
SafeSecKeyRefHandle publicKey;
SafeSecKeyRefHandle privateKey;
Interop.AppleCrypto.EccGenerateKey(KeySizeValue, out publicKey, out privateKey);
current = SecKeyPair.PublicPrivatePair(publicKey, privateKey);
_keys = current;
return current;
}
}
}
#if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS
}
#endif
internal static class EcKeyBlobHelpers
{
private static readonly byte[] s_version1 = { 1 };
private static readonly byte[][] s_encodedVersion1 = DerEncoder.SegmentedEncodeUnsignedInteger(s_version1);
private static readonly Oid s_idEcPublicKey = new Oid("1.2.840.10045.2.1", null);
private static readonly byte[][] s_encodedIdEcPublicKey = DerEncoder.SegmentedEncodeOid(s_idEcPublicKey);
internal static void ReadPkcs8Blob(this DerSequenceReader reader, ref ECParameters parameters)
{
// OneAsymmetricKey ::= SEQUENCE {
// version Version,
// privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
// privateKey PrivateKey,
// attributes [0] Attributes OPTIONAL,
// ...,
// [[2: publicKey [1] PublicKey OPTIONAL ]],
// ...
// }
//
// PrivateKeyInfo ::= OneAsymmetricKey
//
// PrivateKey ::= OCTET STRING
int version = reader.ReadInteger();
// We understand both version 0 and 1 formats,
// which are now known as v1 and v2, respectively.
if (version > 1)
{
throw new CryptographicException();
}
{
// Ensure we're reading EC Public Key (well, Private, but the OID says Public)
DerSequenceReader algorithm = reader.ReadSequence();
string algorithmOid = algorithm.ReadOidAsString();
if (algorithmOid != s_idEcPublicKey.Value)
{
throw new CryptographicException();
}
}
byte[] privateKeyBlob = reader.ReadOctetString();
// ECPrivateKey{CURVES:IOSet} ::= SEQUENCE {
// version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
// privateKey OCTET STRING,
// parameters [0] Parameters{{IOSet}} OPTIONAL,
// publicKey [1] BIT STRING OPTIONAL
// }
DerSequenceReader keyReader = new DerSequenceReader(privateKeyBlob);
version = keyReader.ReadInteger();
// We understand the version 1 format
if (version > 1)
{
throw new CryptographicException();
}
parameters.D = keyReader.ReadOctetString();
// Check for context specific 0
const byte ConstructedContextSpecific =
DerSequenceReader.ContextSpecificTagFlag | DerSequenceReader.ConstructedFlag;
const byte ConstructedContextSpecific0 = (ConstructedContextSpecific | 0);
const byte ConstructedContextSpecific1 = (ConstructedContextSpecific | 1);
if (keyReader.PeekTag() != ConstructedContextSpecific0)
{
throw new CryptographicException();
}
// Parameters ::= CHOICE {
// ecParameters ECParameters,
// namedCurve CURVES.&id({ CurveNames}),
// implicitlyCA NULL
// }
DerSequenceReader parametersReader = keyReader.ReadSequence();
if (parametersReader.PeekTag() != (int)DerSequenceReader.DerTag.ObjectIdentifier)
{
throw new PlatformNotSupportedException(SR.Cryptography_ECC_NamedCurvesOnly);
}
parameters.Curve = ECCurve.CreateFromValue(parametersReader.ReadOidAsString());
// Check for context specific 1
if (keyReader.PeekTag() != ConstructedContextSpecific1)
{
throw new CryptographicException();
}
keyReader = keyReader.ReadSequence();
byte[] encodedPoint = keyReader.ReadBitString();
ReadEncodedPoint(encodedPoint, ref parameters);
// We don't care about the rest of the blob here, but it's expected to not exist.
}
internal static void ReadSubjectPublicKeyInfo(this DerSequenceReader keyInfo, ref ECParameters parameters)
{
// SubjectPublicKeyInfo::= SEQUENCE {
// algorithm AlgorithmIdentifier,
// subjectPublicKey BIT STRING }
DerSequenceReader algorithm = keyInfo.ReadSequence();
string algorithmOid = algorithm.ReadOidAsString();
// EC Public Key
if (algorithmOid != s_idEcPublicKey.Value)
{
throw new CryptographicException();
}
if (algorithm.PeekTag() != (int)DerSequenceReader.DerTag.ObjectIdentifier)
{
throw new PlatformNotSupportedException(SR.Cryptography_ECC_NamedCurvesOnly);
}
parameters.Curve = ECCurve.CreateFromValue(algorithm.ReadOidAsString());
byte[] encodedPoint = keyInfo.ReadBitString();
ReadEncodedPoint(encodedPoint, ref parameters);
// We don't care about the rest of the blob here, but it's expected to not exist.
}
internal static byte[] ToSubjectPublicKeyInfo(this ECParameters parameters)
{
parameters.Validate();
if (!parameters.Curve.IsNamed)
{
throw new PlatformNotSupportedException(SR.Cryptography_ECC_NamedCurvesOnly);
}
byte[] pointBlob = GetPointBlob(ref parameters);
return DerEncoder.ConstructSequence(
DerEncoder.ConstructSegmentedSequence(
s_encodedIdEcPublicKey,
DerEncoder.SegmentedEncodeOid(parameters.Curve.Oid)),
DerEncoder.SegmentedEncodeBitString(pointBlob));
}
private static byte[] GetPointBlob(ref ECParameters parameters)
{
byte[] pointBlob = new byte[parameters.Q.X.Length + parameters.Q.Y.Length + 1];
// Uncompressed point
pointBlob[0] = 0x04;
Buffer.BlockCopy(parameters.Q.X, 0, pointBlob, 1, parameters.Q.X.Length);
Buffer.BlockCopy(parameters.Q.Y, 0, pointBlob, 1 + parameters.Q.X.Length, parameters.Q.Y.Length);
return pointBlob;
}
internal static byte[] ToPrivateKeyBlob(this ECParameters parameters)
{
parameters.Validate();
if (!parameters.Curve.IsNamed)
{
throw new PlatformNotSupportedException(SR.Cryptography_ECC_NamedCurvesOnly);
}
byte[] pointBlob = GetPointBlob(ref parameters);
// ECPrivateKey{CURVES:IOSet} ::= SEQUENCE {
// version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
// privateKey OCTET STRING,
// parameters [0] Parameters{{IOSet}} OPTIONAL,
// publicKey [1] BIT STRING OPTIONAL
// }
return DerEncoder.ConstructSequence(
s_encodedVersion1,
DerEncoder.SegmentedEncodeOctetString(parameters.D),
DerEncoder.ConstructSegmentedContextSpecificValue(
0,
DerEncoder.SegmentedEncodeOid(parameters.Curve.Oid)),
DerEncoder.ConstructSegmentedContextSpecificValue(
1,
DerEncoder.SegmentedEncodeBitString(pointBlob)));
}
private static void ReadEncodedPoint(byte[] encodedPoint, ref ECParameters parameters)
{
if (encodedPoint == null || encodedPoint.Length < 1)
{
throw new CryptographicException();
}
byte encoding = encodedPoint[0];
switch (encoding)
{
// Uncompressed encoding (04 xbytes ybytes)
case 0x04:
// Hybrid encoding, ~yp == 0 (06 xbytes ybytes)
case 0x06:
// Hybrid encoding, ~yp == 1 (07 xbytes ybytes)
case 0x07:
break;
default:
Debug.Fail($"Don't know how to read point encoding {encoding}");
throw new CryptographicException();
}
// For formats 04, 06, and 07 the X and Y points are equal length, and they should
// already be left-padded with zeros in cases where they're short.
int pointEncodingSize = (encodedPoint.Length - 1) / 2;
byte[] encodedX = new byte[pointEncodingSize];
byte[] encodedY = new byte[pointEncodingSize];
Buffer.BlockCopy(encodedPoint, 1, encodedX, 0, pointEncodingSize);
Buffer.BlockCopy(encodedPoint, 1 + pointEncodingSize, encodedY, 0, pointEncodingSize);
parameters.Q.X = encodedX;
parameters.Q.Y = encodedY;
}
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2009, 2010 Oracle and/or its affiliates. All rights reserved.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using BerkeleyDB;
using NUnit.Framework;
namespace CsharpAPITest
{
[TestFixture]
public class DatabaseEnvironmentConfigTest
{
private string testFixtureHome;
private string testFixtureName;
private string testName;
private string testHome;
[TestFixtureSetUp]
public void RunBeforeTests()
{
testFixtureName = "DatabaseEnvironmentConfigTest";
testFixtureHome = "./TestOut/" + testFixtureName;
Configuration.ClearDir(testFixtureHome);
}
[Test]
public void TestConfig()
{
testName = "TestConfig";
XmlElement xmlElem = Configuration.TestSetUp(
testFixtureName, testName);
DatabaseEnvironmentConfig envConfig =
new DatabaseEnvironmentConfig();
Config(xmlElem, ref envConfig, true);
Confirm(xmlElem, envConfig, true);
}
public static void Confirm(XmlElement xmlElement,
DatabaseEnvironmentConfig envConfig, bool compulsory)
{
Configuration.ConfirmBool(xmlElement, "AutoCommit",
envConfig.AutoCommit, compulsory);
Configuration.ConfirmBool(xmlElement, "CDB_ALLDB",
envConfig.CDB_ALLDB, compulsory);
Configuration.ConfirmBool(xmlElement, "Create",
envConfig.Create, compulsory);
Configuration.ConfirmStringList(xmlElement, "DataDirs",
envConfig.DataDirs, compulsory);
Configuration.ConfirmString(xmlElement, "ErrorPrefix",
envConfig.ErrorPrefix, compulsory);
Configuration.ConfirmBool(xmlElement, "ForceFlush",
envConfig.ForceFlush, compulsory);
Configuration.ConfirmBool(xmlElement, "FreeThreaded",
envConfig.FreeThreaded, compulsory);
Configuration.ConfirmBool(xmlElement, "InitRegions",
envConfig.InitRegions, compulsory);
Configuration.ConfirmString(xmlElement,
"IntermediateDirMode",
envConfig.IntermediateDirMode, compulsory);
Configuration.ConfirmBool(xmlElement, "Lockdown",
envConfig.Lockdown, compulsory);
Configuration.ConfirmUint(xmlElement, "LockTimeout",
envConfig.LockTimeout, compulsory);
Configuration.ConfirmUint(xmlElement, "MaxTransactions",
envConfig.MaxTransactions, compulsory);
Configuration.ConfirmBool(xmlElement, "NoBuffer",
envConfig.NoBuffer, compulsory);
Configuration.ConfirmBool(xmlElement, "NoLocking",
envConfig.NoLocking, compulsory);
Configuration.ConfirmBool(xmlElement, "NoMMap",
envConfig.NoMMap, compulsory);
Configuration.ConfirmBool(xmlElement, "NoLocking",
envConfig.NoLocking, compulsory);
Configuration.ConfirmBool(xmlElement, "NoPanic",
envConfig.NoPanic, compulsory);
Configuration.ConfirmBool(xmlElement, "Overwrite",
envConfig.Overwrite, compulsory);
Configuration.ConfirmBool(xmlElement, "Private",
envConfig.Private, compulsory);
Configuration.ConfirmBool(xmlElement, "Register",
envConfig.Register, compulsory);
Configuration.ConfirmBool(xmlElement, "RunFatalRecovery",
envConfig.RunFatalRecovery, compulsory);
Configuration.ConfirmBool(xmlElement, "RunRecovery",
envConfig.RunRecovery, compulsory);
Configuration.ConfirmBool(xmlElement, "SystemMemory",
envConfig.SystemMemory, compulsory);
Configuration.ConfirmString(xmlElement, "TempDir",
envConfig.TempDir, compulsory);
Configuration.ConfirmBool(xmlElement, "TimeNotGranted",
envConfig.TimeNotGranted, compulsory);
Configuration.ConfirmBool(xmlElement, "TxnNoSync",
envConfig.TxnNoSync, compulsory);
Configuration.ConfirmBool(xmlElement, "TxnNoWait",
envConfig.TxnNoWait, compulsory);
Configuration.ConfirmBool(xmlElement, "TxnSnapshot",
envConfig.TxnSnapshot, compulsory);
Configuration.ConfirmDateTime(xmlElement,"TxnTimestamp",
envConfig.TxnTimestamp, compulsory);
Configuration.ConfirmBool(xmlElement, "TxnWriteNoSync",
envConfig.TxnWriteNoSync, compulsory);
Configuration.ConfirmBool(xmlElement, "UseCDB",
envConfig.UseCDB, compulsory);
Configuration.ConfirmBool(xmlElement, "UseLocking",
envConfig.UseLocking, compulsory);
Configuration.ConfirmBool(xmlElement, "UseLogging",
envConfig.UseLogging, compulsory);
Configuration.ConfirmBool(xmlElement, "UseMPool",
envConfig.UseMPool, compulsory);
Configuration.ConfirmBool(xmlElement, "UseMVCC",
envConfig.UseMVCC, compulsory);
Configuration.ConfirmBool(xmlElement, "UseReplication",
envConfig.UseReplication, compulsory);
Configuration.ConfirmBool(xmlElement, "UseTxns",
envConfig.UseTxns, compulsory);
envConfig.Verbosity = new VerboseMessages();
Configuration.ConfirmVerboseMessages(xmlElement,
"Verbosity", envConfig.Verbosity, compulsory);
Configuration.ConfirmBool(xmlElement, "YieldCPU",
envConfig.YieldCPU, compulsory);
}
public static void Config(XmlElement xmlElement,
ref DatabaseEnvironmentConfig envConfig, bool compulsory)
{
uint value = new uint();
DateTime time = new DateTime();
Configuration.ConfigBool(xmlElement, "AutoCommit",
ref envConfig.AutoCommit, compulsory);
Configuration.ConfigBool(xmlElement, "CDB_ALLDB",
ref envConfig.CDB_ALLDB, compulsory);
Configuration.ConfigBool(xmlElement, "Create",
ref envConfig.Create, compulsory);
Configuration.ConfigString(xmlElement, "CreationDir",
ref envConfig.CreationDir, compulsory);
Configuration.ConfigStringList(xmlElement, "DataDirs",
ref envConfig.DataDirs, compulsory);
Configuration.ConfigString(xmlElement, "ErrorPrefix",
ref envConfig.ErrorPrefix, compulsory);
Configuration.ConfigBool(xmlElement, "ForceFlush",
ref envConfig.ForceFlush, compulsory);
Configuration.ConfigBool(xmlElement, "FreeThreaded",
ref envConfig.FreeThreaded, compulsory);
Configuration.ConfigBool(xmlElement, "InitRegions",
ref envConfig.InitRegions, compulsory);
Configuration.ConfigString(xmlElement, "IntermediateDirMode",
ref envConfig.IntermediateDirMode, compulsory);
Configuration.ConfigBool(xmlElement, "Lockdown",
ref envConfig.Lockdown, compulsory);
if (Configuration.ConfigUint(xmlElement, "LockTimeout",
ref value, compulsory))
envConfig.LockTimeout = value;
if (Configuration.ConfigUint(xmlElement, "MaxTransactions",
ref value, compulsory))
envConfig.MaxTransactions = value;
Configuration.ConfigBool(xmlElement, "NoBuffer",
ref envConfig.NoBuffer, compulsory);
Configuration.ConfigBool(xmlElement, "NoLocking",
ref envConfig.NoLocking, compulsory);
Configuration.ConfigBool(xmlElement, "NoMMap",
ref envConfig.NoMMap, compulsory);
Configuration.ConfigBool(xmlElement, "NoLocking",
ref envConfig.NoLocking, compulsory);
Configuration.ConfigBool(xmlElement, "NoPanic",
ref envConfig.NoPanic, compulsory);
Configuration.ConfigBool(xmlElement, "Overwrite",
ref envConfig.Overwrite, compulsory);
Configuration.ConfigBool(xmlElement, "Private",
ref envConfig.Private, compulsory);
Configuration.ConfigBool(xmlElement, "Register",
ref envConfig.Register, compulsory);
Configuration.ConfigBool(xmlElement, "RunFatalRecovery",
ref envConfig.RunFatalRecovery, compulsory);
Configuration.ConfigBool(xmlElement, "RunRecovery",
ref envConfig.RunRecovery, compulsory);
Configuration.ConfigBool(xmlElement, "SystemMemory",
ref envConfig.SystemMemory, compulsory);
Configuration.ConfigString(xmlElement, "TempDir",
ref envConfig.TempDir, compulsory);
Configuration.ConfigBool(xmlElement, "TimeNotGranted",
ref envConfig.TimeNotGranted, compulsory);
Configuration.ConfigBool(xmlElement, "TxnNoSync",
ref envConfig.TxnNoSync, compulsory);
Configuration.ConfigBool(xmlElement, "TxnNoWait",
ref envConfig.TxnNoWait, compulsory);
Configuration.ConfigBool(xmlElement, "TxnSnapshot",
ref envConfig.TxnSnapshot, compulsory);
if (Configuration.ConfigDateTime(xmlElement, "TxnTimestamp",
ref time, compulsory))
envConfig.TxnTimestamp = time;
Configuration.ConfigBool(xmlElement, "TxnWriteNoSync",
ref envConfig.TxnWriteNoSync, compulsory);
Configuration.ConfigBool(xmlElement, "UseLocking",
ref envConfig.UseLocking, compulsory);
Configuration.ConfigBool(xmlElement, "UseLogging",
ref envConfig.UseLogging, compulsory);
Configuration.ConfigBool(xmlElement, "UseMPool",
ref envConfig.UseMPool, compulsory);
Configuration.ConfigBool(xmlElement, "UseMVCC",
ref envConfig.UseMVCC, compulsory);
Configuration.ConfigBool(xmlElement, "UseReplication",
ref envConfig.UseReplication, compulsory);
Configuration.ConfigBool(xmlElement, "UseTxns",
ref envConfig.UseTxns, compulsory);
envConfig.Verbosity = new VerboseMessages();
Configuration.ConfigVerboseMessages(xmlElement,
"Verbosity", ref envConfig.Verbosity, compulsory);
Configuration.ConfigBool(xmlElement, "YieldCPU",
ref envConfig.YieldCPU, compulsory);
}
[Test]
public void TestConfigLock()
{
testName = "TestConfigLock";
XmlElement xmlElem = Configuration.TestSetUp(
testFixtureName, testName);
DatabaseEnvironmentConfig cfg =
new DatabaseEnvironmentConfig();
cfg.LockSystemCfg = new LockingConfig();
LockingConfigTest.Config(xmlElem,
ref cfg.LockSystemCfg, true);
LockingConfigTest.Confirm(xmlElem,
cfg.LockSystemCfg, true);
}
[Test]
public void TestConfigLog()
{
testName = "TestConfigLog";
XmlElement xmlElem = Configuration.TestSetUp(
testFixtureName, testName);
DatabaseEnvironmentConfig cfg =
new DatabaseEnvironmentConfig();
cfg.LogSystemCfg = new LogConfig();
LogConfigTest.Config(xmlElem, ref cfg.LogSystemCfg, true);
LogConfigTest.Confirm(xmlElem, cfg.LogSystemCfg, true);
}
[Test]
public void TestConfigMutex()
{
testName = "TestConfigMutex";
XmlElement xmlElem = Configuration.TestSetUp(
testFixtureName, testName);
DatabaseEnvironmentConfig cfg =
new DatabaseEnvironmentConfig();
cfg.MutexSystemCfg = new MutexConfig();
MutexConfigTest.Config(xmlElem, ref cfg.MutexSystemCfg, true);
MutexConfigTest.Confirm(xmlElem, cfg.MutexSystemCfg, true);
}
[Test]
public void TestConfigReplication()
{
testName = "TestConfigReplication";
XmlElement xmlElem = Configuration.TestSetUp(
testFixtureName, testName);
DatabaseEnvironmentConfig cfg =
new DatabaseEnvironmentConfig();
cfg.RepSystemCfg = new ReplicationConfig();
ReplicationConfigTest.Config(xmlElem,
ref cfg.RepSystemCfg, true);
ReplicationConfigTest.Confirm(xmlElem,
cfg.RepSystemCfg, true);
}
[Test]
public void TestSetEncryption()
{
testName = "TestSetEncryption";
testHome = testFixtureHome + "/" + testName;
Configuration.ClearDir(testHome);
DatabaseEnvironmentConfig envConfig =
new DatabaseEnvironmentConfig();
envConfig.Create = true;
envConfig.SetEncryption("key", EncryptionAlgorithm.AES);
Assert.AreEqual("key", envConfig.EncryptionPassword);
Assert.AreEqual(EncryptionAlgorithm.AES, envConfig.EncryptAlgorithm);
DatabaseEnvironment env = DatabaseEnvironment.Open(
testHome, envConfig);
Assert.AreEqual(EncryptionAlgorithm.AES, env.EncryptAlgorithm);
env.Close();
}
}
}
| |
using System;
/// <summary>
/// UIntPtr.ToUInt32()
/// Converts the value of this instance to a 32-bit unsigned integer.
/// This method is not CLS-compliant.
/// </summary>
public class UIntPtrToUInt32
{
public static int Main()
{
UIntPtrToUInt32 testObj = new UIntPtrToUInt32();
TestLibrary.TestFramework.BeginTestCase("for method: UIntPtr.ToPointer()");
if (testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_ID = "P001";
const string c_TEST_DESC = "PosTest1: UIntPtr.Zero";
string errorDesc;
UInt32 actualUI, expectedUI;
UIntPtr uiPtr;
bool actualResult;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
expectedUI = 0;
uiPtr = UIntPtr.Zero;
actualUI = uiPtr.ToUInt32();
actualResult = actualUI == expectedUI;
if (!actualResult)
{
errorDesc = "Actual UInt32 from UIntPtr is not " + expectedUI + " as expected: Actual(" + actualUI + ")";
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_ID = "P002";
const string c_TEST_DESC = "PosTest2: UIntPtr with a random Int32 value ";
string errorDesc;
UInt32 actualUI, expectedUI;
UIntPtr uiPtr;
bool actualResult;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
expectedUI = (UInt32)TestLibrary.Generator.GetInt32(-55);
uiPtr = new UIntPtr(expectedUI);
actualUI = uiPtr.ToUInt32();
actualResult = actualUI == expectedUI;
if (!actualResult)
{
errorDesc = "Actual UInt32 from UIntPtr is not " + expectedUI + " as expected: Actual(" + actualUI + ")";
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_ID = "P003";
const string c_TEST_DESC = "PosTest3: UIntPtr with a value greater than Int32.MaxValue";
string errorDesc;
UInt32 actualUI, expectedUI;
UIntPtr uiPtr;
bool actualResult;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
expectedUI = (UInt32)Int32.MaxValue + (UInt32)TestLibrary.Generator.GetInt32(-55);
uiPtr = new UIntPtr(expectedUI);
actualUI = uiPtr.ToUInt32();
actualResult = actualUI == expectedUI;
if (!actualResult)
{
errorDesc = "Actual hash code is not " + expectedUI + " as expected: Actual(" + actualUI + ")";
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_ID = "P004";
const string c_TEST_DESC = "PosTest4: UIntPtr with a value UInt32.MaxValue";
string errorDesc;
UInt32 actualUI, expectedUI;
UIntPtr uiPtr;
bool actualResult;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
expectedUI = UInt32.MaxValue;
uiPtr = new UIntPtr(expectedUI);
actualUI = uiPtr.ToUInt32();
actualResult = actualUI == expectedUI;
if (!actualResult)
{
errorDesc = "Actual hash code is not " + expectedUI + " as expected: Actual(" + actualUI + ")";
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
#region Negative tests
//OverflowException
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_ID = "N001";
const string c_TEST_DESC = "NegTest1: On a 32-bit platform, the value of this instance is too large to represent as a 32-bit unsigned integer.";
string errorDesc;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
if (UIntPtr.Size != 8) // platform is 64-bit
{
UInt64 ui = UInt32.MaxValue + this.GetUInt64() % (UInt64.MaxValue - UInt32.MaxValue) + 1;
UIntPtr actualUIntPtr = new UIntPtr(ui);
errorDesc = "OverflowException is not thrown as expected";
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
else
{
retVal = true;
}
}
catch (OverflowException)
{
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("08" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
#region helper method for tests
private UInt64 GetUInt64()
{
byte[] buffer = new byte[8];
UInt64 uiVal;
TestLibrary.Generator.GetBytes(-55, buffer);
// convert to UInt64
uiVal = 0;
for (int i = 0; i < buffer.Length; i++)
{
uiVal |= ((UInt64)buffer[i] << (i * 8));
}
TestLibrary.TestFramework.LogInformation("Random UInt64 produced: " + uiVal.ToString());
return uiVal;
}
#endregion
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Asn1
{
public class DerObjectIdentifier
: Asn1Object
{
private readonly string identifier;
private byte[] body = null;
/**
* return an Oid from the passed in object
*
* @exception ArgumentException if the object cannot be converted.
*/
public static DerObjectIdentifier GetInstance(object obj)
{
if (obj == null || obj is DerObjectIdentifier)
return (DerObjectIdentifier) obj;
if (obj is byte[])
return FromOctetString((byte[])obj);
throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name, "obj");
}
/**
* return an object Identifier from a tagged object.
*
* @param obj the tagged object holding the object we want
* @param explicitly true if the object is meant to be explicitly
* tagged false otherwise.
* @exception ArgumentException if the tagged object cannot
* be converted.
*/
public static DerObjectIdentifier GetInstance(
Asn1TaggedObject obj,
bool explicitly)
{
return GetInstance(obj.GetObject());
}
public DerObjectIdentifier(
string identifier)
{
if (identifier == null)
throw new ArgumentNullException("identifier");
if (!IsValidIdentifier(identifier))
throw new FormatException("string " + identifier + " not an OID");
this.identifier = identifier;
}
internal DerObjectIdentifier(DerObjectIdentifier oid, string branchID)
{
if (!IsValidBranchID(branchID, 0))
throw new ArgumentException("string " + branchID + " not a valid OID branch", "branchID");
this.identifier = oid.Id + "." + branchID;
}
// TODO Change to ID?
public string Id
{
get { return identifier; }
}
public virtual DerObjectIdentifier Branch(string branchID)
{
return new DerObjectIdentifier(this, branchID);
}
/**
* Return true if this oid is an extension of the passed in branch, stem.
* @param stem the arc or branch that is a possible parent.
* @return true if the branch is on the passed in stem, false otherwise.
*/
public virtual bool On(DerObjectIdentifier stem)
{
string id = Id, stemId = stem.Id;
return id.Length > stemId.Length && id[stemId.Length] == '.' && id.StartsWith(stemId);
}
internal DerObjectIdentifier(byte[] bytes)
{
this.identifier = MakeOidStringFromBytes(bytes);
this.body = Arrays.Clone(bytes);
}
private void WriteField(
Stream outputStream,
long fieldValue)
{
byte[] result = new byte[9];
int pos = 8;
result[pos] = (byte)(fieldValue & 0x7f);
while (fieldValue >= (1L << 7))
{
fieldValue >>= 7;
result[--pos] = (byte)((fieldValue & 0x7f) | 0x80);
}
outputStream.Write(result, pos, 9 - pos);
}
private void WriteField(
Stream outputStream,
BigInteger fieldValue)
{
int byteCount = (fieldValue.BitLength + 6) / 7;
if (byteCount == 0)
{
outputStream.WriteByte(0);
}
else
{
BigInteger tmpValue = fieldValue;
byte[] tmp = new byte[byteCount];
for (int i = byteCount-1; i >= 0; i--)
{
tmp[i] = (byte) ((tmpValue.IntValue & 0x7f) | 0x80);
tmpValue = tmpValue.ShiftRight(7);
}
tmp[byteCount-1] &= 0x7f;
outputStream.Write(tmp, 0, tmp.Length);
}
}
private void DoOutput(MemoryStream bOut)
{
OidTokenizer tok = new OidTokenizer(identifier);
string token = tok.NextToken();
int first = int.Parse(token) * 40;
token = tok.NextToken();
if (token.Length <= 18)
{
WriteField(bOut, first + Int64.Parse(token));
}
else
{
WriteField(bOut, new BigInteger(token).Add(BigInteger.ValueOf(first)));
}
while (tok.HasMoreTokens)
{
token = tok.NextToken();
if (token.Length <= 18)
{
WriteField(bOut, Int64.Parse(token));
}
else
{
WriteField(bOut, new BigInteger(token));
}
}
}
internal byte[] GetBody()
{
lock (this)
{
if (body == null)
{
MemoryStream bOut = new MemoryStream();
DoOutput(bOut);
body = bOut.ToArray();
}
}
return body;
}
internal override void Encode(
DerOutputStream derOut)
{
derOut.WriteEncoded(Asn1Tags.ObjectIdentifier, GetBody());
}
protected override int Asn1GetHashCode()
{
return identifier.GetHashCode();
}
protected override bool Asn1Equals(
Asn1Object asn1Object)
{
DerObjectIdentifier other = asn1Object as DerObjectIdentifier;
if (other == null)
return false;
return this.identifier.Equals(other.identifier);
}
public override string ToString()
{
return identifier;
}
private static bool IsValidBranchID(
String branchID, int start)
{
bool periodAllowed = false;
int pos = branchID.Length;
while (--pos >= start)
{
char ch = branchID[pos];
// TODO Leading zeroes?
if ('0' <= ch && ch <= '9')
{
periodAllowed = true;
continue;
}
if (ch == '.')
{
if (!periodAllowed)
return false;
periodAllowed = false;
continue;
}
return false;
}
return periodAllowed;
}
private static bool IsValidIdentifier(string identifier)
{
if (identifier.Length < 3 || identifier[1] != '.')
return false;
char first = identifier[0];
if (first < '0' || first > '2')
return false;
return IsValidBranchID(identifier, 2);
}
private const long LONG_LIMIT = (long.MaxValue >> 7) - 0x7f;
private static string MakeOidStringFromBytes(
byte[] bytes)
{
StringBuilder objId = new StringBuilder();
long value = 0;
BigInteger bigValue = null;
bool first = true;
for (int i = 0; i != bytes.Length; i++)
{
int b = bytes[i];
if (value <= LONG_LIMIT)
{
value += (b & 0x7f);
if ((b & 0x80) == 0) // end of number reached
{
if (first)
{
if (value < 40)
{
objId.Append('0');
}
else if (value < 80)
{
objId.Append('1');
value -= 40;
}
else
{
objId.Append('2');
value -= 80;
}
first = false;
}
objId.Append('.');
objId.Append(value);
value = 0;
}
else
{
value <<= 7;
}
}
else
{
if (bigValue == null)
{
bigValue = BigInteger.ValueOf(value);
}
bigValue = bigValue.Or(BigInteger.ValueOf(b & 0x7f));
if ((b & 0x80) == 0)
{
if (first)
{
objId.Append('2');
bigValue = bigValue.Subtract(BigInteger.ValueOf(80));
first = false;
}
objId.Append('.');
objId.Append(bigValue);
bigValue = null;
value = 0;
}
else
{
bigValue = bigValue.ShiftLeft(7);
}
}
}
return objId.ToString();
}
private static readonly DerObjectIdentifier[] cache = new DerObjectIdentifier[1024];
internal static DerObjectIdentifier FromOctetString(byte[] enc)
{
int hashCode = Arrays.GetHashCode(enc);
int first = hashCode & 1023;
lock (cache)
{
DerObjectIdentifier entry = cache[first];
if (entry != null && Arrays.AreEqual(enc, entry.GetBody()))
{
return entry;
}
return cache[first] = new DerObjectIdentifier(enc);
}
}
}
}
#endif
| |
// 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!
namespace Google.Cloud.Trace.V1.Snippets
{
using Google.Api.Gax;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedTraceServiceClientSnippets
{
/// <summary>Snippet for ListTraces</summary>
public void ListTracesRequestObject()
{
// Snippet: ListTraces(ListTracesRequest, CallSettings)
// Create client
TraceServiceClient traceServiceClient = TraceServiceClient.Create();
// Initialize request argument(s)
ListTracesRequest request = new ListTracesRequest
{
ProjectId = "",
View = ListTracesRequest.Types.ViewType.Unspecified,
StartTime = new Timestamp(),
EndTime = new Timestamp(),
Filter = "",
OrderBy = "",
};
// Make the request
PagedEnumerable<ListTracesResponse, Trace> response = traceServiceClient.ListTraces(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Trace item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTracesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Trace item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Trace> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Trace item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTracesAsync</summary>
public async Task ListTracesRequestObjectAsync()
{
// Snippet: ListTracesAsync(ListTracesRequest, CallSettings)
// Create client
TraceServiceClient traceServiceClient = await TraceServiceClient.CreateAsync();
// Initialize request argument(s)
ListTracesRequest request = new ListTracesRequest
{
ProjectId = "",
View = ListTracesRequest.Types.ViewType.Unspecified,
StartTime = new Timestamp(),
EndTime = new Timestamp(),
Filter = "",
OrderBy = "",
};
// Make the request
PagedAsyncEnumerable<ListTracesResponse, Trace> response = traceServiceClient.ListTracesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Trace item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTracesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Trace item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Trace> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Trace item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTraces</summary>
public void ListTraces()
{
// Snippet: ListTraces(string, string, int?, CallSettings)
// Create client
TraceServiceClient traceServiceClient = TraceServiceClient.Create();
// Initialize request argument(s)
string projectId = "";
// Make the request
PagedEnumerable<ListTracesResponse, Trace> response = traceServiceClient.ListTraces(projectId);
// Iterate over all response items, lazily performing RPCs as required
foreach (Trace item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTracesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Trace item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Trace> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Trace item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTracesAsync</summary>
public async Task ListTracesAsync()
{
// Snippet: ListTracesAsync(string, string, int?, CallSettings)
// Create client
TraceServiceClient traceServiceClient = await TraceServiceClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
// Make the request
PagedAsyncEnumerable<ListTracesResponse, Trace> response = traceServiceClient.ListTracesAsync(projectId);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Trace item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTracesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Trace item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Trace> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Trace item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetTrace</summary>
public void GetTraceRequestObject()
{
// Snippet: GetTrace(GetTraceRequest, CallSettings)
// Create client
TraceServiceClient traceServiceClient = TraceServiceClient.Create();
// Initialize request argument(s)
GetTraceRequest request = new GetTraceRequest
{
ProjectId = "",
TraceId = "",
};
// Make the request
Trace response = traceServiceClient.GetTrace(request);
// End snippet
}
/// <summary>Snippet for GetTraceAsync</summary>
public async Task GetTraceRequestObjectAsync()
{
// Snippet: GetTraceAsync(GetTraceRequest, CallSettings)
// Additional: GetTraceAsync(GetTraceRequest, CancellationToken)
// Create client
TraceServiceClient traceServiceClient = await TraceServiceClient.CreateAsync();
// Initialize request argument(s)
GetTraceRequest request = new GetTraceRequest
{
ProjectId = "",
TraceId = "",
};
// Make the request
Trace response = await traceServiceClient.GetTraceAsync(request);
// End snippet
}
/// <summary>Snippet for GetTrace</summary>
public void GetTrace()
{
// Snippet: GetTrace(string, string, CallSettings)
// Create client
TraceServiceClient traceServiceClient = TraceServiceClient.Create();
// Initialize request argument(s)
string projectId = "";
string traceId = "";
// Make the request
Trace response = traceServiceClient.GetTrace(projectId, traceId);
// End snippet
}
/// <summary>Snippet for GetTraceAsync</summary>
public async Task GetTraceAsync()
{
// Snippet: GetTraceAsync(string, string, CallSettings)
// Additional: GetTraceAsync(string, string, CancellationToken)
// Create client
TraceServiceClient traceServiceClient = await TraceServiceClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
string traceId = "";
// Make the request
Trace response = await traceServiceClient.GetTraceAsync(projectId, traceId);
// End snippet
}
/// <summary>Snippet for PatchTraces</summary>
public void PatchTracesRequestObject()
{
// Snippet: PatchTraces(PatchTracesRequest, CallSettings)
// Create client
TraceServiceClient traceServiceClient = TraceServiceClient.Create();
// Initialize request argument(s)
PatchTracesRequest request = new PatchTracesRequest
{
ProjectId = "",
Traces = new Traces(),
};
// Make the request
traceServiceClient.PatchTraces(request);
// End snippet
}
/// <summary>Snippet for PatchTracesAsync</summary>
public async Task PatchTracesRequestObjectAsync()
{
// Snippet: PatchTracesAsync(PatchTracesRequest, CallSettings)
// Additional: PatchTracesAsync(PatchTracesRequest, CancellationToken)
// Create client
TraceServiceClient traceServiceClient = await TraceServiceClient.CreateAsync();
// Initialize request argument(s)
PatchTracesRequest request = new PatchTracesRequest
{
ProjectId = "",
Traces = new Traces(),
};
// Make the request
await traceServiceClient.PatchTracesAsync(request);
// End snippet
}
/// <summary>Snippet for PatchTraces</summary>
public void PatchTraces()
{
// Snippet: PatchTraces(string, Traces, CallSettings)
// Create client
TraceServiceClient traceServiceClient = TraceServiceClient.Create();
// Initialize request argument(s)
string projectId = "";
Traces traces = new Traces();
// Make the request
traceServiceClient.PatchTraces(projectId, traces);
// End snippet
}
/// <summary>Snippet for PatchTracesAsync</summary>
public async Task PatchTracesAsync()
{
// Snippet: PatchTracesAsync(string, Traces, CallSettings)
// Additional: PatchTracesAsync(string, Traces, CancellationToken)
// Create client
TraceServiceClient traceServiceClient = await TraceServiceClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
Traces traces = new Traces();
// Make the request
await traceServiceClient.PatchTracesAsync(projectId, traces);
// End snippet
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Rynchodon.AntennaRelay;
using Rynchodon.Attached;
using Rynchodon.Autopilot.Data;
using Sandbox.ModAPI;
using VRageMath;
namespace Rynchodon.Autopilot
{
/// <summary>
/// Finds a friendly grid and possibly a block, given a ship controller block.
/// </summary>
public class GridFinder
{
public enum ReasonCannotTarget : byte { None, Too_Far, Grid_Condition, Too_Fast }
private const ulong SearchInterval_Grid = 100ul, SearchInterval_Block = 1000ul;
public readonly string m_targetGridName, m_targetBlockName;
public readonly ShipController m_controller;
public readonly ShipControllerBlock m_controlBlock;
public readonly AttachedGrid.AttachmentKind m_allowedAttachment;
public readonly Vector3 m_startPosition;
private readonly Logger m_logger;
private readonly AllNavigationSettings m_navSet;
private readonly bool m_mustBeRecent;
private ulong NextSearch_Grid, NextSearch_Block;
private List<LastSeen> m_enemies;
public virtual LastSeen Grid { get; protected set; }
public IMyCubeBlock Block { get; private set; }
public Func<IMyCubeGrid, bool> GridCondition { get; set; }
/// <summary>Block requirements, other than can control.</summary>
public Func<IMyCubeBlock, bool> BlockCondition { get; set; }
public ReasonCannotTarget m_reason;
public long m_reasonGrid;
protected float MaximumRange { get; set; }
/// <summary>
/// Creates a GridFinder to find a friendly grid based on its name.
/// </summary>
public GridFinder(AllNavigationSettings navSet, ShipControllerBlock controller, string targetGrid, string targetBlock = null,
AttachedGrid.AttachmentKind allowedAttachment = AttachedGrid.AttachmentKind.Permanent)
{
this.m_logger = new Logger(GetType().Name + " friendly", controller.CubeBlock);
m_logger.debugLog(navSet == null, "navSet == null", "GridFinder()", Logger.severity.FATAL);
m_logger.debugLog(controller == null, "controller == null", "GridFinder()", Logger.severity.FATAL);
m_logger.debugLog(controller.CubeBlock == null, "controller.CubeBlock == null", "GridFinder()", Logger.severity.FATAL);
m_logger.debugLog(targetGrid == null, "targetGrid == null", "GridFinder()", Logger.severity.FATAL);
if (!Registrar.TryGetValue(controller.CubeBlock.EntityId, out this.m_controller))
throw new NullReferenceException("ShipControllerBlock is not a ShipController");
this.m_targetGridName = targetGrid.LowerRemoveWhitespace();
if (targetBlock != null)
this.m_targetBlockName = targetBlock.LowerRemoveWhitespace();
this.m_controlBlock = controller;
this.m_allowedAttachment = allowedAttachment;
this.m_startPosition = m_controlBlock.CubeBlock.GetPosition();
this.MaximumRange = float.MaxValue;
this.m_navSet = navSet;
}
/// <summary>
/// Creates a GridFinder to find an enemy grid based on distance.
/// </summary>
public GridFinder(AllNavigationSettings navSet, ShipControllerBlock controller, float maxRange = 0f)
{
this.m_logger = new Logger(GetType().Name + " enemy", controller.CubeBlock);
m_logger.debugLog(navSet == null, "navSet == null", "GridFinder()", Logger.severity.FATAL);
m_logger.debugLog(controller == null, "controller == null", "GridFinder()", Logger.severity.FATAL);
m_logger.debugLog(controller.CubeBlock == null, "controller.CubeBlock == null", "GridFinder()", Logger.severity.FATAL);
this.m_controlBlock = controller;
this.m_enemies = new List<LastSeen>();
if (!Registrar.TryGetValue(controller.CubeBlock.EntityId, out this.m_controller))
throw new NullReferenceException("ShipControllerBlock is not a ShipController");
this.m_startPosition = m_controlBlock.CubeBlock.GetPosition();
this.MaximumRange = maxRange;
this.m_navSet = navSet;
this.m_mustBeRecent = true;
}
public void Update()
{
m_logger.debugLog("entered Update()", "Update()");
if (Grid == null)
{
if (Globals.UpdateCount >= NextSearch_Grid)
GridSearch();
}
else
GridUpdate();
if (Grid != null && m_targetBlockName != null)
{
if (Block == null)
{
if (Globals.UpdateCount >= NextSearch_Block)
BlockSearch();
}
else
BlockCheck();
}
}
public Vector3D GetPosition(Vector3D NavPos, Vector3D blockOffset)
{
return !Grid.isRecent() ? Grid.predictPosition()
: Block != null ? GetBlockPosition(blockOffset)
: GridCellCache.GetCellCache(Grid.Entity as IMyCubeGrid).GetClosestOccupiedCellPosition(NavPos);
}
private Vector3D GetBlockPosition(Vector3D blockOffset)
{
MatrixD WorldMatrix = Block.WorldMatrix;
return Block.GetPosition() + WorldMatrix.Right * blockOffset.X + WorldMatrix.Up * blockOffset.Y + WorldMatrix.Backward * blockOffset.Z;
}
/// <summary>
/// Find a seen grid that matches m_targetGridName
/// </summary>
private void GridSearch()
{
NextSearch_Grid = Globals.UpdateCount + SearchInterval_Grid;
if (m_targetGridName != null)
GridSearch_Friend();
else
GridSearch_Enemy();
}
private void GridSearch_Friend()
{
int bestNameLength = int.MaxValue;
m_controller.ForEachLastSeen(seen => {
IMyCubeGrid grid = seen.Entity as IMyCubeGrid;
if (grid != null && grid.DisplayName.Length < bestNameLength && grid.DisplayName.LowerRemoveWhitespace().Contains(m_targetGridName) && CanTarget(seen))
{
Grid = seen;
bestNameLength = grid.DisplayName.Length;
if (bestNameLength == m_targetGridName.Length)
{
m_logger.debugLog("perfect match LastSeen: " + seen.Entity.getBestName(), "GridSearch()");
return true;
}
}
return false;
});
if (Grid != null)
m_logger.debugLog("Best match LastSeen: " + Grid.Entity.getBestName(), "GridSearch()");
}
protected void GridSearch_Enemy()
{
Vector3D position = m_controlBlock.CubeBlock.GetPosition();
m_enemies.Clear();
m_controller.ForEachLastSeen(seen => {
if (!seen.IsValid || !seen.isRecent())
return false;
IMyCubeGrid asGrid = seen.Entity as IMyCubeGrid;
if (asGrid == null || !m_controlBlock.CubeBlock.canConsiderHostile(asGrid))
return false;
m_enemies.Add(seen);
m_logger.debugLog("enemy: " + seen.Entity.getBestName(), "Search()");
return false;
});
m_logger.debugLog("number of enemies: " + m_enemies.Count, "Search()");
IOrderedEnumerable<LastSeen> enemiesByDistance = m_enemies.OrderBy(seen => Vector3D.DistanceSquared(position, seen.GetPosition()));
m_reason = ReasonCannotTarget.None;
foreach (LastSeen enemy in enemiesByDistance)
{
if (CanTarget(enemy))
{
Grid = enemy;
m_logger.debugLog("found target: " + enemy.Entity.getBestName(), "Search()");
return;
}
}
Grid = null;
m_logger.debugLog("nothing found", "Search()");
}
private void GridUpdate()
{
m_logger.debugLog(Grid == null, "Grid == null", "GridUpdate()", Logger.severity.FATAL);
if (!Grid.IsValid)
{
m_logger.debugLog("no longer valid: " + Grid.Entity.getBestName(), "GridUpdate()", Logger.severity.DEBUG);
Grid = null;
return;
}
if (m_mustBeRecent && !Grid.isRecent())
{
m_logger.debugLog("no longer recent: " + Grid.Entity.getBestName() + ", age: " + (DateTime.UtcNow - Grid.LastSeenAt), "CanTarget()");
Grid = null;
return;
}
if (!CanTarget(Grid))
{
m_logger.debugLog("can no longer target: " + Grid.Entity.getBestName(), "GridUpdate()", Logger.severity.DEBUG);
Grid = null;
return;
}
LastSeen updated;
if (!m_controller.tryGetLastSeen(Grid.Entity.EntityId, out updated))
{
m_logger.alwaysLog("Where does the good go?", "GridUpdate()", Logger.severity.WARNING);
Grid = null;
return;
}
m_logger.debugLog("updating grid last seen " + Grid.LastSeenAt + " => " + updated.LastSeenAt, "GridUpdate()");
Grid = updated;
}
/// <summary>
/// Find a block that matches m_targetBlockName.
/// </summary>
private void BlockSearch()
{
m_logger.debugLog(Grid == null, "Grid == null", "BlockSearch()", Logger.severity.FATAL);
m_logger.debugLog(m_targetBlockName == null, "m_targetBlockName == null", "BlockSearch()", Logger.severity.FATAL);
NextSearch_Block = Globals.UpdateCount + SearchInterval_Block;
Block = null;
int bestNameLength = int.MaxValue;
IMyCubeGrid asGrid = Grid.Entity as IMyCubeGrid;
m_logger.debugLog(asGrid == null, "asGrid == null", "BlockSearch()", Logger.severity.FATAL);
AttachedGrid.RunOnAttachedBlock(asGrid, m_allowedAttachment, slim => {
IMyCubeBlock Fatblock = slim.FatBlock;
if (Fatblock == null || !m_controller.CubeBlock.canControlBlock(Fatblock))
return false;
string blockName;
try
{
blockName = ShipController_Autopilot.IsAutopilotBlock(Fatblock)
? Fatblock.getNameOnly().LowerRemoveWhitespace()
: Fatblock.DisplayNameText.LowerRemoveWhitespace();
}
catch (NullReferenceException nre)
{
m_logger.alwaysLog("Exception: " + nre, "BlockSearch()", Logger.severity.ERROR);
m_logger.alwaysLog("Fatblock: " + Fatblock + ", DefinitionDisplayNameText: " + Fatblock.DefinitionDisplayNameText + ", DisplayNameText: " + Fatblock.DisplayNameText + ", Name only: " + Fatblock.getNameOnly(), "BlockSearch()", Logger.severity.ERROR);
throw nre;
}
if (BlockCondition != null && !BlockCondition(Fatblock))
return false;
m_logger.debugLog("checking block name: \"" + blockName + "\" contains \"" + m_targetBlockName + "\"", "BlockSearch()");
if (blockName.Length < bestNameLength && blockName.Contains(m_targetBlockName))
{
m_logger.debugLog("block name matches: " + Fatblock.DisplayNameText, "BlockSearch()");
Block = Fatblock;
bestNameLength = blockName.Length;
if (m_targetBlockName.Length == bestNameLength)
return true;
}
return false;
}, true);
}
private void BlockCheck()
{
m_logger.debugLog(Grid == null, "Grid == null", "BlockCheck()", Logger.severity.FATAL);
m_logger.debugLog(m_targetBlockName == null, "m_targetBlockName == null", "BlockCheck()", Logger.severity.FATAL);
m_logger.debugLog(Block == null, "Block == null", "BlockCheck()", Logger.severity.FATAL);
if (!m_controller.CubeBlock.canControlBlock(Block))
{
m_logger.debugLog("lost control of block: " + Block.DisplayNameText, "BlockCheck()", Logger.severity.DEBUG);
Block = null;
return;
}
if (BlockCondition != null && !BlockCondition(Block))
{
m_logger.debugLog("Block does not statisfy condition: " + Block.DisplayNameText, "BlockCheck()", Logger.severity.DEBUG);
Block = null;
return;
}
}
private bool CanTarget(LastSeen seen)
{
try
{
// if it is too far from start, cannot target
if (MaximumRange > 1f && Vector3.DistanceSquared(m_startPosition, seen.GetPosition()) > MaximumRange * MaximumRange)
{
m_logger.debugLog("out of range of start position: " + seen.Entity.getBestName(), "CanTarget()");
if (m_reason < ReasonCannotTarget.Too_Far)
{
m_reason = ReasonCannotTarget.Too_Far;
m_reasonGrid = seen.Entity.EntityId;
}
return false;
}
// if it is too fast, cannot target
float speedTarget = m_navSet.Settings_Current.SpeedTarget - 1f;
if (seen.GetLinearVelocity().LengthSquared() >= speedTarget * speedTarget)
{
m_logger.debugLog("too fast to target: " + seen.Entity.getBestName(), "CanTarget()");
if (m_reason < ReasonCannotTarget.Too_Fast)
{
m_reason = ReasonCannotTarget.Too_Fast;
m_reasonGrid = seen.Entity.EntityId;
}
return false;
}
if (GridCondition != null && !GridCondition(seen.Entity as IMyCubeGrid))
{
m_logger.debugLog("Failed grid condition: " + seen.Entity.getBestName(), "CanTarget()");
if (m_reason < ReasonCannotTarget.Grid_Condition)
{
m_reason = ReasonCannotTarget.Grid_Condition;
m_reasonGrid = seen.Entity.EntityId;
}
return false;
}
return true;
}
catch (NullReferenceException nre)
{
m_logger.alwaysLog("Exception: " + nre, "CanTarget()", Logger.severity.ERROR);
if (!seen.Entity.Closed)
throw nre;
m_logger.debugLog("Caught exception caused by grid closing, ignoring.", "CanTarget()");
return false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IdentityModel;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.ServiceModel.Security.Tokens;
using Microsoft.Xml;
namespace System.ServiceModel.Security
{
internal class WSKeyInfoSerializer : KeyInfoSerializer
{
private static Func<KeyInfoSerializer, IEnumerable<SecurityTokenSerializer.SerializerEntries>> CreateAdditionalEntries(SecurityVersion securityVersion, SecureConversationVersion secureConversationVersion)
{
return (KeyInfoSerializer keyInfoSerializer) =>
{
List<SecurityTokenSerializer.SerializerEntries> serializerEntries = new List<SecurityTokenSerializer.SerializerEntries>();
if (securityVersion == SecurityVersion.WSSecurity10)
{
serializerEntries.Add(new System.IdentityModel.Tokens.WSSecurityJan2004(keyInfoSerializer));
}
else if (securityVersion == SecurityVersion.WSSecurity11)
{
serializerEntries.Add(new System.IdentityModel.Tokens.WSSecurityXXX2005(keyInfoSerializer));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("securityVersion", SRServiceModel.MessageSecurityVersionOutOfRange));
}
if (secureConversationVersion == SecureConversationVersion.WSSecureConversationFeb2005)
{
serializerEntries.Add(new WSSecureConversationFeb2005(keyInfoSerializer));
}
else if (secureConversationVersion == SecureConversationVersion.WSSecureConversation13)
{
serializerEntries.Add(new WSSecureConversationDec2005(keyInfoSerializer));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
return serializerEntries;
};
}
public WSKeyInfoSerializer(bool emitBspRequiredAttributes, DictionaryManager dictionaryManager, System.IdentityModel.TrustDictionary trustDictionary, SecurityTokenSerializer innerSecurityTokenSerializer, SecurityVersion securityVersion, SecureConversationVersion secureConversationVersion)
: base(emitBspRequiredAttributes, dictionaryManager, trustDictionary, innerSecurityTokenSerializer, CreateAdditionalEntries(securityVersion, secureConversationVersion))
{
}
#region WSSecureConversation classes
internal abstract class WSSecureConversation : SecurityTokenSerializer.SerializerEntries
{
private KeyInfoSerializer _securityTokenSerializer;
protected WSSecureConversation(KeyInfoSerializer securityTokenSerializer)
{
_securityTokenSerializer = securityTokenSerializer;
}
public KeyInfoSerializer SecurityTokenSerializer
{
get { return _securityTokenSerializer; }
}
public abstract System.IdentityModel.SecureConversationDictionary SerializerDictionary
{
get;
}
public virtual string DerivationAlgorithm
{
get { return SecurityAlgorithms.Psha1KeyDerivation; }
}
public override void PopulateTokenEntries(IList<TokenEntry> tokenEntryList)
{
if (tokenEntryList == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenEntryList");
}
tokenEntryList.Add(new DerivedKeyTokenEntry(this));
tokenEntryList.Add(new SecurityContextTokenEntry(this));
}
internal protected abstract class SctStrEntry : StrEntry
{
private WSSecureConversation _parent;
public SctStrEntry(WSSecureConversation parent)
{
_parent = parent;
}
protected WSSecureConversation Parent
{
get { return _parent; }
}
public override Type GetTokenType(SecurityKeyIdentifierClause clause)
{
return null;
}
public override string GetTokenTypeUri()
{
return null;
}
public override bool CanReadClause(XmlDictionaryReader reader, string tokenType)
{
if (tokenType != null && tokenType != _parent.SerializerDictionary.SecurityContextTokenType.Value)
{
return false;
}
if (reader.IsStartElement(
_parent.SecurityTokenSerializer.DictionaryManager.SecurityJan2004Dictionary.Reference,
_parent.SecurityTokenSerializer.DictionaryManager.SecurityJan2004Dictionary.Namespace))
{
string valueType = reader.GetAttribute(_parent.SecurityTokenSerializer.DictionaryManager.SecurityJan2004Dictionary.ValueType, null);
if (valueType != null && valueType != _parent.SerializerDictionary.SecurityContextTokenReferenceValueType.Value)
{
return false;
}
string uri = reader.GetAttribute(_parent.SecurityTokenSerializer.DictionaryManager.SecurityJan2004Dictionary.URI, null);
if (uri != null)
{
if (uri.Length > 0 && uri[0] != '#')
{
return true;
}
}
}
return false;
}
public override SecurityKeyIdentifierClause ReadClause(XmlDictionaryReader reader, byte[] derivationNonce, int derivationLength, string tokenType)
{
Microsoft.Xml.UniqueId uri = XmlHelper.GetAttributeAsUniqueId(reader, XD.SecurityJan2004Dictionary.URI, null);
Microsoft.Xml.UniqueId generation = ReadGeneration(reader);
if (reader.IsEmptyElement)
{
reader.Read();
}
else
{
reader.ReadStartElement();
while (reader.IsStartElement())
{
reader.Skip();
}
reader.ReadEndElement();
}
return new SecurityContextKeyIdentifierClause(uri, generation, derivationNonce, derivationLength);
}
protected abstract Microsoft.Xml.UniqueId ReadGeneration(XmlDictionaryReader reader);
public override bool SupportsCore(SecurityKeyIdentifierClause clause)
{
return clause is SecurityContextKeyIdentifierClause;
}
public override void WriteContent(XmlDictionaryWriter writer, SecurityKeyIdentifierClause clause)
{
SecurityContextKeyIdentifierClause sctClause = clause as SecurityContextKeyIdentifierClause;
writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.Reference, XD.SecurityJan2004Dictionary.Namespace);
XmlHelper.WriteAttributeStringAsUniqueId(writer, null, XD.SecurityJan2004Dictionary.URI, null, sctClause.ContextId);
WriteGeneration(writer, sctClause);
writer.WriteAttributeString(XD.SecurityJan2004Dictionary.ValueType, null, _parent.SerializerDictionary.SecurityContextTokenReferenceValueType.Value);
writer.WriteEndElement();
}
protected abstract void WriteGeneration(XmlDictionaryWriter writer, SecurityContextKeyIdentifierClause clause);
}
internal protected class SecurityContextTokenEntry : SecurityTokenSerializer.TokenEntry
{
private WSSecureConversation _parent;
private Type[] _tokenTypes;
public SecurityContextTokenEntry(WSSecureConversation parent)
{
_parent = parent;
}
protected WSSecureConversation Parent
{
get { return _parent; }
}
protected override XmlDictionaryString LocalName { get { return _parent.SerializerDictionary.SecurityContextToken; } }
protected override XmlDictionaryString NamespaceUri { get { return _parent.SerializerDictionary.Namespace; } }
protected override Type[] GetTokenTypesCore()
{
if (_tokenTypes == null)
_tokenTypes = new Type[] { typeof(SecurityContextSecurityToken) };
return _tokenTypes;
}
public override string TokenTypeUri { get { return _parent.SerializerDictionary.SecurityContextTokenType.Value; } }
protected override string ValueTypeUri { get { return null; } }
}
internal protected class DerivedKeyTokenEntry : SecurityTokenSerializer.TokenEntry
{
public const string DefaultLabel = "WS-SecureConversation";
private WSSecureConversation _parent;
private Type[] _tokenTypes;
public DerivedKeyTokenEntry(WSSecureConversation parent)
{
if (parent == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parent");
}
_parent = parent;
}
protected override XmlDictionaryString LocalName { get { return _parent.SerializerDictionary.DerivedKeyToken; } }
protected override XmlDictionaryString NamespaceUri { get { return _parent.SerializerDictionary.Namespace; } }
protected override Type[] GetTokenTypesCore()
{
if (_tokenTypes == null)
_tokenTypes = new Type[] { typeof(DerivedKeySecurityToken) };
return _tokenTypes;
}
public override string TokenTypeUri { get { return _parent.SerializerDictionary.DerivedKeyTokenType.Value; } }
protected override string ValueTypeUri { get { return null; } }
}
}
internal class WSSecureConversationFeb2005 : WSSecureConversation
{
public WSSecureConversationFeb2005(KeyInfoSerializer securityTokenSerializer)
: base(securityTokenSerializer)
{
}
public override System.IdentityModel.SecureConversationDictionary SerializerDictionary
{
get { return this.SecurityTokenSerializer.DictionaryManager.SecureConversationFeb2005Dictionary; }
}
public override void PopulateStrEntries(IList<StrEntry> strEntries)
{
strEntries.Add(new SctStrEntryFeb2005(this));
}
internal class SctStrEntryFeb2005 : SctStrEntry
{
public SctStrEntryFeb2005(WSSecureConversationFeb2005 parent)
: base(parent)
{
}
protected override Microsoft.Xml.UniqueId ReadGeneration(XmlDictionaryReader reader)
{
return XmlHelper.GetAttributeAsUniqueId(
reader,
this.Parent.SecurityTokenSerializer.DictionaryManager.SecureConversationDec2005Dictionary.Instance,
this.Parent.SecurityTokenSerializer.DictionaryManager.SecureConversationFeb2005Dictionary.Namespace);
}
protected override void WriteGeneration(XmlDictionaryWriter writer, SecurityContextKeyIdentifierClause clause)
{
// serialize the generation
if (clause.Generation != null)
{
XmlHelper.WriteAttributeStringAsUniqueId(
writer,
this.Parent.SecurityTokenSerializer.DictionaryManager.SecureConversationFeb2005Dictionary.Prefix.Value,
this.Parent.SecurityTokenSerializer.DictionaryManager.SecureConversationDec2005Dictionary.Instance,
this.Parent.SecurityTokenSerializer.DictionaryManager.SecureConversationFeb2005Dictionary.Namespace,
clause.Generation);
}
}
}
}
internal class WSSecureConversationDec2005 : WSSecureConversation
{
public WSSecureConversationDec2005(KeyInfoSerializer securityTokenSerializer)
: base(securityTokenSerializer)
{
}
public override System.IdentityModel.SecureConversationDictionary SerializerDictionary
{
get { return this.SecurityTokenSerializer.DictionaryManager.SecureConversationDec2005Dictionary; }
}
public override void PopulateStrEntries(IList<StrEntry> strEntries)
{
strEntries.Add(new SctStrEntryDec2005(this));
}
public override string DerivationAlgorithm
{
get
{
return SecurityAlgorithms.Psha1KeyDerivationDec2005;
}
}
internal class SctStrEntryDec2005 : SctStrEntry
{
public SctStrEntryDec2005(WSSecureConversationDec2005 parent)
: base(parent)
{
}
protected override Microsoft.Xml.UniqueId ReadGeneration(XmlDictionaryReader reader)
{
return XmlHelper.GetAttributeAsUniqueId(reader, this.Parent.SecurityTokenSerializer.DictionaryManager.SecureConversationDec2005Dictionary.Instance,
this.Parent.SecurityTokenSerializer.DictionaryManager.SecureConversationDec2005Dictionary.Namespace);
}
protected override void WriteGeneration(XmlDictionaryWriter writer, SecurityContextKeyIdentifierClause clause)
{
// serialize the generation
if (clause.Generation != null)
{
XmlHelper.WriteAttributeStringAsUniqueId(
writer,
this.Parent.SecurityTokenSerializer.DictionaryManager.SecureConversationDec2005Dictionary.Prefix.Value,
this.Parent.SecurityTokenSerializer.DictionaryManager.SecureConversationDec2005Dictionary.Instance,
this.Parent.SecurityTokenSerializer.DictionaryManager.SecureConversationDec2005Dictionary.Namespace,
clause.Generation);
}
}
}
}
#endregion
}
}
| |
//
// EventServer.cs
//
// Author:
// Scott Thomas <lunchtimemama@gmail.com>
//
// Copyright (C) 2008 S&S Black Ltd.
//
// 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.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Xml;
using Mono.Upnp.Control;
namespace Mono.Upnp.Internal
{
sealed class EventServer : UpnpServer
{
class Subscription
{
public readonly Uri Callback;
public readonly string Sid;
public volatile uint Seq;
public volatile int ConnectFailures;
public uint TimeoutId;
public Subscription (Uri callback, string sid)
{
this.Callback = callback;
this.Sid = sid;
}
}
readonly IEnumerable<StateVariable> state_variables;
volatile bool started;
readonly Dictionary<string, Subscription> subscribers = new Dictionary<string, Subscription> ();
readonly TimeoutDispatcher dispatcher = new TimeoutDispatcher ();
readonly List<StateVariable> updated_state_variables = new List<StateVariable> ();
Thread publish_thread;
public EventServer (IEnumerable<StateVariable> stateVariables, Uri url)
: base (url)
{
this.state_variables = GetEventedStateVariables (stateVariables);
}
public void QueueUpdate (StateVariable stateVariable)
{
lock (this) {
if (!updated_state_variables.Contains (stateVariable)) {
updated_state_variables.Add (stateVariable);
Monitor.Pulse (this);
}
}
}
public override void Start ()
{
started = true;
publish_thread = new Thread (new ThreadStart (Publish));
publish_thread.Start ();
base.Start ();
}
public override void Stop ()
{
started = false;
lock (this) {
Monitor.Pulse (this);
}
base.Stop ();
}
void Publish ()
{
lock (this) {
Monitor.Wait (this);
while (started) {
Monitor.Exit (this);
Thread.Sleep (TimeSpan.FromSeconds (1));
Monitor.Enter (this);
PublishUpdates (updated_state_variables);
updated_state_variables.Clear ();
Monitor.Wait (this);
}
}
}
void PublishUpdates (IEnumerable<StateVariable> stateVariables)
{
lock (subscribers) {
foreach (var subscriber in subscribers.Values) {
PublishUpdates (subscriber, stateVariables);
}
}
}
void PublishUpdates (Subscription subscriber, IEnumerable<StateVariable> stateVariables)
{
var request = (HttpWebRequest)WebRequest.Create (subscriber.Callback);
var seq = subscriber.Seq;
request.Method = "NOTIFY";
request.ContentType = "text/xml";
request.Headers.Add ("NT", "upnp:event");
request.Headers.Add ("NTS", "upnp:propchange");
request.Headers.Add ("SID", subscriber.Sid);
request.Headers.Add ("SEQ", seq.ToString ());
request.KeepAlive = false;
subscriber.Seq++;
using (var stream = request.GetRequestStream ()) {
using (var writer = XmlWriter.Create (stream,
new XmlWriterSettings { Encoding = Helper.UTF8Unsigned }))
{
writer.WriteProcessingInstruction ("xml", @"version=""1.0""");
writer.WriteStartElement ("e", "propertyset", Protocol.EventSchema);
foreach (var state_variable in stateVariables) {
writer.WriteStartElement ("property", Protocol.EventSchema);
writer.WriteElementString (state_variable.Name, state_variable.Value);
writer.WriteEndElement ();
}
writer.WriteEndElement ();
}
}
request.BeginGetResponse (async => {
try {
request.EndGetResponse (async).Close ();
#pragma warning disable 0420
Interlocked.Exchange (ref subscriber.ConnectFailures, 0);
#pragma warning restore 0420
} catch (Exception e) {
Log.Exception (string.Format (
"There was a problem publishing updates to subscription {0}.", subscriber.Sid), e);
#pragma warning disable 0420
Interlocked.Increment (ref subscriber.ConnectFailures);
#pragma warning restore 0420
if (subscriber.ConnectFailures == 2) {
lock (subscribers) {
if (subscribers.ContainsKey (subscriber.Sid)) {
subscribers.Remove (subscriber.Sid);
Log.Information (string.Format (
"Subscription {0} failed multiple times and was removed.", subscriber.Sid));
}
}
}
}
}, null);
}
protected override void HandleContext (HttpListenerContext context)
{
base.HandleContext (context);
var method = context.Request.HttpMethod.ToUpper ();
if (method == "SUBSCRIBE") {
var callback = context.Request.Headers["CALLBACK"];
if (callback != null) {
Subscribe (context, callback);
} else {
Renew (context);
}
} else if (method == "UNSUBSCRIBE") {
Unsubscribe (context);
} else {
Log.Warning (string.Format (
"A request from {0} to {1} uses an unsupported HTTP method: {2}.",
context.Request.RemoteEndPoint, context.Request.Url, method));
}
}
void Subscribe (HttpListenerContext context, string callback)
{
var url_string = callback.Length < 3 ? null : callback.Substring (1, callback.Length - 2);
if (url_string == null || !Uri.IsWellFormedUriString (url_string, UriKind.Absolute)) {
Log.Error (string.Format (
"The subscription request from {0} to {1} provided an illegal callback: {2}.",
context.Request.RemoteEndPoint, context.Request.Url, callback));
return;
}
var url = new Uri (url_string);
if (url.Scheme != Uri.UriSchemeHttp) {
Log.Error (string.Format (
"The callback for the subscription request from {0} to {1} is not HTTP: {2}.",
context.Request.RemoteEndPoint, context.Request.Url, url));
return;
}
var uuid = string.Format ("uuid:{0}", Guid.NewGuid ());
var subscriber = new Subscription (url, uuid);
if (!HandleSubscription (context, subscriber)) {
Log.Error (string.Format (
"{0} from {1} failed to subscribe to {0}.",
subscriber.Callback, context.Request.RemoteEndPoint, context.Request.Url));
return;
}
lock (subscribers) {
subscribers.Add (uuid, subscriber);
}
Log.Information (string.Format (
"{0} from {1} subscribed to {2} as {3}.",
subscriber.Callback, context.Request.RemoteEndPoint, context.Request.Url, subscriber.Sid));
PublishUpdates (subscriber, state_variables);
}
void Renew (HttpListenerContext context)
{
var sid = context.Request.Headers["SID"];
if (sid == null) {
Log.Error (string.Format (
"A subscription request from {0} to {1} provided neither a CALLBACK nor a SID.",
context.Request.RemoteEndPoint, context.Request.Url));
return;
}
Subscription subscription;
lock (subscribers) {
if (!subscribers.TryGetValue (sid, out subscription)) {
Log.Error (string.Format (
"A renewal request from {0} to {1} was for subscription {2} which does not exist.",
context.Request.RemoteEndPoint, context.Request.Url, sid));
return;
}
}
if (!HandleSubscription (context, subscription)) {
Log.Error (string.Format ("Failed to renew subscription {0}.", sid));
return;
}
Log.Information (string.Format ("Subscription {0} was renewed.", sid));
}
void Unsubscribe (HttpListenerContext context)
{
var sid = context.Request.Headers["SID"];
if (sid == null) {
Log.Error (string.Format (
"An unsubscribe request from {0} to {1} did not provide an SID.",
context.Request.RemoteEndPoint, context.Request.Url));
return;
}
Subscription subscription;
lock (subscribers) {
if (!subscribers.TryGetValue (sid, out subscription)) {
Log.Error (string.Format (
"An unsubscribe request from {0} to {1} was for subscription {2} which does not exist.",
context.Request.RemoteEndPoint, context.Request.Url, sid));
return;
}
subscribers.Remove (sid);
}
dispatcher.Remove (subscription.TimeoutId);
Log.Information (string.Format ("Subscription {0} was canceled.", sid));
}
bool HandleSubscription (HttpListenerContext context, Subscription subscriber)
{
dispatcher.Remove (subscriber.TimeoutId);
var timeout = context.Request.Headers["TIMEOUT"] ?? "Second-1800";
if (timeout != "infinite") {
int time;
if (timeout.Length > 7 && int.TryParse (timeout.Substring (7), out time)) {
subscriber.TimeoutId = dispatcher.Add (TimeSpan.FromSeconds (time), OnTimeout, subscriber.Sid);
} else {
Log.Error (string.Format (
"Subscription request {0} from {1} to {2} has an illegal TIMEOUT value: {3}",
subscriber.Callback, context.Request.RemoteEndPoint, context.Request.Url, timeout));
return false;
}
}
context.Response.AddHeader ("DATE", DateTime.Now.ToString ("r"));
context.Response.AddHeader ("SERVER", Protocol.UserAgent);
context.Response.AddHeader ("SID", subscriber.Sid);
context.Response.AddHeader ("TIMEOUT", timeout);
context.Response.StatusCode = 200;
context.Response.StatusDescription = "OK";
return true;
}
bool OnTimeout (object state, ref TimeSpan interval)
{
lock (subscribers) {
subscribers.Remove ((string)state);
}
Log.Information (string.Format ("Subscription {0} expired and was removed.", state));
return false;
}
static IEnumerable<StateVariable> GetEventedStateVariables (IEnumerable<StateVariable> stateVariables)
{
foreach (var state_variable in stateVariables) {
if (state_variable.SendsEvents) {
yield return state_variable;
}
}
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// gRPC server. A single server can server arbitrary number of services and can listen on more than one ports.
/// </summary>
public class Server
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Server>();
readonly AtomicCounter activeCallCounter = new AtomicCounter();
readonly ServiceDefinitionCollection serviceDefinitions;
readonly ServerPortCollection ports;
readonly GrpcEnvironment environment;
readonly List<ChannelOption> options;
readonly ServerSafeHandle handle;
readonly object myLock = new object();
readonly List<ServerServiceDefinition> serviceDefinitionsList = new List<ServerServiceDefinition>();
readonly List<ServerPort> serverPortList = new List<ServerPort>();
readonly Dictionary<string, IServerCallHandler> callHandlers = new Dictionary<string, IServerCallHandler>();
readonly TaskCompletionSource<object> shutdownTcs = new TaskCompletionSource<object>();
bool startRequested;
bool shutdownRequested;
/// <summary>
/// Create a new server.
/// </summary>
/// <param name="options">Channel options.</param>
public Server(IEnumerable<ChannelOption> options = null)
{
this.serviceDefinitions = new ServiceDefinitionCollection(this);
this.ports = new ServerPortCollection(this);
this.environment = GrpcEnvironment.AddRef();
this.options = options != null ? new List<ChannelOption>(options) : new List<ChannelOption>();
using (var channelArgs = ChannelOptions.CreateChannelArgs(this.options))
{
this.handle = ServerSafeHandle.NewServer(environment.CompletionQueue, channelArgs);
}
}
/// <summary>
/// Services that will be exported by the server once started. Register a service with this
/// server by adding its definition to this collection.
/// </summary>
public ServiceDefinitionCollection Services
{
get
{
return serviceDefinitions;
}
}
/// <summary>
/// Ports on which the server will listen once started. Register a port with this
/// server by adding its definition to this collection.
/// </summary>
public ServerPortCollection Ports
{
get
{
return ports;
}
}
/// <summary>
/// To allow awaiting termination of the server.
/// </summary>
public Task ShutdownTask
{
get
{
return shutdownTcs.Task;
}
}
/// <summary>
/// Starts the server.
/// </summary>
public void Start()
{
lock (myLock)
{
Preconditions.CheckState(!startRequested);
startRequested = true;
handle.Start();
AllowOneRpc();
}
}
/// <summary>
/// Requests server shutdown and when there are no more calls being serviced,
/// cleans up used resources. The returned task finishes when shutdown procedure
/// is complete.
/// </summary>
public async Task ShutdownAsync()
{
lock (myLock)
{
Preconditions.CheckState(startRequested);
Preconditions.CheckState(!shutdownRequested);
shutdownRequested = true;
}
handle.ShutdownAndNotify(HandleServerShutdown, environment);
await shutdownTcs.Task;
DisposeHandle();
await Task.Run(() => GrpcEnvironment.Release());
}
/// <summary>
/// Requests server shutdown while cancelling all the in-progress calls.
/// The returned task finishes when shutdown procedure is complete.
/// </summary>
public async Task KillAsync()
{
lock (myLock)
{
Preconditions.CheckState(startRequested);
Preconditions.CheckState(!shutdownRequested);
shutdownRequested = true;
}
handle.ShutdownAndNotify(HandleServerShutdown, environment);
handle.CancelAllCalls();
await shutdownTcs.Task;
DisposeHandle();
}
internal void AddCallReference(object call)
{
activeCallCounter.Increment();
bool success = false;
handle.DangerousAddRef(ref success);
Preconditions.CheckState(success);
}
internal void RemoveCallReference(object call)
{
handle.DangerousRelease();
activeCallCounter.Decrement();
}
/// <summary>
/// Adds a service definition.
/// </summary>
private void AddServiceDefinitionInternal(ServerServiceDefinition serviceDefinition)
{
lock (myLock)
{
Preconditions.CheckState(!startRequested);
foreach (var entry in serviceDefinition.CallHandlers)
{
callHandlers.Add(entry.Key, entry.Value);
}
serviceDefinitionsList.Add(serviceDefinition);
}
}
/// <summary>
/// Adds a listening port.
/// </summary>
private int AddPortInternal(ServerPort serverPort)
{
lock (myLock)
{
Preconditions.CheckNotNull(serverPort.Credentials, "serverPort");
Preconditions.CheckState(!startRequested);
var address = string.Format("{0}:{1}", serverPort.Host, serverPort.Port);
int boundPort;
using (var nativeCredentials = serverPort.Credentials.ToNativeCredentials())
{
if (nativeCredentials != null)
{
boundPort = handle.AddSecurePort(address, nativeCredentials);
}
else
{
boundPort = handle.AddInsecurePort(address);
}
}
var newServerPort = new ServerPort(serverPort, boundPort);
this.serverPortList.Add(newServerPort);
return boundPort;
}
}
/// <summary>
/// Allows one new RPC call to be received by server.
/// </summary>
private void AllowOneRpc()
{
lock (myLock)
{
if (!shutdownRequested)
{
handle.RequestCall(HandleNewServerRpc, environment);
}
}
}
private void DisposeHandle()
{
var activeCallCount = activeCallCounter.Count;
if (activeCallCount > 0)
{
Logger.Warning("Server shutdown has finished but there are still {0} active calls for that server.", activeCallCount);
}
handle.Dispose();
}
/// <summary>
/// Selects corresponding handler for given call and handles the call.
/// </summary>
private async Task HandleCallAsync(ServerRpcNew newRpc)
{
try
{
IServerCallHandler callHandler;
if (!callHandlers.TryGetValue(newRpc.Method, out callHandler))
{
callHandler = NoSuchMethodCallHandler.Instance;
}
await callHandler.HandleCall(newRpc, environment);
}
catch (Exception e)
{
Logger.Warning(e, "Exception while handling RPC.");
}
}
/// <summary>
/// Handles the native callback.
/// </summary>
private void HandleNewServerRpc(bool success, BatchContextSafeHandle ctx)
{
if (success)
{
ServerRpcNew newRpc = ctx.GetServerRpcNew(this);
// after server shutdown, the callback returns with null call
if (!newRpc.Call.IsInvalid)
{
Task.Run(async () => await HandleCallAsync(newRpc));
}
}
AllowOneRpc();
}
/// <summary>
/// Handles native callback.
/// </summary>
private void HandleServerShutdown(bool success, BatchContextSafeHandle ctx)
{
shutdownTcs.SetResult(null);
}
/// <summary>
/// Collection of service definitions.
/// </summary>
public class ServiceDefinitionCollection : IEnumerable<ServerServiceDefinition>
{
readonly Server server;
internal ServiceDefinitionCollection(Server server)
{
this.server = server;
}
/// <summary>
/// Adds a service definition to the server. This is how you register
/// handlers for a service with the server. Only call this before Start().
/// </summary>
public void Add(ServerServiceDefinition serviceDefinition)
{
server.AddServiceDefinitionInternal(serviceDefinition);
}
/// <summary>
/// Gets enumerator for this collection.
/// </summary>
public IEnumerator<ServerServiceDefinition> GetEnumerator()
{
return server.serviceDefinitionsList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return server.serviceDefinitionsList.GetEnumerator();
}
}
/// <summary>
/// Collection of server ports.
/// </summary>
public class ServerPortCollection : IEnumerable<ServerPort>
{
readonly Server server;
internal ServerPortCollection(Server server)
{
this.server = server;
}
/// <summary>
/// Adds a new port on which server should listen.
/// Only call this before Start().
/// <returns>The port on which server will be listening.</returns>
/// </summary>
public int Add(ServerPort serverPort)
{
return server.AddPortInternal(serverPort);
}
/// <summary>
/// Adds a new port on which server should listen.
/// <returns>The port on which server will be listening.</returns>
/// </summary>
/// <param name="host">the host</param>
/// <param name="port">the port. If zero, an unused port is chosen automatically.</param>
/// <param name="credentials">credentials to use to secure this port.</param>
public int Add(string host, int port, ServerCredentials credentials)
{
return Add(new ServerPort(host, port, credentials));
}
/// <summary>
/// Gets enumerator for this collection.
/// </summary>
public IEnumerator<ServerPort> GetEnumerator()
{
return server.serverPortList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return server.serverPortList.GetEnumerator();
}
}
}
}
| |
/*
* (c) 2008 MOSA - The Managed Operating System Alliance
*
* Licensed under the terms of the New BSD License.
*
* Authors:
* Simon Wollwage (rootnode) <kintaro@think-in-co.de>
*/
namespace Pictor.PixelFormat
{
public interface IPixelFormat
{
///<summary>
///</summary>
uint Width
{
get;
}
///<summary>
///</summary>
uint Height
{
get;
}
///<summary>
///</summary>
int Stride
{
get;
}
///<summary>
///</summary>
IBlender Blender
{
get;
}
///<summary>
///</summary>
///<param name="x"></param>
///<param name="y"></param>
///<returns></returns>
RGBA_Bytes Pixel(int x, int y);
///<summary>
///</summary>
///<param name="x"></param>
///<param name="y"></param>
///<param name="c"></param>
unsafe void CopyPixel(int x, int y, byte* c);
///<summary>
///</summary>
///<param name="from"></param>
///<param name="xdst"></param>
///<param name="ydst"></param>
///<param name="xsrc"></param>
///<param name="ysrc"></param>
///<param name="len"></param>
void CopyFrom(RasterBuffer from, int xdst, int ydst, int xsrc, int ysrc, uint len);
///<summary>
///</summary>
///<param name="p"></param>
///<param name="c"></param>
unsafe void MakePixel(byte* p, IColorType c);
///<summary>
///</summary>
///<param name="x"></param>
///<param name="y"></param>
///<param name="c"></param>
///<param name="cover"></param>
void BlendPixel(int x, int y, RGBA_Bytes c, byte cover);
///<summary>
///</summary>
///<param name="x"></param>
///<param name="y"></param>
///<param name="len"></param>
///<param name="c"></param>
void CopyHorizontalLine(int x, int y, uint len, RGBA_Bytes c);
///<summary>
///</summary>
///<param name="x"></param>
///<param name="y"></param>
///<param name="len"></param>
///<param name="c"></param>
void CopyVerticalLine(int x, int y, uint len, RGBA_Bytes c);
///<summary>
///</summary>
///<param name="x"></param>
///<param name="y"></param>
///<param name="x2"></param>
///<param name="c"></param>
///<param name="cover"></param>
void BlendHorizontalLine(int x, int y, int x2, RGBA_Bytes c, byte cover);
///<summary>
///</summary>
///<param name="x"></param>
///<param name="y1"></param>
///<param name="y2"></param>
///<param name="c"></param>
///<param name="cover"></param>
void BlendVerticalLine(int x, int y1, int y2, RGBA_Bytes c, byte cover);
///<summary>
///</summary>
///<param name="x"></param>
///<param name="y"></param>
///<param name="len"></param>
///<param name="colors"></param>
unsafe void CopyHorizontalColorSpan(int x, int y, uint len, RGBA_Bytes* colors);
///<summary>
///</summary>
///<param name="x"></param>
///<param name="y"></param>
///<param name="len"></param>
///<param name="colors"></param>
unsafe void CopyVerticalColorSpan(int x, int y, uint len, RGBA_Bytes* colors);
///<summary>
///</summary>
///<param name="x"></param>
///<param name="y"></param>
///<param name="len"></param>
///<param name="c"></param>
///<param name="covers"></param>
unsafe void BlendSolidHorizontalSpan(int x, int y, uint len, RGBA_Bytes c, byte* covers);
///<summary>
///</summary>
///<param name="x"></param>
///<param name="y"></param>
///<param name="len"></param>
///<param name="c"></param>
///<param name="covers"></param>
unsafe void BlendSolidVerticalSpan(int x, int y, uint len, RGBA_Bytes c, byte* covers);
///<summary>
///</summary>
///<param name="x"></param>
///<param name="y"></param>
///<param name="len"></param>
///<param name="colors"></param>
///<param name="covers"></param>
///<param name="cover"></param>
unsafe void BlendHorizontalColorSpan(int x, int y, uint len, RGBA_Bytes* colors, byte* covers, byte cover);
///<summary>
///</summary>
///<param name="x"></param>
///<param name="y"></param>
///<param name="len"></param>
///<param name="colors"></param>
///<param name="covers"></param>
///<param name="cover"></param>
unsafe void BlendVerticalColorSpan(int x, int y, uint len, RGBA_Bytes* colors, byte* covers, byte cover);
///<summary>
///</summary>
RasterBuffer RenderingBuffer
{
get;
}
///<summary>
///</summary>
///<param name="y"></param>
///<returns></returns>
unsafe byte* RowPointer(int y);
///<summary>
///</summary>
///<param name="x"></param>
///<param name="y"></param>
///<returns></returns>
unsafe byte* PixelPointer(int x, int y);
///<summary>
///</summary>
uint PixelWidthInBytes
{
get;
}
};
///<summary>
///</summary>
public abstract class PixelFormatProxy : IPixelFormat
{
protected IPixelFormat PixelFormat;
///<summary>
///</summary>
///<param name="pixf"></param>
public PixelFormatProxy(IPixelFormat pixf)
{
PixelFormat = pixf;
}
///<summary>
///</summary>
///<param name="pixf"></param>
public virtual void Attach(IPixelFormat pixf)
{
PixelFormat = pixf;
}
public virtual uint Width
{
get { return PixelFormat.Width; }
}
public virtual uint Height
{
get { return PixelFormat.Height; }
}
public virtual int Stride
{
get { return PixelFormat.Stride; }
}
public IBlender Blender
{
get
{
return PixelFormat.Blender;
}
}
public virtual RGBA_Bytes Pixel(int x, int y)
{
return PixelFormat.Pixel(y, x);
}
public unsafe virtual void CopyPixel(int x, int y, byte* c)
{
PixelFormat.CopyPixel(x, y, c);
}
public virtual void CopyFrom(RasterBuffer from, int xdst, int ydst, int xsrc, int ysrc, uint len)
{
PixelFormat.CopyFrom(from, xdst, ydst, xsrc, ysrc, len);
}
public unsafe virtual void MakePixel(byte* p, IColorType c)
{
PixelFormat.MakePixel(p, c);
}
public virtual void BlendPixel(int x, int y, RGBA_Bytes c, byte cover)
{
PixelFormat.BlendPixel(x, y, c, cover);
}
public virtual void CopyHorizontalLine(int x, int y, uint len, RGBA_Bytes c)
{
PixelFormat.CopyHorizontalLine(x, y, len, c);
}
public virtual void CopyVerticalLine(int x, int y, uint len, RGBA_Bytes c)
{
PixelFormat.CopyVerticalLine(x, y, len, c);
}
public virtual void BlendHorizontalLine(int x1, int y, int x2, RGBA_Bytes c, byte cover)
{
PixelFormat.BlendHorizontalLine(x1, y, x2, c, cover);
}
public virtual void BlendVerticalLine(int x, int y1, int y2, RGBA_Bytes c, byte cover)
{
PixelFormat.BlendVerticalLine(x, y1, y2, c, cover);
}
public unsafe virtual void BlendSolidHorizontalSpan(int x, int y, uint len, RGBA_Bytes c, byte* covers)
{
PixelFormat.BlendSolidHorizontalSpan(x, y, len, c, covers);
}
public unsafe virtual void BlendSolidVerticalSpan(int x, int y, uint len, RGBA_Bytes c, byte* covers)
{
PixelFormat.BlendSolidVerticalSpan(x, y, len, c, covers);
}
public unsafe virtual void CopyHorizontalColorSpan(int x, int y, uint len, RGBA_Bytes* colors)
{
PixelFormat.CopyHorizontalColorSpan(x, y, len, colors);
}
public unsafe virtual void CopyVerticalColorSpan(int x, int y, uint len, RGBA_Bytes* colors)
{
PixelFormat.CopyVerticalColorSpan(x, y, len, colors);
}
public unsafe virtual void BlendHorizontalColorSpan(int x, int y, uint len, RGBA_Bytes* colors, byte* covers, byte cover)
{
PixelFormat.BlendHorizontalColorSpan(x, y, len, colors, covers, cover);
}
public unsafe virtual void BlendVerticalColorSpan(int x, int y, uint len, RGBA_Bytes* colors, byte* covers, byte cover)
{
PixelFormat.BlendVerticalColorSpan(x, y, len, colors, covers, cover);
}
public virtual RasterBuffer RenderingBuffer
{
get
{
return PixelFormat.RenderingBuffer;
}
}
public unsafe byte* RowPointer(int y)
{
return PixelFormat.RowPointer(y);
}
public unsafe virtual byte* PixelPointer(int x, int y)
{
return PixelFormat.PixelPointer(x, y);
}
public virtual uint PixelWidthInBytes
{
get
{
return PixelFormat.PixelWidthInBytes;
}
}
};
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace System.Data.SqlClient.SNI
{
/// <summary>
/// SNI Packet
/// </summary>
internal class SNIPacket : IDisposable, IEquatable<SNIPacket>
{
private byte[] _data;
private int _length;
private int _capacity;
private int _offset;
private string _description;
private SNIAsyncCallback _completionCallback;
/// <summary>
/// Constructor
/// </summary>
/// <param name="handle">Owning SNI handle</param>
public SNIPacket(SNIHandle handle)
{
_offset = 0;
}
/// <summary>
/// Packet description (used for debugging)
/// </summary>
public string Description
{
get
{
return _description;
}
set
{
_description = value;
}
}
/// <summary>
/// Data left to process
/// </summary>
public int DataLeft
{
get
{
return _length - _offset;
}
}
/// <summary>
/// Length of data
/// </summary>
public int Length
{
get
{
return _length;
}
}
/// <summary>
/// Packet validity
/// </summary>
public bool IsInvalid
{
get
{
return _data == null;
}
}
/// <summary>
/// Packet data
/// </summary>
public void Dispose()
{
_data = null;
_length = 0;
_capacity = 0;
}
/// <summary>
/// Set async completion callback
/// </summary>
/// <param name="completionCallback">Completion callback</param>
public void SetCompletionCallback(SNIAsyncCallback completionCallback)
{
_completionCallback = completionCallback;
}
/// <summary>
/// Invoke the completion callback
/// </summary>
/// <param name="sniErrorCode">SNI error</param>
public void InvokeCompletionCallback(uint sniErrorCode)
{
_completionCallback(this, sniErrorCode);
}
/// <summary>
/// Allocate space for data
/// </summary>
/// <param name="capacity">Bytes to allocate</param>
public void Allocate(int capacity)
{
_capacity = capacity;
_data = new Byte[capacity];
}
/// <summary>
/// Clone packet
/// </summary>
/// <returns>Cloned packet</returns>
public SNIPacket Clone()
{
SNIPacket packet = new SNIPacket(null);
packet._data = new byte[_length];
Array.Copy(_data, 0, packet._data, 0, _length);
packet._length = _length;
return packet;
}
/// <summary>
/// Get packet data
/// </summary>
/// <param name="inBuff">Buffer</param>
/// <param name="dataSize">Data in packet</param>
public void GetData(byte[] buffer, ref int dataSize)
{
Buffer.BlockCopy(_data, 0, buffer, 0, _length);
dataSize = _length;
}
/// <summary>
/// Set packet data
/// </summary>
/// <param name="data">Data</param>
/// <param name="length">Length</param>
public void SetData(byte[] data, int length)
{
_data = data;
_length = length;
_capacity = length;
_offset = 0;
}
/// <summary>
/// Take data from another packet
/// </summary>
/// <param name="packet">Packet</param>
/// <param name="size">Data to take</param>
/// <returns>Amount of data taken</returns>
public int TakeData(SNIPacket packet, int size)
{
int dataSize = TakeData(packet._data, packet._length, size);
packet._length += dataSize;
return dataSize;
}
/// <summary>
/// Append data
/// </summary>
/// <param name="data">Data</param>
/// <param name="size">Size</param>
public void AppendData(byte[] data, int size)
{
Buffer.BlockCopy(data, 0, _data, _length, size);
_length += size;
}
/// <summary>
/// Append another packet
/// </summary>
/// <param name="packet">Packet</param>
public void AppendPacket(SNIPacket packet)
{
Buffer.BlockCopy(packet._data, 0, _data, _length, packet._length);
_length += packet._length;
}
/// <summary>
/// Take data from packet and advance offset
/// </summary>
/// <param name="buffer">Buffer</param>
/// <param name="dataOffset">Data offset</param>
/// <param name="size">Size</param>
/// <returns></returns>
public int TakeData(byte[] buffer, int dataOffset, int size)
{
if (_offset >= _length)
{
return 0;
}
if (_offset + size > _length)
{
size = _length - _offset;
}
Buffer.BlockCopy(_data, _offset, buffer, dataOffset, size);
_offset = _offset + size;
return size;
}
/// <summary>
/// Release packet
/// </summary>
public void Release()
{
_length = 0;
_capacity = 0;
_data = null;
}
/// <summary>
/// Reset packet
/// </summary>
public void Reset()
{
_length = 0;
_data = new byte[_capacity];
}
/// <summary>
/// Read data from a stream asynchronously
/// </summary>
/// <param name="stream">Stream to read from</param>
/// <param name="callback">Completion callback</param>
public void ReadFromStreamAsync(Stream stream, SNIAsyncCallback callback)
{
bool error = false;
stream.ReadAsync(_data, 0, _capacity).ContinueWith(t =>
{
Exception e = t.Exception != null ? t.Exception.InnerException : null;
if (e != null)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, SNICommon.InternalExceptionError, e);
error = true;
}
else
{
_length = t.Result;
if (_length == 0)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, 0, SNICommon.ConnTerminatedError, string.Empty);
error = true;
}
}
if (error)
{
this.Release();
}
callback(this, error ? TdsEnums.SNI_ERROR : TdsEnums.SNI_SUCCESS);
},
CancellationToken.None,
TaskContinuationOptions.DenyChildAttach,
TaskScheduler.Default);
}
/// <summary>
/// Read data from a stream synchronously
/// </summary>
/// <param name="stream">Stream to read from</param>
public void ReadFromStream(Stream stream)
{
_length = stream.Read(_data, 0, _capacity);
}
/// <summary>
/// Write data to a stream synchronously
/// </summary>
/// <param name="stream">Stream to write to</param>
public void WriteToStream(Stream stream)
{
stream.Write(_data, 0, _length);
}
/// <summary>
/// Get hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Check packet equality
/// </summary>
/// <param name="obj"></param>
/// <returns>true if equal</returns>
public override bool Equals(object obj)
{
SNIPacket packet = obj as SNIPacket;
if (packet != null)
{
return Equals(packet);
}
return false;
}
/// <summary>
/// Check packet equality
/// </summary>
/// <param name="obj"></param>
/// <returns>true if equal</returns>
public bool Equals(SNIPacket packet)
{
if (packet != null)
{
return object.ReferenceEquals(packet, this);
}
return false;
}
}
}
| |
// 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.Collections.Immutable;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Semantics;
namespace Microsoft.ApiDesignGuidelines.Analyzers
{
/// <summary>
/// CA1063: Implement IDisposable Correctly
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class ImplementIDisposableCorrectlyAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA1063";
private const string HelpLinkUri = "https://msdn.microsoft.com/library/ms244737.aspx";
private const string DisposeMethodName = "Dispose";
private const string GarbageCollectorTypeName = "System.GC";
private const string SuppressFinalizeMethodName = "SuppressFinalize";
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyTitle), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageIDisposableReimplementation = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageIDisposableReimplementation), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageFinalizeOverride = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageFinalizeOverride), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageDisposeOverride = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageDisposeOverride), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageDisposeSignature = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageDisposeSignature), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageRenameDispose = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageRenameDispose), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageDisposeBoolSignature = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageDisposeBoolSignature), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageDisposeImplementation = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageDisposeImplementation), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageFinalizeImplementation = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageFinalizeImplementation), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageProvideDisposeBool = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageProvideDisposeBool), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyDescription), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
internal static DiagnosticDescriptor IDisposableReimplementationRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageIDisposableReimplementation,
DiagnosticCategory.Design,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: HelpLinkUri,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor FinalizeOverrideRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageFinalizeOverride,
DiagnosticCategory.Design,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: HelpLinkUri,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor DisposeOverrideRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageDisposeOverride,
DiagnosticCategory.Design,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: HelpLinkUri,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor DisposeSignatureRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageDisposeSignature,
DiagnosticCategory.Design,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: HelpLinkUri,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor RenameDisposeRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageRenameDispose,
DiagnosticCategory.Design,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: HelpLinkUri,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor DisposeBoolSignatureRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageDisposeBoolSignature,
DiagnosticCategory.Design,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: HelpLinkUri,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor DisposeImplementationRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageDisposeImplementation,
DiagnosticCategory.Design,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: HelpLinkUri,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor FinalizeImplementationRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageFinalizeImplementation,
DiagnosticCategory.Design,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: HelpLinkUri,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor ProvideDisposeBoolRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageProvideDisposeBool,
DiagnosticCategory.Design,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: HelpLinkUri,
customTags: WellKnownDiagnosticTags.Telemetry);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(IDisposableReimplementationRule, FinalizeOverrideRule, DisposeOverrideRule, DisposeSignatureRule, RenameDisposeRule, DisposeBoolSignatureRule, DisposeImplementationRule, FinalizeImplementationRule, ProvideDisposeBoolRule);
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.EnableConcurrentExecution();
analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
analysisContext.RegisterCompilationStartAction(
context =>
{
INamedTypeSymbol disposableType = WellKnownTypes.IDisposable(context.Compilation);
if (disposableType == null)
{
return;
}
var disposeInterfaceMethod = disposableType.GetMembers(DisposeMethodName).Single() as IMethodSymbol;
if (disposeInterfaceMethod == null)
{
return;
}
INamedTypeSymbol garbageCollectorType = context.Compilation.GetTypeByMetadataName(GarbageCollectorTypeName);
if (garbageCollectorType == null)
{
return;
}
var suppressFinalizeMethod = garbageCollectorType.GetMembers(SuppressFinalizeMethodName).Single() as IMethodSymbol;
if (suppressFinalizeMethod == null)
{
return;
}
var analyzer = new PerCompilationAnalyzer(disposableType, disposeInterfaceMethod, suppressFinalizeMethod);
analyzer.Initialize(context);
});
}
private static bool IsDisposeBoolMethod(IMethodSymbol method)
{
if (method.Name == DisposeMethodName && method.MethodKind == MethodKind.Ordinary &&
method.ReturnsVoid && method.Parameters.Length == 1)
{
IParameterSymbol parameter = method.Parameters[0];
if (parameter.Type != null && parameter.Type.SpecialType == SpecialType.System_Boolean && parameter.RefKind == RefKind.None)
{
return true;
}
}
return false;
}
/// <summary>
/// Analyzes single instance of compilation.
/// </summary>
private class PerCompilationAnalyzer
{
private readonly INamedTypeSymbol _disposableType;
private readonly IMethodSymbol _disposeInterfaceMethod;
private readonly IMethodSymbol _suppressFinalizeMethod;
public PerCompilationAnalyzer(INamedTypeSymbol disposableType, IMethodSymbol disposeInterfaceMethod, IMethodSymbol suppressFinalizeMethod)
{
_disposableType = disposableType;
_disposeInterfaceMethod = disposeInterfaceMethod;
_suppressFinalizeMethod = suppressFinalizeMethod;
}
public void Initialize(CompilationStartAnalysisContext context)
{
context.RegisterSymbolAction(AnalyzeNamedTypeSymbol, SymbolKind.NamedType);
context.RegisterOperationBlockAction(AnalyzeOperationBlock);
}
private void AnalyzeNamedTypeSymbol(SymbolAnalysisContext context)
{
var type = context.Symbol as INamedTypeSymbol;
if (type != null && type.TypeKind == TypeKind.Class)
{
bool implementsDisposableInBaseType = ImplementsDisposableInBaseType(type);
if (ImplementsDisposableDirectly(type))
{
IMethodSymbol disposeMethod = FindDisposeMethod(type);
if (disposeMethod != null)
{
// This is difference from FxCop implementation
// IDisposable Reimplementation Rule is violated only if type re-implements Dispose method, not just interface
// For example see unit tests:
// CSharp_CA1063_IDisposableReimplementation_NoDiagnostic_ImplementingInheritedInterfaceWithNoDisposeReimplementation
// Basic_CA1063_IDisposableReimplementation_NoDiagnostic_ImplementingInheritedInterfaceWithNoDisposeReimplementation
CheckIDisposableReimplementationRule(type, context, implementsDisposableInBaseType);
CheckDisposeSignatureRule(disposeMethod, type, context);
CheckRenameDisposeRule(disposeMethod, type, context);
if (!type.IsSealed && type.DeclaredAccessibility != Accessibility.Private)
{
IMethodSymbol disposeBoolMethod = FindDisposeBoolMethod(type);
if (disposeBoolMethod != null)
{
CheckDisposeBoolSignatureRule(disposeBoolMethod, type, context);
}
else
{
CheckProvideDisposeBoolRule(type, context);
}
}
}
else if (type.Interfaces.Contains(_disposableType))
{
// Reports violation, when type mentions IDisposable as implemented interface,
// even when Dispose method is not implemented, but inherited from base type
// For example see unit test:
// CSharp_CA1063_IDisposableReimplementation_Diagnostic_ReImplementingIDisposableWithNoDisposeMethod
CheckIDisposableReimplementationRule(type, context, implementsDisposableInBaseType);
}
}
if (implementsDisposableInBaseType)
{
foreach (IMethodSymbol method in type.GetMembers().OfType<IMethodSymbol>())
{
CheckDisposeOverrideRule(method, type, context);
}
CheckFinalizeOverrideRule(type, context);
}
}
}
private void AnalyzeOperationBlock(OperationBlockAnalysisContext context)
{
var method = context.OwningSymbol as IMethodSymbol;
if (method == null)
{
return;
}
bool isFinalizerMethod = method.IsFinalizer();
bool isDisposeMethod = method.Name == DisposeMethodName;
if (isFinalizerMethod || isDisposeMethod)
{
INamedTypeSymbol type = method.ContainingType;
if (type != null && type.TypeKind == TypeKind.Class &&
!type.IsSealed && type.DeclaredAccessibility != Accessibility.Private)
{
if (ImplementsDisposableDirectly(type))
{
IMethodSymbol disposeMethod = FindDisposeMethod(type);
if (disposeMethod != null)
{
if (method == disposeMethod)
{
CheckDisposeImplementationRule(method, type, context.OperationBlocks, context);
}
else if (isFinalizerMethod)
{
// Check implementation of finalizer only if the class explicitly implements IDisposable
// If class implements interface inherited from IDisposable and IDisposable is implemented in base class
// then implementation of finalizer is ignored
CheckFinalizeImplementationRule(method, type, context.OperationBlocks, context);
}
}
}
}
}
}
/// <summary>
/// Check rule: Remove IDisposable from the list of interfaces implemented by {0} and override the base class Dispose implementation instead.
/// </summary>
private static void CheckIDisposableReimplementationRule(INamedTypeSymbol type, SymbolAnalysisContext context, bool implementsDisposableInBaseType)
{
if (implementsDisposableInBaseType)
{
context.ReportDiagnostic(type.CreateDiagnostic(IDisposableReimplementationRule, type.Name));
}
}
// CA1801: Remove unused parameters.
// TODO: Remove the below suppression once Roslyn bug https://github.com/dotnet/roslyn/issues/8884 is fixed.
#pragma warning disable CA1801
/// <summary>
/// Checks rule: Ensure that {0} is declared as public and sealed.
/// </summary>
private static void CheckDisposeSignatureRule(IMethodSymbol method, INamedTypeSymbol type, SymbolAnalysisContext context)
#pragma warning restore CA1801
{
if (!method.IsPublic() ||
method.IsAbstract || method.IsVirtual || (method.IsOverride && !method.IsSealed))
{
context.ReportDiagnostic(method.CreateDiagnostic(DisposeSignatureRule, $"{type.Name}.{method.Name}"));
}
}
// CA1801: Remove unused parameters.
// TODO: Remove the below suppression once Roslyn bug https://github.com/dotnet/roslyn/issues/8884 is fixed.
#pragma warning disable CA1801
/// <summary>
/// Checks rule: Rename {0} to 'Dispose' and ensure that it is declared as public and sealed.
/// </summary>
private static void CheckRenameDisposeRule(IMethodSymbol method, INamedTypeSymbol type, SymbolAnalysisContext context)
#pragma warning restore CA1801
{
if (method.Name != DisposeMethodName)
{
context.ReportDiagnostic(method.CreateDiagnostic(RenameDisposeRule, $"{type.Name}.{method.Name}"));
}
}
// CA1801: Remove unused parameters.
// TODO: Remove the below suppression once Roslyn bug https://github.com/dotnet/roslyn/issues/8884 is fixed.
#pragma warning disable CA1801
/// <summary>
/// Checks rule: Remove {0}, override Dispose(bool disposing), and put the dispose logic in the code path where 'disposing' is true.
/// </summary>
private void CheckDisposeOverrideRule(IMethodSymbol method, INamedTypeSymbol type, SymbolAnalysisContext context)
#pragma warning restore CA1801
{
if (method.MethodKind == MethodKind.Ordinary && method.IsOverride && method.ReturnsVoid && method.Parameters.Length == 0)
{
bool isDisposeOverride = false;
for (IMethodSymbol m = method.OverriddenMethod; m != null; m = m.OverriddenMethod)
{
if (m == FindDisposeMethod(m.ContainingType))
{
isDisposeOverride = true;
break;
}
}
if (isDisposeOverride)
{
context.ReportDiagnostic(method.CreateDiagnostic(DisposeOverrideRule, $"{type.Name}.{method.Name}"));
}
}
}
/// <summary>
/// Checks rule: Remove the finalizer from type {0}, override Dispose(bool disposing), and put the finalization logic in the code path where 'disposing' is false.
/// </summary>
private static void CheckFinalizeOverrideRule(INamedTypeSymbol type, SymbolAnalysisContext context)
{
if (type.HasFinalizer())
{
context.ReportDiagnostic(type.CreateDiagnostic(FinalizeOverrideRule, type.Name));
}
}
/// <summary>
/// Checks rule: Provide an overridable implementation of Dispose(bool) on {0} or mark the type as sealed. A call to Dispose(false) should only clean up native resources. A call to Dispose(true) should clean up both managed and native resources.
/// </summary>
private static void CheckProvideDisposeBoolRule(INamedTypeSymbol type, SymbolAnalysisContext context)
{
context.ReportDiagnostic(type.CreateDiagnostic(ProvideDisposeBoolRule, type.Name));
}
// CA1801: Remove unused parameters.
// TODO: Remove the below suppression once Roslyn bug https://github.com/dotnet/roslyn/issues/8884 is fixed.
#pragma warning disable CA1801
/// <summary>
/// Checks rule: Ensure that {0} is declared as protected, virtual, and unsealed.
/// </summary>
private static void CheckDisposeBoolSignatureRule(IMethodSymbol method, INamedTypeSymbol type, SymbolAnalysisContext context)
#pragma warning restore CA1801
{
if (method.DeclaredAccessibility != Accessibility.Protected ||
!(method.IsVirtual || method.IsAbstract || method.IsOverride) || method.IsSealed)
{
context.ReportDiagnostic(method.CreateDiagnostic(DisposeBoolSignatureRule, $"{type.Name}.{method.Name}"));
}
}
/// <summary>
/// Checks rule: Modify {0} so that it calls Dispose(true), then calls GC.SuppressFinalize on the current object instance ('this' or 'Me' in Visual Basic), and then returns.
/// </summary>
private void CheckDisposeImplementationRule(IMethodSymbol method, INamedTypeSymbol type, ImmutableArray<IOperation> operationBlocks, OperationBlockAnalysisContext context)
{
var validator = new DisposeImplementationValidator(_suppressFinalizeMethod, type);
if (!validator.Validate(operationBlocks))
{
context.ReportDiagnostic(method.CreateDiagnostic(DisposeImplementationRule, $"{type.Name}.{method.Name}"));
}
}
// CA1801: Remove unused parameters.
#pragma warning disable CA1801
/// <summary>
/// Checks rule: Modify {0} so that it calls Dispose(false) and then returns.
/// </summary>
private static void CheckFinalizeImplementationRule(IMethodSymbol method, INamedTypeSymbol type, ImmutableArray<IOperation> operationBlocks, OperationBlockAnalysisContext context)
#pragma warning restore CA1801
{
// TODO: Implement check of Finalize
}
/// <summary>
/// Checks if type implements IDisposable interface or an interface inherited from IDisposable.
/// Only direct implementation is taken into account, implementation in base type is ignored.
/// </summary>
private bool ImplementsDisposableDirectly(ITypeSymbol type)
{
return type.Interfaces.Any(i => i.Inherits(_disposableType));
}
/// <summary>
/// Checks if base type implements IDisposable interface directly or indirectly.
/// </summary>
private bool ImplementsDisposableInBaseType(ITypeSymbol type)
{
return type.BaseType != null && type.BaseType.AllInterfaces.Contains(_disposableType);
}
/// <summary>
/// Returns method that implements IDisposable.Dispose operation.
/// Only direct implementation is taken into account, implementation in base type is ignored.
/// </summary>
private IMethodSymbol FindDisposeMethod(INamedTypeSymbol type)
{
var disposeMethod = type.FindImplementationForInterfaceMember(_disposeInterfaceMethod) as IMethodSymbol;
if (disposeMethod != null && disposeMethod.ContainingType == type)
{
return disposeMethod;
}
return null;
}
/// <summary>
/// Returns method: void Dispose(bool)
/// </summary>
private static IMethodSymbol FindDisposeBoolMethod(INamedTypeSymbol type)
{
return type.GetMembers(DisposeMethodName).OfType<IMethodSymbol>().FirstOrDefault(IsDisposeBoolMethod);
}
}
/// <summary>
/// Validates implementation of Dispose method. The method must call Dispose(true) and then GC.SuppressFinalize(this).
/// </summary>
private struct DisposeImplementationValidator
{
// this type will be created per compilation
// this is actually a bug - https://github.com/dotnet/roslyn-analyzers/issues/845
#pragma warning disable RS1008
private readonly IMethodSymbol _suppressFinalizeMethod;
private readonly INamedTypeSymbol _type;
#pragma warning restore RS1008
private bool _callsDisposeBool;
private bool _callsSuppressFinalize;
public DisposeImplementationValidator(IMethodSymbol suppressFinalizeMethod, INamedTypeSymbol type)
{
_callsDisposeBool = false;
_callsSuppressFinalize = false;
_suppressFinalizeMethod = suppressFinalizeMethod;
_type = type;
}
public bool Validate(ImmutableArray<IOperation> operations)
{
_callsDisposeBool = false;
_callsSuppressFinalize = false;
if (ValidateOperations(operations))
{
return _callsDisposeBool && _callsSuppressFinalize;
}
return false;
}
private bool ValidateOperations(ImmutableArray<IOperation> operations)
{
foreach (IOperation operation in operations)
{
if (!ValidateOperation(operation))
{
return false;
}
}
return true;
}
private bool ValidateOperation(IOperation operation)
{
switch (operation.Kind)
{
case OperationKind.EmptyStatement:
case OperationKind.LabelStatement:
return true;
case OperationKind.BlockStatement:
var blockStatement = (IBlockStatement)operation;
return ValidateOperations(blockStatement.Statements);
case OperationKind.ExpressionStatement:
var expressionStatement = (IExpressionStatement)operation;
return ValidateExpression(expressionStatement);
default:
return false;
}
}
private bool ValidateExpression(IExpressionStatement expressionStatement)
{
if (expressionStatement.Expression == null || expressionStatement.Expression.Kind != OperationKind.InvocationExpression)
{
return false;
}
var invocationExpression = (IInvocationExpression)expressionStatement.Expression;
if (!_callsDisposeBool)
{
bool result = IsDisposeBoolCall(invocationExpression);
if (result)
{
_callsDisposeBool = true;
}
return result;
}
else if (!_callsSuppressFinalize)
{
bool result = IsSuppressFinalizeCall(invocationExpression);
if (result)
{
_callsSuppressFinalize = true;
}
return result;
}
return false;
}
private bool IsDisposeBoolCall(IInvocationExpression invocationExpression)
{
if (invocationExpression.TargetMethod == null ||
invocationExpression.TargetMethod.ContainingType != _type ||
!IsDisposeBoolMethod(invocationExpression.TargetMethod))
{
return false;
}
if (invocationExpression.Instance.Kind != OperationKind.InstanceReferenceExpression)
{
return false;
}
var instanceReferenceExpression = (IInstanceReferenceExpression)invocationExpression.Instance;
if (instanceReferenceExpression.InstanceReferenceKind != InstanceReferenceKind.Implicit &&
instanceReferenceExpression.InstanceReferenceKind != InstanceReferenceKind.Explicit)
{
return false;
}
if (invocationExpression.ArgumentsInParameterOrder.Length != 1)
{
return false;
}
IArgument argument = invocationExpression.ArgumentsInParameterOrder[0];
if (argument.Value.Kind != OperationKind.LiteralExpression)
{
return false;
}
var literal = (ILiteralExpression)argument.Value;
if (!literal.ConstantValue.HasValue || !true.Equals(literal.ConstantValue.Value))
{
return false;
}
return true;
}
private bool IsSuppressFinalizeCall(IInvocationExpression invocationExpression)
{
if (invocationExpression.TargetMethod != _suppressFinalizeMethod)
{
return false;
}
if (invocationExpression.ArgumentsInParameterOrder.Length != 1)
{
return false;
}
IOperation argumentValue = invocationExpression.ArgumentsInParameterOrder[0].Value;
if (argumentValue.Kind != OperationKind.ConversionExpression)
{
return false;
}
var conversion = (IConversionExpression)argumentValue;
if (conversion.ConversionKind != ConversionKind.Cast && conversion.ConversionKind != ConversionKind.CSharp && conversion.ConversionKind != ConversionKind.Basic)
{
return false;
}
if (conversion.Operand == null || conversion.Operand.Kind != OperationKind.InstanceReferenceExpression)
{
return false;
}
var instanceReferenceExpression = (IInstanceReferenceExpression)conversion.Operand;
if (instanceReferenceExpression.InstanceReferenceKind != InstanceReferenceKind.Implicit &&
instanceReferenceExpression.InstanceReferenceKind != InstanceReferenceKind.Explicit)
{
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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Xml.Serialization
{
[System.AttributeUsageAttribute((System.AttributeTargets)(10624), AllowMultiple = false)]
public partial class XmlAnyAttributeAttribute : System.Attribute
{
public XmlAnyAttributeAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(10624), AllowMultiple = true)]
public partial class XmlAnyElementAttribute : System.Attribute
{
public XmlAnyElementAttribute() { }
public XmlAnyElementAttribute(string name) { }
public XmlAnyElementAttribute(string name, string ns) { }
public string Name { get { return default(string); } set { } }
public string Namespace { get { return default(string); } set { } }
public int Order { get { return default(int); } set { } }
}
public partial class XmlAnyElementAttributes
{
public XmlAnyElementAttributes() { }
public System.Xml.Serialization.XmlAnyElementAttribute this[int index] { get { return default(System.Xml.Serialization.XmlAnyElementAttribute); } set { } }
public int Add(System.Xml.Serialization.XmlAnyElementAttribute attribute) { return default(int); }
public bool Contains(System.Xml.Serialization.XmlAnyElementAttribute attribute) { return default(bool); }
public void CopyTo(System.Xml.Serialization.XmlAnyElementAttribute[] array, int index) { }
public int IndexOf(System.Xml.Serialization.XmlAnyElementAttribute attribute) { return default(int); }
public void Insert(int index, System.Xml.Serialization.XmlAnyElementAttribute attribute) { }
public void Remove(System.Xml.Serialization.XmlAnyElementAttribute attribute) { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(10624), AllowMultiple = false)]
public partial class XmlArrayAttribute : System.Attribute
{
public XmlArrayAttribute() { }
public XmlArrayAttribute(string elementName) { }
public string ElementName { get { return default(string); } set { } }
public System.Xml.Schema.XmlSchemaForm Form { get { return default(System.Xml.Schema.XmlSchemaForm); } set { } }
public bool IsNullable { get { return default(bool); } set { } }
public string Namespace { get { return default(string); } set { } }
public int Order { get { return default(int); } set { } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(10624), AllowMultiple = true)]
public partial class XmlArrayItemAttribute : System.Attribute
{
public XmlArrayItemAttribute() { }
public XmlArrayItemAttribute(string elementName) { }
public XmlArrayItemAttribute(string elementName, System.Type type) { }
public XmlArrayItemAttribute(System.Type type) { }
public string DataType { get { return default(string); } set { } }
public string ElementName { get { return default(string); } set { } }
public System.Xml.Schema.XmlSchemaForm Form { get { return default(System.Xml.Schema.XmlSchemaForm); } set { } }
public bool IsNullable { get { return default(bool); } set { } }
public string Namespace { get { return default(string); } set { } }
public int NestingLevel { get { return default(int); } set { } }
public System.Type Type { get { return default(System.Type); } set { } }
}
public partial class XmlArrayItemAttributes
{
public XmlArrayItemAttributes() { }
public System.Xml.Serialization.XmlArrayItemAttribute this[int index] { get { return default(System.Xml.Serialization.XmlArrayItemAttribute); } set { } }
public int Add(System.Xml.Serialization.XmlArrayItemAttribute attribute) { return default(int); }
public bool Contains(System.Xml.Serialization.XmlArrayItemAttribute attribute) { return default(bool); }
public void CopyTo(System.Xml.Serialization.XmlArrayItemAttribute[] array, int index) { }
public int IndexOf(System.Xml.Serialization.XmlArrayItemAttribute attribute) { return default(int); }
public void Insert(int index, System.Xml.Serialization.XmlArrayItemAttribute attribute) { }
public void Remove(System.Xml.Serialization.XmlArrayItemAttribute attribute) { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(10624))]
public partial class XmlAttributeAttribute : System.Attribute
{
public XmlAttributeAttribute() { }
public XmlAttributeAttribute(string attributeName) { }
public XmlAttributeAttribute(string attributeName, System.Type type) { }
public XmlAttributeAttribute(System.Type type) { }
public string AttributeName { get { return default(string); } set { } }
public string DataType { get { return default(string); } set { } }
public System.Xml.Schema.XmlSchemaForm Form { get { return default(System.Xml.Schema.XmlSchemaForm); } set { } }
public string Namespace { get { return default(string); } set { } }
public System.Type Type { get { return default(System.Type); } set { } }
}
public partial class XmlAttributeOverrides
{
public XmlAttributeOverrides() { }
public System.Xml.Serialization.XmlAttributes this[System.Type type] { get { return default(System.Xml.Serialization.XmlAttributes); } }
public System.Xml.Serialization.XmlAttributes this[System.Type type, string member] { get { return default(System.Xml.Serialization.XmlAttributes); } }
public void Add(System.Type type, string member, System.Xml.Serialization.XmlAttributes attributes) { }
public void Add(System.Type type, System.Xml.Serialization.XmlAttributes attributes) { }
}
public partial class XmlAttributes
{
public XmlAttributes() { }
public System.Xml.Serialization.XmlAnyAttributeAttribute XmlAnyAttribute { get { return default(System.Xml.Serialization.XmlAnyAttributeAttribute); } set { } }
public System.Xml.Serialization.XmlAnyElementAttributes XmlAnyElements { get { return default(System.Xml.Serialization.XmlAnyElementAttributes); } }
public System.Xml.Serialization.XmlArrayAttribute XmlArray { get { return default(System.Xml.Serialization.XmlArrayAttribute); } set { } }
public System.Xml.Serialization.XmlArrayItemAttributes XmlArrayItems { get { return default(System.Xml.Serialization.XmlArrayItemAttributes); } }
public System.Xml.Serialization.XmlAttributeAttribute XmlAttribute { get { return default(System.Xml.Serialization.XmlAttributeAttribute); } set { } }
public System.Xml.Serialization.XmlChoiceIdentifierAttribute XmlChoiceIdentifier { get { return default(System.Xml.Serialization.XmlChoiceIdentifierAttribute); } }
public object XmlDefaultValue { get { return default(object); } set { } }
public System.Xml.Serialization.XmlElementAttributes XmlElements { get { return default(System.Xml.Serialization.XmlElementAttributes); } }
public System.Xml.Serialization.XmlEnumAttribute XmlEnum { get { return default(System.Xml.Serialization.XmlEnumAttribute); } set { } }
public bool XmlIgnore { get { return default(bool); } set { } }
public bool Xmlns { get { return default(bool); } set { } }
public System.Xml.Serialization.XmlRootAttribute XmlRoot { get { return default(System.Xml.Serialization.XmlRootAttribute); } set { } }
public System.Xml.Serialization.XmlTextAttribute XmlText { get { return default(System.Xml.Serialization.XmlTextAttribute); } set { } }
public System.Xml.Serialization.XmlTypeAttribute XmlType { get { return default(System.Xml.Serialization.XmlTypeAttribute); } set { } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(10624), AllowMultiple = false)]
public partial class XmlChoiceIdentifierAttribute : System.Attribute
{
public XmlChoiceIdentifierAttribute() { }
public XmlChoiceIdentifierAttribute(string name) { }
public string MemberName { get { return default(string); } set { } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(10624), AllowMultiple = true)]
public partial class XmlElementAttribute : System.Attribute
{
public XmlElementAttribute() { }
public XmlElementAttribute(string elementName) { }
public XmlElementAttribute(string elementName, System.Type type) { }
public XmlElementAttribute(System.Type type) { }
public string DataType { get { return default(string); } set { } }
public string ElementName { get { return default(string); } set { } }
public System.Xml.Schema.XmlSchemaForm Form { get { return default(System.Xml.Schema.XmlSchemaForm); } set { } }
public bool IsNullable { get { return default(bool); } set { } }
public string Namespace { get { return default(string); } set { } }
public int Order { get { return default(int); } set { } }
public System.Type Type { get { return default(System.Type); } set { } }
}
public partial class XmlElementAttributes
{
public XmlElementAttributes() { }
public System.Xml.Serialization.XmlElementAttribute this[int index] { get { return default(System.Xml.Serialization.XmlElementAttribute); } set { } }
public int Add(System.Xml.Serialization.XmlElementAttribute attribute) { return default(int); }
public bool Contains(System.Xml.Serialization.XmlElementAttribute attribute) { return default(bool); }
public void CopyTo(System.Xml.Serialization.XmlElementAttribute[] array, int index) { }
public int IndexOf(System.Xml.Serialization.XmlElementAttribute attribute) { return default(int); }
public void Insert(int index, System.Xml.Serialization.XmlElementAttribute attribute) { }
public void Remove(System.Xml.Serialization.XmlElementAttribute attribute) { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(256))]
public partial class XmlEnumAttribute : System.Attribute
{
public XmlEnumAttribute() { }
public XmlEnumAttribute(string name) { }
public string Name { get { return default(string); } set { } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(10624))]
public partial class XmlIgnoreAttribute : System.Attribute
{
public XmlIgnoreAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(1100), AllowMultiple = true)]
public partial class XmlIncludeAttribute : System.Attribute
{
public XmlIncludeAttribute(System.Type type) { }
public System.Type Type { get { return default(System.Type); } set { } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(10624), AllowMultiple = false)]
public partial class XmlNamespaceDeclarationsAttribute : System.Attribute
{
public XmlNamespaceDeclarationsAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(9244))]
public partial class XmlRootAttribute : System.Attribute
{
public XmlRootAttribute() { }
public XmlRootAttribute(string elementName) { }
public string DataType { get { return default(string); } set { } }
public string ElementName { get { return default(string); } set { } }
public bool IsNullable { get { return default(bool); } set { } }
public string Namespace { get { return default(string); } set { } }
}
public partial class XmlSerializer
{
protected XmlSerializer() { }
public XmlSerializer(System.Type type) { }
public XmlSerializer(System.Type type, string defaultNamespace) { }
public XmlSerializer(System.Type type, System.Type[] extraTypes) { }
public XmlSerializer(System.Type type, System.Xml.Serialization.XmlAttributeOverrides overrides) { }
public XmlSerializer(System.Type type, System.Xml.Serialization.XmlAttributeOverrides overrides, System.Type[] extraTypes, System.Xml.Serialization.XmlRootAttribute root, string defaultNamespace) { }
public XmlSerializer(System.Type type, System.Xml.Serialization.XmlRootAttribute root) { }
public virtual bool CanDeserialize(System.Xml.XmlReader xmlReader) { return default(bool); }
public object Deserialize(System.IO.Stream stream) { return default(object); }
public object Deserialize(System.IO.TextReader textReader) { return default(object); }
public object Deserialize(System.Xml.XmlReader xmlReader) { return default(object); }
public static System.Xml.Serialization.XmlSerializer[] FromTypes(System.Type[] types) { return default(System.Xml.Serialization.XmlSerializer[]); }
public void Serialize(System.IO.Stream stream, object o) { }
public void Serialize(System.IO.Stream stream, object o, System.Xml.Serialization.XmlSerializerNamespaces namespaces) { }
public void Serialize(System.IO.TextWriter textWriter, object o) { }
public void Serialize(System.IO.TextWriter textWriter, object o, System.Xml.Serialization.XmlSerializerNamespaces namespaces) { }
public void Serialize(System.Xml.XmlWriter xmlWriter, object o) { }
public void Serialize(System.Xml.XmlWriter xmlWriter, object o, System.Xml.Serialization.XmlSerializerNamespaces namespaces) { }
}
public partial class XmlSerializerNamespaces
{
public XmlSerializerNamespaces() { }
public XmlSerializerNamespaces(System.Xml.Serialization.XmlSerializerNamespaces namespaces) { }
public XmlSerializerNamespaces(System.Xml.XmlQualifiedName[] namespaces) { }
public int Count { get { return default(int); } }
public void Add(string prefix, string ns) { }
public System.Xml.XmlQualifiedName[] ToArray() { return default(System.Xml.XmlQualifiedName[]); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(10624))]
public partial class XmlTextAttribute : System.Attribute
{
public XmlTextAttribute() { }
public XmlTextAttribute(System.Type type) { }
public string DataType { get { return default(string); } set { } }
public System.Type Type { get { return default(System.Type); } set { } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(1052))]
public partial class XmlTypeAttribute : System.Attribute
{
public XmlTypeAttribute() { }
public XmlTypeAttribute(string typeName) { }
public bool AnonymousType { get { return default(bool); } set { } }
public bool IncludeInSchema { get { return default(bool); } set { } }
public string Namespace { get { return default(string); } set { } }
public string TypeName { get { return default(string); } set { } }
}
public abstract partial class XmlMapping
{
internal XmlMapping() { }
public string ElementName { get { return default(string); } }
public string Namespace { get { return default(string); } }
public string XsdElementName { get { return default(string); } }
public void SetKey(string key) { }
}
[System.FlagsAttribute]
public enum XmlMappingAccess
{
None = 0,
Read = 1,
Write = 2,
}
public partial class XmlMemberMapping
{
internal XmlMemberMapping() { }
public bool Any { get { return default(bool); } }
public bool CheckSpecified { get { return default(bool); } }
public string ElementName { get { return default(string); } }
public string MemberName { get { return default(string); } }
public string Namespace { get { return default(string); } }
public string TypeFullName { get { return default(string); } }
public string TypeName { get { return default(string); } }
public string TypeNamespace { get { return default(string); } }
public string XsdElementName { get { return default(string); } }
}
public partial class XmlMembersMapping : System.Xml.Serialization.XmlMapping
{
internal XmlMembersMapping() { }
public int Count { get { return default(int); } }
public System.Xml.Serialization.XmlMemberMapping this[int index] { get { return default(System.Xml.Serialization.XmlMemberMapping); } }
public string TypeName { get { return default(string); } }
public string TypeNamespace { get { return default(string); } }
}
public partial class XmlReflectionImporter
{
public XmlReflectionImporter() { }
public XmlReflectionImporter(string defaultNamespace) { }
public XmlReflectionImporter(System.Xml.Serialization.XmlAttributeOverrides attributeOverrides) { }
public XmlReflectionImporter(System.Xml.Serialization.XmlAttributeOverrides attributeOverrides, string defaultNamespace) { }
public System.Xml.Serialization.XmlMembersMapping ImportMembersMapping(string elementName, string ns, System.Xml.Serialization.XmlReflectionMember[] members, bool hasWrapperElement) { return default(System.Xml.Serialization.XmlMembersMapping); }
public System.Xml.Serialization.XmlMembersMapping ImportMembersMapping(string elementName, string ns, System.Xml.Serialization.XmlReflectionMember[] members, bool hasWrapperElement, bool rpc) { return default(System.Xml.Serialization.XmlMembersMapping); }
public System.Xml.Serialization.XmlMembersMapping ImportMembersMapping(string elementName, string ns, System.Xml.Serialization.XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, bool openModel) { return default(System.Xml.Serialization.XmlMembersMapping); }
public System.Xml.Serialization.XmlMembersMapping ImportMembersMapping(string elementName, string ns, System.Xml.Serialization.XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, bool openModel, System.Xml.Serialization.XmlMappingAccess access) { return default(System.Xml.Serialization.XmlMembersMapping); }
public System.Xml.Serialization.XmlTypeMapping ImportTypeMapping(System.Type type) { return default(System.Xml.Serialization.XmlTypeMapping); }
public System.Xml.Serialization.XmlTypeMapping ImportTypeMapping(System.Type type, string defaultNamespace) { return default(System.Xml.Serialization.XmlTypeMapping); }
public System.Xml.Serialization.XmlTypeMapping ImportTypeMapping(System.Type type, System.Xml.Serialization.XmlRootAttribute root) { return default(System.Xml.Serialization.XmlTypeMapping); }
public System.Xml.Serialization.XmlTypeMapping ImportTypeMapping(System.Type type, System.Xml.Serialization.XmlRootAttribute root, string defaultNamespace) { return default(System.Xml.Serialization.XmlTypeMapping); }
public void IncludeType(System.Type type) { }
}
public partial class SoapAttributes
{
public SoapAttributes() { }
}
public partial class XmlReflectionMember
{
public XmlReflectionMember() { }
public bool IsReturnValue { get { return default(bool); } set { } }
public string MemberName { get { return default(string); } set { } }
public System.Type MemberType { get { return default(System.Type); } set { } }
public bool OverrideIsNullable { get { return default(bool); } set { } }
public System.Xml.Serialization.SoapAttributes SoapAttributes { get { return default(System.Xml.Serialization.SoapAttributes); } set { } }
public System.Xml.Serialization.XmlAttributes XmlAttributes { get { return default(System.Xml.Serialization.XmlAttributes); } set { } }
}
public delegate void XmlSerializationCollectionFixupCallback(object collection, object collectionItems);
public delegate void XmlSerializationFixupCallback(object fixup);
public abstract partial class XmlSerializationGeneratedCode
{
protected XmlSerializationGeneratedCode() { }
}
public delegate object XmlSerializationReadCallback();
[System.AttributeUsageAttribute((System.AttributeTargets)(1052))]
public sealed partial class XmlSerializerAssemblyAttribute : System.Attribute
{
public XmlSerializerAssemblyAttribute() { }
public XmlSerializerAssemblyAttribute(string assemblyName) { }
public XmlSerializerAssemblyAttribute(string assemblyName, string codeBase) { }
public string AssemblyName { get { return default(string); } set { } }
public string CodeBase { get { return default(string); } set { } }
}
public sealed partial class XmlSerializerVersionAttribute : System.Attribute
{
public XmlSerializerVersionAttribute() { }
public XmlSerializerVersionAttribute(System.Type type) { }
public string Namespace { get { return default(string); } set { } }
public string ParentAssemblyId { get { return default(string); } set { } }
public System.Type Type { get { return default(System.Type); } set { } }
public string Version { get { return default(string); } set { } }
}
public partial class XmlTypeMapping : System.Xml.Serialization.XmlMapping
{
internal XmlTypeMapping() { }
public string TypeFullName { get { return default(string); } }
public string TypeName { get { return default(string); } }
public string XsdTypeName { get { return default(string); } }
public string XsdTypeNamespace { get { return default(string); } }
}
public abstract partial class XmlSerializationWriter : System.Xml.Serialization.XmlSerializationGeneratedCode
{
protected XmlSerializationWriter() { }
protected bool EscapeName { get { return default(bool); } set { } }
protected System.Collections.ArrayList Namespaces { get { return default(System.Collections.ArrayList); } set { } }
protected System.Xml.XmlWriter Writer { get { return default(System.Xml.XmlWriter); } set { } }
protected void AddWriteCallback(System.Type type, string typeName, string typeNs, System.Xml.Serialization.XmlSerializationWriteCallback callback) { }
protected System.Exception CreateChoiceIdentifierValueException(string value, string identifier, string name, string ns) { return default(System.Exception); }
protected System.Exception CreateInvalidAnyTypeException(object o) { return default(System.Exception); }
protected System.Exception CreateInvalidAnyTypeException(System.Type type) { return default(System.Exception); }
protected System.Exception CreateInvalidChoiceIdentifierValueException(string type, string identifier) { return default(System.Exception); }
protected System.Exception CreateInvalidEnumValueException(object value, string typeName) { return default(System.Exception); }
protected System.Exception CreateMismatchChoiceException(string value, string elementName, string enumValue) { return default(System.Exception); }
protected System.Exception CreateUnknownAnyElementException(string name, string ns) { return default(System.Exception); }
protected System.Exception CreateUnknownTypeException(object o) { return default(System.Exception); }
protected System.Exception CreateUnknownTypeException(System.Type type) { return default(System.Exception); }
protected static byte[] FromByteArrayBase64(byte[] value) { return default(byte[]); }
protected static string FromByteArrayHex(byte[] value) { return default(string); }
protected static string FromChar(char value) { return default(string); }
protected static string FromDate(System.DateTime value) { return default(string); }
protected static string FromDateTime(System.DateTime value) { return default(string); }
protected static string FromEnum(long value, string[] values, long[] ids) { return default(string); }
protected static string FromEnum(long value, string[] values, long[] ids, string typeName) { return default(string); }
protected static string FromTime(System.DateTime value) { return default(string); }
protected static string FromXmlName(string name) { return default(string); }
protected static string FromXmlNCName(string ncName) { return default(string); }
protected static string FromXmlNmToken(string nmToken) { return default(string); }
protected static string FromXmlNmTokens(string nmTokens) { return default(string); }
protected string FromXmlQualifiedName(System.Xml.XmlQualifiedName xmlQualifiedName) { return default(string); }
protected string FromXmlQualifiedName(System.Xml.XmlQualifiedName xmlQualifiedName, bool ignoreEmpty) { return default(string); }
protected abstract void InitCallbacks();
protected static System.Reflection.Assembly ResolveDynamicAssembly(string assemblyFullName) { return default(System.Reflection.Assembly); }
protected void TopLevelElement() { }
protected void WriteAttribute(string localName, byte[] value) { }
protected void WriteAttribute(string localName, string value) { }
protected void WriteAttribute(string localName, string ns, byte[] value) { }
protected void WriteAttribute(string localName, string ns, string value) { }
protected void WriteAttribute(string prefix, string localName, string ns, string value) { }
protected void WriteElementEncoded(System.Xml.XmlNode node, string name, string ns, bool isNullable, bool any) { }
protected void WriteElementLiteral(System.Xml.XmlNode node, string name, string ns, bool isNullable, bool any) { }
protected void WriteElementQualifiedName(string localName, string ns, System.Xml.XmlQualifiedName value) { }
protected void WriteElementQualifiedName(string localName, string ns, System.Xml.XmlQualifiedName value, System.Xml.XmlQualifiedName xsiType) { }
protected void WriteElementQualifiedName(string localName, System.Xml.XmlQualifiedName value) { }
protected void WriteElementQualifiedName(string localName, System.Xml.XmlQualifiedName value, System.Xml.XmlQualifiedName xsiType) { }
protected void WriteElementString(string localName, string value) { }
protected void WriteElementString(string localName, string ns, string value) { }
protected void WriteElementString(string localName, string ns, string value, System.Xml.XmlQualifiedName xsiType) { }
protected void WriteElementString(string localName, string value, System.Xml.XmlQualifiedName xsiType) { }
protected void WriteElementStringRaw(string localName, byte[] value) { }
protected void WriteElementStringRaw(string localName, byte[] value, System.Xml.XmlQualifiedName xsiType) { }
protected void WriteElementStringRaw(string localName, string value) { }
protected void WriteElementStringRaw(string localName, string ns, byte[] value) { }
protected void WriteElementStringRaw(string localName, string ns, byte[] value, System.Xml.XmlQualifiedName xsiType) { }
protected void WriteElementStringRaw(string localName, string ns, string value) { }
protected void WriteElementStringRaw(string localName, string ns, string value, System.Xml.XmlQualifiedName xsiType) { }
protected void WriteElementStringRaw(string localName, string value, System.Xml.XmlQualifiedName xsiType) { }
protected void WriteEmptyTag(string name) { }
protected void WriteEmptyTag(string name, string ns) { }
protected void WriteEndElement() { }
protected void WriteEndElement(object o) { }
protected void WriteId(object o) { }
protected void WriteNamespaceDeclarations(System.Xml.Serialization.XmlSerializerNamespaces xmlns) { }
protected void WriteNullableQualifiedNameEncoded(string name, string ns, System.Xml.XmlQualifiedName value, System.Xml.XmlQualifiedName xsiType) { }
protected void WriteNullableQualifiedNameLiteral(string name, string ns, System.Xml.XmlQualifiedName value) { }
protected void WriteNullableStringEncoded(string name, string ns, string value, System.Xml.XmlQualifiedName xsiType) { }
protected void WriteNullableStringEncodedRaw(string name, string ns, byte[] value, System.Xml.XmlQualifiedName xsiType) { }
protected void WriteNullableStringEncodedRaw(string name, string ns, string value, System.Xml.XmlQualifiedName xsiType) { }
protected void WriteNullableStringLiteral(string name, string ns, string value) { }
protected void WriteNullableStringLiteralRaw(string name, string ns, byte[] value) { }
protected void WriteNullableStringLiteralRaw(string name, string ns, string value) { }
protected void WriteNullTagEncoded(string name) { }
protected void WriteNullTagEncoded(string name, string ns) { }
protected void WriteNullTagLiteral(string name) { }
protected void WriteNullTagLiteral(string name, string ns) { }
protected void WritePotentiallyReferencingElement(string n, string ns, object o) { }
protected void WritePotentiallyReferencingElement(string n, string ns, object o, System.Type ambientType) { }
protected void WritePotentiallyReferencingElement(string n, string ns, object o, System.Type ambientType, bool suppressReference) { }
protected void WritePotentiallyReferencingElement(string n, string ns, object o, System.Type ambientType, bool suppressReference, bool isNullable) { }
protected void WriteReferencedElements() { }
protected void WriteReferencingElement(string n, string ns, object o) { }
protected void WriteReferencingElement(string n, string ns, object o, bool isNullable) { }
protected void WriteRpcResult(string name, string ns) { }
protected void WriteSerializable(System.Xml.Serialization.IXmlSerializable serializable, string name, string ns, bool isNullable) { }
protected void WriteSerializable(System.Xml.Serialization.IXmlSerializable serializable, string name, string ns, bool isNullable, bool wrapped) { }
protected void WriteStartDocument() { }
protected void WriteStartElement(string name) { }
protected void WriteStartElement(string name, string ns) { }
protected void WriteStartElement(string name, string ns, bool writePrefixed) { }
protected void WriteStartElement(string name, string ns, object o) { }
protected void WriteStartElement(string name, string ns, object o, bool writePrefixed) { }
protected void WriteStartElement(string name, string ns, object o, bool writePrefixed, System.Xml.Serialization.XmlSerializerNamespaces xmlns) { }
protected void WriteTypedPrimitive(string name, string ns, object o, bool xsiType) { }
protected void WriteValue(byte[] value) { }
protected void WriteValue(string value) { }
protected void WriteXmlAttribute(System.Xml.XmlNode node) { }
protected void WriteXmlAttribute(System.Xml.XmlNode node, object container) { }
protected void WriteXsiType(string name, string ns) { }
}
public delegate void XmlSerializationWriteCallback(object o);
public abstract partial class XmlSerializerImplementation
{
protected XmlSerializerImplementation() { }
public virtual System.Xml.Serialization.XmlSerializationReader Reader { get { return default(System.Xml.Serialization.XmlSerializationReader); } }
public virtual System.Collections.Hashtable ReadMethods { get { return default(System.Collections.Hashtable); } }
public virtual System.Collections.Hashtable TypedSerializers { get { return default(System.Collections.Hashtable); } }
public virtual System.Collections.Hashtable WriteMethods { get { return default(System.Collections.Hashtable); } }
public virtual System.Xml.Serialization.XmlSerializationWriter Writer { get { return default(System.Xml.Serialization.XmlSerializationWriter); } }
public virtual bool CanSerialize(System.Type type) { return default(bool); }
public virtual System.Xml.Serialization.XmlSerializer GetSerializer(System.Type type) { return default(System.Xml.Serialization.XmlSerializer); }
}
public abstract partial class XmlSerializationReader : System.Xml.Serialization.XmlSerializationGeneratedCode
{
protected XmlSerializationReader() { }
protected bool DecodeName { get { return default(bool); } set { } }
protected System.Xml.XmlDocument Document { get { return default(System.Xml.XmlDocument); } }
protected bool IsReturnValue { get { return default(bool); } set { } }
protected System.Xml.XmlReader Reader { get { return default(System.Xml.XmlReader); } }
protected int ReaderCount { get { return default(int); } }
protected void AddFixup(System.Xml.Serialization.XmlSerializationReader.CollectionFixup fixup) { }
protected void AddFixup(System.Xml.Serialization.XmlSerializationReader.Fixup fixup) { }
protected void AddReadCallback(string name, string ns, System.Type type, System.Xml.Serialization.XmlSerializationReadCallback read) { }
protected void AddTarget(string id, object o) { }
protected void CheckReaderCount(ref int whileIterations, ref int readerCount) { }
protected string CollapseWhitespace(string value) { return default(string); }
protected System.Exception CreateAbstractTypeException(string name, string ns) { return default(System.Exception); }
protected System.Exception CreateBadDerivationException(string xsdDerived, string nsDerived, string xsdBase, string nsBase, string clrDerived, string clrBase) { return default(System.Exception); }
protected System.Exception CreateCtorHasSecurityException(string typeName) { return default(System.Exception); }
protected System.Exception CreateInaccessibleConstructorException(string typeName) { return default(System.Exception); }
protected System.Exception CreateInvalidCastException(System.Type type, object value) { return default(System.Exception); }
protected System.Exception CreateInvalidCastException(System.Type type, object value, string id) { return default(System.Exception); }
protected System.Exception CreateMissingIXmlSerializableType(string name, string ns, string clrType) { return default(System.Exception); }
protected System.Exception CreateReadOnlyCollectionException(string name) { return default(System.Exception); }
protected System.Exception CreateUnknownConstantException(string value, System.Type enumType) { return default(System.Exception); }
protected System.Exception CreateUnknownNodeException() { return default(System.Exception); }
protected System.Exception CreateUnknownTypeException(System.Xml.XmlQualifiedName type) { return default(System.Exception); }
protected System.Array EnsureArrayIndex(System.Array a, int index, System.Type elementType) { return default(System.Array); }
protected void FixupArrayRefs(object fixup) { }
protected int GetArrayLength(string name, string ns) { return default(int); }
protected bool GetNullAttr() { return default(bool); }
protected object GetTarget(string id) { return default(object); }
protected System.Xml.XmlQualifiedName GetXsiType() { return default(System.Xml.XmlQualifiedName); }
protected abstract void InitCallbacks();
protected abstract void InitIDs();
protected bool IsXmlnsAttribute(string name) { return default(bool); }
protected void ParseWsdlArrayType(System.Xml.XmlAttribute attr) { }
protected System.Xml.XmlQualifiedName ReadElementQualifiedName() { return default(System.Xml.XmlQualifiedName); }
protected void ReadEndElement() { }
protected bool ReadNull() { return default(bool); }
protected System.Xml.XmlQualifiedName ReadNullableQualifiedName() { return default(System.Xml.XmlQualifiedName); }
protected string ReadNullableString() { return default(string); }
protected bool ReadReference(out string fixupReference) { fixupReference = default(string); return default(bool); }
protected object ReadReferencedElement() { return default(object); }
protected object ReadReferencedElement(string name, string ns) { return default(object); }
protected void ReadReferencedElements() { }
protected object ReadReferencingElement(string name, string ns, bool elementCanBeType, out string fixupReference) { fixupReference = default(string); return default(object); }
protected object ReadReferencingElement(string name, string ns, out string fixupReference) { fixupReference = default(string); return default(object); }
protected object ReadReferencingElement(out string fixupReference) { fixupReference = default(string); return default(object); }
protected System.Xml.Serialization.IXmlSerializable ReadSerializable(System.Xml.Serialization.IXmlSerializable serializable) { return default(System.Xml.Serialization.IXmlSerializable); }
protected string ReadString(string value) { return default(string); }
protected string ReadString(string value, bool trim) { return default(string); }
protected object ReadTypedNull(System.Xml.XmlQualifiedName type) { return default(object); }
protected object ReadTypedPrimitive(System.Xml.XmlQualifiedName type) { return default(object); }
protected System.Xml.XmlDocument ReadXmlDocument(bool wrapped) { return default(System.Xml.XmlDocument); }
protected System.Xml.XmlNode ReadXmlNode(bool wrapped) { return default(System.Xml.XmlNode); }
protected void Referenced(object o) { }
protected static System.Reflection.Assembly ResolveDynamicAssembly(string assemblyFullName) { return default(System.Reflection.Assembly); }
protected System.Array ShrinkArray(System.Array a, int length, System.Type elementType, bool isNullable) { return default(System.Array); }
protected byte[] ToByteArrayBase64(bool isNull) { return default(byte[]); }
protected static byte[] ToByteArrayBase64(string value) { return default(byte[]); }
protected byte[] ToByteArrayHex(bool isNull) { return default(byte[]); }
protected static byte[] ToByteArrayHex(string value) { return default(byte[]); }
protected static char ToChar(string value) { return default(char); }
protected static System.DateTime ToDate(string value) { return default(System.DateTime); }
protected static System.DateTime ToDateTime(string value) { return default(System.DateTime); }
protected static long ToEnum(string value, System.Collections.Hashtable h, string typeName) { return default(long); }
protected static System.DateTime ToTime(string value) { return default(System.DateTime); }
protected static string ToXmlName(string value) { return default(string); }
protected static string ToXmlNCName(string value) { return default(string); }
protected static string ToXmlNmToken(string value) { return default(string); }
protected static string ToXmlNmTokens(string value) { return default(string); }
protected System.Xml.XmlQualifiedName ToXmlQualifiedName(string value) { return default(System.Xml.XmlQualifiedName); }
protected void UnknownAttribute(object o, System.Xml.XmlAttribute attr) { }
protected void UnknownAttribute(object o, System.Xml.XmlAttribute attr, string qnames) { }
protected void UnknownElement(object o, System.Xml.XmlElement elem) { }
protected void UnknownElement(object o, System.Xml.XmlElement elem, string qnames) { }
protected void UnknownNode(object o) { }
protected void UnknownNode(object o, string qnames) { }
protected void UnreferencedObject(string id, object o) { }
protected partial class CollectionFixup
{
public CollectionFixup(object collection, System.Xml.Serialization.XmlSerializationCollectionFixupCallback callback, object collectionItems) { }
public System.Xml.Serialization.XmlSerializationCollectionFixupCallback Callback { get { return default(System.Xml.Serialization.XmlSerializationCollectionFixupCallback); } }
public object Collection { get { return default(object); } }
public object CollectionItems { get { return default(object); } }
}
protected partial class Fixup
{
public Fixup(object o, System.Xml.Serialization.XmlSerializationFixupCallback callback, int count) { }
public Fixup(object o, System.Xml.Serialization.XmlSerializationFixupCallback callback, string[] ids) { }
public System.Xml.Serialization.XmlSerializationFixupCallback Callback { get { return default(System.Xml.Serialization.XmlSerializationFixupCallback); } }
public string[] Ids { get { return default(string[]); } }
public object Source { get { return default(object); } set { } }
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.LayoutRenderers
{
using System;
using Xunit;
public class ExceptionDataLayoutRendererTests : NLogTestBase
{
[Fact]
public void ExceptionWithDataItemIsLoggedTest()
{
const string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
<nlog>
<targets>
<target name='debug' type='Debug' layout='${exceptiondata:" + exceptionDataKey + @"}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug' />
</rules>
</nlog>").LogFactory;
Exception ex = new ArgumentException(exceptionMessage);
ex.Data.Add(exceptionDataKey, exceptionDataValue);
logFactory.GetCurrentClassLogger().Error(ex, "msg");
logFactory.AssertDebugLastMessage("debug", exceptionDataValue);
}
[Fact]
public void ExceptionWithOutDataIsNotLoggedTest()
{
const string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
<nlog>
<targets>
<target name='debug' type='Debug' layout='${exceptiondata:" + exceptionDataKey + @"}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug' />
</rules>
</nlog>").LogFactory;
Exception ex = new ArgumentException(exceptionMessage);
logFactory.GetCurrentClassLogger().Error(ex, "msg");
logFactory.AssertDebugLastMessage("");
}
[Fact]
public void ExceptionUsingSpecifiedParamLogsProperlyTest()
{
const string exceptionMessage = "I don't like nullref exception!";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
<nlog>
<targets>
<target name='debug' type='Debug' layout='${exceptiondata:item=" + exceptionDataKey + @"}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug' />
</rules>
</nlog>").LogFactory;
Exception ex = new ArgumentException(exceptionMessage);
ex.Data.Add(exceptionDataKey, exceptionDataValue);
logFactory.GetCurrentClassLogger().Error(ex);
logFactory.AssertDebugLastMessage(exceptionDataValue);
}
[Fact]
public void BadDataForItemResultsInEmptyValueTest()
{
const string exceptionMessage = "I don't like nullref exception!";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
<nlog>
<targets>
<target name='debug' type='Debug' layout='${exceptiondata:item=@}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug' />
</rules>
</nlog>").LogFactory;
Exception ex = new ArgumentException(exceptionMessage);
ex.Data.Add(exceptionDataKey, exceptionDataValue);
logFactory.GetCurrentClassLogger().Error(ex);
logFactory.AssertDebugLastMessage("");
}
[Fact]
public void NoDatkeyTest()
{
const string exceptionMessage = "I don't like nullref exception!";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
<nlog>
<targets>
<target name='debug' type='Debug' layout='${exceptiondata:}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug' />
</rules>
</nlog>").LogFactory;
Exception ex = new ArgumentException(exceptionMessage);
ex.Data.Add(exceptionDataKey, exceptionDataValue);
logFactory.GetCurrentClassLogger().Error(ex);
logFactory.AssertDebugLastMessage("");
}
[Fact]
public void NoDatkeyUingParamTest()
{
const string exceptionMessage = "I don't like nullref exception!";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
<nlog>
<targets>
<target name='debug' type='Debug' layout='${exceptiondata:item=}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug' />
</rules>
</nlog>").LogFactory;
Exception ex = new ArgumentException(exceptionMessage);
ex.Data.Add(exceptionDataKey, exceptionDataValue);
logFactory.GetCurrentClassLogger().Error(ex);
logFactory.AssertDebugLastMessage("");
}
[Fact]
public void BaseExceptionFlippedTest()
{
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
<nlog>
<targets>
<target name='debug' type='Debug' layout='${exceptiondata:item=" + exceptionDataKey + @":BaseException=true}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug' />
</rules>
</nlog>").LogFactory;
Exception exceptionToTest;
try
{
try
{
try
{
var except = new ArgumentException("Inner Exception");
except.Data[exceptionDataKey] = exceptionDataValue;
throw except;
}
catch (Exception exception)
{
throw new System.ArgumentException("Wrapper1", exception);
}
}
catch (Exception exception)
{
throw new ApplicationException("Wrapper2", exception);
}
}
catch (Exception ex)
{
exceptionToTest = ex;
}
logFactory.GetCurrentClassLogger().Fatal(exceptionToTest, "msg");
logFactory.AssertDebugLastMessage(exceptionDataValue);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Android.Animation;
using Android.Views.Animations;
using Android.Graphics;
using Android.Graphics.Drawables;
// Flyout menu source from https://github.com/garuma/FlyOutMenu
namespace CCadmin
{
public class FlyOutContainer : FrameLayout
{
bool opened;
int contentOffsetX;
ValueAnimator animator;
ITimeInterpolator interpolator = new SmoothInterpolator ();
VelocityTracker velocityTracker;
bool stateBeforeTracking;
bool isTracking;
bool preTracking;
int startX = -1, startY = -1;
const int BezelArea = 30; //dip
const int MaxOverlayAlpha = 170;
const float ParallaxSpeedRatio = 0.25f;
int touchSlop;
int pagingTouchSlop;
int minFlingVelocity;
int maxFlingVelocity;
GradientDrawable shadowDrawable;
Paint overlayPaint;
public FlyOutContainer (Context context) :
base (context)
{
Initialize ();
}
public FlyOutContainer (Context context, IAttributeSet attrs) :
base (context, attrs)
{
Initialize ();
}
public FlyOutContainer (Context context, IAttributeSet attrs, int defStyle) :
base (context, attrs, defStyle)
{
Initialize ();
}
void Initialize ()
{
var config = ViewConfiguration.Get (Context);
this.touchSlop = config.ScaledTouchSlop;
this.pagingTouchSlop = config.ScaledPagingTouchSlop;
this.minFlingVelocity = config.ScaledMinimumFlingVelocity;
this.maxFlingVelocity = config.ScaledMaximumFlingVelocity;
const int BaseShadowColor = 0;
var shadowColors = new[] {
Color.Argb (0x90, BaseShadowColor, BaseShadowColor, BaseShadowColor).ToArgb (),
Color.Argb (0, BaseShadowColor, BaseShadowColor, BaseShadowColor).ToArgb ()
};
this.shadowDrawable = new GradientDrawable (GradientDrawable.Orientation.RightLeft,
shadowColors);
this.overlayPaint = new Paint {
Color = Color.Black,
AntiAlias = true
};
}
View ContentView {
get {
return FindViewById (Resource.Id.contentContainerFrameLayout);
}
}
View MenuView {
get {
return FindViewById (Resource.Id.dashboardContainerLinearLayout);
}
}
int MaxOffset {
get {
return MenuView.Width;
}
}
public bool Opened {
get {
return opened;
}
set {
SetOpened (value, animated: false);
}
}
public bool AnimatedOpened {
get {
return opened;
}
set {
SetOpened (value, animated: true);
}
}
public void SetOpened (bool opened, bool animated = true)
{
this.opened = opened;
if (!animated)
SetNewOffset (opened ? MaxOffset : 0);
else {
if (animator != null) {
animator.Cancel ();
animator = null;
}
animator = ValueAnimator.OfInt (contentOffsetX, opened ? MaxOffset : 0);
animator.SetInterpolator (interpolator);
animator.SetDuration (Context.Resources.GetInteger (Android.Resource.Integer.ConfigMediumAnimTime));
animator.Update += (sender, e) => SetNewOffset ((int)e.Animation.AnimatedValue);
animator.AnimationEnd += (sender, e) => { animator.RemoveAllListeners (); animator = null; };
animator.Start ();
}
}
void SetNewOffset (int newOffset)
{
var oldOffset = contentOffsetX;
contentOffsetX = Math.Min (Math.Max (0, newOffset), MaxOffset);
ContentView.OffsetLeftAndRight (contentOffsetX - oldOffset);
if (opened && contentOffsetX == 0)
opened = false;
else if (!opened && contentOffsetX == MaxOffset)
opened = true;
UpdateParallax ();
Invalidate ();
}
void UpdateParallax ()
{
var openness = ((float)(MaxOffset - contentOffsetX)) / MaxOffset;
MenuView.OffsetLeftAndRight ((int)(-openness * MaxOffset * ParallaxSpeedRatio) - MenuView.Left);
}
public override bool OnInterceptTouchEvent (MotionEvent ev)
{
// Only accept single touch
if (ev.PointerCount != 1)
return false;
return CaptureMovementCheck (ev);
}
public override bool OnTouchEvent (MotionEvent e)
{
if (e.Action == MotionEventActions.Down) {
CaptureMovementCheck (e);
return true;
}
if (!isTracking && !CaptureMovementCheck (e))
return true;
if (e.Action != MotionEventActions.Move || MoveDirectionTest (e))
velocityTracker.AddMovement (e);
if (e.Action == MotionEventActions.Move) {
var x = e.HistorySize > 0 ? e.GetHistoricalX (0) : e.GetX ();
var traveledDistance = (int)Math.Round (Math.Abs (x - (startX)));
SetNewOffset (stateBeforeTracking ?
MaxOffset - Math.Min (MaxOffset, traveledDistance)
: Math.Max (0, traveledDistance));
} else if (e.Action == MotionEventActions.Up
&& stateBeforeTracking == opened) {
velocityTracker.ComputeCurrentVelocity (1000, maxFlingVelocity);
if (Math.Abs (velocityTracker.XVelocity) > minFlingVelocity)
SetOpened (!opened);
else if (!opened && contentOffsetX > MaxOffset / 2)
SetOpened (true);
else if (opened && contentOffsetX < MaxOffset / 2)
SetOpened (false);
else
SetOpened (opened);
preTracking = isTracking = false;
}
return true;
}
bool CaptureMovementCheck (MotionEvent ev)
{
if (ev.Action == MotionEventActions.Down) {
startX = (int)ev.GetX ();
startY = (int)ev.GetY ();
// Only work if the initial touch was in the start strip when the menu is closed
// When the menu is opened, anywhere will do
if (!opened && (startX > Context.ToPixels (30)))
return false;
velocityTracker = VelocityTracker.Obtain ();
velocityTracker.AddMovement (ev);
preTracking = true;
stateBeforeTracking = opened;
return false;
}
if (ev.Action == MotionEventActions.Up)
preTracking = isTracking = false;
if (!preTracking)
return false;
velocityTracker.AddMovement (ev);
if (ev.Action == MotionEventActions.Move) {
// Check we are going in the right direction, if not cancel the current gesture
if (!MoveDirectionTest (ev)) {
preTracking = false;
return false;
}
// If the current gesture has not gone long enough don't intercept it just yet
var distance = Math.Sqrt (Math.Pow (ev.GetX () - startX, 2) + Math.Pow (ev.GetY () - startY, 2));
if (distance < pagingTouchSlop)
return false;
}
startX = (int)ev.GetX ();
startY = (int)ev.GetY ();
isTracking = true;
return true;
}
// Check that movement is in a common vertical area and that we are going in the right direction
bool MoveDirectionTest (MotionEvent e)
{
return (stateBeforeTracking ? e.GetX () <= startX : e.GetX () >= startX)
&& Math.Abs (e.GetY () - startY) < touchSlop;
}
protected override void DispatchDraw (Android.Graphics.Canvas canvas)
{
base.DispatchDraw (canvas);
if (opened || isTracking || animator != null) {
// Draw inset shadow on the menu
canvas.Save ();
shadowDrawable.SetBounds (0, 0, Context.ToPixels (8), Height);
canvas.Translate (ContentView.Left - shadowDrawable.Bounds.Width (), 0);
shadowDrawable.Draw (canvas);
canvas.Restore ();
if (contentOffsetX != 0) {
// Cover the area with a black overlay to display openess graphically
var openness = ((float)(MaxOffset - contentOffsetX)) / MaxOffset;
overlayPaint.Alpha = Math.Max (0, (int)(MaxOverlayAlpha * openness));
if (overlayPaint.Alpha > 0)
canvas.DrawRect (0, 0, ContentView.Left, Height, overlayPaint);
}
}
}
class SmoothInterpolator : Java.Lang.Object, ITimeInterpolator
{
public float GetInterpolation (float input)
{
return (float)Math.Pow (input - 1, 5) + 1;
}
}
}
static class DensityExtensions
{
static readonly DisplayMetrics displayMetrics = new DisplayMetrics ();
public static int ToPixels (this Context ctx, int dp)
{
var wm = ctx.GetSystemService (Context.WindowService).JavaCast<IWindowManager> ();
wm.DefaultDisplay.GetMetrics (displayMetrics);
var density = displayMetrics.Density;
return (int)(dp * density + 0.5f);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: imageProc.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 ImageProc {
/// <summary>Holder for reflection information generated from imageProc.proto</summary>
public static partial class ImageProcReflection {
#region Descriptor
/// <summary>File descriptor for imageProc.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ImageProcReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cg9pbWFnZVByb2MucHJvdG8SCWltYWdlUHJvYyJTChJFbmhhbmNlbWVudFJl",
"cXVlc3QSDQoFd2lkdGgYASABKAUSDgoGaGVpZ2h0GAIgASgFEg8KB2NoYW5u",
"ZWwYAyABKAUSDQoFaW1hZ2UYBCABKAwiYQoQRW5oYW5jZW1lbnRSZXBseRIO",
"CgZyZXN1bHQYASABKAUSDQoFd2lkdGgYAiABKAUSDgoGaGVpZ2h0GAMgASgF",
"Eg8KB2NoYW5uZWwYBCABKAUSDQoFaW1hZ2UYBSABKAwyWAoJSW1hZ2VQcm9j",
"EksKC0VuaGFuY2VtZW50Eh0uaW1hZ2VQcm9jLkVuaGFuY2VtZW50UmVxdWVz",
"dBobLmltYWdlUHJvYy5FbmhhbmNlbWVudFJlcGx5IgBiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::ImageProc.EnhancementRequest), global::ImageProc.EnhancementRequest.Parser, new[]{ "Width", "Height", "Channel", "Image" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::ImageProc.EnhancementReply), global::ImageProc.EnhancementReply.Parser, new[]{ "Result", "Width", "Height", "Channel", "Image" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class EnhancementRequest : pb::IMessage<EnhancementRequest> {
private static readonly pb::MessageParser<EnhancementRequest> _parser = new pb::MessageParser<EnhancementRequest>(() => new EnhancementRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<EnhancementRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::ImageProc.ImageProcReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EnhancementRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EnhancementRequest(EnhancementRequest other) : this() {
width_ = other.width_;
height_ = other.height_;
channel_ = other.channel_;
image_ = other.image_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EnhancementRequest Clone() {
return new EnhancementRequest(this);
}
/// <summary>Field number for the "width" field.</summary>
public const int WidthFieldNumber = 1;
private int width_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Width {
get { return width_; }
set {
width_ = value;
}
}
/// <summary>Field number for the "height" field.</summary>
public const int HeightFieldNumber = 2;
private int height_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Height {
get { return height_; }
set {
height_ = value;
}
}
/// <summary>Field number for the "channel" field.</summary>
public const int ChannelFieldNumber = 3;
private int channel_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Channel {
get { return channel_; }
set {
channel_ = value;
}
}
/// <summary>Field number for the "image" field.</summary>
public const int ImageFieldNumber = 4;
private pb::ByteString image_ = pb::ByteString.Empty;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString Image {
get { return image_; }
set {
image_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as EnhancementRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(EnhancementRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Width != other.Width) return false;
if (Height != other.Height) return false;
if (Channel != other.Channel) return false;
if (Image != other.Image) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Width != 0) hash ^= Width.GetHashCode();
if (Height != 0) hash ^= Height.GetHashCode();
if (Channel != 0) hash ^= Channel.GetHashCode();
if (Image.Length != 0) hash ^= Image.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 (Width != 0) {
output.WriteRawTag(8);
output.WriteInt32(Width);
}
if (Height != 0) {
output.WriteRawTag(16);
output.WriteInt32(Height);
}
if (Channel != 0) {
output.WriteRawTag(24);
output.WriteInt32(Channel);
}
if (Image.Length != 0) {
output.WriteRawTag(34);
output.WriteBytes(Image);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Width != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Width);
}
if (Height != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Height);
}
if (Channel != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Channel);
}
if (Image.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Image);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(EnhancementRequest other) {
if (other == null) {
return;
}
if (other.Width != 0) {
Width = other.Width;
}
if (other.Height != 0) {
Height = other.Height;
}
if (other.Channel != 0) {
Channel = other.Channel;
}
if (other.Image.Length != 0) {
Image = other.Image;
}
}
[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: {
Width = input.ReadInt32();
break;
}
case 16: {
Height = input.ReadInt32();
break;
}
case 24: {
Channel = input.ReadInt32();
break;
}
case 34: {
Image = input.ReadBytes();
break;
}
}
}
}
}
public sealed partial class EnhancementReply : pb::IMessage<EnhancementReply> {
private static readonly pb::MessageParser<EnhancementReply> _parser = new pb::MessageParser<EnhancementReply>(() => new EnhancementReply());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<EnhancementReply> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::ImageProc.ImageProcReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EnhancementReply() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EnhancementReply(EnhancementReply other) : this() {
result_ = other.result_;
width_ = other.width_;
height_ = other.height_;
channel_ = other.channel_;
image_ = other.image_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EnhancementReply Clone() {
return new EnhancementReply(this);
}
/// <summary>Field number for the "result" field.</summary>
public const int ResultFieldNumber = 1;
private int result_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Result {
get { return result_; }
set {
result_ = value;
}
}
/// <summary>Field number for the "width" field.</summary>
public const int WidthFieldNumber = 2;
private int width_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Width {
get { return width_; }
set {
width_ = value;
}
}
/// <summary>Field number for the "height" field.</summary>
public const int HeightFieldNumber = 3;
private int height_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Height {
get { return height_; }
set {
height_ = value;
}
}
/// <summary>Field number for the "channel" field.</summary>
public const int ChannelFieldNumber = 4;
private int channel_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Channel {
get { return channel_; }
set {
channel_ = value;
}
}
/// <summary>Field number for the "image" field.</summary>
public const int ImageFieldNumber = 5;
private pb::ByteString image_ = pb::ByteString.Empty;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString Image {
get { return image_; }
set {
image_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as EnhancementReply);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(EnhancementReply other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Result != other.Result) return false;
if (Width != other.Width) return false;
if (Height != other.Height) return false;
if (Channel != other.Channel) return false;
if (Image != other.Image) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Result != 0) hash ^= Result.GetHashCode();
if (Width != 0) hash ^= Width.GetHashCode();
if (Height != 0) hash ^= Height.GetHashCode();
if (Channel != 0) hash ^= Channel.GetHashCode();
if (Image.Length != 0) hash ^= Image.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 (Result != 0) {
output.WriteRawTag(8);
output.WriteInt32(Result);
}
if (Width != 0) {
output.WriteRawTag(16);
output.WriteInt32(Width);
}
if (Height != 0) {
output.WriteRawTag(24);
output.WriteInt32(Height);
}
if (Channel != 0) {
output.WriteRawTag(32);
output.WriteInt32(Channel);
}
if (Image.Length != 0) {
output.WriteRawTag(42);
output.WriteBytes(Image);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Result != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Result);
}
if (Width != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Width);
}
if (Height != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Height);
}
if (Channel != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Channel);
}
if (Image.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Image);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(EnhancementReply other) {
if (other == null) {
return;
}
if (other.Result != 0) {
Result = other.Result;
}
if (other.Width != 0) {
Width = other.Width;
}
if (other.Height != 0) {
Height = other.Height;
}
if (other.Channel != 0) {
Channel = other.Channel;
}
if (other.Image.Length != 0) {
Image = other.Image;
}
}
[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: {
Result = input.ReadInt32();
break;
}
case 16: {
Width = input.ReadInt32();
break;
}
case 24: {
Height = input.ReadInt32();
break;
}
case 32: {
Channel = input.ReadInt32();
break;
}
case 42: {
Image = input.ReadBytes();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using Exceptionless.Core.Models;
using Exceptionless.Core.Models.Data;
using Foundatio.Elasticsearch.Configuration;
using Nest;
namespace Exceptionless.Core.Repositories.Configuration {
public class EventIndex : ITemplatedElasticIndex {
public int Version => 1;
public static string Alias => Settings.Current.AppScopePrefix + "events";
public string AliasName => Alias;
public string VersionedName => String.Concat(AliasName, "-v", Version);
public IDictionary<Type, IndexType> GetIndexTypes() {
return new Dictionary<Type, IndexType> {
{ typeof(PersistentEvent), new IndexType { Name = "events" } }
};
}
public CreateIndexDescriptor CreateIndex(CreateIndexDescriptor idx) {
throw new NotImplementedException();
}
public PutTemplateDescriptor CreateTemplate(PutTemplateDescriptor template) {
return template
.Template(VersionedName + "-*")
.Settings(s => s.Add("analysis", BuildAnalysisSettings()))
.AddMapping<PersistentEvent>(map => map
.Dynamic(DynamicMappingOption.Ignore)
.DynamicTemplates(dt => dt.Add(t => t.Name("idx_reference").Match("*-r").Mapping(m => m.Generic(f => f.Type("string").Index("not_analyzed")))))
.IncludeInAll(false)
.DisableSizeField(false)
.Transform(t => t.Script(FLATTEN_ERRORS_SCRIPT).Language(ScriptLang.Groovy))
.AllField(i => i.IndexAnalyzer("standardplus").SearchAnalyzer("whitespace_lower"))
.Properties(p => p
.Date(f => f.Name(e => e.CreatedUtc).IndexName(Fields.PersistentEvent.CreatedUtc))
.String(f => f.Name(e => e.Id).IndexName(Fields.PersistentEvent.Id).Index(FieldIndexOption.NotAnalyzed).IncludeInAll())
.String(f => f.Name(e => e.OrganizationId).IndexName("organization").Index(FieldIndexOption.NotAnalyzed))
.String(f => f.Name(e => e.ProjectId).IndexName("project").Index(FieldIndexOption.NotAnalyzed))
.String(f => f.Name(e => e.StackId).IndexName("stack").Index(FieldIndexOption.NotAnalyzed))
.String(f => f.Name(e => e.ReferenceId).IndexName("reference").Index(FieldIndexOption.NotAnalyzed))
.String(f => f.Name(e => e.Type).IndexName(Fields.PersistentEvent.Type).Index(FieldIndexOption.NotAnalyzed))
.String(f => f.Name(e => e.Source).IndexName("source").Index(FieldIndexOption.Analyzed).IncludeInAll())
.Date(f => f.Name(e => e.Date).IndexName(Fields.PersistentEvent.Date))
.String(f => f.Name(e => e.Message).IndexName("message").Index(FieldIndexOption.Analyzed).IncludeInAll())
.String(f => f.Name(e => e.Tags).IndexName("tag").Index(FieldIndexOption.Analyzed).IncludeInAll().Boost(1.2))
.GeoPoint(f => f.Name(e => e.Geo).IndexLatLon())
.Number(f => f.Name(e => e.Value).IndexName("value"))
.Boolean(f => f.Name(e => e.IsFirstOccurrence).IndexName("first"))
.Boolean(f => f.Name(e => e.IsFixed).IndexName("fixed"))
.Boolean(f => f.Name(e => e.IsHidden).IndexName("hidden"))
.Object<object>(f => f.Name("idx").Dynamic())
.Object<DataDictionary>(f => f.Name(e => e.Data).Path("just_name").Properties(p2 => p2
.String(f2 => f2.Name(Event.KnownDataKeys.Version).IndexName("version").Index(FieldIndexOption.Analyzed).IndexAnalyzer("version_index").SearchAnalyzer("version_search"))
.String(f2 => f2.Name(Event.KnownDataKeys.Level).IndexName("level").Index(FieldIndexOption.Analyzed))
.String(f2 => f2.Name(Event.KnownDataKeys.SubmissionMethod).IndexName("submission").Index(FieldIndexOption.Analyzed))
.Object<Location>(f2 => f2.Name(Event.KnownDataKeys.Location).Path("just_name").Properties(p3 => p3
.String(f3 => f3.Name(r => r.Country).IndexName(Fields.PersistentEvent.LocationCountry).Index(FieldIndexOption.NotAnalyzed))
.String(f3 => f3.Name(r => r.Country).IndexName(Fields.PersistentEvent.LocationLevel1).Index(FieldIndexOption.NotAnalyzed))
.String(f3 => f3.Name(r => r.Country).IndexName(Fields.PersistentEvent.LocationLevel2).Index(FieldIndexOption.NotAnalyzed))
.String(f3 => f3.Name(r => r.Country).IndexName(Fields.PersistentEvent.LocationLocality).Index(FieldIndexOption.NotAnalyzed))))
.Object<RequestInfo>(f2 => f2.Name(Event.KnownDataKeys.RequestInfo).Path("just_name").Properties(p3 => p3
.String(f3 => f3.Name(r => r.ClientIpAddress).IndexName(Fields.PersistentEvent.IpAddress).Index(FieldIndexOption.Analyzed).IncludeInAll().Analyzer("comma_whitespace"))
.String(f3 => f3.Name(r => r.UserAgent).IndexName("useragent").Index(FieldIndexOption.Analyzed))
.String(f3 => f3.Name(r => r.Path).IndexName("path").Index(FieldIndexOption.Analyzed).IncludeInAll())
.Object<DataDictionary>(f3 => f3.Name(e => e.Data).Path("just_name").Properties(p4 => p4
.String(f4 => f4.Name(RequestInfo.KnownDataKeys.Browser).IndexName("browser").Index(FieldIndexOption.Analyzed)
.Fields(fields => fields.String(ss => ss.Name("browser.raw").Index(FieldIndexOption.NotAnalyzed))))
.String(f4 => f4.Name(RequestInfo.KnownDataKeys.BrowserVersion).IndexName("browser.version").Index(FieldIndexOption.Analyzed)
.Fields(fields => fields.String(ss => ss.Name("browser.version.raw").Index(FieldIndexOption.NotAnalyzed))))
.String(f4 => f4.Name(RequestInfo.KnownDataKeys.BrowserMajorVersion).IndexName("browser.major").Index(FieldIndexOption.NotAnalyzed))
.String(f4 => f4.Name(RequestInfo.KnownDataKeys.Device).IndexName("device").Index(FieldIndexOption.Analyzed)
.Fields(fields => fields.String(ss => ss.Name("device.raw").Index(FieldIndexOption.NotAnalyzed))))
.String(f4 => f4.Name(RequestInfo.KnownDataKeys.OS).IndexName("os").Index(FieldIndexOption.Analyzed)
.Fields(fields => fields.String(ss => ss.Name("os.raw").Index(FieldIndexOption.NotAnalyzed))))
.String(f4 => f4.Name(RequestInfo.KnownDataKeys.OSVersion).IndexName("os.version").Index(FieldIndexOption.Analyzed)
.Fields(fields => fields.String(ss => ss.Name("os.version.raw").Index(FieldIndexOption.NotAnalyzed))))
.String(f4 => f4.Name(RequestInfo.KnownDataKeys.OSMajorVersion).IndexName("os.major").Index(FieldIndexOption.NotAnalyzed))
.Boolean(f4 => f4.Name(RequestInfo.KnownDataKeys.IsBot).IndexName("bot"))))))
.Object<Error>(f2 => f2.Name(Event.KnownDataKeys.Error).Path("just_name").Properties(p3 => p3
.String(f3 => f3.Name("all_codes").IndexName("error.code").Index(FieldIndexOption.NotAnalyzed).Analyzer("whitespace").IncludeInAll().Boost(1.1))
.String(f3 => f3.Name("all_messages").IndexName("error.message").Index(FieldIndexOption.Analyzed).IncludeInAll())
.Object<DataDictionary>(f4 => f4.Name(e => e.Data).Path("just_name").Properties(p4 => p4
.Object<object>(f5 => f5.Name(Error.KnownDataKeys.TargetInfo).Path("just_name").Properties(p5 => p5
.String(f6 => f6.Name("ExceptionType").IndexName("error.targettype").Index(FieldIndexOption.Analyzed).IndexAnalyzer("typename").SearchAnalyzer("whitespace_lower").IncludeInAll().Boost(1.2)
.Fields(fields => fields.String(ss => ss.Name("error.targettype.raw").Index(FieldIndexOption.NotAnalyzed))))
.String(f6 => f6.Name("Method").IndexName("error.targetmethod").Index(FieldIndexOption.Analyzed).IndexAnalyzer("typename").SearchAnalyzer("whitespace_lower").IncludeInAll().Boost(1.2))))))
.String(f3 => f3.Name("all_types").IndexName("error.type").Index(FieldIndexOption.Analyzed).IndexAnalyzer("typename").SearchAnalyzer("whitespace_lower").IncludeInAll().Boost(1.1))))
.Object<SimpleError>(f2 => f2.Name(Event.KnownDataKeys.SimpleError).Path("just_name").Properties(p3 => p3
.String(f3 => f3.Name("all_messages").IndexName("error.message").Index(FieldIndexOption.Analyzed).IncludeInAll())
.Object<DataDictionary>(f4 => f4.Name(e => e.Data).Path("just_name").Properties(p4 => p4
.Object<object>(f5 => f5.Name(Error.KnownDataKeys.TargetInfo).Path("just_name").Properties(p5 => p5
.String(f6 => f6.Name("ExceptionType").IndexName("error.targettype").Index(FieldIndexOption.Analyzed).IndexAnalyzer("typename").SearchAnalyzer("whitespace_lower").IncludeInAll().Boost(1.2))))))
.String(f3 => f3.Name("all_types").IndexName("error.type").Index(FieldIndexOption.Analyzed).IndexAnalyzer("typename").SearchAnalyzer("whitespace_lower").IncludeInAll().Boost(1.1))))
.Object<EnvironmentInfo>(f2 => f2.Name(Event.KnownDataKeys.EnvironmentInfo).Path("just_name").Properties(p3 => p3
.String(f3 => f3.Name(r => r.IpAddress).IndexName(Fields.PersistentEvent.IpAddress).Index(FieldIndexOption.Analyzed).IncludeInAll().Analyzer("comma_whitespace"))
.String(f3 => f3.Name(r => r.MachineName).IndexName("machine").Index(FieldIndexOption.Analyzed).IncludeInAll().Boost(1.1))
.String(f3 => f3.Name(r => r.OSName).IndexName("os").Index(FieldIndexOption.Analyzed))
.String(f3 => f3.Name(r => r.Architecture).IndexName("architecture").Index(FieldIndexOption.NotAnalyzed))))
.Object<UserDescription>(f2 => f2.Name(Event.KnownDataKeys.UserDescription).Path("just_name").Properties(p3 => p3
.String(f3 => f3.Name(r => r.Description).IndexName("user.description").Index(FieldIndexOption.Analyzed).IncludeInAll())
.String(f3 => f3.Name(r => r.EmailAddress).IndexName(Fields.PersistentEvent.UserEmail).Index(FieldIndexOption.Analyzed).IndexAnalyzer("email").SearchAnalyzer("simple").IncludeInAll().Boost(1.1))))
.Object<UserInfo>(f2 => f2.Name(Event.KnownDataKeys.UserInfo).Path("just_name").Properties(p3 => p3
.String(f3 => f3.Name(r => r.Identity).IndexName(Fields.PersistentEvent.User).Index(FieldIndexOption.Analyzed).IndexAnalyzer("email").SearchAnalyzer("whitespace_lower").IncludeInAll().Boost(1.1)
.Fields(fields => fields.String(ss => ss.Name(Fields.PersistentEvent.UserRaw).Index(FieldIndexOption.NotAnalyzed))))
.String(f3 => f3.Name(r => r.Name).IndexName(Fields.PersistentEvent.UserName).Index(FieldIndexOption.Analyzed).IncludeInAll())))))
));
}
private object BuildAnalysisSettings() {
return new {
filter = new {
email = new {
type = "pattern_capture",
patterns = new[] {
@"(\w+)",
@"(\p{L}+)",
@"(\d+)",
@"(.+)@",
@"@(.+)"
}
},
version = new {
type = "pattern_capture",
patterns = new[] {
@"^(\d+)\.",
@"^(\d+\.\d+)",
@"^(\d+\.\d+\.\d+)"
}
},
version_pad1 = new {
type = "pattern_replace",
pattern = @"(\.|^)(\d{1})(?=\.|$)",
replacement = @"$10000$2"
},
version_pad2 = new {
type = "pattern_replace",
pattern = @"(\.|^)(\d{2})(?=\.|$)",
replacement = @"$1000$2"
},
version_pad3 = new {
type = "pattern_replace",
pattern = @"(\.|^)(\d{3})(?=\.|$)",
replacement = @"$100$2"
},
version_pad4 = new {
type = "pattern_replace",
pattern = @"(\.|^)(\d{4})(?=\.|$)",
replacement = @"$10$2"
},
typename = new {
type = "pattern_capture",
patterns = new[] {
@"\.(\w+)"
}
}
},
analyzer = new {
comma_whitespace = new {
type = "pattern",
pattern = @"[,\s]+"
},
email = new {
type = "custom",
tokenizer = "keyword",
filter = new[] {
"email",
"lowercase",
"unique"
}
},
version_index = new {
type = "custom",
tokenizer = "whitespace",
filter = new[] {
"version_pad1",
"version_pad2",
"version_pad3",
"version_pad4",
"version",
"lowercase",
"unique"
}
},
version_search = new {
type = "custom",
tokenizer = "whitespace",
filter = new[] {
"version_pad1",
"version_pad2",
"version_pad3",
"version_pad4",
"lowercase"
}
},
whitespace_lower = new {
type = "custom",
tokenizer = "whitespace",
filter = new[] { "lowercase" }
},
typename = new {
type = "custom",
tokenizer = "whitespace",
filter = new[] {
"typename",
"lowercase",
"unique"
}
},
standardplus = new {
type = "custom",
tokenizer = "whitespace",
filter = new[] {
"standard",
"typename",
"lowercase",
"stop",
"unique"
}
}
}
};
}
const string FLATTEN_ERRORS_SCRIPT = @"
if (!ctx._source.containsKey('data') || !(ctx._source.data.containsKey('@error') || ctx._source.data.containsKey('@simple_error')))
return
def types = []
def messages = []
def codes = []
def err = ctx._source.data.containsKey('@error') ? ctx._source.data['@error'] : ctx._source.data['@simple_error']
def curr = err
while (curr != null) {
if (curr.containsKey('type'))
types.add(curr.type)
if (curr.containsKey('message'))
messages.add(curr.message)
if (curr.containsKey('code'))
codes.add(curr.code)
curr = curr.inner
}
err['all_types'] = types.join(' ')
err['all_messages'] = messages.join(' ')
err['all_codes'] = codes.join(' ')";
public class Fields {
public class PersistentEvent {
public const string CreatedUtc = "created";
public const string Id = "id";
public const string Date = "date";
public const string Type = "type";
public const string IpAddress = "ip";
public const string User = "user";
public const string UserRaw = "user.raw";
public const string UserName = "user.name";
public const string UserEmail = "user.email";
public const string LocationCountry = "country";
public const string LocationLevel1 = "level1";
public const string LocationLevel2 = "level2";
public const string LocationLocality = "locality";
}
}
}
}
| |
// 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.ComponentModel;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.WebSockets.Client.Tests
{
public sealed class ArraySegmentSendReceiveTest : SendReceiveTest
{
public ArraySegmentSendReceiveTest(ITestOutputHelper output) : base(output) { }
protected override Task<WebSocketReceiveResult> ReceiveAsync(WebSocket ws, ArraySegment<byte> arraySegment, CancellationToken cancellationToken) =>
ws.ReceiveAsync(arraySegment, cancellationToken);
protected override Task SendAsync(WebSocket ws, ArraySegment<byte> arraySegment, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) =>
ws.SendAsync(arraySegment, messageType, endOfMessage, cancellationToken);
}
public abstract class SendReceiveTest : ClientWebSocketTestBase
{
protected abstract Task SendAsync(WebSocket ws, ArraySegment<byte> arraySegment, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken);
protected abstract Task<WebSocketReceiveResult> ReceiveAsync(WebSocket ws, ArraySegment<byte> arraySegment, CancellationToken cancellationToken);
public static bool PartialMessagesSupported => PlatformDetection.ClientWebSocketPartialMessagesSupported;
public SendReceiveTest(ITestOutputHelper output) : base(output) { }
[OuterLoop] // TODO: Issue #11345
[ActiveIssue(9296)]
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task SendReceive_PartialMessageDueToSmallReceiveBuffer_Success(Uri server)
{
var sendBuffer = new byte[1024];
var sendSegment = new ArraySegment<byte>(sendBuffer);
var receiveBuffer = new byte[1024];
var receiveSegment = new ArraySegment<byte>(receiveBuffer);
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds);
// The server will read buffers and aggregate it up to 64KB before echoing back a complete message.
// But since this test uses a receive buffer that is small, we will get back partial message fragments
// as we read them until we read the complete message payload.
for (int i = 0; i < 63; i++)
{
await SendAsync(cws, sendSegment, WebSocketMessageType.Binary, false, ctsDefault.Token);
}
await SendAsync(cws, sendSegment, WebSocketMessageType.Binary, true, ctsDefault.Token);
WebSocketReceiveResult recvResult = await ReceiveAsync(cws, receiveSegment, ctsDefault.Token);
Assert.Equal(false, recvResult.EndOfMessage);
while (recvResult.EndOfMessage == false)
{
recvResult = await ReceiveAsync(cws, receiveSegment, ctsDefault.Token);
}
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "PartialMessageDueToSmallReceiveBufferTest", ctsDefault.Token);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported), nameof(PartialMessagesSupported)), MemberData(nameof(EchoServers))]
public async Task SendReceive_PartialMessageBeforeCompleteMessageArrives_Success(Uri server)
{
var rand = new Random();
var sendBuffer = new byte[ushort.MaxValue + 1];
rand.NextBytes(sendBuffer);
var sendSegment = new ArraySegment<byte>(sendBuffer);
// Ask the remote server to echo back received messages without ever signaling "end of message".
var ub = new UriBuilder(server);
ub.Query = "replyWithPartialMessages";
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(ub.Uri, TimeOutMilliseconds, _output))
{
var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds);
// Send data to the server; the server will reply back with one or more partial messages. We should be
// able to consume that data as it arrives, without having to wait for "end of message" to be signaled.
await SendAsync(cws, sendSegment, WebSocketMessageType.Binary, true, ctsDefault.Token);
int totalBytesReceived = 0;
var receiveBuffer = new byte[sendBuffer.Length];
while (totalBytesReceived < receiveBuffer.Length)
{
WebSocketReceiveResult recvResult = await ReceiveAsync(
cws,
new ArraySegment<byte>(receiveBuffer, totalBytesReceived, receiveBuffer.Length - totalBytesReceived),
ctsDefault.Token);
Assert.Equal(false, recvResult.EndOfMessage);
Assert.InRange(recvResult.Count, 0, receiveBuffer.Length - totalBytesReceived);
totalBytesReceived += recvResult.Count;
}
Assert.Equal(receiveBuffer.Length, totalBytesReceived);
Assert.Equal<byte>(sendBuffer, receiveBuffer);
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "PartialMessageBeforeCompleteMessageArrives", ctsDefault.Token);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task SendAsync_SendCloseMessageType_ThrowsArgumentExceptionWithMessage(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
string expectedInnerMessage = ResourceHelper.GetExceptionMessage(
"net_WebSockets_Argument_InvalidMessageType",
"Close",
"SendAsync",
"Binary",
"Text",
"CloseOutputAsync");
var expectedException = new ArgumentException(expectedInnerMessage, "messageType");
string expectedMessage = expectedException.Message;
AssertExtensions.Throws<ArgumentException>("messageType", () =>
{
Task t = SendAsync(cws, new ArraySegment<byte>(), WebSocketMessageType.Close, true, cts.Token);
});
Assert.Equal(WebSocketState.Open, cws.State);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task SendAsync_MultipleOutstandingSendOperations_Throws(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
Task[] tasks = new Task[10];
try
{
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = SendAsync(
cws,
WebSocketData.GetBufferFromText("hello"),
WebSocketMessageType.Text,
true,
cts.Token);
}
Task.WaitAll(tasks);
Assert.Equal(WebSocketState.Open, cws.State);
}
catch (AggregateException ag)
{
foreach (var ex in ag.InnerExceptions)
{
if (ex is InvalidOperationException)
{
Assert.Equal(
ResourceHelper.GetExceptionMessage(
"net_Websockets_AlreadyOneOutstandingOperation",
"SendAsync"),
ex.Message);
Assert.Equal(WebSocketState.Aborted, cws.State);
}
else if (ex is WebSocketException)
{
// Multiple cases.
Assert.Equal(WebSocketState.Aborted, cws.State);
WebSocketError errCode = (ex as WebSocketException).WebSocketErrorCode;
Assert.True(
(errCode == WebSocketError.InvalidState) || (errCode == WebSocketError.Success),
"WebSocketErrorCode");
}
else
{
Assert.IsAssignableFrom<OperationCanceledException>(ex);
}
}
}
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task ReceiveAsync_MultipleOutstandingReceiveOperations_Throws(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
Task[] tasks = new Task[2];
await SendAsync(
cws,
WebSocketData.GetBufferFromText(".delay5sec"),
WebSocketMessageType.Text,
true,
cts.Token);
var recvBuffer = new byte[100];
var recvSegment = new ArraySegment<byte>(recvBuffer);
try
{
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = ReceiveAsync(cws, recvSegment, cts.Token);
}
Task.WaitAll(tasks);
Assert.Equal(WebSocketState.Open, cws.State);
}
catch (AggregateException ag)
{
foreach (var ex in ag.InnerExceptions)
{
if (ex is InvalidOperationException)
{
Assert.Equal(
ResourceHelper.GetExceptionMessage(
"net_Websockets_AlreadyOneOutstandingOperation",
"ReceiveAsync"),
ex.Message);
Assert.Equal(WebSocketState.Aborted, cws.State);
}
else if (ex is WebSocketException)
{
// Multiple cases.
Assert.Equal(WebSocketState.Aborted, cws.State);
WebSocketError errCode = (ex as WebSocketException).WebSocketErrorCode;
Assert.True(
(errCode == WebSocketError.InvalidState) || (errCode == WebSocketError.Success),
"WebSocketErrorCode");
}
else if (ex is OperationCanceledException)
{
Assert.Equal(WebSocketState.Aborted, cws.State);
}
else
{
Assert.True(false, "Unexpected exception: " + ex.Message);
}
}
}
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task SendAsync_SendZeroLengthPayloadAsEndOfMessage_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
string message = "hello";
await SendAsync(
cws,
WebSocketData.GetBufferFromText(message),
WebSocketMessageType.Text,
false,
cts.Token);
Assert.Equal(WebSocketState.Open, cws.State);
await SendAsync(
cws,
new ArraySegment<byte>(new byte[0]),
WebSocketMessageType.Text,
true,
cts.Token);
Assert.Equal(WebSocketState.Open, cws.State);
var recvBuffer = new byte[100];
var receiveSegment = new ArraySegment<byte>(recvBuffer);
WebSocketReceiveResult recvRet = await ReceiveAsync(cws, receiveSegment, cts.Token);
Assert.Equal(WebSocketState.Open, cws.State);
Assert.Equal(message.Length, recvRet.Count);
Assert.Equal(WebSocketMessageType.Text, recvRet.MessageType);
Assert.Equal(true, recvRet.EndOfMessage);
Assert.Equal(null, recvRet.CloseStatus);
Assert.Equal(null, recvRet.CloseStatusDescription);
var recvSegment = new ArraySegment<byte>(receiveSegment.Array, receiveSegment.Offset, recvRet.Count);
Assert.Equal(message, WebSocketData.GetTextFromBuffer(recvSegment));
}
}
[ActiveIssue(23765)]
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task SendReceive_VaryingLengthBuffers_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var rand = new Random();
var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds);
// Values chosen close to boundaries in websockets message length handling as well
// as in vectors used in mask application.
foreach (int bufferSize in new int[] { 1, 3, 4, 5, 31, 32, 33, 125, 126, 127, 128, ushort.MaxValue - 1, ushort.MaxValue, ushort.MaxValue + 1, ushort.MaxValue * 2 })
{
byte[] sendBuffer = new byte[bufferSize];
rand.NextBytes(sendBuffer);
await SendAsync(cws, new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Binary, true, ctsDefault.Token);
byte[] receiveBuffer = new byte[bufferSize];
int totalReceived = 0;
while (true)
{
WebSocketReceiveResult recvResult = await ReceiveAsync(
cws,
new ArraySegment<byte>(receiveBuffer, totalReceived, receiveBuffer.Length - totalReceived),
ctsDefault.Token);
Assert.InRange(recvResult.Count, 0, receiveBuffer.Length - totalReceived);
totalReceived += recvResult.Count;
if (recvResult.EndOfMessage) break;
}
Assert.Equal(receiveBuffer.Length, totalReceived);
Assert.Equal<byte>(sendBuffer, receiveBuffer);
}
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "SendReceive_VaryingLengthBuffers_Success", ctsDefault.Token);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task SendReceive_Concurrent_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds);
byte[] receiveBuffer = new byte[10];
byte[] sendBuffer = new byte[10];
for (int i = 0; i < sendBuffer.Length; i++)
{
sendBuffer[i] = (byte)i;
}
for (int i = 0; i < sendBuffer.Length; i++)
{
Task<WebSocketReceiveResult> receive = ReceiveAsync(cws, new ArraySegment<byte>(receiveBuffer, receiveBuffer.Length - i - 1, 1), ctsDefault.Token);
Task send = SendAsync(cws, new ArraySegment<byte>(sendBuffer, i, 1), WebSocketMessageType.Binary, true, ctsDefault.Token);
await Task.WhenAll(receive, send);
Assert.Equal(1, receive.Result.Count);
}
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "SendReceive_VaryingLengthBuffers_Success", ctsDefault.Token);
Array.Reverse(receiveBuffer);
Assert.Equal<byte>(sendBuffer, receiveBuffer);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(WebSocketsSupported))]
public async Task SendReceive_ConnectionClosedPrematurely_ReceiveAsyncFailsAndWebSocketStateUpdated()
{
var options = new LoopbackServer.Options { WebSocketEndpoint = true };
Func<ClientWebSocket, Socket, Uri, Task> connectToServerThatAbortsConnection = async (clientSocket, server, url) =>
{
AutoResetEvent pendingReceiveAsyncPosted = new AutoResetEvent(false);
// Start listening for incoming connections on the server side.
Task<List<string>> acceptTask = LoopbackServer.AcceptSocketAsync(server, async (socket, stream, reader, writer) =>
{
// Complete the WebSocket upgrade. After this is done, the client-side ConnectAsync should complete.
Assert.True(await LoopbackServer.WebSocketHandshakeAsync(socket, reader, writer));
// Wait for client-side ConnectAsync to complete and for a pending ReceiveAsync to be posted.
pendingReceiveAsyncPosted.WaitOne(TimeOutMilliseconds);
// Close the underlying connection prematurely (without sending a WebSocket Close frame).
socket.Shutdown(SocketShutdown.Both);
socket.Close();
return null;
}, options);
// Initiate a connection attempt.
var cts = new CancellationTokenSource(TimeOutMilliseconds);
await clientSocket.ConnectAsync(url, cts.Token);
// Post a pending ReceiveAsync before the TCP connection is torn down.
var recvBuffer = new byte[100];
var recvSegment = new ArraySegment<byte>(recvBuffer);
Task pendingReceiveAsync = ReceiveAsync(clientSocket, recvSegment, cts.Token);
pendingReceiveAsyncPosted.Set();
// Wait for the server to close the underlying connection.
acceptTask.Wait(cts.Token);
// Validate I/O errors and socket state.
if (!PlatformDetection.IsWindows)
{
_output.WriteLine("[Non-Windows] ManagedWebSocket-based implementation.");
WebSocketException pendingReceiveException = await Assert.ThrowsAsync<WebSocketException>(() => pendingReceiveAsync);
Assert.Equal(WebSocketError.ConnectionClosedPrematurely, pendingReceiveException.WebSocketErrorCode);
WebSocketException newReceiveException =
await Assert.ThrowsAsync<WebSocketException>(() => ReceiveAsync(clientSocket, recvSegment, cts.Token));
Assert.Equal(WebSocketError.ConnectionClosedPrematurely, newReceiveException.WebSocketErrorCode);
Assert.Equal(WebSocketState.Open, clientSocket.State);
Assert.Null(clientSocket.CloseStatus);
}
else if (PlatformDetection.IsFullFramework)
{
_output.WriteLine("[Windows] ManagedWebSocket-based implementation.");
WebSocketException pendingReceiveException = await Assert.ThrowsAsync<WebSocketException>(() => pendingReceiveAsync);
Assert.Equal(WebSocketError.ConnectionClosedPrematurely, pendingReceiveException.WebSocketErrorCode);
WebSocketException newReceiveException =
await Assert.ThrowsAsync<WebSocketException>(() => ReceiveAsync(clientSocket, recvSegment, cts.Token));
Assert.Equal(WebSocketError.Success, newReceiveException.WebSocketErrorCode);
Assert.Equal(
ResourceHelper.GetExceptionMessage("net_WebSockets_InvalidState", "Aborted", "Open, CloseSent"),
newReceiveException.Message);
Assert.Equal(WebSocketState.Aborted, clientSocket.State);
Assert.Null(clientSocket.CloseStatus);
}
else if (PlatformDetection.IsUap)
{
_output.WriteLine("WinRTWebSocket-based implementation.");
const uint WININET_E_CONNECTION_ABORTED = 0x80072EFE;
WebSocketException pendingReceiveException = await Assert.ThrowsAsync<WebSocketException>(() => pendingReceiveAsync);
Assert.Equal(WebSocketError.ConnectionClosedPrematurely, pendingReceiveException.WebSocketErrorCode);
Assert.NotNull(pendingReceiveException.InnerException);
Assert.Equal(WININET_E_CONNECTION_ABORTED, (uint)pendingReceiveException.InnerException.HResult);
WebSocketException newReceiveException =
await Assert.ThrowsAsync<WebSocketException>(() => ReceiveAsync(clientSocket, recvSegment, cts.Token));
Assert.Equal(WebSocketError.Success, newReceiveException.WebSocketErrorCode);
Assert.Equal(
ResourceHelper.GetExceptionMessage("net_WebSockets_InvalidState", "Aborted", "Open, CloseSent"),
newReceiveException.Message);
Assert.Equal(WebSocketState.Aborted, clientSocket.State);
Assert.Null(clientSocket.CloseStatus);
}
else
{
_output.WriteLine("WinHttpWebSocket-based implementation.");
const uint WININET_E_CONNECTION_RESET = 0x80072eff;
Win32Exception pendingReceiveException = await Assert.ThrowsAnyAsync<Win32Exception>(() => pendingReceiveAsync);
Assert.Equal(WININET_E_CONNECTION_RESET, (uint)pendingReceiveException.HResult);
Win32Exception newReceiveException =
await Assert.ThrowsAnyAsync<Win32Exception>(() => ReceiveAsync(clientSocket, recvSegment, cts.Token));
Assert.Equal(WININET_E_CONNECTION_RESET, (uint)newReceiveException.HResult);
Assert.Equal(WebSocketState.Open, clientSocket.State);
Assert.Null(clientSocket.CloseStatus);
}
};
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (ClientWebSocket clientSocket = new ClientWebSocket())
{
await connectToServerThatAbortsConnection(clientSocket, server, url);
}
}, options);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Runtime.InteropServices.TCEAdapterGen {
using System.Runtime.InteropServices;
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections;
using System.Diagnostics.Contracts;
internal class EventSinkHelperWriter
{
public static readonly String GeneratedTypeNamePostfix = "_SinkHelper";
public EventSinkHelperWriter( ModuleBuilder OutputModule, Type InputType, Type EventItfType )
{
m_InputType = InputType;
m_OutputModule = OutputModule;
m_EventItfType = EventItfType;
}
public Type Perform()
{
// Create the output Type.
Type[] aInterfaces = new Type[1];
aInterfaces[0] = m_InputType;
String strFullName = null;
String strNameSpace = NameSpaceExtractor.ExtractNameSpace( m_EventItfType.FullName );
if (strNameSpace != "")
strFullName = strNameSpace + ".";
strFullName += m_InputType.Name + GeneratedTypeNamePostfix;
TypeBuilder OutputTypeBuilder = TCEAdapterGenerator.DefineUniqueType(
strFullName,
TypeAttributes.Sealed | TypeAttributes.Public,
null,
aInterfaces,
m_OutputModule
);
// Hide the _SinkProvider interface
TCEAdapterGenerator.SetHiddenAttribute(OutputTypeBuilder);
// Set the class interface to none.
TCEAdapterGenerator.SetClassInterfaceTypeToNone(OutputTypeBuilder);
// Retrieve the property methods on the input interface and give them a dummy implementation.
MethodInfo[] pMethods = TCEAdapterGenerator.GetPropertyMethods(m_InputType);
foreach (MethodInfo method in pMethods)
{
DefineBlankMethod(OutputTypeBuilder, method);
}
// Retrieve the non-property methods on the input interface.
MethodInfo[] aMethods = TCEAdapterGenerator.GetNonPropertyMethods(m_InputType);
// Allocate an array to contain the delegate fields.
FieldBuilder[] afbDelegates = new FieldBuilder[aMethods.Length];
// Process all the methods on the input interface.
for ( int cMethods = 0; cMethods < aMethods.Length; cMethods++ )
{
if ( m_InputType == aMethods[cMethods].DeclaringType )
{
// Retrieve the delegate type from the add_XXX method.
MethodInfo AddMeth = m_EventItfType.GetMethod( "add_" + aMethods[cMethods].Name );
ParameterInfo[] aParams = AddMeth.GetParameters();
Contract.Assert(aParams.Length == 1, "All event interface methods must take a single delegate derived type and have a void return type");
Type DelegateCls = aParams[0].ParameterType;
// Define the delegate instance field.
afbDelegates[cMethods] = OutputTypeBuilder.DefineField(
"m_" + aMethods[cMethods].Name + "Delegate",
DelegateCls,
FieldAttributes.Public
);
// Define the event method itself.
DefineEventMethod( OutputTypeBuilder, aMethods[cMethods], DelegateCls, afbDelegates[cMethods] );
}
}
// Create the cookie field.
FieldBuilder fbCookie = OutputTypeBuilder.DefineField(
"m_dwCookie",
typeof(Int32),
FieldAttributes.Public
);
// Define the constructor.
DefineConstructor( OutputTypeBuilder, fbCookie, afbDelegates );
return OutputTypeBuilder.CreateType();
}
private void DefineBlankMethod(TypeBuilder OutputTypeBuilder, MethodInfo Method)
{
ParameterInfo[] PIs = Method.GetParameters();
Type[] parameters = new Type[PIs.Length];
for (int i=0; i < PIs.Length; i++)
{
parameters[i] = PIs[i].ParameterType;
}
MethodBuilder Meth = OutputTypeBuilder.DefineMethod(Method.Name,
Method.Attributes & ~MethodAttributes.Abstract,
Method.CallingConvention,
Method.ReturnType,
parameters);
ILGenerator il = Meth.GetILGenerator();
AddReturn(Method.ReturnType, il, Meth);
il.Emit(OpCodes.Ret);
}
private void DefineEventMethod( TypeBuilder OutputTypeBuilder, MethodInfo Method, Type DelegateCls, FieldBuilder fbDelegate )
{
// Retrieve the method info for the invoke method on the delegate.
MethodInfo DelegateInvokeMethod = DelegateCls.GetMethod( "Invoke" );
Contract.Assert(DelegateInvokeMethod != null, "Unable to find method Delegate.Invoke()");
// Retrieve the return type.
Type ReturnType = Method.ReturnType;
// Define the actual event method.
ParameterInfo[] paramInfos = Method.GetParameters();
Type[] parameterTypes;
if (paramInfos != null)
{
parameterTypes = new Type[paramInfos.Length];
for (int i = 0; i < paramInfos.Length; i++)
{
parameterTypes[i] = paramInfos[i].ParameterType;
}
}
else
parameterTypes = null;
MethodAttributes attr = MethodAttributes.Public | MethodAttributes.Virtual;
MethodBuilder Meth = OutputTypeBuilder.DefineMethod( Method.Name,
attr,
CallingConventions.Standard,
ReturnType,
parameterTypes);
// We explicitly do not specify parameter name and attributes since this Type
// is not meant to be exposed to the user. It is only used internally to do the
// connection point to TCE mapping.
ILGenerator il = Meth.GetILGenerator();
// Create the exit branch.
Label ExitLabel = il.DefineLabel();
// Generate the code that verifies that the delegate is not null.
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldfld, fbDelegate );
il.Emit( OpCodes.Brfalse, ExitLabel );
// The delegate is not NULL so we need to invoke it.
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldfld, fbDelegate );
// Generate the code to load the arguments before we call invoke.
ParameterInfo[] aParams = Method.GetParameters();
for ( int cParams = 0; cParams < aParams.Length; cParams++ )
{
il.Emit( OpCodes.Ldarg, (short)(cParams + 1) );
}
// Generate a tail call to invoke. This will cause the callvirt to return
// directly to the caller of the current method instead of actually coming
// back to the current method and returning. This will cause the value returned
// from the call to the COM server to be returned to the caller of this method.
il.Emit( OpCodes.Callvirt, DelegateInvokeMethod );
il.Emit( OpCodes.Ret );
// This is the label that will be jumped to if no delegate is present.
il.MarkLabel( ExitLabel );
AddReturn(ReturnType, il, Meth);
il.Emit( OpCodes.Ret );
}
private void AddReturn(Type ReturnType, ILGenerator il, MethodBuilder Meth)
{
// Place a dummy return value on the stack before we return.
if ( ReturnType == typeof(void) )
{
// There is nothing to place on the stack.
}
else if ( ReturnType.IsPrimitive )
{
switch (System.Type.GetTypeCode(ReturnType))
{
case TypeCode.Boolean:
case TypeCode.Char:
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
il.Emit( OpCodes.Ldc_I4_0 );
break;
case TypeCode.Int64:
case TypeCode.UInt64:
il.Emit( OpCodes.Ldc_I4_0 );
il.Emit( OpCodes.Conv_I8 );
break;
case TypeCode.Single:
il.Emit( OpCodes.Ldc_R4, 0 );
break;
case TypeCode.Double:
il.Emit( OpCodes.Ldc_R4, 0 );
il.Emit( OpCodes.Conv_R8 );
break;
default:
// "TypeCode" does not include IntPtr, so special case it.
if ( ReturnType == typeof(IntPtr) )
il.Emit( OpCodes.Ldc_I4_0 );
else
Contract.Assert(false, "Unexpected type for Primitive type.");
break;
}
}
else if ( ReturnType.IsValueType )
{
// Allocate stack space for the return value type. Zero-init.
Meth.InitLocals = true;
LocalBuilder ltRetVal = il.DeclareLocal( ReturnType );
// Load the value class on the stack.
il.Emit( OpCodes.Ldloc_S, ltRetVal );
}
else
{
// The return type is a normal type.
il.Emit( OpCodes.Ldnull );
}
}
private void DefineConstructor( TypeBuilder OutputTypeBuilder, FieldBuilder fbCookie, FieldBuilder[] afbDelegates )
{
// Retrieve the constructor info for the base classe's constructor.
ConstructorInfo DefaultBaseClsCons = typeof(Object).GetConstructor(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, new Type[0], null );
Contract.Assert(DefaultBaseClsCons != null, "Unable to find the constructor for class " + m_InputType.Name);
// Define the default constructor.
MethodBuilder Cons = OutputTypeBuilder.DefineMethod( ".ctor",
MethodAttributes.Assembly | MethodAttributes.SpecialName,
CallingConventions.Standard,
null,
null);
ILGenerator il = Cons.GetILGenerator();
// Generate the code to call the constructor of the base class.
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Call, DefaultBaseClsCons );
// Generate the code to set the cookie field to 0.
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldc_I4, 0 );
il.Emit( OpCodes.Stfld, fbCookie );
// Generate the code to set all the delegates to NULL.
for ( int cDelegates = 0; cDelegates < afbDelegates.Length; cDelegates++ )
{
if (afbDelegates[cDelegates] != null)
{
il.Emit( OpCodes.Ldarg,(short)0 );
il.Emit( OpCodes.Ldnull );
il.Emit( OpCodes.Stfld, afbDelegates[cDelegates] );
}
}
// Emit the return opcode.
il.Emit( OpCodes.Ret );
}
private Type m_InputType;
private Type m_EventItfType;
private ModuleBuilder m_OutputModule;
}
}
| |
/*
* 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.
*/
// ReSharper disable once CheckNamespace
namespace Apache.Ignite.Platform.Model
{
using System;
/// <summary>
/// A class is a clone of Java class Address with the same namespace.
/// </summary>
public class Address
{
/** */
public string Zip { get; set; }
/** */
public string Addr { get; set; }
}
/// <summary>
/// A class is a clone of Java class Department with the same namespace.
/// </summary>
public class Department
{
/** */
public string Name { get; set; }
}
/// <summary>
/// A class is a clone of Java class Employee with the same namespace.
/// </summary>
public class Employee
{
/** */
public string Fio { get; set; }
/** */
public long Salary { get; set; }
}
/// <summary>
/// A class is a clone of Java class Employee with the same namespace.
/// </summary>
public class Key
{
public long Id { get; set; }
protected bool Equals(Key other)
{
return Id == other.Id;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Key) obj);
}
public override int GetHashCode()
{
// ReSharper disable once NonReadonlyMemberInGetHashCode
return Id.GetHashCode();
}
}
/// <summary>
/// A class is a clone of Java class Employee with the same namespace.
/// </summary>
public class Value
{
public string Val { get; set; }
}
/// <summary>
/// A class is a clone of Java class Account with the same namespace.
/// </summary>
public class Account
{
public String Id { get; set; }
public int Amount { get; set; }
protected bool Equals(Account other)
{
return Id == other.Id;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Account) obj);
}
public override int GetHashCode()
{
// ReSharper disable once NonReadonlyMemberInGetHashCode
return Id.GetHashCode();
}
}
/// <summary>
/// A enum is a clone of Java class User with the same namespace.
/// </summary>
// ReSharper disable once InconsistentNaming
public enum ACL
{
ALLOW, DENY
}
/// <summary>
/// A enum is a clone of Java class AccessLevel with the same namespace.
/// </summary>
public enum AccessLevel
{
USER, SUPER
}
/// <summary>
/// A class is a clone of Java class Role with the same namespace.
/// </summary>
public class Role
{
public String Name { get; set; }
/** Tests declaration as System.Enum. */
public Enum AccessLevel { get; set; }
}
/// <summary>
/// A class is a clone of Java class User with the same namespace.
/// </summary>
public class User
{
public int Id { get; set; }
public ACL Acl { get; set; }
public Role Role { get; set; }
}
/// <summary>
/// A class is a clone of Java class ParamValue with the same namespace.
/// </summary>
public class ParamValue
{
/** */
public int Id { get; set; }
/** */
public long Val { get; set; }
}
/// <summary>
/// A class is a clone of Java class Parameter with the same namespace.
/// </summary>
public class Parameter
{
/** */
public int Id { get; set; }
/** */
public ParamValue[] Values { get; set; }
}
/// <summary>
/// A class is a clone of Java class V1 with the same namespace.
/// </summary>
public class V1 { public String Name { get; set; } }
/// <summary>
/// A class is a clone of Java class V2 with the same namespace.
/// </summary>
public class V2 { public String Name { get; set; } }
/// <summary>
/// A class is a clone of Java class V3 with the same namespace.
/// </summary>
public class V3 { public String Name { get; set; } }
/// <summary>
/// A class is a clone of Java class V4 with the same namespace.
/// </summary>
public class V4 { public String Name { get; set; } }
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Platform;
using osu.Framework.Testing;
using osu.Game.Configuration;
using osu.Game.IO;
namespace osu.Game.Tests.NonVisual
{
[TestFixture]
public class CustomDataDirectoryTest : ImportTest
{
[Test]
public void TestDefaultDirectory()
{
using (var host = new CustomTestHeadlessGameHost())
{
try
{
string defaultStorageLocation = getDefaultLocationFor(nameof(TestDefaultDirectory));
var osu = LoadOsuIntoHost(host);
var storage = osu.Dependencies.Get<Storage>();
Assert.That(storage.GetFullPath("."), Is.EqualTo(defaultStorageLocation));
}
finally
{
host.Exit();
}
}
}
[Test]
public void TestCustomDirectory()
{
string customPath = prepareCustomPath();
using (var host = new CustomTestHeadlessGameHost())
{
using (var storageConfig = new StorageConfigManager(host.InitialStorage))
storageConfig.SetValue(StorageConfig.FullPath, customPath);
try
{
var osu = LoadOsuIntoHost(host);
// switch to DI'd storage
var storage = osu.Dependencies.Get<Storage>();
Assert.That(storage.GetFullPath("."), Is.EqualTo(customPath));
}
finally
{
host.Exit();
}
}
}
[Test]
public void TestSubDirectoryLookup()
{
string customPath = prepareCustomPath();
using (var host = new CustomTestHeadlessGameHost())
{
using (var storageConfig = new StorageConfigManager(host.InitialStorage))
storageConfig.SetValue(StorageConfig.FullPath, customPath);
try
{
var osu = LoadOsuIntoHost(host);
// switch to DI'd storage
var storage = osu.Dependencies.Get<Storage>();
string actualTestFile = Path.Combine(customPath, "rulesets", "test");
File.WriteAllText(actualTestFile, "test");
var rulesetStorage = storage.GetStorageForDirectory("rulesets");
var lookupPath = rulesetStorage.GetFiles(".").Single();
Assert.That(lookupPath, Is.EqualTo("test"));
}
finally
{
host.Exit();
}
}
}
[Test]
public void TestMigration()
{
string customPath = prepareCustomPath();
using (var host = new CustomTestHeadlessGameHost())
{
try
{
string defaultStorageLocation = getDefaultLocationFor(nameof(TestMigration));
var osu = LoadOsuIntoHost(host);
var storage = osu.Dependencies.Get<Storage>();
var osuStorage = storage as MigratableStorage;
// Store the current storage's path. We'll need to refer to this for assertions in the original directory after the migration completes.
string originalDirectory = storage.GetFullPath(".");
// ensure we perform a save
host.Dependencies.Get<FrameworkConfigManager>().Save();
// ensure we "use" cache
host.Storage.GetStorageForDirectory("cache");
// for testing nested files are not ignored (only top level)
host.Storage.GetStorageForDirectory("test-nested").GetStorageForDirectory("cache");
Assert.That(storage.GetFullPath("."), Is.EqualTo(defaultStorageLocation));
osu.Migrate(customPath);
Assert.That(storage.GetFullPath("."), Is.EqualTo(customPath));
// ensure cache was not moved
Assert.That(Directory.Exists(Path.Combine(originalDirectory, "cache")));
// ensure nested cache was moved
Assert.That(!Directory.Exists(Path.Combine(originalDirectory, "test-nested", "cache")));
Assert.That(storage.ExistsDirectory(Path.Combine("test-nested", "cache")));
Assert.That(osuStorage, Is.Not.Null);
foreach (var file in osuStorage.IgnoreFiles)
{
// avoid touching realm files which may be a pipe and break everything.
// this is also done locally inside OsuStorage via the IgnoreFiles list.
if (file.EndsWith(".ini", StringComparison.Ordinal))
Assert.That(File.Exists(Path.Combine(originalDirectory, file)));
Assert.That(storage.Exists(file), Is.False);
}
foreach (var dir in osuStorage.IgnoreDirectories)
{
Assert.That(Directory.Exists(Path.Combine(originalDirectory, dir)));
Assert.That(storage.ExistsDirectory(dir), Is.False);
}
Assert.That(new StreamReader(Path.Combine(originalDirectory, "storage.ini")).ReadToEnd().Contains($"FullPath = {customPath}"));
}
finally
{
host.Exit();
}
}
}
[Test]
public void TestMigrationBetweenTwoTargets()
{
string customPath = prepareCustomPath();
string customPath2 = prepareCustomPath("-2");
using (var host = new CustomTestHeadlessGameHost())
{
try
{
var osu = LoadOsuIntoHost(host);
const string database_filename = "client.db";
Assert.DoesNotThrow(() => osu.Migrate(customPath));
Assert.That(File.Exists(Path.Combine(customPath, database_filename)));
Assert.DoesNotThrow(() => osu.Migrate(customPath2));
Assert.That(File.Exists(Path.Combine(customPath2, database_filename)));
// some files may have been left behind for whatever reason, but that's not what we're testing here.
customPath = prepareCustomPath();
Assert.DoesNotThrow(() => osu.Migrate(customPath));
Assert.That(File.Exists(Path.Combine(customPath, database_filename)));
}
finally
{
host.Exit();
}
}
}
[Test]
public void TestMigrationToSameTargetFails()
{
string customPath = prepareCustomPath();
using (var host = new CustomTestHeadlessGameHost())
{
try
{
var osu = LoadOsuIntoHost(host);
Assert.DoesNotThrow(() => osu.Migrate(customPath));
Assert.Throws<ArgumentException>(() => osu.Migrate(customPath));
}
finally
{
host.Exit();
}
}
}
[Test]
public void TestMigrationToNestedTargetFails()
{
string customPath = prepareCustomPath();
using (var host = new CustomTestHeadlessGameHost())
{
try
{
var osu = LoadOsuIntoHost(host);
Assert.DoesNotThrow(() => osu.Migrate(customPath));
string subFolder = Path.Combine(customPath, "sub");
if (Directory.Exists(subFolder))
Directory.Delete(subFolder, true);
Directory.CreateDirectory(subFolder);
Assert.Throws<ArgumentException>(() => osu.Migrate(subFolder));
}
finally
{
host.Exit();
}
}
}
[Test]
public void TestMigrationToSeeminglyNestedTarget()
{
string customPath = prepareCustomPath();
using (var host = new CustomTestHeadlessGameHost())
{
try
{
var osu = LoadOsuIntoHost(host);
Assert.DoesNotThrow(() => osu.Migrate(customPath));
string seeminglySubFolder = customPath + "sub";
if (Directory.Exists(seeminglySubFolder))
Directory.Delete(seeminglySubFolder, true);
Directory.CreateDirectory(seeminglySubFolder);
osu.Migrate(seeminglySubFolder);
}
finally
{
host.Exit();
}
}
}
private static string getDefaultLocationFor(string testTypeName)
{
string path = Path.Combine(TestRunHeadlessGameHost.TemporaryTestDirectory, testTypeName);
if (Directory.Exists(path))
Directory.Delete(path, true);
return path;
}
private string prepareCustomPath(string suffix = "")
{
string path = Path.Combine(TestRunHeadlessGameHost.TemporaryTestDirectory, $"custom-path{suffix}");
if (Directory.Exists(path))
Directory.Delete(path, true);
return path;
}
public class CustomTestHeadlessGameHost : CleanRunHeadlessGameHost
{
public Storage InitialStorage { get; }
public CustomTestHeadlessGameHost([CallerMemberName] string callingMethodName = @"")
: base(callingMethodName: callingMethodName)
{
string defaultStorageLocation = getDefaultLocationFor(callingMethodName);
InitialStorage = new DesktopStorage(defaultStorageLocation, this);
InitialStorage.DeleteDirectory(string.Empty);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
try
{
// the storage may have changed from the initial location.
// this handles cleanup of the initial location.
InitialStorage.DeleteDirectory(string.Empty);
}
catch { }
}
}
}
}
| |
// 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.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Test.Common;
using System.Security.Authentication;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
using Xunit.NetCore.Extensions;
namespace System.Net.Security.Tests
{
public class KDCSetup : IDisposable
{
private const string Krb5ConfigFile = "/etc/krb5.conf";
private const string KDestroyCmd = "kdestroy";
private const string ScriptName = "setup-kdc.sh";
private const string ScriptUninstallArgs = "--uninstall --yes";
private const string ScriptInstallArgs = "--password {0} --yes";
private const int InstalledButUnconfiguredExitCode = 2;
private readonly bool _isKrbPreInstalled;
public readonly string password;
private const string NtlmUserFile = "NTLM_USER_FILE";
private readonly bool _successfulSetup = true;
public KDCSetup()
{
_isKrbPreInstalled = File.Exists(Krb5ConfigFile) &&
File.ReadAllText(Krb5ConfigFile).Contains(TestConfiguration.Realm);
if (!_isKrbPreInstalled)
{
password = Guid.NewGuid().ToString("N");
int exitCode = RunSetupScript(string.Format(ScriptInstallArgs, password));
if (exitCode != 0)
{
if (exitCode != InstalledButUnconfiguredExitCode)
{
Dispose();
}
_successfulSetup = false;
}
}
else
{
password = TestConfiguration.DefaultPassword;
}
}
public void Dispose()
{
if (!_isKrbPreInstalled)
{
RunSetupScript(ScriptUninstallArgs);
}
}
// checks for availability of Kerberos related infrastructure
// on the host. Returns true available, false otherwise
public bool CheckAndClearCredentials(ITestOutputHelper output)
{
if (!_successfulSetup)
{
return false;
}
// Clear the credentials
var startInfo = new ProcessStartInfo(KDestroyCmd);
startInfo.CreateNoWindow = true;
startInfo.Arguments = "-A";
using (Process clearCreds = Process.Start(startInfo))
{
clearCreds.WaitForExit();
output.WriteLine("kdestroy returned {0}", clearCreds.ExitCode);
return (clearCreds.ExitCode == 0);
}
}
public bool CheckAndInitializeNtlm(bool isKrbAvailable)
{
if (!_successfulSetup || !isKrbAvailable)
{
return false;
}
if (File.Exists(TestConfiguration.NtlmUserFilePath))
{
Environment.SetEnvironmentVariable(NtlmUserFile, TestConfiguration.NtlmUserFilePath);
return true;
}
return false;
}
private static int RunSetupScript(string args = null)
{
try
{
return AdminHelpers.RunAsSudo($"bash {ScriptName} {args}");
}
catch
{
// Could not find the file
return 1;
}
}
}
[Trait(XunitConstants.Category, XunitConstants.RequiresElevation)]
public class NegotiateStreamTest : IDisposable, IClassFixture<KDCSetup>
{
private readonly byte[] _firstMessage = Encoding.UTF8.GetBytes("Sample First Message");
private readonly byte[] _secondMessage = Encoding.UTF8.GetBytes("Sample Second Message");
private readonly bool _isKrbAvailable; // tests are no-op if kerberos is not available on the host machine
private readonly bool _isNtlmAvailable; // tests are no-op if ntlm is not available on the host machine
private readonly KDCSetup _fixture;
private readonly ITestOutputHelper _output;
private readonly string _emptyTarget = string.Empty;
private readonly string _testTarget = "TestTarget";
private static readonly string _ntlmPassword = TestConfiguration.NtlmPassword;
private void AssertClientPropertiesForTarget(NegotiateStream client, string target)
{
Assert.True(client.IsAuthenticated, "client.IsAuthenticated");
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.True(client.IsEncrypted, "client.IsEncrypted");
Assert.True(client.IsMutuallyAuthenticated, "client.IsMutuallyAuthenticated");
Assert.False(client.IsServer, "client.IsServer");
Assert.True(client.IsSigned, "client.IsSigned");
Assert.False(client.LeaveInnerStreamOpen, "client.LeaveInnerStreamOpen");
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("Kerberos", serverIdentity.AuthenticationType);
Assert.True(serverIdentity.IsAuthenticated, "serverIdentity.IsAuthenticated");
IdentityValidator.AssertHasName(serverIdentity, target);
}
public NegotiateStreamTest(KDCSetup fixture, ITestOutputHelper output)
{
_fixture = fixture;
_output = output;
_isKrbAvailable = _fixture.CheckAndClearCredentials(_output);
_isNtlmAvailable = _fixture.CheckAndInitializeNtlm(_isKrbAvailable);
}
[Fact, OuterLoop]
[PlatformSpecific(TestPlatforms.Linux)]
public async Task NegotiateStream_StreamToStream_KerberosAuthentication_Success()
{
if (!_isKrbAvailable)
{
_output.WriteLine("skipping NegotiateStream_StreamToStream_KerberosAuthentication_Success");
return;
}
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 UnixGssFakeNegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated, "client is not authenticated");
string user = string.Format("{0}@{1}", TestConfiguration.KerberosUser, TestConfiguration.Realm);
string target = string.Format("{0}@{1}", TestConfiguration.HostTarget, TestConfiguration.Realm);
NetworkCredential credential = new NetworkCredential(user, _fixture.password);
Task[] auth = new Task[] {
client.AuthenticateAsClientAsync(credential, target),
server.AuthenticateAsServerAsync()
};
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);
AssertClientPropertiesForTarget(client, target);
}
}
[Fact, OuterLoop]
[PlatformSpecific(TestPlatforms.Linux)]
public async Task NegotiateStream_StreamToStream_AuthToHttpTarget_Success()
{
if (!_isKrbAvailable)
{
_output.WriteLine("skipping NegotiateStream_StreamToStream_AuthToHttpTarget_Success");
return;
}
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 UnixGssFakeNegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
string user = string.Format("{0}@{1}", TestConfiguration.KerberosUser, TestConfiguration.Realm);
NetworkCredential credential = new NetworkCredential(user, _fixture.password);
Task[] auth = new Task[] {
client.AuthenticateAsClientAsync(credential, TestConfiguration.HttpTarget),
server.AuthenticateAsServerAsync()
};
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);
AssertClientPropertiesForTarget(client, TestConfiguration.HttpTarget);
}
}
[Fact, OuterLoop]
[PlatformSpecific(TestPlatforms.Linux)]
public async Task NegotiateStream_StreamToStream_KerberosAuthWithoutRealm_Success()
{
if (!_isKrbAvailable)
{
_output.WriteLine("skipping NegotiateStream_StreamToStream_KerberosAuthWithoutRealm_Success");
return;
}
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 UnixGssFakeNegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
NetworkCredential credential = new NetworkCredential(TestConfiguration.KerberosUser, _fixture.password);
Task[] auth = new Task[] {
client.AuthenticateAsClientAsync(credential, TestConfiguration.HostTarget),
server.AuthenticateAsServerAsync()
};
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);
AssertClientPropertiesForTarget(client, TestConfiguration.HostTarget);
}
}
[Fact, OuterLoop]
[PlatformSpecific(TestPlatforms.Linux)]
public async Task NegotiateStream_StreamToStream_KerberosAuthDefaultCredentials_Success()
{
if (!_isKrbAvailable)
{
_output.WriteLine("skipping NegotiateStream_StreamToStream_KerberosAuthDefaultCredentials_Success");
return;
}
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 UnixGssFakeNegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated, "client is not authenticated before AuthenticateAsClient call");
string user = string.Format("{0}@{1}", TestConfiguration.KerberosUser, TestConfiguration.Realm);
string target = string.Format("{0}@{1}", TestConfiguration.HostTarget, TestConfiguration.Realm);
// Seed the default Kerberos cache with the TGT
UnixGssFakeNegotiateStream.GetDefaultKerberosCredentials(user, _fixture.password);
Task[] auth = new Task[] {
client.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, target),
server.AuthenticateAsServerAsync()
};
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);
AssertClientPropertiesForTarget(client, target);
}
}
[Fact, OuterLoop]
[PlatformSpecific(TestPlatforms.Linux)]
public async Task NegotiateStream_EchoServer_ClientWriteRead_Successive_Sync_Success()
{
if (!_isKrbAvailable)
{
_output.WriteLine("skipping NegotiateStream_EchoServer_ClientWriteRead_Successive_Sync_Success");
return;
}
VirtualNetwork network = new VirtualNetwork();
byte[] firstRecvBuffer = new byte[_firstMessage.Length];
byte[] secondRecvBuffer = new byte[_secondMessage.Length];
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 UnixGssFakeNegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated, "client is not authenticated before AuthenticateAsClient call");
string user = string.Format("{0}@{1}", TestConfiguration.KerberosUser, TestConfiguration.Realm);
string target = string.Format("{0}@{1}", TestConfiguration.HostTarget, TestConfiguration.Realm);
NetworkCredential credential = new NetworkCredential(user, _fixture.password);
Task[] auth = new Task[] {
client.AuthenticateAsClientAsync(credential, target),
server.AuthenticateAsServerAsync()
};
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);
Task svrMsgTask = server.PollMessageAsync(2);
client.Write(_firstMessage, 0, _firstMessage.Length);
client.Write(_secondMessage, 0, _secondMessage.Length);
client.Read(firstRecvBuffer, 0, firstRecvBuffer.Length);
client.Read(secondRecvBuffer, 0, secondRecvBuffer.Length);
Assert.True(_firstMessage.SequenceEqual(firstRecvBuffer), "first message received is as expected");
Assert.True(_secondMessage.SequenceEqual(secondRecvBuffer), "second message received is as expected");
await svrMsgTask.TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
}
}
[Fact, OuterLoop]
[PlatformSpecific(TestPlatforms.Linux)]
public async Task NegotiateStream_EchoServer_ClientWriteRead_Successive_Async_Success()
{
if (!_isKrbAvailable)
{
_output.WriteLine("skipping NegotiateStream_EchoServer_ClientWriteRead_Successive_Async_Success");
return;
}
VirtualNetwork network = new VirtualNetwork();
byte[] firstRecvBuffer = new byte[_firstMessage.Length];
byte[] secondRecvBuffer = new byte[_secondMessage.Length];
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 UnixGssFakeNegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated, "client is not authenticated before AuthenticateAsClient call");
string user = string.Format("{0}@{1}", TestConfiguration.KerberosUser, TestConfiguration.Realm);
string target = string.Format("{0}@{1}", TestConfiguration.HostTarget, TestConfiguration.Realm);
NetworkCredential credential = new NetworkCredential(user, _fixture.password);
Task[] auth = new Task[] {
client.AuthenticateAsClientAsync(credential, target),
server.AuthenticateAsServerAsync()
};
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);
Task serverTask = server.PollMessageAsync(2);
Task[] msgTasks = new Task[] {
client.WriteAsync(_firstMessage, 0, _firstMessage.Length).ContinueWith((t) =>
client.WriteAsync(_secondMessage, 0, _secondMessage.Length)).Unwrap(),
ReadAllAsync(client, firstRecvBuffer, 0, firstRecvBuffer.Length).ContinueWith((t) =>
ReadAllAsync(client, secondRecvBuffer, 0, secondRecvBuffer.Length)).Unwrap(),
serverTask
};
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(msgTasks);
Assert.True(_firstMessage.SequenceEqual(firstRecvBuffer), "The first message received is as expected");
Assert.True(_secondMessage.SequenceEqual(secondRecvBuffer), "The second message received is as expected");
}
}
private static async Task ReadAllAsync(Stream source, byte[] buffer, int offset, int count)
{
while (count > 0)
{
int bytesRead = await source.ReadAsync(buffer, offset, count).ConfigureAwait(false);
if (bytesRead == 0) break;
offset += bytesRead;
count -= bytesRead;
}
}
[Fact, OuterLoop]
[PlatformSpecific(TestPlatforms.Linux)]
public void NegotiateStream_StreamToStream_KerberosAuthDefaultCredentialsNoSeed_Failure()
{
if (!_isKrbAvailable)
{
_output.WriteLine("skipping NegotiateStream_StreamToStream_KerberosAuthDefaultCredentialsNoSeed_Failure");
return;
}
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var client = new NegotiateStream(clientStream))
{
Assert.False(client.IsAuthenticated, "client is not authenticated before AuthenticateAsClient call");
string user = string.Format("{0}@{1}", TestConfiguration.KerberosUser, TestConfiguration.Realm);
string target = string.Format("{0}@{1}", TestConfiguration.HostTarget, TestConfiguration.Realm);
Assert.ThrowsAsync<AuthenticationException>(() => client.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, target));
}
}
[Fact, OuterLoop]
[PlatformSpecific(TestPlatforms.Linux)]
public void NegotiateStream_StreamToStream_KerberosAuthInvalidUser_Failure()
{
if (!_isKrbAvailable)
{
_output.WriteLine("skipping NegotiateStream_StreamToStream_KerberosAuthInvalidUser_Failure");
return;
}
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 UnixGssFakeNegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated, "client is not authenticated by default");
string user = string.Format("{0}@{1}", TestConfiguration.KerberosUser, TestConfiguration.Realm);
string target = string.Format("{0}@{1}", TestConfiguration.HostTarget, TestConfiguration.Realm);
NetworkCredential credential = new NetworkCredential(user.Substring(1), _fixture.password);
Assert.ThrowsAsync<AuthenticationException>(() => client.AuthenticateAsClientAsync(credential, target));
Assert.ThrowsAsync<AuthenticationException>(() => server.AuthenticateAsServerAsync());
}
}
[Fact, OuterLoop]
[PlatformSpecific(TestPlatforms.Linux)]
public void NegotiateStream_StreamToStream_KerberosAuthInvalidPassword_Failure()
{
if (!_isKrbAvailable)
{
_output.WriteLine("skipping NegotiateStream_StreamToStream_KerberosAuthInvalidPassword_Failure");
return;
}
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 UnixGssFakeNegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated, "client stream is not authenticated by default");
string user = string.Format("{0}@{1}", TestConfiguration.KerberosUser, TestConfiguration.Realm);
string target = string.Format("{0}@{1}", TestConfiguration.HostTarget, TestConfiguration.Realm);
NetworkCredential credential = new NetworkCredential(user, _fixture.password.Substring(1));
Task serverAuth = server.AuthenticateAsServerAsync();
Assert.ThrowsAsync<AuthenticationException>(() => client.AuthenticateAsClientAsync(credential, target));
Assert.ThrowsAsync<AuthenticationException>(() => server.AuthenticateAsServerAsync());
}
}
[Fact, OuterLoop]
[PlatformSpecific(TestPlatforms.Linux)]
public void NegotiateStream_StreamToStream_KerberosAuthInvalidTarget_Failure()
{
if (!_isKrbAvailable)
{
_output.WriteLine("skipping NegotiateStream_StreamToStream_KerberosAuthInvalidTarget_Failure");
return;
}
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var client = new NegotiateStream(clientStream))
{
Assert.False(client.IsAuthenticated, "client stream is not authenticated by default");
string user = string.Format("{0}@{1}", TestConfiguration.KerberosUser, TestConfiguration.Realm);
string target = string.Format("{0}@{1}", TestConfiguration.HostTarget, TestConfiguration.Realm);
NetworkCredential credential = new NetworkCredential(user, _fixture.password);
Assert.ThrowsAsync<AuthenticationException>(() => client.AuthenticateAsClientAsync(credential, target.Substring(1)));
}
}
public static IEnumerable<object[]> ValidNtlmCredentials()
{
yield return new object[] { new NetworkCredential(TestConfiguration.NtlmUser, _ntlmPassword, TestConfiguration.Domain) };
yield return new object[] { new NetworkCredential(TestConfiguration.NtlmUser, _ntlmPassword) };
yield return new object[]
{
new NetworkCredential($@"{TestConfiguration.Domain}\{TestConfiguration.NtlmUser}", _ntlmPassword)
};
yield return new object[]
{
new NetworkCredential($"{TestConfiguration.NtlmUser}@{TestConfiguration.Domain}", _ntlmPassword)
};
}
public static IEnumerable<object[]> InvalidNtlmCredentials
{
get
{
yield return new object[] { new NetworkCredential(TestConfiguration.NtlmUser, _ntlmPassword, TestConfiguration.Domain.Substring(1)) };
yield return new object[] { new NetworkCredential(TestConfiguration.NtlmUser.Substring(1), _ntlmPassword, TestConfiguration.Domain) };
yield return new object[] { new NetworkCredential(TestConfiguration.NtlmUser, _ntlmPassword.Substring(1), TestConfiguration.Domain) };
yield return new object[] { new NetworkCredential($@"{TestConfiguration.Domain}\{TestConfiguration.NtlmUser}", _ntlmPassword, TestConfiguration.Domain.Substring(1)) };
yield return new object[] { new NetworkCredential($"{TestConfiguration.NtlmUser}@{TestConfiguration.Domain.Substring(1)}", _ntlmPassword) };
yield return new object[] { new NetworkCredential($@"{TestConfiguration.Domain.Substring(1)}\{TestConfiguration.NtlmUser}", _ntlmPassword, TestConfiguration.Domain) };
yield return new object[] { new NetworkCredential(TestConfiguration.NtlmUser, _ntlmPassword, TestConfiguration.Realm) };
}
}
[Theory, OuterLoop]
[MemberData(nameof(ValidNtlmCredentials))]
[PlatformSpecific(TestPlatforms.Linux)]
public async Task NegotiateStream_StreamToStream_NtlmAuthentication_ValidCredentials_Success(NetworkCredential credential)
{
if (!_isNtlmAvailable)
{
_output.WriteLine("skipping NegotiateStream_StreamToStream_NtlmAuthentication_ValidCredentials_Success");
return;
}
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 UnixGssFakeNegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated, "client.IsAuthenticated");
Assert.False(server.IsAuthenticated, "server.IsAuthenticated");
Task[] auth = new Task[] {
client.AuthenticateAsClientAsync(credential, _testTarget, ProtectionLevel.None, TokenImpersonationLevel.Identification),
server.AuthenticateAsServerAsync()
};
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);
// Expected Client property values:
Assert.True(client.IsAuthenticated, "client.IsAuthenticated");
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.False(client.IsEncrypted, "client.IsEncrypted");
Assert.False(client.IsMutuallyAuthenticated, "client.IsMutuallyAuthenticated");
Assert.False(client.IsServer, "client.IsServer");
Assert.False(client.IsSigned, "client.IsSigned");
Assert.False(client.LeaveInnerStreamOpen, "client.LeaveInnerStreamOpen");
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.True(serverIdentity.IsAuthenticated, "serverIdentity.IsAuthenticated");
IdentityValidator.AssertHasName(serverIdentity, _testTarget);
}
}
[Fact, OuterLoop]
[PlatformSpecific(TestPlatforms.Linux)]
public async Task NegotiateStream_StreamToStream_NtlmAuthentication_Fallback_Success()
{
if (!_isNtlmAvailable)
{
_output.WriteLine("skipping NegotiateStream_StreamToStream_NtlmAuthentication_EmptyTarget_KerberosUser_Fallback_Success");
return;
}
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 UnixGssFakeNegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated, "client.IsAuthenticated");
Assert.False(server.IsAuthenticated, "server.IsAuthenticated");
string user = string.Format("{0}@{1}", TestConfiguration.NtlmUser, TestConfiguration.Domain);
NetworkCredential credential = new NetworkCredential(user, TestConfiguration.NtlmPassword);
Task[] auth = new Task[] {
client.AuthenticateAsClientAsync(credential, TestConfiguration.HostTarget),
server.AuthenticateAsServerAsync()
};
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);
// Expected Client property values:
Assert.True(client.IsAuthenticated, "client.IsAuthenticated");
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.True(client.IsEncrypted, "client.IsEncrypted");
Assert.False(client.IsMutuallyAuthenticated, "client.IsMutuallyAuthenticated");
Assert.False(client.IsServer, "client.IsServer");
Assert.True(client.IsSigned, "client.IsSigned");
Assert.False(client.LeaveInnerStreamOpen, "client.LeaveInnerStreamOpen");
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.False(serverIdentity.IsAuthenticated, "serverIdentity.IsAuthenticated");
}
}
[Fact, OuterLoop]
[PlatformSpecific(TestPlatforms.Linux)]
public async Task NegotiateStream_StreamToStream_NtlmAuthentication_KerberosCreds_Success()
{
if (!_isNtlmAvailable)
{
_output.WriteLine("skipping NegotiateStream_StreamToStream_NtlmAuthentication_KerberosCreds_Success");
return;
}
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 UnixGssFakeNegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated, "client.IsAuthenticated");
Assert.False(server.IsAuthenticated, "server.IsAuthenticated");
string user = string.Format("{0}@{1}", TestConfiguration.KerberosUser, TestConfiguration.Realm);
NetworkCredential credential = new NetworkCredential(user, _fixture.password);
Task[] auth = new Task[] {
client.AuthenticateAsClientAsync(credential, TestConfiguration.HttpTarget, ProtectionLevel.None, TokenImpersonationLevel.Identification),
server.AuthenticateAsServerAsync()
};
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);
// Expected Client property values:
Assert.True(client.IsAuthenticated, "client.IsAuthenticated");
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.False(client.IsEncrypted, "client.IsEncrypted");
Assert.False(client.IsMutuallyAuthenticated, "client.IsMutuallyAuthenticated");
Assert.False(client.IsServer, "client.IsServer");
Assert.False(client.IsSigned, "client.IsSigned");
Assert.False(client.LeaveInnerStreamOpen, "client.LeaveInnerStreamOpen");
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.True(serverIdentity.IsAuthenticated, "server identity is authenticated");
IdentityValidator.AssertHasName(serverIdentity, TestConfiguration.HttpTarget);
}
}
[Fact, OuterLoop]
[PlatformSpecific(TestPlatforms.Linux)]
public async Task NegotiateStream_EchoServer_NTLM_ClientWriteRead_Successive_Sync_Success()
{
if (!_isNtlmAvailable)
{
_output.WriteLine("skipping NegotiateStream_EchoServer_NTLM_ClientWriteRead_Successive_Sync_Success");
return;
}
byte[] firstRecvBuffer = new byte[_firstMessage.Length];
byte[] secondRecvBuffer = new byte[_secondMessage.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 UnixGssFakeNegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated, "client.IsAuthenticated");
Assert.False(server.IsAuthenticated, "server.IsAuthenticated");
string user = string.Format("{0}@{1}", TestConfiguration.NtlmUser, TestConfiguration.Domain);
NetworkCredential credential = new NetworkCredential(user, TestConfiguration.NtlmPassword);
Task[] auth = new Task[] {
client.AuthenticateAsClientAsync(credential, TestConfiguration.HostTarget),
server.AuthenticateAsServerAsync()
};
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);
//clearing message queue
byte[] junkBytes = new byte[5];
int j = clientStream.Read(junkBytes, 0, 5);
Task svrMsgTask = server.PollMessageAsync(2);
client.Write(_firstMessage, 0, _firstMessage.Length);
client.Write(_secondMessage, 0, _secondMessage.Length);
client.Read(firstRecvBuffer, 0, firstRecvBuffer.Length);
client.Read(secondRecvBuffer, 0, secondRecvBuffer.Length);
Assert.True(_firstMessage.SequenceEqual(firstRecvBuffer), "first message received is as expected");
Assert.True(_secondMessage.SequenceEqual(secondRecvBuffer), "second message received is as expected");
await svrMsgTask.TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
}
}
[Fact, OuterLoop]
[PlatformSpecific(TestPlatforms.Linux)]
public async Task NegotiateStream_EchoServer_NTLM_ClientWriteRead_Successive_Async_Success()
{
if (!_isNtlmAvailable)
{
_output.WriteLine("skipping NegotiateStream_EchoServer_NTLM_ClientWriteRead_Successive_Async_Success");
return;
}
byte[] firstRecvBuffer = new byte[_firstMessage.Length];
byte[] secondRecvBuffer = new byte[_secondMessage.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 UnixGssFakeNegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated, "client.IsAuthenticated");
Assert.False(server.IsAuthenticated, "server.IsAuthenticated");
string user = string.Format("{0}@{1}", TestConfiguration.NtlmUser, TestConfiguration.Domain);
NetworkCredential credential = new NetworkCredential(user, TestConfiguration.NtlmPassword);
Task[] auth = new Task[] {
client.AuthenticateAsClientAsync(credential, TestConfiguration.HostTarget),
server.AuthenticateAsServerAsync()
};
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);
//clearing message queue
byte[] junkBytes = new byte[5];
int j = clientStream.Read(junkBytes, 0, 5);
Task serverTask = server.PollMessageAsync(2);
Task[] msgTasks = new Task[] {
client.WriteAsync(_firstMessage, 0, _firstMessage.Length).ContinueWith((t) =>
client.WriteAsync(_secondMessage, 0, _secondMessage.Length)).Unwrap(),
ReadAllAsync(client, firstRecvBuffer, 0, firstRecvBuffer.Length).ContinueWith((t) =>
ReadAllAsync(client, secondRecvBuffer, 0, secondRecvBuffer.Length)).Unwrap(),
serverTask
};
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(msgTasks);
Assert.True(_firstMessage.SequenceEqual(firstRecvBuffer), "The first message received is as expected");
Assert.True(_secondMessage.SequenceEqual(secondRecvBuffer), "The second message received is as expected");
}
}
[Theory, OuterLoop]
[MemberData(nameof(InvalidNtlmCredentials))]
[PlatformSpecific(TestPlatforms.Linux)]
public void NegotiateStream_StreamToStream_NtlmAuthentication_NtlmUser_InvalidCredentials_Fail(NetworkCredential credential)
{
if (!_isNtlmAvailable)
{
_output.WriteLine("skipping NegotiateStream_StreamToStream_NtlmAuthentication_NtlmUser_InvalidCredentials_Fail");
return;
}
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 UnixGssFakeNegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated, "client.IsAuthenticated");
Assert.ThrowsAsync<AuthenticationException>(() => server.AuthenticateAsServerAsync());
Assert.ThrowsAsync<AuthenticationException>(() => client.AuthenticateAsClientAsync(credential, _testTarget, ProtectionLevel.None, TokenImpersonationLevel.Identification));
}
}
public void Dispose()
{
try
{
_fixture.CheckAndClearCredentials(_output);
}
catch
{
}
}
}
}
| |
// 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.MethodXml
{
internal class MethodXmlBuilder : AbstractMethodXmlBuilder
{
private MethodXmlBuilder(IMethodSymbol symbol, SemanticModel semanticModel)
: base(symbol, semanticModel)
{
}
private void GenerateBlock(BlockSyntax block)
{
using (BlockTag())
{
foreach (var statement in block.Statements)
{
GenerateComments(statement.GetLeadingTrivia());
GenerateStatement(statement);
}
// Handle any additional comments now, but only comments within the extent of this block.
GenerateComments(block.CloseBraceToken.LeadingTrivia);
}
}
private void GenerateComments(SyntaxTriviaList triviaList)
{
foreach (var trivia in triviaList)
{
// Multi-line comment forms are ignored.
if (trivia.Kind() == SyntaxKind.SingleLineCommentTrivia)
{
// In order to be valid, the comment must appear on its own line.
var line = Text.Lines.GetLineFromPosition(trivia.SpanStart);
var firstNonWhitespacePosition = line.GetFirstNonWhitespacePosition() ?? -1;
if (firstNonWhitespacePosition == trivia.SpanStart)
{
using (var tag = CommentTag())
{
// Skip initial slashes
var trimmedComment = trivia.ToString().Substring(2);
EncodedText(trimmedComment);
}
}
}
}
}
private void GenerateStatement(StatementSyntax statement)
{
var success = false;
int mark = GetMark();
switch (statement.Kind())
{
case SyntaxKind.LocalDeclarationStatement:
success = TryGenerateLocal((LocalDeclarationStatementSyntax)statement);
break;
case SyntaxKind.Block:
success = true;
GenerateBlock((BlockSyntax)statement);
break;
case SyntaxKind.ExpressionStatement:
success = TryGenerateExpressionStatement((ExpressionStatementSyntax)statement);
break;
}
if (!success)
{
Rewind(mark);
GenerateUnknown(statement);
}
// Just for readability
LineBreak();
}
private bool TryGenerateLocal(LocalDeclarationStatementSyntax localDeclarationStatement)
{
/*
- <ElementType name="Local" content="eltOnly">
<attribute type="id" />
<attribute type="static" />
<attribute type="instance" />
<attribute type="implicit" />
<attribute type="constant" />
- <group order="one">
<element type="Type" />
<element type="ArrayType" />
</group>
- <group minOccurs="1" maxOccurs="*" order="seq">
<element type="LocalName" />
<element type="Expression" minOccurs="0" maxOccurs="1" />
</group>
</ElementType>
*/
using (LocalTag(GetLineNumber(localDeclarationStatement)))
{
// Spew the type first
if (!TryGenerateType(localDeclarationStatement.Declaration.Type))
{
return false;
}
// Now spew the list of variables
foreach (var variable in localDeclarationStatement.Declaration.Variables)
{
GenerateName(variable.Identifier.ToString());
if (variable.Initializer != null)
{
if (!TryGenerateExpression(variable.Initializer.Value))
{
return false;
}
}
}
}
return true;
}
private bool TryGenerateExpressionStatement(ExpressionStatementSyntax expressionStatement)
{
using (ExpressionStatementTag(GetLineNumber(expressionStatement)))
{
return TryGenerateExpression(expressionStatement.Expression);
}
}
private bool TryGenerateType(TypeSyntax type)
{
var typeSymbol = SemanticModel.GetTypeInfo(type).Type;
if (typeSymbol == null)
{
return false;
}
GenerateType(typeSymbol);
return true;
}
private bool TryGenerateExpression(ExpressionSyntax expression)
{
using (ExpressionTag())
{
return TryGenerateExpressionSansTag(expression);
}
}
private bool TryGenerateExpressionSansTag(ExpressionSyntax expression)
{
switch (expression.Kind())
{
case SyntaxKind.CharacterLiteralExpression:
return TryGenerateCharLiteral(expression);
case SyntaxKind.UnaryMinusExpression:
case SyntaxKind.NumericLiteralExpression:
case SyntaxKind.StringLiteralExpression:
case SyntaxKind.TrueLiteralExpression:
case SyntaxKind.FalseLiteralExpression:
return TryGenerateLiteral(expression);
case SyntaxKind.NullLiteralExpression:
GenerateNullLiteral();
return true;
case SyntaxKind.ParenthesizedExpression:
return TryGenerateParentheses((ParenthesizedExpressionSyntax)expression);
case SyntaxKind.AddExpression:
case SyntaxKind.BitwiseOrExpression:
case SyntaxKind.BitwiseAndExpression:
return TryGenerateBinaryOperation((BinaryExpressionSyntax)expression);
case SyntaxKind.SimpleAssignmentExpression:
case SyntaxKind.AddAssignmentExpression:
return TryGenerateAssignment((AssignmentExpressionSyntax)expression);
case SyntaxKind.CastExpression:
return TryGenerateCast((CastExpressionSyntax)expression);
case SyntaxKind.ObjectCreationExpression:
return TryGenerateNewClass((ObjectCreationExpressionSyntax)expression);
case SyntaxKind.ArrayCreationExpression:
return TryGenerateNewArray((ArrayCreationExpressionSyntax)expression);
case SyntaxKind.ArrayInitializerExpression:
return TryGenerateArrayLiteral((InitializerExpressionSyntax)expression);
case SyntaxKind.SimpleMemberAccessExpression:
return TryGenerateNameRef((MemberAccessExpressionSyntax)expression);
case SyntaxKind.IdentifierName:
return TryGenerateNameRef((IdentifierNameSyntax)expression);
case SyntaxKind.InvocationExpression:
return GenerateMethodCall((InvocationExpressionSyntax)expression);
case SyntaxKind.ElementAccessExpression:
return TryGenerateArrayElementAccess((ElementAccessExpressionSyntax)expression);
case SyntaxKind.TypeOfExpression:
return TryGenerateTypeOfExpression((TypeOfExpressionSyntax)expression);
case SyntaxKind.ThisExpression:
GenerateThisReference();
return true;
case SyntaxKind.BaseExpression:
GenerateBaseReference();
return true;
}
return false;
}
private bool TryGenerateLiteral(ExpressionSyntax expression)
{
/*
<ElementType name="Literal" content="eltOnly">
- <group order="one">
<element type="Null" />
<element type="Number" />
<element type="Boolean" />
<element type="Char" />
<element type="String" />
<element type="Array" />
<element type="Type" />
</group>
</ElementType>
*/
using (LiteralTag())
{
var constantValue = SemanticModel.GetConstantValue(expression);
if (!constantValue.HasValue)
{
return false;
}
var type = SemanticModel.GetTypeInfo(expression).Type;
if (type == null)
{
return false;
}
switch (expression.Kind())
{
case SyntaxKind.UnaryMinusExpression:
case SyntaxKind.NumericLiteralExpression:
GenerateNumber(constantValue.Value, type);
return true;
case SyntaxKind.StringLiteralExpression:
GenerateString((string)constantValue.Value);
return true;
case SyntaxKind.TrueLiteralExpression:
case SyntaxKind.FalseLiteralExpression:
GenerateBoolean((bool)constantValue.Value);
return true;
}
return false;
}
}
private bool TryGenerateCharLiteral(ExpressionSyntax expression)
{
// For non-letters and digits, generate a cast of the numeric value to a char.
// Otherwise, we might end up generating invalid XML.
if (expression.Kind() != SyntaxKind.CharacterLiteralExpression)
{
return false;
}
var constantValue = SemanticModel.GetConstantValue(expression);
if (!constantValue.HasValue)
{
return false;
}
var ch = (char)constantValue.Value;
if (!char.IsLetterOrDigit(ch))
{
using (CastTag())
{
GenerateType(SpecialType.System_Char);
using (ExpressionTag())
using (LiteralTag())
{
GenerateNumber((ushort)ch, SpecialType.System_UInt16);
}
}
}
else
{
using (LiteralTag())
{
GenerateChar(ch);
}
}
return true;
}
private bool TryGenerateParentheses(ParenthesizedExpressionSyntax parenthesizedExpression)
{
using (ParenthesesTag())
{
return TryGenerateExpression(parenthesizedExpression.Expression);
}
}
private bool TryGenerateBinaryOperation(BinaryExpressionSyntax binaryExpression)
{
BinaryOperatorKind kind;
switch (binaryExpression.Kind())
{
case SyntaxKind.AddExpression:
kind = BinaryOperatorKind.Plus;
break;
case SyntaxKind.BitwiseOrExpression:
kind = BinaryOperatorKind.BitwiseOr;
break;
case SyntaxKind.BitwiseAndExpression:
kind = BinaryOperatorKind.BitwiseAnd;
break;
default:
return false;
}
using (BinaryOperationTag(kind))
{
return TryGenerateExpression(binaryExpression.Left)
&& TryGenerateExpression(binaryExpression.Right);
}
}
private bool TryGenerateAssignment(AssignmentExpressionSyntax binaryExpression)
{
var kind = BinaryOperatorKind.None;
switch (binaryExpression.Kind())
{
case SyntaxKind.AddAssignmentExpression:
kind = BinaryOperatorKind.AddDelegate;
break;
}
using (AssignmentTag(kind))
{
return TryGenerateExpression(binaryExpression.Left)
&& TryGenerateExpression(binaryExpression.Right);
}
}
private bool TryGenerateCast(CastExpressionSyntax castExpression)
{
var type = SemanticModel.GetTypeInfo(castExpression.Type).Type;
if (type == null)
{
return false;
}
using (CastTag())
{
GenerateType(type);
return TryGenerateExpression(castExpression.Expression);
}
}
private bool TryGenerateNewClass(ObjectCreationExpressionSyntax objectCreationExpression)
{
var type = SemanticModel.GetSymbolInfo(objectCreationExpression.Type).Symbol as ITypeSymbol;
if (type == null)
{
return false;
}
using (NewClassTag())
{
GenerateType(type);
foreach (var argument in objectCreationExpression.ArgumentList.Arguments)
{
if (!TryGenerateArgument(argument))
{
return false;
}
}
}
return true;
}
private bool TryGenerateNewArray(ArrayCreationExpressionSyntax arrayCreationExpression)
{
var type = SemanticModel.GetTypeInfo(arrayCreationExpression).Type;
if (type == null)
{
return false;
}
using (NewArrayTag())
{
GenerateType(type);
if (arrayCreationExpression.Initializer != null)
{
using (BoundTag())
using (ExpressionTag())
using (LiteralTag())
using (NumberTag())
{
EncodedText(arrayCreationExpression.Initializer.Expressions.Count.ToString());
}
if (!TryGenerateExpression(arrayCreationExpression.Initializer))
{
return false;
}
}
else
{
foreach (var rankSpecifier in arrayCreationExpression.Type.RankSpecifiers)
{
foreach (var size in rankSpecifier.Sizes)
{
using (BoundTag())
{
if (!TryGenerateExpression(size))
{
return false;
}
}
}
}
}
}
return true;
}
private bool TryGenerateArrayLiteral(InitializerExpressionSyntax initializerExpression)
{
using (LiteralTag())
using (ArrayTag())
{
foreach (var expression in initializerExpression.Expressions)
{
if (!TryGenerateExpression(expression))
{
return false;
}
}
}
return true;
}
private bool TryGenerateNameRef(MemberAccessExpressionSyntax memberAccessExpression)
{
var symbol = SemanticModel.GetSymbolInfo(memberAccessExpression).Symbol;
// No null check for 'symbol' here. If 'symbol' unknown, we'll
// generate an "unknown" name ref.
using (NameRefTag(GetVariableKind(symbol)))
{
var leftHandSymbol = SemanticModel.GetSymbolInfo(memberAccessExpression.Expression).Symbol;
if (leftHandSymbol != null)
{
if (leftHandSymbol.Kind == SymbolKind.Alias)
{
leftHandSymbol = ((IAliasSymbol)leftHandSymbol).Target;
}
}
// If the left-hand side is a named type, we generate a literal expression
// with the type name. Otherwise, we generate the expression normally.
if (leftHandSymbol != null && leftHandSymbol.Kind == SymbolKind.NamedType)
{
using (ExpressionTag())
using (LiteralTag())
{
GenerateType((ITypeSymbol)leftHandSymbol);
}
}
else if (!TryGenerateExpression(memberAccessExpression.Expression))
{
return false;
}
GenerateName(memberAccessExpression.Name.Identifier.ValueText);
}
return true;
}
private bool TryGenerateNameRef(IdentifierNameSyntax identifierName)
{
var symbol = SemanticModel.GetSymbolInfo(identifierName).Symbol;
// No null check for 'symbol' here. If 'symbol' unknown, we'll
// generate an "unknown" name ref.
var variableKind = GetVariableKind(symbol);
using (NameRefTag(variableKind))
{
if (symbol != null && variableKind != VariableKind.Local)
{
using (ExpressionTag())
{
GenerateThisReference();
}
}
GenerateName(identifierName.Identifier.ToString());
}
return true;
}
private bool GenerateMethodCall(InvocationExpressionSyntax invocationExpression)
{
using (MethodCallTag())
{
if (!TryGenerateExpression(invocationExpression.Expression))
{
return false;
}
foreach (var argument in invocationExpression.ArgumentList.Arguments)
{
if (!TryGenerateArgument(argument))
{
return false;
}
}
}
return true;
}
private bool TryGenerateTypeOfExpression(TypeOfExpressionSyntax typeOfExpression)
{
if (typeOfExpression.Type == null)
{
return false;
}
var type = SemanticModel.GetTypeInfo(typeOfExpression.Type).Type;
if (type == null)
{
return false;
}
GenerateType(type);
return true;
}
private bool TryGenerateArrayElementAccess(ElementAccessExpressionSyntax elementAccessExpression)
{
using (ArrayElementAccessTag())
{
if (!TryGenerateExpression(elementAccessExpression.Expression))
{
return false;
}
foreach (var argument in elementAccessExpression.ArgumentList.Arguments)
{
if (argument.Expression == null || !TryGenerateExpression(argument.Expression))
{
return false;
}
}
}
return true;
}
private bool TryGenerateArgument(ArgumentSyntax argument)
{
using (ArgumentTag())
{
return argument.Expression != null && TryGenerateExpression(argument.Expression);
}
}
public static string Generate(MethodDeclarationSyntax methodDeclaration, SemanticModel semanticModel)
{
var symbol = semanticModel.GetDeclaredSymbol(methodDeclaration);
var builder = new MethodXmlBuilder(symbol, semanticModel);
builder.GenerateBlock(methodDeclaration.Body);
return builder.ToString();
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="QuaternionAnimationUsingKeyFrames.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using MS.Internal.PresentationCore;
namespace System.Windows.Media.Animation
{
/// <summary>
/// This class is used to animate a Quaternion property value along a set
/// of key frames.
/// </summary>
[ContentProperty("KeyFrames")]
public class QuaternionAnimationUsingKeyFrames : QuaternionAnimationBase, IKeyFrameAnimation, IAddChild
{
#region Data
private QuaternionKeyFrameCollection _keyFrames;
private ResolvedKeyFrameEntry[] _sortedResolvedKeyFrames;
private bool _areKeyTimesValid;
#endregion
#region Constructors
/// <Summary>
/// Creates a new KeyFrameQuaternionAnimation.
/// </Summary>
public QuaternionAnimationUsingKeyFrames()
: base()
{
_areKeyTimesValid = true;
}
#endregion
#region Freezable
/// <summary>
/// Creates a copy of this KeyFrameQuaternionAnimation.
/// </summary>
/// <returns>The copy</returns>
public new QuaternionAnimationUsingKeyFrames Clone()
{
return (QuaternionAnimationUsingKeyFrames)base.Clone();
}
/// <summary>
/// Returns a version of this class with all its base property values
/// set to the current animated values and removes the animations.
/// </summary>
/// <returns>
/// Since this class isn't animated, this method will always just return
/// this instance of the class.
/// </returns>
public new QuaternionAnimationUsingKeyFrames CloneCurrentValue()
{
return (QuaternionAnimationUsingKeyFrames)base.CloneCurrentValue();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>.
/// </summary>
protected override bool FreezeCore(bool isChecking)
{
bool canFreeze = base.FreezeCore(isChecking);
canFreeze &= Freezable.Freeze(_keyFrames, isChecking);
if (canFreeze & !_areKeyTimesValid)
{
ResolveKeyTimes();
}
return canFreeze;
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.OnChanged">Freezable.OnChanged</see>.
/// </summary>
protected override void OnChanged()
{
_areKeyTimesValid = false;
base.OnChanged();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new QuaternionAnimationUsingKeyFrames();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>.
/// </summary>
protected override void CloneCore(Freezable sourceFreezable)
{
QuaternionAnimationUsingKeyFrames sourceAnimation = (QuaternionAnimationUsingKeyFrames) sourceFreezable;
base.CloneCore(sourceFreezable);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(Freezable)">Freezable.CloneCurrentValueCore</see>.
/// </summary>
protected override void CloneCurrentValueCore(Freezable sourceFreezable)
{
QuaternionAnimationUsingKeyFrames sourceAnimation = (QuaternionAnimationUsingKeyFrames) sourceFreezable;
base.CloneCurrentValueCore(sourceFreezable);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(Freezable)">Freezable.GetAsFrozenCore</see>.
/// </summary>
protected override void GetAsFrozenCore(Freezable source)
{
QuaternionAnimationUsingKeyFrames sourceAnimation = (QuaternionAnimationUsingKeyFrames) source;
base.GetAsFrozenCore(source);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>.
/// </summary>
protected override void GetCurrentValueAsFrozenCore(Freezable source)
{
QuaternionAnimationUsingKeyFrames sourceAnimation = (QuaternionAnimationUsingKeyFrames) source;
base.GetCurrentValueAsFrozenCore(source);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true);
}
/// <summary>
/// Helper used by the four Freezable clone methods to copy the resolved key times and
/// key frames. The Get*AsFrozenCore methods are implemented the same as the Clone*Core
/// methods; Get*AsFrozen at the top level will recursively Freeze so it's not done here.
/// </summary>
/// <param name="sourceAnimation"></param>
/// <param name="isCurrentValueClone"></param>
private void CopyCommon(QuaternionAnimationUsingKeyFrames sourceAnimation, bool isCurrentValueClone)
{
_areKeyTimesValid = sourceAnimation._areKeyTimesValid;
if ( _areKeyTimesValid
&& sourceAnimation._sortedResolvedKeyFrames != null)
{
// _sortedResolvedKeyFrames is an array of ResolvedKeyFrameEntry so the notion of CurrentValueClone doesn't apply
_sortedResolvedKeyFrames = (ResolvedKeyFrameEntry[])sourceAnimation._sortedResolvedKeyFrames.Clone();
}
if (sourceAnimation._keyFrames != null)
{
if (isCurrentValueClone)
{
_keyFrames = (QuaternionKeyFrameCollection)sourceAnimation._keyFrames.CloneCurrentValue();
}
else
{
_keyFrames = (QuaternionKeyFrameCollection)sourceAnimation._keyFrames.Clone();
}
OnFreezablePropertyChanged(null, _keyFrames);
}
}
#endregion // Freezable
#region IAddChild interface
/// <summary>
/// Adds a child object to this KeyFrameAnimation.
/// </summary>
/// <param name="child">
/// The child object to add.
/// </param>
/// <remarks>
/// A KeyFrameAnimation only accepts a KeyFrame of the proper type as
/// a child.
/// </remarks>
void IAddChild.AddChild(object child)
{
WritePreamble();
if (child == null)
{
throw new ArgumentNullException("child");
}
AddChild(child);
WritePostscript();
}
/// <summary>
/// Implemented to allow KeyFrames to be direct children
/// of KeyFrameAnimations in markup.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddChild(object child)
{
QuaternionKeyFrame keyFrame = child as QuaternionKeyFrame;
if (keyFrame != null)
{
KeyFrames.Add(keyFrame);
}
else
{
throw new ArgumentException(SR.Get(SRID.Animation_ChildMustBeKeyFrame), "child");
}
}
/// <summary>
/// Adds a text string as a child of this KeyFrameAnimation.
/// </summary>
/// <param name="childText">
/// The text to add.
/// </param>
/// <remarks>
/// A KeyFrameAnimation does not accept text as a child, so this method will
/// raise an InvalididOperationException unless a derived class has
/// overridden the behavior to add text.
/// </remarks>
/// <exception cref="ArgumentNullException">The childText parameter is
/// null.</exception>
void IAddChild.AddText(string childText)
{
if (childText == null)
{
throw new ArgumentNullException("childText");
}
AddText(childText);
}
/// <summary>
/// This method performs the core functionality of the AddText()
/// method on the IAddChild interface. For a KeyFrameAnimation this means
/// throwing and InvalidOperationException because it doesn't
/// support adding text.
/// </summary>
/// <remarks>
/// This method is the only core implementation. It does not call
/// WritePreamble() or WritePostscript(). It also doesn't throw an
/// ArgumentNullException if the childText parameter is null. These tasks
/// are performed by the interface implementation. Therefore, it's OK
/// for a derived class to override this method and call the base
/// class implementation only if they determine that it's the right
/// course of action. The derived class can rely on KeyFrameAnimation's
/// implementation of IAddChild.AddChild or implement their own
/// following the Freezable pattern since that would be a public
/// method.
/// </remarks>
/// <param name="childText">A string representing the child text that
/// should be added. If this is a KeyFrameAnimation an exception will be
/// thrown.</param>
/// <exception cref="InvalidOperationException">Timelines have no way
/// of adding text.</exception>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddText(string childText)
{
throw new InvalidOperationException(SR.Get(SRID.Animation_NoTextChildren));
}
#endregion
#region QuaternionAnimationBase
/// <summary>
/// Calculates the value this animation believes should be the current value for the property.
/// </summary>
/// <param name="defaultOriginValue">
/// This value is the suggested origin value provided to the animation
/// to be used if the animation does not have its own concept of a
/// start value. If this animation is the first in a composition chain
/// this value will be the snapshot value if one is available or the
/// base property value if it is not; otherise this value will be the
/// value returned by the previous animation in the chain with an
/// animationClock that is not Stopped.
/// </param>
/// <param name="defaultDestinationValue">
/// This value is the suggested destination value provided to the animation
/// to be used if the animation does not have its own concept of an
/// end value. This value will be the base value if the animation is
/// in the first composition layer of animations on a property;
/// otherwise this value will be the output value from the previous
/// composition layer of animations for the property.
/// </param>
/// <param name="animationClock">
/// This is the animationClock which can generate the CurrentTime or
/// CurrentProgress value to be used by the animation to generate its
/// output value.
/// </param>
/// <returns>
/// The value this animation believes should be the current value for the property.
/// </returns>
protected sealed override Quaternion GetCurrentValueCore(
Quaternion defaultOriginValue,
Quaternion defaultDestinationValue,
AnimationClock animationClock)
{
Debug.Assert(animationClock.CurrentState != ClockState.Stopped);
if (_keyFrames == null)
{
return defaultDestinationValue;
}
// We resolved our KeyTimes when we froze, but also got notified
// of the frozen state and therefore invalidated ourselves.
if (!_areKeyTimesValid)
{
ResolveKeyTimes();
}
if (_sortedResolvedKeyFrames == null)
{
return defaultDestinationValue;
}
TimeSpan currentTime = animationClock.CurrentTime.Value;
Int32 keyFrameCount = _sortedResolvedKeyFrames.Length;
Int32 maxKeyFrameIndex = keyFrameCount - 1;
Quaternion currentIterationValue;
Debug.Assert(maxKeyFrameIndex >= 0, "maxKeyFrameIndex is less than zero which means we don't actually have any key frames.");
Int32 currentResolvedKeyFrameIndex = 0;
// Skip all the key frames with key times lower than the current time.
// currentResolvedKeyFrameIndex will be greater than maxKeyFrameIndex
// if we are past the last key frame.
while ( currentResolvedKeyFrameIndex < keyFrameCount
&& currentTime > _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
{
currentResolvedKeyFrameIndex++;
}
// If there are multiple key frames at the same key time, be sure to go to the last one.
while ( currentResolvedKeyFrameIndex < maxKeyFrameIndex
&& currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex + 1]._resolvedKeyTime)
{
currentResolvedKeyFrameIndex++;
}
if (currentResolvedKeyFrameIndex == keyFrameCount)
{
// Past the last key frame.
currentIterationValue = GetResolvedKeyFrameValue(maxKeyFrameIndex);
}
else if (currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
{
// Exactly on a key frame.
currentIterationValue = GetResolvedKeyFrameValue(currentResolvedKeyFrameIndex);
}
else
{
// Between two key frames.
Double currentSegmentProgress = 0.0;
Quaternion fromValue;
if (currentResolvedKeyFrameIndex == 0)
{
// The current key frame is the first key frame so we have
// some special rules for determining the fromValue and an
// optimized method of calculating the currentSegmentProgress.
// If we're additive we want the base value to be a zero value
// so that if there isn't a key frame at time 0.0, we'll use
// the zero value for the time 0.0 value and then add that
// later to the base value.
if (IsAdditive)
{
fromValue = AnimatedTypeHelpers.GetZeroValueQuaternion(defaultOriginValue);
}
else
{
fromValue = defaultOriginValue;
}
// Current segment time divided by the segment duration.
// Note: the reason this works is that we know that we're in
// the first segment, so we can assume:
//
// currentTime.TotalMilliseconds = current segment time
// _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds = current segment duration
currentSegmentProgress = currentTime.TotalMilliseconds
/ _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds;
}
else
{
Int32 previousResolvedKeyFrameIndex = currentResolvedKeyFrameIndex - 1;
TimeSpan previousResolvedKeyTime = _sortedResolvedKeyFrames[previousResolvedKeyFrameIndex]._resolvedKeyTime;
fromValue = GetResolvedKeyFrameValue(previousResolvedKeyFrameIndex);
TimeSpan segmentCurrentTime = currentTime - previousResolvedKeyTime;
TimeSpan segmentDuration = _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime - previousResolvedKeyTime;
currentSegmentProgress = segmentCurrentTime.TotalMilliseconds
/ segmentDuration.TotalMilliseconds;
}
currentIterationValue = GetResolvedKeyFrame(currentResolvedKeyFrameIndex).InterpolateValue(fromValue, currentSegmentProgress);
}
// If we're cumulative, we need to multiply the final key frame
// value by the current repeat count and add this to the return
// value.
if (IsCumulative)
{
Double currentRepeat = (Double)(animationClock.CurrentIteration - 1);
if (currentRepeat > 0.0)
{
currentIterationValue = AnimatedTypeHelpers.AddQuaternion(
currentIterationValue,
AnimatedTypeHelpers.ScaleQuaternion(GetResolvedKeyFrameValue(maxKeyFrameIndex), currentRepeat));
}
}
// If we're additive we need to add the base value to the return value.
if (IsAdditive)
{
return AnimatedTypeHelpers.AddQuaternion(defaultOriginValue, currentIterationValue);
}
return currentIterationValue;
}
/// <summary>
/// Provide a custom natural Duration when the Duration property is set to Automatic.
/// </summary>
/// <param name="clock">
/// The Clock whose natural duration is desired.
/// </param>
/// <returns>
/// If the last KeyFrame of this animation is a KeyTime, then this will
/// be used as the NaturalDuration; otherwise it will be one second.
/// </returns>
protected override sealed Duration GetNaturalDurationCore(Clock clock)
{
return new Duration(LargestTimeSpanKeyTime);
}
#endregion
#region IKeyFrameAnimation
/// <summary>
/// Returns the QuaternionKeyFrameCollection used by this KeyFrameQuaternionAnimation.
/// </summary>
IList IKeyFrameAnimation.KeyFrames
{
get
{
return KeyFrames;
}
set
{
KeyFrames = (QuaternionKeyFrameCollection)value;
}
}
/// <summary>
/// Returns the QuaternionKeyFrameCollection used by this KeyFrameQuaternionAnimation.
/// </summary>
public QuaternionKeyFrameCollection KeyFrames
{
get
{
ReadPreamble();
// The reason we don't just set _keyFrames to the empty collection
// in the first place is that null tells us that the user has not
// asked for the collection yet. The first time they ask for the
// collection and we're unfrozen, policy dictates that we give
// them a new unfrozen collection. All subsequent times they will
// get whatever collection is present, whether frozen or unfrozen.
if (_keyFrames == null)
{
if (this.IsFrozen)
{
_keyFrames = QuaternionKeyFrameCollection.Empty;
}
else
{
WritePreamble();
_keyFrames = new QuaternionKeyFrameCollection();
OnFreezablePropertyChanged(null, _keyFrames);
WritePostscript();
}
}
return _keyFrames;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
WritePreamble();
if (value != _keyFrames)
{
OnFreezablePropertyChanged(_keyFrames, value);
_keyFrames = value;
WritePostscript();
}
}
}
/// <summary>
/// Returns true if we should serialize the KeyFrames, property for this Animation.
/// </summary>
/// <returns>True if we should serialize the KeyFrames property for this Animation; otherwise false.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeKeyFrames()
{
ReadPreamble();
return _keyFrames != null
&& _keyFrames.Count > 0;
}
#endregion
#region Public Properties
/// <summary>
/// If this property is set to true, this animation will add its value
/// to the base value or the value of the previous animation in the
/// composition chain. Another way of saying this is that the units
/// specified in the animation are relative to the base value rather
/// than absolute units.
/// </summary>
/// <remarks>
/// In the case where the first key frame's resolved key time is not
/// 0.0 there is slightly different behavior between KeyFrameQuaternionAnimations
/// with IsAdditive set and without. Animations with the property set to false
/// will behave as if there is a key frame at time 0.0 with the value of the
/// base value. Animations with the property set to true will behave as if
/// there is a key frame at time 0.0 with a zero value appropriate to the type
/// of the animation. These behaviors provide the results most commonly expected
/// and can be overridden by simply adding a key frame at time 0.0 with the preferred value.
/// </remarks>
public bool IsAdditive
{
get
{
return (bool)GetValue(IsAdditiveProperty);
}
set
{
SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value));
}
}
/// <summary>
/// If this property is set to true, the value of this animation will
/// accumulate over repeat cycles. For example, if this is a point
/// animation and your key frames describe something approximating and
/// arc, setting this property to true will result in an animation that
/// would appear to bounce the point across the screen.
/// </summary>
/// <remarks>
/// This property works along with the IsAdditive property. Setting
/// this value to true has no effect unless IsAdditive is also set
/// to true.
/// </remarks>
public bool IsCumulative
{
get
{
return (bool)GetValue(IsCumulativeProperty);
}
set
{
SetValueInternal(IsCumulativeProperty, BooleanBoxes.Box(value));
}
}
#endregion
#region Private Methods
private struct KeyTimeBlock
{
public int BeginIndex;
public int EndIndex;
}
private Quaternion GetResolvedKeyFrameValue(Int32 resolvedKeyFrameIndex)
{
Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrameValue");
return GetResolvedKeyFrame(resolvedKeyFrameIndex).Value;
}
private QuaternionKeyFrame GetResolvedKeyFrame(Int32 resolvedKeyFrameIndex)
{
Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrame");
return _keyFrames[_sortedResolvedKeyFrames[resolvedKeyFrameIndex]._originalKeyFrameIndex];
}
/// <summary>
/// Returns the largest time span specified key time from all of the key frames.
/// If there are not time span key times a time span of one second is returned
/// to match the default natural duration of the From/To/By animations.
/// </summary>
private TimeSpan LargestTimeSpanKeyTime
{
get
{
bool hasTimeSpanKeyTime = false;
TimeSpan largestTimeSpanKeyTime = TimeSpan.Zero;
if (_keyFrames != null)
{
Int32 keyFrameCount = _keyFrames.Count;
for (int index = 0; index < keyFrameCount; index++)
{
KeyTime keyTime = _keyFrames[index].KeyTime;
if (keyTime.Type == KeyTimeType.TimeSpan)
{
hasTimeSpanKeyTime = true;
if (keyTime.TimeSpan > largestTimeSpanKeyTime)
{
largestTimeSpanKeyTime = keyTime.TimeSpan;
}
}
}
}
if (hasTimeSpanKeyTime)
{
return largestTimeSpanKeyTime;
}
else
{
return TimeSpan.FromSeconds(1.0);
}
}
}
private void ResolveKeyTimes()
{
Debug.Assert(!_areKeyTimesValid, "KeyFrameQuaternionAnimaton.ResolveKeyTimes() shouldn't be called if the key times are already valid.");
int keyFrameCount = 0;
if (_keyFrames != null)
{
keyFrameCount = _keyFrames.Count;
}
if (keyFrameCount == 0)
{
_sortedResolvedKeyFrames = null;
_areKeyTimesValid = true;
return;
}
_sortedResolvedKeyFrames = new ResolvedKeyFrameEntry[keyFrameCount];
int index = 0;
// Initialize the _originalKeyFrameIndex.
for ( ; index < keyFrameCount; index++)
{
_sortedResolvedKeyFrames[index]._originalKeyFrameIndex = index;
}
// calculationDuration represents the time span we will use to resolve
// percent key times. This is defined as the value in the following
// precedence order:
// 1. The animation's duration, but only if it is a time span, not auto or forever.
// 2. The largest time span specified key time of all the key frames.
// 3. 1 second, to match the From/To/By animations.
TimeSpan calculationDuration = TimeSpan.Zero;
Duration duration = Duration;
if (duration.HasTimeSpan)
{
calculationDuration = duration.TimeSpan;
}
else
{
calculationDuration = LargestTimeSpanKeyTime;
}
int maxKeyFrameIndex = keyFrameCount - 1;
ArrayList unspecifiedBlocks = new ArrayList();
bool hasPacedKeyTimes = false;
//
// Pass 1: Resolve Percent and Time key times.
//
index = 0;
while (index < keyFrameCount)
{
KeyTime keyTime = _keyFrames[index].KeyTime;
switch (keyTime.Type)
{
case KeyTimeType.Percent:
_sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.FromMilliseconds(
keyTime.Percent * calculationDuration.TotalMilliseconds);
index++;
break;
case KeyTimeType.TimeSpan:
_sortedResolvedKeyFrames[index]._resolvedKeyTime = keyTime.TimeSpan;
index++;
break;
case KeyTimeType.Paced:
case KeyTimeType.Uniform:
if (index == maxKeyFrameIndex)
{
// If the last key frame doesn't have a specific time
// associated with it its resolved key time will be
// set to the calculationDuration, which is the
// defined in the comments above where it is set.
// Reason: We only want extra time at the end of the
// key frames if the user specifically states that
// the last key frame ends before the animation ends.
_sortedResolvedKeyFrames[index]._resolvedKeyTime = calculationDuration;
index++;
}
else if ( index == 0
&& keyTime.Type == KeyTimeType.Paced)
{
// Note: It's important that this block come after
// the previous if block because of rule precendence.
// If the first key frame in a multi-frame key frame
// collection is paced, we set its resolved key time
// to 0.0 for performance reasons. If we didn't, the
// resolved key time list would be dependent on the
// base value which can change every animation frame
// in many cases.
_sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.Zero;
index++;
}
else
{
if (keyTime.Type == KeyTimeType.Paced)
{
hasPacedKeyTimes = true;
}
KeyTimeBlock block = new KeyTimeBlock();
block.BeginIndex = index;
// NOTE: We don't want to go all the way up to the
// last frame because if it is Uniform or Paced its
// resolved key time will be set to the calculation
// duration using the logic above.
//
// This is why the logic is:
// ((++index) < maxKeyFrameIndex)
// instead of:
// ((++index) < keyFrameCount)
while ((++index) < maxKeyFrameIndex)
{
KeyTimeType type = _keyFrames[index].KeyTime.Type;
if ( type == KeyTimeType.Percent
|| type == KeyTimeType.TimeSpan)
{
break;
}
else if (type == KeyTimeType.Paced)
{
hasPacedKeyTimes = true;
}
}
Debug.Assert(index < keyFrameCount,
"The end index for a block of unspecified key frames is out of bounds.");
block.EndIndex = index;
unspecifiedBlocks.Add(block);
}
break;
}
}
//
// Pass 2: Resolve Uniform key times.
//
for (int j = 0; j < unspecifiedBlocks.Count; j++)
{
KeyTimeBlock block = (KeyTimeBlock)unspecifiedBlocks[j];
TimeSpan blockBeginTime = TimeSpan.Zero;
if (block.BeginIndex > 0)
{
blockBeginTime = _sortedResolvedKeyFrames[block.BeginIndex - 1]._resolvedKeyTime;
}
// The number of segments is equal to the number of key
// frames we're working on plus 1. Think about the case
// where we're working on a single key frame. There's a
// segment before it and a segment after it.
//
// Time known Uniform Time known
// ^ ^ ^
// | | |
// | (segment 1) | (segment 2) |
Int64 segmentCount = (block.EndIndex - block.BeginIndex) + 1;
TimeSpan uniformTimeStep = TimeSpan.FromTicks((_sortedResolvedKeyFrames[block.EndIndex]._resolvedKeyTime - blockBeginTime).Ticks / segmentCount);
index = block.BeginIndex;
TimeSpan resolvedTime = blockBeginTime + uniformTimeStep;
while (index < block.EndIndex)
{
_sortedResolvedKeyFrames[index]._resolvedKeyTime = resolvedTime;
resolvedTime += uniformTimeStep;
index++;
}
}
//
// Pass 3: Resolve Paced key times.
//
if (hasPacedKeyTimes)
{
ResolvePacedKeyTimes();
}
//
// Sort resolved key frame entries.
//
Array.Sort(_sortedResolvedKeyFrames);
_areKeyTimesValid = true;
return;
}
/// <summary>
/// This should only be called from ResolveKeyTimes and only at the
/// appropriate time.
/// </summary>
private void ResolvePacedKeyTimes()
{
Debug.Assert(_keyFrames != null && _keyFrames.Count > 2,
"Caller must guard against calling this method when there are insufficient keyframes.");
// If the first key frame is paced its key time has already
// been resolved, so we start at index 1.
int index = 1;
int maxKeyFrameIndex = _sortedResolvedKeyFrames.Length - 1;
do
{
if (_keyFrames[index].KeyTime.Type == KeyTimeType.Paced)
{
//
// We've found a paced key frame so this is the
// beginning of a paced block.
//
// The first paced key frame in this block.
int firstPacedBlockKeyFrameIndex = index;
// List of segment lengths for this paced block.
List<Double> segmentLengths = new List<Double>();
// The resolved key time for the key frame before this
// block which we'll use as our starting point.
TimeSpan prePacedBlockKeyTime = _sortedResolvedKeyFrames[index - 1]._resolvedKeyTime;
// The total of the segment lengths of the paced key
// frames in this block.
Double totalLength = 0.0;
// The key value of the previous key frame which will be
// used to determine the segment length of this key frame.
Quaternion prevKeyValue = _keyFrames[index - 1].Value;
do
{
Quaternion currentKeyValue = _keyFrames[index].Value;
// Determine the segment length for this key frame and
// add to the total length.
totalLength += AnimatedTypeHelpers.GetSegmentLengthQuaternion(prevKeyValue, currentKeyValue);
// Temporarily store the distance into the total length
// that this key frame represents in the resolved
// key times array to be converted to a resolved key
// time outside of this loop.
segmentLengths.Add(totalLength);
// Prepare for the next iteration.
prevKeyValue = currentKeyValue;
index++;
}
while ( index < maxKeyFrameIndex
&& _keyFrames[index].KeyTime.Type == KeyTimeType.Paced);
// index is currently set to the index of the key frame
// after the last paced key frame. This will always
// be a valid index because we limit ourselves with
// maxKeyFrameIndex.
// We need to add the distance between the last paced key
// frame and the next key frame to get the total distance
// inside the key frame block.
totalLength += AnimatedTypeHelpers.GetSegmentLengthQuaternion(prevKeyValue, _keyFrames[index].Value);
// Calculate the time available in the resolved key time space.
TimeSpan pacedBlockDuration = _sortedResolvedKeyFrames[index]._resolvedKeyTime - prePacedBlockKeyTime;
// Convert lengths in segmentLengths list to resolved
// key times for the paced key frames in this block.
for (int i = 0, currentKeyFrameIndex = firstPacedBlockKeyFrameIndex; i < segmentLengths.Count; i++, currentKeyFrameIndex++)
{
// The resolved key time for each key frame is:
//
// The key time of the key frame before this paced block
// + ((the percentage of the way through the total length)
// * the resolved key time space available for the block)
_sortedResolvedKeyFrames[currentKeyFrameIndex]._resolvedKeyTime = prePacedBlockKeyTime + TimeSpan.FromMilliseconds(
(segmentLengths[i] / totalLength) * pacedBlockDuration.TotalMilliseconds);
}
}
else
{
index++;
}
}
while (index < maxKeyFrameIndex);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace ServiceStack.OrmLite.Dapper
{
public static partial class SqlMapper
{
private sealed partial class DapperRow
: IDictionary<string, object>
, IReadOnlyDictionary<string, object>
{
private readonly DapperTable table;
private object[] values;
public DapperRow(DapperTable table, object[] values)
{
this.table = table ?? throw new ArgumentNullException(nameof(table));
this.values = values ?? throw new ArgumentNullException(nameof(values));
}
private sealed class DeadValue
{
public static readonly DeadValue Default = new DeadValue();
private DeadValue() { /* hiding constructor */ }
}
int ICollection<KeyValuePair<string, object>>.Count
{
get
{
int count = 0;
for (int i = 0; i < values.Length; i++)
{
if (!(values[i] is DeadValue)) count++;
}
return count;
}
}
public bool TryGetValue(string key, out object value)
=> TryGetValue(table.IndexOfName(key), out value);
internal bool TryGetValue(int index, out object value)
{
if (index < 0)
{ // doesn't exist
value = null;
return false;
}
// exists, **even if** we don't have a value; consider table rows heterogeneous
value = index < values.Length ? values[index] : null;
if (value is DeadValue)
{ // pretend it isn't here
value = null;
return false;
}
return true;
}
public override string ToString()
{
var sb = GetStringBuilder().Append("{DapperRow");
foreach (var kv in this)
{
var value = kv.Value;
sb.Append(", ").Append(kv.Key);
if (value != null)
{
sb.Append(" = '").Append(kv.Value).Append('\'');
}
else
{
sb.Append(" = NULL");
}
}
return sb.Append('}').__ToStringRecycle();
}
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
var names = table.FieldNames;
for (var i = 0; i < names.Length; i++)
{
object value = i < values.Length ? values[i] : null;
if (!(value is DeadValue))
{
yield return new KeyValuePair<string, object>(names[i], value);
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#region Implementation of ICollection<KeyValuePair<string,object>>
void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item)
{
IDictionary<string, object> dic = this;
dic.Add(item.Key, item.Value);
}
void ICollection<KeyValuePair<string, object>>.Clear()
{ // removes values for **this row**, but doesn't change the fundamental table
for (int i = 0; i < values.Length; i++)
values[i] = DeadValue.Default;
}
bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item)
{
return TryGetValue(item.Key, out object value) && Equals(value, item.Value);
}
void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{
foreach (var kv in this)
{
array[arrayIndex++] = kv; // if they didn't leave enough space; not our fault
}
}
bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item)
{
IDictionary<string, object> dic = this;
return dic.Remove(item.Key);
}
bool ICollection<KeyValuePair<string, object>>.IsReadOnly => false;
#endregion
#region Implementation of IDictionary<string,object>
bool IDictionary<string, object>.ContainsKey(string key)
{
int index = table.IndexOfName(key);
if (index < 0 || index >= values.Length || values[index] is DeadValue) return false;
return true;
}
void IDictionary<string, object>.Add(string key, object value)
{
SetValue(key, value, true);
}
bool IDictionary<string, object>.Remove(string key)
=> Remove(table.IndexOfName(key));
internal bool Remove(int index)
{
if (index < 0 || index >= values.Length || values[index] is DeadValue) return false;
values[index] = DeadValue.Default;
return true;
}
object IDictionary<string, object>.this[string key]
{
get { TryGetValue(key, out object val); return val; }
set { SetValue(key, value, false); }
}
public object SetValue(string key, object value)
{
return SetValue(key, value, false);
}
private object SetValue(string key, object value, bool isAdd)
{
if (key == null) throw new ArgumentNullException(nameof(key));
int index = table.IndexOfName(key);
if (index < 0)
{
index = table.AddField(key);
}
else if (isAdd && index < values.Length && !(values[index] is DeadValue))
{
// then semantically, this value already exists
throw new ArgumentException("An item with the same key has already been added", nameof(key));
}
return SetValue(index, value);
}
internal object SetValue(int index, object value)
{
int oldLength = values.Length;
if (oldLength <= index)
{
// we'll assume they're doing lots of things, and
// grow it to the full width of the table
Array.Resize(ref values, table.FieldCount);
for (int i = oldLength; i < values.Length; i++)
{
values[i] = DeadValue.Default;
}
}
return values[index] = value;
}
ICollection<string> IDictionary<string, object>.Keys
{
get { return this.Select(kv => kv.Key).ToArray(); }
}
ICollection<object> IDictionary<string, object>.Values
{
get { return this.Select(kv => kv.Value).ToArray(); }
}
#endregion
#region Implementation of IReadOnlyDictionary<string,object>
int IReadOnlyCollection<KeyValuePair<string, object>>.Count
{
get
{
return values.Count(t => !(t is DeadValue));
}
}
bool IReadOnlyDictionary<string, object>.ContainsKey(string key)
{
int index = table.IndexOfName(key);
return index >= 0 && index < values.Length && !(values[index] is DeadValue);
}
object IReadOnlyDictionary<string, object>.this[string key]
{
get { TryGetValue(key, out object val); return val; }
}
IEnumerable<string> IReadOnlyDictionary<string, object>.Keys
{
get { return this.Select(kv => kv.Key); }
}
IEnumerable<object> IReadOnlyDictionary<string, object>.Values
{
get { return this.Select(kv => kv.Value); }
}
#endregion
}
}
}
| |
using Microsoft.Xna.Framework.Graphics;
using System;
using MonoFlixel;
namespace MonoFlixel
{
/// <summary>
/// <code>FlxEmitter</code> is a lightweight particle emitter.
/// It can be used for one-time explosions or for
/// continuous fx like rain and fire. <code>FlxEmitter</code>
/// is not optimized or anything; all it does is launch
/// <code>FlxParticle</code> objects out at set intervals
/// by setting their positions and velocities accordingly.
/// It is easy to use and relatively efficient,
/// relying on <code>FlxGroup</code>'s RECYCLE POWERS.
/// </summary>
public class FlxEmitter : FlxGroup
{
/// <summary>
/// The X position of the top left corner of the emitter in world space.
/// Already inherited by FlxObject.
/// </summary>
//public new float x { get; set; }
/// <summary>
/// The Y position of the top left corner of emitter in world space.
/// Already inherited by FlxObject.
/// </summary>
//public new float y { get; set; }
/// <summary>
/// The width of the emitter. Particles can be randomly generated from anywhere within this box.
/// Already inherited by FlxObject.
/// </summary>
//public new float width { get; set; }
/// <summary>
/// The height of the emitter. Particles can be randomly generated from anywhere within this box.
/// Already inherited by FlxObject.
/// </summary>
//public new float height { get; set; }
/// <summary>
/// The minimum possible velocity of a particle.
/// The default value is (-100,-100).
/// </summary>
public FlxPoint minParticleSpeed;
/// <summary>
/// The maximum possible velocity of a particle.
/// The default value is (100,100).
/// </summary>
public FlxPoint maxParticleSpeed;
/// <summary>
/// The X and Y drag component of particles launched from the emitter.
/// </summary>
public FlxPoint particleDrag;
/// <summary>
/// The minimum possible angular velocity of a particle. The default value is -360.
/// NOTE: rotating particles are more expensive to draw than non-rotating ones!
/// </summary>
public float minRotation;
/// <summary>
/// The maximum possible angular velocity of a particle. The default value is 360.
/// NOTE: rotating particles are more expensive to draw than non-rotating ones!
/// </summary>
public float maxRotation;
/// <summary>
/// Sets the <code>acceleration.y</code> member of each particle to this value on launch.
/// </summary>
public float gravity;
/// <summary>
/// Determines whether the emitter is currently emitting particles.
/// It is totally safe to directly toggle this.
/// </summary>
public bool on;
/// <summary>
/// How often a particle is emitted (if emitter is started with Explode == false).
/// </summary>
public float frequency;
/// <summary>
/// How long each particle lives once it is emitted.
/// Set lifespan to 'zero' for particles to live forever.
/// </summary>
public float lifespan;
/// <summary>
/// How much each particle should bounce. 1 = full bounce, 0 = no bounce.
/// </summary>
public float bounce;
/// <summary>
/// Set your own particle class type here.
/// Default is <code>FlxParticle</code>.
/// </summary>
public Object particleClass;
/// <summary>
/// Internal helper for deciding how many particles to launch.
/// </summary>
protected uint _quantity;
/// <summary>
/// Internal helper for the style of particle emission (all at once, or one at a time).
/// </summary>
protected bool _explode;
/// <summary>
/// Internal helper for deciding when to launch particles or kill them.
/// </summary>
protected float _timer;
/// <summary>
/// Internal counter for figuring out how many particles to launch.
/// </summary>
protected uint _counter;
/// <summary>
/// Internal counter for figuring out how many particles to launch.
/// </summary>
protected FlxPoint _point;
/// <summary>
/// Creates a new <code>FlxEmitter</code> object at a specific position.
/// Does NOT automatically generate or attach particles!
/// </summary>
/// <param name="X">The X position of the emitter.</param>
/// <param name="Y">The Y position of the emitter.</param>
/// <param name="size">Optional, specifies a maximum capacity for this emitter.</param>
public FlxEmitter(float X=0, float Y=0, uint size=0) : base(size)
{
((FlxObject) this).X = X;
((FlxObject) this).Y = Y;
Width = 0;
Height = 0;
minParticleSpeed = new FlxPoint(-100,-100);
maxParticleSpeed = new FlxPoint(100,100);
minRotation = -360;
maxRotation = 360;
gravity = 0;
particleClass = null;
particleDrag = new FlxPoint();
frequency = 0.1f;
lifespan = 3;
bounce = 0;
_quantity = 0;
_counter = 0;
_explode = true;
on = false;
_point = new FlxPoint();
}
/// <summary>
/// Clean up memory.
/// </summary>
override public void destroy()
{
minParticleSpeed = null;
maxParticleSpeed = null;
particleDrag = null;
particleClass = null;
_point = null;
base.destroy();
}
/// <summary>
/// This function generates a new array of particle sprites to attach to the emitter.
/// </summary>
/// <param name="graphics">Texture for the particles - can be one square or a spritesheet. Set Multiple to true if it is a spritesheet and it will automatically create the particles as long as each frame on the spritesheet is square</param>
/// <param name="Multiple">Whether or not the Texture contains multiple sprites for particles</param>
/// <param name="Quantity">The number of particles to generate</param>
/// <param name="Rotation">The amount of rotation in degrees per frame, so keep this number low</param>
/// <param name="Collide">The collidability of the particle, 1 = Full and 0 = None</param>
/// <returns>This FlxEmitter instance (nice for chaining stuff together, if you're into that).</returns>
//public FlxEmitter makeParticles(Texture2D graphics, bool Multiple=false, uint Quantity = 50, float Rotation = 1f, float Collide = 0.8f)
public FlxEmitter makeParticles(string graphics, uint Quantity = 50, uint BakedRotations = 0, bool Multiple = false, float Collide = 0.8f)
{
maxSize = Quantity;
uint totalFrames = 0;
if (Multiple) {
FlxSprite sprite = new FlxSprite();
sprite.loadGraphic(graphics,true);
totalFrames = sprite.Frames;
sprite.destroy();
}
uint randomFrame;
FlxParticle particle;
int i = 0;
while(i < Quantity)
{
particle = new FlxParticle();
/*
if(particleClass == null)
particle = new FlxParticle();
else
particle = new particleClass();
*/
if(Multiple)
{
randomFrame = (uint)(FlxG.random()*totalFrames);
if(BakedRotations > 0)
particle.loadRotatedGraphic(graphics,BakedRotations,(int)randomFrame);
else
{
particle.loadGraphic(graphics,true);
particle.Frame = (int)randomFrame;
}
}
else
{
if(BakedRotations > 0)
particle.loadRotatedGraphic(graphics,BakedRotations);
else
particle.loadGraphic(graphics);
}
if(Collide > 0)
{
particle.Width *= Collide;
particle.Height *= Collide;
particle.centerOffsets();
}
else
particle.AllowCollisions = FlxObject.None;
particle.Exists = false;
add(particle);
i++;
}
return this;
}
/// <summary>
/// Called automatically by the game loop, decides when to launch particles and when to "die".
/// </summary>
override public void update()
{
if(on)
{
if(_explode)
{
on = false;
uint i = 0;
uint l = _quantity;
if((l <= 0) || (l > length))
l = (uint)length;
while(i < l)
{
emitParticle();
i++;
}
_quantity = 0;
}
else
{
_timer = _timer + FlxG.elapsed;
while((frequency > 0) && (_timer > frequency) && on)
{
_timer = _timer - frequency;
emitParticle();
if((_quantity > 0) && (++_counter >= _quantity))
{
on = false;
_quantity = 0;
}
}
}
}
base.update();
}
/// <summary>
/// Call this function to turn off all the particles and the emitter.
/// </summary>
override public void kill()
{
on = false;
base.kill();
}
/// <summary>
/// Call this function to start emitting particles.
/// </summary>
/// <param name="Explode">Whether the particles should all burst out at once.</param>
/// <param name="Lifespan">How long each particle lives once emitted. 0 = forever.</param>
/// <param name="Frequency">Ignored if Explode is set to true. Frequency is how often to emit a particle. 0 = never emit, 0.1 = 1 particle every 0.1 seconds, 5 = 1 particle every 5 seconds.</param>
/// <param name="Quantity">How many particles to launch. 0 = "all of the particles".</param>
public void start(bool Explode=true, float Lifespan=0, float Frequency=0.1f, uint Quantity=0)
{
revive();
Visible = true;
on = true;
_explode = Explode;
lifespan = Lifespan;
frequency = Frequency;
_quantity += Quantity;
_counter = 0;
_timer = 0;
}
/// <summary>
/// This function can be used both internally and externally to emit the next particle.
/// </summary>
public void emitParticle()
{
var particle = recycle(typeof(FlxBasic)) as FlxParticle;
if (particle == null)
{
throw new Exception("RecyclingWTFException");
}
particle.Lifespan = lifespan;
particle.Elasticity = bounce;
particle.reset(X - ((int)particle.Width >> 1) + FlxG.random() * Width, Y - ((int)particle.Height >> 1) + FlxG.random() * Height);
particle.Visible = true;
if (minParticleSpeed.X != maxParticleSpeed.X)
{
particle.Velocity.X = minParticleSpeed.X + FlxG.random()*(maxParticleSpeed.X - minParticleSpeed.X);
}
else
{
particle.Velocity.X = minParticleSpeed.X;
}
if (minParticleSpeed.Y != maxParticleSpeed.Y)
{
particle.Velocity.Y = minParticleSpeed.Y + FlxG.random()*(maxParticleSpeed.Y - minParticleSpeed.Y);
}
else
{
particle.Velocity.Y = minParticleSpeed.Y;
}
particle.Acceleration.Y = gravity;
if (minRotation != maxRotation)
{
particle.AngularVelocity = minRotation + FlxG.random()*(maxRotation - minRotation);
}
else
{
particle.AngularVelocity = minRotation;
}
if (particle.AngularVelocity != 0)
{
particle.Angle = FlxG.random() * 360 - 180;
}
particle.Visible = true;
particle.Drag.X = particleDrag.X;
particle.Drag.Y = particleDrag.Y;
particle.onEmit();
}
/// <summary>
/// A more compact way of setting the width and height of the emitter.
/// </summary>
/// <param name="Width">The desired width of the emitter (particles are spawned randomly within these dimensions).</param>
/// <param name="Height">The desired height of the emitter.</param>
public void setSize(uint Width, uint Height)
{
((FlxObject) this).Width = Width;
((FlxObject) this).Height = Height;
}
/// <summary>
/// A more compact way of setting the X velocity range of the emitter.
/// </summary>
/// <param name="Min">The minimum value for this range.</param>
/// <param name="Max">The maximum value for this range.</param>
public void setXSpeed(float Min=0, float Max=0)
{
minParticleSpeed.X = Min;
maxParticleSpeed.X = Max;
}
/// <summary>
/// A more compact way of setting the Y velocity range of the emitter.
/// </summary>
/// <param name="Min">The minimum value for this range.</param>
/// <param name="Max">The maximum value for this range.</param>
public void setYSpeed(float Min=0, float Max=0)
{
minParticleSpeed.Y = Min;
maxParticleSpeed.Y = Max;
}
/// <summary>
/// A more compact way of setting the angular velocity constraints of the emitter.
/// </summary>
/// <param name="Min">The minimum value for this range.</param>
/// <param name="Max">The maximum value for this range.</param>
public void setRotation(float Min=0, float Max=0)
{
minRotation = Min;
maxRotation = Max;
}
/// <summary>
/// Change the emitter's midpoint to match the midpoint of a <code>FlxObject</code>.
/// </summary>
/// <param name="flxObject">The <code>FlxObject</code> that you want to sync up with.</param>
public void at(FlxObject flxObject)
{
flxObject.getMidpoint(_point);
X = _point.X - (Convert.ToInt32(Width)>>1);
Y = _point.Y - (Convert.ToInt32(Height)>>1);
}
}
}
| |
/*
* XmlDocumentType.cs - Implementation of the
* "System.Xml.XmlDocumentType" class.
*
* Copyright (C) 2002 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Xml
{
using System;
using System.Xml.Private;
#if ECMA_COMPAT
internal
#else
public
#endif
class XmlDocumentType : XmlLinkedNode
{
// Internal state.
private String name;
private String publicId;
private String systemId;
private String internalSubset;
private XmlNamedNodeMap entities;
private XmlNamedNodeMap notations;
private XmlAttributeCollection attributes;
// Constructor.
internal XmlDocumentType(XmlNode parent, String name, String publicId,
String systemId, String internalSubset)
: base(parent)
{
XmlNameTable nt = parent.FindOwnerQuick().NameTable;
this.name = name;
this.publicId = publicId;
this.systemId = systemId;
this.internalSubset = internalSubset;
entities = new XmlNamedNodeMap(this);
notations = new XmlNamedNodeMap(this);
attributes = null;
}
protected internal XmlDocumentType(String name, String publicId,
String systemId, String internalSubset,
XmlDocument doc)
: this(doc, name, publicId, systemId, internalSubset)
{
// Nothing to do here.
}
// Get the entity list for this document type.
public XmlNamedNodeMap Entities
{
get
{
return entities;
}
}
// Get the internal subset information for this document type.
public String InternalSubset
{
get
{
return internalSubset;
}
}
// Determine if this node is read-only.
public override bool IsReadOnly
{
get
{
return true;
}
}
// Get the local name of the document type.
public override String LocalName
{
get
{
return name;
}
}
// Get the qualified name of the document type.
public override String Name
{
get
{
return name;
}
}
// Get the type of this node.
public override XmlNodeType NodeType
{
get
{
return XmlNodeType.DocumentType;
}
}
// Get the notation list for this document type.
public XmlNamedNodeMap Notations
{
get
{
return notations;
}
}
// Get the public identifier for this document type.
public String PublicId
{
get
{
return publicId;
}
}
// Get the system identifier for this document type.
public String SystemId
{
get
{
return systemId;
}
}
// Clone this node.
public override XmlNode CloneNode(bool deep)
{
return OwnerDocument.CreateDocumentType
(name, publicId, systemId, internalSubset);
}
// Writes the contents of this node to a specified XmlWriter.
public override void WriteContentTo(XmlWriter w)
{
// Nothing needs to be done here for DTD nodes.
}
// Write this node and all of its contents to a specified XmlWriter.
public override void WriteTo(XmlWriter w)
{
w.WriteDocType(name, publicId, systemId, internalSubset);
}
// Get and set special attributes on this node.
internal override String GetSpecialAttribute(String name)
{
if(name == "PUBLIC")
{
return PublicId;
}
else if(name == "SYSTEM")
{
return SystemId;
}
else
{
return String.Empty;
}
}
internal override void SetSpecialAttribute(String name, String value)
{
XmlNameTable nt = FindOwnerQuick().NameTable;
if(name == "PUBLIC")
{
publicId = ((value != null) ? nt.Add(value) : String.Empty);
}
else if(name == "SYSTEM")
{
systemId = ((value != null) ? nt.Add(value) : String.Empty);
}
else
{
throw new ArgumentException
(S._("Xml_InvalidSpecialAttribute"), "name");
}
}
// Get the internal attribute collection for this node.
internal override XmlAttributeCollection AttributesInternal
{
get
{
if(attributes == null)
{
attributes = new XmlAttributeCollection(this);
attributes.Append
(new XmlSpecialAttribute(this, "PUBLIC"));
attributes.Append
(new XmlSpecialAttribute(this, "SYSTEM"));
}
return attributes;
}
}
}; // class XmlDocumentType
}; // namespace System.Xml
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.IO;
using System.Text;
using System.Collections.ObjectModel;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell.Commands;
using System.Collections.Generic;
using System.Management.Automation.Language;
using System.Management.Automation.Security;
#if CORECLR
// Use stub for SerializableAttribute
using Microsoft.PowerShell.CoreClr.Stubs;
#endif
namespace System.Management.Automation
{
/// <summary>
/// Provides information for MSH scripts that are directly executable by MSH
/// but are not built into the runspace configuration.
/// </summary>
public class ExternalScriptInfo : CommandInfo, IScriptCommandInfo
{
#region ctor
/// <summary>
/// Creates an instance of the ExternalScriptInfo class with the specified name, and path.
/// </summary>
///
/// <param name="name">
/// The name of the script.
/// </param>
///
/// <param name="path">
/// The path to the script
/// </param>
///
/// <param name="context">
/// The context of the currently running engine.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="context"/> is null.
/// </exception>
///
/// <exception cref="ArgumentException">
/// If <paramref name="path"/> is null or empty.
/// </exception>
///
internal ExternalScriptInfo(string name, string path, ExecutionContext context)
: base(name, CommandTypes.ExternalScript, context)
{
if (String.IsNullOrEmpty(path))
{
throw PSTraceSource.NewArgumentException("path");
}
Diagnostics.Assert(IO.Path.IsPathRooted(path), "Caller makes sure that 'path' is already resolved.");
// Path might contian short-name syntax such as 'DOCUME~1'. Use Path.GetFullPath to expand the short name
_path = IO.Path.GetFullPath(path);
CommonInitialization();
}
/// <summary>
/// Creates an instance of ExternalScriptInfo that has no ExecutionContext.
/// This is used exclusively to pass it to the AuthorizationManager that just uses the path parameter
/// </summary>
/// <param name="name">
/// The name of the script.
/// </param>
///
/// <param name="path">
/// The path to the script
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="path"/> is null or empty.
/// </exception>
///
internal ExternalScriptInfo(string name, string path) : base(name, CommandTypes.ExternalScript)
{
if (String.IsNullOrEmpty(path))
{
throw PSTraceSource.NewArgumentException("path");
}
Diagnostics.Assert(IO.Path.IsPathRooted(path), "Caller makes sure that 'path' is already resolved.");
// Path might contian short-name syntax such as 'DOCUME~1'. Use Path.GetFullPath to expand the short name
_path = IO.Path.GetFullPath(path);
CommonInitialization();
}
/// <summary>
/// This is a copy constructor, used primarily for get-command.
/// </summary>
internal ExternalScriptInfo(ExternalScriptInfo other)
: base(other)
{
_path = other._path;
CommonInitialization();
}
/// <summary>
/// Common initialization for all constructors
/// </summary>
private void CommonInitialization()
{
// Assume external scripts are untrusted by defult (for Get-Command, etc)
// until we've actually parsed their script block.
if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.None)
{
// Get the lock down policy with no handle. This only impacts command discovery,
// as the real language mode assignment will be done when we read the script
// contents.
SystemEnforcementMode scriptSpecificPolicy = SystemPolicy.GetLockdownPolicy(_path, null);
if (scriptSpecificPolicy != SystemEnforcementMode.Enforce)
{
this.DefiningLanguageMode = PSLanguageMode.FullLanguage;
}
else
{
this.DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage;
}
}
}
/// <summary>
/// Create a copy of commandInfo for GetCommandCommand so that we can generate parameter
/// sets based on an argument list (so we can get the dynamic parameters.)
/// </summary>
internal override CommandInfo CreateGetCommandCopy(object[] argumentList)
{
ExternalScriptInfo copy = new ExternalScriptInfo(this) { IsGetCommandCopy = true, Arguments = argumentList };
return copy;
}
#endregion ctor
internal override HelpCategory HelpCategory
{
get { return HelpCategory.ExternalScript; }
}
/// <summary>
/// Gets the path to the script file.
/// </summary>
public string Path
{
get { return _path; }
}
private readonly string _path = String.Empty;
/// <summary>
/// Gets the path to the script file.
/// </summary>
public override string Definition
{
get { return Path; }
}
/// <summary>
/// Gets the source of this command
/// </summary>
public override string Source
{
get { return this.Definition; }
}
/// <summary>
/// Returns the syntax of a command
/// </summary>
internal override string Syntax
{
get
{
StringBuilder synopsis = new StringBuilder();
foreach (CommandParameterSetInfo parameterSet in ParameterSets)
{
synopsis.AppendLine(
String.Format(
Globalization.CultureInfo.CurrentCulture,
"{0} {1}",
Name,
parameterSet));
}
return synopsis.ToString();
}
}
/// <summary>
/// Determine the visibility for this script...
/// </summary>
public override SessionStateEntryVisibility Visibility
{
get
{
if (Context == null) return SessionStateEntryVisibility.Public;
return Context.EngineSessionState.CheckScriptVisibility(_path);
}
set { throw PSTraceSource.NewNotImplementedException(); }
}
/// <summary>
/// The script block that represents the external script
/// </summary>
///
public ScriptBlock ScriptBlock
{
get
{
if (_scriptBlock == null)
{
// Skip ShouldRun check for .psd1 files.
// Use ValidateScriptInfo() for explicitly validating the checkpolicy for psd1 file.
//
if (!_path.EndsWith(".psd1", StringComparison.OrdinalIgnoreCase))
{
ValidateScriptInfo(null);
}
// parse the script into an expression tree...
ScriptBlock newScriptBlock = ScriptBlock.Create(new Parser(), _path, ScriptContents);
this.ScriptBlock = newScriptBlock;
}
return _scriptBlock;
}
private set
{
_scriptBlock = value;
if (value != null)
{
_scriptBlock.LanguageMode = this.DefiningLanguageMode;
}
}
}
private ScriptBlock _scriptBlock;
private ScriptBlockAst _scriptBlockAst;
internal ScriptBlockAst GetScriptBlockAst()
{
var scriptContents = ScriptContents;
if (_scriptBlock == null)
{
this.ScriptBlock = ScriptBlock.TryGetCachedScriptBlock(_path, scriptContents);
}
if (_scriptBlock != null)
{
return (ScriptBlockAst)_scriptBlock.Ast;
}
if (_scriptBlockAst == null)
{
ParseError[] errors;
Parser parser = new Parser();
_scriptBlockAst = parser.Parse(_path, ScriptContents, null, out errors, ParseMode.Default);
if (errors.Length == 0)
{
this.ScriptBlock = new ScriptBlock(_scriptBlockAst, isFilter: false);
ScriptBlock.CacheScriptBlock(_scriptBlock.Clone(), _path, scriptContents);
}
}
return _scriptBlockAst;
}
/// <summary>
/// Validates the external script info
/// </summary>
///
/// <param name="host"></param>
///
public void ValidateScriptInfo(Host.PSHost host)
{
if (!_signatureChecked)
{
ExecutionContext context = Context ?? LocalPipeline.GetExecutionContextFromTLS();
ReadScriptContents();
// We have no way to check the signature w/o context because we don't have
// an AuthorizationManager. This can happen during initialization when trying
// to get the CommandMetadata for a script (either to prepopulate the metadata
// or creating a proxy). If context can be null under any other circumstances,
// we need to make sure it's acceptable if the parser is invoked on unsigned scripts.
if (context != null)
{
CommandDiscovery.ShouldRun(context, host, this, CommandOrigin.Internal);
_signatureChecked = true;
}
}
}
/// <summary>
/// The output type(s) is specified in the script block
/// </summary>
public override ReadOnlyCollection<PSTypeName> OutputType
{
get { return ScriptBlock.OutputType; }
}
internal bool SignatureChecked
{
set { _signatureChecked = value; }
}
private bool _signatureChecked;
#region Internal
/// <summary>
/// The command metadata for the script.
/// </summary>
internal override CommandMetadata CommandMetadata
{
get
{
return _commandMetadata ??
(_commandMetadata =
new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS()));
}
}
private CommandMetadata _commandMetadata;
/// <summary>
/// True if the command has dynamic parameters, false otherwise.
/// </summary>
internal override bool ImplementsDynamicParameters
{
get
{
try
{
return ScriptBlock.HasDynamicParameters;
}
catch (ParseException) { }
catch (ScriptRequiresException) { }
// If we got here, there was some sort of parsing exception. We'll just
// ignore it and assume the script does not implement dynamic parameters.
// Futhermore, we'll clear out the fields so that the next attempt to
// access ScriptBlock will result in an exception that doesn't get ignored.
_scriptBlock = null;
_scriptContents = null;
return false;
}
}
#endregion Internal
private ScriptRequirements GetRequiresData()
{
return GetScriptBlockAst().ScriptRequirements;
}
internal string RequiresApplicationID
{
get
{
var data = GetRequiresData();
return data == null ? null : data.RequiredApplicationId;
}
}
internal uint ApplicationIDLineNumber
{
get { return 0; }
}
internal Version RequiresPSVersion
{
get
{
var data = GetRequiresData();
return data == null ? null : data.RequiredPSVersion;
}
}
internal IEnumerable<string> RequiresPSEditions
{
get
{
var data = GetRequiresData();
return data == null ? null : data.RequiredPSEditions;
}
}
internal IEnumerable<ModuleSpecification> RequiresModules
{
get
{
var data = GetRequiresData();
return data == null ? null : data.RequiredModules;
}
}
internal bool RequiresElevation
{
get
{
var data = GetRequiresData();
return data == null ? false : data.IsElevationRequired;
}
}
internal uint PSVersionLineNumber
{
get { return 0; }
}
internal IEnumerable<PSSnapInSpecification> RequiresPSSnapIns
{
get
{
var data = GetRequiresData();
return data == null ? null : data.RequiresPSSnapIns;
}
}
/// <summary>
/// Gets the original contents of the script.
/// </summary>
public string ScriptContents
{
get
{
if (_scriptContents == null)
{
ReadScriptContents();
}
return _scriptContents;
}
}
private string _scriptContents;
/// <summary>
/// Gets the original encoding of the script.
/// </summary>
public Encoding OriginalEncoding
{
get
{
if (_scriptContents == null)
{
ReadScriptContents();
}
return _originalEncoding;
}
}
private Encoding _originalEncoding;
private void ReadScriptContents()
{
if (_scriptContents == null)
{
// make sure we can actually load the script and that it's non-empty
// before we call it.
// Note, although we are passing ASCII as the encoding, the StreamReader
// class still obeys the byte order marks at the beginning of the file
// if present. If not present, then ASCII is used as the default encoding.
try
{
using (FileStream readerStream = new FileStream(_path, FileMode.Open, FileAccess.Read))
{
Encoding defaultEncoding = ClrFacade.GetDefaultEncoding();
Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = readerStream.SafeFileHandle;
using (StreamReader scriptReader = new StreamReader(readerStream, defaultEncoding))
{
_scriptContents = scriptReader.ReadToEnd();
_originalEncoding = scriptReader.CurrentEncoding;
// Check if this came from a trusted path. If so, set its language mode to FullLanguage.
if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.None)
{
SystemEnforcementMode scriptSpecificPolicy = SystemPolicy.GetLockdownPolicy(_path, safeFileHandle);
if (scriptSpecificPolicy != SystemEnforcementMode.Enforce)
{
this.DefiningLanguageMode = PSLanguageMode.FullLanguage;
}
else
{
this.DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage;
}
}
else
{
if (this.Context != null)
{
this.DefiningLanguageMode = this.Context.LanguageMode;
}
}
}
}
}
catch (ArgumentException e)
{
// This catches PSArgumentException as well.
ThrowCommandNotFoundException(e);
}
catch (IOException e)
{
ThrowCommandNotFoundException(e);
}
catch (NotSupportedException e)
{
ThrowCommandNotFoundException(e);
}
catch (UnauthorizedAccessException e)
{
// this is unadvertised exception thrown by the StreamReader ctor when
// no permission to read the script file
ThrowCommandNotFoundException(e);
}
}
}
private static void ThrowCommandNotFoundException(Exception innerException)
{
CommandNotFoundException cmdE = new CommandNotFoundException(innerException.Message, innerException);
throw cmdE;
}
} // ExternalScriptInfo
/// <summary>
/// Thrown when fail to parse #requires statements. Caught by CommandDiscovery.
/// </summary>
internal class ScriptRequiresSyntaxException : ScriptRequiresException
{
internal ScriptRequiresSyntaxException(string message)
: base(message)
{
}
}
/// <summary>
/// Defines the name and version tuple of a PSSnapin
/// </summary>
[Serializable]
public class PSSnapInSpecification
{
internal PSSnapInSpecification(string psSnapinName)
{
PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(psSnapinName);
Name = psSnapinName;
Version = null;
}
/// <summary>
/// The name of the snapin.
/// </summary>
public string Name { get; internal set; }
/// <summary>
/// The version of the snapin.
/// </summary>
public Version Version { get; internal set; }
}
} // namespace System.Management.Automation
| |
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.EventSystems;
using System.Linq;
using MoonSharp.Interpreter;
namespace Fungus
{
/// <summary>
/// Presents multiple choice buttons to the players.
/// </summary>
public class MenuDialog : MonoBehaviour
{
[Tooltip("Automatically select the first interactable button when the menu is shown.")]
[SerializeField] protected bool autoSelectFirstButton = false;
protected Button[] cachedButtons;
protected Slider cachedSlider;
private int nextOptionIndex;
#region Public members
/// <summary>
/// Currently active Menu Dialog used to display Menu options
/// </summary>
public static MenuDialog ActiveMenuDialog { get; set; }
/// <summary>
/// A cached list of button objects in the menu dialog.
/// </summary>
/// <value>The cached buttons.</value>
public virtual Button[] CachedButtons { get { return cachedButtons; } }
/// <summary>
/// A cached slider object used for the timer in the menu dialog.
/// </summary>
/// <value>The cached slider.</value>
public virtual Slider CachedSlider { get { return cachedSlider; } }
/// <summary>
/// Sets the active state of the Menu Dialog gameobject.
/// </summary>
public virtual void SetActive(bool state)
{
gameObject.SetActive(state);
}
/// <summary>
/// Returns a menu dialog by searching for one in the scene or creating one if none exists.
/// </summary>
public static MenuDialog GetMenuDialog()
{
if (ActiveMenuDialog == null)
{
// Use first Menu Dialog found in the scene (if any)
var md = GameObject.FindObjectOfType<MenuDialog>();
if (md != null)
{
ActiveMenuDialog = md;
}
if (ActiveMenuDialog == null)
{
// Auto spawn a menu dialog object from the prefab
GameObject prefab = Resources.Load<GameObject>("Prefabs/MenuDialog");
if (prefab != null)
{
GameObject go = Instantiate(prefab) as GameObject;
go.SetActive(false);
go.name = "MenuDialog";
ActiveMenuDialog = go.GetComponent<MenuDialog>();
}
}
}
return ActiveMenuDialog;
}
protected virtual void Awake()
{
Button[] optionButtons = GetComponentsInChildren<Button>();
cachedButtons = optionButtons;
Slider timeoutSlider = GetComponentInChildren<Slider>();
cachedSlider = timeoutSlider;
if (Application.isPlaying)
{
// Don't auto disable buttons in the editor
Clear();
}
CheckEventSystem();
}
// There must be an Event System in the scene for Say and Menu input to work.
// This method will automatically instantiate one if none exists.
protected virtual void CheckEventSystem()
{
EventSystem eventSystem = GameObject.FindObjectOfType<EventSystem>();
if (eventSystem == null)
{
// Auto spawn an Event System from the prefab
GameObject prefab = Resources.Load<GameObject>("Prefabs/EventSystem");
if (prefab != null)
{
GameObject go = Instantiate(prefab) as GameObject;
go.name = "EventSystem";
}
}
}
protected virtual void OnEnable()
{
// The canvas may fail to update if the menu dialog is enabled in the first game frame.
// To fix this we just need to force a canvas update when the object is enabled.
Canvas.ForceUpdateCanvases();
}
protected virtual IEnumerator WaitForTimeout(float timeoutDuration, Block targetBlock)
{
float elapsedTime = 0;
Slider timeoutSlider = CachedSlider;
while (elapsedTime < timeoutDuration)
{
if (timeoutSlider != null)
{
float t = 1f - elapsedTime / timeoutDuration;
timeoutSlider.value = t;
}
elapsedTime += Time.deltaTime;
yield return null;
}
Clear();
gameObject.SetActive(false);
HideSayDialog();
if (targetBlock != null)
{
targetBlock.StartExecution();
}
}
protected IEnumerator CallBlock(Block block)
{
yield return new WaitForEndOfFrame();
block.StartExecution();
}
protected IEnumerator CallLuaClosure(LuaEnvironment luaEnv, Closure callback)
{
yield return new WaitForEndOfFrame();
if (callback != null)
{
luaEnv.RunLuaFunction(callback, true);
}
}
/// <summary>
/// Clear all displayed options in the Menu Dialog.
/// </summary>
public virtual void Clear()
{
StopAllCoroutines();
//if something was shown notify that we are ending
if(nextOptionIndex != 0)
MenuSignals.DoMenuEnd(this);
nextOptionIndex = 0;
var optionButtons = CachedButtons;
for (int i = 0; i < optionButtons.Length; i++)
{
var button = optionButtons[i];
button.onClick.RemoveAllListeners();
}
for (int i = 0; i < optionButtons.Length; i++)
{
var button = optionButtons[i];
if (button != null)
{
button.transform.SetSiblingIndex(i);
button.gameObject.SetActive(false);
}
}
Slider timeoutSlider = CachedSlider;
if (timeoutSlider != null)
{
timeoutSlider.gameObject.SetActive(false);
}
}
/// <summary>
/// Hides any currently displayed Say Dialog.
/// </summary>
public virtual void HideSayDialog()
{
var sayDialog = SayDialog.GetSayDialog();
if (sayDialog != null)
{
sayDialog.FadeWhenDone = true;
}
}
/// <summary>
/// Adds the option to the list of displayed options. Calls a Block when selected.
/// Will cause the Menu dialog to become visible if it is not already visible.
/// </summary>
/// <returns><c>true</c>, if the option was added successfully.</returns>
/// <param name="text">The option text to display on the button.</param>
/// <param name="interactable">If false, the option is displayed but is not selectable.</param>
/// <param name="hideOption">If true, the option is not displayed but the menu knows that option can or did exist</param>
/// <param name="targetBlock">Block to execute when the option is selected.</param>
public virtual bool AddOption(string text, bool interactable, bool hideOption, Block targetBlock)
{
var block = targetBlock;
UnityEngine.Events.UnityAction action = delegate
{
EventSystem.current.SetSelectedGameObject(null);
StopAllCoroutines();
// Stop timeout
Clear();
HideSayDialog();
if (block != null)
{
var flowchart = block.GetFlowchart();
#if UNITY_EDITOR
// Select the new target block in the Flowchart window
flowchart.SelectedBlock = block;
#endif
gameObject.SetActive(false);
// Use a coroutine to call the block on the next frame
// Have to use the Flowchart gameobject as the MenuDialog is now inactive
flowchart.StartCoroutine(CallBlock(block));
}
};
return AddOption(text, interactable, hideOption, action);
}
/// <summary>
/// Adds the option to the list of displayed options, calls a Lua function when selected.
/// Will cause the Menu dialog to become visible if it is not already visible.
/// </summary>
/// <returns><c>true</c>, if the option was added successfully.</returns>
public virtual bool AddOption(string text, bool interactable, LuaEnvironment luaEnv, Closure callBack)
{
if (!gameObject.activeSelf)
{
gameObject.SetActive(true);
}
// Copy to local variables
LuaEnvironment env = luaEnv;
Closure call = callBack;
UnityEngine.Events.UnityAction action = delegate
{
StopAllCoroutines();
// Stop timeout
Clear();
HideSayDialog();
// Use a coroutine to call the callback on the next frame
StartCoroutine(CallLuaClosure(env, call));
};
return AddOption(text, interactable, false, action);
}
/// <summary>
/// Adds the option to the list of displayed options. Calls a Block when selected.
/// Will cause the Menu dialog to become visible if it is not already visible.
/// </summary>
/// <returns><c>true</c>, if the option was added successfully.</returns>
/// <param name="text">The option text to display on the button.</param>
/// <param name="interactable">If false, the option is displayed but is not selectable.</param>
/// <param name="hideOption">If true, the option is not displayed but the menu knows that option can or did exist</param>
/// <param name="action">Action attached to the button on the menu item</param>
private bool AddOption(string text, bool interactable, bool hideOption, UnityEngine.Events.UnityAction action)
{
if (nextOptionIndex >= CachedButtons.Length)
return false;
//if first option notify that a menu has started
if(nextOptionIndex == 0)
MenuSignals.DoMenuStart(this);
var button = cachedButtons[nextOptionIndex];
//move forward for next call
nextOptionIndex++;
//don't need to set anything on it
if (hideOption)
return true;
button.gameObject.SetActive(true);
button.interactable = interactable;
if (interactable && autoSelectFirstButton && !cachedButtons.Select(x => x.gameObject).Contains(EventSystem.current.currentSelectedGameObject))
{
EventSystem.current.SetSelectedGameObject(button.gameObject);
}
TextAdapter textAdapter = new TextAdapter();
textAdapter.InitFromGameObject(button.gameObject, true);
if (textAdapter.HasTextObject())
{
text = TextVariationHandler.SelectVariations(text);
textAdapter.Text = text;
}
button.onClick.AddListener(action);
return true;
}
/// <summary>
/// Show a timer during which the player can select an option. Calls a Block when the timer expires.
/// </summary>
/// <param name="duration">The duration during which the player can select an option.</param>
/// <param name="targetBlock">Block to execute if the player does not select an option in time.</param>
public virtual void ShowTimer(float duration, Block targetBlock)
{
if (cachedSlider != null)
{
cachedSlider.gameObject.SetActive(true);
gameObject.SetActive(true);
StopAllCoroutines();
StartCoroutine(WaitForTimeout(duration, targetBlock));
}
}
/// <summary>
/// Show a timer during which the player can select an option. Calls a Lua function when the timer expires.
/// </summary>
public virtual IEnumerator ShowTimer(float duration, LuaEnvironment luaEnv, Closure callBack)
{
if (CachedSlider == null ||
duration <= 0f)
{
yield break;
}
CachedSlider.gameObject.SetActive(true);
StopAllCoroutines();
float elapsedTime = 0;
Slider timeoutSlider = CachedSlider;
while (elapsedTime < duration)
{
if (timeoutSlider != null)
{
float t = 1f - elapsedTime / duration;
timeoutSlider.value = t;
}
elapsedTime += Time.deltaTime;
yield return null;
}
Clear();
gameObject.SetActive(false);
HideSayDialog();
if (callBack != null)
{
luaEnv.RunLuaFunction(callBack, true);
}
}
/// <summary>
/// Returns true if the Menu Dialog is currently displayed.
/// </summary>
public virtual bool IsActive()
{
return gameObject.activeInHierarchy;
}
/// <summary>
/// Returns the number of currently displayed options.
/// </summary>
public virtual int DisplayedOptionsCount
{
get {
int count = 0;
for (int i = 0; i < cachedButtons.Length; i++)
{
var button = cachedButtons[i];
if (button.gameObject.activeSelf)
{
count++;
}
}
return count;
}
}
/// <summary>
/// Shuffle the parent order of the cached buttons, allows for randomising button order, buttons are auto reordered when cleared
/// </summary>
public void Shuffle(System.Random r)
{
for (int i = 0; i < CachedButtons.Length; i++)
{
CachedButtons[i].transform.SetSiblingIndex(r.Next(CachedButtons.Length));
}
}
#endregion
}
}
| |
// Knockout.cs
// Script#/Libraries/Knockout
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Html;
using System.Runtime.CompilerServices;
namespace KnockoutApi {
/// <summary>
/// Provides Knockout functionality.
/// </summary>
[ScriptImport]
[ScriptIgnoreNamespace]
[ScriptName("ko")]
public static class Knockout {
/// <summary>
/// Provides access to the currently registered binding handlers.
/// </summary>
[ScriptField]
public static Dictionary<string, BindingHandler> BindingHandlers {
get {
return null;
}
}
/// <summary>
/// Gets the mapping plugin which allows converting models to plain
/// objects and JSON and vice-versa.
/// </summary>
[ScriptField]
public static KnockoutMapping Mapping {
get {
return null;
}
}
/// <summary>
/// Gets the current model.
/// </summary>
/// <returns>The object represented by 'this' within a handler.</returns>
[ScriptAlias("this")]
[ScriptField]
public static object Model {
get {
return null;
}
}
/// <summary>
/// Sets up bindings using the specified model.
/// </summary>
/// <param name="model">The model.</param>
public static void ApplyBindings(object model) {
}
/// <summary>
/// Sets up bindings within the specified root element using the specified the model.
/// </summary>
/// <param name="model">The model.</param>
/// <param name="rootElement">The element to bind to.</param>
public static void ApplyBindings(object model, Element rootElement) {
}
/// <summary>
/// Set up bindings on a single node without binding any of its descendents.
/// </summary>
/// <param name="node">The node to bind to.</param>
/// <param name="bindings">An optional dictionary of bindings, pass null to let Knockout gather them from the element.</param>
/// <param name="viewModel">The view model instance.</param>
public static void ApplyBindingsToNode(Element node, Dictionary bindings, object viewModel) {
}
/// <summary>
/// Set up bindings on a single node without binding any of its descendents.
/// </summary>
/// <param name="node">The node to bind to.</param>
/// <param name="bindings">An optional dictionary of bindings, pass null to let Knockout gather them from the element.</param>
/// <param name="viewModel">The view model instance.</param>
/// <param name="bindingAttributeName">The name of the attribute which has the binding definitions.</param>
public static void ApplyBindingsToNode(Element node, Dictionary bindings, object viewModel, string bindingAttributeName) {
}
/// <summary>
/// Set up bindings on a single node without binding any of its descendents.
/// </summary>
/// <param name="rootNode">The root node to bind to.</param>
/// <param name="bindings">An optional dictionary of bindings, pass null to let Knockout gather them from the element.</param>
/// <param name="viewModel">The view model instance.</param>
/// <param name="bindingAttributeName">The name of the attribute which has the binding definitions.</param>
public static void ApplyBindingsToDescendants(Element rootNode, Dictionary bindings, object viewModel, string bindingAttributeName) {
}
/// <summary>
/// Removes all bindings from an Html Element.
/// </summary>
/// <param name="rootElement">The root node to clear all bindings from.</param>
public static void CleanNode(Element rootElement) {
}
/// <summary>
/// Creates an observable with a value computed from one or more other values.
/// </summary>
/// <typeparam name="T">The type of the observable value.</typeparam>
/// <param name="function">A function to compute the value.</param>
/// <returns>A new computed observable instance.</returns>
public static ComputedObservable<T> Computed<T>(Func<T> function) {
return null;
}
/// <summary>
/// Creates an observable with a value computed from one or more other values.
/// </summary>
/// <typeparam name="T">The type of the observable value.</typeparam>
/// <param name="options">Options for the computed observable.</param>
public static ComputedObservable<T> Computed<T>(ComputedObservableOptions<T> options) {
return null;
}
/// <summary>
/// Returns the entire binding context associated with the DOM element
/// </summary>
/// <param name="node"></param>
public static BindingContext<TRoot, TParent, T> ContextFor<TRoot, TParent, T>(Element node) {
return null;
}
/// <summary>
/// Returns the data item associated with a particular DOM element
/// </summary>
/// <param name="node"></param>
public static T DataFor<T>(Element node) {
return default(T);
}
/// <summary>
/// Returns true if the value is subscribable, false otherwise.
/// </summary>
/// <param name="value">The value to check.</param>
public static bool IsSubscribable(object value) {
return false;
}
/// <summary>
/// Returns true if the value is an observable, false otherwise.
/// </summary>
/// <param name="value">The value to check.</param>
public static bool IsObservable(object value) {
return false;
}
/// <summary>
/// Returns true if the value is an writable observable, false otherwise.
/// </summary>
/// <param name="value">The value to check.</param>
public static bool IsWriteableObservable(object value) {
return false;
}
/// <summary>
/// Creates an subscribable value.
/// </summary>
/// <typeparam name="T">The type of the subscribable.</typeparam>
/// <returns>A new subscribable value instance.</returns>
public static Subscribable<T> Subscribable<T>() {
return null;
}
/// <summary>
/// Creates an observable value.
/// </summary>
/// <typeparam name="T">The type of the observable.</typeparam>
/// <returns>A new observable value instance.</returns>
public static Observable<T> Observable<T>() {
return null;
}
/// <summary>
/// Creates an observable with an initial value.
/// </summary>
/// <typeparam name="T">The type of the observable.</typeparam>
/// <param name="initialValue">The initial value.</param>
/// <returns>A new observable value instance.</returns>
public static Observable<T> Observable<T>(T initialValue) {
return null;
}
/// <summary>
/// Creates an empty observable array.
/// </summary>
/// <returns>A new observable array.</returns>
/// <typeparam name="T">The type of items in the array.</typeparam>
public static ObservableArray<T> ObservableArray<T>() {
return null;
}
/// <summary>
/// Creates an observable array with some initial items.
/// </summary>
/// <param name="initialItems">A sequence of initial items.</param>
/// <returns>A new observable array.</returns>
/// <typeparam name="T">The type of items in the array.</typeparam>
public static ObservableArray<T> ObservableArray<T>(IEnumerable<T> initialItems) {
return null;
}
/// <summary>
/// Converts a model into the equivalent JSON representation.
/// </summary>
/// <param name="model">The model object to convert.</param>
/// <returns>The JSON string representing the model data.</returns>
[ScriptName("toJSON")]
public static string ToJson(object model) {
return null;
}
/// <summary>
/// Converts a model into the equivalent vanilla script object.
/// </summary>
/// <param name="model">The model object to convert.</param>
/// <returns>The vanilla script object representing the model data.</returns>
[ScriptName("toJS")]
public static object ToObject(object model) {
return null;
}
/// <summary>
/// Converts a model into the equivalent vanilla script object.
/// </summary>
/// <param name="model">The model object to convert.</param>
/// <returns>The vanilla script object representing the model data.</returns>
[ScriptName("toJS")]
public static T ToObject<T>(object model) {
return default(T);
}
/// <summary>
/// If the provided value is an observable, return its value, otherwise just pass it through.
/// </summary>
/// <param name="value">The value to unwrap.</param>
[ScriptAlias("ko.utils.unwrapObservable")]
public static T UnwrapObservable<T>(object value) {
return default(T);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Ftp.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
//-----------------------------------------------------------------------
namespace MSBuild.ExtensionPack.Communication
{
using System.Globalization;
using System.IO;
using System.Linq;
using Microsoft.Build.Framework;
using MSBuild.ExtensionPack.Communication.Extended;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>UploadFiles</i> (<b>Required:</b> Host, FileNames <b>Optional:</b> UserName, UserPassword, WorkingDirectory, RemoteDirectoryName, Port)</para>
/// <para><i>DownloadFiles</i> (<b>Required:</b> Host <b>Optional:</b> FileNames, UserName, UserPassword, WorkingDirectory, RemoteDirectoryName, Port)</para>
/// <para><i>DeleteFiles</i> (<b>Required:</b> Host, FileNames <b>Optional:</b> UserName, UserPassword, WorkingDirectory, RemoteDirectoryName, Port)</para>
/// <para><i>DeleteDirectory</i> (<b>Required:</b> Host<b>Optional:</b> UserName, UserPassword, WorkingDirectory, RemoteDirectoryName, Port)</para>
/// <para><i>CreateDirectory</i> (<b>Required:</b> Host<b>Optional:</b> UserName, UserPassword, WorkingDirectory, RemoteDirectoryName, Port)</para>
/// <para><b>Remote Execution Support:</b> NA</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// <ftpHost>localhost</ftpHost>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <Target Name="Default">
/// <ItemGroup>
/// <!-- Specify FilesToUpload -->
/// <FilesToUpload Include="C:\demo.txt" />
/// <FilesToUpload Include="C:\demo2.txt" />
/// </ItemGroup>
/// <MSBuild.ExtensionPack.Communication.Ftp TaskAction="UploadFiles" Host="$(ftpHost)" FileNames="@(FilesToUpload)"/>
/// <ItemGroup>
/// <!-- Specify the files to Download-->
/// <FilesToDownload Include="demo2.txt" />
/// <FilesToDownload Include="demo.txt" />
/// </ItemGroup>
/// <MSBuild.ExtensionPack.Communication.Ftp TaskAction="DownloadFiles" Host="$(ftpHost)" FileNames="@(FilesToDownload)" WorkingDirectory="C:\FtpWorkingFolder"/>
/// <MSBuild.ExtensionPack.Communication.Ftp TaskAction="CreateDirectory" Host="$(ftpHost)" RemoteDirectoryName="NewFolder1"/>
/// <MSBuild.ExtensionPack.Communication.Ftp TaskAction="CreateDirectory" Host="$(ftpHost)" RemoteDirectoryName="NewFolder2"/>
/// <MSBuild.ExtensionPack.Communication.Ftp TaskAction="DeleteDirectory" Host="$(ftpHost)" RemoteDirectoryName="NewFolder1"/>
/// <MSBuild.ExtensionPack.Communication.Ftp TaskAction="DeleteFiles" Host="$(ftpHost)" FileNames="@(FilesToDownload)" />
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
[HelpUrl("http://www.msbuildextensionpack.com/help/3.5.12.0/html/e38221c2-c686-2a47-489c-ea2ef10d915b.htm")]
public class Ftp : BaseTask
{
private const string UploadFilesTaskAction = "UploadFiles";
private const string DownloadFilesTaskAction = "DownloadFiles";
private const string DeleteFilesTaskAction = "DeleteFiles";
private const string DeleteDirectoryTaskAction = "DeleteDirectory";
private const string CreateDirectoryTaskAction = "CreateDirectory";
[DropdownValue(CreateDirectoryTaskAction)]
[DropdownValue(DeleteDirectoryTaskAction)]
[DropdownValue(DeleteFilesTaskAction)]
[DropdownValue(DownloadFilesTaskAction)]
[DropdownValue(UploadFilesTaskAction)]
public override string TaskAction
{
get { return base.TaskAction; }
set { base.TaskAction = value; }
}
/// <summary>
/// Sets the Host of the FTP Site.
/// </summary>
[Required]
[TaskAction(CreateDirectoryTaskAction, true)]
[TaskAction(DeleteDirectoryTaskAction, true)]
[TaskAction(DeleteFilesTaskAction, true)]
[TaskAction(DownloadFilesTaskAction, true)]
[TaskAction(UploadFilesTaskAction, true)]
public string Host { get; set; }
/// <summary>
/// Sets the Remote Path to connect to the FTP Site
/// </summary>
[TaskAction(CreateDirectoryTaskAction, true)]
[TaskAction(DeleteDirectoryTaskAction, true)]
[TaskAction(DeleteFilesTaskAction, false)]
[TaskAction(DownloadFilesTaskAction, false)]
[TaskAction(UploadFilesTaskAction, false)]
public string RemoteDirectoryName { get; set; }
/// <summary>
/// Sets the working directory on the local machine
/// </summary>
[TaskAction(CreateDirectoryTaskAction, false)]
[TaskAction(DeleteDirectoryTaskAction, false)]
[TaskAction(DeleteFilesTaskAction, false)]
[TaskAction(DownloadFilesTaskAction, false)]
[TaskAction(UploadFilesTaskAction, false)]
public string WorkingDirectory { get; set; }
/// <summary>
/// The port used to connect to the ftp server.
/// </summary>
[TaskAction(CreateDirectoryTaskAction, false)]
[TaskAction(DeleteDirectoryTaskAction, false)]
[TaskAction(DeleteFilesTaskAction, false)]
[TaskAction(DownloadFilesTaskAction, false)]
[TaskAction(UploadFilesTaskAction, false)]
public int Port { get; set; }
/// <summary>
/// The list of files that needs to be transfered over FTP
/// </summary>
[TaskAction(CreateDirectoryTaskAction, false)]
[TaskAction(DeleteDirectoryTaskAction, false)]
[TaskAction(DeleteFilesTaskAction, true)]
[TaskAction(DownloadFilesTaskAction, false)]
[TaskAction(UploadFilesTaskAction, true)]
public ITaskItem[] FileNames { get; set; }
/// <summary>
/// Performs the action of this task.
/// </summary>
protected override void InternalExecute()
{
if (string.IsNullOrEmpty(this.Host))
{
this.Log.LogError("The required host attribute has not been set for FTP.");
return;
}
switch (this.TaskAction)
{
case CreateDirectoryTaskAction:
this.CreateDirectory();
break;
case DeleteDirectoryTaskAction:
this.DeleteDirectory();
break;
case DeleteFilesTaskAction:
this.DeleteFiles();
break;
case DownloadFilesTaskAction:
this.DownloadFiles();
break;
case UploadFilesTaskAction:
this.UploadFiles();
break;
default:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid Task Action passed: {0}", this.TaskAction));
return;
}
}
/// <summary>
/// Creates a new Ftp directory on the ftp server.
/// </summary>
private void CreateDirectory()
{
if (string.IsNullOrEmpty(this.RemoteDirectoryName))
{
this.Log.LogError("The required RemoteDirectoryName attribute has not been set for FTP.");
return;
}
using (FtpConnection ftpConnection = this.CreateFtpConnection())
{
ftpConnection.LogOn();
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Creating Directory: {0}", this.RemoteDirectoryName));
try
{
ftpConnection.CreateDirectory(this.RemoteDirectoryName);
}
catch (FtpException ex)
{
if (ex.Message.Contains("550"))
{
return;
}
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "There was an error creating ftp directory: {0}. The Error Details are \"{1}\" and error code is {2} ", this.RemoteDirectoryName, ex.Message, ex.ErrorCode));
}
}
}
/// <summary>
/// Deletes an Ftp directory on the ftp server.
/// </summary>
private void DeleteDirectory()
{
if (string.IsNullOrEmpty(this.RemoteDirectoryName))
{
this.Log.LogError("The required RemoteDirectoryName attribute has not been set for FTP.");
return;
}
using (FtpConnection ftpConnection = this.CreateFtpConnection())
{
ftpConnection.LogOn();
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Deleting Directory: {0}", this.RemoteDirectoryName));
try
{
ftpConnection.DeleteDirectory(this.RemoteDirectoryName);
}
catch (FtpException ex)
{
if (ex.Message.Contains("550"))
{
return;
}
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "There was an error deleting ftp directory: {0}. The Error Details are \"{1}\" and error code is {2} ", this.RemoteDirectoryName, ex.Message, ex.ErrorCode));
}
}
}
/// <summary>
/// Delete given files from the FTP Directory
/// </summary>
private void DeleteFiles()
{
if (this.FileNames == null)
{
this.Log.LogError("The required FileNames attribute has not been set for FTP.");
return;
}
using (FtpConnection ftpConnection = this.CreateFtpConnection())
{
ftpConnection.LogOn();
this.LogTaskMessage("Deleting Files");
if (!string.IsNullOrEmpty(this.RemoteDirectoryName))
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Current Directory: {0}", this.RemoteDirectoryName));
ftpConnection.SetCurrentDirectory(this.RemoteDirectoryName);
}
foreach (string fileName in this.FileNames.Select(item => item.ItemSpec))
{
try
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Deleting: {0}", fileName));
ftpConnection.DeleteFile(fileName);
}
catch (FtpException ex)
{
if (ex.Message.Contains("550"))
{
continue;
}
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "There was an error in deleting file: {0}. The Error Details are \"{1}\" and error code is {2} ", fileName, ex.Message, ex.ErrorCode));
}
}
}
}
/// <summary>
/// Upload Files
/// </summary>
private void UploadFiles()
{
if (this.FileNames == null)
{
this.Log.LogError("The required fileNames attribute has not been set for FTP.");
return;
}
using (FtpConnection ftpConnection = this.CreateFtpConnection())
{
this.LogTaskMessage("Uploading Files");
if (!string.IsNullOrEmpty(this.WorkingDirectory))
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Local Directory: {0}", this.WorkingDirectory));
FtpConnection.SetLocalDirectory(this.WorkingDirectory);
}
ftpConnection.LogOn();
if (!string.IsNullOrEmpty(this.RemoteDirectoryName))
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Current Directory: {0}", this.RemoteDirectoryName));
ftpConnection.SetCurrentDirectory(this.RemoteDirectoryName);
}
foreach (string fileName in this.FileNames.Select(item => item.ItemSpec))
{
try
{
if (File.Exists(fileName))
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Uploading: {0}", fileName));
ftpConnection.PutFile(fileName);
}
}
catch (FtpException ex)
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "There was an error uploading file: {0}. The Error Details are \"{1}\" and error code is {2} ", fileName, ex.Message, ex.ErrorCode));
}
}
}
}
/// <summary>
/// Download Files
/// </summary>
private void DownloadFiles()
{
using (FtpConnection ftpConnection = this.CreateFtpConnection())
{
if (!string.IsNullOrEmpty(this.WorkingDirectory))
{
if (!Directory.Exists(this.WorkingDirectory))
{
Directory.CreateDirectory(this.WorkingDirectory);
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Local Directory: {0}", this.WorkingDirectory));
FtpConnection.SetLocalDirectory(this.WorkingDirectory);
}
ftpConnection.LogOn();
if (!string.IsNullOrEmpty(this.RemoteDirectoryName))
{
ftpConnection.SetCurrentDirectory(this.RemoteDirectoryName);
}
this.LogTaskMessage("Downloading Files");
if (this.FileNames == null)
{
FtpFileInfo[] filesToDownload = ftpConnection.GetFiles();
foreach (FtpFileInfo fileToDownload in filesToDownload)
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Downloading: {0}", fileToDownload));
ftpConnection.GetFile(fileToDownload.Name, false);
}
}
else
{
foreach (string fileName in this.FileNames.Select(item => item.ItemSpec.Trim()))
{
try
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Downloading: {0}", fileName));
ftpConnection.GetFile(fileName, false);
}
catch (FtpException ex)
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "There was an error downloading file: {0}. The Error Details are \"{1}\" and error code is {2} ", fileName, ex.Message, ex.ErrorCode));
}
}
}
}
}
/// <summary>
/// Creates an FTP Connection object
/// </summary>
/// <returns>An initialised FTP Connection</returns>
private FtpConnection CreateFtpConnection()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Connecting to FTP Host: {0}", this.Host));
if (!string.IsNullOrEmpty(this.UserName))
{
return this.Port != 0 ? new FtpConnection(this.Host, this.Port, this.UserName, this.UserPassword) : new FtpConnection(this.Host, this.UserName, this.UserPassword);
}
return this.Port != 0 ? new FtpConnection(this.Host, this.Port) : new FtpConnection(this.Host);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using TestAndRemember.Models;
using TestAndRemember.Models.AccountViewModels;
using TestAndRemember.Services;
namespace TestAndRemember.Controllers
{
[Authorize]
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<AccountController>();
}
//
// GET: /Account/Login
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation(1, "User logged in.");
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning(2, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/Register
[HttpGet]
[AllowAnonymous]
public IActionResult Register(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
//var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
// $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User created a new account with password.");
return RedirectToLocal(returnUrl);
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LogOff()
{
await _signInManager.SignOutAsync();
_logger.LogInformation(4, "User logged out.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return Challenge(properties, provider);
}
//
// GET: /Account/ExternalLoginCallback
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
return View(nameof(Login));
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction(nameof(Login));
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
_logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
// If the user does not have an account, then ask the user to create an account.
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
var email = info.Principal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
// GET: /Account/ConfirmEmail
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GeneratePasswordResetTokenAsync(user);
//var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Reset Password",
// $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");
//return View("ForgotPasswordConfirmation");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPasswordConfirmation()
{
return View();
}
//
// GET: /Account/SendCode
[HttpGet]
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
// Generate the token and send it
var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
if (string.IsNullOrWhiteSpace(code))
{
return View("Error");
}
var message = "Your security code is: " + code;
if (model.SelectedProvider == "Email")
{
await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message);
}
else if (model.SelectedProvider == "Phone")
{
await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message);
}
return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/VerifyCode
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{
// Require that the user has already logged in via username/password or external login
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
return RedirectToLocal(model.ReturnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning(7, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid code.");
return View(model);
}
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
#endregion
}
}
| |
//TODO - object initialization syntax cleanup
using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
//http://digitalx.org/cue-sheet/index.html "all cue sheet information is a straight 1:1 copy from the cdrwin helpfile"
//http://www.gnu.org/software/libcdio/libcdio.html#Sectors
//this is actually a great reference. they use LSN instead of LBA.. maybe a good idea for us
namespace BizHawk.Emulation.DiscSystem.CUE
{
/// <summary>
/// Performs minimum parse processing on a cue file
/// </summary>
class ParseCueJob : DiscJob
{
/// <summary>
/// input: the cue string to parse
/// </summary>
public string IN_CueString;
/// <summary>
/// output: the resulting minimally-processed cue file
/// </summary>
public CUE_File OUT_CueFile;
/// <summary>
/// Indicates whether parsing will be strict or lenient
/// </summary>
public bool IN_Strict = false;
class CueLineParser
{
int index;
string str;
public bool EOF;
public CueLineParser(string line)
{
str = line;
}
public string ReadPath() { return ReadToken(Mode.Quotable); }
public string ReadToken() { return ReadToken(Mode.Normal); }
public string ReadLine()
{
int len = str.Length;
string ret = str.Substring(index, len - index);
index = len;
EOF = true;
return ret;
}
enum Mode
{
Normal, Quotable
}
string ReadToken(Mode mode)
{
if (EOF) return null;
bool isPath = mode == Mode.Quotable;
int startIndex = index;
bool inToken = false;
bool inQuote = false;
for (; ; )
{
bool done = false;
char c = str[index];
bool isWhiteSpace = (c == ' ' || c == '\t');
if (isWhiteSpace)
{
if (inQuote)
index++;
else
{
if (inToken)
done = true;
else
index++;
}
}
else
{
bool startedQuote = false;
if (!inToken)
{
startIndex = index;
if (isPath && c == '"')
startedQuote = inQuote = true;
inToken = true;
}
switch (str[index])
{
case '"':
index++;
if (inQuote && !startedQuote)
{
done = true;
}
break;
case '\\':
index++;
break;
default:
index++;
break;
}
}
if (index == str.Length)
{
EOF = true;
done = true;
}
if (done) break;
}
string ret = str.Substring(startIndex, index - startIndex);
if (mode == Mode.Quotable)
ret = ret.Trim('"');
return ret;
}
}
void LoadFromString(ParseCueJob job)
{
string cueString = job.IN_CueString;
TextReader tr = new StringReader(cueString);
for (; ; )
{
job.CurrentLine++;
string line = tr.ReadLine();
if (line == null) break;
line = line.Trim();
if (line == "") continue;
var clp = new CueLineParser(line);
string key = clp.ReadToken().ToUpperInvariant();
//remove nonsense at beginning
if (!IN_Strict)
{
while (key.Length > 0)
{
char c = key[0];
if(c == ';') break;
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) break;
key = key.Substring(1);
}
}
bool startsWithSemicolon = key.StartsWith(";");
if (startsWithSemicolon)
{
clp.EOF = true;
OUT_CueFile.Commands.Add(new CUE_File.Command.COMMENT() { Value = line });
}
else switch (key)
{
default:
job.Warn("Unknown command: " + key);
break;
case "CATALOG":
if (OUT_CueFile.GlobalDiscInfo.Catalog != null)
job.Warn("Multiple CATALOG commands detected. Subsequent ones are ignored.");
else if (clp.EOF)
job.Warn("Ignoring empty CATALOG command");
else OUT_CueFile.Commands.Add(OUT_CueFile.GlobalDiscInfo.Catalog = new CUE_File.Command.CATALOG() { Value = clp.ReadToken() });
break;
case "CDTEXTFILE":
if (OUT_CueFile.GlobalDiscInfo.CDTextFile != null)
job.Warn("Multiple CDTEXTFILE commands detected. Subsequent ones are ignored.");
else if (clp.EOF)
job.Warn("Ignoring empty CDTEXTFILE command");
else OUT_CueFile.Commands.Add(OUT_CueFile.GlobalDiscInfo.CDTextFile = new CUE_File.Command.CDTEXTFILE() { Path = clp.ReadPath() });
break;
case "FILE":
{
var path = clp.ReadPath();
CueFileType ft;
if (clp.EOF)
{
job.Error("FILE command is missing file type.");
ft = CueFileType.Unspecified;
}
else
{
var strType = clp.ReadToken().ToUpperInvariant();
switch (strType)
{
default:
job.Error("Unknown FILE type: " + strType);
ft = CueFileType.Unspecified;
break;
case "BINARY": ft = CueFileType.BINARY; break;
case "MOTOROLA": ft = CueFileType.MOTOROLA; break;
case "BINARAIFF": ft = CueFileType.AIFF; break;
case "WAVE": ft = CueFileType.WAVE; break;
case "MP3": ft = CueFileType.MP3; break;
}
}
OUT_CueFile.Commands.Add(new CUE_File.Command.FILE() { Path = path, Type = ft });
}
break;
case "FLAGS":
{
var cmd = new CUE_File.Command.FLAGS();
OUT_CueFile.Commands.Add(cmd);
while (!clp.EOF)
{
var flag = clp.ReadToken().ToUpperInvariant();
switch (flag)
{
case "DATA":
default:
job.Warn("Unknown FLAG: " + flag);
break;
case "DCP": cmd.Flags |= CueTrackFlags.DCP; break;
case "4CH": cmd.Flags |= CueTrackFlags._4CH; break;
case "PRE": cmd.Flags |= CueTrackFlags.PRE; break;
case "SCMS": cmd.Flags |= CueTrackFlags.SCMS; break;
}
}
if (cmd.Flags == CueTrackFlags.None)
job.Warn("Empty FLAG command");
}
break;
case "INDEX":
{
if (clp.EOF)
{
job.Error("Incomplete INDEX command");
break;
}
string strindexnum = clp.ReadToken();
int indexnum;
if (!int.TryParse(strindexnum, out indexnum) || indexnum < 0 || indexnum > 99)
{
job.Error("Invalid INDEX number: " + strindexnum);
break;
}
string str_timestamp = clp.ReadToken();
var ts = new Timestamp(str_timestamp);
if (!ts.Valid && !IN_Strict)
{
//try cleaning it up
str_timestamp = Regex.Replace(str_timestamp, "[^0-9:]", "");
ts = new Timestamp(str_timestamp);
}
if (!ts.Valid)
{
if (IN_Strict)
job.Error("Invalid INDEX timestamp: " + str_timestamp);
break;
}
OUT_CueFile.Commands.Add(new CUE_File.Command.INDEX() { Number = indexnum, Timestamp = ts });
}
break;
case "ISRC":
if (OUT_CueFile.GlobalDiscInfo.ISRC != null)
job.Warn("Multiple ISRC commands detected. Subsequent ones are ignored.");
else if (clp.EOF)
job.Warn("Ignoring empty ISRC command");
else
{
var isrc = clp.ReadToken();
if (isrc.Length != 12)
job.Warn("Invalid ISRC code ignored: " + isrc);
else
{
OUT_CueFile.Commands.Add(OUT_CueFile.GlobalDiscInfo.ISRC = new CUE_File.Command.ISRC() { Value = isrc });
}
}
break;
case "PERFORMER":
OUT_CueFile.Commands.Add(new CUE_File.Command.PERFORMER() { Value = clp.ReadPath() ?? "" });
break;
case "POSTGAP":
case "PREGAP":
{
var str_msf = clp.ReadToken();
var msf = new Timestamp(str_msf);
if (!msf.Valid)
job.Error("Ignoring {0} with invalid length MSF: " + str_msf, key);
else
{
if (key == "POSTGAP")
OUT_CueFile.Commands.Add(new CUE_File.Command.POSTGAP() { Length = msf });
else
OUT_CueFile.Commands.Add(new CUE_File.Command.PREGAP() { Length = msf });
}
}
break;
case "REM":
OUT_CueFile.Commands.Add(new CUE_File.Command.REM() { Value = clp.ReadLine() });
break;
case "SONGWRITER":
OUT_CueFile.Commands.Add(new CUE_File.Command.SONGWRITER() { Value = clp.ReadPath() ?? "" });
break;
case "TITLE":
OUT_CueFile.Commands.Add(new CUE_File.Command.TITLE() { Value = clp.ReadPath() ?? "" });
break;
case "TRACK":
{
if (clp.EOF)
{
job.Error("Incomplete TRACK command");
break;
}
string str_tracknum = clp.ReadToken();
int tracknum;
if (!int.TryParse(str_tracknum, out tracknum) || tracknum < 1 || tracknum > 99)
{
job.Error("Invalid TRACK number: " + str_tracknum);
break;
}
//TODO - check sequentiality? maybe as a warning
CueTrackType tt;
var str_trackType = clp.ReadToken();
switch (str_trackType.ToUpperInvariant())
{
default:
job.Error("Unknown TRACK type: " + str_trackType);
tt = CueTrackType.Unknown;
break;
case "AUDIO": tt = CueTrackType.Audio; break;
case "CDG": tt = CueTrackType.CDG; break;
case "MODE1/2048": tt = CueTrackType.Mode1_2048; break;
case "MODE1/2352": tt = CueTrackType.Mode1_2352; break;
case "MODE2/2336": tt = CueTrackType.Mode2_2336; break;
case "MODE2/2352": tt = CueTrackType.Mode2_2352; break;
case "CDI/2336": tt = CueTrackType.CDI_2336; break;
case "CDI/2352": tt = CueTrackType.CDI_2352; break;
}
OUT_CueFile.Commands.Add(new CUE_File.Command.TRACK() { Number = tracknum, Type = tt });
}
break;
}
if (!clp.EOF)
{
var remainder = clp.ReadLine();
if (remainder.TrimStart().StartsWith(";"))
{
//add a comment
OUT_CueFile.Commands.Add(new CUE_File.Command.COMMENT() { Value = remainder });
}
else job.Warn("Unknown text at end of line after processing command: " + key);
}
} //end cue parsing loop
job.FinishLog();
} //LoadFromString
public void Run(ParseCueJob job)
{
job.OUT_CueFile = new CUE_File();
job.LoadFromString(job);
}
}
} //namespace
| |
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using SourceCode.Chasm.Repository.Disk;
using SourceCode.Chasm.Repository.Internal;
using SourceCode.Clay;
namespace SourceCode.Chasm.Repository.AzureBlob
{
partial class AzureBlobChasmRepo // .Object
{
private const string ContentTypeKey = "contentType";
private const string FilenameKey = "filename";
#region Read
public override async Task<bool> ExistsAsync(Sha1 objectId, ChasmRequestContext requestContext = default, CancellationToken cancellationToken = default)
{
requestContext = ChasmRequestContext.Ensure(requestContext);
// Try disk repo first
bool exists = await _diskRepo.ExistsAsync(objectId, requestContext, cancellationToken)
.ConfigureAwait(false);
// Else go to cloud
if (!exists)
{
exists = await ExistsOnCloudAsync(objectId, requestContext, cancellationToken)
.ConfigureAwait(false);
}
return exists;
}
private async Task<bool> ExistsOnCloudAsync(Sha1 objectId, ChasmRequestContext requestContext = default, CancellationToken cancellationToken = default)
{
requestContext = ChasmRequestContext.Ensure(requestContext);
var opContext = new OperationContext
{
ClientRequestID = requestContext.CorrelationId,
CustomUserAgent = requestContext.CustomUserAgent
};
string blobName = DeriveBlobName(objectId);
CloudBlobContainer objectsContainer = _objectsContainer.Value;
CloudAppendBlob blobRef = objectsContainer.GetAppendBlobReference(blobName);
bool exists = await blobRef.ExistsAsync(default, opContext, cancellationToken)
.ConfigureAwait(false);
return exists;
}
public override async Task<IChasmBlob> ReadObjectAsync(Sha1 objectId, ChasmRequestContext requestContext = default, CancellationToken cancellationToken = default)
{
requestContext = ChasmRequestContext.Ensure(requestContext);
var opContext = new OperationContext
{
ClientRequestID = requestContext.CorrelationId,
CustomUserAgent = requestContext.CustomUserAgent
};
// Try disk repo first
IChasmBlob cached = await _diskRepo.ReadObjectAsync(objectId, requestContext, cancellationToken)
.ConfigureAwait(false);
if (cached != null)
return cached;
// Else go to cloud
string blobName = DeriveBlobName(objectId);
CloudBlobContainer objectsContainer = _objectsContainer.Value;
CloudAppendBlob blobRef = objectsContainer.GetAppendBlobReference(blobName);
try
{
// Fetch metadata
await blobRef.FetchAttributesAsync(default, default, opContext, cancellationToken)
.ConfigureAwait(false);
blobRef.Metadata.TryGetValue(FilenameKey, out string filename);
blobRef.Metadata.TryGetValue(ContentTypeKey, out string contentType);
var metadata = new ChasmMetadata(contentType, filename);
using (var output = new MemoryStream())
{
// TODO: Perf: Use a stream instead of a preceding call to fetch the buffer length
await blobRef.DownloadToStreamAsync(output, default, default, opContext, cancellationToken)
.ConfigureAwait(false);
byte[] buffer = output.ToArray(); // TODO: Perf
return new ChasmBlob(buffer, metadata);
}
}
// Try-catch is cheaper than a separate (latent) exists check
catch (StorageException se) when (se.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound)
{
se.Suppress();
return default;
}
}
public override async Task<IChasmStream> ReadStreamAsync(Sha1 objectId, ChasmRequestContext requestContext = default, CancellationToken cancellationToken = default)
{
requestContext = ChasmRequestContext.Ensure(requestContext);
var opContext = new OperationContext
{
ClientRequestID = requestContext.CorrelationId,
CustomUserAgent = requestContext.CustomUserAgent
};
// Try disk repo first
IChasmStream cached = await _diskRepo.ReadStreamAsync(objectId, requestContext, cancellationToken)
.ConfigureAwait(false);
if (cached != null)
return cached;
// Else go to cloud
string blobName = DeriveBlobName(objectId);
CloudBlobContainer objectsContainer = _objectsContainer.Value;
CloudAppendBlob blobRef = objectsContainer.GetAppendBlobReference(blobName);
try
{
// Fetch metadata
await blobRef.FetchAttributesAsync()
.ConfigureAwait(false);
blobRef.Metadata.TryGetValue(FilenameKey, out string filename);
blobRef.Metadata.TryGetValue(ContentTypeKey, out string contentType);
var metadata = new ChasmMetadata(contentType, filename);
// TODO: Perf: Use a stream instead of a preceding call to fetch the buffer length
var output = new MemoryStream();
await blobRef.DownloadToStreamAsync(output, default, default, opContext, cancellationToken)
.ConfigureAwait(false);
return new ChasmStream(output, metadata);
}
// Try-catch is cheaper than a separate (latent) exists check
catch (StorageException se) when (se.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound)
{
se.Suppress();
return default;
}
}
#endregion
#region Write
/// <summary>
/// Writes a buffer to the destination, returning the content's <see cref="Sha1"/> value.
/// </summary>
/// <param name="buffer">The content to hash and write.</param>
/// <param name="forceOverwrite">Forces the target to be ovwerwritten, even if it already exists.</param>
/// <param name="cancellationToken">Allows the operation to be cancelled.</param>
public override async Task<WriteResult<Sha1>> WriteObjectAsync(ReadOnlyMemory<byte> buffer, ChasmMetadata metadata, bool forceOverwrite, ChasmRequestContext requestContext = default, CancellationToken cancellationToken = default)
{
requestContext = ChasmRequestContext.Ensure(requestContext);
var created = true;
async ValueTask AfterWrite(Sha1 sha1, string filePath)
{
created = await UploadAsync(sha1, filePath, metadata, forceOverwrite, requestContext, cancellationToken)
.ConfigureAwait(false);
}
Sha1 objectId = await DiskChasmRepo.WriteFileAsync(buffer, AfterWrite, cancellationToken)
.ConfigureAwait(false);
return new WriteResult<Sha1>(objectId, created);
}
/// <summary>
/// Writes a stream to the destination, returning the content's <see cref="Sha1"/> value.
/// </summary>
/// <param name="stream">The content to hash and write.</param>
/// <param name="forceOverwrite">Forces the target to be ovwerwritten, even if it already exists.</param>
/// <param name="cancellationToken">Allows the operation to be cancelled.</param>
public override async Task<WriteResult<Sha1>> WriteObjectAsync(Stream stream, ChasmMetadata metadata, bool forceOverwrite, ChasmRequestContext requestContext = default, CancellationToken cancellationToken = default)
{
if (stream == null) throw new ArgumentNullException(nameof(stream));
requestContext = ChasmRequestContext.Ensure(requestContext);
var created = true;
async ValueTask AfterWrite(Sha1 sha1, string filePath)
{
created = await UploadAsync(sha1, filePath, metadata, forceOverwrite, requestContext, cancellationToken)
.ConfigureAwait(false);
}
Sha1 objectId = await DiskChasmRepo.WriteFileAsync(stream, AfterWrite, cancellationToken)
.ConfigureAwait(false);
return new WriteResult<Sha1>(objectId, created);
}
/// <summary>
/// Writes a stream to the destination, returning the content's <see cref="Sha1"/> value.
/// The <paramref name="beforeHash"/> function permits a transformation operation
/// on the source value before calculating the hash and writing to the destination.
/// For example, the source stream may be encoded as Json.
/// </summary>
/// <param name="beforeHash">An action to take on the internal stream, before calculating the hash.</param>
/// <param name="forceOverwrite">Forces the target to be ovwerwritten, even if it already exists.</param>
/// <param name="cancellationToken">Allows the operation to be cancelled.</param>
/// <remarks>Note that the <paramref name="beforeHash"/> function should maintain the integrity
/// of the source stream: the hash will be taken on the result of this operation.
/// For example, transforming to Json is appropriate but compression is not since the latter
/// is not a representative model of the original content, but rather a storage optimization.</remarks>
public override async Task<WriteResult<Sha1>> WriteObjectAsync(Func<Stream, ValueTask> beforeHash, ChasmMetadata metadata, bool forceOverwrite, ChasmRequestContext requestContext = default, CancellationToken cancellationToken = default)
{
if (beforeHash == null) throw new ArgumentNullException(nameof(beforeHash));
requestContext = ChasmRequestContext.Ensure(requestContext);
var created = true;
async ValueTask AfterWrite(Sha1 sha1, string filePath)
{
created = await UploadAsync(sha1, filePath, metadata, forceOverwrite, requestContext, cancellationToken)
.ConfigureAwait(false);
}
Sha1 objectId = await DiskChasmRepo.StageFileAsync(beforeHash, AfterWrite, cancellationToken)
.ConfigureAwait(false);
return new WriteResult<Sha1>(objectId, created);
}
private async ValueTask<bool> UploadAsync(Sha1 objectId, string filePath, ChasmMetadata metadata, bool forceOverwrite, ChasmRequestContext requestContext = default, CancellationToken cancellationToken = default)
{
requestContext = ChasmRequestContext.Ensure(requestContext);
var opContext = new OperationContext
{
ClientRequestID = requestContext.CorrelationId,
CustomUserAgent = requestContext.CustomUserAgent
};
if (!forceOverwrite)
{
bool exists = await ExistsOnCloudAsync(objectId, requestContext, cancellationToken)
.ConfigureAwait(false);
// Not created (already existed)
if (exists)
return false;
}
// Objects are immutable
AccessCondition accessCondition = forceOverwrite ? null : AccessCondition.GenerateIfNotExistsCondition(); // If-None-Match *
string blobName = DeriveBlobName(objectId);
CloudBlobContainer objectsContainer = _objectsContainer.Value;
CloudAppendBlob blobRef = objectsContainer.GetAppendBlobReference(blobName);
try
{
// Required to create blob header before appending to it
await blobRef.CreateOrReplaceAsync(accessCondition, default, opContext, cancellationToken)
.ConfigureAwait(false);
Task metadataTask = null;
if (metadata != null)
{
blobRef.Metadata.Add(FilenameKey, metadata.Filename);
blobRef.Metadata.Add(ContentTypeKey, metadata.ContentType);
metadataTask = blobRef.SetMetadataAsync(default, default, opContext, cancellationToken);
}
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
// Append blob. Following seems to be the only safe multi-writer method available
// http://stackoverflow.com/questions/32530126/azure-cloudappendblob-errors-with-concurrent-access
await blobRef.AppendBlockAsync(fs, default, default, default, opContext, cancellationToken)
.ConfigureAwait(false);
if (metadataTask != null)
{
await metadataTask
.ConfigureAwait(false);
}
}
}
// Try-catch is cheaper than a separate (latent) exists check
catch (StorageException se) when (!forceOverwrite && se.RequestInformation.HttpStatusCode == (int)HttpStatusCode.Conflict)
{
se.Suppress();
}
// Created
return true;
}
public static string DeriveBlobName(Sha1 sha1)
{
System.Collections.Generic.KeyValuePair<string, string> tokens = sha1.Split(2);
string blobName = $@"{tokens.Key}/{tokens.Value}";
blobName = Uri.EscapeUriString(blobName);
return blobName;
}
#endregion
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using FluentAssertions;
using Microsoft.Build.Construction;
using Microsoft.DotNet.Tools;
using Microsoft.DotNet.Tools.Test.Utilities;
using Msbuild.Tests.Utilities;
using System;
using System.IO;
using Xunit;
namespace Microsoft.DotNet.Cli.List.Reference.Tests
{
public class GivenDotnetListReference : TestBase
{
private const string HelpText = @"Usage: dotnet list <PROJECT> reference [options]
Arguments:
<PROJECT> The project file to operate on. If a file is not specified, the command will search the current directory for one.
Options:
-h, --help Show help information.
";
private const string ListCommandHelpText = @"Usage: dotnet list [options] <PROJECT> [command]
Arguments:
<PROJECT> The project file to operate on. If a file is not specified, the command will search the current directory for one.
Options:
-h, --help Show help information.
Commands:
reference .NET Core Project-to-Project dependency viewer
";
const string FrameworkNet451Arg = "-f net451";
const string ConditionFrameworkNet451 = "== 'net451'";
const string FrameworkNetCoreApp10Arg = "-f netcoreapp1.0";
const string ConditionFrameworkNetCoreApp10 = "== 'netcoreapp1.0'";
[Theory]
[InlineData("--help")]
[InlineData("-h")]
public void WhenHelpOptionIsPassedItPrintsUsage(string helpArg)
{
var cmd = new ListReferenceCommand().Execute(helpArg);
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Theory]
[InlineData("")]
[InlineData("unknownCommandName")]
public void WhenNoCommandIsPassedItPrintsError(string commandName)
{
var cmd = new DotnetCommand()
.ExecuteWithCapturedOutput($"list {commandName}");
cmd.Should().Fail();
cmd.StdErr.Should().Be(CommonLocalizableStrings.RequiredCommandNotPassed);
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(ListCommandHelpText);
}
[Fact]
public void WhenTooManyArgumentsArePassedItPrintsError()
{
var cmd = new ListReferenceCommand()
.WithProject("one two three")
.Execute("proj.csproj");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().BeVisuallyEquivalentTo($@"{string.Format(CommandLine.LocalizableStrings.UnrecognizedCommandOrArgument, "two")}
{string.Format(CommandLine.LocalizableStrings.UnrecognizedCommandOrArgument, "three")}");
}
[Theory]
[InlineData("idontexist.csproj")]
[InlineData("ihave?inv@lid/char\\acters")]
public void WhenNonExistingProjectIsPassedItPrintsErrorAndUsage(string projName)
{
var setup = Setup();
var cmd = new ListReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(projName)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.CouldNotFindProjectOrDirectory, projName));
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Fact]
public void WhenBrokenProjectIsPassedItPrintsErrorAndUsage()
{
string projName = "Broken/Broken.csproj";
var setup = Setup();
var cmd = new ListReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(projName)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.ProjectIsInvalid, "Broken/Broken.csproj"));
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Fact]
public void WhenMoreThanOneProjectExistsInTheDirectoryItPrintsErrorAndUsage()
{
var setup = Setup();
var workingDir = Path.Combine(setup.TestRoot, "MoreThanOne");
var cmd = new ListReferenceCommand()
.WithWorkingDirectory(workingDir)
.Execute($"\"{setup.ValidRefCsprojRelToOtherProjPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.MoreThanOneProjectInDirectory, workingDir + Path.DirectorySeparatorChar));
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Fact]
public void WhenNoProjectsExistsInTheDirectoryItPrintsErrorAndUsage()
{
var setup = Setup();
var cmd = new ListReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.CouldNotFindAnyProjectInDirectory, setup.TestRoot + Path.DirectorySeparatorChar));
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Fact]
public void WhenNoProjectReferencesArePresentInTheProjectItPrintsError()
{
var lib = NewLib();
var cmd = new ListReferenceCommand()
.WithProject(lib.CsProjPath)
.Execute();
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.NoReferencesFound, CommonLocalizableStrings.P2P, lib.CsProjPath));
}
[Fact]
public void ItPrintsSingleReference()
{
string OutputText = CommonLocalizableStrings.ProjectReferenceOneOrMore;
OutputText += $@"
{new string('-', OutputText.Length)}
..\ref\ref.csproj";
var lib = NewLib("lib");
string ref1 = NewLib("ref").CsProjPath;
AddValidRef(ref1, lib);
var cmd = new ListReferenceCommand()
.WithProject(lib.CsProjPath)
.Execute();
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentTo(OutputText);
}
[Fact]
public void ItPrintsMultipleReferences()
{
string OutputText = CommonLocalizableStrings.ProjectReferenceOneOrMore;
OutputText += $@"
{new string('-', OutputText.Length)}
..\ref1\ref1.csproj
..\ref2\ref2.csproj
..\ref3\ref3.csproj";
var lib = NewLib("lib");
string ref1 = NewLib("ref1").CsProjPath;
string ref2 = NewLib("ref2").CsProjPath;
string ref3 = NewLib("ref3").CsProjPath;
AddValidRef(ref1, lib);
AddValidRef(ref2, lib);
AddValidRef(ref3, lib);
var cmd = new ListReferenceCommand()
.WithProject(lib.CsProjPath)
.Execute();
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentTo(OutputText);
}
private TestSetup Setup([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(Setup), string identifier = "")
{
return new TestSetup(
TestAssets.Get(TestSetup.TestGroup, TestSetup.ProjectName)
.CreateInstance(callingMethod: callingMethod, identifier: identifier)
.WithSourceFiles()
.Root
.FullName);
}
private ProjDir NewDir(string testProjectName = "temp", [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "")
{
return new ProjDir(TestAssets.CreateTestDirectory(testProjectName: testProjectName, callingMethod: callingMethod, identifier: identifier).FullName);
}
private ProjDir NewLib(string testProjectName = "temp", [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "")
{
var dir = NewDir(testProjectName: testProjectName, callingMethod: callingMethod, identifier: identifier);
try
{
string newArgs = $"classlib -o \"{dir.Path}\" --debug:ephemeral-hive --no-restore";
new NewCommandShim()
.WithWorkingDirectory(dir.Path)
.ExecuteWithCapturedOutput(newArgs)
.Should().Pass();
}
catch (System.ComponentModel.Win32Exception e)
{
throw new Exception($"Intermittent error in `dotnet new` occurred when running it in dir `{dir.Path}`\nException:\n{e}");
}
return dir;
}
private void AddValidRef(string path, ProjDir proj)
{
new AddReferenceCommand()
.WithProject(proj.CsProjPath)
.Execute($"\"{path}\"")
.Should().Pass();
}
}
}
| |
/*
Copyright (c) 2005 Poderosa Project, All Rights Reserved.
This file is a part of the Granados SSH Client Library that is subject to
the license included in the distributed package.
You may not use this file except in compliance with the license.
$Id: ConfigAttr.cs,v 1.2 2011/10/27 23:21:57 kzmi Exp $
*/
using System;
using System.Diagnostics;
using System.Reflection;
using System.Text;
namespace Poderosa.PortForwarding {
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public abstract class ConfigElementAttribute : Attribute {
protected string _externalName;
protected FieldInfo _fieldInfo;
public FieldInfo FieldInfo {
get {
return _fieldInfo;
}
set {
_fieldInfo = value;
_externalName = ToExternalName(_fieldInfo.Name);
}
}
public string ExternalName {
get {
return _externalName;
}
}
public static string ToExternalName(string value) {
//if the field name starts with '_', strip it off
if (value[0] == '_')
return value.Substring(1);
else
return value;
}
public abstract void ExportTo(object holder, ConfigNode node);
public abstract void ImportFrom(object holder, ConfigNode node);
public abstract void Reset(object holder);
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class ConfigIntElementAttribute : ConfigElementAttribute {
private int _initial;
public int Initial {
get {
return _initial;
}
set {
_initial = value;
}
}
public override void ExportTo(object holder, ConfigNode node) {
int value = (int)_fieldInfo.GetValue(holder);
if (value != _initial)
node[_externalName] = value.ToString();
}
public override void ImportFrom(object holder, ConfigNode node) {
_fieldInfo.SetValue(holder, ParseInt(node[_externalName], _initial));
}
public override void Reset(object holder) {
_fieldInfo.SetValue(holder, _initial);
}
public static int ParseInt(string value, int defaultvalue) {
try {
if (value == null || value.Length == 0)
return defaultvalue;
else
return Int32.Parse(value);
}
catch (Exception) {
return defaultvalue;
}
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class ConfigBoolElementAttribute : ConfigElementAttribute {
private bool _initial;
public bool Initial {
get {
return _initial;
}
set {
_initial = value;
}
}
public override void ExportTo(object holder, ConfigNode node) {
bool value = (bool)_fieldInfo.GetValue(holder);
if (value != _initial)
node[_externalName] = value.ToString();
}
public override void ImportFrom(object holder, ConfigNode node) {
_fieldInfo.SetValue(holder, ParseBool(node[_externalName], _initial));
}
public override void Reset(object holder) {
_fieldInfo.SetValue(holder, _initial);
}
public static bool ParseBool(string value, bool defaultvalue) {
try {
if (value == null || value.Length == 0)
return defaultvalue;
else
return Boolean.Parse(value);
}
catch (Exception) {
return defaultvalue;
}
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class ConfigFloatElementAttribute : ConfigElementAttribute {
private float _initial;
public float Initial {
get {
return _initial;
}
set {
_initial = value;
}
}
public override void ExportTo(object holder, ConfigNode node) {
float value = (float)_fieldInfo.GetValue(holder);
if (value != _initial)
node[_externalName] = value.ToString();
}
public override void ImportFrom(object holder, ConfigNode node) {
_fieldInfo.SetValue(holder, ParseFloat(node[_externalName], _initial));
}
public override void Reset(object holder) {
_fieldInfo.SetValue(holder, _initial);
}
public static float ParseFloat(string value, float defaultvalue) {
try {
if (value == null || value.Length == 0)
return defaultvalue;
else
return Single.Parse(value);
}
catch (Exception) {
return defaultvalue;
}
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class ConfigStringElementAttribute : ConfigElementAttribute {
private string _initial;
public string Initial {
get {
return _initial;
}
set {
_initial = value;
}
}
public override void ExportTo(object holder, ConfigNode node) {
string value = _fieldInfo.GetValue(holder) as string;
if (value != _initial)
node[_externalName] = value == null ? "" : value;
}
public override void ImportFrom(object holder, ConfigNode node) {
string t = node[_externalName];
_fieldInfo.SetValue(holder, t == null ? _initial : t);
}
public override void Reset(object holder) {
_fieldInfo.SetValue(holder, _initial);
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class ConfigStringArrayElementAttribute : ConfigElementAttribute {
private string[] _initial;
public string[] Initial {
get {
return _initial;
}
set {
_initial = value;
}
}
public override void ExportTo(object holder, ConfigNode node) {
string[] t = (string[])_fieldInfo.GetValue(holder);
StringBuilder bld = new StringBuilder();
foreach (string a in t) {
if (bld.Length > 0)
bld.Append(',');
bld.Append(a);
}
node[_externalName] = bld.ToString();
}
public override void ImportFrom(object holder, ConfigNode node) {
string t = node[_externalName];
_fieldInfo.SetValue(holder, t == null ? _initial : t.Split(','));
}
public override void Reset(object holder) {
_fieldInfo.SetValue(holder, _initial);
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class ConfigEnumElementAttribute : ConfigElementAttribute {
private ValueType _initial;
private Type _enumType;
public ConfigEnumElementAttribute(Type t) {
_enumType = t;
}
public int InitialAsInt {
get {
return (int)_initial;
}
set {
_initial = (ValueType)value;
}
}
public Type Type {
get {
return _enumType;
}
}
public override void ExportTo(object holder, ConfigNode node) {
ValueType value = (ValueType)_fieldInfo.GetValue(holder);
if (value != _initial)
node[_externalName] = value.ToString();
}
public override void ImportFrom(object holder, ConfigNode node) {
object v = ParseEnum(_enumType, node[_externalName], _initial);
_fieldInfo.SetValue(holder, v);
}
public override void Reset(object holder) {
_fieldInfo.SetValue(holder, Enum.ToObject(_enumType, (int)_initial));
}
public static ValueType ParseEnum(Type enumtype, string t, ValueType defaultvalue) {
try {
if (t == null || t.Length == 0)
return (ValueType)Enum.ToObject(enumtype, (int)defaultvalue);
else
return (ValueType)Enum.Parse(enumtype, t, false);
}
catch (FormatException) {
return (ValueType)Enum.ToObject(enumtype, (int)defaultvalue);
}
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class ConfigFlagElementAttribute : ConfigElementAttribute {
private int _initial;
private int _max;
private Type _enumType;
public ConfigFlagElementAttribute(Type t) {
_enumType = t;
}
public int Initial {
get {
return _initial;
}
set {
_initial = value;
}
}
public int Max {
get {
return _max;
}
set {
_max = value;
}
}
public Type Type {
get {
return _enumType;
}
}
public override void ExportTo(object holder, ConfigNode node) {
int value = (int)_fieldInfo.GetValue(holder);
StringBuilder bld = new StringBuilder();
for (int i = 1; i <= _max; i <<= 1) {
if ((i & value) != 0) {
if (bld.Length > 0)
bld.Append(',');
bld.Append(Enum.GetName(_enumType, i));
}
}
node[_externalName] = bld.ToString();
}
public override void ImportFrom(object holder, ConfigNode node) {
string value = node[_externalName];
if (value == null)
_fieldInfo.SetValue(holder, Enum.ToObject(_enumType, (int)_initial));
else {
int r = 0;
foreach (string t in value.Split(','))
r |= (int)Enum.Parse(_enumType, t, false);
_fieldInfo.SetValue(holder, Enum.ToObject(_enumType, (int)r));
}
}
public override void Reset(object holder) {
_fieldInfo.SetValue(holder, Enum.ToObject(_enumType, (int)_initial));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: The boolean class serves as a wrapper for the primitive
** type boolean.
**
**
===========================================================*/
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
namespace System
{
[Serializable]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public readonly struct Boolean : IComparable, IConvertible, IComparable<bool>, IEquatable<bool>
{
//
// Member Variables
//
private readonly bool m_value; // Do not rename (binary serialization)
// The true value.
//
internal const int True = 1;
// The false value.
//
internal const int False = 0;
//
// Internal Constants are real consts for performance.
//
// The internal string representation of true.
//
internal const string TrueLiteral = "True";
// The internal string representation of false.
//
internal const string FalseLiteral = "False";
//
// Public Constants
//
// The public string representation of true.
//
public static readonly string TrueString = TrueLiteral;
// The public string representation of false.
//
public static readonly string FalseString = FalseLiteral;
//
// Overriden Instance Methods
//
/*=================================GetHashCode==================================
**Args: None
**Returns: 1 or 0 depending on whether this instance represents true or false.
**Exceptions: None
**Overriden From: Value
==============================================================================*/
// Provides a hash code for this instance.
public override int GetHashCode()
{
return (m_value) ? True : False;
}
/*===================================ToString===================================
**Args: None
**Returns: "True" or "False" depending on the state of the boolean.
**Exceptions: None.
==============================================================================*/
// Converts the boolean value of this instance to a String.
public override string ToString()
{
if (false == m_value)
{
return FalseLiteral;
}
return TrueLiteral;
}
public string ToString(IFormatProvider? provider)
{
return ToString();
}
public bool TryFormat(Span<char> destination, out int charsWritten)
{
if (m_value)
{
if ((uint)destination.Length > 3) // uint cast, per https://github.com/dotnet/coreclr/issues/18688
{
destination[0] = 'T';
destination[1] = 'r';
destination[2] = 'u';
destination[3] = 'e';
charsWritten = 4;
return true;
}
}
else
{
if ((uint)destination.Length > 4)
{
destination[0] = 'F';
destination[1] = 'a';
destination[2] = 'l';
destination[3] = 's';
destination[4] = 'e';
charsWritten = 5;
return true;
}
}
charsWritten = 0;
return false;
}
// Determines whether two Boolean objects are equal.
public override bool Equals(object? obj)
{
//If it's not a boolean, we're definitely not equal
if (!(obj is bool))
{
return false;
}
return (m_value == ((bool)obj).m_value);
}
[NonVersionable]
public bool Equals(bool obj)
{
return m_value == obj;
}
// Compares this object to another object, returning an integer that
// indicates the relationship. For booleans, false sorts before true.
// null is considered to be less than any instance.
// If object is not of type boolean, this method throws an ArgumentException.
//
// Returns a value less than zero if this object
//
public int CompareTo(object? obj)
{
if (obj == null)
{
return 1;
}
if (!(obj is bool))
{
throw new ArgumentException(SR.Arg_MustBeBoolean);
}
if (m_value == ((bool)obj).m_value)
{
return 0;
}
else if (m_value == false)
{
return -1;
}
return 1;
}
public int CompareTo(bool value)
{
if (m_value == value)
{
return 0;
}
else if (m_value == false)
{
return -1;
}
return 1;
}
//
// Static Methods
//
// Custom string compares for early application use by config switches, etc
//
internal static bool IsTrueStringIgnoreCase(ReadOnlySpan<char> value)
{
return (value.Length == 4 &&
(value[0] == 't' || value[0] == 'T') &&
(value[1] == 'r' || value[1] == 'R') &&
(value[2] == 'u' || value[2] == 'U') &&
(value[3] == 'e' || value[3] == 'E'));
}
internal static bool IsFalseStringIgnoreCase(ReadOnlySpan<char> value)
{
return (value.Length == 5 &&
(value[0] == 'f' || value[0] == 'F') &&
(value[1] == 'a' || value[1] == 'A') &&
(value[2] == 'l' || value[2] == 'L') &&
(value[3] == 's' || value[3] == 'S') &&
(value[4] == 'e' || value[4] == 'E'));
}
// Determines whether a String represents true or false.
//
public static bool Parse(string value)
{
if (value == null) throw new ArgumentNullException(nameof(value));
return Parse(value.AsSpan());
}
public static bool Parse(ReadOnlySpan<char> value) =>
TryParse(value, out bool result) ? result : throw new FormatException(SR.Format(SR.Format_BadBoolean, new string(value)));
// Determines whether a String represents true or false.
//
public static bool TryParse(string? value, out bool result)
{
if (value == null)
{
result = false;
return false;
}
return TryParse(value.AsSpan(), out result);
}
public static bool TryParse(ReadOnlySpan<char> value, out bool result)
{
if (IsTrueStringIgnoreCase(value))
{
result = true;
return true;
}
if (IsFalseStringIgnoreCase(value))
{
result = false;
return true;
}
// Special case: Trim whitespace as well as null characters.
value = TrimWhiteSpaceAndNull(value);
if (IsTrueStringIgnoreCase(value))
{
result = true;
return true;
}
if (IsFalseStringIgnoreCase(value))
{
result = false;
return true;
}
result = false;
return false;
}
private static ReadOnlySpan<char> TrimWhiteSpaceAndNull(ReadOnlySpan<char> value)
{
const char nullChar = (char)0x0000;
int start = 0;
while (start < value.Length)
{
if (!char.IsWhiteSpace(value[start]) && value[start] != nullChar)
{
break;
}
start++;
}
int end = value.Length - 1;
while (end >= start)
{
if (!char.IsWhiteSpace(value[end]) && value[end] != nullChar)
{
break;
}
end--;
}
return value.Slice(start, end - start + 1);
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.Boolean;
}
bool IConvertible.ToBoolean(IFormatProvider? provider)
{
return m_value;
}
char IConvertible.ToChar(IFormatProvider? provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "Char"));
}
sbyte IConvertible.ToSByte(IFormatProvider? provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider? provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider? provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider? provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider? provider)
{
return Convert.ToInt32(m_value);
}
uint IConvertible.ToUInt32(IFormatProvider? provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider? provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider? provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider? provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider? provider)
{
return Convert.ToDouble(m_value);
}
decimal IConvertible.ToDecimal(IFormatProvider? provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider? provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "DateTime"));
}
object IConvertible.ToType(Type type, IFormatProvider? provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* 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 halcyon nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using KellermanSoftware.CompareNetObjects;
using System.Threading;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.FrameworkTests
{
[TestFixture]
class SurroundingRegionManagerTests
{
private Scene mockScene;
private SurroundingRegionManager srm;
private Dictionary<NeighborStateChangeType, int> stateChangeCounts = new Dictionary<NeighborStateChangeType, int>();
[SetUp]
public void Setup()
{
mockScene = InWorldz.Testing.SceneHelper.CreateScene(9000, 1000, 1000);
srm = mockScene.SurroundingRegions;
srm.OnNeighborStateChange += srm_OnNeighborStateChange;
}
void srm_OnNeighborStateChange(SimpleRegionInfo neighbor, NeighborStateChangeType changeType)
{
if (stateChangeCounts.ContainsKey(changeType))
{
stateChangeCounts[changeType]++;
}
else
{
stateChangeCounts[changeType] = 1;
}
}
[TearDown]
public void TearDown()
{
InWorldz.Testing.SceneHelper.TearDownScene(mockScene);
}
public static void SendCreateRegionMessage(uint xloc, uint yloc, ushort receiverServerPort, ushort regionServerport)
{
RegionInfo info = new RegionInfo
{
ExternalHostName = "localhost",
InternalEndPoint = new System.Net.IPEndPoint(new System.Net.IPAddress(2130706433), 9001),
HttpPort = regionServerport,
OutsideIP = "127.0.0.1",
RegionID = UUID.Random(),
RegionLocX = xloc,
RegionLocY = yloc,
};
WebRequest req = HttpWebRequest.Create("http://127.0.0.1:" + receiverServerPort + "/region2/regionup");
req.Headers["authorization"] = Util.GenerateHttpAuthorization("key");
req.Timeout = 10000;
req.Method = "POST";
byte[] serRegInfo = OSDParser.SerializeLLSDBinary(info.PackRegionInfoData());
var rs = req.GetRequestStream();
rs.Write(serRegInfo, 0, serRegInfo.Length);
rs.Flush();
var response = req.GetResponse();
response.Dispose();
}
public static void SendRegionDownMessage(uint xloc, uint yloc, ushort receiverServerPort, ushort regionServerport)
{
RegionInfo info = new RegionInfo
{
ExternalHostName = "localhost",
InternalEndPoint = new System.Net.IPEndPoint(new System.Net.IPAddress(2130706433), 9001),
HttpPort = regionServerport,
OutsideIP = "127.0.0.1",
RegionID = UUID.Random(),
RegionLocX = xloc,
RegionLocY = yloc,
};
WebRequest req = HttpWebRequest.Create("http://127.0.0.1:" + receiverServerPort + "/region2/regiondown");
req.Headers["authorization"] = Util.GenerateHttpAuthorization("key");
req.Timeout = 10000;
req.Method = "POST";
byte[] serRegInfo = OSDParser.SerializeLLSDBinary(info.PackRegionInfoData());
var rs = req.GetRequestStream();
rs.Write(serRegInfo, 0, serRegInfo.Length);
rs.Flush();
var response = req.GetResponse();
response.Dispose();
}
[Test]
public void TestAddRegion()
{
RegionInfo info = new RegionInfo
{
ExternalHostName = "localhost",
InternalEndPoint = new System.Net.IPEndPoint(new System.Net.IPAddress(2130706433), 9001),
HttpPort = 9000,
OutsideIP = "127.0.0.1",
RegionID = UUID.Random(),
RegionLocX = 1100,
RegionLocY = 1000,
};
WebRequest req = HttpWebRequest.Create("http://127.0.0.1:9000/region2/regionup");
req.Headers["authorization"] = Util.GenerateHttpAuthorization("key");
req.Timeout = 10000;
req.Method = "POST";
byte[] serRegInfo = OSDParser.SerializeLLSDBinary(info.PackRegionInfoData());
var rs = req.GetRequestStream();
rs.Write(serRegInfo, 0, serRegInfo.Length);
rs.Flush();
var response = req.GetResponse();
Assert.AreEqual(2, response.ContentLength);
StreamReader sr = new StreamReader(response.GetResponseStream());
Assert.AreEqual("OK", sr.ReadToEnd());
var neighbors = srm.GetNeighborsSnapshot();
Assert.AreEqual(1, neighbors.Count);
CompareObjects.Equals((SimpleRegionInfo)info, neighbors[0].RegionInfo);
Assert.AreEqual(1, stateChangeCounts[NeighborStateChangeType.NeighborUp]);
stateChangeCounts.Clear();
}
[Test]
public void TestRemoveRegion()
{
RegionInfo info = new RegionInfo
{
ExternalHostName = "localhost",
InternalEndPoint = new System.Net.IPEndPoint(new System.Net.IPAddress(2130706433), 9001),
HttpPort = 9000,
OutsideIP = "127.0.0.1",
RegionID = UUID.Random(),
RegionLocX = 1100,
RegionLocY = 1000,
};
WebRequest req = HttpWebRequest.Create("http://127.0.0.1:9000/region2/regionup");
req.Headers["authorization"] = Util.GenerateHttpAuthorization("key");
req.Timeout = 10000;
req.Method = "POST";
byte[] serRegInfo = OSDParser.SerializeLLSDBinary(info.PackRegionInfoData());
var rs = req.GetRequestStream();
rs.Write(serRegInfo, 0, serRegInfo.Length);
rs.Flush();
var response = req.GetResponse();
Assert.AreEqual(2, response.ContentLength);
StreamReader sr = new StreamReader(response.GetResponseStream());
Assert.AreEqual("OK", sr.ReadToEnd());
var neighbors = srm.GetNeighborsSnapshot();
Assert.AreEqual(1, neighbors.Count);
CompareObjects.Equals((SimpleRegionInfo)info, neighbors[0].RegionInfo);
response.Dispose();
req = HttpWebRequest.Create("http://127.0.0.1:9000/region2/regiondown");
req.Headers["authorization"] = Util.GenerateHttpAuthorization("key");
req.Timeout = 10000;
req.Method = "POST";
serRegInfo = OSDParser.SerializeLLSDBinary(info.PackRegionInfoData());
rs = req.GetRequestStream();
rs.Write(serRegInfo, 0, serRegInfo.Length);
rs.Flush();
response = req.GetResponse();
Assert.AreEqual(2, response.ContentLength);
sr = new StreamReader(response.GetResponseStream());
Assert.AreEqual("OK", sr.ReadToEnd());
neighbors = srm.GetNeighborsSnapshot();
Assert.AreEqual(0, neighbors.Count);
response.Dispose();
Assert.AreEqual(1, stateChangeCounts[NeighborStateChangeType.NeighborDown]);
stateChangeCounts.Clear();
}
[Test]
public void TestRegionPing()
{
RegionInfo info = new RegionInfo
{
ExternalHostName = "localhost",
InternalEndPoint = new System.Net.IPEndPoint(new System.Net.IPAddress(2130706433), 9001),
HttpPort = 9000,
OutsideIP = "127.0.0.1",
RegionID = UUID.Random(),
RegionLocX = 1100,
RegionLocY = 1000,
};
WebRequest req = HttpWebRequest.Create("http://127.0.0.1:9000/region2/regionup");
req.Headers["authorization"] = Util.GenerateHttpAuthorization("key");
req.Timeout = 10000;
req.Method = "POST";
byte[] serRegInfo = OSDParser.SerializeLLSDBinary(info.PackRegionInfoData());
var rs = req.GetRequestStream();
rs.Write(serRegInfo, 0, serRegInfo.Length);
rs.Flush();
var response = req.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
response.Dispose();
var neighbors = srm.GetNeighborsSnapshot();
var firstPing = neighbors[0].LastPingReceivedOn;
Thread.Sleep(1000);
req = HttpWebRequest.Create("http://127.0.0.1:9000/region2/heartbeat");
req.Headers["authorization"] = Util.GenerateHttpAuthorization("key");
req.Timeout = 10000;
req.Method = "POST";
serRegInfo = OSDParser.SerializeLLSDBinary(info.PackRegionInfoData());
rs = req.GetRequestStream();
rs.Write(serRegInfo, 0, serRegInfo.Length);
rs.Flush();
response = req.GetResponse();
Assert.AreEqual(2, response.ContentLength);
sr = new StreamReader(response.GetResponseStream());
Assert.AreEqual("OK", sr.ReadToEnd());
neighbors = srm.GetNeighborsSnapshot();
Assert.AreEqual(1, neighbors.Count);
Assert.Greater(neighbors[0].LastPingReceivedOn, firstPing);
response.Dispose();
Assert.AreEqual(1, stateChangeCounts[NeighborStateChangeType.NeighborPing]);
stateChangeCounts.Clear();
}
[Test]
public void TestUnauthorized()
{
RegionInfo info = new RegionInfo
{
ExternalHostName = "localhost",
InternalEndPoint = new System.Net.IPEndPoint(new System.Net.IPAddress(2130706433), 9001),
HttpPort = 9000,
OutsideIP = "127.0.0.1",
RegionID = UUID.Random(),
RegionLocX = 1100,
RegionLocY = 1000,
};
WebRequest req = HttpWebRequest.Create("http://127.0.0.1:9000/region2/regionup");
req.Headers["authorization"] = Util.GenerateHttpAuthorization("BADPASSWORD");
req.Timeout = 10000;
req.Method = "POST";
byte[] serRegInfo = OSDParser.SerializeLLSDBinary(info.PackRegionInfoData());
var rs = req.GetRequestStream();
rs.Write(serRegInfo, 0, serRegInfo.Length);
rs.Flush();
Assert.Throws<System.Net.WebException>(() =>
{
var response = req.GetResponse();
});
}
[Test]
public void TestQuerySurroundingRegions256()
{
// U = us at 1000, 1000
// N N N
// N U N
// N N N
//top row
SendCreateRegionMessage(999, 999, 9000, 9001);
SendCreateRegionMessage(1000, 999, 9000, 9001);
SendCreateRegionMessage(1001, 999, 9000, 9001);
//middle row
SendCreateRegionMessage(999, 1000, 9000, 9001);
SendCreateRegionMessage(1001, 1000, 9000, 9001);
//bottom row
SendCreateRegionMessage(999, 1001, 9000, 9001);
SendCreateRegionMessage(1000, 1001, 9000, 9001);
SendCreateRegionMessage(1001, 1001, 9000, 9001);
Assert.NotNull(srm.GetKnownNeighborAt(999, 999));
Assert.NotNull(srm.GetKnownNeighborAt(1000, 999));
Assert.NotNull(srm.GetKnownNeighborAt(1001, 999));
Assert.NotNull(srm.GetKnownNeighborAt(999, 1000));
Assert.NotNull(srm.GetKnownNeighborAt(1001, 1000));
Assert.NotNull(srm.GetKnownNeighborAt(999, 1001));
Assert.NotNull(srm.GetKnownNeighborAt(1000, 1001));
Assert.NotNull(srm.GetKnownNeighborAt(1001, 1001));
//try a surrounding query
Assert.AreEqual(8, srm.GetKnownNeighborsWithinClientDD(1).Count);
Assert.AreEqual(8, srm.GetKnownNeighborsWithinClientDD(256).Count);
}
[Test]
public void TestQuerySurroundingRegions512()
{
// U = us at 1000, 1000
// X X X X X
// X N N N X
// X N U N X
// X N N N X
// X X X X X
//top row
SendCreateRegionMessage(998, 998, 9000, 9001);
SendCreateRegionMessage(999, 998, 9000, 9001);
SendCreateRegionMessage(1000, 998, 9000, 9001);
SendCreateRegionMessage(1001, 998, 9000, 9001);
SendCreateRegionMessage(1002, 998, 9000, 9001);
//second row
SendCreateRegionMessage(998, 999, 9000, 9001);
SendCreateRegionMessage(999, 999, 9000, 9001);
SendCreateRegionMessage(1000, 999, 9000, 9001);
SendCreateRegionMessage(1001, 999, 9000, 9001);
SendCreateRegionMessage(1002, 999, 9000, 9001);
//middle row
SendCreateRegionMessage(998, 1000, 9000, 9001);
SendCreateRegionMessage(999, 1000, 9000, 9001);
SendCreateRegionMessage(1001, 1000, 9000, 9001);
SendCreateRegionMessage(1002, 1000, 9000, 9001);
//an extra to try to trip up the limiter
SendCreateRegionMessage(1003, 1000, 9000, 9001);
//second to last row
SendCreateRegionMessage(998, 1001, 9000, 9001);
SendCreateRegionMessage(999, 1001, 9000, 9001);
SendCreateRegionMessage(1000, 1001, 9000, 9001);
SendCreateRegionMessage(1001, 1001, 9000, 9001);
SendCreateRegionMessage(1002, 1001, 9000, 9001);
//last row
SendCreateRegionMessage(998, 1002, 9000, 9001);
SendCreateRegionMessage(999, 1002, 9000, 9001);
SendCreateRegionMessage(1000, 1002, 9000, 9001);
SendCreateRegionMessage(1001, 1002, 9000, 9001);
SendCreateRegionMessage(1002, 1002, 9000, 9001);
//top row
Assert.NotNull(srm.GetKnownNeighborAt(998, 998));
Assert.NotNull(srm.GetKnownNeighborAt(999, 998));
Assert.NotNull(srm.GetKnownNeighborAt(1000, 998));
Assert.NotNull(srm.GetKnownNeighborAt(1001, 998));
Assert.NotNull(srm.GetKnownNeighborAt(1002, 998));
//second row
Assert.NotNull(srm.GetKnownNeighborAt(998, 999));
Assert.NotNull(srm.GetKnownNeighborAt(999, 999));
Assert.NotNull(srm.GetKnownNeighborAt(1000, 999));
Assert.NotNull(srm.GetKnownNeighborAt(1001, 999));
Assert.NotNull(srm.GetKnownNeighborAt(1002, 999));
//middle row
Assert.NotNull(srm.GetKnownNeighborAt(998, 1000));
Assert.NotNull(srm.GetKnownNeighborAt(999, 1000));
Assert.NotNull(srm.GetKnownNeighborAt(1001, 1000));
Assert.NotNull(srm.GetKnownNeighborAt(1002, 1000));
//second to last row
Assert.NotNull(srm.GetKnownNeighborAt(998, 1001));
Assert.NotNull(srm.GetKnownNeighborAt(999, 1001));
Assert.NotNull(srm.GetKnownNeighborAt(1000, 1001));
Assert.NotNull(srm.GetKnownNeighborAt(1001, 1001));
Assert.NotNull(srm.GetKnownNeighborAt(1002, 1001));
//last row
Assert.NotNull(srm.GetKnownNeighborAt(998, 1002));
Assert.NotNull(srm.GetKnownNeighborAt(999, 1002));
Assert.NotNull(srm.GetKnownNeighborAt(1000, 1002));
Assert.NotNull(srm.GetKnownNeighborAt(1001, 1002));
Assert.NotNull(srm.GetKnownNeighborAt(1002, 1002));
//try a surrounding query
Assert.AreEqual(8, srm.GetKnownNeighborsWithinClientDD(1).Count);
Assert.AreEqual(8, srm.GetKnownNeighborsWithinClientDD(256).Count);
Assert.AreEqual(24, srm.GetKnownNeighborsWithinClientDD(257).Count);
Assert.AreEqual(24, srm.GetKnownNeighborsWithinClientDD(512).Count);
Assert.AreEqual(24, srm.GetKnownNeighborsWithinClientDD(1024).Count);
}
}
}
| |
#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 System.IO;
using Common.Logging;
using Spring.Util;
using IHttpHandler = System.Web.IHttpHandler;
using HttpException = System.Web.HttpException;
namespace Spring.Objects.Factory.Support
{
/// <summary>
/// Miscellaneous utility methods to support web functionality within Spring.Objects
/// </summary>
/// <author>Aleksandar Seovic</author>
public sealed class WebObjectUtils
{
private static ILog s_log = LogManager.GetLogger( typeof( WebObjectUtils ) );
// CLOVER:OFF
/// <summary>
/// Creates a new instance of the <see cref="Spring.Util.WebUtils"/> class.
/// </summary>
/// <remarks>
/// <p>
/// This is a utility class, and as such exposes no public constructors.
/// </p>
/// </remarks>
private WebObjectUtils()
{ }
// CLOVER:ON
/// <summary>
/// Creates an instance of the ASPX page
/// referred to by the supplied <paramref name="pageUrl"/>.
/// </summary>
/// <param name="pageUrl">
/// The URL of the ASPX page.
/// </param>
/// <returns>Page instance.</returns>
/// <exception cref="Spring.Objects.Factory.ObjectCreationException">
/// If this method is not called in the scope of an active web session
/// (i.e. the implementation this method depends on this code executing
/// in the environs of a running web server such as IIS); or if the
/// page could not be instantiated (for whatever reason, such as the
/// ASPX <paramref name="pageUrl"/> not actually existing).
/// </exception>
public static IHttpHandler CreatePageInstance( string pageUrl )
{
if (s_log.IsDebugEnabled)
{
s_log.Debug( "creating page instance '" + pageUrl + "'" );
}
IHttpHandler page;
try
{
page = CreateHandler( pageUrl );
}
catch (HttpException httpEx)
{
string msg = String.Format( "Unable to instantiate page [{0}]: {1}", pageUrl, httpEx.Message );
if (httpEx.GetHttpCode() == 404)
{
throw new FileNotFoundException( msg );
}
s_log.Error( msg, httpEx );
throw new ObjectCreationException( msg, httpEx );
}
catch (Exception ex)
{
// in case of FileNotFound recreate the exception for clarity
FileNotFoundException fnfe = ex as FileNotFoundException;
if (fnfe != null)
{
string fmsg = String.Format( "Unable to instantiate page [{0}]: The file '{1}' does not exist.", pageUrl, fnfe.Message );
throw new FileNotFoundException( fmsg );
}
string msg = String.Format( "Unable to instantiate page [{0}]", pageUrl );
s_log.Error( msg, ex );
throw new ObjectCreationException( msg, ex );
}
return page;
}
/// <summary>
/// Creates the raw handler instance without any exception handling
/// </summary>
/// <param name="pageUrl"></param>
/// <returns></returns>
internal static IHttpHandler CreateHandler( string pageUrl )
{
return VirtualEnvironment.CreateInstanceFromVirtualPath(pageUrl, typeof(IHttpHandler)) as IHttpHandler;
}
/// <summary>
/// Returns the <see cref="System.Type"/> of the ASPX page
/// referred to by the supplied <paramref name="pageUrl"/>.
/// </summary>
/// <remarks>
/// <p>
/// As indicated by the exception that can be thrown by this method,
/// the ASPX page referred to by the supplied <paramref name="pageUrl"/>
/// does have to be instantiated in order to determine its
/// see cref="System.Type"/>
/// </p>
/// </remarks>
/// <param name="pageUrl">
/// The filename of the ASPX page.
/// </param>
/// <returns>
/// The <see cref="System.Type"/> of the ASPX page
/// referred to by the supplied <paramref name="pageUrl"/>.
/// </returns>
/// <exception cref="System.ArgumentNullException">
/// If the supplied <paramref name="pageUrl"/> is <see langword="null"/> or
/// contains only whitespace character(s).
/// </exception>
/// <exception cref="Spring.Objects.Factory.ObjectCreationException">
/// If this method is not called in the scope of an active web session
/// (i.e. the implementation this method depends on this code executing
/// in the environs of a running web server such as IIS); or if the
/// page could not be instantiated (for whatever reason, such as the
/// ASPX <paramref name="pageUrl"/> not actually existing).
/// </exception>
public static Type GetPageType( string pageUrl )
{
AssertUtils.ArgumentHasText( pageUrl, "pageUrl" );
// HttpContext ctx = HttpContext.Current;
// if (ctx == null)
// {
// throw new ObjectCreationException( "Unable to get page type. HttpContext is not defined." );
// }
try
{
Type pageType = GetCompiledPageType( pageUrl );
return pageType;
}
catch (Exception ex)
{
string msg = String.Format( "Unable to get page type for url [{0}]", pageUrl );
s_log.Error( msg, ex );
throw new ObjectCreationException( msg, ex );
}
}
/// <summary>
/// Calls the underlying ASP.NET infrastructure to obtain the compiled page type
/// relative to the current <see cref="System.Web.HttpRequest.CurrentExecutionFilePath"/>.
/// </summary>
/// <param name="pageUrl">
/// The filename of the ASPX page relative to the current <see cref="System.Web.HttpRequest.CurrentExecutionFilePath"/>
/// </param>
/// <returns>
/// The <see cref="System.Type"/> of the ASPX page
/// referred to by the supplied <paramref name="pageUrl"/>.
/// </returns>
public static Type GetCompiledPageType( string pageUrl )
{
if (s_log.IsDebugEnabled)
{
s_log.Debug( "getting page type for " + pageUrl );
}
string rootedVPath = WebUtils.CombineVirtualPaths( VirtualEnvironment.CurrentExecutionFilePath, pageUrl );
if (s_log.IsDebugEnabled)
{
s_log.Debug( "page vpath is " + rootedVPath );
}
Type pageType = VirtualEnvironment.GetCompiledType(rootedVPath);
if (s_log.IsDebugEnabled)
{
s_log.Debug( string.Format( "got page type '{0}' for vpath '{1}'", pageType.FullName, rootedVPath ) );
}
return pageType;
}
/// <summary>
/// Gets the controls type from a given filename
/// </summary>
public static Type GetControlType( string controlName )
{
AssertUtils.ArgumentHasText( controlName, "controlName" );
if (s_log.IsDebugEnabled)
{
s_log.Debug( "getting control type for " + controlName );
}
// HttpContext ctx = HttpContext.Current;
// if (ctx == null)
// {
// throw new ObjectCreationException( "Unable to get control type. HttpContext is not defined." );
// }
string rootedVPath = WebUtils.CombineVirtualPaths( VirtualEnvironment.CurrentExecutionFilePath, controlName );
if (s_log.IsDebugEnabled)
{
s_log.Debug( "control vpath is " + rootedVPath );
}
Type controlType;
try
{
controlType = VirtualEnvironment.GetCompiledType(rootedVPath);
}
catch (HttpException httpEx)
{
// for better error-handling suppress 404 HttpExceptions here
if (httpEx.GetHttpCode() == 404)
{
throw new FileNotFoundException( string.Format( "Control '{0}' does not exist", rootedVPath ) );
}
throw;
}
if (s_log.IsDebugEnabled)
{
s_log.Debug( string.Format( "got control type '{0}' for vpath '{1}'", controlType.FullName, rootedVPath ) );
}
return controlType;
}
}
}
| |
// 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.Net.Security;
using System.Net.Test.Common;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework throws PNSE for ServerCertificateCustomValidationCallback")]
public partial class HttpClientHandler_ServerCertificates_Test : RemoteExecutorTestBase
{
// TODO: https://github.com/dotnet/corefx/issues/7812
private static bool ClientSupportsDHECipherSuites => (!PlatformDetection.IsWindows || PlatformDetection.IsWindows10Version1607OrGreater);
private static bool BackendSupportsCustomCertificateHandlingAndClientSupportsDHECipherSuites =>
(BackendSupportsCustomCertificateHandling && ClientSupportsDHECipherSuites);
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.Uap)]
public void Ctor_ExpectedDefaultPropertyValues_UapPlatform()
{
using (var handler = new HttpClientHandler())
{
Assert.Null(handler.ServerCertificateCustomValidationCallback);
Assert.True(handler.CheckCertificateRevocationList);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
public void Ctor_ExpectedDefaultValues_NotUapPlatform()
{
using (var handler = new HttpClientHandler())
{
Assert.Null(handler.ServerCertificateCustomValidationCallback);
Assert.False(handler.CheckCertificateRevocationList);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task NoCallback_ValidCertificate_SuccessAndExpectedPropertyBehavior()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.SecureRemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.Throws<InvalidOperationException>(() => handler.ServerCertificateCustomValidationCallback = null);
Assert.Throws<InvalidOperationException>(() => handler.CheckCertificateRevocationList = false);
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP won't send requests through a custom proxy")]
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_HaveNoCredsAndUseAuthenticatedCustomProxyAndPostToSecureServer_ProxyAuthenticationRequiredStatusCode()
{
if (ManagedHandlerTestHelpers.IsEnabled)
{
return; // TODO #21452: SSL proxy tunneling not yet implemented in ManagedHandler
}
int port;
Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(
out port,
requireAuth: true,
expectCreds: false);
Uri proxyUrl = new Uri($"http://localhost:{port}");
var handler = new HttpClientHandler();
handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, null);
handler.ServerCertificateCustomValidationCallback = delegate { return true; };
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> responseTask = client.PostAsync(
Configuration.Http.SecureRemoteEchoServer,
new StringContent("This is a test"));
await TestHelper.WhenAllCompletedOrAnyFailed(proxyTask, responseTask);
using (responseTask.Result)
{
Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, responseTask.Result.StatusCode);
}
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task UseCallback_NotSecureConnection_CallbackNotCalled()
{
if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
{
Console.WriteLine($"Skipping {nameof(UseCallback_NotSecureConnection_CallbackNotCalled)}()");
return;
}
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = delegate { callbackCalled = true; return true; };
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.False(callbackCalled);
}
}
public static IEnumerable<object[]> UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls()
{
foreach (bool checkRevocation in new[] { true, false })
{
yield return new object[] { Configuration.Http.SecureRemoteEchoServer, checkRevocation };
yield return new object[] {
Configuration.Http.RedirectUriForDestinationUri(
secure:true,
statusCode:302,
destinationUri:Configuration.Http.SecureRemoteEchoServer,
hops:1),
checkRevocation };
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls))]
public async Task UseCallback_ValidCertificate_ExpectedValuesDuringCallback(Uri url, bool checkRevocation)
{
if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
{
Console.WriteLine($"Skipping {nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback)}({url}, {checkRevocation})");
return;
}
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.CheckCertificateRevocationList = checkRevocation;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => {
callbackCalled = true;
Assert.NotNull(request);
Assert.Equal(SslPolicyErrors.None, errors);
Assert.True(chain.ChainElements.Count > 0);
Assert.NotEmpty(cert.Subject);
// UWP always uses CheckCertificateRevocationList=true regardless of setting the property and
// the getter always returns true. So, for this next Assert, it is better to get the property
// value back from the handler instead of using the parameter value of the test.
Assert.Equal(
handler.CheckCertificateRevocationList ? X509RevocationMode.Online : X509RevocationMode.NoCheck,
chain.ChainPolicy.RevocationMode);
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task UseCallback_CallbackReturnsFailure_ThrowsException()
{
if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
{
Console.WriteLine($"Skipping {nameof(UseCallback_CallbackReturnsFailure_ThrowsException)}()");
return;
}
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = delegate { return false; };
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[ActiveIssue(21904, ~TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_CallbackThrowsException_ExceptionPropagatesAsInnerException()
{
if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
{
Console.WriteLine($"Skipping {nameof(UseCallback_CallbackThrowsException_ExceptionPropagatesAsInnerException)}()");
return;
}
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
var e = new DivideByZeroException();
handler.ServerCertificateCustomValidationCallback = delegate { throw e; };
HttpRequestException ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
Assert.Same(e, ex.InnerException);
}
}
public static readonly object[][] CertificateValidationServers =
{
new object[] { Configuration.Http.ExpiredCertRemoteServer },
new object[] { Configuration.Http.SelfSignedCertRemoteServer },
new object[] { Configuration.Http.WrongHostNameCertRemoteServer },
};
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(ClientSupportsDHECipherSuites))]
[MemberData(nameof(CertificateValidationServers))]
public async Task NoCallback_BadCertificate_ThrowsException(string url)
{
using (var client = new HttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url));
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP doesn't allow revocation checking to be turned off")]
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(ClientSupportsDHECipherSuites))]
public async Task NoCallback_RevokedCertificate_NoRevocationChecking_Succeeds()
{
// On macOS (libcurl+darwinssl) we cannot turn revocation off.
// But we also can't realistically say that the default value for
// CheckCertificateRevocationList throws in the general case.
try
{
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RevokedCertRemoteServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
catch (HttpRequestException)
{
if (!ShouldSuppressRevocationException)
throw;
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task NoCallback_RevokedCertificate_RevocationChecking_Fails()
{
if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
{
Console.WriteLine($"Skipping {nameof(NoCallback_RevokedCertificate_RevocationChecking_Fails)}()");
return;
}
var handler = new HttpClientHandler() { CheckCertificateRevocationList = true };
using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.RevokedCertRemoteServer));
}
}
public static readonly object[][] CertificateValidationServersAndExpectedPolicies =
{
new object[] { Configuration.Http.ExpiredCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors },
new object[] { Configuration.Http.SelfSignedCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors },
new object[] { Configuration.Http.WrongHostNameCertRemoteServer , SslPolicyErrors.RemoteCertificateNameMismatch},
};
public async Task UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(string url, SslPolicyErrors expectedErrors)
{
if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
{
Console.WriteLine($"Skipping {nameof(UseCallback_BadCertificate_ExpectedPolicyErrors)}({url}, {expectedErrors})");
return;
}
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) =>
{
callbackCalled = true;
Assert.NotNull(request);
Assert.NotNull(cert);
Assert.NotNull(chain);
if (!ManagedHandlerTestHelpers.IsEnabled)
{
// TODO #21452: This test is failing with the managed handler on the exact value of the managed errors,
// e.g. reporting "RemoteCertificateNameMismatch, RemoteCertificateChainErrors" when we only expect
// "RemoteCertificateChainErrors"
Assert.Equal(expectedErrors, errors);
}
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(BackendSupportsCustomCertificateHandlingAndClientSupportsDHECipherSuites))]
[MemberData(nameof(CertificateValidationServersAndExpectedPolicies))]
public async Task UseCallback_BadCertificate_ExpectedPolicyErrors(string url, SslPolicyErrors expectedErrors)
{
if (PlatformDetection.IsUap)
{
// UAP HTTP stack caches connections per-process. This causes interference when these tests run in
// the same process as the other tests. Each test needs to be isolated to its own process.
// See dicussion: https://github.com/dotnet/corefx/issues/21945
RemoteInvoke((remoteUrl, remoteExpectedErrors) =>
{
UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(
remoteUrl,
(SslPolicyErrors)Enum.Parse(typeof(SslPolicyErrors), remoteExpectedErrors)).Wait();
return SuccessExitCode;
}, url, expectedErrors.ToString()).Dispose();
}
else
{
await UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(url, expectedErrors);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task SSLBackendNotSupported_Callback_ThrowsPlatformNotSupportedException()
{
if (BackendSupportsCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
{
return;
}
using (var client = new HttpClient(new HttpClientHandler() { ServerCertificateCustomValidationCallback = delegate { return true; } }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
// For macOS the "custom handling" means that revocation can't be *disabled*. So this test does not apply.
[PlatformSpecific(~TestPlatforms.OSX)]
public async Task SSLBackendNotSupported_Revocation_ThrowsPlatformNotSupportedException()
{
if (BackendSupportsCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
{
return;
}
using (var client = new HttpClient(new HttpClientHandler() { CheckCertificateRevocationList = true }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop] // TODO: Issue #11345
[PlatformSpecific(TestPlatforms.Windows)] // CopyToAsync(Stream, TransportContext) isn't used on unix
[Fact]
public async Task PostAsync_Post_ChannelBinding_ConfiguredCorrectly()
{
var content = new ChannelBindingAwareContent("Test contest");
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.SecureRemoteEchoServer, content))
{
// Validate status.
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Validate the ChannelBinding object exists.
ChannelBinding channelBinding = content.ChannelBinding;
if (PlatformDetection.IsUap)
{
// UAP currently doesn't expose channel binding information.
Assert.Null(channelBinding);
}
else
{
Assert.NotNull(channelBinding);
// Validate the ChannelBinding's validity.
if (BackendSupportsCustomCertificateHandling)
{
Assert.False(channelBinding.IsInvalid, "Expected valid binding");
Assert.NotEqual(IntPtr.Zero, channelBinding.DangerousGetHandle());
// Validate the ChannelBinding's description.
string channelBindingDescription = channelBinding.ToString();
Assert.NotNull(channelBindingDescription);
Assert.NotEmpty(channelBindingDescription);
Assert.True((channelBindingDescription.Length + 1) % 3 == 0, $"Unexpected length {channelBindingDescription.Length}");
for (int i = 0; i < channelBindingDescription.Length; i++)
{
char c = channelBindingDescription[i];
if (i % 3 == 2)
{
Assert.Equal(' ', c);
}
else
{
Assert.True((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'), $"Expected hex, got {c}");
}
}
}
else
{
// Backend doesn't support getting the details to create the CBT.
Assert.True(channelBinding.IsInvalid, "Expected invalid binding");
Assert.Equal(IntPtr.Zero, channelBinding.DangerousGetHandle());
Assert.Null(channelBinding.ToString());
}
}
}
}
}
}
| |
namespace NArrange.Tests.Core.Configuration
{
using System;
using NArrange.Core;
using NArrange.Core.Configuration;
using NUnit.Framework;
/// <summary>
/// Test fixture for the FilterExpressionParser class.
/// </summary>
[TestFixture]
public class ConditionExpressionParserTests
{
#region Methods
/// <summary>
/// Tests parsing an AND expression.
/// </summary>
[Test]
public void ParseAndExpressionTest()
{
Action<string> testExpression = delegate(string condition)
{
IConditionExpression expression = ConditionExpressionParser.Instance.Parse(
condition);
Assert.IsNotNull(expression, "Expected an expression instance.");
BinaryOperatorExpression operatorExpression = expression as BinaryOperatorExpression;
Assert.IsNotNull(operatorExpression, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.And, operatorExpression.Operator, "Unexpected operator.");
//
// Left
//
BinaryOperatorExpression leftExpression = expression.Left as BinaryOperatorExpression;
Assert.IsNotNull(leftExpression, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Equal, leftExpression.Operator, "Unexpected operator.");
ElementAttributeExpression leftAttributeExpression = leftExpression.Left as ElementAttributeExpression;
Assert.IsNotNull(leftAttributeExpression, "Unexpected left node type.");
Assert.AreEqual(ElementAttributeType.Name, leftAttributeExpression.ElementAttribute, "Attribute expression was not parsed correctly.");
StringExpression leftStringExpression = leftExpression.Right as StringExpression;
Assert.IsNotNull(leftStringExpression, "Unexpected right node type.");
Assert.AreEqual("Test 1", leftStringExpression.Text, "String expression was not parsed correctly.");
//
// Right
//
BinaryOperatorExpression rightExpression = expression.Right as BinaryOperatorExpression;
Assert.IsNotNull(rightExpression, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Equal, rightExpression.Operator, "Unexpected operator.");
ElementAttributeExpression rightAttributeExpression = rightExpression.Left as ElementAttributeExpression;
Assert.IsNotNull(rightAttributeExpression, "Unexpected left node type.");
Assert.AreEqual(ElementAttributeType.Name, rightAttributeExpression.ElementAttribute, "Attribute expression was not parsed correctly.");
StringExpression rightStringExpression = rightExpression.Right as StringExpression;
Assert.IsNotNull(rightStringExpression, "Unexpected right node type.");
Assert.AreEqual("Test 2", rightStringExpression.Text, "String expression was not parsed correctly.");
};
string expressionText;
expressionText = "($(Name) == 'Test 1') And ($(Name) == 'Test 2')";
testExpression(expressionText);
expressionText = "$(Name) == 'Test 1' And $(Name) == 'Test 2'";
testExpression(expressionText);
}
/// <summary>
/// Tests parsing an expression.
/// </summary>
[Test]
public void ParseAndOrExpressionTest()
{
Action<string> testExpression = delegate(string condition)
{
IConditionExpression expression = ConditionExpressionParser.Instance.Parse(
condition);
Assert.IsNotNull(expression, "Expected an expression instance.");
BinaryOperatorExpression operatorExpression = expression as BinaryOperatorExpression;
Assert.IsNotNull(operatorExpression, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.And, operatorExpression.Operator, "Unexpected operator.");
//
// And left
//
BinaryOperatorExpression testExpression3 = operatorExpression.Left as BinaryOperatorExpression;
Assert.IsNotNull(testExpression3, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Equal, testExpression3.Operator, "Unexpected operator.");
ElementAttributeExpression test3AttributeExpression = testExpression3.Left as ElementAttributeExpression;
Assert.IsNotNull(test3AttributeExpression, "Unexpected left node type.");
Assert.AreEqual(ElementAttributeType.Name, test3AttributeExpression.ElementAttribute, "Attribute expression was not parsed correctly.");
StringExpression test3StringExpression = testExpression3.Right as StringExpression;
Assert.IsNotNull(test3StringExpression, "Unexpected right node type.");
Assert.AreEqual("Test 3", test3StringExpression.Text, "String expression was not parsed correctly.");
//
// And right
//
BinaryOperatorExpression orRightExpression = operatorExpression.Right as BinaryOperatorExpression;
Assert.IsNotNull(orRightExpression, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Or, orRightExpression.Operator, "Unexpected operator.");
//
// Or Left
//
BinaryOperatorExpression orLeftExpression = orRightExpression.Left as BinaryOperatorExpression;
Assert.IsNotNull(orLeftExpression, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Equal, orLeftExpression.Operator, "Unexpected operator.");
ElementAttributeExpression test1AttributeExpression = orLeftExpression.Left as ElementAttributeExpression;
Assert.IsNotNull(test1AttributeExpression, "Unexpected left node type.");
Assert.AreEqual(ElementAttributeType.Name, test1AttributeExpression.ElementAttribute, "Attribute expression was not parsed correctly.");
StringExpression test1StringExpression = orLeftExpression.Right as StringExpression;
Assert.IsNotNull(test1StringExpression, "Unexpected right node type.");
Assert.AreEqual("Test 1", test1StringExpression.Text, "String expression was not parsed correctly.");
//
// Or Right
//
BinaryOperatorExpression testExpression2 = orRightExpression.Right as BinaryOperatorExpression;
Assert.IsNotNull(testExpression2, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Equal, testExpression2.Operator, "Unexpected operator.");
ElementAttributeExpression test2AttributeExpression = testExpression2.Left as ElementAttributeExpression;
Assert.IsNotNull(test2AttributeExpression, "Unexpected left node type.");
Assert.AreEqual(ElementAttributeType.Name, test2AttributeExpression.ElementAttribute, "Attribute expression was not parsed correctly.");
StringExpression test2StringExpression = testExpression2.Right as StringExpression;
Assert.IsNotNull(test2StringExpression, "Unexpected right node type.");
Assert.AreEqual("Test 2", test2StringExpression.Text, "String expression was not parsed correctly.");
};
string expressionText;
expressionText = "($(Name) == 'Test 3') And (($(Name) == 'Test 1') Or ($(Name) == 'Test 2'))";
testExpression(expressionText);
expressionText = "$(Name) == 'Test 3' And ($(Name) == 'Test 1' Or $(Name) == 'Test 2')";
}
/// <summary>
/// Tests parsing a complex negate expression.
/// </summary>
[Test]
public void ParseComplexNegateTest()
{
string expression =
"!($(Element.Name) : 'Test' Or $(Access) == 'Protected' Or " +
"$(Access) == 'Private' And $(Element.Name) : 'OrAnd' And $(Type) == 'int')";
IConditionExpression conditionExpression = ConditionExpressionParser.Instance.Parse(
expression);
Assert.IsNotNull(conditionExpression, "Expected an expression instance.");
string expressionString = conditionExpression.ToString();
Assert.AreEqual(
"!(((($(Element.Name) : 'Test') Or ($(Element.Access) == 'Protected')) Or " +
"((($(Element.Access) == 'Private') And ($(Element.Name) : 'OrAnd')) And ($(Element.Type) == 'int'))))",
expressionString,
"Unexpected parsed expression.");
// Parse the ToString representation and verify we get the same result
conditionExpression = ConditionExpressionParser.Instance.Parse(
expressionString);
Assert.AreEqual(expressionString, conditionExpression.ToString(), "Unexpected parsed expression.");
}
/// <summary>
/// Tests parsing a complex expression.
/// </summary>
[Test]
public void ParseComplexTest()
{
string expression =
"$(Element.Name) : 'Test' Or $(Access) == 'Protected' Or " +
"$(Access) == 'Private' And $(Element.Name) : 'OrAnd' And $(Type) == 'int'";
IConditionExpression conditionExpression = ConditionExpressionParser.Instance.Parse(
expression);
Assert.IsNotNull(conditionExpression, "Expected an expression instance.");
string expressionString = conditionExpression.ToString();
Assert.AreEqual(
"((($(Element.Name) : 'Test') Or ($(Element.Access) == 'Protected')) Or " +
"((($(Element.Access) == 'Private') And ($(Element.Name) : 'OrAnd')) And ($(Element.Type) == 'int')))",
expressionString,
"Unexpected parsed expression.");
// Parse the ToString representation and verify we get the same result
conditionExpression = ConditionExpressionParser.Instance.Parse(
expressionString);
Assert.AreEqual(expressionString, conditionExpression.ToString(), "Unexpected parsed expression.");
}
/// <summary>
/// Tests parsing a null expression.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void ParseEmptyTest()
{
IConditionExpression expression = ConditionExpressionParser.Instance.Parse(
string.Empty);
}
/// <summary>
/// Tests parsing an equals expression.
/// </summary>
[Test]
public void ParseEqualsExpressionTest()
{
string[] variations = new string[]
{
"$(Name) == 'Test'",
"$(Name) == 'Test'",
"($(Name) == 'Test')",
"(($(Name) == 'Test'))"
};
foreach (string variation in variations)
{
try
{
IConditionExpression expression = ConditionExpressionParser.Instance.Parse(
variation);
Assert.IsNotNull(expression, "Expected an expression instance for {0}", variation);
BinaryOperatorExpression operatorExpression = expression as BinaryOperatorExpression;
Assert.IsNotNull(operatorExpression, "Expected an operator expression for {0}", variation);
Assert.AreEqual(BinaryExpressionOperator.Equal, operatorExpression.Operator, "Unexpected operator");
ElementAttributeExpression attributeExpression = operatorExpression.Left as ElementAttributeExpression;
Assert.IsNotNull(attributeExpression, "Unexpected left node type.");
Assert.AreEqual(ElementAttributeType.Name, attributeExpression.ElementAttribute, "Attribute expression was not parsed correctly.");
Assert.AreEqual(ElementAttributeScope.Element, attributeExpression.Scope, "Attribute scope was not parsed correctly.");
StringExpression stringExpression = operatorExpression.Right as StringExpression;
Assert.IsNotNull(stringExpression, "Unexpected right node type.");
Assert.AreEqual("Test", stringExpression.Text, "String expression was not parsed correctly.");
}
catch (FormatException ex)
{
Assert.Fail(ex.Message);
}
}
}
/// <summary>
/// Tests parsing a file name contains expression.
/// </summary>
[Test]
public void ParseFileNameContainsExpressionTest()
{
string expressionText = "$(File.Name) : '.Designer.'";
IConditionExpression expression = ConditionExpressionParser.Instance.Parse(
expressionText);
Assert.IsNotNull(expression, "Expected an expression instance.");
BinaryOperatorExpression operatorExpression = expression as BinaryOperatorExpression;
Assert.IsNotNull(operatorExpression, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Contains, operatorExpression.Operator, "Unexpected operator.");
FileAttributeExpression attributeExpression = operatorExpression.Left as FileAttributeExpression;
Assert.IsNotNull(attributeExpression, "Unexpected left node type.");
Assert.AreEqual(FileAttributeType.Name, attributeExpression.FileAttribute, "Attribute expression was not parsed correctly.");
StringExpression stringExpression = operatorExpression.Right as StringExpression;
Assert.IsNotNull(stringExpression, "Unexpected right node type.");
Assert.AreEqual(".Designer.", stringExpression.Text, "String expression was not parsed correctly.");
}
/// <summary>
/// Tests parsing a file name doesn't contain expression.
/// </summary>
[Test]
public void ParseFileNotNameContainsExpressionTest()
{
string expressionText = "!($(File.Name) : '.Designer.')";
IConditionExpression expression = ConditionExpressionParser.Instance.Parse(
expressionText);
Assert.IsNotNull(expression, "Expected an expression instance.");
UnaryOperatorExpression negateExpression = expression as UnaryOperatorExpression;
Assert.IsNotNull(negateExpression, "Expected a unary operator expression.");
Assert.AreEqual(UnaryExpressionOperator.Negate, negateExpression.Operator, "Unexpected operator.");
BinaryOperatorExpression operatorExpression = negateExpression.InnerExpression as BinaryOperatorExpression;
Assert.IsNotNull(operatorExpression, "Expected a binary operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Contains, operatorExpression.Operator, "Unexpected operator.");
FileAttributeExpression attributeExpression = operatorExpression.Left as FileAttributeExpression;
Assert.IsNotNull(attributeExpression, "Unexpected left node type.");
Assert.AreEqual(FileAttributeType.Name, attributeExpression.FileAttribute, "Attribute expression was not parsed correctly.");
StringExpression stringExpression = operatorExpression.Right as StringExpression;
Assert.IsNotNull(stringExpression, "Unexpected right node type.");
Assert.AreEqual(".Designer.", stringExpression.Text, "String expression was not parsed correctly.");
}
/// <summary>
/// Tests parsing an invalid attribute scope.
/// </summary>
[Test]
[ExpectedException(typeof(FormatException),
MatchType = MessageMatch.Contains,
ExpectedMessage = "Unknown attribute scope")]
public void ParseInvalidAttributeScopeTest()
{
string expression = "$(Foo.Name) : 'Test'";
IConditionExpression conditionExpression = ConditionExpressionParser.Instance.Parse(
expression);
}
/// <summary>
/// Tests parsing an invalid attribute name.
/// </summary>
[Test]
[ExpectedException(typeof(FormatException))]
public void ParseInvalidAttributeTest()
{
string expression = "$(Or) : 'Test'";
IConditionExpression conditionExpression = ConditionExpressionParser.Instance.Parse(
expression);
}
/// <summary>
/// Tests parsing an invalid binary operator.
/// </summary>
[Test]
[ExpectedException(typeof(FormatException),
MatchType = MessageMatch.Contains,
ExpectedMessage = "Invalid operator #")]
public void ParseInvalidBinaryOperatorTest1()
{
string expression = "$(File.Name) # 'Or')";
IConditionExpression conditionExpression = ConditionExpressionParser.Instance.Parse(
expression);
}
/// <summary>
/// Tests parsing an invalid binary operator.
/// </summary>
[Test]
[ExpectedException(typeof(FormatException),
MatchType = MessageMatch.Contains,
ExpectedMessage = "Invalid operator #")]
public void ParseInvalidBinaryOperatorTest2()
{
string expression = "$(File.Name) : 'Or' # ($(File.Name) : 'And')";
IConditionExpression conditionExpression = ConditionExpressionParser.Instance.Parse(
expression);
}
/// <summary>
/// Tests parsing an invalid cased binary operator.
/// </summary>
[Test]
[ExpectedException(typeof(FormatException),
MatchType = MessageMatch.Contains,
ExpectedMessage = "Invalid operator or")]
public void ParseInvalidCasedBinaryOperatorTest()
{
string expression = "$(File.Name) : 'Or' or $(File.Name) : 'And'";
IConditionExpression conditionExpression = ConditionExpressionParser.Instance.Parse(
expression);
}
/// <summary>
/// Tests parsing an invalid expression.
/// </summary>
[Test]
[ExpectedException(typeof(FormatException),
MatchType = MessageMatch.Contains,
ExpectedMessage = "Unmatched )")]
public void ParseInvalidExpressionExtraParenthesesTest1()
{
string expression = "($(Name) == 'Test'))";
IConditionExpression conditionExpression = ConditionExpressionParser.Instance.Parse(
expression);
}
/// <summary>
/// Tests parsing an invalid expression.
/// </summary>
[Test]
[ExpectedException(typeof(FormatException),
MatchType = MessageMatch.Contains,
ExpectedMessage = "Unmatched )")]
public void ParseInvalidExpressionExtraParenthesesTest2()
{
string expression = "$(Name) == 'Test')";
IConditionExpression conditionExpression = ConditionExpressionParser.Instance.Parse(
expression);
}
/// <summary>
/// Tests parsing an invalid expression.
/// </summary>
[Test]
[ExpectedException(typeof(FormatException))]
public void ParseInvalidExpressionMissingOperatorTest()
{
string expression = "$(Name) == 'Test' $(Name) == 'Foo'";
IConditionExpression conditionExpression = ConditionExpressionParser.Instance.Parse(
expression);
}
/// <summary>
/// Tests parsing an invalid expression.
/// </summary>
[Test]
[ExpectedException(typeof(FormatException),
MatchType = MessageMatch.Contains,
ExpectedMessage = "Expected )")]
public void ParseInvalidExpressionMissingParenthesesTest()
{
string expression = "($(Name) == 'Test'";
IConditionExpression conditionExpression = ConditionExpressionParser.Instance.Parse(
expression);
}
/// <summary>
/// Tests parsing an invalid expression.
/// </summary>
[Test]
[ExpectedException(typeof(FormatException),
MatchType = MessageMatch.Contains,
ExpectedMessage = "Expected '")]
public void ParseInvalidExpressionMissingQuoteTest()
{
string expression = "$(Name) == 'Test";
IConditionExpression conditionExpression = ConditionExpressionParser.Instance.Parse(
expression);
}
/// <summary>
/// Tests parsing an invalid expression.
/// </summary>
[Test]
[ExpectedException(typeof(FormatException))]
public void ParseInvalidExpressionNoOperatorTest()
{
string expression = "$(Name)";
IConditionExpression conditionExpression = ConditionExpressionParser.Instance.Parse(
expression);
}
/// <summary>
/// Tests parsing an invalid expression.
/// </summary>
[Test]
[ExpectedException(typeof(FormatException))]
public void ParseInvalidExpressionNoTermsTest()
{
string expression = "()";
IConditionExpression conditionExpression = ConditionExpressionParser.Instance.Parse(
expression);
}
/// <summary>
/// Tests parsing an invalid expression.
/// </summary>
[Test]
[ExpectedException(typeof(FormatException))]
public void ParseInvalidExpressionStringTest()
{
string expression = "'Test'";
IConditionExpression conditionExpression = ConditionExpressionParser.Instance.Parse(
expression);
}
/// <summary>
/// Tests parsing an invalid expression.
/// </summary>
[Test]
[ExpectedException(typeof(FormatException))]
public void ParseInvalidExpressionTooManyTermsTest()
{
string expression = "$(Name) == 'Test' == $(Name)";
IConditionExpression conditionExpression = ConditionExpressionParser.Instance.Parse(
expression);
}
/// <summary>
/// Tests parsing an invalid file attribute.
/// </summary>
[Test]
[ExpectedException(typeof(FormatException),
MatchType = MessageMatch.Contains,
ExpectedMessage = "Unknown attribute")]
public void ParseInvalidFileAttributeScopeTest()
{
string expression = "$(File.Blah) : 'Test'";
IConditionExpression conditionExpression = ConditionExpressionParser.Instance.Parse(
expression);
}
/// <summary>
/// Tests parsing an invalid nested expression.
/// </summary>
[Test]
[ExpectedException(typeof(FormatException))]
public void ParseInvalidNestedExpressionTest()
{
string expression = "$(File.Name) : 'Test' And ()";
IConditionExpression conditionExpression = ConditionExpressionParser.Instance.Parse(
expression);
}
/// <summary>
/// Tests parsing an invalid unary operator.
/// </summary>
[Test]
[ExpectedException(typeof(FormatException),
MatchType = MessageMatch.Contains,
ExpectedMessage = "Invalid operator #")]
public void ParseInvalidUnaryOperatorTest()
{
string expression = "#($(File.Name) : 'Or')";
IConditionExpression conditionExpression = ConditionExpressionParser.Instance.Parse(
expression);
}
/// <summary>
/// Tests parsing a regular expression match expression.
/// </summary>
[Test]
public void ParseMatchesExpressionTest()
{
string expressionText = "$(Name) =~ '.*\\.Tests\\..*'";
IConditionExpression expression = ConditionExpressionParser.Instance.Parse(
expressionText);
Assert.IsNotNull(expression, "Expected an expression instance.");
BinaryOperatorExpression operatorExpression = expression as BinaryOperatorExpression;
Assert.IsNotNull(operatorExpression, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Matches, operatorExpression.Operator, "Unexpected operator.");
ElementAttributeExpression attributeExpression = operatorExpression.Left as ElementAttributeExpression;
Assert.IsNotNull(attributeExpression, "Unexpected left node type.");
Assert.AreEqual(ElementAttributeType.Name, attributeExpression.ElementAttribute, "Attribute expression was not parsed correctly.");
Assert.AreEqual(ElementAttributeScope.Element, attributeExpression.Scope, "Attribute scope was not parsed correctly.");
StringExpression stringExpression = operatorExpression.Right as StringExpression;
Assert.IsNotNull(stringExpression, "Unexpected right node type.");
Assert.AreEqual(".*\\.Tests\\..*", stringExpression.Text, "String expression was not parsed correctly.");
}
/// <summary>
/// Tests parsing a negation expression.
/// </summary>
[Test]
public void ParseNegateExpressionTest()
{
string[] variations = new string[]
{
"!($(Name) : 'Test')",
"!(($(Name) : 'Test'))",
"!((($(Name) : 'Test')))"
};
foreach (string variation in variations)
{
IConditionExpression expression = ConditionExpressionParser.Instance.Parse(
variation);
Assert.IsNotNull(expression, "Expected an expression instance from {0}", variation);
UnaryOperatorExpression negateExpression = expression as UnaryOperatorExpression;
Assert.IsNotNull(negateExpression, "Expected a unary operator expression from {0}", variation);
Assert.AreEqual(UnaryExpressionOperator.Negate, negateExpression.Operator, "Unexpected operator.");
BinaryOperatorExpression binaryOperatorExpression = negateExpression.InnerExpression as BinaryOperatorExpression;
Assert.IsNotNull(binaryOperatorExpression, "Expected a binary operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Contains, binaryOperatorExpression.Operator, "Unexpected operator.");
ElementAttributeExpression attributeExpression = binaryOperatorExpression.Left as ElementAttributeExpression;
Assert.IsNotNull(attributeExpression, "Unexpected left node type.");
Assert.AreEqual(ElementAttributeType.Name, attributeExpression.ElementAttribute, "Attribute expression was not parsed correctly.");
Assert.AreEqual(ElementAttributeScope.Element, attributeExpression.Scope, "Attribute scope was not parsed correctly.");
StringExpression stringExpression = binaryOperatorExpression.Right as StringExpression;
Assert.IsNotNull(stringExpression, "Unexpected right node type.");
Assert.AreEqual("Test", stringExpression.Text, "String expression was not parsed correctly.");
}
}
/// <summary>
/// Tests parsing a null expression.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void ParseNullTest()
{
IConditionExpression expression = ConditionExpressionParser.Instance.Parse(
null);
}
/// <summary>
/// Tests parsing an expression.
/// </summary>
[Test]
public void ParseOrAndExpressionTest1()
{
Action<string> testExpression = delegate(string condition)
{
IConditionExpression expression = ConditionExpressionParser.Instance.Parse(
condition);
Assert.IsNotNull(expression, "Expected an expression instance.");
BinaryOperatorExpression operatorExpression = expression as BinaryOperatorExpression;
Assert.IsNotNull(operatorExpression, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Or, operatorExpression.Operator, "Unexpected operator.");
//
// Or left
//
BinaryOperatorExpression andExpression = operatorExpression.Left as BinaryOperatorExpression;
Assert.IsNotNull(andExpression, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.And, andExpression.Operator, "Unexpected operator.");
//
// And Left
//
BinaryOperatorExpression testExpression1 = andExpression.Left as BinaryOperatorExpression;
Assert.IsNotNull(testExpression1, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Equal, testExpression1.Operator, "Unexpected operator.");
ElementAttributeExpression test1AttributeExpression = testExpression1.Left as ElementAttributeExpression;
Assert.IsNotNull(test1AttributeExpression, "Unexpected left node type.");
Assert.AreEqual(ElementAttributeType.Name, test1AttributeExpression.ElementAttribute, "Attribute expression was not parsed correctly.");
StringExpression test1StringExpression = testExpression1.Right as StringExpression;
Assert.IsNotNull(test1StringExpression, "Unexpected right node type.");
Assert.AreEqual("Test 1", test1StringExpression.Text, "String expression was not parsed correctly.");
//
// And Right
//
BinaryOperatorExpression testExpression2 = andExpression.Right as BinaryOperatorExpression;
Assert.IsNotNull(testExpression2, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Equal, testExpression2.Operator, "Unexpected operator.");
ElementAttributeExpression test2AttributeExpression = testExpression2.Left as ElementAttributeExpression;
Assert.IsNotNull(test2AttributeExpression, "Unexpected left node type.");
Assert.AreEqual(ElementAttributeType.Name, test2AttributeExpression.ElementAttribute, "Attribute expression was not parsed correctly.");
StringExpression test2StringExpression = testExpression2.Right as StringExpression;
Assert.IsNotNull(test2StringExpression, "Unexpected right node type.");
Assert.AreEqual("Test 2", test2StringExpression.Text, "String expression was not parsed correctly.");
//
// Or right
//
BinaryOperatorExpression testExpression3 = operatorExpression.Right as BinaryOperatorExpression;
Assert.IsNotNull(testExpression3, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Equal, testExpression3.Operator, "Unexpected operator.");
ElementAttributeExpression test3AttributeExpression = testExpression3.Left as ElementAttributeExpression;
Assert.IsNotNull(test3AttributeExpression, "Unexpected left node type.");
Assert.AreEqual(ElementAttributeType.Name, test3AttributeExpression.ElementAttribute, "Attribute expression was not parsed correctly.");
StringExpression test3StringExpression = testExpression3.Right as StringExpression;
Assert.IsNotNull(test3StringExpression, "Unexpected right node type.");
Assert.AreEqual("Test 3", test3StringExpression.Text, "String expression was not parsed correctly.");
};
string expressionText;
expressionText = "(($(Name) == 'Test 1') And ($(Name) == 'Test 2')) Or ($(Name) == 'Test 3')";
testExpression(expressionText);
expressionText = "$(Name) == 'Test 1' And $(Name) == 'Test 2' Or $(Name) == 'Test 3'";
testExpression(expressionText);
}
/// <summary>
/// Tests parsing an expression.
/// </summary>
[Test]
public void ParseOrAndExpressionTest2()
{
Action<string> testExpression = delegate(string condition)
{
IConditionExpression expression = ConditionExpressionParser.Instance.Parse(
condition);
Assert.IsNotNull(expression, "Expected an expression instance.");
BinaryOperatorExpression operatorExpression = expression as BinaryOperatorExpression;
Assert.IsNotNull(operatorExpression, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Or, operatorExpression.Operator, "Unexpected operator.");
//
// Or left
//
BinaryOperatorExpression testExpression1 = operatorExpression.Left as BinaryOperatorExpression;
Assert.IsNotNull(testExpression1, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Equal, testExpression1.Operator, "Unexpected operator.");
ElementAttributeExpression test1AttributeExpression = testExpression1.Left as ElementAttributeExpression;
Assert.IsNotNull(test1AttributeExpression, "Unexpected left node type.");
Assert.AreEqual(ElementAttributeType.Name, test1AttributeExpression.ElementAttribute, "Attribute expression was not parsed correctly.");
StringExpression test1StringExpression = testExpression1.Right as StringExpression;
Assert.IsNotNull(test1StringExpression, "Unexpected right node type.");
Assert.AreEqual("Test 1", test1StringExpression.Text, "String expression was not parsed correctly.");
//
// Or right
//
BinaryOperatorExpression andExpression = operatorExpression.Right as BinaryOperatorExpression;
Assert.IsNotNull(andExpression, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.And, andExpression.Operator, "Unexpected operator.");
//
// And Left
//
BinaryOperatorExpression testExpression2 = andExpression.Left as BinaryOperatorExpression;
Assert.IsNotNull(testExpression2, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Equal, testExpression2.Operator, "Unexpected operator.");
ElementAttributeExpression test2AttributeExpression = testExpression2.Left as ElementAttributeExpression;
Assert.IsNotNull(test2AttributeExpression, "Unexpected left node type.");
Assert.AreEqual(ElementAttributeType.Name, test2AttributeExpression.ElementAttribute, "Attribute expression was not parsed correctly.");
StringExpression test2StringExpression = testExpression2.Right as StringExpression;
Assert.IsNotNull(test2StringExpression, "Unexpected right node type.");
Assert.AreEqual("Test 2", test2StringExpression.Text, "String expression was not parsed correctly.");
//
// And Right
//
BinaryOperatorExpression testExpression3 = andExpression.Right as BinaryOperatorExpression;
Assert.IsNotNull(testExpression3, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Equal, testExpression3.Operator, "Unexpected operator.");
ElementAttributeExpression test3AttributeExpression = testExpression3.Left as ElementAttributeExpression;
Assert.IsNotNull(test3AttributeExpression, "Unexpected left node type.");
Assert.AreEqual(ElementAttributeType.Name, test3AttributeExpression.ElementAttribute, "Attribute expression was not parsed correctly.");
StringExpression test3StringExpression = testExpression3.Right as StringExpression;
Assert.IsNotNull(test3StringExpression, "Unexpected right node type.");
Assert.AreEqual("Test 3", test3StringExpression.Text, "String expression was not parsed correctly.");
};
string expressionText;
expressionText = "(($(Name) == 'Test 1') Or (($(Name) == 'Test 2') And ($(Name) == 'Test 3')))";
testExpression(expressionText);
expressionText = "$(Name) == 'Test 1' Or $(Name) == 'Test 2' And $(Name) == 'Test 3'";
testExpression(expressionText);
}
/// <summary>
/// Tests parsing an OR expression.
/// </summary>
[Test]
public void ParseOrExpressionTest()
{
Action<string> testExpression = delegate(string condition)
{
IConditionExpression expression = ConditionExpressionParser.Instance.Parse(
condition);
Assert.IsNotNull(expression, "Expected an expression instance.");
BinaryOperatorExpression operatorExpression = expression as BinaryOperatorExpression;
Assert.IsNotNull(operatorExpression, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Or, operatorExpression.Operator, "Unexpected operator.");
//
// Left
//
BinaryOperatorExpression leftExpression = expression.Left as BinaryOperatorExpression;
Assert.IsNotNull(leftExpression, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Equal, leftExpression.Operator, "Unexpected operator.");
ElementAttributeExpression leftAttributeExpression = leftExpression.Left as ElementAttributeExpression;
Assert.IsNotNull(leftAttributeExpression, "Unexpected left node type.");
Assert.AreEqual(ElementAttributeType.Name, leftAttributeExpression.ElementAttribute, "Attribute expression was not parsed correctly.");
StringExpression leftStringExpression = leftExpression.Right as StringExpression;
Assert.IsNotNull(leftStringExpression, "Unexpected right node type.");
Assert.AreEqual("Test 1", leftStringExpression.Text, "String expression was not parsed correctly.");
//
// Right
//
BinaryOperatorExpression rightExpression = expression.Right as BinaryOperatorExpression;
Assert.IsNotNull(rightExpression, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Equal, rightExpression.Operator, "Unexpected operator.");
ElementAttributeExpression rightAttributeExpression = rightExpression.Left as ElementAttributeExpression;
Assert.IsNotNull(rightAttributeExpression, "Unexpected left node type.");
Assert.AreEqual(ElementAttributeType.Name, rightAttributeExpression.ElementAttribute, "Attribute expression was not parsed correctly.");
StringExpression rightStringExpression = rightExpression.Right as StringExpression;
Assert.IsNotNull(rightStringExpression, "Unexpected right node type.");
Assert.AreEqual("Test 2", rightStringExpression.Text, "String expression was not parsed correctly.");
};
string expressionText;
expressionText = "($(Name) == 'Test 1') Or ($(Name) == 'Test 2')";
testExpression(expressionText);
expressionText = "$(Name) == 'Test 1' Or $(Name) == 'Test 2'";
testExpression(expressionText);
}
/// <summary>
/// Tests parsing a parent name contains expression.
/// </summary>
[Test]
public void ParseParentNameContainsExpressionTest()
{
string expressionText = "$(Parent.Name) : 'Converter'";
IConditionExpression expression = ConditionExpressionParser.Instance.Parse(
expressionText);
Assert.IsNotNull(expression, "Expected an expression instance.");
BinaryOperatorExpression operatorExpression = expression as BinaryOperatorExpression;
Assert.IsNotNull(operatorExpression, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Contains, operatorExpression.Operator, "Unexpected operator.");
ElementAttributeExpression attributeExpression = operatorExpression.Left as ElementAttributeExpression;
Assert.IsNotNull(attributeExpression, "Unexpected left node type.");
Assert.AreEqual(ElementAttributeType.Name, attributeExpression.ElementAttribute, "Attribute expression was not parsed correctly.");
Assert.AreEqual(ElementAttributeScope.Parent, attributeExpression.Scope, "Attribute scope was not parsed correctly.");
StringExpression stringExpression = operatorExpression.Right as StringExpression;
Assert.IsNotNull(stringExpression, "Unexpected right node type.");
Assert.AreEqual("Converter", stringExpression.Text, "String expression was not parsed correctly.");
}
/// <summary>
/// Tests parsing a string expression with an escaped apostrophe.
/// </summary>
[Test]
public void ParseStringExpressionEscapedApostropheEndTest()
{
string expressionText = "$(Name) == 'Test it'''";
IConditionExpression expression = ConditionExpressionParser.Instance.Parse(
expressionText);
Assert.IsNotNull(expression, "Expected an expression instance.");
BinaryOperatorExpression operatorExpression = expression as BinaryOperatorExpression;
Assert.IsNotNull(operatorExpression, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Equal, operatorExpression.Operator, "Unexpected operator.");
ElementAttributeExpression attributeExpression = operatorExpression.Left as ElementAttributeExpression;
Assert.IsNotNull(attributeExpression, "Unexpected left node type.");
Assert.AreEqual(ElementAttributeType.Name, attributeExpression.ElementAttribute, "Attribute expression was not parsed correctly.");
Assert.AreEqual(ElementAttributeScope.Element, attributeExpression.Scope, "Attribute scope was not parsed correctly.");
StringExpression stringExpression = operatorExpression.Right as StringExpression;
Assert.IsNotNull(stringExpression, "Expected a string expression.");
Assert.AreEqual("Test it'", stringExpression.Text, "Unexpected expression text.");
}
/// <summary>
/// Tests parsing a string expression with an escaped apostrophe.
/// </summary>
[Test]
public void ParseStringExpressionEscapedApostropheTest()
{
string expressionText = "$(Name) == 'Test '' it'";
IConditionExpression expression = ConditionExpressionParser.Instance.Parse(
expressionText);
Assert.IsNotNull(expression, "Expected an expression instance.");
BinaryOperatorExpression operatorExpression = expression as BinaryOperatorExpression;
Assert.IsNotNull(operatorExpression, "Expected an operator expression.");
Assert.AreEqual(BinaryExpressionOperator.Equal, operatorExpression.Operator, "Unexpected operator.");
ElementAttributeExpression attributeExpression = operatorExpression.Left as ElementAttributeExpression;
Assert.IsNotNull(attributeExpression, "Unexpected left node type.");
Assert.AreEqual(ElementAttributeType.Name, attributeExpression.ElementAttribute, "Attribute expression was not parsed correctly.");
Assert.AreEqual(ElementAttributeScope.Element, attributeExpression.Scope, "Attribute scope was not parsed correctly.");
StringExpression stringExpression = operatorExpression.Right as StringExpression;
Assert.IsNotNull(stringExpression, "Expected a string expression.");
Assert.AreEqual("Test ' it", stringExpression.Text, "Unexpected expression text.");
}
#endregion Methods
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace WebProxy.Swagger
{
public class SwaggerParser
{
public ProxyDefinition ParseSwaggerDocument(string swaggerDocument)
{
var jObject = JObject.Parse(swaggerDocument);
var proxyDefinition = new ProxyDefinition();
var infoToken = jObject["info"];
proxyDefinition.Title = infoToken["title"].ToString();
var descriptionToken = infoToken["description"];
proxyDefinition.Description = descriptionToken != null ? descriptionToken.ToString() : null;
this.ParsePaths(jObject, proxyDefinition);
this.ParseDefinitions(jObject, proxyDefinition);
return proxyDefinition;
}
private void ParsePaths(JObject jObject, ProxyDefinition proxyDefinition)
{
foreach (var pathToken in jObject["paths"].Cast<JProperty>())
{
var path = pathToken.Name;
foreach (var operationToken in pathToken.First.Cast<JProperty>())
{
var proxyName = string.Empty;
var method = operationToken.Name;
var operationId = operationToken.First["operationId"].ToString();
if (operationId.Contains("_"))
{
var underscoreLocation = operationId.IndexOf("_", StringComparison.OrdinalIgnoreCase);
proxyName = operationId.Substring(0, underscoreLocation);
operationId = operationId.Substring(underscoreLocation + 1);
}
if (string.IsNullOrWhiteSpace(proxyName))
{
// didn't get the proxy name from the operation id, let's try the tags
var tagToken = operationToken.First["tags"];
if (tagToken != null)
{
var tags = tagToken.ToObject<List<string>>();
proxyName = tags.First();
}
}
var descriptionToken = operationToken.First["description"];
string description = null;
if (descriptionToken != null)
{
description = descriptionToken.ToString();
}
string returnType;
var schema = operationToken.First["responses"]["200"];
if (schema != null)
{
bool dummyNullable;
returnType = this.GetTypeName(schema, out dummyNullable);
if (returnType != null && returnType.Equals("Void"))
returnType = null;
}
else
{
returnType = null;
}
var parameters = new List<Parameter>();
var paramTokens = operationToken.First["parameters"];
if (paramTokens != null)
{
foreach (var prop in paramTokens)
{
var type = ParseType(prop);
var isRequired = prop["required"].ToObject<bool>();
ParameterIn parameterIn;
if (prop["in"].ToString().Equals("path"))
{
parameterIn = ParameterIn.Path;
}
else if (prop["in"].ToString().Equals("query"))
{
parameterIn = ParameterIn.Query;
}
else if (prop["in"].ToString().Equals("formData"))
{
parameterIn = ParameterIn.FormData;
}
else
{
parameterIn = ParameterIn.Body;
}
var propDescriptionToken = prop["description"];
string propDescription = string.Empty;
if (propDescriptionToken != null)
{
propDescription = propDescriptionToken.ToString();
}
string collectionFormat = string.Empty;
var collectionFormatToken = prop["collectionFormat"];
if (collectionFormatToken != null)
{
collectionFormat = collectionFormatToken.ToString();
}
parameters.Add(new Parameter(type, parameterIn, isRequired, propDescription, collectionFormat));
}
}
proxyDefinition.Operations.Add(new Operation(returnType, method, path, parameters, operationId, description, proxyName));
}
}
}
private void ParseDefinitions(JObject jObject, ProxyDefinition proxyDefinition)
{
foreach (var definitionToken in jObject["definitions"].Where(i => i.Type == JTokenType.Property).Cast<JProperty>())
{
bool addIt = true;
var classDefinition = new ClassDefinition(definitionToken.Name);
var allOf = definitionToken.First["allOf"];
if (allOf != null)
{
foreach (var itemToken in allOf)
{
var refType = itemToken["$ref"] as JValue;
if (refType != null)
{
classDefinition.Inherits = refType.Value.ToString();
}
var properties = itemToken["properties"];
if (properties != null)
{
foreach (var prop in properties)
{
var type = ParseType(prop);
classDefinition.Properties.Add(type);
}
}
}
}
else
{
var properties = definitionToken.Value["properties"];
if (properties != null)
{
foreach (var prop in properties)
{
var type = ParseType(prop);
classDefinition.Properties.Add(type);
}
}
else
{
addIt = false;
}
}
classDefinition.Name = FixGenericName(classDefinition.Name);
if (classDefinition.Name.Equals("Void", StringComparison.InvariantCulture))
{
addIt = false;
}
if (addIt)
{
proxyDefinition.ClassDefinitions.Add(classDefinition);
}
}
}
private TypeDefinition ParseType(JToken token)
{
bool isNullable;
JToken workingToken;
string name;
if (token.First is JProperty)
{
workingToken = token;
name = workingToken["name"].ToString();
}
else
{
workingToken = token.First;
name = ((JProperty)token).Name;
}
var typeName = GetTypeName(workingToken, out isNullable);
var enumToken = workingToken["enum"];
string[] enumValues = null;
if (enumToken != null)
{
List<string> enumList = new List<string>();
bool anyRawNumbers = false;
foreach (var enumValueToken in enumToken)
{
var enumValue = enumValueToken.ToString();
decimal value;
if (Decimal.TryParse(enumValue, out value))
{
anyRawNumbers = true;
}
enumList.Add(enumValue);
}
if (anyRawNumbers == false)
{
enumValues = enumList.ToArray();
typeName = FixTypeName(name + "Values");
}
}
typeName = FixGenericName(typeName);
TypeDefinition type = new TypeDefinition(typeName, name, enumValues, isNullable);
return type;
}
private string ParseRef(string input)
{
return input.StartsWith("#/definitions/") ? input.Substring("#/definitions/".Length) : input;
}
private static string FixGenericName(string input)
{
if (input.Contains("[") == false || input.Contains("]") == false)
{
return input;
}
if (input.StartsWith("Dictionary[") || input.StartsWith("IDictionary["))
{
return input.Replace("[", "<").Replace("]", ">");
}
var firstBracket = input.IndexOf("[", StringComparison.InvariantCulture) + 1;
var secondBracket = input.IndexOf("]", StringComparison.InvariantCulture);
string typeName = input.Substring(firstBracket, secondBracket - firstBracket);
string genericName = input.Substring(0, firstBracket - 1);
return typeName + genericName;
}
private string GetTypeName(JToken token, out bool isNullable)
{
var refType = token["$ref"] as JValue;
bool hasNullFlag = false;
if (refType != null)
{
isNullable = false;
return FixTypeName(this.ParseRef(refType.Value.ToString()));
}
var schema = token["schema"];
if (schema != null)
{
return FixTypeName(this.GetTypeName(schema, out isNullable));
}
var type = token["type"] as JValue;
if (type == null)
{
isNullable = false;
return null;
}
var nullableToken = token["x-nullable"] as JValue;
if (nullableToken != null)
{
hasNullFlag = true;
}
if (type.Value.Equals("array"))
{
isNullable = false;
var jToken = token["items"];
bool throwawayNullable; // we don't care what the underlying
return string.Format("List<{0}>", this.GetTypeName(jToken, out throwawayNullable));
}
if (type.Value.Equals("boolean"))
{
isNullable = true;
return (hasNullFlag) ? "bool?" : "bool";
}
if (type.Value.Equals("file"))
{
isNullable = true;
return "file";
}
if (type.Value.Equals("string"))
{
var format = token["format"] as JValue;
if (format == null)
{
isNullable = false;
return "string";
}
if (format.Value.Equals("date") || format.Value.Equals("date-time"))
{
isNullable = true;
return (hasNullFlag) ? "DateTime?" : "DateTime";
}
if (format.Value.Equals("byte"))
{
isNullable = true;
return (hasNullFlag) ? "byte?" : "byte";
}
isNullable = false;
return "string";
}
if (type.Value.Equals("integer"))
{
isNullable = true;
var format = token["format"] as JValue;
if (format != null)
{
if (format.Value.Equals("int32"))
return (hasNullFlag) ? "int?" : "int";
if (format.Value.Equals("int64"))
return (hasNullFlag) ? "long?" : "long";
}
return "int";
}
if (type.Value.Equals("number"))
{
isNullable = true;
var format = token["format"] as JValue;
if (format != null)
{
if (format.Value.Equals("float"))
return (hasNullFlag) ? "float?" : "float";
if (format.Value.Equals("double"))
return (hasNullFlag) ? "double?" : "double";
if (format.Value.Equals("decimal"))
return (hasNullFlag) ? "decimal?" : "decimal";
}
}
if (type.Value.Equals("object"))
{
isNullable = false;
return "object";
}
isNullable = false;
return "";
}
public static string FixTypeName(string input)
{
if (string.IsNullOrWhiteSpace(input))
return input;
var output = input.Replace(" ", "");
output = SwaggerParser.FixGenericName(output);
if (char.IsLetter(output[0]) == false)
output = "_" + output;
return output;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace SecurityUsingOAuth.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Data;
using System.Data.Odbc;
using System.Text;
/* Created By: Brahim Al-Hawwas
* Last Modified: 7:35 13/12/2007
* Notices: Tested with telnet, but file reading does not work
*
*/
namespace RemedyServer
{
class HandleLeader
{
private NetworkStream ns;
private StreamReader reader;
private StreamWriter writer;
private OdbcConnection dbConn;
private OdbcCommand sqlCommand;
private OdbcDataReader dbReader;
private Handle_File fileHandler;
private string line, command, userName, assigned, memEmail,fileName, requirenments;
private string due_Date, memName, email, password, body, subject;
private string[] fileNames;
private int fileNumber,fileLength, seq, ticketNum;
public HandleLeader(OdbcConnection dbConn,NetworkStream ns, StreamReader reader, StreamWriter writer, string userName)
{
this.dbConn = dbConn;
this.reader = reader;
this.writer = writer;
this.ns = ns;
this.userName = userName;
fileHandler = new Handle_File(ns, reader, writer);
BeginHandling();
}
public void BeginHandling()//initializing the leader handler
{
try
{
email = DB_Handler.GetEmail(userName, dbConn);
// command = " SELECT T.Number, T.Issue_Date, I.Assigned, I.Attachment, I.JobDone, I.Status, I.Sequence, I.Due_Date, I.Requirements" +
// " FROM Ticket AS T, Ticket_Information AS I WHERE T.Number=I.Number";
command = " SELECT T.Number, T.Issue_Date, I.Assigned,I.Status, I.Due_Date" +
" FROM Ticket AS T, Ticket_Information AS I WHERE T.Number=I.Number AND T.Assigner ='" + userName + "'";
sqlCommand = new OdbcCommand(command, dbConn);
dbReader = sqlCommand.ExecuteReader();
while (dbReader.Read())
{
line = "";//empty the line so you can read the next row
for (int i = 0; i < dbReader.FieldCount-1; i++)
{
line += dbReader.GetString(i) + "##";// but the whole row in one column and send it, seperated by commas
}
writer.WriteLine(line);
writer.Flush();
}
writer.WriteLine(".");// end of reading from the database
writer.Flush();
DB_Handler.DisposeAll(sqlCommand, dbReader);
WaitForQueries();
}
catch
{
Console.WriteLine(" The Database is down please try again later");//for debugging server
DB_Handler.DisposeAll(sqlCommand, dbReader);
}
}
public void WaitForQueries()
{
do
{
try
{
line = reader.ReadLine();//reader the command the user wants to issue
switch (line)
{
case "Create Ticket":
SendMemNum();
SendMembers();
seq = int.Parse(reader.ReadLine());
Console.WriteLine("the sequence is " + seq);
CreateTicket();//Create an initial ticket that is mapped to Ticket Table
for (int i = 1; i <= seq; i++)
ReadTicket(i);
//end of reading the number of members and sending it to client
writer.WriteLine("OK");
writer.Flush();
break;
case "Create Member":
memName = reader.ReadLine();
memEmail = reader.ReadLine();
password = reader.ReadLine();
body = "Dear " + memName + " :\n Welcome to our Group that is lead by " +
userName + "\n name: " + memName + "\n password: " + password;
Mail_Sender.SendMail(email, memEmail, "You are joining a new group", body);
command = "INSERT INTO User_Information Values('" + memName + "','" + memEmail + "','" + password +"','Member')";//name,email,pass
sqlCommand = new OdbcCommand(command, dbConn);
sqlCommand.ExecuteNonQuery();
AcceptedCommand();
break;
case "Ticket Info":
GetTicketInfo();
AcceptedCommand();
break;
case "Get Attachment":
GetAttachment();
AcceptedCommand();
break;
case "Delete Member":
try
{
memName = reader.ReadLine();
command = "DELETE FROM User_Information WHERE Name ='" + memName + "' AND Role = 'Member'";
sqlCommand = new OdbcCommand(command, dbConn);
sqlCommand.ExecuteNonQuery();
AcceptedCommand();
}
catch
{
writer.WriteLine("Not OK");
writer.Flush();
}
break;
case "Referesh":
BeginHandling();
break;
case "Quit":
line = "break";
break;
default:
writer.WriteLine("not known Command");
writer.Flush();
break;
}
}
catch
{
Console.WriteLine(" The Database is down please try again later");//for debugging server only
}
} while (line!="break");
}
public void SendMemNum()
{
command = "SELECT COUNT(*) FROM User_Information WHERE ROLE='Member'";
sqlCommand = new OdbcCommand(command, dbConn);
dbReader = sqlCommand.ExecuteReader();
dbReader.Read();
Console.WriteLine(" I have got the count" + dbReader.GetString(0));
writer.WriteLine(dbReader.GetString(0));
writer.Flush();
}
public void SendMembers()
{
command = "SELECT Name FROM User_Information WHERE Role='Member'";
sqlCommand = new OdbcCommand(command, dbConn);
dbReader = sqlCommand.ExecuteReader();
while (dbReader.Read())
{
writer.WriteLine(dbReader.GetString(0));
writer.Flush();
}
}
public void ReadTicket(int sequence)
{
assigned = reader.ReadLine();
Console.WriteLine("The assigned is: "+assigned);
fileNumber = int.Parse(reader.ReadLine());
Console.WriteLine("The number of files are: "+fileNumber);
fileNames = new string[fileNumber];
for (int i = fileNumber; i > 0; i--)
{
Console.WriteLine("Reading the file #: " + i);
fileName = reader.ReadLine();
Console.WriteLine("The file Name is: "+fileName);
fileNames[i - 1] = fileName;
fileLength = int.Parse(reader.ReadLine());
Console.WriteLine("The File Length is: " + fileLength);
fileHandler.ReadAttachments(ticketNum, assigned, fileName, fileLength);//uploading attachment to the server
Console.WriteLine("I have read the attachments");
}
requirenments = reader.ReadLine();// reading the requirements
Console.WriteLine("The req are " + requirenments);
due_Date = reader.ReadLine();//reading the due-date
Console.WriteLine("the Due_date is: " + due_Date);
string allFiles="##";
for (int i = 0; i < fileNumber; i++)
{
allFiles += fileNames[i]+"##"; //seperate files by ## and insert their names to the database
}
if (sequence == 1)
{
command = "INSERT INTO Ticket_Information " +
"Values('" + ticketNum + "','" + assigned + "','" + allFiles + "','None','Assigned','" + sequence + "',#" + due_Date + "#,'" + requirenments + "')";
subject = "You have been Assigned a ticket";
body = "Dear " + assigned + ":\n You have been assigned a Ticket having a number: " +
ticketNum + ", The Due Date is: " + due_Date + "\n\n Open Your Remedy Client for more info";
}
else
{
command = "INSERT INTO Ticket_Information " +
"Values('" + ticketNum + "','" + assigned + "','" + allFiles + "','None','Waiting','" + sequence + "',#" + due_Date + "#,'" + requirenments + "')";
subject = "You have been Assigned a ticket but waiting in Sequence";
body = "Dear " + assigned + ":\n You have been assigned a Ticket having a number: " +
ticketNum + ", The Due Date is: " + due_Date + "\n\n Open Your Remedy Client for more info";
}
memEmail = DB_Handler.GetEmail(assigned,dbConn);
Mail_Sender.SendMail(email, memEmail, subject, body);
sqlCommand = new OdbcCommand(command, dbConn);
sqlCommand.ExecuteNonQuery();
}
public void CreateTicket()//No reading/writing from/to the user, Just setting the ticketNum
{
DateTime date = System.DateTime.Now;
command = "INSERT INTO Ticket (Assigner, Issue_Date) Values('" + userName + "','" + date + "')";
sqlCommand = new OdbcCommand(command, dbConn);
sqlCommand.ExecuteNonQuery();
command = " SELECT Number" +
" FROM Ticket WHERE Issue_Date=#" + date + "#";
sqlCommand = new OdbcCommand(command, dbConn);
dbReader = sqlCommand.ExecuteReader();
dbReader.Read();
ticketNum = int.Parse(dbReader.GetString(0));
}
public void GetTicketInfo()
{
ticketNum = int.Parse(reader.ReadLine());//get the ticket number you want to handle
assigned = reader.ReadLine();
command = "SELECT T.Number, T.Issue_Date,I.Assigned, I.JobDone, I.Status, I.Sequence, I.Due_Date, I.Requirements, I.Attachment " +
"FROM Ticket_Information AS I, Ticket AS T WHERE I.Assigned = '"+assigned+"'AND T.Number=" + ticketNum + " AND T.Number=I.Number";//name,email,pass
sqlCommand = new OdbcCommand(command, dbConn);
dbReader = sqlCommand.ExecuteReader();
while (dbReader.Read())
{
line = "";//empty the line so you can read the next row
for (int i = 0; i < dbReader.FieldCount ; i++)
{
line += dbReader.GetString(i) + "##";// but the whole row in one column and send it, seperated by ##
}
writer.WriteLine(line);
writer.Flush();
}
writer.WriteLine(".");//sending the end of tickets info
writer.Flush();
}
public void GetAttachment()
{
ticketNum = int.Parse(reader.ReadLine());
assigned = reader.ReadLine().Trim();
fileName = reader.ReadLine().Trim();
fileHandler.GetAttachment(ticketNum, assigned, fileName);
}
public void AcceptedCommand()
{
writer.WriteLine("OK");//I am accepting the command and I have executed it
writer.Flush();
DB_Handler.DisposeAll(sqlCommand, dbReader);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.Diagnostics;
using Internal.Runtime.CompilerServices;
namespace System.Runtime.InteropServices
{
/// <summary>
/// Provides a collection of methods for interoperating with <see cref="Memory{T}"/>, <see cref="ReadOnlyMemory{T}"/>,
/// <see cref="Span{T}"/>, and <see cref="ReadOnlySpan{T}"/>.
/// </summary>
public static partial class MemoryMarshal
{
/// <summary>
/// Get an array segment from the underlying memory.
/// If unable to get the array segment, return false with a default array segment.
/// </summary>
public static bool TryGetArray<T>(ReadOnlyMemory<T> memory, out ArraySegment<T> segment)
{
object obj = memory.GetObjectStartLength(out int index, out int length);
if (index < 0)
{
Debug.Assert(length >= 0);
if (((MemoryManager<T>)obj).TryGetArray(out ArraySegment<T> arraySegment))
{
segment = new ArraySegment<T>(arraySegment.Array, arraySegment.Offset + (index & ReadOnlyMemory<T>.RemoveFlagsBitMask), length);
return true;
}
}
else if (obj is T[] arr)
{
segment = new ArraySegment<T>(arr, index, length & ReadOnlyMemory<T>.RemoveFlagsBitMask);
return true;
}
if ((length & ReadOnlyMemory<T>.RemoveFlagsBitMask) == 0)
{
segment = ArraySegment<T>.Empty;
return true;
}
segment = default;
return false;
}
/// <summary>
/// Gets an <see cref="MemoryManager{T}"/> from the underlying read-only memory.
/// If unable to get the <typeparamref name="TManager"/> type, returns false.
/// </summary>
/// <typeparam name="T">The element type of the <paramref name="memory" />.</typeparam>
/// <typeparam name="TManager">The type of <see cref="MemoryManager{T}"/> to try and retrive.</typeparam>
/// <param name="memory">The memory to get the manager for.</param>
/// <param name="manager">The returned manager of the <see cref="ReadOnlyMemory{T}"/>.</param>
/// <returns>A <see cref="bool"/> indicating if it was successful.</returns>
public static bool TryGetMemoryManager<T, TManager>(ReadOnlyMemory<T> memory, out TManager manager)
where TManager : MemoryManager<T>
{
TManager localManager; // Use register for null comparison rather than byref
manager = localManager = memory.GetObjectStartLength(out _, out _) as TManager;
return manager != null;
}
/// <summary>
/// Gets an <see cref="MemoryManager{T}"/> and <paramref name="start" />, <paramref name="length" /> from the underlying read-only memory.
/// If unable to get the <typeparamref name="TManager"/> type, returns false.
/// </summary>
/// <typeparam name="T">The element type of the <paramref name="memory" />.</typeparam>
/// <typeparam name="TManager">The type of <see cref="MemoryManager{T}"/> to try and retrive.</typeparam>
/// <param name="memory">The memory to get the manager for.</param>
/// <param name="manager">The returned manager of the <see cref="ReadOnlyMemory{T}"/>.</param>
/// <param name="start">The offset from the start of the <paramref name="manager" /> that the <paramref name="memory" /> represents.</param>
/// <param name="length">The length of the <paramref name="manager" /> that the <paramref name="memory" /> represents.</param>
/// <returns>A <see cref="bool"/> indicating if it was successful.</returns>
public static bool TryGetMemoryManager<T, TManager>(ReadOnlyMemory<T> memory, out TManager manager, out int start, out int length)
where TManager : MemoryManager<T>
{
TManager localManager; // Use register for null comparison rather than byref
manager = localManager = memory.GetObjectStartLength(out start, out length) as TManager;
start &= ReadOnlyMemory<T>.RemoveFlagsBitMask;
Debug.Assert(length >= 0);
if (manager == null)
{
start = default;
length = default;
return false;
}
return true;
}
/// <summary>
/// Creates an <see cref="IEnumerable{T}"/> view of the given <paramref name="memory" /> to allow
/// the <paramref name="memory" /> to be used in existing APIs that take an <see cref="IEnumerable{T}"/>.
/// </summary>
/// <typeparam name="T">The element type of the <paramref name="memory" />.</typeparam>
/// <param name="memory">The ReadOnlyMemory to view as an <see cref="IEnumerable{T}"/></param>
/// <returns>An <see cref="IEnumerable{T}"/> view of the given <paramref name="memory" /></returns>
public static IEnumerable<T> ToEnumerable<T>(ReadOnlyMemory<T> memory)
{
for (int i = 0; i < memory.Length; i++)
yield return memory.Span[i];
}
/// <summary>Attempts to get the underlying <see cref="string"/> from a <see cref="ReadOnlyMemory{T}"/>.</summary>
/// <param name="memory">The memory that may be wrapping a <see cref="string"/> object.</param>
/// <param name="text">The string.</param>
/// <param name="start">The starting location in <paramref name="text"/>.</param>
/// <param name="length">The number of items in <paramref name="text"/>.</param>
/// <returns></returns>
public static bool TryGetString(ReadOnlyMemory<char> memory, out string text, out int start, out int length)
{
if (memory.GetObjectStartLength(out int offset, out int count) is string s)
{
Debug.Assert(offset >= 0);
Debug.Assert(count >= 0);
text = s;
start = offset;
length = count;
return true;
}
else
{
text = null;
start = 0;
length = 0;
return false;
}
}
/// <summary>
/// Reads a structure of type T out of a read-only span of bytes.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T Read<T>(ReadOnlySpan<byte> source)
where T : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
}
if (Unsafe.SizeOf<T>() > source.Length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length);
}
return Unsafe.ReadUnaligned<T>(ref GetReference(source));
}
/// <summary>
/// Reads a structure of type T out of a span of bytes.
/// <returns>If the span is too small to contain the type T, return false.</returns>
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryRead<T>(ReadOnlySpan<byte> source, out T value)
where T : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
}
if (Unsafe.SizeOf<T>() > (uint)source.Length)
{
value = default;
return false;
}
value = Unsafe.ReadUnaligned<T>(ref GetReference(source));
return true;
}
/// <summary>
/// Writes a structure of type T into a span of bytes.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write<T>(Span<byte> destination, ref T value)
where T : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
}
if ((uint)Unsafe.SizeOf<T>() > (uint)destination.Length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length);
}
Unsafe.WriteUnaligned<T>(ref GetReference(destination), value);
}
/// <summary>
/// Writes a structure of type T into a span of bytes.
/// <returns>If the span is too small to contain the type T, return false.</returns>
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryWrite<T>(Span<byte> destination, ref T value)
where T : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
}
if (Unsafe.SizeOf<T>() > (uint)destination.Length)
{
return false;
}
Unsafe.WriteUnaligned<T>(ref GetReference(destination), value);
return true;
}
/// <summary>
/// Re-interprets a span of bytes as a reference to structure of type T.
/// The type may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <remarks>
/// Supported only for platforms that support misaligned memory access or when the memory block is aligned by other means.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T AsRef<T>(Span<byte> span)
where T : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
}
if (Unsafe.SizeOf<T>() > (uint)span.Length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length);
}
return ref Unsafe.As<byte, T>(ref GetReference(span));
}
/// <summary>
/// Re-interprets a span of bytes as a reference to structure of type T.
/// The type may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <remarks>
/// Supported only for platforms that support misaligned memory access or when the memory block is aligned by other means.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref readonly T AsRef<T>(ReadOnlySpan<byte> span)
where T : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
}
if (Unsafe.SizeOf<T>() > (uint)span.Length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length);
}
return ref Unsafe.As<byte, T>(ref GetReference(span));
}
/// <summary>
/// Creates a new memory over the portion of the pre-pinned target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The pre-pinned target array.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
/// <remarks>This method should only be called on an array that is already pinned and
/// that array should not be unpinned while the returned Memory<typeparamref name="T"/> is still in use.
/// Calling this method on an unpinned array could result in memory corruption.</remarks>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Memory<T> CreateFromPinnedArray<T>(T[] array, int start, int length)
{
if (array == null)
{
if (start != 0 || length != 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
return default;
}
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException();
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
// Before using _length, check if _length < 0, then 'and' it with RemoveFlagsBitMask
return new Memory<T>((object)array, start, length | (1 << 31));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Versioning;
using Xunit;
using Xunit.Extensions;
namespace NuGet.Test
{
public class VersionUtilityTest
{
[Theory]
[InlineData("boo\\foo.dll", "foo.dll")]
[InlineData("far\\sub\\sub2\\foo.dll", "sub\\sub2\\foo.dll")]
[InlineData("netum\\who\\bar.dll", "who\\bar.dll")]
public void ParseFrameworkFolderNameStrictReturnsUnsupportedFxIfParsingFails(string path, string expectedEffectivePath)
{
// Act
string effectivePath;
var frameworkName = VersionUtility.ParseFrameworkFolderName(
path, strictParsing: true, effectivePath: out effectivePath);
// Assert
Assert.Equal(VersionUtility.UnsupportedFrameworkName, frameworkName);
Assert.Equal(expectedEffectivePath, effectivePath);
}
[Theory]
[InlineData("lib\\net40\\foo.dll", "4.0", ".NETFramework", "foo.dll")]
[InlineData("lib\\net40\\sub\\foo.dll", "4.0", ".NETFramework", "sub\\foo.dll")]
[InlineData("lib\\foo.dll", null, null, "foo.dll")]
[InlineData("content\\sl35\\javascript\\jQuery.js", "3.5", "Silverlight", "javascript\\jQuery.js")]
[InlineData("content\\netmf\\CSS\\jQuery.css", "0.0", ".NETMicroFramework", "CSS\\jQuery.css")]
[InlineData("tools\\winrt45\\install.ps1", "4.5", ".NETCore", "install.ps1")]
[InlineData("tools\\winrt10\\uninstall.ps1", "1.0", ".NETCore", "uninstall.ps1")]
[InlineData("tools\\winkt10\\uninstall.ps1", null, null, "winkt10\\uninstall.ps1")]
[InlineData("tools\\init.ps1", null, null, "init.ps1")]
[InlineData("random\\foo.txt", null, null, "random\\foo.txt")]
public void TestParseFrameworkFolderNameFromFilePath(
string filePath, string expectedVersion, string expectedIdentifier, string expectedEffectivePath)
{
// Act
string effectivePath;
var frameworkName = VersionUtility.ParseFrameworkNameFromFilePath(filePath, out effectivePath);
// Assert
if (expectedVersion == null)
{
Assert.Null(frameworkName);
}
else
{
Assert.NotNull(frameworkName);
Assert.Equal(expectedIdentifier, frameworkName.Identifier);
Assert.Equal(expectedVersion, frameworkName.Version.ToString());
}
Assert.Equal(expectedEffectivePath, effectivePath);
}
[Theory]
[InlineData("net40\\foo.dll", "4.0", ".NETFramework", "foo.dll")]
[InlineData("netmu40\\sub\\foo.dll", "0.0", "Unsupported", "sub\\foo.dll")]
[InlineData("foo.dll", null, null, "foo.dll")]
[InlineData("sl35\\javascript\\jQuery.js", "3.5", "Silverlight", "javascript\\jQuery.js")]
[InlineData("netmf\\CSS\\jQuery.css", "0.0", ".NETMicroFramework", "CSS\\jQuery.css")]
[InlineData("CSS\\jQuery.css", "0.0", "Unsupported", "jQuery.css")]
[InlineData("winrt45\\install.ps1", "4.5", ".NETCore", "install.ps1")]
[InlineData("winrt10\\uninstall.ps1", "1.0", ".NETCore", "uninstall.ps1")]
[InlineData("winkt10\\uninstall.ps1", "0.0", "Unsupported", "uninstall.ps1")]
[InlineData("init.ps1", null, null, "init.ps1")]
[InlineData("random\\foo.txt", "0.0", "Unsupported", "foo.txt")]
public void TestParseFrameworkFolderNameWithStrickParsing(
string filePath, string expectedVersion, string expectedIdentifier, string expectedEffectivePath)
{
// Act
string effectivePath;
var frameworkName = VersionUtility.ParseFrameworkFolderName(filePath, strictParsing: true, effectivePath: out effectivePath);
// Assert
if (expectedVersion == null)
{
Assert.Null(frameworkName);
}
else
{
Assert.NotNull(frameworkName);
Assert.Equal(expectedIdentifier, frameworkName.Identifier);
Assert.Equal(expectedVersion, frameworkName.Version.ToString());
}
Assert.Equal(expectedEffectivePath, effectivePath);
}
[Theory]
[InlineData("net40\\foo.dll", "4.0", ".NETFramework", "foo.dll")]
[InlineData("net40\\sub\\foo.dll", "4.0", ".NETFramework", "sub\\foo.dll")]
[InlineData("foo.dll", null, null, "foo.dll")]
[InlineData("sl35\\javascript\\jQuery.js", "3.5", "Silverlight", "javascript\\jQuery.js")]
[InlineData("netmf\\CSS\\jQuery.css", "0.0", ".NETMicroFramework", "CSS\\jQuery.css")]
[InlineData("netmf\\CSS\\jQuery.css", "0.0", ".NETMicroFramework", "CSS\\jQuery.css")]
[InlineData("winrt45\\install.ps1", "4.5", ".NETCore", "install.ps1")]
[InlineData("winrt10\\uninstall.ps1", "1.0", ".NETCore", "uninstall.ps1")]
[InlineData("winrt10\\uninstall.ps1", "1.0", ".NETCore", "uninstall.ps1")]
[InlineData("init.ps1", null, null, "init.ps1")]
[InlineData("random\\foo.txt", null, null, "random\\foo.txt")]
public void TestParseFrameworkFolderNameWithNonStrickParsing(
string filePath, string expectedVersion, string expectedIdentifier, string expectedEffectivePath)
{
// Act
string effectivePath;
var frameworkName = VersionUtility.ParseFrameworkFolderName(filePath, strictParsing: false, effectivePath: out effectivePath);
// Assert
if (expectedVersion == null)
{
Assert.Null(frameworkName);
}
else
{
Assert.NotNull(frameworkName);
Assert.Equal(expectedIdentifier, frameworkName.Identifier);
Assert.Equal(expectedVersion, frameworkName.Version.ToString());
}
Assert.Equal(expectedEffectivePath, effectivePath);
}
[Theory]
[InlineData("content\\-\\wow\\cool.txt", "-\\wow\\cool.txt")]
[InlineData("content\\-world\\x.dll", "-world\\x.dll")]
public void ParseFrameworkNameFromFilePathDoesNotThrowIfPathHasADash(string path, string expectedPath)
{
// Act
string effectivePath;
var framework = VersionUtility.ParseFrameworkNameFromFilePath(path, out effectivePath);
// Assert
Assert.Null(framework);
Assert.Equal(expectedPath, effectivePath);
}
[Fact]
public void ParseFrameworkNameNormalizesNativeFrameworkNames()
{
// Arrange
Version defaultVersion = new Version("0.0");
// Act
var frameworkName = VersionUtility.ParseFrameworkName("native");
// Assert
Assert.Equal("native", frameworkName.Identifier);
Assert.Equal(defaultVersion, frameworkName.Version);
}
[Fact]
public void ParseFrameworkNameNormalizesSupportedNetFrameworkNames()
{
// Arrange
var knownNameFormats = new[] { ".net", ".netframework", "net", "netframework" };
Version defaultVersion = new Version("0.0");
// Act
var frameworkNames = knownNameFormats.Select(fmt => VersionUtility.ParseFrameworkName(fmt));
// Assert
foreach (var frameworkName in frameworkNames)
{
Assert.Equal(".NETFramework", frameworkName.Identifier);
Assert.Equal(defaultVersion, frameworkName.Version);
}
}
[Fact]
public void ParseFrameworkNameNormalizesSupportedPortableNetFrameworkNames()
{
// Arrange
var knownNameFormats = new[] { ".netportable-sl3", "netportable-net4", "portable-netcore45" };
Version defaultVersion = new Version("0.0");
// Act
var frameworkNames = knownNameFormats.Select(fmt => VersionUtility.ParseFrameworkName(fmt));
// Assert
foreach (var frameworkName in frameworkNames)
{
Assert.Equal(".NETPortable", frameworkName.Identifier);
Assert.Equal(defaultVersion, frameworkName.Version);
}
}
[Fact]
public void ParseFrameworkNameNormalizesSupportedWindowsPhoneNames()
{
// Arrange
var knownNameFormats = new[] { "windowsphone", "wp" };
Version defaultVersion = new Version("0.0");
// Act
var frameworkNames = knownNameFormats.Select(fmt => VersionUtility.ParseFrameworkName(fmt));
// Assert
foreach (var frameworkName in frameworkNames)
{
Assert.Equal("WindowsPhone", frameworkName.Identifier);
Assert.Equal(defaultVersion, frameworkName.Version);
}
}
[Fact]
public void ParseFrameworkNameNormalizesSupportedWinRTFrameworkNames()
{
// Arrange
var knownNameFormats = new[] { "winrt", ".NETCore", "NetCore" };
Version defaultVersion = new Version("0.0");
// Act
var frameworkNames = knownNameFormats.Select(fmt => VersionUtility.ParseFrameworkName(fmt));
// Assert
foreach (var frameworkName in frameworkNames)
{
Assert.Equal(".NETCore", frameworkName.Identifier);
Assert.Equal(defaultVersion, frameworkName.Version);
}
}
[Fact]
public void ParseFrameworkNameNormalizesSupportedWindowsFrameworkNames()
{
// Arrange
var knownNameFormats = new[] { "Windows", "win" };
Version defaultVersion = new Version("0.0");
// Act
var frameworkNames = knownNameFormats.Select(fmt => VersionUtility.ParseFrameworkName(fmt));
// Assert
foreach (var frameworkName in frameworkNames)
{
Assert.Equal("Windows", frameworkName.Identifier);
Assert.Equal(defaultVersion, frameworkName.Version);
}
}
[Fact]
public void ParseFrameworkNameNormalizesSupportedNetMicroFrameworkNames()
{
// Arrange
var knownNameFormats = new[] { "netmf4.1", ".NETMicroFramework4.1" };
Version version41 = new Version("4.1");
// Act
var frameworkNames = knownNameFormats.Select(fmt => VersionUtility.ParseFrameworkName(fmt));
// Assert
foreach (var frameworkName in frameworkNames)
{
Assert.Equal(".NETMicroFramework", frameworkName.Identifier);
Assert.Equal(version41, frameworkName.Version);
}
}
[Fact]
public void ParseFrameworkNameNormalizesSupportedSilverlightNames()
{
// Arrange
var knownNameFormats = new[] { "sl", "SL", "SilVerLight", "Silverlight", "Silverlight " };
Version defaultVersion = new Version("0.0");
// Act
var frameworkNames = knownNameFormats.Select(VersionUtility.ParseFrameworkName);
// Assert
foreach (var frameworkName in frameworkNames)
{
Assert.Equal("Silverlight", frameworkName.Identifier);
Assert.Equal(defaultVersion, frameworkName.Version);
}
}
[Fact]
public void ParseFrameworkNameNormalizesSupportedMonoAndroidNames()
{
// Arrange
var knownNameFormats = new[] { "MonoAndroid", "monoandroid", "MONOANDROID " };
Version defaultVersion = new Version("0.0");
// Act
var frameworkNames = knownNameFormats.Select(VersionUtility.ParseFrameworkName);
// Assert
foreach (var frameworkName in frameworkNames)
{
Assert.Equal("MonoAndroid", frameworkName.Identifier);
Assert.Equal(defaultVersion, frameworkName.Version);
}
}
[Fact]
public void ParseFrameworkNameNormalizesSupportedMonoTouchNames()
{
// Arrange
var knownNameFormats = new[] { "MonoTouch", "monotouch", "monoTOUCH " };
Version defaultVersion = new Version("0.0");
// Act
var frameworkNames = knownNameFormats.Select(VersionUtility.ParseFrameworkName);
// Assert
foreach (var frameworkName in frameworkNames)
{
Assert.Equal("MonoTouch", frameworkName.Identifier);
Assert.Equal(defaultVersion, frameworkName.Version);
}
}
[Fact]
public void ParseFrameworkNameNormalizesSupportedMonoMacNames()
{
// Arrange
var knownNameFormats = new[] { "MonoMac", "monomac", "mONOmAC " };
Version defaultVersion = new Version("0.0");
// Act
var frameworkNames = knownNameFormats.Select(VersionUtility.ParseFrameworkName);
// Assert
foreach (var frameworkName in frameworkNames)
{
Assert.Equal("MonoMac", frameworkName.Identifier);
Assert.Equal(defaultVersion, frameworkName.Version);
}
}
[Fact]
public void ParseFrameworkNameReturnsUnsupportedFrameworkNameIfUnrecognized()
{
// Act
var frameworkName1 = VersionUtility.ParseFrameworkName("NETCF20");
var frameworkName2 = VersionUtility.ParseFrameworkName("NET40ClientProfile");
var frameworkName3 = VersionUtility.ParseFrameworkName("NET40Foo");
// Assert
Assert.Equal("Unsupported", frameworkName1.Identifier);
Assert.Equal("Unsupported", frameworkName2.Identifier);
Assert.Equal("Unsupported", frameworkName3.Identifier);
}
[Fact]
public void ParseFrameworkNameUsesNetFrameworkIfOnlyVersionSpecified()
{
// Arrange
Version version20 = new Version("2.0");
// Act
var frameworkName = VersionUtility.ParseFrameworkName("20");
// Assert
Assert.Equal(".NETFramework", frameworkName.Identifier);
Assert.Equal(version20, frameworkName.Version);
}
[Fact]
public void ParseFrameworkNameVersionFormats()
{
// Arrange
var versionFormats = new[] { "4.0", "40", "4" };
Version version40 = new Version("4.0");
// Act
var frameworkNames = versionFormats.Select(VersionUtility.ParseFrameworkName);
// Assert
foreach (var frameworkName in frameworkNames)
{
Assert.Equal(".NETFramework", frameworkName.Identifier);
Assert.Equal(version40, frameworkName.Version);
}
}
[Fact]
public void ParseFrameworkNameVersionIntegerLongerThan4CharsTrimsExccess()
{
// Act
var frameworkName = VersionUtility.ParseFrameworkName("NET41235");
// Assert
Assert.Equal(".NETFramework", frameworkName.Identifier);
Assert.Equal(new Version("4.1.2.3"), frameworkName.Version);
}
[Fact]
public void ParseFrameworkNameInvalidVersionFormatUsesDefaultVersion()
{
// Act
var frameworkName = VersionUtility.ParseFrameworkName("NET4.1.4.5.5");
// Assert
Assert.Equal("Unsupported", frameworkName.Identifier);
}
[Fact]
public void ParseFrameworkNameWithProfile()
{
// Act
var frameworkName = VersionUtility.ParseFrameworkName("net40-client");
// Assert
Assert.Equal(".NETFramework", frameworkName.Identifier);
Assert.Equal(new Version("4.0"), frameworkName.Version);
Assert.Equal("Client", frameworkName.Profile);
}
[Fact]
public void ParseFrameworkNameWithUnknownProfileUsesProfileAsIs()
{
// Act
var frameworkName = VersionUtility.ParseFrameworkName("net40-other");
// Assert
Assert.Equal(".NETFramework", frameworkName.Identifier);
Assert.Equal(new Version("4.0"), frameworkName.Version);
Assert.Equal("other", frameworkName.Profile);
}
[Fact]
public void ParseFrameworkNameWithFullProfileNoamlizesToEmptyProfile()
{
// Act
var frameworkName = VersionUtility.ParseFrameworkName("net40-full");
// Assert
Assert.Equal(".NETFramework", frameworkName.Identifier);
Assert.Equal(new Version("4.0"), frameworkName.Version);
Assert.Equal(String.Empty, frameworkName.Profile);
}
[Fact]
public void ParseFrameworkNameWithWPProfileGetNormalizedToWindowsPhone()
{
// Act
var frameworkName = VersionUtility.ParseFrameworkName("sl4-wp");
// Assert
Assert.Equal("Silverlight", frameworkName.Identifier);
Assert.Equal(new Version("4.0"), frameworkName.Version);
Assert.Equal("WindowsPhone", frameworkName.Profile);
}
[Fact]
public void ParseFrameworkNameWithCFProfileGetNormalizedToCompactFramework()
{
// Act
var frameworkName = VersionUtility.ParseFrameworkName("net20-cf");
// Assert
Assert.Equal(".NETFramework", frameworkName.Identifier);
Assert.Equal(new Version("2.0"), frameworkName.Version);
Assert.Equal("CompactFramework", frameworkName.Profile);
}
[Fact]
public void ParseFrameworkNameWithEmptyProfile()
{
// Act
var frameworkName = VersionUtility.ParseFrameworkName("sl4-");
// Assert
Assert.Equal("Silverlight", frameworkName.Identifier);
Assert.Equal(new Version("4.0"), frameworkName.Version);
Assert.Equal(String.Empty, frameworkName.Profile);
}
[Fact]
public void ParseFrameworkNameWithInvalidFrameworkNameThrows()
{
// Act
ExceptionAssert.ThrowsArgumentException(() => VersionUtility.ParseFrameworkName("-"), "frameworkName", "Framework name is missing.");
ExceptionAssert.ThrowsArgumentException(() => VersionUtility.ParseFrameworkName("-client"), "frameworkName", "Framework name is missing.");
ExceptionAssert.ThrowsArgumentException(() => VersionUtility.ParseFrameworkName(""), "frameworkName", "Framework name is missing.");
ExceptionAssert.ThrowsArgumentException(() => VersionUtility.ParseFrameworkName("---"), "frameworkName", "Invalid framework name format. Expected {framework}{version}-{profile}.");
}
[Fact]
public void ParseFrameworkFolderName()
{
// foo.dll
// sub\foo.dll -> Unsupported since we can't tell if this was meant to be a framework name or not
// {FrameworkName}{Version}\foo.dll
// {FrameworkName}{Version}\sub1\foo.dll
// {FrameworkName}{Version}\sub1\sub2\foo.dll
var f1 = VersionUtility.ParseFrameworkFolderName(@"foo.dll");
var f2 = VersionUtility.ParseFrameworkFolderName(@"sub\foo.dll");
var f3 = VersionUtility.ParseFrameworkFolderName(@"SL4\foo.dll");
var f4 = VersionUtility.ParseFrameworkFolderName(@"SL3\sub1\foo.dll");
var f5 = VersionUtility.ParseFrameworkFolderName(@"SL20\sub1\sub2\foo.dll");
var f6 = VersionUtility.ParseFrameworkFolderName(@"net\foo.dll");
var f7 = VersionUtility.ParseFrameworkFolderName(@"winrt45\foo.dll");
Assert.Null(f1);
Assert.Equal("Unsupported", f2.Identifier);
Assert.Equal("Silverlight", f3.Identifier);
Assert.Equal(new Version("4.0"), f3.Version);
Assert.Equal("Silverlight", f4.Identifier);
Assert.Equal(new Version("3.0"), f4.Version);
Assert.Equal("Silverlight", f5.Identifier);
Assert.Equal(new Version("2.0"), f5.Version);
Assert.Equal(".NETFramework", f6.Identifier);
Assert.Equal(new Version(), f6.Version);
Assert.Equal(".NETCore", f7.Identifier);
Assert.Equal(new Version("4.5"), f7.Version);
}
[Fact]
public void GetFrameworkStringFromFrameworkName()
{
// Arrange
var net40 = new FrameworkName(".NETFramework", new Version(4, 0));
var net40Client = new FrameworkName(".NETFramework", new Version(4, 0), "Client");
var sl3 = new FrameworkName("Silverlight", new Version(3, 0));
var sl4 = new FrameworkName("Silverlight", new Version(4, 0));
var wp7 = new FrameworkName("Silverlight", new Version(4, 0), "WindowsPhone");
var wp7Mango = new FrameworkName("Silverlight", new Version(4, 0), "WindowsPhone71");
var netMicro41 = new FrameworkName(".NETMicroFramework", new Version(4, 1));
var winrt = new FrameworkName(".NETCore", new Version(4, 5));
// Act
string net40Value = VersionUtility.GetFrameworkString(net40);
string net40ClientValue = VersionUtility.GetFrameworkString(net40Client);
string sl3Value = VersionUtility.GetFrameworkString(sl3);
string sl4Value = VersionUtility.GetFrameworkString(sl4);
string wp7Value = VersionUtility.GetFrameworkString(wp7);
string wp7MangoValue = VersionUtility.GetFrameworkString(wp7Mango);
string netMicro41Value = VersionUtility.GetFrameworkString(netMicro41);
string winrtValue = VersionUtility.GetFrameworkString(winrt);
// Assert
Assert.Equal(".NETFramework4.0", net40Value);
Assert.Equal(".NETFramework4.0-Client", net40ClientValue);
Assert.Equal("Silverlight3.0", sl3Value);
Assert.Equal("Silverlight4.0", sl4Value);
Assert.Equal("Silverlight4.0-WindowsPhone", wp7Value);
Assert.Equal("Silverlight4.0-WindowsPhone71", wp7MangoValue);
Assert.Equal(".NETMicroFramework4.1", netMicro41Value);
Assert.Equal(".NETCore4.5", winrtValue);
}
[Fact]
public void ParseVersionSpecWithNullThrows()
{
// Act & Assert
ExceptionAssert.ThrowsArgNull(() => VersionUtility.ParseVersionSpec(null), "value");
}
[Fact]
public void ParseVersionSpecSimpleVersionNoBrackets()
{
// Act
var versionInfo = VersionUtility.ParseVersionSpec("1.2");
// Assert
Assert.Equal("1.2", versionInfo.MinVersion.ToString());
Assert.True(versionInfo.IsMinInclusive);
Assert.Equal(null, versionInfo.MaxVersion);
Assert.False(versionInfo.IsMaxInclusive);
}
[Fact]
public void ParseVersionSpecSimpleVersionNoBracketsExtraSpaces()
{
// Act
var versionInfo = VersionUtility.ParseVersionSpec(" 1 . 2 ");
// Assert
Assert.Equal("1.2", versionInfo.MinVersion.ToString());
Assert.True(versionInfo.IsMinInclusive);
Assert.Equal(null, versionInfo.MaxVersion);
Assert.False(versionInfo.IsMaxInclusive);
}
[Fact]
public void ParseVersionSpecMaxOnlyInclusive()
{
// Act
var versionInfo = VersionUtility.ParseVersionSpec("(,1.2]");
// Assert
Assert.Equal(null, versionInfo.MinVersion);
Assert.False(versionInfo.IsMinInclusive);
Assert.Equal("1.2", versionInfo.MaxVersion.ToString());
Assert.True(versionInfo.IsMaxInclusive);
}
[Fact]
public void ParseVersionSpecMaxOnlyExclusive()
{
var versionInfo = VersionUtility.ParseVersionSpec("(,1.2)");
Assert.Equal(null, versionInfo.MinVersion);
Assert.False(versionInfo.IsMinInclusive);
Assert.Equal("1.2", versionInfo.MaxVersion.ToString());
Assert.False(versionInfo.IsMaxInclusive);
}
[Fact]
public void ParseVersionSpecExactVersion()
{
// Act
var versionInfo = VersionUtility.ParseVersionSpec("[1.2]");
// Assert
Assert.Equal("1.2", versionInfo.MinVersion.ToString());
Assert.True(versionInfo.IsMinInclusive);
Assert.Equal("1.2", versionInfo.MaxVersion.ToString());
Assert.True(versionInfo.IsMaxInclusive);
}
[Fact]
public void ParseVersionSpecMinOnlyExclusive()
{
// Act
var versionInfo = VersionUtility.ParseVersionSpec("(1.2,)");
// Assert
Assert.Equal("1.2", versionInfo.MinVersion.ToString());
Assert.False(versionInfo.IsMinInclusive);
Assert.Equal(null, versionInfo.MaxVersion);
Assert.False(versionInfo.IsMaxInclusive);
}
[Fact]
public void ParseVersionSpecRangeExclusiveExclusive()
{
// Act
var versionInfo = VersionUtility.ParseVersionSpec("(1.2,2.3)");
// Assert
Assert.Equal("1.2", versionInfo.MinVersion.ToString());
Assert.False(versionInfo.IsMinInclusive);
Assert.Equal("2.3", versionInfo.MaxVersion.ToString());
Assert.False(versionInfo.IsMaxInclusive);
}
[Fact]
public void ParseVersionSpecRangeExclusiveInclusive()
{
// Act
var versionInfo = VersionUtility.ParseVersionSpec("(1.2,2.3]");
// Assert
Assert.Equal("1.2", versionInfo.MinVersion.ToString());
Assert.False(versionInfo.IsMinInclusive);
Assert.Equal("2.3", versionInfo.MaxVersion.ToString());
Assert.True(versionInfo.IsMaxInclusive);
}
[Fact]
public void ParseVersionSpecRangeInclusiveExclusive()
{
// Act
var versionInfo = VersionUtility.ParseVersionSpec("[1.2,2.3)");
Assert.Equal("1.2", versionInfo.MinVersion.ToString());
Assert.True(versionInfo.IsMinInclusive);
Assert.Equal("2.3", versionInfo.MaxVersion.ToString());
Assert.False(versionInfo.IsMaxInclusive);
}
[Fact]
public void ParseVersionSpecRangeInclusiveInclusive()
{
// Act
var versionInfo = VersionUtility.ParseVersionSpec("[1.2,2.3]");
// Assert
Assert.Equal("1.2", versionInfo.MinVersion.ToString());
Assert.True(versionInfo.IsMinInclusive);
Assert.Equal("2.3", versionInfo.MaxVersion.ToString());
Assert.True(versionInfo.IsMaxInclusive);
}
[Fact]
public void ParseVersionSpecRangeInclusiveInclusiveExtraSpaces()
{
// Act
var versionInfo = VersionUtility.ParseVersionSpec(" [ 1 .2 , 2 .3 ] ");
// Assert
Assert.Equal("1.2", versionInfo.MinVersion.ToString());
Assert.True(versionInfo.IsMinInclusive);
Assert.Equal("2.3", versionInfo.MaxVersion.ToString());
Assert.True(versionInfo.IsMaxInclusive);
}
[Fact]
public void NormalizeVersionFillsInZerosForUnsetVersionParts()
{
// Act
Version version = VersionUtility.NormalizeVersion(new Version("1.5"));
// Assert
Assert.Equal(new Version("1.5.0.0"), version);
}
[Fact]
public void ParseVersionSpecRangeIntegerRanges()
{
// Act
var versionInfo = VersionUtility.ParseVersionSpec(" [1, 2] ");
// Assert
Assert.Equal("1.0", versionInfo.MinVersion.ToString());
Assert.True(versionInfo.IsMinInclusive);
Assert.Equal("2.0", versionInfo.MaxVersion.ToString());
Assert.True(versionInfo.IsMaxInclusive);
}
[Fact]
public void ParseVersionSpecRangeNegativeIntegerRanges()
{
// Act
IVersionSpec versionInfo;
bool parsed = VersionUtility.TryParseVersionSpec(" [-1, 2] ", out versionInfo);
Assert.False(parsed);
Assert.Null(versionInfo);
}
public static IEnumerable<object[]> TrimVersionData
{
get
{
yield return new object[] { new Version(1, 2, 3, 0), new Version(1, 2, 3) };
yield return new object[] { new Version("1.2.3.0"), new Version("1.2.3") };
yield return new object[] { new Version(1, 2, 0, 0), new Version(1, 2) };
yield return new object[] { new Version("1.2.0.0"), new Version("1.2") };
yield return new object[] { new Version(1, 2, 0, 5), new Version(1, 2, 0, 5) };
}
}
[Theory]
[PropertyData("TrimVersionData")]
public void TrimVersionTrimsRevisionIfZero(Version version, Version expected)
{
// Act
var result = VersionUtility.TrimVersion(version);
// Assert
Assert.Equal(expected, result);
}
[Fact]
public void GetAllPossibleVersionsTwoDigits()
{
// Arrange
var expectedVersions = new[] {
new SemanticVersion("1.1"),
new SemanticVersion("1.1.0"),
new SemanticVersion("1.1.0.0")
};
// Act
var versions = VersionUtility.GetPossibleVersions(new SemanticVersion("1.1")).ToList();
// Assert
Assert.Equal(expectedVersions, versions);
}
[Fact]
public void GetAllPossibleVersionsThreeDigits()
{
// Arrange
var expectedVersions = new[] {
new SemanticVersion("1.0"),
new SemanticVersion("1.0.0"),
new SemanticVersion("1.0.0.0"),
};
// Act
var versions = VersionUtility.GetPossibleVersions(new SemanticVersion("1.0.0")).ToList();
// Assert
Assert.Equal(expectedVersions, versions);
}
[Fact]
public void GetAllPossibleVersionsFourDigits()
{
// Arrange
var expectedVersions = new[] {
new SemanticVersion("1.0"),
new SemanticVersion("1.0.0"),
new SemanticVersion("1.0.0.0"),
};
var expectedVersionStrings = new[] {
"1.0",
"1.0.0",
"1.0.0.0"
};
// Act
var versions = VersionUtility.GetPossibleVersions(new SemanticVersion("1.0.0.0")).ToList();
// Assert
Assert.Equal(expectedVersions, versions);
Assert.Equal(expectedVersionStrings, versions.Select(v => v.ToString()));
}
[Fact]
public void GetAllPossibleVersionsThreeDigitsWithZeroBetween()
{
// Arrange
var expectedVersions = new[] {
new SemanticVersion("1.0.1"),
new SemanticVersion("1.0.1.0")
};
var expectedVersionStrings = new[]
{
"1.0.1",
"1.0.1.0",
};
// Act
var versions = VersionUtility.GetPossibleVersions(new SemanticVersion("1.0.1")).ToList();
// Assert
Assert.Equal(expectedVersions, versions);
Assert.Equal(expectedVersionStrings, versions.Select(v => v.ToString()));
}
[Fact]
public void GetAllPossibleVersionsFourDigitsWithTrailingZeros()
{
// Arrange
var expectedVersions = new[] {
new SemanticVersion("1.1"),
new SemanticVersion("1.1.0"),
new SemanticVersion("1.1.0.0"),
};
var expectedVersionStrings = new[]
{
"1.1",
"1.1.0",
"1.1.0.0",
};
// Act
var versions = VersionUtility.GetPossibleVersions(new SemanticVersion("1.1.0.0")).ToList();
// Assert
Assert.Equal(expectedVersions, versions);
Assert.Equal(expectedVersionStrings, versions.Select(v => v.ToString()));
}
[Fact]
public void GetSafeVersions()
{
// Act
IVersionSpec versionSpec1 = VersionUtility.GetSafeRange(new SemanticVersion("1.3"));
IVersionSpec versionSpec2 = VersionUtility.GetSafeRange(new SemanticVersion("0.9"));
IVersionSpec versionSpec3 = VersionUtility.GetSafeRange(new SemanticVersion("2.9.45.6"));
// Assert
AssertSafeVersion(versionSpec1, new SemanticVersion("1.3"), new SemanticVersion("1.4"));
AssertSafeVersion(versionSpec2, new SemanticVersion("0.9"), new SemanticVersion("0.10"));
AssertSafeVersion(versionSpec3, new SemanticVersion("2.9.45.6"), new SemanticVersion("2.10"));
}
private void AssertSafeVersion(IVersionSpec versionSpec, SemanticVersion minVer, SemanticVersion maxVer)
{
Assert.True(versionSpec.IsMinInclusive);
Assert.False(versionSpec.IsMaxInclusive);
Assert.Equal(versionSpec.MinVersion, minVer);
Assert.Equal(versionSpec.MaxVersion, maxVer);
}
[Fact]
public void TrimVersionThrowsIfVersionNull()
{
ExceptionAssert.ThrowsArgNull(() => VersionUtility.TrimVersion(null), "version");
}
[Fact]
public void IsCompatibleReturnsFalseForSlAndWindowsPhoneFrameworks()
{
// Arrange
FrameworkName sl3 = VersionUtility.ParseFrameworkName("sl3");
FrameworkName wp7 = VersionUtility.ParseFrameworkName("sl3-wp");
// Act
bool wp7CompatibleWithSl = VersionUtility.IsCompatible(sl3, wp7);
bool slCompatibleWithWp7 = VersionUtility.IsCompatible(wp7, sl3);
// Assert
Assert.False(slCompatibleWithWp7);
Assert.False(wp7CompatibleWithSl);
}
[Fact]
public void IsCompatibleWindowsPhoneVersions()
{
// Arrange
FrameworkName wp7 = VersionUtility.ParseFrameworkName("sl3-wp");
FrameworkName wp7Mango = VersionUtility.ParseFrameworkName("sl4-wp71");
FrameworkName wp8 = new FrameworkName("WindowsPhone, Version=v8.0");
// Act
bool wp7MangoCompatibleWithwp7 = VersionUtility.IsCompatible(wp7, wp7Mango);
bool wp7CompatibleWithwp7Mango = VersionUtility.IsCompatible(wp7Mango, wp7);
bool wp7CompatibleWithwp8 = VersionUtility.IsCompatible(wp8, wp7);
bool wp7MangoCompatibleWithwp8 = VersionUtility.IsCompatible(wp8, wp7Mango);
bool wp8CompatibleWithwp7 = VersionUtility.IsCompatible(wp7, wp8);
bool wp8CompatbielWithwp7Mango = VersionUtility.IsCompatible(wp7Mango, wp8);
// Assert
Assert.False(wp7MangoCompatibleWithwp7);
Assert.True(wp7CompatibleWithwp7Mango);
Assert.True(wp7CompatibleWithwp8);
Assert.True(wp7MangoCompatibleWithwp8);
Assert.False(wp8CompatibleWithwp7);
Assert.False(wp8CompatbielWithwp7Mango);
}
[Theory]
[InlineData("wp")]
[InlineData("wp7")]
[InlineData("wp70")]
[InlineData("windowsphone")]
[InlineData("windowsphone7")]
[InlineData("windowsphone70")]
[InlineData("sl3-wp")]
public void WindowsPhone7IdentifierCompatibleWithAllWPProjects(string wp7Identifier)
{
// Arrange
var wp7Package = VersionUtility.ParseFrameworkName(wp7Identifier);
var wp7Project = new FrameworkName("Silverlight, Version=v3.0, Profile=WindowsPhone");
var mangoProject = new FrameworkName("Silverlight, Version=v4.0, Profile=WindowsPhone71");
var apolloProject = new FrameworkName("WindowsPhone, Version=v8.0");
// Act & Assert
Assert.True(VersionUtility.IsCompatible(wp7Project, wp7Package));
Assert.True(VersionUtility.IsCompatible(mangoProject, wp7Package));
Assert.True(VersionUtility.IsCompatible(apolloProject, wp7Package));
}
[Theory]
[InlineData("wp71")]
[InlineData("windowsphone71")]
[InlineData("sl4-wp71")]
public void WindowsPhoneMangoIdentifierCompatibleWithAllWPProjects(string mangoIdentifier)
{
// Arrange
var mangoPackage = VersionUtility.ParseFrameworkName(mangoIdentifier);
var wp7Project = new FrameworkName("Silverlight, Version=v3.0, Profile=WindowsPhone");
var mangoProject = new FrameworkName("Silverlight, Version=v4.0, Profile=WindowsPhone71");
var apolloProject = new FrameworkName("WindowsPhone, Version=v8.0");
// Act & Assert
Assert.False(VersionUtility.IsCompatible(wp7Project, mangoPackage));
Assert.True(VersionUtility.IsCompatible(mangoProject, mangoPackage));
Assert.True(VersionUtility.IsCompatible(apolloProject, mangoPackage));
}
[Theory]
[InlineData("wp8")]
[InlineData("wp80")]
[InlineData("windowsphone8")]
[InlineData("windowsphone80")]
public void WindowsPhoneApolloIdentifierCompatibleWithAllWPProjects(string apolloIdentifier)
{
// Arrange
var apolloPackage = VersionUtility.ParseFrameworkName(apolloIdentifier);
var wp7Project = new FrameworkName("Silverlight, Version=v3.0, Profile=WindowsPhone");
var mangoProject = new FrameworkName("Silverlight, Version=v4.0, Profile=WindowsPhone71");
var apolloProject = new FrameworkName("WindowsPhone, Version=v8.0");
// Act & Assert
Assert.False(VersionUtility.IsCompatible(wp7Project, apolloPackage));
Assert.False(VersionUtility.IsCompatible(mangoProject, apolloPackage));
Assert.True(VersionUtility.IsCompatible(apolloProject, apolloPackage));
}
[Theory]
[InlineData("windows")]
[InlineData("windows8")]
[InlineData("win")]
[InlineData("win8")]
public void WindowsIdentifierCompatibleWithWindowsStoreAppProjects(string identifier)
{
// Arrange
var packageFramework = VersionUtility.ParseFrameworkName(identifier);
var projectFramework = new FrameworkName(".NETCore, Version=4.5");
// Act && Assert
Assert.True(VersionUtility.IsCompatible(projectFramework, packageFramework));
}
[Theory]
[InlineData("windows9")]
[InlineData("win9")]
[InlineData("win10")]
[InlineData("windows81")]
[InlineData("windows45")]
[InlineData("windows1")]
public void WindowsIdentifierWithUnsupportedVersionNotCompatibleWithWindowsStoreAppProjects(string identifier)
{
// Arrange
var packageFramework = VersionUtility.ParseFrameworkName(identifier);
var projectFramework = new FrameworkName(".NETCore, Version=4.5");
// Act && Assert
Assert.False(VersionUtility.IsCompatible(projectFramework, packageFramework));
}
[Fact]
public void NetFrameworkCompatibiilityIsCompatibleReturns()
{
// Arrange
FrameworkName net40 = VersionUtility.ParseFrameworkName("net40");
FrameworkName net40Client = VersionUtility.ParseFrameworkName("net40-client");
// Act
bool netClientCompatibleWithNet = VersionUtility.IsCompatible(net40, net40Client);
bool netCompatibleWithClient = VersionUtility.IsCompatible(net40Client, net40);
// Assert
Assert.True(netClientCompatibleWithNet);
Assert.True(netCompatibleWithClient);
}
[Fact]
public void LowerFrameworkVersionsAreNotCompatibleWithHigherFrameworkVersionsWithSameFrameworkName()
{
// Arrange
FrameworkName net40 = VersionUtility.ParseFrameworkName("net40");
FrameworkName net20 = VersionUtility.ParseFrameworkName("net20");
// Act
bool net40CompatibleWithNet20 = VersionUtility.IsCompatible(net20, net40);
bool net20CompatibleWithNet40 = VersionUtility.IsCompatible(net40, net20);
// Assert
Assert.False(net40CompatibleWithNet20);
Assert.True(net20CompatibleWithNet40);
}
[Fact]
public void IsCompatibleReturnsTrueIfSupportedFrameworkListIsEmpty()
{
// Arrange
FrameworkName net40Client = VersionUtility.ParseFrameworkName("net40-client");
// Act
var result = VersionUtility.IsCompatible(net40Client, Enumerable.Empty<FrameworkName>());
// Assert
Assert.True(result);
}
[Fact]
public void IsCompatibleReturnsTrueIfProjectFrameworkIsNully()
{
// Arrange
FrameworkName net40Client = VersionUtility.ParseFrameworkName("net40-client");
// Act
var result = VersionUtility.IsCompatible(null, net40Client);
// Assert
Assert.True(result);
}
[Fact]
public void ParseVersionThrowsIfExclusiveMinAndMaxVersionSpecContainsNoValues()
{
// Arrange
var versionString = "(,)";
// Assert
var exception = Assert.Throws<ArgumentException>(() => VersionUtility.ParseVersionSpec(versionString));
Assert.Equal("'(,)' is not a valid version string.", exception.Message);
}
[Fact]
public void ParseVersionThrowsIfInclusiveMinAndMaxVersionSpecContainsNoValues()
{
// Arrange
var versionString = "[,]";
// Assert
var exception = Assert.Throws<ArgumentException>(() => VersionUtility.ParseVersionSpec(versionString));
Assert.Equal("'[,]' is not a valid version string.", exception.Message);
}
[Fact]
public void ParseVersionThrowsIfInclusiveMinAndExclusiveMaxVersionSpecContainsNoValues()
{
// Arrange
var versionString = "[,)";
// Assert
var exception = Assert.Throws<ArgumentException>(() => VersionUtility.ParseVersionSpec(versionString));
Assert.Equal("'[,)' is not a valid version string.", exception.Message);
}
[Fact]
public void ParseVersionThrowsIfExclusiveMinAndInclusiveMaxVersionSpecContainsNoValues()
{
// Arrange
var versionString = "(,]";
// Assert
var exception = Assert.Throws<ArgumentException>(() => VersionUtility.ParseVersionSpec(versionString));
Assert.Equal("'(,]' is not a valid version string.", exception.Message);
}
[Fact]
public void ParseVersionThrowsIfVersionSpecIsMissingVersionComponent()
{
// Arrange
var versionString = "(,1.3..2]";
// Assert
var exception = Assert.Throws<ArgumentException>(() => VersionUtility.ParseVersionSpec(versionString));
Assert.Equal("'(,1.3..2]' is not a valid version string.", exception.Message);
}
[Fact]
public void ParseVersionThrowsIfVersionSpecContainsMoreThen4VersionComponents()
{
// Arrange
var versionString = "(1.2.3.4.5,1.2]";
// Assert
var exception = Assert.Throws<ArgumentException>(() => VersionUtility.ParseVersionSpec(versionString));
Assert.Equal("'(1.2.3.4.5,1.2]' is not a valid version string.", exception.Message);
}
[Theory]
[PropertyData("VersionSpecData")]
public void ParseVersionParsesTokensVersionsCorrectly(string versionString, VersionSpec versionSpec)
{
// Act
var actual = VersionUtility.ParseVersionSpec(versionString);
// Assert
Assert.Equal(versionSpec.IsMinInclusive, actual.IsMinInclusive);
Assert.Equal(versionSpec.IsMaxInclusive, actual.IsMaxInclusive);
Assert.Equal(versionSpec.MinVersion, actual.MinVersion);
Assert.Equal(versionSpec.MaxVersion, actual.MaxVersion);
}
public static IEnumerable<object[]> VersionSpecData
{
get
{
yield return new object[] { "(1.2.3.4, 3.2)", new VersionSpec { MinVersion = new SemanticVersion("1.2.3.4"), MaxVersion = new SemanticVersion("3.2"), IsMinInclusive = false, IsMaxInclusive = false } };
yield return new object[] { "(1.2.3.4, 3.2]", new VersionSpec { MinVersion = new SemanticVersion("1.2.3.4"), MaxVersion = new SemanticVersion("3.2"), IsMinInclusive = false, IsMaxInclusive = true } };
yield return new object[] { "[1.2, 3.2.5)", new VersionSpec { MinVersion = new SemanticVersion("1.2"), MaxVersion = new SemanticVersion("3.2.5"), IsMinInclusive = true, IsMaxInclusive = false } };
yield return new object[] { "[2.3.7, 3.2.4.5]", new VersionSpec { MinVersion = new SemanticVersion("2.3.7"), MaxVersion = new SemanticVersion("3.2.4.5"), IsMinInclusive = true, IsMaxInclusive = true } };
yield return new object[] { "(, 3.2.4.5]", new VersionSpec { MinVersion = null, MaxVersion = new SemanticVersion("3.2.4.5"), IsMinInclusive = false, IsMaxInclusive = true } };
yield return new object[] { "(1.6, ]", new VersionSpec { MinVersion = new SemanticVersion("1.6"), MaxVersion = null, IsMinInclusive = false, IsMaxInclusive = true } };
yield return new object[] { "(1.6)", new VersionSpec { MinVersion = new SemanticVersion("1.6"), MaxVersion = new SemanticVersion("1.6"), IsMinInclusive = false, IsMaxInclusive = false } };
yield return new object[] { "[2.7]", new VersionSpec { MinVersion = new SemanticVersion("2.7"), MaxVersion = new SemanticVersion("2.7"), IsMinInclusive = true, IsMaxInclusive = true } };
}
}
[Fact]
public void ParsePortableFrameworkNameThrowsIfProfileIsEmpty()
{
// Act & Assert
ExceptionAssert.ThrowsArgumentException(
() => VersionUtility.ParseFrameworkName("portable45"),
"profilePart",
"Portable target framework must not have an empty profile part.");
}
[Fact]
public void ParsePortableFrameworkNameThrowsIfProfileContainsASpace()
{
// Act & Assert
ExceptionAssert.ThrowsArgumentException(
() => VersionUtility.ParseFrameworkName("portable45-sl4 net45"),
"profilePart",
"The profile part of a portable target framework must not contain empty space.");
}
[Fact]
public void ParsePortableFrameworkNameThrowsIfProfileContainsEmptyComponent()
{
// Act & Assert
ExceptionAssert.ThrowsArgumentException(
() => VersionUtility.ParseFrameworkName("portable45-sl4++net45"),
"profilePart",
"The profile part of a portable target framework must not contain empty component.");
}
[Fact]
public void ParsePortableFrameworkNameThrowsIfProfileContainsPortableFramework()
{
// Act & Assert
ExceptionAssert.ThrowsArgumentException(
() => VersionUtility.ParseFrameworkName("portable-net45+portable"),
"profilePart",
"The profile part of a portable target framework must not contain a portable framework component.");
}
[Fact]
public void TestGetShortNameForPortableFramework()
{
// Arrange
NetPortableProfileTable.Profiles = BuildProfileCollection();
var framework = new FrameworkName(".NETPortable, Version=4.0, Profile=Profile1");
// Act-1
string shortName = VersionUtility.GetShortFrameworkName(framework);
// Assert-2
Assert.Equal("portable-net45+sl40+wp71", shortName);
// Arrange
var framework2 = new FrameworkName(".NETPortable, Version=4.0, Profile=Profile2");
// Act-2
string shortName2 = VersionUtility.GetShortFrameworkName(framework2);
// Assert-2
Assert.Equal("portable-win+sl30+wp71", shortName2);
// Arrange
var framework3 = new FrameworkName(".NETPortable, Version=4.0, Profile=Profile4");
// Act-3
string shortName3 = VersionUtility.GetShortFrameworkName(framework3);
// Assert-4
Assert.Equal("portable-sl20+wp", shortName3);
}
[Fact]
public void GetShortNameDoesNotIncludeVersionIfVersionIs00()
{
// Act
string shortName = VersionUtility.GetShortFrameworkName(new FrameworkName("Silverlight, Version=v0.0"));
// Assert
Assert.Equal("sl", shortName);
}
[Fact]
public void GetShortNameForNetCore45ReturnsWindows()
{
// Act
string shortName = VersionUtility.GetShortFrameworkName(new FrameworkName(".NETCore, Version=v4.5"));
// Assert
Assert.Equal("win", shortName);
}
[Fact]
public void GetShortNameForWindowsPhoneReturnsWP()
{
// Act
string shortName = VersionUtility.GetShortFrameworkName(new FrameworkName("Silverlight, Version=v3.0, Profile=WindowsPhone"));
// Assert
Assert.Equal("wp", shortName);
}
[Fact]
public void GetShortNameForMangoReturnsWP71()
{
// Act
string shortName = VersionUtility.GetShortFrameworkName(new FrameworkName("Silverlight, Version=v4.0, Profile=WindowsPhone71"));
// Assert
Assert.Equal("wp71", shortName);
}
[Fact]
public void IsCompatibleReturnsTrueForPortableFrameworkAndNormalFramework()
{
// Arrange
var portableFramework = VersionUtility.ParseFrameworkName("portable-netcore45+sl4");
var normalFramework = VersionUtility.ParseFrameworkName("silverlight45");
// Act
bool isCompatible = VersionUtility.IsCompatible(normalFramework, portableFramework);
// Assert
Assert.True(isCompatible);
}
[Fact]
public void IsCompatibleReturnsFalseForPortableFrameworkAndNormalFramework()
{
// Arrange
var portableFramework = VersionUtility.ParseFrameworkName("portable-netcore45+sl4");
var normalFramework = VersionUtility.ParseFrameworkName("silverlight3");
// Act
bool isCompatible = VersionUtility.IsCompatible(normalFramework, portableFramework);
// Assert
Assert.False(isCompatible);
}
[Fact]
public void IsCompatibleReturnsFalseForPortableFrameworkAndNormalFramework2()
{
// Arrange
var portableFramework = VersionUtility.ParseFrameworkName("portable-netcore45+sl4");
var normalFramework = VersionUtility.ParseFrameworkName("wp7");
// Act
bool isCompatible = VersionUtility.IsCompatible(normalFramework, portableFramework);
// Assert
Assert.False(isCompatible);
}
[Theory]
[InlineData("silverlight4")]
[InlineData("silverlight3")]
[InlineData("silverlight5")]
[InlineData("netcore45")]
[InlineData("netcore5")]
public void IsCompatibleReturnsFalseForNormalFrameworkAndPortableFramework(string frameworkValue)
{
// Arrange
var portableFramework = VersionUtility.ParseFrameworkName("portable-netcore45+sl4");
var normalFramework = VersionUtility.ParseFrameworkName(frameworkValue);
// Act
bool isCompatible = VersionUtility.IsCompatible(portableFramework, normalFramework);
// Assert
Assert.False(isCompatible);
}
[Theory]
[InlineData("portable-netcore45+sl4+wp", "portable-netcore45+sl4")]
[InlineData("portable-netcore45+sl4+wp", "portable-netcore5+wp7")]
[InlineData("portable-netcore45+sl4+wp+net", "portable-wp7")]
public void IsCompatibleReturnsTrueForPortableFrameworkAndPortableFramework(string packageFramework, string projectFramework)
{
// Arrange
var packagePortableFramework = VersionUtility.ParseFrameworkName(packageFramework);
var projectPortableFramework = VersionUtility.ParseFrameworkName(projectFramework);
// Act
bool isCompatible = VersionUtility.IsCompatible(projectPortableFramework, packagePortableFramework);
// Assert
Assert.True(isCompatible);
}
[Theory]
[InlineData("portable-netcore45+sl4+wp", "portable-netcore4+sl4")]
[InlineData("portable-netcore45+sl4+wp", "portable-netcore5+wp7+net")]
[InlineData("portable-netcore45+sl4+wp+net", "portable-wp7+netcore4")]
[InlineData("portable-netcore45+sl4", "portable-net4+wp7")]
public void IsCompatibleReturnsFalseForPortableFrameworkAndPortableFramework(string packageFramework, string projectFramework)
{
// Arrange
var packagePortableFramework = VersionUtility.ParseFrameworkName(packageFramework);
var projectPortableFramework = VersionUtility.ParseFrameworkName(projectFramework);
// Act
bool isCompatible = VersionUtility.IsCompatible(projectPortableFramework, packagePortableFramework);
// Assert
Assert.False(isCompatible);
}
[Theory]
[InlineData("portable-net45+sl5+wp71", "portable-net45+sl5+wp71", -3)]
[InlineData("portable-net45+sl5+wp71", "portable-net45+sl5+wp71+win8", -4)]
[InlineData("portable-net45+sl5+wp71", "portable-net45+sl4+wp71+win8", -54)]
[InlineData("portable-net45+sl5+wp71", "portable-net4+sl4+wp71+win8", -104)]
[InlineData("portable-net45+sl5+wp71", "portable-net4+sl4+wp7+win8", -154)]
[InlineData("portable-win8+wp8", "portable-win8+wp7", -52)]
[InlineData("portable-win8+wp8", "portable-win8+wp7+silverlight4", -53)]
public void TestGetCompatibilityBetweenPortableLibraryAndPortableLibrary(string frameworkName, string targetFrameworkName, int expectedScore)
{
// Arrange
var framework = VersionUtility.ParseFrameworkName(frameworkName);
var targetFramework = VersionUtility.ParseFrameworkName(targetFrameworkName);
// Act
int score = VersionUtility.GetCompatibilityBetweenPortableLibraryAndPortableLibrary(framework, targetFramework);
// Assert
Assert.Equal(expectedScore, score);
}
private NetPortableProfileCollection BuildProfileCollection()
{
var profileCollection = new NetPortableProfileCollection();
var profile1 = new NetPortableProfile(
"Profile1",
new[] {
new FrameworkName(".NETFramework, Version=4.5"),
new FrameworkName("Silverlight, Version=4.0"),
new FrameworkName("WindowsPhone, Version=7.1"),
});
var profile2 = new NetPortableProfile(
"Profile2",
new[] {
new FrameworkName(".NetCore, Version=4.5"),
new FrameworkName("Silverlight, Version=3.0"),
new FrameworkName("WindowsPhone, Version=7.1"),
});
var profile3 = new NetPortableProfile(
"Profile3",
new[] {
new FrameworkName(".NetCore, Version=4.5"),
new FrameworkName(".NETFramework, Version=2.0"),
});
var profile4 = new NetPortableProfile(
"Profile4",
new[] {
new FrameworkName("Silverlight, Version=2.0"),
new FrameworkName("Silverlight, Version=3.0, Profile=WindowsPhone"),
});
profileCollection.Add(profile1);
profileCollection.Add(profile2);
profileCollection.Add(profile3);
profileCollection.Add(profile4);
return profileCollection;
}
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using Cassandra.IntegrationTests.TestBase;
using Cassandra.IntegrationTests.TestClusterManagement;
using Cassandra.Tests;
using NUnit.Framework;
namespace Cassandra.IntegrationTests.Policies.Util
{
public class PolicyTestTools
{
public string TableName;
// Coordinators are: Dictionary<(string>HostIpThatWasQueriedAtLeastOnce, (int)NumberOfTimesThisHostWasQueried>
public Dictionary<string, int> Coordinators = new Dictionary<string, int>();
public List<ConsistencyLevel> AchievedConsistencies = new List<ConsistencyLevel>();
public PreparedStatement PreparedStatement;
public string DefaultKeyspace = "policytesttoolsks";
public PolicyTestTools()
{
TableName = TestUtils.GetUniqueTableName();
}
/// <summary>
/// Create schemas for the policy tests, depending on replication factors/strategies.
/// </summary>
public void CreateSchema(ISession session)
{
CreateSchema(session, 1);
}
public void CreateSchema(ISession session, int replicationFactor, string keyspace = null, bool forceSchemaAgreement = false)
{
try
{
session.Execute(string.Format(TestUtils.CreateKeyspaceSimpleFormat, keyspace ?? DefaultKeyspace, replicationFactor));
}
catch (AlreadyExistsException)
{
}
if (forceSchemaAgreement)
{
TestHelper.RetryAssert(
() => Assert.IsTrue(session.Cluster.Metadata.CheckSchemaAgreementAsync().Result),
1000, 60);
}
else
{
TestUtils.WaitForSchemaAgreement(session.Cluster);
}
session.ChangeKeyspace(keyspace ?? DefaultKeyspace);
session.Execute($"CREATE TABLE {TableName} (k int PRIMARY KEY, i int)");
if (forceSchemaAgreement)
{
TestHelper.RetryAssert(
() => Assert.IsTrue(session.Cluster.Metadata.CheckSchemaAgreementAsync().Result),
1000, 60);
}
else
{
TestUtils.WaitForSchemaAgreement(session.Cluster);
}
}
public void CreateMultiDcSchema(ISession session, int dc1RF = 1, int dc2RF = 1)
{
session.Execute(string.Format(TestUtils.CreateKeyspaceGenericFormat, DefaultKeyspace, "NetworkTopologyStrategy",
string.Format("'dc1' : {0}, 'dc2' : {1}", dc1RF, dc2RF)));
TestUtils.WaitForSchemaAgreement(session.Cluster);
session.ChangeKeyspace(DefaultKeyspace);
TestUtils.WaitForSchemaAgreement(session.Cluster);
session.Execute(string.Format("CREATE TABLE {0} (k int PRIMARY KEY, i int)", TableName));
TestUtils.WaitForSchemaAgreement(session.Cluster);
}
/// Coordinator management/count
public void AddCoordinator(string coordinator, ConsistencyLevel consistencyLevel)
{
if (!Coordinators.ContainsKey(coordinator))
Coordinators.Add(coordinator, 0);
int n = Coordinators[coordinator];
Coordinators[coordinator] = n + 1;
AchievedConsistencies.Add(consistencyLevel);
}
public void ResetCoordinators()
{
Coordinators.Clear();
AchievedConsistencies.Clear();
}
public void AssertQueried(string host, int expectedHostQueryCount)
{
// if the host is not found, that's the same as it being queried zero times
int actualHostQueryCount = 0;
if (Coordinators.ContainsKey(host))
actualHostQueryCount = Coordinators[host];
Assert.AreEqual(expectedHostQueryCount, actualHostQueryCount, "For " + host);
}
/// <summary>
/// Verifies that exactly numberOfInsertsToMake queries were received by the specified set of hosts. Request distribution within
/// the set is not tested.
/// </summary>
public void AssertQueriedSet(String[] hosts, int n)
{
int queriedInSet = 0;
foreach (var host in hosts)
{
queriedInSet += Coordinators.ContainsKey(host) ? (int) Coordinators[host] : 0;
}
Assert.AreEqual(queriedInSet, n, string.Format("For [{0}]", String.Join(", ", hosts)));
}
public void AssertQueriedAtLeast(string host, int n)
{
var queried = 0;
if (Coordinators.ContainsKey(host))
{
queried = Coordinators[host];
}
Assert.GreaterOrEqual(queried, n);
}
/// <summary>
/// Asserts that all consistencies achieved in the last execution are equal to the consistency passed
/// </summary>
public void AssertAchievedConsistencyLevel(ConsistencyLevel expectedConsistency)
{
Assert.True(AchievedConsistencies.All(consistency => consistency == expectedConsistency), "Not all consistencies achieved are " + expectedConsistency);
}
/// <summary>
/// Init methods that handle writes using batch and consistency options.
/// </summary>
public void InitPreparedStatement(ITestCluster testCluster, int numberOfInsertsToMake)
{
InitPreparedStatement(testCluster, numberOfInsertsToMake, false, ConsistencyLevel.One);
}
public void InitPreparedStatement(ITestCluster testCluster, int numberOfInsertsToMake, bool batch)
{
InitPreparedStatement(testCluster, numberOfInsertsToMake, batch, ConsistencyLevel.One);
}
public void InitPreparedStatement(ITestCluster testCluster, int numberOfInsertsToMake, ConsistencyLevel consistencyLevel)
{
InitPreparedStatement(testCluster, numberOfInsertsToMake, false, consistencyLevel);
}
public void InitPreparedStatement(ITestCluster testCluster, int numberOfInsertsToMake, bool batch, ConsistencyLevel consistencyLevel)
{
// We don't use insert for our test because the resultSet don't ship the queriedHost
// Also note that we don't use tracing because this would trigger requests that screw up the test
for (int i = 0; i < numberOfInsertsToMake; ++i)
if (batch)
// BUG: WriteType == SIMPLE
{
var bth = new StringBuilder();
bth.AppendLine("BEGIN BATCH");
bth.AppendLine(string.Format("INSERT INTO {0}(k, i) VALUES (0, 0)", TableName));
bth.AppendLine("APPLY BATCH");
testCluster.Session.Execute(new SimpleStatement(bth.ToString()).SetConsistencyLevel(consistencyLevel));
}
else
{
testCluster.Session.Execute(
new SimpleStatement(string.Format("INSERT INTO {0}(k, i) VALUES (0, 0)", TableName)).SetConsistencyLevel(consistencyLevel));
}
PreparedStatement = testCluster.Session.Prepare("SELECT * FROM " + TableName + " WHERE k = ?").SetConsistencyLevel(consistencyLevel);
}
/// <summary>
/// Query methods that handle reads based on PreparedStatements and/or
/// ConsistencyLevels.
/// </summary>
public void Query(ITestCluster testCluster, int numberOfQueriesToExecute)
{
Query(testCluster, numberOfQueriesToExecute, false, ConsistencyLevel.One);
}
public void Query(ITestCluster testCluster, int numberOfQueriesToExecute, bool usePrepared)
{
Query(testCluster, numberOfQueriesToExecute, usePrepared, ConsistencyLevel.One);
}
public void Query(ITestCluster testCluster, int numberOfQueriesToExecute, ConsistencyLevel consistencyLevel)
{
Query(testCluster, numberOfQueriesToExecute, false, consistencyLevel);
}
public void Query(ITestCluster testCluster, int numberOfQueriesToExecute, bool usePrepared, ConsistencyLevel consistencyLevel)
{
if (usePrepared)
{
BoundStatement bs = PreparedStatement.Bind(0);
for (int i = 0; i < numberOfQueriesToExecute; ++i)
{
ConsistencyLevel cac;
var rs = testCluster.Session.Execute(bs);
{
string queriedHost = rs.Info.QueriedHost.ToString();
cac = rs.Info.AchievedConsistency;
AddCoordinator(queriedHost, cac);
}
}
}
else
{
var routingKey = new RoutingKey();
routingKey.RawRoutingKey = Enumerable.Repeat((byte) 0x00, 4).ToArray();
for (int i = 0; i < numberOfQueriesToExecute; ++i)
{
string hostQueried;
ConsistencyLevel achievedConsistency;
var rs = testCluster.Session.Execute(
new SimpleStatement(string.Format("SELECT * FROM {0} WHERE k = 0", TableName)).SetRoutingKey(routingKey)
.SetConsistencyLevel(consistencyLevel));
{
hostQueried = rs.Info.QueriedHost.ToString();
achievedConsistency = rs.Info.AchievedConsistency;
Trace.TraceInformation("Query {0} executed by {1} with consistency {2}", i, hostQueried, achievedConsistency);
}
AddCoordinator(hostQueried, achievedConsistency);
}
}
}
public void WaitForPolicyToolsQueryToHitBootstrappedIp(ITestCluster testCluster, string newlyBootstrappedIp)
{
int secondsToPoll = 120;
DateTime futureDateTime = DateTime.Now.AddSeconds(120);
Trace.TraceInformation("Polling for " + secondsToPoll + " seconds while we wait for bootstrapped IP to join the ring, be found by the client");
while (!Coordinators.ContainsKey(newlyBootstrappedIp) && DateTime.Now < futureDateTime)
{
try
{
Query(testCluster, 10);
}
catch (Exception e)
{
string[] expectedErrMessages =
{
"Keyspace '" + DefaultKeyspace + "' does not exist",
"unconfigured columnfamily",
"Cassandra timeout during read query at consistency"
};
Assert.IsTrue(e.Message.Contains(expectedErrMessages[0]) || e.Message.Contains(expectedErrMessages[1]) || e.Message.Contains(expectedErrMessages[2]),
"Error message '" + e.Message + "' did not contain one of these acceptable error messages: " + string.Join(",", expectedErrMessages));
Trace.TraceInformation("Caught acceptable one of these acceptable error messages: " + string.Join(",", expectedErrMessages));
}
Thread.Sleep(250);
}
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace XenAPI
{
/// <summary>
/// A group of compatible USBs across the resource pool
/// First published in XenServer 7.3.
/// </summary>
public partial class USB_group : XenObject<USB_group>
{
public USB_group()
{
}
public USB_group(string uuid,
string name_label,
string name_description,
List<XenRef<PUSB>> PUSBs,
List<XenRef<VUSB>> VUSBs,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.PUSBs = PUSBs;
this.VUSBs = VUSBs;
this.other_config = other_config;
}
/// <summary>
/// Creates a new USB_group from a Proxy_USB_group.
/// </summary>
/// <param name="proxy"></param>
public USB_group(Proxy_USB_group proxy)
{
this.UpdateFromProxy(proxy);
}
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given USB_group.
/// </summary>
public override void UpdateFrom(USB_group update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
PUSBs = update.PUSBs;
VUSBs = update.VUSBs;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_USB_group proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
name_label = proxy.name_label == null ? null : (string)proxy.name_label;
name_description = proxy.name_description == null ? null : (string)proxy.name_description;
PUSBs = proxy.PUSBs == null ? null : XenRef<PUSB>.Create(proxy.PUSBs);
VUSBs = proxy.VUSBs == null ? null : XenRef<VUSB>.Create(proxy.VUSBs);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_USB_group ToProxy()
{
Proxy_USB_group result_ = new Proxy_USB_group();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.PUSBs = (PUSBs != null) ? Helper.RefListToStringArray(PUSBs) : new string[] {};
result_.VUSBs = (VUSBs != null) ? Helper.RefListToStringArray(VUSBs) : new string[] {};
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new USB_group from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public USB_group(Hashtable table) : this()
{
UpdateFrom(table);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this USB_group
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("PUSBs"))
PUSBs = Marshalling.ParseSetRef<PUSB>(table, "PUSBs");
if (table.ContainsKey("VUSBs"))
VUSBs = Marshalling.ParseSetRef<VUSB>(table, "VUSBs");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(USB_group other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._PUSBs, other._PUSBs) &&
Helper.AreEqual2(this._VUSBs, other._VUSBs) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
internal static List<USB_group> ProxyArrayToObjectList(Proxy_USB_group[] input)
{
var result = new List<USB_group>();
foreach (var item in input)
result.Add(new USB_group(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, USB_group server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_name_label, server._name_label))
{
USB_group.set_name_label(session, opaqueRef, _name_label);
}
if (!Helper.AreEqual2(_name_description, server._name_description))
{
USB_group.set_name_description(session, opaqueRef, _name_description);
}
if (!Helper.AreEqual2(_other_config, server._other_config))
{
USB_group.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given USB_group.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_usb_group">The opaque_ref of the given usb_group</param>
public static USB_group get_record(Session session, string _usb_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.usb_group_get_record(session.opaque_ref, _usb_group);
else
return new USB_group((Proxy_USB_group)session.proxy.usb_group_get_record(session.opaque_ref, _usb_group ?? "").parse());
}
/// <summary>
/// Get a reference to the USB_group instance with the specified UUID.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<USB_group> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.usb_group_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<USB_group>.Create(session.proxy.usb_group_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get all the USB_group instances with the given label.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<USB_group>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.usb_group_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<USB_group>.Create(session.proxy.usb_group_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given USB_group.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_usb_group">The opaque_ref of the given usb_group</param>
public static string get_uuid(Session session, string _usb_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.usb_group_get_uuid(session.opaque_ref, _usb_group);
else
return (string)session.proxy.usb_group_get_uuid(session.opaque_ref, _usb_group ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given USB_group.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_usb_group">The opaque_ref of the given usb_group</param>
public static string get_name_label(Session session, string _usb_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.usb_group_get_name_label(session.opaque_ref, _usb_group);
else
return (string)session.proxy.usb_group_get_name_label(session.opaque_ref, _usb_group ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given USB_group.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_usb_group">The opaque_ref of the given usb_group</param>
public static string get_name_description(Session session, string _usb_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.usb_group_get_name_description(session.opaque_ref, _usb_group);
else
return (string)session.proxy.usb_group_get_name_description(session.opaque_ref, _usb_group ?? "").parse();
}
/// <summary>
/// Get the PUSBs field of the given USB_group.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_usb_group">The opaque_ref of the given usb_group</param>
public static List<XenRef<PUSB>> get_PUSBs(Session session, string _usb_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.usb_group_get_pusbs(session.opaque_ref, _usb_group);
else
return XenRef<PUSB>.Create(session.proxy.usb_group_get_pusbs(session.opaque_ref, _usb_group ?? "").parse());
}
/// <summary>
/// Get the VUSBs field of the given USB_group.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_usb_group">The opaque_ref of the given usb_group</param>
public static List<XenRef<VUSB>> get_VUSBs(Session session, string _usb_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.usb_group_get_vusbs(session.opaque_ref, _usb_group);
else
return XenRef<VUSB>.Create(session.proxy.usb_group_get_vusbs(session.opaque_ref, _usb_group ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given USB_group.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_usb_group">The opaque_ref of the given usb_group</param>
public static Dictionary<string, string> get_other_config(Session session, string _usb_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.usb_group_get_other_config(session.opaque_ref, _usb_group);
else
return Maps.convert_from_proxy_string_string(session.proxy.usb_group_get_other_config(session.opaque_ref, _usb_group ?? "").parse());
}
/// <summary>
/// Set the name/label field of the given USB_group.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_usb_group">The opaque_ref of the given usb_group</param>
/// <param name="_label">New value to set</param>
public static void set_name_label(Session session, string _usb_group, string _label)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.usb_group_set_name_label(session.opaque_ref, _usb_group, _label);
else
session.proxy.usb_group_set_name_label(session.opaque_ref, _usb_group ?? "", _label ?? "").parse();
}
/// <summary>
/// Set the name/description field of the given USB_group.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_usb_group">The opaque_ref of the given usb_group</param>
/// <param name="_description">New value to set</param>
public static void set_name_description(Session session, string _usb_group, string _description)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.usb_group_set_name_description(session.opaque_ref, _usb_group, _description);
else
session.proxy.usb_group_set_name_description(session.opaque_ref, _usb_group ?? "", _description ?? "").parse();
}
/// <summary>
/// Set the other_config field of the given USB_group.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_usb_group">The opaque_ref of the given usb_group</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _usb_group, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.usb_group_set_other_config(session.opaque_ref, _usb_group, _other_config);
else
session.proxy.usb_group_set_other_config(session.opaque_ref, _usb_group ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given USB_group.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_usb_group">The opaque_ref of the given usb_group</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _usb_group, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.usb_group_add_to_other_config(session.opaque_ref, _usb_group, _key, _value);
else
session.proxy.usb_group_add_to_other_config(session.opaque_ref, _usb_group ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given USB_group. If the key is not in that Map, then do nothing.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_usb_group">The opaque_ref of the given usb_group</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _usb_group, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.usb_group_remove_from_other_config(session.opaque_ref, _usb_group, _key);
else
session.proxy.usb_group_remove_from_other_config(session.opaque_ref, _usb_group ?? "", _key ?? "").parse();
}
/// <summary>
///
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_name_label"></param>
/// <param name="_name_description"></param>
/// <param name="_other_config"></param>
public static XenRef<USB_group> create(Session session, string _name_label, string _name_description, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.usb_group_create(session.opaque_ref, _name_label, _name_description, _other_config);
else
return XenRef<USB_group>.Create(session.proxy.usb_group_create(session.opaque_ref, _name_label ?? "", _name_description ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse());
}
/// <summary>
///
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_name_label"></param>
/// <param name="_name_description"></param>
/// <param name="_other_config"></param>
public static XenRef<Task> async_create(Session session, string _name_label, string _name_description, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_usb_group_create(session.opaque_ref, _name_label, _name_description, _other_config);
else
return XenRef<Task>.Create(session.proxy.async_usb_group_create(session.opaque_ref, _name_label ?? "", _name_description ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse());
}
/// <summary>
///
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_usb_group">The opaque_ref of the given usb_group</param>
public static void destroy(Session session, string _usb_group)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.usb_group_destroy(session.opaque_ref, _usb_group);
else
session.proxy.usb_group_destroy(session.opaque_ref, _usb_group ?? "").parse();
}
/// <summary>
///
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_usb_group">The opaque_ref of the given usb_group</param>
public static XenRef<Task> async_destroy(Session session, string _usb_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_usb_group_destroy(session.opaque_ref, _usb_group);
else
return XenRef<Task>.Create(session.proxy.async_usb_group_destroy(session.opaque_ref, _usb_group ?? "").parse());
}
/// <summary>
/// Return a list of all the USB_groups known to the system.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<USB_group>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.usb_group_get_all(session.opaque_ref);
else
return XenRef<USB_group>.Create(session.proxy.usb_group_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the USB_group Records at once, in a single XML RPC call
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<USB_group>, USB_group> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.usb_group_get_all_records(session.opaque_ref);
else
return XenRef<USB_group>.Create<Proxy_USB_group>(session.proxy.usb_group_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// List of PUSBs in the group
/// </summary>
[JsonConverter(typeof(XenRefListConverter<PUSB>))]
public virtual List<XenRef<PUSB>> PUSBs
{
get { return _PUSBs; }
set
{
if (!Helper.AreEqual(value, _PUSBs))
{
_PUSBs = value;
Changed = true;
NotifyPropertyChanged("PUSBs");
}
}
}
private List<XenRef<PUSB>> _PUSBs = new List<XenRef<PUSB>>() {};
/// <summary>
/// List of VUSBs using the group
/// </summary>
[JsonConverter(typeof(XenRefListConverter<VUSB>))]
public virtual List<XenRef<VUSB>> VUSBs
{
get { return _VUSBs; }
set
{
if (!Helper.AreEqual(value, _VUSBs))
{
_VUSBs = value;
Changed = true;
NotifyPropertyChanged("VUSBs");
}
}
}
private List<XenRef<VUSB>> _VUSBs = new List<XenRef<VUSB>>() {};
/// <summary>
/// Additional configuration
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
}
}
| |
// 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 MaxByte()
{
var test = new SimpleBinaryOpTest__MaxByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MaxByte
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Byte);
private static Byte[] _data1 = new Byte[ElementCount];
private static Byte[] _data2 = new Byte[ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private SimpleBinaryOpTest__DataTable<Byte> _dataTable;
static SimpleBinaryOpTest__MaxByte()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__MaxByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Byte>(_data1, _data2, new Byte[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Max(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Max(
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Max(
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Max), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Max), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Max), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Max(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Sse2.Max(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.Max(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.Max(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__MaxByte();
var result = Sse2.Max(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Max(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Byte> left, Vector128<Byte> right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[ElementCount];
Byte[] inArray2 = new Byte[ElementCount];
Byte[] outArray = new Byte[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[ElementCount];
Byte[] inArray2 = new Byte[ElementCount];
Byte[] outArray = new Byte[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
if (Math.Max(left[0], right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if (Math.Max(left[i], right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Max)}<Byte>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Orleans.CodeGeneration;
using Orleans.Runtime;
using Orleans.Serialization;
using Orleans.Serialization.Invocation;
using Orleans.Transactions;
namespace Orleans
{
/// <summary>
/// The TransactionAttribute attribute is used to mark methods that start and join transactions.
/// </summary>
[InvokableCustomInitializer("SetTransactionOptions")]
[InvokableBaseType(typeof(NewGrainReference), typeof(ValueTask), typeof(TransactionRequest))]
[InvokableBaseType(typeof(NewGrainReference), typeof(ValueTask<>), typeof(TransactionRequest<>))]
[InvokableBaseType(typeof(NewGrainReference), typeof(Task), typeof(TransactionTaskRequest))]
[InvokableBaseType(typeof(NewGrainReference), typeof(Task<>), typeof(TransactionTaskRequest<>))]
[AttributeUsage(AttributeTargets.Method)]
public sealed class TransactionAttribute : Attribute
{
public TransactionAttribute(TransactionOption requirement)
{
Requirement = requirement;
ReadOnly = false;
}
public TransactionAttribute(TransactionOptionAlias alias)
{
Requirement = (TransactionOption)(int)alias;
ReadOnly = false;
}
public TransactionOption Requirement { get; }
public bool ReadOnly { get; set; }
}
public enum TransactionOption
{
Suppress, // Logic is not transactional but can be called from within a transaction. If called within the context of a transaction, the context will not be passed to the call.
CreateOrJoin, // Logic is transactional. If called within the context of a transaction, it will use that context, else it will create a new context.
Create, // Logic is transactional and will always create a new transaction context, even if called within an existing transaction context.
Join, // Logic is transactional but can only be called within the context of an existing transaction.
Supported, // Logic is not transactional but supports transactions. If called within the context of a transaction, the context will be passed to the call.
NotAllowed // Logic is not transactional and cannot be called from within a transaction. If called within the context of a transaction, it will throw a not supported exception.
}
public enum TransactionOptionAlias
{
Suppress = TransactionOption.Supported,
Required = TransactionOption.CreateOrJoin,
RequiresNew = TransactionOption.Create,
Mandatory = TransactionOption.Join,
Never = TransactionOption.NotAllowed,
}
[GenerateSerializer]
public abstract class TransactionRequestBase : RequestBase, IOutgoingGrainCallFilter, IOnDeserialized
{
[NonSerialized]
private Serializer<OrleansTransactionAbortedException> _serializer;
[NonSerialized]
private ITransactionAgent _transactionAgent;
private ITransactionAgent TransactionAgent => _transactionAgent ?? throw new OrleansTransactionsDisabledException();
[Id(1)]
public TransactionOption TransactionOption { get; set; }
[Id(2)]
public TransactionInfo TransactionInfo { get; set; }
[GeneratedActivatorConstructor]
protected TransactionRequestBase(Serializer<OrleansTransactionAbortedException> exceptionSerializer, IServiceProvider serviceProvider)
{
_serializer = exceptionSerializer;
// May be null, eg on an external client. We will throw if it's null at the time of invocation.
_transactionAgent = serviceProvider.GetService<ITransactionAgent>();
}
public bool IsAmbientTransactionSuppressed => TransactionOption switch
{
TransactionOption.Create => true,
TransactionOption.Suppress => true,
_ => false
};
public bool IsTransactionRequired => TransactionOption switch
{
TransactionOption.Create => true,
TransactionOption.CreateOrJoin => true,
TransactionOption.Join => true,
_ => false
};
protected void SetTransactionOptions(TransactionOptionAlias txOption) => SetTransactionOptions((TransactionOption)txOption);
protected void SetTransactionOptions(TransactionOption txOption)
{
this.TransactionOption = txOption;
}
async Task IOutgoingGrainCallFilter.Invoke(IOutgoingGrainCallContext context)
{
var transactionInfo = SetTransactionInfo();
try
{
await context.Invoke();
}
finally
{
var returnedTransactionInfo = (context.Response as TransactionResponse)?.TransactionInfo;
if (transactionInfo is { } && returnedTransactionInfo is { })
{
transactionInfo.Join(returnedTransactionInfo);
}
}
}
private TransactionInfo SetTransactionInfo()
{
// Clear transaction info if transaction operation requires new transaction.
var transactionInfo = TransactionContext.GetTransactionInfo();
// Enforce join transaction calls
if (TransactionOption == TransactionOption.Join && transactionInfo == null)
{
throw new NotSupportedException("Call cannot be made outside of a transaction.");
}
// Enforce not allowed transaction calls
if (TransactionOption == TransactionOption.NotAllowed && transactionInfo != null)
{
throw new NotSupportedException("Call cannot be made within a transaction.");
}
// Clear transaction context if creating a transaction or transaction is suppressed
if (TransactionOption is TransactionOption.Create or TransactionOption.Suppress)
{
transactionInfo = null;
}
if (transactionInfo == null)
{
// if we're leaving a transaction context, make sure it's been cleared from the request context.
TransactionContext.Clear();
}
else
{
this.TransactionInfo = transactionInfo?.Fork();
}
return transactionInfo;
}
public override async ValueTask<Response> Invoke()
{
Response response;
var transactionInfo = this.TransactionInfo;
bool startedNewTransaction = false;
try
{
if (IsTransactionRequired && transactionInfo == null)
{
// TODO: this should be a configurable parameter
var transactionTimeout = Debugger.IsAttached ? TimeSpan.FromMinutes(30) : TimeSpan.FromSeconds(10);
// Start a new transaction
var isReadOnly = (this.Options | InvokeMethodOptions.ReadOnly) == InvokeMethodOptions.ReadOnly;
transactionInfo = await TransactionAgent.StartTransaction(isReadOnly, transactionTimeout);
startedNewTransaction = true;
}
TransactionContext.SetTransactionInfo(transactionInfo);
response = await BaseInvoke();
}
catch (Exception exception)
{
response = Response.FromException(exception);
}
finally
{
TransactionContext.Clear();
}
if (transactionInfo != null)
{
transactionInfo.ReconcilePending();
if (response.Exception is { } invokeException)
{
// Record reason for abort, if not already set.
transactionInfo.RecordException(invokeException, _serializer);
}
OrleansTransactionException transactionException = transactionInfo.MustAbort(_serializer);
// This request started the transaction, so we try to commit before returning,
// or if it must abort, tell participants that it aborted
if (startedNewTransaction)
{
if (transactionException is not null)
{
await TransactionAgent.Abort(transactionInfo);
}
else
{
var (status, exception) = await TransactionAgent.Resolve(transactionInfo);
if (status != TransactionalStatus.Ok)
{
transactionException = status.ConvertToUserException(transactionInfo.Id, exception);
}
}
}
if (transactionException != null)
{
response = Response.FromException(transactionException);
}
response = TransactionResponse.Create(response, transactionInfo);
}
return response;
}
protected abstract ValueTask<Response> BaseInvoke();
public override void Dispose()
{
TransactionInfo = null;
}
void IOnDeserialized.OnDeserialized(DeserializationContext context)
{
_serializer = context.ServiceProvider.GetRequiredService<Serializer<OrleansTransactionAbortedException>>();
_transactionAgent = context.ServiceProvider.GetRequiredService<ITransactionAgent>();
}
}
[GenerateSerializer]
public sealed class TransactionResponse : Response
{
[Id(0)]
private Response _response;
[Id(1)]
public TransactionInfo TransactionInfo { get; set; }
public static TransactionResponse Create(Response response, TransactionInfo transactionInfo)
{
return new TransactionResponse
{
_response = response,
TransactionInfo = transactionInfo
};
}
public override object Result { get => _response.Result; set => _response.Result = value; }
public override Exception Exception { get => _response.Exception; set => _response.Exception = value; }
public override void Dispose()
{
TransactionInfo = null;
_response.Dispose();
}
public override T GetResult<T>() => _response.GetResult<T>();
}
[GenerateSerializer]
public abstract class TransactionRequest : TransactionRequestBase
{
[GeneratedActivatorConstructor]
protected TransactionRequest(Serializer<OrleansTransactionAbortedException> exceptionSerializer, IServiceProvider serviceProvider) : base(exceptionSerializer, serviceProvider)
{
}
protected override ValueTask<Response> BaseInvoke()
{
try
{
var resultTask = InvokeInner();
if (resultTask.IsCompleted)
{
resultTask.GetAwaiter().GetResult();
return new ValueTask<Response>(Response.Completed);
}
return CompleteInvokeAsync(resultTask);
}
catch (Exception exception)
{
return new ValueTask<Response>(Response.FromException(exception));
}
}
private static async ValueTask<Response> CompleteInvokeAsync(ValueTask resultTask)
{
try
{
await resultTask;
return Response.Completed;
}
catch (Exception exception)
{
return Response.FromException(exception);
}
}
// Generated
protected abstract ValueTask InvokeInner();
}
[GenerateSerializer]
public abstract class TransactionRequest<TResult> : TransactionRequestBase
{
[GeneratedActivatorConstructor]
protected TransactionRequest(Serializer<OrleansTransactionAbortedException> exceptionSerializer, IServiceProvider serviceProvider) : base(exceptionSerializer, serviceProvider)
{
}
protected override ValueTask<Response> BaseInvoke()
{
try
{
var resultTask = InvokeInner();
if (resultTask.IsCompleted)
{
return new ValueTask<Response>(Response.FromResult(resultTask.Result));
}
return CompleteInvokeAsync(resultTask);
}
catch (Exception exception)
{
return new ValueTask<Response>(Response.FromException(exception));
}
}
private static async ValueTask<Response> CompleteInvokeAsync(ValueTask<TResult> resultTask)
{
try
{
var result = await resultTask;
return Response.FromResult(result);
}
catch (Exception exception)
{
return Response.FromException(exception);
}
}
// Generated
protected abstract ValueTask<TResult> InvokeInner();
}
[GenerateSerializer]
public abstract class TransactionTaskRequest<TResult> : TransactionRequestBase
{
[GeneratedActivatorConstructor]
protected TransactionTaskRequest(Serializer<OrleansTransactionAbortedException> exceptionSerializer, IServiceProvider serviceProvider) : base(exceptionSerializer, serviceProvider)
{
}
protected override ValueTask<Response> BaseInvoke()
{
try
{
var resultTask = InvokeInner();
var status = resultTask.Status;
if (resultTask.IsCompleted)
{
return new ValueTask<Response>(Response.FromResult(resultTask.GetAwaiter().GetResult()));
}
return CompleteInvokeAsync(resultTask);
}
catch (Exception exception)
{
return new ValueTask<Response>(Response.FromException(exception));
}
}
private static async ValueTask<Response> CompleteInvokeAsync(Task<TResult> resultTask)
{
try
{
var result = await resultTask;
return Response.FromResult(result);
}
catch (Exception exception)
{
return Response.FromException(exception);
}
}
// Generated
protected abstract Task<TResult> InvokeInner();
}
[GenerateSerializer]
public abstract class TransactionTaskRequest : TransactionRequestBase
{
[GeneratedActivatorConstructor]
protected TransactionTaskRequest(Serializer<OrleansTransactionAbortedException> exceptionSerializer, IServiceProvider serviceProvider) : base(exceptionSerializer, serviceProvider)
{
}
protected override ValueTask<Response> BaseInvoke()
{
try
{
var resultTask = InvokeInner();
var status = resultTask.Status;
if (resultTask.IsCompleted)
{
resultTask.GetAwaiter().GetResult();
return new ValueTask<Response>(Response.Completed);
}
return CompleteInvokeAsync(resultTask);
}
catch (Exception exception)
{
return new ValueTask<Response>(Response.FromException(exception));
}
}
private static async ValueTask<Response> CompleteInvokeAsync(Task resultTask)
{
try
{
await resultTask;
return Response.Completed;
}
catch (Exception exception)
{
return Response.FromException(exception);
}
}
// Generated
protected abstract Task InvokeInner();
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FlowSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Akka.Actor;
using Akka.Configuration;
using Akka.Pattern;
using Akka.Streams.Dsl;
using Akka.Streams.Implementation;
using Akka.Streams.Implementation.Fusing;
using Akka.Streams.Stage;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.TestKit;
using Akka.TestKit.Internal;
using Akka.TestKit.TestEvent;
using FluentAssertions;
using Reactive.Streams;
using Xunit;
using Xunit.Abstractions;
// ReSharper disable InvokeAsExtensionMethod
// ReSharper disable UnusedVariable
namespace Akka.Streams.Tests.Dsl
{
public class FlowSpec : AkkaSpec
{
private interface IFruit { };
private sealed class Apple : IFruit { };
private static IEnumerable<Apple> Apples() => Enumerable.Range(1, 1000).Select(_ => new Apple());
private static readonly Config Config = ConfigurationFactory.ParseString(@"
akka.actor.debug.receive=off
akka.loglevel=INFO
");
public ActorMaterializerSettings Settings { get; }
private ActorMaterializer Materializer { get; }
public FlowSpec(ITestOutputHelper helper) : base(Config.WithFallback(ConfigurationFactory.FromResource<ScriptedTest>("Akka.Streams.TestKit.Tests.reference.conf")), helper)
{
Settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(2, 2);
Materializer = ActorMaterializer.Create(Sys, Settings);
}
[Theory]
[InlineData("identity", 1)]
[InlineData("identity", 2)]
[InlineData("identity", 4)]
[InlineData("identity2", 1)]
[InlineData("identity2", 2)]
[InlineData("identity2", 4)]
public void A_flow_must_request_initial_elements_from_upstream(string name, int n)
{
ChainSetup<int, int, NotUsed> setup;
if (name.Equals("identity"))
setup = new ChainSetup<int, int, NotUsed>(Identity, Settings.WithInputBuffer(n, n),
(settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this);
else
setup = new ChainSetup<int, int, NotUsed>(Identity2, Settings.WithInputBuffer(n, n),
(settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this);
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, setup.Settings.MaxInputBufferSize);
}
[Fact]
public void A_Flow_must_request_more_elements_from_upstream_when_downstream_requests_more_elements()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings,
(settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this);
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, Settings.MaxInputBufferSize);
setup.DownstreamSubscription.Request(1);
setup.Upstream.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
setup.DownstreamSubscription.Request(2);
setup.Upstream.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
setup.UpstreamSubscription.SendNext("a");
setup.Downstream.ExpectNext("a");
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
setup.Upstream.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
setup.UpstreamSubscription.SendNext("b");
setup.UpstreamSubscription.SendNext("c");
setup.UpstreamSubscription.SendNext("d");
setup.Downstream.ExpectNext("b");
setup.Downstream.ExpectNext("c");
}
[Fact]
public void A_Flow_must_deliver_events_when_publisher_sends_elements_and_then_completes()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings,
(settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this);
setup.DownstreamSubscription.Request(1);
setup.UpstreamSubscription.SendNext("test");
setup.UpstreamSubscription.SendComplete();
setup.Downstream.ExpectNext("test");
setup.Downstream.ExpectComplete();
}
[Fact]
public void A_Flow_must_deliver_complete_signal_when_publisher_immediately_completes()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings,
(settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this);
setup.UpstreamSubscription.SendComplete();
setup.Downstream.ExpectComplete();
}
[Fact]
public void A_Flow_must_deliver_error_signal_when_publisher_immediately_fails()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings,
(settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this);
var weirdError = new Exception("weird test exception");
setup.UpstreamSubscription.SendError(weirdError);
setup.Downstream.ExpectError().Should().Be(weirdError);
}
[Fact]
public void A_Flow_must_cancel_upstream_when_single_subscriber_cancels_subscription_while_receiving_data()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1),
(settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this);
setup.DownstreamSubscription.Request(5);
setup.UpstreamSubscription.ExpectRequest(1);
setup.UpstreamSubscription.SendNext("test");
setup.UpstreamSubscription.ExpectRequest(1);
setup.UpstreamSubscription.SendNext("test2");
setup.Downstream.ExpectNext("test");
setup.Downstream.ExpectNext("test2");
setup.DownstreamSubscription.Cancel();
// because of the "must cancel its upstream Subscription if its last downstream Subscription has been canceled" rule
setup.UpstreamSubscription.ExpectCancellation();
}
[Fact]
public void A_Flow_must_materialize_into_Publisher_Subscriber()
{
var flow = Flow.Create<string>();
var t = MaterializeIntoSubscriberAndPublisher(flow, Materializer);
var flowIn = t.Item1;
var flowOut = t.Item2;
var c1 = this.CreateManualSubscriberProbe<string>();
flowOut.Subscribe(c1);
var source = Source.From(new[] {"1", "2", "3"}).RunWith(Sink.AsPublisher<string>(false), Materializer);
source.Subscribe(flowIn);
var sub1 = c1.ExpectSubscription();
sub1.Request(3);
c1.ExpectNext("1");
c1.ExpectNext("2");
c1.ExpectNext("3");
c1.ExpectComplete();
}
[Fact]
public void A_Flow_must_materialize_into_Publisher_Subscriber_and_transformation_processor()
{
var flow = Flow.Create<int>().Select(i=>i.ToString());
var t = MaterializeIntoSubscriberAndPublisher(flow, Materializer);
var flowIn = t.Item1;
var flowOut = t.Item2;
var c1 = this.CreateManualSubscriberProbe<string>();
flowOut.Subscribe(c1);
var sub1 = c1.ExpectSubscription();
sub1.Request(3);
c1.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
var source = Source.From(new[] { 1, 2, 3 }).RunWith(Sink.AsPublisher<int>(false), Materializer);
source.Subscribe(flowIn);
c1.ExpectNext("1");
c1.ExpectNext("2");
c1.ExpectNext("3");
c1.ExpectComplete();
}
[Fact]
public void A_Flow_must_materialize_into_Publisher_Subscriber_and_multiple_transformation_processor()
{
var flow = Flow.Create<int>().Select(i => i.ToString()).Select(s => "elem-" + s);
var t = MaterializeIntoSubscriberAndPublisher(flow, Materializer);
var flowIn = t.Item1;
var flowOut = t.Item2;
var c1 = this.CreateManualSubscriberProbe<string>();
flowOut.Subscribe(c1);
var sub1 = c1.ExpectSubscription();
sub1.Request(3);
c1.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
var source = Source.From(new[] { 1, 2, 3 }).RunWith(Sink.AsPublisher<int>(false), Materializer);
source.Subscribe(flowIn);
c1.ExpectNext("elem-1");
c1.ExpectNext("elem-2");
c1.ExpectNext("elem-3");
c1.ExpectComplete();
}
[Fact]
public void A_Flow_must_subscribe_Subscriber()
{
var flow = Flow.Create<string>();
var c1 = this.CreateManualSubscriberProbe<string>();
var sink = flow.To(Sink.FromSubscriber(c1));
var publisher = Source.From(new[] { "1", "2", "3" }).RunWith(Sink.AsPublisher<string>(false), Materializer);
Source.FromPublisher(publisher).To(sink).Run(Materializer);
var sub1 = c1.ExpectSubscription();
sub1.Request(3);
c1.ExpectNext("1");
c1.ExpectNext("2");
c1.ExpectNext("3");
c1.ExpectComplete();
}
[Fact]
public void A_Flow_must_perform_transformation_operation()
{
var flow = Flow.Create<int>().Select(i =>
{
TestActor.Tell(i.ToString());
return i.ToString();
});
var publisher = Source.From(new[] { 1, 2, 3 }).RunWith(Sink.AsPublisher<int>(false), Materializer);
Source.FromPublisher(publisher).Via(flow).To(Sink.Ignore<string>()).Run(Materializer);
ExpectMsg("1");
ExpectMsg("2");
ExpectMsg("3");
}
[Fact]
public void A_Flow_must_perform_transformation_operation_and_subscribe_Subscriber()
{
var flow = Flow.Create<int>().Select(i => i.ToString());
var c1 = this.CreateManualSubscriberProbe<string>();
var sink = flow.To(Sink.FromSubscriber(c1));
var publisher = Source.From(new[] { 1, 2, 3 }).RunWith(Sink.AsPublisher<int>(false), Materializer);
Source.FromPublisher(publisher).To(sink).Run(Materializer);
var sub1 = c1.ExpectSubscription();
sub1.Request(3);
c1.ExpectNext("1");
c1.ExpectNext("2");
c1.ExpectNext("3");
c1.ExpectComplete();
}
[Fact]
public void A_Flow_must_be_materializable_several_times_with_fanout_publisher()
{
this.AssertAllStagesStopped(() =>
{
var flow = Source.From(new[] {1, 2, 3}).Select(i => i.ToString());
var p1 = flow.RunWith(Sink.AsPublisher<string>(true), Materializer);
var p2 = flow.RunWith(Sink.AsPublisher<string>(true), Materializer);
var s1 = this.CreateManualSubscriberProbe<string>();
var s2 = this.CreateManualSubscriberProbe<string>();
var s3 = this.CreateManualSubscriberProbe<string>();
p1.Subscribe(s1);
p2.Subscribe(s2);
p2.Subscribe(s3);
var sub1 = s1.ExpectSubscription();
var sub2 = s2.ExpectSubscription();
var sub3 = s3.ExpectSubscription();
sub1.Request(3);
s1.ExpectNext("1");
s1.ExpectNext("2");
s1.ExpectNext("3");
s1.ExpectComplete();
sub2.Request(3);
sub3.Request(3);
s2.ExpectNext("1");
s2.ExpectNext("2");
s2.ExpectNext("3");
s2.ExpectComplete();
s3.ExpectNext("1");
s3.ExpectNext("2");
s3.ExpectNext("3");
s3.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_Flow_must_be_covariant()
{
Source<IFruit, NotUsed> f1 = Source.From<IFruit>(Apples());
IPublisher<IFruit> p1 = Source.From<IFruit>(Apples()).RunWith(Sink.AsPublisher<IFruit>(false), Materializer);
SubFlow<IFruit, NotUsed, IRunnableGraph<NotUsed>> f2 =
Source.From<IFruit>(Apples()).SplitWhen(_ => true);
SubFlow<IFruit, NotUsed, IRunnableGraph<NotUsed>> f3 =
Source.From<IFruit>(Apples()).GroupBy(2, _ => true);
Source<Tuple<IImmutableList<IFruit>, Source<IFruit, NotUsed>>, NotUsed> f4 =
Source.From<IFruit>(Apples()).PrefixAndTail(1);
SubFlow<IFruit, NotUsed, Sink<string, NotUsed>> d1 =
Flow.Create<string>()
.Select<string, string, IFruit, NotUsed>(_ => new Apple())
.SplitWhen(_ => true);
SubFlow<IFruit, NotUsed, Sink<string, NotUsed>> d2 =
Flow.Create<string>()
.Select<string, string, IFruit, NotUsed>(_ => new Apple())
.GroupBy(-1,_ => 2);
Flow<string, Tuple<IImmutableList<IFruit>, Source<IFruit, NotUsed>>, NotUsed> d3 =
Flow.Create<string>().Select<string, string, IFruit, NotUsed>(_ => new Apple()).PrefixAndTail(1);
}
[Fact]
public void A_Flow_must_be_possible_to_convert_to_a_processor_and_should_be_able_to_take_a_Processor()
{
var identity1 = Flow.Create<int>().ToProcessor();
var identity2 = Flow.FromProcessor(() => identity1.Run(Materializer));
var task = Source.From(Enumerable.Range(1, 10))
.Via(identity2)
.Limit(100)
.RunWith(Sink.Seq<int>(), Materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1,10));
// Reusable:
task = Source.From(Enumerable.Range(1, 10))
.Via(identity2)
.Limit(100)
.RunWith(Sink.Seq<int>(), Materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 10));
}
[Fact]
public void A_Flow_with_multiple_subscribers_FanOutBox_must_adapt_speed_to_the_currently_slowest_subscriber()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1),
(settings, factory) => ActorMaterializer.Create(factory, settings),
(source, materializer) => ToFanoutPublisher(source, materializer, 1), this);
var downstream2 = this.CreateManualSubscriberProbe<string>();
setup.Publisher.Subscribe(downstream2);
var downstream2Subscription = downstream2.ExpectSubscription();
setup.DownstreamSubscription.Request(5);
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); // because initialInputBufferSize=1
setup.UpstreamSubscription.SendNext("firstElement");
setup.Downstream.ExpectNext("firstElement");
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
setup.UpstreamSubscription.SendNext("element2");
setup.Downstream.ExpectNoMsg(TimeSpan.FromSeconds(1));
downstream2Subscription.Request(1);
downstream2.ExpectNext("firstElement");
setup.Downstream.ExpectNext("element2");
downstream2Subscription.Request(1);
downstream2.ExpectNext("element2");
}
[Fact]
public void A_Flow_with_multiple_subscribers_FanOutBox_must_support_slow_subscriber_with_fan_out_2()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1),
(settings, factory) => ActorMaterializer.Create(factory, settings),
(source, materializer) => ToFanoutPublisher(source, materializer, 2), this);
var downstream2 = this.CreateManualSubscriberProbe<string>();
setup.Publisher.Subscribe(downstream2);
var downstream2Subscription = downstream2.ExpectSubscription();
setup.DownstreamSubscription.Request(5);
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); // because initialInputBufferSize=1
setup.UpstreamSubscription.SendNext("element1");
setup.Downstream.ExpectNext("element1");
setup.UpstreamSubscription.ExpectRequest(1);
setup.UpstreamSubscription.SendNext("element2");
setup.Downstream.ExpectNext("element2");
setup.UpstreamSubscription.ExpectRequest(1);
setup.UpstreamSubscription.SendNext("element3");
// downstream2 has not requested anything, fan-out buffer 2
setup.Downstream.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(100)));
downstream2Subscription.Request(2);
setup.Downstream.ExpectNext("element3");
downstream2.ExpectNext("element1");
downstream2.ExpectNext("element2");
downstream2.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(100)));
setup.UpstreamSubscription.Request(1);
setup.UpstreamSubscription.SendNext("element4");
setup.Downstream.ExpectNext("element4");
downstream2Subscription.Request(2);
downstream2.ExpectNext("element3");
downstream2.ExpectNext("element4");
setup.UpstreamSubscription.SendComplete();
setup.Downstream.ExpectComplete();
downstream2.ExpectComplete();
}
[Fact]
public void A_Flow_with_multiple_subscribers_FanOutBox_must_support_incoming_subscriber_while_elements_were_requested_before()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1),
(settings, factory) => ActorMaterializer.Create(factory, settings),
(source, materializer) => ToFanoutPublisher(source, materializer, 1), this);
setup.DownstreamSubscription.Request(5);
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
setup.UpstreamSubscription.SendNext("a1");
setup.Downstream.ExpectNext("a1");
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
setup.UpstreamSubscription.SendNext("a2");
setup.Downstream.ExpectNext("a2");
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
// link now while an upstream element is already requested
var downstream2 = this.CreateManualSubscriberProbe<string>();
setup.Publisher.Subscribe(downstream2);
var downstream2Subscription = downstream2.ExpectSubscription();
// situation here:
// downstream 1 now has 3 outstanding
// downstream 2 has 0 outstanding
setup.UpstreamSubscription.SendNext("a3");
setup.Downstream.ExpectNext("a3");
downstream2.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(100))); // as nothing was requested yet, fanOutBox needs to cache element in this case
downstream2Subscription.Request(1);
downstream2.ExpectNext("a3");
// d1 now has 2 outstanding
// d2 now has 0 outstanding
// buffer should be empty so we should be requesting one new element
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); // because of buffer size 1
}
[Fact]
public void A_Flow_with_multiple_subscribers_FanOutBox_must_be_unblocked_when_blocking_subscriber_cancels_subscription()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1),
(settings, factory) => ActorMaterializer.Create(factory, settings),
(source, materializer) => ToFanoutPublisher(source, materializer, 1), this);
var downstream2 = this.CreateManualSubscriberProbe<string>();
setup.Publisher.Subscribe(downstream2);
var downstream2Subscription = downstream2.ExpectSubscription();
setup.DownstreamSubscription.Request(5);
setup.UpstreamSubscription.ExpectRequest(1);
setup.UpstreamSubscription.SendNext("firstElement");
setup.Downstream.ExpectNext("firstElement");
downstream2Subscription.Request(1);
downstream2.ExpectNext("firstElement");
setup.UpstreamSubscription.ExpectRequest(1);
setup.UpstreamSubscription.SendNext("element2");
setup.Downstream.ExpectNext("element2");
setup.UpstreamSubscription.ExpectRequest(1);
setup.UpstreamSubscription.SendNext("element3");
setup.UpstreamSubscription.ExpectRequest(1);
setup.Downstream.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(200)));
setup.Upstream.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(200)));
downstream2.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(200)));
// should unblock fanoutbox
downstream2Subscription.Cancel();
setup.Downstream.ExpectNext("element3");
setup.UpstreamSubscription.SendNext("element4");
setup.Downstream.ExpectNext("element4");
setup.UpstreamSubscription.SendComplete();
setup.Downstream.ExpectComplete();
}
[Fact]
public void A_Flow_with_multiple_subscribers_FanOutBox_must_call_future_subscribers_OnError_after_OnSubscribe_if_initial_upstream_was_completed()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1),
(settings, factory) => ActorMaterializer.Create(factory, settings),
(source, materializer) => ToFanoutPublisher(source, materializer, 1), this);
var downstream2 = this.CreateManualSubscriberProbe<string>();
// don't link it just yet
setup.DownstreamSubscription.Request(5);
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
setup.UpstreamSubscription.SendNext("a1");
setup.Downstream.ExpectNext("a1");
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
setup.UpstreamSubscription.SendNext("a2");
setup.Downstream.ExpectNext("a2");
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
// link now while an upstream element is already requested
setup.Publisher.Subscribe(downstream2);
var downstream2Subscription = downstream2.ExpectSubscription();
setup.UpstreamSubscription.SendNext("a3");
setup.UpstreamSubscription.SendComplete();
setup.Downstream.ExpectNext("a3");
setup.Downstream.ExpectComplete();
downstream2.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(100))); // as nothing was requested yet, fanOutBox needs to cache element in this case
downstream2Subscription.Request(1);
downstream2.ExpectNext("a3");
downstream2.ExpectComplete();
var downstream3 = this.CreateManualSubscriberProbe<string>();
setup.Publisher.Subscribe(downstream3);
downstream3.ExpectSubscription();
downstream3.ExpectError().Should().BeOfType<NormalShutdownException>();
}
[Fact]
public void A_Flow_with_multiple_subscribers_FanOutBox_must_call_future_subscribers_OnError_should_be_called_instead_of_OnSubscribed_after_initial_upstream_reported_an_error()
{
var setup = new ChainSetup<int, string, NotUsed>(flow => flow.Select<int,int,string,NotUsed>(_ =>
{
throw new TestException("test");
}), Settings.WithInputBuffer(1, 1),
(settings, factory) => ActorMaterializer.Create(factory, settings),
(source, materializer) => ToFanoutPublisher(source, materializer, 1), this);
setup.DownstreamSubscription.Request(1);
setup.UpstreamSubscription.ExpectRequest(1);
setup.UpstreamSubscription.SendNext(5);
setup.UpstreamSubscription.ExpectRequest(1);
setup.UpstreamSubscription.ExpectCancellation();
setup.Downstream.ExpectError().Should().BeOfType<TestException>();
var downstream2 = this.CreateManualSubscriberProbe<string>();
setup.Publisher.Subscribe(downstream2);
downstream2.ExpectSubscriptionAndError().Should().BeOfType<TestException>();
}
[Fact]
public void A_Flow_with_multiple_subscribers_FanOutBox_must_call_future_subscribers_OnError_when_all_subscriptions_were_cancelled ()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1),
(settings, factory) => ActorMaterializer.Create(factory, settings),
(source, materializer) => ToFanoutPublisher(source, materializer, 16), this);
// make sure stream is initialized before canceling downstream
Thread.Sleep(100);
setup.UpstreamSubscription.ExpectRequest(1);
setup.DownstreamSubscription.Cancel();
setup.UpstreamSubscription.ExpectCancellation();
var downstream2 = this.CreateManualSubscriberProbe<string>();
setup.Publisher.Subscribe(downstream2);
// IllegalStateException shut down
downstream2.ExpectSubscriptionAndError().Should().BeAssignableTo<IllegalStateException>();
}
[Fact]
public void A_Flow_with_multiple_subscribers_FanOutBox_should_be_created_from_a_function_easily()
{
Source.From(Enumerable.Range(0, 10))
.Via(Flow.FromFunction<int, int>(i => i + 1))
.RunWith(Sink.Seq<int>(), Materializer)
.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 10));
}
[Fact]
public void A_broken_Flow_must_cancel_upstream_and_call_onError_on_current_and_future_downstream_subscribers_if_an_internal_error_occurs()
{
var setup = new ChainSetup<string, string, NotUsed>(FaultyFlow<string,string,string>, Settings.WithInputBuffer(1, 1),
(settings, factory) => ActorMaterializer.Create(factory, settings),
(source, materializer) => ToFanoutPublisher(source, materializer, 16), this);
Action<TestSubscriber.ManualProbe<string>> checkError = sprobe =>
{
var error = sprobe.ExpectError();
error.Should().BeOfType<AbruptTerminationException>();
error.Message.Should().StartWith("Processor actor");
};
var downstream2 = this.CreateManualSubscriberProbe<string>();
setup.Publisher.Subscribe(downstream2);
var downstream2Subscription = downstream2.ExpectSubscription();
setup.DownstreamSubscription.Request(5);
downstream2Subscription.Request(5);
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
setup.UpstreamSubscription.SendNext("a1");
setup.Downstream.ExpectNext("a1");
downstream2.ExpectNext("a1");
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
setup.UpstreamSubscription.SendNext("a2");
setup.Downstream.ExpectNext("a2");
downstream2.ExpectNext("a2");
var filters = new EventFilterBase[]
{
new ErrorFilter(typeof(NullReferenceException)),
new ErrorFilter(typeof(IllegalStateException)),
new ErrorFilter(typeof(PostRestartException)),// This is thrown because we attach the dummy failing actor to toplevel
};
try
{
Sys.EventStream.Publish(new Mute(filters));
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
setup.UpstreamSubscription.SendNext("a3");
setup.UpstreamSubscription.ExpectCancellation();
// IllegalStateException terminated abruptly
checkError(setup.Downstream);
checkError(downstream2);
var downstream3 = this.CreateManualSubscriberProbe<string>();
setup.Publisher.Subscribe(downstream3);
downstream3.ExpectSubscription();
// IllegalStateException terminated abruptly
checkError(downstream3);
}
finally
{
Sys.EventStream.Publish(new Unmute(filters));
}
}
[Fact]
public void A_broken_Flow_must_suitably_override_attribute_hanling_methods()
{
var f = Flow.Create<int>().Select(x => x + 1).Async().AddAttributes(Attributes.None).Named("name");
f.Module.Attributes.GetFirstAttribute<Attributes.Name>().Value.Should().Be("name");
f.Module.Attributes.GetFirstAttribute<Attributes.AsyncBoundary>()
.Should()
.Be(Attributes.AsyncBoundary.Instance);
}
private static Flow<TIn, TOut, TMat> Identity<TIn, TOut, TMat>(Flow<TIn, TOut, TMat> flow) => flow.Select(e => e);
private static Flow<TIn, TOut, TMat> Identity2<TIn, TOut, TMat>(Flow<TIn, TOut, TMat> flow) => Identity(flow);
private sealed class BrokenActorInterpreter : ActorGraphInterpreter
{
private readonly object _brokenMessage;
public BrokenActorInterpreter(GraphInterpreterShell shell, object brokenMessage) : base(shell)
{
_brokenMessage = brokenMessage;
}
protected override bool AroundReceive(Receive receive, object message)
{
var next = message as OnNext?;
if (next.HasValue && next.Value.Id == 0 && next.Value.Event == _brokenMessage)
throw new NullReferenceException($"I'm so broken {next.Value.Event}");
return base.AroundReceive(receive, message);
}
}
private Flow<TIn, TOut2, NotUsed> FaultyFlow<TIn, TOut, TOut2>(Flow<TIn, TOut, NotUsed> flow) where TOut : TOut2
{
Func<Flow<TOut, TOut2, NotUsed>> createGraph = () =>
{
var stage = new Select<TOut, TOut2>(x => x);
var assembly = new GraphAssembly(new IGraphStageWithMaterializedValue<Shape, object>[] { stage }, new[] { Attributes.None },
new Inlet[] { stage.Shape.Inlet , null}, new[] { 0, -1 }, new Outlet[] { null, stage.Shape.Outlet }, new[] { -1, 0 });
var t = assembly.Materialize(Attributes.None, assembly.Stages.Select(s => s.Module).ToArray(),
new Dictionary<IModule, object>(), _ => { });
var connections = t.Item1;
var logics = t.Item2;
var shell = new GraphInterpreterShell(assembly, connections, logics, stage.Shape, Settings,
(ActorMaterializerImpl) Materializer);
var props =
Props.Create(() => new BrokenActorInterpreter(shell, "a3"))
.WithDeploy(Deploy.Local)
.WithDispatcher("akka.test.stream-dispatcher");
var impl = Sys.ActorOf(props, "broken-stage-actor");
var subscriber = new ActorGraphInterpreter.BoundarySubscriber<TOut>(impl, shell, 0);
var publisher = new FaultyFlowPublisher<TOut2>(impl, shell);
impl.Tell(new ActorGraphInterpreter.ExposedPublisher(shell, 0, publisher));
return Flow.FromSinkAndSource(Sink.FromSubscriber(subscriber),
Source.FromPublisher(publisher));
};
return flow.Via(createGraph());
}
private sealed class FaultyFlowPublisher<TOut> : ActorPublisher<TOut>
{
public FaultyFlowPublisher(IActorRef impl, GraphInterpreterShell shell) : base(impl)
{
WakeUpMessage = new ActorGraphInterpreter.SubscribePending(shell, 0);
}
protected override object WakeUpMessage { get; }
}
private static IPublisher<TOut> ToPublisher<TOut, TMat>(Source<TOut, TMat> source,
ActorMaterializer materializer) => source.RunWith(Sink.AsPublisher<TOut>(false), materializer);
private static IPublisher<TOut> ToFanoutPublisher<TOut, TMat>(Source<TOut, TMat> source,
ActorMaterializer materializer, int elasticity)
=>
source.RunWith(
Sink.AsPublisher<TOut>(true).WithAttributes(Attributes.CreateInputBuffer(elasticity, elasticity)),
materializer);
private static Tuple<ISubscriber<TIn>, IPublisher<TOut>> MaterializeIntoSubscriberAndPublisher<TIn, TOut, TMat>(
Flow<TIn, TOut, TMat> flow, ActorMaterializer materializer)
=> flow.RunWith(Source.AsSubscriber<TIn>(), Sink.AsPublisher<TOut>(false), materializer);
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Threading;
namespace Microsoft.DotNet.CoreSetup.Test
{
/// <summary>
/// Helper class for creating, modifying and cleaning up shared frameworks
/// </summary>
internal static class SharedFramework
{
private static readonly Mutex id_mutex = new Mutex();
// MultilevelDirectory is %TEST_ARTIFACTS%\dotnetMultilevelSharedFxLookup\id.
// We must locate the first non existing id.
public static string CalculateUniqueTestDirectory(string baseDir)
{
id_mutex.WaitOne();
int count = 0;
string dir;
do
{
dir = Path.Combine(baseDir, count.ToString());
count++;
} while (Directory.Exists(dir));
id_mutex.ReleaseMutex();
return dir;
}
// This method adds a list of new framework version folders in the specified
// sharedFxBaseDir. The files are copied from the _buildSharedFxDir.
// Remarks:
// - If the sharedFxBaseDir does not exist, then a DirectoryNotFoundException
// is thrown.
// - If a specified version folder already exists, then it is deleted and replaced
// with the contents of the _builtSharedFxDir.
public static void AddAvailableSharedFxVersions(string sharedFxDir, string sharedFxBaseDir, params string[] availableVersions)
{
DirectoryInfo sharedFxBaseDirInfo = new DirectoryInfo(sharedFxBaseDir);
if (!sharedFxBaseDirInfo.Exists)
{
throw new DirectoryNotFoundException();
}
foreach (string version in availableVersions)
{
string newSharedFxDir = Path.Combine(sharedFxBaseDir, version);
CopyDirectory(sharedFxDir, newSharedFxDir);
}
}
// This method adds a list of new framework version folders in the specified
// sharedFxUberBaseDir. A runtimeconfig file is created that references
// Microsoft.NETCore.App version=sharedFxBaseVersion
public static void AddAvailableSharedUberFxVersions(string sharedFxDir, string sharedUberFxBaseDir, string sharedFxBaseVersion, string testConfigPropertyValue = null, params string[] availableUberVersions)
{
DirectoryInfo sharedFxUberBaseDirInfo = new DirectoryInfo(sharedUberFxBaseDir);
if (!sharedFxUberBaseDirInfo.Exists)
{
sharedFxUberBaseDirInfo.Create();
}
foreach (string version in availableUberVersions)
{
string newSharedFxDir = Path.Combine(sharedUberFxBaseDir, version);
CopyDirectory(sharedFxDir, newSharedFxDir);
string runtimeBaseConfig = Path.Combine(newSharedFxDir, "Microsoft.UberFramework.runtimeconfig.json");
SharedFramework.SetRuntimeConfigJson(runtimeBaseConfig, sharedFxBaseVersion, null, testConfigPropertyValue);
}
}
// Generated json file:
/*
* {
* "runtimeOptions": {
* "framework": {
* "name": "Microsoft.NETCore.App",
* "version": {version}
* },
* "rollForwardOnNoCandidateFx": {rollFwdOnNoCandidateFx} <-- only if rollFwdOnNoCandidateFx is defined
* }
* }
*/
public static void SetRuntimeConfigJson(string destFile, string version, int? rollFwdOnNoCandidateFx = null, string testConfigPropertyValue = null, bool? useUberFramework = false, JArray additionalFrameworks = null)
{
string name = useUberFramework.HasValue && useUberFramework.Value ? "Microsoft.UberFramework" : "Microsoft.NETCore.App";
JObject runtimeOptions = new JObject(
new JProperty("framework",
new JObject(
new JProperty("name", name),
new JProperty("version", version)
)
)
);
if (rollFwdOnNoCandidateFx.HasValue)
{
runtimeOptions.Add("rollForwardOnNoCandidateFx", rollFwdOnNoCandidateFx);
}
if (testConfigPropertyValue != null)
{
runtimeOptions.Add(
new JProperty("configProperties",
new JObject(
new JProperty("TestProperty", testConfigPropertyValue)
)
)
);
}
if (additionalFrameworks != null)
{
runtimeOptions.Add("additionalFrameworks", additionalFrameworks);
}
FileInfo file = new FileInfo(destFile);
if (!file.Directory.Exists)
{
file.Directory.Create();
}
JObject json = new JObject();
json.Add("runtimeOptions", runtimeOptions);
File.WriteAllText(destFile, json.ToString());
}
// CopyDirectory recursively copies a directory
// Remarks:
// - If the dest dir does not exist, then it is created.
// - If the dest dir exists, then it is substituted with the new one
// (original files and subfolders are deleted).
// - If the src dir does not exist, then a DirectoryNotFoundException
// is thrown.
public static void CopyDirectory(string srcDir, string dstDir)
{
DirectoryInfo srcDirInfo = new DirectoryInfo(srcDir);
if (!srcDirInfo.Exists)
{
throw new DirectoryNotFoundException();
}
DirectoryInfo dstDirInfo = new DirectoryInfo(dstDir);
if (dstDirInfo.Exists)
{
dstDirInfo.Delete(true);
}
dstDirInfo.Create();
foreach (FileInfo fileInfo in srcDirInfo.GetFiles())
{
string newFile = Path.Combine(dstDir, fileInfo.Name);
fileInfo.CopyTo(newFile);
}
foreach (DirectoryInfo subdirInfo in srcDirInfo.GetDirectories())
{
string newDir = Path.Combine(dstDir, subdirInfo.Name);
CopyDirectory(subdirInfo.FullName, newDir);
}
}
public static void CreateUberFrameworkArtifacts(string builtSharedFxDir, string builtSharedUberFxDir, string assemblyVersion = null, string fileVersion = null)
{
DirectoryInfo dir = new DirectoryInfo(builtSharedUberFxDir);
if (dir.Exists)
{
dir.Delete(true);
}
dir.Create();
JObject versionInfo = new JObject();
if (assemblyVersion != null)
{
versionInfo.Add(new JProperty("assemblyVersion", assemblyVersion));
}
if (fileVersion != null)
{
versionInfo.Add(new JProperty("fileVersion", fileVersion));
}
JObject depsjson = CreateDepsJson("UberFx", "System.Collections.Immutable/1.0.0", "System.Collections.Immutable", versionInfo);
string depsFile = Path.Combine(builtSharedUberFxDir, "Microsoft.UberFramework.deps.json");
File.WriteAllText(depsFile, depsjson.ToString());
// Copy the test assembly
string fileSource = Path.Combine(builtSharedFxDir, "System.Collections.Immutable.dll");
string fileDest = Path.Combine(builtSharedUberFxDir, "System.Collections.Immutable.dll");
File.Copy(fileSource, fileDest);
}
public static JObject CreateDepsJson(string fxName, string testPackage, string testAssembly, JObject versionInfo = null)
{
// Create the deps.json. Generated file (example)
/*
{
"runtimeTarget": {
"name": "UberFx"
},
"targets": {
"UberFx": {
"System.Collections.Immutable/1.0.0": {
"dependencies": {}
"runtime": {
"System.Collections.Immutable.dll": {}
}
}
}
},
"libraries": {
"System.Collections.Immutable/1.0.0": {
"type": "assemblyreference",
"serviceable": false,
"sha512": ""
}
}
}
*/
if (versionInfo == null)
{
versionInfo = new JObject();
}
JObject depsjson = new JObject(
new JProperty("runtimeTarget",
new JObject(
new JProperty("name", fxName)
)
),
new JProperty("targets",
new JObject(
new JProperty(fxName,
new JObject(
new JProperty(testPackage,
new JObject(
new JProperty("dependencies",
new JObject()
),
new JProperty("runtime",
new JObject(
new JProperty(testAssembly + ".dll",
versionInfo
)
)
)
)
)
)
)
)
),
new JProperty("libraries",
new JObject(
new JProperty(testPackage,
new JObject(
new JProperty("type", "assemblyreference"),
new JProperty("serviceable", false),
new JProperty("sha512", "")
)
)
)
)
);
return depsjson;
}
public static void AddReferenceToDepsJson(string jsonFile, string fxNamewWithVersion, string testPackage, string testPackageVersion, JObject testAssemblyVersionInfo = null)
{
JObject depsjson = JObject.Parse(File.ReadAllText(jsonFile));
string testPackageWithVersion = testPackage + "/" + testPackageVersion;
string testAssembly = testPackage + ".dll";
JProperty targetsProperty = (JProperty)depsjson["targets"].First;
JObject targetsValue = (JObject)targetsProperty.Value;
var assembly = new JProperty(testPackage, testPackageVersion);
JObject packageDependencies = (JObject)targetsValue[fxNamewWithVersion]["dependencies"];
packageDependencies.Add(assembly);
if (testAssemblyVersionInfo == null)
{
testAssemblyVersionInfo = new JObject();
}
var package = new JProperty(testPackageWithVersion,
new JObject(
new JProperty("runtime",
new JObject(
new JProperty(testAssembly,
new JObject(
testAssemblyVersionInfo
)
)
)
)
)
);
targetsValue.Add(package);
var library = new JProperty(testPackageWithVersion,
new JObject(
new JProperty("type", "assemblyreference"),
new JProperty("serviceable", false),
new JProperty("sha512", "")
)
);
JObject libraries = (JObject)depsjson["libraries"];
libraries.Add(library);
File.WriteAllText(jsonFile, depsjson.ToString());
}
}
}
| |
// 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.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Venus;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using MSXML;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
{
internal abstract class AbstractSnippetExpansionClient : ForegroundThreadAffinitizedObject, IVsExpansionClient
{
protected readonly IVsEditorAdaptersFactoryService EditorAdaptersFactoryService;
protected readonly Guid LanguageServiceGuid;
protected readonly ITextView TextView;
protected readonly ITextBuffer SubjectBuffer;
protected bool indentCaretOnCommit;
protected int indentDepth;
protected bool earlyEndExpansionHappened;
internal IVsExpansionSession ExpansionSession;
public AbstractSnippetExpansionClient(Guid languageServiceGuid, ITextView textView, ITextBuffer subjectBuffer, IVsEditorAdaptersFactoryService editorAdaptersFactoryService)
{
this.LanguageServiceGuid = languageServiceGuid;
this.TextView = textView;
this.SubjectBuffer = subjectBuffer;
this.EditorAdaptersFactoryService = editorAdaptersFactoryService;
}
public abstract int GetExpansionFunction(IXMLDOMNode xmlFunctionNode, string bstrFieldName, out IVsExpansionFunction pFunc);
protected abstract ITrackingSpan InsertEmptyCommentAndGetEndPositionTrackingSpan();
internal abstract Document AddImports(Document document, XElement snippetNode, bool placeSystemNamespaceFirst, CancellationToken cancellationToken);
public int FormatSpan(IVsTextLines pBuffer, VsTextSpan[] tsInSurfaceBuffer)
{
// Formatting a snippet isn't cancellable.
var cancellationToken = CancellationToken.None;
// At this point, the $selection$ token has been replaced with the selected text and
// declarations have been replaced with their default text. We need to format the
// inserted snippet text while carefully handling $end$ position (where the caret goes
// after Return is pressed). The IVsExpansionSession keeps a tracking point for this
// position but we do the tracking ourselves to properly deal with virtual space. To
// ensure the end location is correct, we take three extra steps:
// 1. Insert an empty comment ("/**/" or "'") at the current $end$ position (prior
// to formatting), and keep a tracking span for the comment.
// 2. After formatting the new snippet text, find and delete the empty multiline
// comment (via the tracking span) and notify the IVsExpansionSession of the new
// $end$ location. If the line then contains only whitespace (due to the formatter
// putting the empty comment on its own line), then delete the white space and
// remember the indentation depth for that line.
// 3. When the snippet is finally completed (via Return), and PositionCaretForEditing()
// is called, check to see if the end location was on a line containing only white
// space in the previous step. If so, and if that line is still empty, then position
// the caret in virtual space.
// This technique ensures that a snippet like "if($condition$) { $end$ }" will end up
// as:
// if ($condition$)
// {
// $end$
// }
SnapshotSpan snippetSpan;
if (!TryGetSubjectBufferSpan(tsInSurfaceBuffer[0], out snippetSpan))
{
return VSConstants.S_OK;
}
// Insert empty comment and track end position
var snippetTrackingSpan = snippetSpan.CreateTrackingSpan(SpanTrackingMode.EdgeInclusive);
var fullSnippetSpan = new VsTextSpan[1];
ExpansionSession.GetSnippetSpan(fullSnippetSpan);
var isFullSnippetFormat =
fullSnippetSpan[0].iStartLine == tsInSurfaceBuffer[0].iStartLine &&
fullSnippetSpan[0].iStartIndex == tsInSurfaceBuffer[0].iStartIndex &&
fullSnippetSpan[0].iEndLine == tsInSurfaceBuffer[0].iEndLine &&
fullSnippetSpan[0].iEndIndex == tsInSurfaceBuffer[0].iEndIndex;
var endPositionTrackingSpan = isFullSnippetFormat ? InsertEmptyCommentAndGetEndPositionTrackingSpan() : null;
var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(SubjectBuffer.CurrentSnapshot, snippetTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot));
SubjectBuffer.CurrentSnapshot.FormatAndApplyToBuffer(formattingSpan, CancellationToken.None);
if (isFullSnippetFormat)
{
CleanUpEndLocation(endPositionTrackingSpan);
// Unfortunately, this is the only place we can safely add references and imports
// specified in the snippet xml. In OnBeforeInsertion we have no guarantee that the
// snippet xml will be available, and changing the buffer during OnAfterInsertion can
// cause the underlying tracking spans to get out of sync.
AddReferencesAndImports(ExpansionSession, cancellationToken);
SetNewEndPosition(endPositionTrackingSpan);
}
return VSConstants.S_OK;
}
private void SetNewEndPosition(ITrackingSpan endTrackingSpan)
{
if (SetEndPositionIfNoneSpecified(ExpansionSession))
{
return;
}
if (endTrackingSpan != null)
{
SnapshotSpan endSpanInSurfaceBuffer;
if (!TryGetSpanOnHigherBuffer(
endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot),
TextView.TextBuffer,
out endSpanInSurfaceBuffer))
{
return;
}
int endLine, endColumn;
TextView.TextSnapshot.GetLineAndColumn(endSpanInSurfaceBuffer.Start.Position, out endLine, out endColumn);
ExpansionSession.SetEndSpan(new VsTextSpan
{
iStartLine = endLine,
iStartIndex = endColumn,
iEndLine = endLine,
iEndIndex = endColumn
});
}
}
private void CleanUpEndLocation(ITrackingSpan endTrackingSpan)
{
if (endTrackingSpan != null)
{
// Find the empty comment and remove it...
var endSnapshotSpan = endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot);
SubjectBuffer.Delete(endSnapshotSpan.Span);
// Remove the whitespace before the comment if necessary. If whitespace is removed,
// then remember the indentation depth so we can appropriately position the caret
// in virtual space when the session is ended.
var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(endSnapshotSpan.Start.Position);
var lineText = line.GetText();
if (lineText.Trim() == string.Empty)
{
indentCaretOnCommit = true;
var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
var optionService = document.Project.Solution.Workspace.Services.GetService<IOptionService>();
var tabSize = optionService.GetOption(FormattingOptions.TabSize, document.Project.Language);
indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize);
}
else
{
// If we don't have a document, then just guess the typical default TabSize value.
indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize: 4);
}
SubjectBuffer.Delete(new Span(line.Start.Position, line.Length));
endSnapshotSpan = SubjectBuffer.CurrentSnapshot.GetSpan(new Span(line.Start.Position, 0));
}
}
}
/// <summary>
/// If there was no $end$ token, place it at the end of the snippet code. Otherwise, it
/// defaults to the beginning of the snippet code.
/// </summary>
private static bool SetEndPositionIfNoneSpecified(IVsExpansionSession pSession)
{
XElement snippetNode;
if (!TryGetSnippetNode(pSession, out snippetNode))
{
return false;
}
var ns = snippetNode.Name.NamespaceName;
var codeNode = snippetNode.Element(XName.Get("Code", ns));
if (codeNode == null)
{
return false;
}
var delimiterAttribute = codeNode.Attribute("Delimiter");
var delimiter = delimiterAttribute != null ? delimiterAttribute.Value : "$";
if (codeNode.Value.IndexOf(string.Format("{0}end{0}", delimiter), StringComparison.OrdinalIgnoreCase) != -1)
{
return false;
}
var snippetSpan = new VsTextSpan[1];
if (pSession.GetSnippetSpan(snippetSpan) != VSConstants.S_OK)
{
return false;
}
var newEndSpan = new VsTextSpan
{
iStartLine = snippetSpan[0].iEndLine,
iStartIndex = snippetSpan[0].iEndIndex,
iEndLine = snippetSpan[0].iEndLine,
iEndIndex = snippetSpan[0].iEndIndex
};
pSession.SetEndSpan(newEndSpan);
return true;
}
protected static bool TryGetSnippetNode(IVsExpansionSession pSession, out XElement snippetNode)
{
IXMLDOMNode xmlNode = null;
snippetNode = null;
try
{
// Cast to our own version of IVsExpansionSession so that we can get pNode as an
// IntPtr instead of a via a RCW. This allows us to guarantee that it pNode is
// released before leaving this method. Otherwise, a second invocation of the same
// snippet may cause an AccessViolationException.
var session = (IVsExpansionSessionInternal)pSession;
IntPtr pNode;
if (session.GetSnippetNode(null, out pNode) != VSConstants.S_OK)
{
return false;
}
xmlNode = (IXMLDOMNode)Marshal.GetUniqueObjectForIUnknown(pNode);
snippetNode = XElement.Parse(xmlNode.xml);
return true;
}
finally
{
if (xmlNode != null && Marshal.IsComObject(xmlNode))
{
Marshal.ReleaseComObject(xmlNode);
}
}
}
public int PositionCaretForEditing(IVsTextLines pBuffer, [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")]VsTextSpan[] ts)
{
// If the formatted location of the $end$ position (the inserted comment) was on an
// empty line and indented, then we have already removed the white space on that line
// and the navigation location will be at column 0 on a blank line. We must now
// position the caret in virtual space.
int lineLength;
pBuffer.GetLengthOfLine(ts[0].iStartLine, out lineLength);
string endLineText;
pBuffer.GetLineText(ts[0].iStartLine, 0, ts[0].iStartLine, lineLength, out endLineText);
int endLinePosition;
pBuffer.GetPositionOfLine(ts[0].iStartLine, out endLinePosition);
PositionCaretForEditingInternal(endLineText, endLinePosition);
return VSConstants.S_OK;
}
/// <summary>
/// Internal for testing purposes. All real caret positioning logic takes place here. <see cref="PositionCaretForEditing"/>
/// only extracts the <paramref name="endLineText"/> and <paramref name="endLinePosition"/> from the provided <see cref="IVsTextLines"/>.
/// Tests can call this method directly to avoid producing an IVsTextLines.
/// </summary>
/// <param name="endLineText"></param>
/// <param name="endLinePosition"></param>
internal void PositionCaretForEditingInternal(string endLineText, int endLinePosition)
{
if (indentCaretOnCommit && endLineText == string.Empty)
{
TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(TextView.TextSnapshot.GetPoint(endLinePosition), indentDepth));
}
}
public virtual bool TryHandleTab()
{
if (ExpansionSession != null)
{
var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(0);
if (!tabbedInsideSnippetField)
{
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);
ExpansionSession = null;
}
return tabbedInsideSnippetField;
}
return false;
}
public virtual bool TryHandleBackTab()
{
if (ExpansionSession != null)
{
var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToPreviousExpansionField();
if (!tabbedInsideSnippetField)
{
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);
ExpansionSession = null;
}
return tabbedInsideSnippetField;
}
return false;
}
public virtual bool TryHandleEscape()
{
if (ExpansionSession != null)
{
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);
ExpansionSession = null;
return true;
}
return false;
}
public virtual bool TryHandleReturn()
{
if (ExpansionSession != null)
{
// Only move the caret if the enter was hit within the snippet fields.
var hitWithinField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: 0);
ExpansionSession.EndCurrentExpansion(fLeaveCaret: hitWithinField ? 0 : 1);
ExpansionSession = null;
return hitWithinField;
}
return false;
}
public virtual bool TryInsertExpansion(int startPositionInSubjectBuffer, int endPositionInSubjectBuffer)
{
var textViewModel = TextView.TextViewModel;
if (textViewModel == null)
{
Debug.Assert(TextView.IsClosed);
return false;
}
int startLine = 0;
int startIndex = 0;
int endLine = 0;
int endIndex = 0;
// The expansion itself needs to be created in the data buffer, so map everything up
var startPointInSubjectBuffer = SubjectBuffer.CurrentSnapshot.GetPoint(startPositionInSubjectBuffer);
var endPointInSubjectBuffer = SubjectBuffer.CurrentSnapshot.GetPoint(endPositionInSubjectBuffer);
SnapshotSpan dataBufferSpan;
if (!TryGetSpanOnHigherBuffer(
SubjectBuffer.CurrentSnapshot.GetSpan(startPositionInSubjectBuffer, endPositionInSubjectBuffer - startPositionInSubjectBuffer),
textViewModel.DataBuffer,
out dataBufferSpan))
{
return false;
}
var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer);
var expansion = buffer as IVsExpansion;
if (buffer == null || expansion == null)
{
return false;
}
buffer.GetLineIndexOfPosition(dataBufferSpan.Start.Position, out startLine, out startIndex);
buffer.GetLineIndexOfPosition(dataBufferSpan.End.Position, out endLine, out endIndex);
var textSpan = new VsTextSpan
{
iStartLine = startLine,
iStartIndex = startIndex,
iEndLine = endLine,
iEndIndex = endIndex
};
return expansion.InsertExpansion(textSpan, textSpan, this, LanguageServiceGuid, out ExpansionSession) == VSConstants.S_OK;
}
public int EndExpansion()
{
if (ExpansionSession == null)
{
earlyEndExpansionHappened = true;
}
ExpansionSession = null;
indentCaretOnCommit = false;
return VSConstants.S_OK;
}
public int IsValidKind(IVsTextLines pBuffer, VsTextSpan[] ts, string bstrKind, out int pfIsValidKind)
{
pfIsValidKind = 1;
return VSConstants.S_OK;
}
public int IsValidType(IVsTextLines pBuffer, VsTextSpan[] ts, string[] rgTypes, int iCountTypes, out int pfIsValidType)
{
pfIsValidType = 1;
return VSConstants.S_OK;
}
public int OnAfterInsertion(IVsExpansionSession pSession)
{
Logger.Log(FunctionId.Snippet_OnAfterInsertion);
return VSConstants.S_OK;
}
public int OnBeforeInsertion(IVsExpansionSession pSession)
{
Logger.Log(FunctionId.Snippet_OnBeforeInsertion);
this.ExpansionSession = pSession;
return VSConstants.S_OK;
}
public int OnItemChosen(string pszTitle, string pszPath)
{
var textViewModel = TextView.TextViewModel;
if (textViewModel == null)
{
Debug.Assert(TextView.IsClosed);
return VSConstants.E_FAIL;
}
var hr = VSConstants.S_OK;
try
{
VsTextSpan textSpan;
GetCaretPositionInSurfaceBuffer(out textSpan.iStartLine, out textSpan.iStartIndex);
textSpan.iEndLine = textSpan.iStartLine;
textSpan.iEndIndex = textSpan.iStartIndex;
IVsExpansion expansion = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer) as IVsExpansion;
earlyEndExpansionHappened = false;
hr = expansion.InsertNamedExpansion(pszTitle, pszPath, textSpan, this, LanguageServiceGuid, fShowDisambiguationUI: 0, pSession: out ExpansionSession);
if (earlyEndExpansionHappened)
{
// EndExpansion was called before InsertNamedExpansion returned, so set
// expansionSession to null to indicate that there is no active expansion
// session. This can occur when the snippet inserted doesn't have any expansion
// fields.
ExpansionSession = null;
earlyEndExpansionHappened = false;
}
}
catch (COMException ex)
{
hr = ex.ErrorCode;
}
return hr;
}
private void GetCaretPositionInSurfaceBuffer(out int caretLine, out int caretColumn)
{
var vsTextView = EditorAdaptersFactoryService.GetViewAdapter(TextView);
vsTextView.GetCaretPos(out caretLine, out caretColumn);
IVsTextLines textLines;
vsTextView.GetBuffer(out textLines);
// Handle virtual space (e.g, see Dev10 778675)
int lineLength;
textLines.GetLengthOfLine(caretLine, out lineLength);
if (caretColumn > lineLength)
{
caretColumn = lineLength;
}
}
private void AddReferencesAndImports(IVsExpansionSession pSession, CancellationToken cancellationToken)
{
XElement snippetNode;
if (!TryGetSnippetNode(pSession, out snippetNode))
{
return;
}
var documentWithImports = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (documentWithImports == null)
{
return;
}
var optionService = documentWithImports.Project.Solution.Workspace.Services.GetService<IOptionService>();
var placeSystemNamespaceFirst = optionService.GetOption(OrganizerOptions.PlaceSystemNamespaceFirst, documentWithImports.Project.Language);
documentWithImports = AddImports(documentWithImports, snippetNode, placeSystemNamespaceFirst, cancellationToken);
AddReferences(documentWithImports.Project, snippetNode);
}
private void AddReferences(Project originalProject, XElement snippetNode)
{
var referencesNode = snippetNode.Element(XName.Get("References", snippetNode.Name.NamespaceName));
if (referencesNode == null)
{
return;
}
var existingReferenceNames = originalProject.MetadataReferences.Select(r => Path.GetFileNameWithoutExtension(r.Display));
var workspace = originalProject.Solution.Workspace;
var projectId = originalProject.Id;
var assemblyXmlName = XName.Get("Assembly", snippetNode.Name.NamespaceName);
var failedReferenceAdditions = new List<string>();
var visualStudioWorkspace = workspace as VisualStudioWorkspaceImpl;
foreach (var reference in referencesNode.Elements(XName.Get("Reference", snippetNode.Name.NamespaceName)))
{
// Note: URL references are not supported
var assemblyElement = reference.Element(assemblyXmlName);
var assemblyName = assemblyElement != null ? assemblyElement.Value.Trim() : null;
if (string.IsNullOrEmpty(assemblyName))
{
continue;
}
if (visualStudioWorkspace == null ||
!visualStudioWorkspace.TryAddReferenceToProject(projectId, assemblyName))
{
failedReferenceAdditions.Add(assemblyName);
}
}
if (failedReferenceAdditions.Any())
{
var notificationService = workspace.Services.GetService<INotificationService>();
notificationService.SendNotification(
string.Format(ServicesVSResources.ReferencesNotFound, Environment.NewLine)
+ Environment.NewLine + Environment.NewLine
+ string.Join(Environment.NewLine, failedReferenceAdditions),
severity: NotificationSeverity.Warning);
}
}
protected static bool TryAddImportsToContainedDocument(Document document, IEnumerable<string> memberImportsNamespaces)
{
var vsWorkspace = document.Project.Solution.Workspace as VisualStudioWorkspaceImpl;
if (vsWorkspace == null)
{
return false;
}
var containedDocument = vsWorkspace.GetHostDocument(document.Id) as ContainedDocument;
if (containedDocument == null)
{
return false;
}
var containedLanguageHost = containedDocument.ContainedLanguage.ContainedLanguageHost as IVsContainedLanguageHostInternal;
if (containedLanguageHost != null)
{
foreach (var importClause in memberImportsNamespaces)
{
if (containedLanguageHost.InsertImportsDirective(importClause) != VSConstants.S_OK)
{
return false;
}
}
}
return true;
}
protected static bool TryGetSnippetFunctionInfo(IXMLDOMNode xmlFunctionNode, out string snippetFunctionName, out string param)
{
if (xmlFunctionNode.text.IndexOf('(') == -1 ||
xmlFunctionNode.text.IndexOf(')') == -1 ||
xmlFunctionNode.text.IndexOf(')') < xmlFunctionNode.text.IndexOf('('))
{
snippetFunctionName = null;
param = null;
return false;
}
snippetFunctionName = xmlFunctionNode.text.Substring(0, xmlFunctionNode.text.IndexOf('('));
var paramStart = xmlFunctionNode.text.IndexOf('(') + 1;
var paramLength = xmlFunctionNode.text.LastIndexOf(')') - xmlFunctionNode.text.IndexOf('(') - 1;
param = xmlFunctionNode.text.Substring(paramStart, paramLength);
return true;
}
internal bool TryGetSubjectBufferSpan(VsTextSpan surfaceBufferTextSpan, out SnapshotSpan subjectBufferSpan)
{
var snapshotSpan = TextView.TextSnapshot.GetSpan(surfaceBufferTextSpan);
var subjectBufferSpanCollection = TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, SubjectBuffer);
// Bail if a snippet span does not map down to exactly one subject buffer span.
if (subjectBufferSpanCollection.Count == 1)
{
subjectBufferSpan = subjectBufferSpanCollection.Single();
return true;
}
subjectBufferSpan = default(SnapshotSpan);
return false;
}
internal bool TryGetSpanOnHigherBuffer(SnapshotSpan snapshotSpan, ITextBuffer targetBuffer, out SnapshotSpan span)
{
var spanCollection = TextView.BufferGraph.MapUpToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, targetBuffer);
// Bail if a snippet span does not map up to exactly one span.
if (spanCollection.Count == 1)
{
span = spanCollection.Single();
return true;
}
span = default(SnapshotSpan);
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using P3Net.Kraken.Diagnostics;
using P3Net.Kraken.UnitTesting;
namespace Tests.P3Net.Kraken.Diagnostics
{
[TestClass]
public class StringArgumentConstraintExtensionsTests : UnitTest
{
#region HasLengthBetween
[TestMethod]
public void HasLengthBetween_IsTrue ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "Hello"));
target.HasLengthBetween(1, 10);
}
[TestMethod]
public void HasLengthBetween_IsTooLong ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "Hello"));
Action work = () => target.HasLengthBetween(1, 3);
work.Should().Throw<ArgumentException>();
}
[TestMethod]
public void HasLengthBetween_IsTooShort ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "Hello"));
Action work = () => target.HasLengthBetween(10, 20);
work.Should().Throw<ArgumentException>();
}
[TestMethod]
public void HasLengthBetween_WithMessage ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "Hello"));
var expectedMessage = "Testing";
Action work = () => target.HasLengthBetween(10, 20, expectedMessage);
work.Should().Throw<ArgumentException>().ContainingMessage(expectedMessage);
}
[TestMethod]
public void HasLengthBetween_IsNull ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", null));
Action work = () => target.HasLengthBetween(1, 10);
work.Should().Throw<ArgumentException>();
}
#endregion
#region HasMaximumLength
[TestMethod]
public void HasMaximumLength_IsTrue ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "Hello"));
target.HasMaximumLength(10);
}
[TestMethod]
public void HasMaximumLength_IsFalse ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "Hello"));
Action work = () => target.HasMaximumLength(3);
work.Should().Throw<ArgumentException>();
}
[TestMethod]
public void HasMaximumLength_WithMessage ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "Hello"));
var expectedMessage = "Testing";
Action work = () => target.HasMaximumLength(3, expectedMessage);
work.Should().Throw<ArgumentException>().ContainingMessage(expectedMessage);
}
[TestMethod]
public void HasMaximumLength_IsNull ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", null));
target.HasMaximumLength(1);
}
#endregion
#region HasMinimumLength
[TestMethod]
public void HasMinimumLength_IsTrue ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "Hello"));
target.HasMinimumLength(3);
}
[TestMethod]
public void HasMinimumLength_IsFalse ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "Hello"));
Action work = () => target.HasMinimumLength(10);
work.Should().Throw<ArgumentException>();
}
[TestMethod]
public void HasMinimumLength_WithMessage ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "Hello"));
var expectedMessage = "Testing";
Action work = () => target.HasMinimumLength(10, expectedMessage);
work.Should().Throw<ArgumentException>().ContainingMessage(expectedMessage);
}
[TestMethod]
public void HasMinimumLength_IsNull ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", null));
Action work = () => target.HasMinimumLength(1);
work.Should().Throw<ArgumentException>();
}
#endregion
#region IsAlpha
[TestMethod]
public void IsAlpha_HasAllLetters ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "ABC"));
target.IsAlpha();
}
[TestMethod]
public void IsAlpha_HasMixed ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "123ABC"));
Action work = () => target.IsAlpha();
work.Should().Throw<ArgumentException>();
}
[TestMethod]
public void IsAlpha_HasNoLetters ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "123"));
Action work = () => target.IsAlpha();
work.Should().Throw<ArgumentException>();
}
[TestMethod]
public void IsAlpha_HasMixedWithMessage ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "123ABC"));
var expectedMessage = "Testing";
Action work = () => target.IsAlpha(expectedMessage);
work.Should().Throw<ArgumentException>().ContainingMessage(expectedMessage);
}
[TestMethod]
public void IsAlpha_HasNoLettersWithMessage ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "123"));
var expectedMessage = "Testing";
Action work = () => target.IsAlpha(expectedMessage);
work.Should().Throw<ArgumentException>().ContainingMessage(expectedMessage);
}
[TestMethod]
public void IsAlpha_HasLettersWithMessage ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "ABC"));
target.IsAlpha("Testing");
}
#endregion
#region IsAlphaNumeric
[TestMethod]
public void IsAlphaNumeric_HasAllDigits ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "1234"));
target.IsAlphanumeric();
}
[TestMethod]
public void IsAlphaNumeric_HasAllLetters ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "ABC"));
target.IsAlphanumeric();
}
[TestMethod]
public void IsAlphaNumeric_HasAllLettersAndDigits ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "123ABC"));
target.IsAlphanumeric();
}
[TestMethod]
public void IsAlphaNumeric_HasMixed ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "123_ABC"));
Action work = () => target.IsAlphanumeric();
work.Should().Throw<ArgumentException>();
}
[TestMethod]
public void IsAlphaNumeric_HasMixedWithMessage ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "123_ABC"));
var expectedMessage = "Testing";
Action work = () => target.IsAlphanumeric(expectedMessage);
work.Should().Throw<ArgumentException>().ContainingMessage(expectedMessage);
}
[TestMethod]
public void IsAlphaNumeric_HasLettersAndDigitsWithMessage ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "123ABC"));
target.IsAlphanumeric("Testing");
}
#endregion
#region IsNotNullOrEmpty
[TestMethod]
public void IsNotNullOrEmpty_IsFalse ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "Hello"));
target.IsNotNullOrEmpty();
}
[TestMethod]
public void IsNotNullOrEmpty_IsEmpty ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", ""));
Action work = () => target.IsNotNullOrEmpty();
work.Should().Throw<ArgumentException>();
}
[TestMethod]
public void IsNotNullOrEmpty_IsNull ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", null));
Action work = () => target.IsNotNullOrEmpty();
work.Should().Throw<ArgumentNullException>();
}
[TestMethod]
public void IsNotNullOrEmpty_IsNull_WithMessage ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", null));
var expectedMessage = "Testing";
Action work = () => target.IsNotNullOrEmpty(expectedMessage);
work.Should().Throw<ArgumentException>().ContainingMessage(expectedMessage);
}
[TestMethod]
public void IsNotNullOrEmpty_IsEmpty_WithMessage ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", ""));
var expectedMessage = "Testing";
Action work = () => target.IsNotNullOrEmpty(expectedMessage);
work.Should().Throw<ArgumentException>().ContainingMessage(expectedMessage);
}
[TestMethod]
public void IsNotNullOrEmpty_IsTrue_WithMessage ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "Not"));
target.IsNotNullOrEmpty("Testing");
}
#endregion
#region IsNotNullOrWhiteSpace
[TestMethod]
public void IsNotNullOrWhitespace_IsFalse ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "Hello"));
target.IsNotNullOrWhiteSpace();
}
[TestMethod]
public void IsNotNullOrWhitespace_IsEmpty ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", ""));
Action work = () => target.IsNotNullOrWhiteSpace();
work.Should().Throw<ArgumentException>();
}
[TestMethod]
public void IsNotNullOrWhitespace_IsWhitespace ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", " "));
Action work = () => target.IsNotNullOrWhiteSpace();
work.Should().Throw<ArgumentException>();
}
[TestMethod]
public void IsNotNullOrWhitespace_IsNull ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", null));
Action work = () => target.IsNotNullOrWhiteSpace();
work.Should().Throw<ArgumentNullException>();
}
[TestMethod]
public void IsNotNullOrWhitespace_IsNull_WithMessage ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", null));
var expectedMessage = "Testing";
Action work = () => target.IsNotNullOrWhiteSpace(expectedMessage);
work.Should().Throw<ArgumentException>().ContainingMessage(expectedMessage);
}
[TestMethod]
public void IsNotNullOrWhitespace_IsEmpty_WithMessage ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", ""));
var expectedMessage = "Testing";
Action work = () => target.IsNotNullOrWhiteSpace(expectedMessage);
work.Should().Throw<ArgumentException>().ContainingMessage(expectedMessage);
}
[TestMethod]
public void IsNotNullOrWhitespace_IsTrue_WithMessage ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "Not"));
target.IsNotNullOrWhiteSpace("Testing");
}
#endregion
#region IsNumeric
[TestMethod]
public void IsNumeric_HasAllDigits ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "1234"));
target.IsNumeric();
}
[TestMethod]
public void IsNumeric_HasMixed ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "123ABC"));
Action work = () => target.IsNumeric();
work.Should().Throw<ArgumentException>();
}
[TestMethod]
public void IsNumeric_HasNoDigits ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "ABC"));
Action work = () => target.IsNumeric();
work.Should().Throw<ArgumentException>();
}
[TestMethod]
public void IsNumeric_HasMixedWithMessage ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "123ABC"));
var expectedMessage = "Testing";
Action work = () => target.IsNumeric(expectedMessage);
work.Should().Throw<ArgumentException>().ContainingMessage(expectedMessage);
}
[TestMethod]
public void IsNumeric_HasNoDigitsWithMessage ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "ABC"));
var expectedMessage = "Testing";
Action work = () => target.IsNumeric(expectedMessage);
work.Should().Throw<ArgumentException>().ContainingMessage(expectedMessage);
}
[TestMethod]
public void IsNumeric_HasDigitsWithMessage ()
{
var target = new ArgumentConstraint<string>(new Argument<string>("a", "123"));
target.IsNumeric("Testing");
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.Xml;
using System.Diagnostics;
using System.Collections;
using System.Threading;
using System.Collections.Generic;
using System.Runtime.Versioning;
namespace Microsoft.Xml.Schema
{
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet"]/*' />
/// <devdoc>
/// <para>The XmlSchemaSet contains a set of namespace URI's.
/// Each namespace also have an associated private data cache
/// corresponding to the XML-Data Schema or W3C XML Schema.
/// The XmlSchemaSet will able to load only XSD schemas,
/// and compile them into an internal "cooked schema representation".
/// The Validate method then uses this internal representation for
/// efficient runtime validation of any given subtree.</para>
/// </devdoc>
public class XmlSchemaSet
{
private XmlNameTable _nameTable;
private SchemaNames _schemaNames;
private SortedList _schemas; // List of source schemas
//Event handling
private ValidationEventHandler _internalEventHandler;
private ValidationEventHandler _eventHandler;
private bool _isCompiled = false;
//Dictionary<Uri, XmlSchema> schemaLocations;
//Dictionary<ChameleonKey, XmlSchema> chameleonSchemas;
private Hashtable _schemaLocations;
private Hashtable _chameleonSchemas;
private Hashtable _targetNamespaces;
private bool _compileAll;
//Cached Compiled Info
private SchemaInfo _cachedCompiledInfo;
//Reader settings to parse schema
private XmlReaderSettings _readerSettings;
private XmlSchema _schemaForSchema; //Only one schema for schema per set
//Schema compilation settings
private XmlSchemaCompilationSettings _compilationSettings;
internal XmlSchemaObjectTable elements;
internal XmlSchemaObjectTable attributes;
internal XmlSchemaObjectTable schemaTypes;
internal XmlSchemaObjectTable substitutionGroups;
private XmlSchemaObjectTable _typeExtensions;
//Thread safety
private Object _internalSyncObject;
internal Object InternalSyncObject
{
get
{
if (_internalSyncObject == null)
{
Object o = new Object();
Interlocked.CompareExchange<Object>(ref _internalSyncObject, o, null);
}
return _internalSyncObject;
}
}
//Constructors
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.XmlSchemaSet"]/*' />
/// <devdoc>
/// <para>Construct a new empty schema schemas.</para>
/// </devdoc>
public XmlSchemaSet() : this(new NameTable())
{
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.XmlSchemaSet1"]/*' />
/// <devdoc>
/// <para>Construct a new empty schema schemas with associated XmlNameTable.
/// The XmlNameTable is used when loading schemas</para>
/// </devdoc>
public XmlSchemaSet(XmlNameTable nameTable)
{
if (nameTable == null)
{
throw new ArgumentNullException("nameTable");
}
_nameTable = nameTable;
_schemas = new SortedList();
/*schemaLocations = new Dictionary<Uri, XmlSchema>();
chameleonSchemas = new Dictionary<ChameleonKey, XmlSchema>();*/
_schemaLocations = new Hashtable();
_chameleonSchemas = new Hashtable();
_targetNamespaces = new Hashtable();
_internalEventHandler = new ValidationEventHandler(InternalValidationCallback);
_eventHandler = _internalEventHandler;
_readerSettings = new XmlReaderSettings();
// we don't have to check XmlReaderSettings.EnableLegacyXmlSettings() here because the following
// code will return same result either we are running on v4.5 or later
if (_readerSettings.GetXmlResolver() == null)
{
// The created resolver will be used in the schema validation only
_readerSettings.XmlResolver = new XmlUrlResolver();
_readerSettings.IsXmlResolverSet = false;
}
_readerSettings.NameTable = nameTable;
_readerSettings.DtdProcessing = DtdProcessing.Prohibit;
_compilationSettings = new XmlSchemaCompilationSettings();
_cachedCompiledInfo = new SchemaInfo();
_compileAll = true;
}
//Public Properties
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.NameTable"]/*' />
/// <devdoc>
/// <para>The default XmlNameTable used by the XmlSchemaSet when loading new schemas.</para>
/// </devdoc>
public XmlNameTable NameTable
{
get { return _nameTable; }
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.ValidationEventHandler"]/*' />
public event ValidationEventHandler ValidationEventHandler
{
add
{
_eventHandler -= _internalEventHandler;
_eventHandler += value;
if (_eventHandler == null)
{
_eventHandler = _internalEventHandler;
}
}
remove
{
_eventHandler -= value;
if (_eventHandler == null)
{
_eventHandler = _internalEventHandler;
}
}
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.IsCompiled"]/*' />
/// <devdoc>
/// <para>IsCompiled is true when the schema set is in compiled state</para>
/// </devdoc>
public bool IsCompiled
{
get
{
return _isCompiled;
}
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.XmlResolver"]/*' />
/// <devdoc>
/// <para></para>
/// </devdoc>
public XmlResolver XmlResolver
{
set
{
_readerSettings.XmlResolver = value;
}
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.CompilationSettings"]/*' />
/// <devdoc>
/// <para></para>
/// </devdoc>
public XmlSchemaCompilationSettings CompilationSettings
{
get
{
return _compilationSettings;
}
set
{
_compilationSettings = value;
}
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Count"]/*' />
/// <devdoc>
/// <para>Returns the count of schemas in the set</para>
/// </devdoc>
public int Count
{
get
{
return _schemas.Count;
}
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.GlobalElements"]/*' />
/// <devdoc>
/// <para></para>
/// </devdoc>
public XmlSchemaObjectTable GlobalElements
{
get
{
if (elements == null)
{
elements = new XmlSchemaObjectTable();
}
return elements;
}
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.GlobalAttributes"]/*' />
/// <devdoc>
/// <para></para>
/// </devdoc>
public XmlSchemaObjectTable GlobalAttributes
{
get
{
if (attributes == null)
{
attributes = new XmlSchemaObjectTable();
}
return attributes;
}
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.GlobalTypes"]/*' />
/// <devdoc>
/// <para></para>
/// </devdoc>
public XmlSchemaObjectTable GlobalTypes
{
get
{
if (schemaTypes == null)
{
schemaTypes = new XmlSchemaObjectTable();
}
return schemaTypes;
}
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.SubstitutionGroups"]/*' />
/// <devdoc>
/// <para></para>
/// </devdoc>
/// TODO: Need to make this public
internal XmlSchemaObjectTable SubstitutionGroups
{
get
{
if (substitutionGroups == null)
{
substitutionGroups = new XmlSchemaObjectTable();
}
return substitutionGroups;
}
}
/// <summary>
/// Table of all types extensions
/// </summary>
internal Hashtable SchemaLocations
{
get
{
return _schemaLocations;
}
}
/// <summary>
/// Table of all types extensions
/// </summary>
internal XmlSchemaObjectTable TypeExtensions
{
get
{
if (_typeExtensions == null)
{
_typeExtensions = new XmlSchemaObjectTable();
}
return _typeExtensions;
}
}
//Public Methods
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Add1"]/*' />
/// <devdoc>
/// <para>Add the schema located by the given URL into the schema schemas.
/// If the given schema references other namespaces, the schemas for those other
/// namespaces are NOT automatically loaded.</para>
/// </devdoc>
// [ResourceConsumption(ResourceScope.Machine)]
// [ResourceExposure(ResourceScope.Machine)]
public XmlSchema Add(String targetNamespace, String schemaUri)
{
if (schemaUri == null || schemaUri.Length == 0)
{
throw new ArgumentNullException("schemaUri");
}
if (targetNamespace != null)
{
targetNamespace = XmlComplianceUtil.CDataNormalize(targetNamespace);
}
XmlSchema schema = null;
lock (InternalSyncObject)
{
//Check if schema from url has already been added
XmlResolver tempResolver = _readerSettings.GetXmlResolver();
if (tempResolver == null)
{
tempResolver = new XmlUrlResolver();
}
Uri tempSchemaUri = tempResolver.ResolveUri(null, schemaUri);
if (IsSchemaLoaded(tempSchemaUri, targetNamespace, out schema))
{
return schema;
}
else
{
//Url already not processed; Load SOM from url
XmlReader reader = XmlReader.Create(schemaUri, _readerSettings);
try
{
schema = Add(targetNamespace, ParseSchema(targetNamespace, reader)); //TODO can move parsing outside lock boundary
while (reader.Read()) ;// wellformness check;
}
finally
{
reader.Close();
}
}
}
return schema;
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Add4"]/*' />
/// <devdoc>
/// <para>Add the given schema into the schema schemas.
/// If the given schema references other namespaces, the schemas for those
/// other namespaces are NOT automatically loaded.</para>
/// </devdoc>
public XmlSchema Add(String targetNamespace, XmlReader schemaDocument)
{
if (schemaDocument == null)
{
throw new ArgumentNullException("schemaDocument");
}
if (targetNamespace != null)
{
targetNamespace = XmlComplianceUtil.CDataNormalize(targetNamespace);
}
lock (InternalSyncObject)
{
XmlSchema schema = null;
Uri schemaUri = new Uri(schemaDocument.BaseURI, UriKind.RelativeOrAbsolute);
if (IsSchemaLoaded(schemaUri, targetNamespace, out schema))
{
return schema;
}
else
{
DtdProcessing dtdProcessing = _readerSettings.DtdProcessing;
SetDtdProcessing(schemaDocument);
schema = Add(targetNamespace, ParseSchema(targetNamespace, schemaDocument));
_readerSettings.DtdProcessing = dtdProcessing; //reset dtdProcessing setting
return schema;
}
}
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Add5"]/*' />
/// <devdoc>
/// <para>Adds all the namespaces defined in the given schemas
/// (including their associated schemas) to this schemas.</para>
/// </devdoc>
public void Add(XmlSchemaSet schemas)
{
if (schemas == null)
{
throw new ArgumentNullException("schemas");
}
if (this == schemas)
{
return;
}
bool thisLockObtained = false;
bool schemasLockObtained = false;
try
{
while (true)
{
Monitor.TryEnter(InternalSyncObject, ref thisLockObtained);
if (thisLockObtained)
{
Monitor.TryEnter(schemas.InternalSyncObject, ref schemasLockObtained);
if (schemasLockObtained)
{
break;
}
else
{
Monitor.Exit(InternalSyncObject); //Give up this lock and try both again
thisLockObtained = false;
Thread.Sleep(10); //Thread.Yield(); //Let the thread that holds the lock run
continue;
}
}
}
XmlSchema currentSchema;
//TODO Need to copy chameleon Schemas and schemaLocations from other set
if (schemas.IsCompiled)
{
CopyFromCompiledSet(schemas);
}
else
{
bool remove = false;
string tns = null;
foreach (XmlSchema schema in schemas.SortedSchemas.Values)
{
tns = schema.TargetNamespace;
if (tns == null)
{
tns = string.Empty;
}
if (_schemas.ContainsKey(schema.SchemaId) || FindSchemaByNSAndUrl(schema.BaseUri, tns, null) != null)
{ //Do not already existing url
continue;
}
currentSchema = Add(schema.TargetNamespace, schema);
if (currentSchema == null)
{
remove = true;
break;
}
}
//Remove all from the set if even one schema in the passed in set is not preprocessed.
if (remove)
{
foreach (XmlSchema schema in schemas.SortedSchemas.Values)
{ //Remove all previously added schemas from the set
_schemas.Remove(schema.SchemaId); //Might remove schema that was already there and was not added thru this operation
_schemaLocations.Remove(schema.BaseUri);
}
}
}
}
finally
{ //release locks on sets
if (thisLockObtained)
{
Monitor.Exit(InternalSyncObject);
}
if (schemasLockObtained)
{
Monitor.Exit(schemas.InternalSyncObject);
}
}
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Add6"]/*' />
public XmlSchema Add(XmlSchema schema)
{
if (schema == null)
{
throw new ArgumentNullException("schema");
}
lock (InternalSyncObject)
{
if (_schemas.ContainsKey(schema.SchemaId))
{
return schema;
}
return Add(schema.TargetNamespace, schema);
}
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Remove"]/*' />
public XmlSchema Remove(XmlSchema schema)
{
return Remove(schema, true);
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.RemoveRecursive"]/*' />
public bool RemoveRecursive(XmlSchema schemaToRemove)
{
if (schemaToRemove == null)
{
throw new ArgumentNullException("schemaToRemove");
}
if (!_schemas.ContainsKey(schemaToRemove.SchemaId))
{
return false;
}
lock (InternalSyncObject)
{ //Need to lock here so that remove cannot be called while the set is being compiled
if (_schemas.ContainsKey(schemaToRemove.SchemaId))
{ //Need to check again
//Build disallowedNamespaces list
Hashtable disallowedNamespaces = new Hashtable();
disallowedNamespaces.Add(GetTargetNamespace(schemaToRemove), schemaToRemove);
string importedNS;
for (int i = 0; i < schemaToRemove.ImportedNamespaces.Count; i++)
{
importedNS = (string)schemaToRemove.ImportedNamespaces[i];
if (disallowedNamespaces[importedNS] == null)
{
disallowedNamespaces.Add(importedNS, importedNS);
}
}
//Removal list is all schemas imported by this schema directly or indirectly
//Need to check if other schemas in the set import schemaToRemove / any of its imports
ArrayList needToCheckSchemaList = new ArrayList();
XmlSchema mainSchema;
for (int i = 0; i < _schemas.Count; i++)
{
mainSchema = (XmlSchema)_schemas.GetByIndex(i);
if (mainSchema == schemaToRemove ||
schemaToRemove.ImportedSchemas.Contains(mainSchema))
{
continue;
}
needToCheckSchemaList.Add(mainSchema);
}
mainSchema = null;
for (int i = 0; i < needToCheckSchemaList.Count; i++)
{ //Perf: Not using nested foreach here
mainSchema = (XmlSchema)needToCheckSchemaList[i];
if (mainSchema.ImportedNamespaces.Count > 0)
{
foreach (string tns in disallowedNamespaces.Keys)
{
if (mainSchema.ImportedNamespaces.Contains(tns))
{
SendValidationEvent(new XmlSchemaException(ResXml.Sch_SchemaNotRemoved, string.Empty), XmlSeverityType.Warning);
return false;
}
}
}
}
Remove(schemaToRemove, true);
for (int i = 0; i < schemaToRemove.ImportedSchemas.Count; ++i)
{
XmlSchema impSchema = (XmlSchema)schemaToRemove.ImportedSchemas[i];
Remove(impSchema, true);
}
return true;
}
}
return false;
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Contains1"]/*' />
public bool Contains(String targetNamespace)
{
if (targetNamespace == null)
{
targetNamespace = string.Empty;
}
return _targetNamespaces[targetNamespace] != null;
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Contains2"]/*' />
public bool Contains(XmlSchema schema)
{
if (schema == null)
{
throw new ArgumentNullException("schema");
}
return _schemas.ContainsValue(schema);
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Compile"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Compile()
{
if (_isCompiled)
{
return;
}
if (_schemas.Count == 0)
{
ClearTables(); //Clear any previously present compiled state left by calling just Remove() on the set
_cachedCompiledInfo = new SchemaInfo();
_isCompiled = true;
_compileAll = false;
return;
}
lock (InternalSyncObject)
{
if (!_isCompiled)
{ //Locking before checking isCompiled to avoid problems with double locking
Compiler compiler = new Compiler(_nameTable, _eventHandler, _schemaForSchema, _compilationSettings);
SchemaInfo newCompiledInfo = new SchemaInfo();
int schemaIndex = 0;
if (!_compileAll)
{ //if we are not compiling everything again, Move the pre-compiled schemas to the compiler's tables
compiler.ImportAllCompiledSchemas(this);
}
try
{ //First thing to do in the try block is to acquire locks since finally will try to release them.
//If we dont accuire the locks first, and an exception occurs in the code before the locking code, then Threading.SynchronizationLockException will be thrown
//when attempting to release it in the finally block
XmlSchema currentSchema;
XmlSchema xmlNSSchema = Preprocessor.GetBuildInSchema();
for (schemaIndex = 0; schemaIndex < _schemas.Count; schemaIndex++)
{
currentSchema = (XmlSchema)_schemas.GetByIndex(schemaIndex);
//Lock schema to be compiled
#pragma warning disable 0618
//@TODO: This overload of Monitor.Enter is obsolete. Please change this to use Monitor.Enter(ref bool), and remove the pragmas -- ericeil
Monitor.Enter(currentSchema);
#pragma warning restore 0618
if (!currentSchema.IsPreprocessed)
{
SendValidationEvent(new XmlSchemaException(ResXml.Sch_SchemaNotPreprocessed, string.Empty), XmlSeverityType.Error);
_isCompiled = false;
return;
}
if (currentSchema.IsCompiledBySet)
{
if (!_compileAll)
{
continue;
}
else if ((object)currentSchema == (object)xmlNSSchema)
{ // prepare for xml namespace schema without cleanup
compiler.Prepare(currentSchema, false);
continue;
}
}
compiler.Prepare(currentSchema, true);
}
_isCompiled = compiler.Execute(this, newCompiledInfo);
if (_isCompiled)
{
if (!_compileAll)
{
newCompiledInfo.Add(_cachedCompiledInfo, _eventHandler); //Add all the items from the old to the new compiled object
}
_compileAll = false;
_cachedCompiledInfo = newCompiledInfo; //Replace the compiled info in the set after successful compilation
}
}
finally
{
//Release locks on all schemas
XmlSchema currentSchema;
if (schemaIndex == _schemas.Count)
{
schemaIndex--;
}
for (int i = schemaIndex; i >= 0; i--)
{
currentSchema = (XmlSchema)_schemas.GetByIndex(i);
if (currentSchema == Preprocessor.GetBuildInSchema())
{ //dont re-set compiled flags for xml namespace schema
Monitor.Exit(currentSchema);
continue;
}
currentSchema.IsCompiledBySet = _isCompiled;
Monitor.Exit(currentSchema);
}
}
}
}
return;
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Reprocess"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSchema Reprocess(XmlSchema schema)
{
// Due to bug 644477 - this method is tightly coupled (THE CODE IS BASICALLY COPIED) to Remove, Add and AddSchemaToSet
// methods. If you change anything here *make sure* to update Remove/Add/AddSchemaToSet method(s) accordingly.
// The only difference is that we don't touch .schemas collection here to not break a code like this:
// foreach(XmlSchema s in schemaset.schemas) { schemaset.Reprocess(s); }
// This is by purpose.
if (schema == null)
{
throw new ArgumentNullException("schema");
}
if (!_schemas.ContainsKey(schema.SchemaId))
{
throw new ArgumentException(ResXml.Sch_SchemaDoesNotExist, "schema");
}
XmlSchema originalSchema = schema;
lock (InternalSyncObject)
{ //Lock set so that set cannot be compiled in another thread
// This code is copied from method:
// Remove(XmlSchema schema, bool forceCompile)
// If you changed anything here go and change the same in Remove(XmlSchema schema, bool forceCompile) method
#region Copied from Remove(XmlSchema schema, bool forceCompile)
RemoveSchemaFromGlobalTables(schema);
RemoveSchemaFromCaches(schema);
if (schema.BaseUri != null)
{
_schemaLocations.Remove(schema.BaseUri);
}
string tns = GetTargetNamespace(schema);
if (Schemas(tns).Count == 0)
{ //This is the only schema for that namespace
_targetNamespaces.Remove(tns);
}
_isCompiled = false;
_compileAll = true; //Force compilation of the whole set; This is when the set is not completely thread-safe
#endregion //Copied from Remove(XmlSchema schema, bool forceCompile)
// This code is copied from method:
// Add(string targetNamespace, XmlSchema schema)
// If you changed anything here go and change the same in Add(string targetNamespace, XmlSchema schema) method
#region Copied from Add(string targetNamespace, XmlSchema schema)
if (schema.ErrorCount != 0)
{ //Schema with parsing errors cannot be loaded
return originalSchema;
}
if (PreprocessSchema(ref schema, schema.TargetNamespace))
{ //No perf opt for already compiled schemas
// This code is copied from method:
// AddSchemaToSet(XmlSchema schema)
// If you changed anything here go and change the same in AddSchemaToSet(XmlSchema schema) method
#region Copied from AddSchemaToSet(XmlSchema schema)
//Add to targetNamespaces table
if (_targetNamespaces[tns] == null)
{
_targetNamespaces.Add(tns, tns);
}
if (_schemaForSchema == null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] != null)
{ //it has xs:anyType
_schemaForSchema = schema;
}
for (int i = 0; i < schema.ImportedSchemas.Count; ++i)
{ //Once preprocessed external schemas property is set
XmlSchema s = (XmlSchema)schema.ImportedSchemas[i];
if (!_schemas.ContainsKey(s.SchemaId))
{
_schemas.Add(s.SchemaId, s);
}
tns = GetTargetNamespace(s);
if (_targetNamespaces[tns] == null)
{
_targetNamespaces.Add(tns, tns);
}
if (_schemaForSchema == null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] != null)
{ //it has xs:anyType
_schemaForSchema = schema;
}
}
#endregion //Copied from AddSchemaToSet(XmlSchema schema)
return schema;
}
#endregion // Copied from Add(string targetNamespace, XmlSchema schema)
return originalSchema;
}
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.CopyTo"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void CopyTo(XmlSchema[] schemas, int index)
{
if (schemas == null)
throw new ArgumentNullException("schemas");
if (index < 0 || index > schemas.Length - 1)
throw new ArgumentOutOfRangeException("index");
_schemas.Values.CopyTo(schemas, index);
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Schemas1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public ICollection Schemas()
{
return _schemas.Values;
}
/// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Schemas1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public ICollection Schemas(String targetNamespace)
{
ArrayList tnsSchemas = new ArrayList();
XmlSchema currentSchema;
if (targetNamespace == null)
{
targetNamespace = string.Empty;
}
for (int i = 0; i < _schemas.Count; i++)
{
currentSchema = (XmlSchema)_schemas.GetByIndex(i);
if (GetTargetNamespace(currentSchema) == targetNamespace)
{
tnsSchemas.Add(currentSchema);
}
}
return tnsSchemas;
}
//Internal Methods
private XmlSchema Add(string targetNamespace, XmlSchema schema)
{
// Due to bug 644477 - this method is tightly coupled (THE CODE IS BASICALLY COPIED) to Reprocess
// method. If you change anything here *make sure* to update Reprocess method accordingly.
if (schema == null || schema.ErrorCount != 0)
{ //Schema with parsing errors cannot be loaded
return null;
}
// This code is copied to method:
// Reprocess(XmlSchema schema)
// If you changed anything here go and change the same in Reprocess(XmlSchema schema) method
if (PreprocessSchema(ref schema, targetNamespace))
{ //No perf opt for already compiled schemas
AddSchemaToSet(schema);
_isCompiled = false;
return schema;
}
return null;
}
#if TRUST_COMPILE_STATE
private void AddCompiledSchema(XmlSchema schema) {
if (schema.IsCompiledBySet ) { //trust compiled state always if it is not a chameleon schema
VerifyTables();
SchemaInfo newCompiledInfo = new SchemaInfo();
XmlSchemaObjectTable substitutionGroupsTable = null;
if (!AddToCompiledInfo(schema, newCompiledInfo, ref substitutionGroupsTable)) { //Error while adding main schema
return null;
}
foreach (XmlSchema impSchema in schema.ImportedSchemas) {
if (!AddToCompiledInfo(impSchema, newCompiledInfo, ref substitutionGroupsTable)) { //Error while adding imports
return null;
}
}
newCompiledInfo.Add(cachedCompiledInfo, eventHandler); //Add existing compiled info
cachedCompiledInfo = newCompiledInfo;
if (substitutionGroupsTable != null) {
ProcessNewSubstitutionGroups(substitutionGroupsTable, true);
}
if (schemas.Count == 0) { //If its the first compiled schema being added, then set doesnt need to be compiled
isCompiled = true;
compileAll = false;
}
AddSchemaToSet(schema);
return schema;
}
}
private bool AddToCompiledInfo(XmlSchema schema, SchemaInfo newCompiledInfo, ref XmlSchemaObjectTable substTable) {
//Add schema's compiled tables to the set
if (schema.BaseUri != null && schemaLocations[schema.BaseUri] == null) { //Update schemaLocations table
schemaLocations.Add(schema.BaseUri, schema);
}
foreach (XmlSchemaElement element in schema.Elements.Values) {
if(!AddToTable(elements, element.QualifiedName, element)) {
RemoveSchemaFromGlobalTables(schema);
return false;
}
XmlQualifiedName head = element.SubstitutionGroup;
if (!head.IsEmpty) {
if (substTable == null) {
substTable = new XmlSchemaObjectTable();
}
XmlSchemaSubstitutionGroup substitutionGroup = (XmlSchemaSubstitutionGroup)substTable[head];
if (substitutionGroup == null) {
substitutionGroup = new XmlSchemaSubstitutionGroup();
substitutionGroup.Examplar = head;
substTable.Add(head, substitutionGroup);
}
ArrayList members = substitutionGroup.Members;
if (!members.Contains(element)) { //Members might contain element if the same schema is included and imported through different paths. Imp, hence will be added to set directly
members.Add(element);
}
}
}
foreach (XmlSchemaAttribute attribute in schema.Attributes.Values) {
if (!AddToTable(attributes, attribute.QualifiedName, attribute)) {
RemoveSchemaFromGlobalTables(schema);
return false;
}
}
foreach (XmlSchemaType schemaType in schema.SchemaTypes.Values) {
if (!AddToTable(schemaTypes, schemaType.QualifiedName, schemaType)) {
RemoveSchemaFromGlobalTables(schema);
return false;
}
}
schema.AddCompiledInfo(newCompiledInfo);
return true;
}
#endif
//For use by the validator when loading schemaLocations in the instance
internal void Add(String targetNamespace, XmlReader reader, Hashtable validatedNamespaces)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
if (targetNamespace == null)
{
targetNamespace = string.Empty;
}
if (validatedNamespaces[targetNamespace] != null)
{
if (FindSchemaByNSAndUrl(new Uri(reader.BaseURI, UriKind.RelativeOrAbsolute), targetNamespace, null) != null)
{
return;
}
else
{
throw new XmlSchemaException(ResXml.Sch_ComponentAlreadySeenForNS, targetNamespace);
}
}
//Not locking set as this will not be accessible outside the validator
XmlSchema schema;
if (IsSchemaLoaded(new Uri(reader.BaseURI, UriKind.RelativeOrAbsolute), targetNamespace, out schema))
{
return;
}
else
{ //top-level schema not present for same url
schema = ParseSchema(targetNamespace, reader);
//Store the previous locations
DictionaryEntry[] oldLocations = new DictionaryEntry[_schemaLocations.Count];
_schemaLocations.CopyTo(oldLocations, 0);
//Add to set
Add(targetNamespace, schema);
if (schema.ImportedSchemas.Count > 0)
{ //Check imports
string tns;
for (int i = 0; i < schema.ImportedSchemas.Count; ++i)
{
XmlSchema impSchema = (XmlSchema)schema.ImportedSchemas[i];
tns = impSchema.TargetNamespace;
if (tns == null)
{
tns = string.Empty;
}
if (validatedNamespaces[tns] != null && (FindSchemaByNSAndUrl(impSchema.BaseUri, tns, oldLocations) == null))
{
RemoveRecursive(schema);
throw new XmlSchemaException(ResXml.Sch_ComponentAlreadySeenForNS, tns);
}
}
}
}
}
internal XmlSchema FindSchemaByNSAndUrl(Uri schemaUri, string ns, DictionaryEntry[] locationsTable)
{
if (schemaUri == null || schemaUri.OriginalString.Length == 0)
{
return null;
}
XmlSchema schema = null;
if (locationsTable == null)
{
schema = (XmlSchema)_schemaLocations[schemaUri];
}
else
{
for (int i = 0; i < locationsTable.Length; i++)
{
if (schemaUri.Equals(locationsTable[i].Key))
{
schema = (XmlSchema)locationsTable[i].Value;
break;
}
}
}
if (schema != null)
{
Debug.Assert(ns != null);
string tns = schema.TargetNamespace == null ? string.Empty : schema.TargetNamespace;
if (tns == ns)
{
return schema;
}
else if (tns == string.Empty)
{ //There could be a chameleon for same ns
// It is OK to pass in the schema we have found so far, since it must have the schemaUri we're looking for
// (we found it that way above) and it must be the original chameleon schema (the one without target ns)
// as we don't add the chameleon copies into the locations tables above.
Debug.Assert(schema.BaseUri.Equals(schemaUri));
ChameleonKey cKey = new ChameleonKey(ns, schema);
schema = (XmlSchema)_chameleonSchemas[cKey]; //Need not clone if a schema for that namespace already exists
}
else
{
schema = null;
}
}
return schema;
}
private void SetDtdProcessing(XmlReader reader)
{
if (reader.Settings != null)
{
_readerSettings.DtdProcessing = reader.Settings.DtdProcessing;
}
else
{
XmlTextReader v1Reader = reader as XmlTextReader;
if (v1Reader != null)
{
_readerSettings.DtdProcessing = v1Reader.DtdProcessing;
}
}
}
private void AddSchemaToSet(XmlSchema schema)
{
// Due to bug 644477 - this method is tightly coupled (THE CODE IS BASICALLY COPIED) to Reprocess
// method. If you change anything here *make sure* to update Reprocess method accordingly.
_schemas.Add(schema.SchemaId, schema);
//Add to targetNamespaces table
// This code is copied to method:
// Reprocess(XmlSchema schema)
// If you changed anything here go and change the same in Reprocess(XmlSchema schema) method
#region This code is copied to Reprocess(XmlSchema schema) method
string tns = GetTargetNamespace(schema);
if (_targetNamespaces[tns] == null)
{
_targetNamespaces.Add(tns, tns);
}
if (_schemaForSchema == null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] != null)
{ //it has xs:anyType
_schemaForSchema = schema;
}
for (int i = 0; i < schema.ImportedSchemas.Count; ++i)
{ //Once preprocessed external schemas property is set
XmlSchema s = (XmlSchema)schema.ImportedSchemas[i];
if (!_schemas.ContainsKey(s.SchemaId))
{
_schemas.Add(s.SchemaId, s);
}
tns = GetTargetNamespace(s);
if (_targetNamespaces[tns] == null)
{
_targetNamespaces.Add(tns, tns);
}
if (_schemaForSchema == null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] != null)
{ //it has xs:anyType
_schemaForSchema = schema;
}
}
#endregion // This code is copied to Reprocess(XmlSchema schema) method
}
private void ProcessNewSubstitutionGroups(XmlSchemaObjectTable substitutionGroupsTable, bool resolve)
{
foreach (XmlSchemaSubstitutionGroup substGroup in substitutionGroupsTable.Values)
{
if (resolve)
{ //Resolve substitutionGroups within this schema
ResolveSubstitutionGroup(substGroup, substitutionGroupsTable);
}
//Add or Merge new substitutionGroups with those that already exist in the set
XmlQualifiedName head = substGroup.Examplar;
XmlSchemaSubstitutionGroup oldSubstGroup = (XmlSchemaSubstitutionGroup)substitutionGroups[head];
if (oldSubstGroup != null)
{
for (int i = 0; i < substGroup.Members.Count; ++i)
{
if (!oldSubstGroup.Members.Contains(substGroup.Members[i]))
{
oldSubstGroup.Members.Add(substGroup.Members[i]);
}
}
}
else
{
AddToTable(substitutionGroups, head, substGroup);
}
}
}
private void ResolveSubstitutionGroup(XmlSchemaSubstitutionGroup substitutionGroup, XmlSchemaObjectTable substTable)
{
List<XmlSchemaElement> newMembers = null;
XmlSchemaElement headElement = (XmlSchemaElement)elements[substitutionGroup.Examplar];
if (substitutionGroup.Members.Contains(headElement))
{// already checked
return;
}
for (int i = 0; i < substitutionGroup.Members.Count; ++i)
{
XmlSchemaElement element = (XmlSchemaElement)substitutionGroup.Members[i];
//Chain to other head's that are members of this head's substGroup
XmlSchemaSubstitutionGroup g = (XmlSchemaSubstitutionGroup)substTable[element.QualifiedName];
if (g != null)
{
ResolveSubstitutionGroup(g, substTable);
for (int j = 0; j < g.Members.Count; ++j)
{
XmlSchemaElement element1 = (XmlSchemaElement)g.Members[j];
if (element1 != element)
{ //Exclude the head
if (newMembers == null)
{
newMembers = new List<XmlSchemaElement>();
}
newMembers.Add(element1);
}
}
}
}
if (newMembers != null)
{
for (int i = 0; i < newMembers.Count; ++i)
{
substitutionGroup.Members.Add(newMembers[i]);
}
}
substitutionGroup.Members.Add(headElement);
}
internal XmlSchema Remove(XmlSchema schema, bool forceCompile)
{
// Due to bug 644477 - this method is tightly coupled (THE CODE IS BASICALLY COPIED) to Reprocess
// method. If you change anything here *make sure* to update Reprocess method accordingly.
if (schema == null)
{
throw new ArgumentNullException("schema");
}
lock (InternalSyncObject)
{ //Need to lock here so that remove cannot be called while the set is being compiled
if (_schemas.ContainsKey(schema.SchemaId))
{
// This code is copied to method:
// Reprocess(XmlSchema schema)
// If you changed anything here go and change the same in Reprocess(XmlSchema schema) method
#region This code is copied to Reprocess(XmlSchema schema) method
if (forceCompile)
{
RemoveSchemaFromGlobalTables(schema);
RemoveSchemaFromCaches(schema);
}
_schemas.Remove(schema.SchemaId);
if (schema.BaseUri != null)
{
_schemaLocations.Remove(schema.BaseUri);
}
string tns = GetTargetNamespace(schema);
if (Schemas(tns).Count == 0)
{ //This is the only schema for that namespace
_targetNamespaces.Remove(tns);
}
if (forceCompile)
{
_isCompiled = false;
_compileAll = true; //Force compilation of the whole set; This is when the set is not completely thread-safe
}
return schema;
#endregion // This code is copied to Reprocess(XmlSchema schema) method
}
}
return null;
}
private void ClearTables()
{
GlobalElements.Clear();
GlobalAttributes.Clear();
GlobalTypes.Clear();
SubstitutionGroups.Clear();
TypeExtensions.Clear();
}
internal bool PreprocessSchema(ref XmlSchema schema, string targetNamespace)
{
Preprocessor prep = new Preprocessor(_nameTable, GetSchemaNames(_nameTable), _eventHandler, _compilationSettings);
prep.XmlResolver = _readerSettings.GetXmlResolver_CheckConfig();
prep.ReaderSettings = _readerSettings;
prep.SchemaLocations = _schemaLocations;
prep.ChameleonSchemas = _chameleonSchemas;
bool hasErrors = prep.Execute(schema, targetNamespace, true);
schema = prep.RootSchema; //For any root level chameleon cloned
return hasErrors;
}
internal XmlSchema ParseSchema(string targetNamespace, XmlReader reader)
{
XmlNameTable readerNameTable = reader.NameTable;
SchemaNames schemaNames = GetSchemaNames(readerNameTable);
Parser parser = new Parser(SchemaType.XSD, readerNameTable, schemaNames, _eventHandler);
parser.XmlResolver = _readerSettings.GetXmlResolver_CheckConfig();
SchemaType schemaType;
try
{
schemaType = parser.Parse(reader, targetNamespace);
}
catch (XmlSchemaException e)
{
SendValidationEvent(e, XmlSeverityType.Error);
return null;
}
return parser.XmlSchema;
}
internal void CopyFromCompiledSet(XmlSchemaSet otherSet)
{
XmlSchema currentSchema;
SortedList copyFromList = otherSet.SortedSchemas;
bool setIsCompiled = _schemas.Count == 0 ? true : false;
ArrayList existingSchemas = new ArrayList();
SchemaInfo newCompiledInfo = new SchemaInfo();
Uri baseUri;
for (int i = 0; i < copyFromList.Count; i++)
{
currentSchema = (XmlSchema)copyFromList.GetByIndex(i);
baseUri = currentSchema.BaseUri;
if (_schemas.ContainsKey(currentSchema.SchemaId) || (baseUri != null && baseUri.OriginalString.Length != 0 && _schemaLocations[baseUri] != null))
{
existingSchemas.Add(currentSchema);
continue;
}
_schemas.Add(currentSchema.SchemaId, currentSchema);
if (baseUri != null && baseUri.OriginalString.Length != 0)
{
_schemaLocations.Add(baseUri, currentSchema);
}
string tns = GetTargetNamespace(currentSchema);
if (_targetNamespaces[tns] == null)
{
_targetNamespaces.Add(tns, tns);
}
}
VerifyTables();
foreach (XmlSchemaElement element in otherSet.GlobalElements.Values)
{
if (!AddToTable(elements, element.QualifiedName, element))
{
goto RemoveAll;
}
}
foreach (XmlSchemaAttribute attribute in otherSet.GlobalAttributes.Values)
{
if (!AddToTable(attributes, attribute.QualifiedName, attribute))
{
goto RemoveAll;
}
}
foreach (XmlSchemaType schemaType in otherSet.GlobalTypes.Values)
{
if (!AddToTable(schemaTypes, schemaType.QualifiedName, schemaType))
{
goto RemoveAll;
}
}
//TODO get otherSet's substitutionGroups
ProcessNewSubstitutionGroups(otherSet.SubstitutionGroups, false);
newCompiledInfo.Add(_cachedCompiledInfo, _eventHandler); //Add all the items from the old to the new compiled object
newCompiledInfo.Add(otherSet.CompiledInfo, _eventHandler); //TODO: Throw error on conflicting types that are not from the same schema / baseUri
_cachedCompiledInfo = newCompiledInfo; //Replace the compiled info in the set after successful compilation
if (setIsCompiled)
{
_isCompiled = true;
_compileAll = false;
}
return;
RemoveAll:
foreach (XmlSchema schemaToRemove in copyFromList.Values)
{
if (!existingSchemas.Contains(schemaToRemove))
{
Remove(schemaToRemove, false);
}
}
foreach (XmlSchemaElement elementToRemove in otherSet.GlobalElements.Values)
{
if (!existingSchemas.Contains((XmlSchema)elementToRemove.Parent))
{
elements.Remove(elementToRemove.QualifiedName);
}
}
foreach (XmlSchemaAttribute attributeToRemove in otherSet.GlobalAttributes.Values)
{
if (!existingSchemas.Contains((XmlSchema)attributeToRemove.Parent))
{
attributes.Remove(attributeToRemove.QualifiedName);
}
}
foreach (XmlSchemaType schemaTypeToRemove in otherSet.GlobalTypes.Values)
{
if (!existingSchemas.Contains((XmlSchema)schemaTypeToRemove.Parent))
{
schemaTypes.Remove(schemaTypeToRemove.QualifiedName);
}
}
}
internal SchemaInfo CompiledInfo
{
get
{
return _cachedCompiledInfo;
}
}
internal XmlReaderSettings ReaderSettings
{
get
{
return _readerSettings;
}
}
internal XmlResolver GetResolver()
{
return _readerSettings.GetXmlResolver_CheckConfig();
}
internal ValidationEventHandler GetEventHandler()
{
return _eventHandler;
}
internal SchemaNames GetSchemaNames(XmlNameTable nt)
{
if (_nameTable != nt)
{
return new SchemaNames(nt);
}
else
{
if (_schemaNames == null)
{
_schemaNames = new SchemaNames(_nameTable);
}
return _schemaNames;
}
}
internal bool IsSchemaLoaded(Uri schemaUri, string targetNamespace, out XmlSchema schema)
{
schema = null;
if (targetNamespace == null)
{
targetNamespace = string.Empty;
}
if (GetSchemaByUri(schemaUri, out schema))
{
if (_schemas.ContainsKey(schema.SchemaId) && (targetNamespace.Length == 0 || targetNamespace == schema.TargetNamespace))
{ //schema is present in set
//Schema found
}
else if (schema.TargetNamespace == null)
{ //If schema not in set or namespace doesnt match, then it might be a chameleon
XmlSchema chameleonSchema = FindSchemaByNSAndUrl(schemaUri, targetNamespace, null);
if (chameleonSchema != null && _schemas.ContainsKey(chameleonSchema.SchemaId))
{
schema = chameleonSchema;
}
else
{
schema = Add(targetNamespace, schema);
}
}
else if (targetNamespace.Length != 0 && targetNamespace != schema.TargetNamespace)
{
SendValidationEvent(new XmlSchemaException(ResXml.Sch_MismatchTargetNamespaceEx, new string[] { targetNamespace, schema.TargetNamespace }), XmlSeverityType.Error);
schema = null;
}
else
{
//If here, schema not present in set but in loc and might be added in loc through an earlier include
//S.TNS != null && ( tns == null or tns == s.TNS)
AddSchemaToSet(schema);
}
return true; //Schema Found
}
return false;
}
internal bool GetSchemaByUri(Uri schemaUri, out XmlSchema schema)
{
schema = null;
if (schemaUri == null || schemaUri.OriginalString.Length == 0)
{
return false;
}
schema = (XmlSchema)_schemaLocations[schemaUri];
if (schema != null)
{
return true;
}
return false;
}
internal string GetTargetNamespace(XmlSchema schema)
{
return schema.TargetNamespace == null ? string.Empty : schema.TargetNamespace;
}
internal SortedList SortedSchemas
{
get
{
return _schemas;
}
}
internal bool CompileAll
{
get
{
return _compileAll;
}
}
//Private Methods
private void RemoveSchemaFromCaches(XmlSchema schema)
{
//Remove From ChameleonSchemas and schemaLocations cache
List<XmlSchema> reprocessList = new List<XmlSchema>();
schema.GetExternalSchemasList(reprocessList, schema);
for (int i = 0; i < reprocessList.Count; ++i)
{ //Remove schema from schemaLocations & chameleonSchemas tables
if (reprocessList[i].BaseUri != null && reprocessList[i].BaseUri.OriginalString.Length != 0)
{
_schemaLocations.Remove(reprocessList[i].BaseUri);
}
//Remove from chameleon table
ICollection chameleonKeys = _chameleonSchemas.Keys;
ArrayList removalList = new ArrayList();
foreach (ChameleonKey cKey in chameleonKeys)
{
if (cKey.chameleonLocation.Equals(reprocessList[i].BaseUri))
{
// The key will have the originalSchema set to null if the location was not empty
// otherwise we need to care about it as there may be more chameleon schemas without
// a base URI and we want to remove only those which were created as a clone of the one
// we're removing.
if (cKey.originalSchema == null || Ref.ReferenceEquals(cKey.originalSchema, reprocessList[i]))
{
removalList.Add(cKey);
}
}
}
for (int j = 0; j < removalList.Count; ++j)
{
_chameleonSchemas.Remove(removalList[j]);
}
}
}
private void RemoveSchemaFromGlobalTables(XmlSchema schema)
{
if (_schemas.Count == 0)
{
return;
}
VerifyTables();
foreach (XmlSchemaElement elementToRemove in schema.Elements.Values)
{
XmlSchemaElement elem = (XmlSchemaElement)elements[elementToRemove.QualifiedName];
if (elem == elementToRemove)
{
elements.Remove(elementToRemove.QualifiedName);
}
}
foreach (XmlSchemaAttribute attributeToRemove in schema.Attributes.Values)
{
XmlSchemaAttribute attr = (XmlSchemaAttribute)attributes[attributeToRemove.QualifiedName];
if (attr == attributeToRemove)
{
attributes.Remove(attributeToRemove.QualifiedName);
}
}
foreach (XmlSchemaType schemaTypeToRemove in schema.SchemaTypes.Values)
{
XmlSchemaType schemaType = (XmlSchemaType)schemaTypes[schemaTypeToRemove.QualifiedName];
if (schemaType == schemaTypeToRemove)
{
schemaTypes.Remove(schemaTypeToRemove.QualifiedName);
}
}
}
private bool AddToTable(XmlSchemaObjectTable table, XmlQualifiedName qname, XmlSchemaObject item)
{
if (qname.Name.Length == 0)
{
return true;
}
XmlSchemaObject existingObject = (XmlSchemaObject)table[qname];
if (existingObject != null)
{
if (existingObject == item || existingObject.SourceUri == item.SourceUri)
{
return true;
}
string code = string.Empty;
if (item is XmlSchemaComplexType)
{
code = ResXml.Sch_DupComplexType;
}
else if (item is XmlSchemaSimpleType)
{
code = ResXml.Sch_DupSimpleType;
}
else if (item is XmlSchemaElement)
{
code = ResXml.Sch_DupGlobalElement;
}
else if (item is XmlSchemaAttribute)
{
if (qname.Namespace == XmlReservedNs.NsXml)
{
XmlSchema schemaForXmlNS = Preprocessor.GetBuildInSchema();
XmlSchemaObject builtInAttribute = schemaForXmlNS.Attributes[qname];
if (existingObject == builtInAttribute)
{ //replace built-in one
table.Insert(qname, item);
return true;
}
else if (item == builtInAttribute)
{ //trying to overwrite customer's component with built-in, ignore built-in
return true;
}
}
code = ResXml.Sch_DupGlobalAttribute;
}
SendValidationEvent(new XmlSchemaException(code, qname.ToString()), XmlSeverityType.Error);
return false;
}
else
{
table.Add(qname, item);
return true;
}
}
private void VerifyTables()
{
if (elements == null)
{
elements = new XmlSchemaObjectTable();
}
if (attributes == null)
{
attributes = new XmlSchemaObjectTable();
}
if (schemaTypes == null)
{
schemaTypes = new XmlSchemaObjectTable();
}
if (substitutionGroups == null)
{
substitutionGroups = new XmlSchemaObjectTable();
}
}
private void InternalValidationCallback(object sender, ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Error)
{
throw e.Exception;
}
}
private void SendValidationEvent(XmlSchemaException e, XmlSeverityType severity)
{
if (_eventHandler != null)
{
_eventHandler(this, new ValidationEventArgs(e, severity));
}
else
{
throw e;
}
}
};
}
| |
/* ====================================================================
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.Collections.Generic;
using NPOI.POIFS.Common;
using NPOI.Util;
using NPOI.HWPF.Model.IO;
using System.IO;
using NPOI.HWPF.SPRM;
using System;
namespace NPOI.HWPF.Model
{
/**
* This class holds all of the character formatting properties.
*
* @author Ryan Ackley
*/
public class CHPBinTable
{
/** List of character properties.*/
internal List<CHPX> _textRuns = new List<CHPX>();
public CHPBinTable()
{
}
/**
* Constructor used to read a binTable in from a Word document.
*
* @param documentStream
* @param tableStream
* @param offset
* @param size
* @param fcMin
*/
[Obsolete]
public CHPBinTable(byte[] documentStream, byte[] tableStream, int offset,
int size, int fcMin, TextPieceTable tpt):this( documentStream, tableStream, offset, size, tpt )
{
}
/**
* Constructor used to read a binTable in from a Word document.
*/
public CHPBinTable(byte[] documentStream, byte[] tableStream, int offset,
int size, CharIndexTranslator translator)
{
PlexOfCps binTable = new PlexOfCps(tableStream, offset, size, 4);
int length = binTable.Length;
for (int x = 0; x < length; x++)
{
GenericPropertyNode node = binTable.GetProperty(x);
int pageNum = LittleEndian.GetInt(node.Bytes);
int pageOffset = POIFSConstants.SMALLER_BIG_BLOCK_SIZE * pageNum;
CHPFormattedDiskPage cfkp = new CHPFormattedDiskPage(documentStream,
pageOffset, translator);
int fkpSize = cfkp.Size();
for (int y = 0; y < fkpSize; y++)
{
CHPX chpx = cfkp.GetCHPX(y);
if (chpx != null)
_textRuns.Add(chpx);
}
}
}
internal class CHPXToFileComparer : IComparer<CHPX>
{
Dictionary<CHPX, int> list;
public CHPXToFileComparer(Dictionary<CHPX, int> list)
{
this.list = list;
}
#region IComparer<CHPX> Members
public int Compare(CHPX o1, CHPX o2)
{
int i1 = list[o1];
int i2 = list[o2];
return i1.CompareTo(i2);
}
#endregion
}
private static POILogger logger = POILogFactory
.GetLogger(typeof(CHPBinTable));
public void Rebuild(ComplexFileTable complexFileTable)
{
long start = DateTime.Now.Ticks;
if (complexFileTable != null)
{
SprmBuffer[] sprmBuffers = complexFileTable.GetGrpprls();
// adding CHPX from fast-saved SPRMs
foreach (TextPiece textPiece in complexFileTable.GetTextPieceTable()
.TextPieces)
{
PropertyModifier prm = textPiece.PieceDescriptor.Prm;
if (!prm.IsComplex())
continue;
int igrpprl = prm.GetIgrpprl();
if (igrpprl < 0 || igrpprl >= sprmBuffers.Length)
{
logger.Log(POILogger.WARN, textPiece
+ "'s PRM references to unknown grpprl");
continue;
}
bool hasChp = false;
SprmBuffer sprmBuffer = sprmBuffers[igrpprl];
for (SprmIterator iterator = sprmBuffer.Iterator(); ; iterator
.HasNext())
{
SprmOperation sprmOperation = iterator.Next();
if (sprmOperation.Type == SprmOperation.TYPE_CHP)
{
hasChp = true;
break;
}
}
if (hasChp)
{
SprmBuffer newSprmBuffer;
newSprmBuffer = (SprmBuffer)sprmBuffer.Clone();
CHPX chpx = new CHPX(textPiece.Start,
textPiece.End, newSprmBuffer);
_textRuns.Add(chpx);
}
}
logger.Log(POILogger.DEBUG,
"Merged with CHPX from complex file table in ",
DateTime.Now.Ticks - start,
" ms (", _textRuns.Count,
" elements in total)");
start = DateTime.Now.Ticks;
}
List<CHPX> oldChpxSortedByStartPos = new List<CHPX>(_textRuns);
oldChpxSortedByStartPos.Sort(
(IComparer<CHPX>)PropertyNode.CHPXComparator.instance);
logger.Log(POILogger.DEBUG, "CHPX sorted by start position in ",
DateTime.Now.Ticks - start, " ms");
start = DateTime.Now.Ticks;
Dictionary<CHPX, int> chpxToFileOrder = new Dictionary<CHPX, int>();
int counter = 0;
foreach (CHPX chpx in _textRuns)
{
chpxToFileOrder.Add(chpx, counter++);
}
logger.Log(POILogger.DEBUG, "CHPX's order map created in ",
DateTime.Now.Ticks - start, " ms");
start = DateTime.Now.Ticks;
List<int> textRunsBoundariesList;
List<int> textRunsBoundariesSet = new List<int>();
foreach (CHPX chpx in _textRuns)
{
textRunsBoundariesSet.Add(chpx.Start);
textRunsBoundariesSet.Add(chpx.End);
}
textRunsBoundariesSet.Remove(0);
textRunsBoundariesList = new List<int>(
textRunsBoundariesSet);
textRunsBoundariesList.Sort();
logger.Log(POILogger.DEBUG, "Texts CHPX boundaries collected in ",
DateTime.Now.Ticks - start, " ms");
start = DateTime.Now.Ticks;
List<CHPX> newChpxs = new List<CHPX>();
int lastTextRunStart = 0;
foreach (int objBoundary in textRunsBoundariesList)
{
int boundary = objBoundary;
int startInclusive = lastTextRunStart;
int endExclusive = boundary;
lastTextRunStart = endExclusive;
int startPosition = BinarySearch(oldChpxSortedByStartPos, boundary);
startPosition = Math.Abs(startPosition);
while (startPosition >= oldChpxSortedByStartPos.Count)
startPosition--;
while (startPosition > 0
&& oldChpxSortedByStartPos[startPosition].Start >= boundary)
startPosition--;
List<CHPX> chpxs = new List<CHPX>();
for (int c = startPosition; c < oldChpxSortedByStartPos.Count; c++)
{
CHPX chpx = oldChpxSortedByStartPos[c];
if (boundary < chpx.Start)
break;
int left = Math.Max(startInclusive, chpx.Start);
int right = Math.Min(endExclusive, chpx.End);
if (left < right)
{
chpxs.Add(chpx);
}
}
if (chpxs.Count == 0)
{
logger.Log(POILogger.WARN, "Text piece [",
startInclusive, "; ",
endExclusive,
") has no CHPX. Creating new one.");
// create it manually
CHPX chpx = new CHPX(startInclusive, endExclusive,
new SprmBuffer(0));
newChpxs.Add(chpx);
continue;
}
if (chpxs.Count == 1)
{
// can we reuse existing?
CHPX existing = chpxs[0];
if (existing.Start == startInclusive
&& existing.End == endExclusive)
{
newChpxs.Add(existing);
continue;
}
}
CHPXToFileComparer chpxFileOrderComparator = new CHPXToFileComparer(chpxToFileOrder);
chpxs.Sort(chpxFileOrderComparator);
SprmBuffer sprmBuffer = new SprmBuffer(0);
foreach (CHPX chpx in chpxs)
{
sprmBuffer.Append(chpx.GetGrpprl(), 0);
}
CHPX newChpx = new CHPX(startInclusive, endExclusive, sprmBuffer);
newChpxs.Add(newChpx);
continue;
}
this._textRuns = new List<CHPX>(newChpxs);
logger.Log(POILogger.DEBUG, "CHPX rebuilded in ",
DateTime.Now.Ticks - start, " ms (",
_textRuns.Count, " elements)");
start = DateTime.Now.Ticks;
CHPX previous = null;
for (List<CHPX>.Enumerator iterator = _textRuns.GetEnumerator(); iterator
.MoveNext(); )
{
CHPX current = iterator.Current;
if (previous == null)
{
previous = current;
continue;
}
if (previous.End == current.Start
&& Arrays
.Equals(previous.GetGrpprl(), current.GetGrpprl()))
{
previous.End = current.End;
_textRuns.Remove(current);
continue;
}
previous = current;
}
logger.Log(POILogger.DEBUG, "CHPX compacted in ",
DateTime.Now.Ticks - start, " ms (",
_textRuns.Count, " elements)");
}
private static int BinarySearch(List<CHPX> chpxs, int startPosition)
{
int low = 0;
int high = chpxs.Count - 1;
while (low <= high)
{
int mid = (low + high) >> 1;
CHPX midVal = chpxs[mid];
int midValue = midVal.Start;
if (midValue < startPosition)
low = mid + 1;
else if (midValue > startPosition)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
public void AdjustForDelete(int listIndex, int offset, int Length)
{
int size = _textRuns.Count;
int endMark = offset + Length;
int endIndex = listIndex;
CHPX chpx = _textRuns[endIndex];
while (chpx.End < endMark)
{
chpx = _textRuns[++endIndex];
}
if (listIndex == endIndex)
{
chpx = _textRuns[endIndex];
chpx.End = ((chpx.End - endMark) + offset);
}
else
{
chpx = _textRuns[listIndex];
chpx.End = (offset);
for (int x = listIndex + 1; x < endIndex; x++)
{
chpx = _textRuns[x];
chpx.Start = (offset);
chpx.End = (offset);
}
chpx = _textRuns[endIndex];
chpx.End = ((chpx.End - endMark) + offset);
}
for (int x = endIndex + 1; x < size; x++)
{
chpx = _textRuns[x];
chpx.Start = (chpx.Start - Length);
chpx.End = (chpx.End - Length);
}
}
public void Insert(int listIndex, int cpStart, SprmBuffer buf)
{
CHPX insertChpx = new CHPX(0, 0, buf);
// Ensure character OffSets are really characters
insertChpx.Start = (cpStart);
insertChpx.End = (cpStart);
if (listIndex == _textRuns.Count)
{
_textRuns.Add(insertChpx);
}
else
{
CHPX chpx = _textRuns[listIndex];
if (chpx.Start < cpStart)
{
// Copy the properties of the one before to afterwards
// Will go:
// Original, until insert at point
// New one
// Clone of original, on to the old end
CHPX clone = new CHPX(0, 0, chpx.GetSprmBuf());
// Again ensure Contains character based OffSets no matter what
clone.Start = (cpStart);
clone.End = (chpx.End);
chpx.End = (cpStart);
_textRuns.Insert(listIndex + 1, insertChpx);
_textRuns.Insert(listIndex + 2, clone);
}
else
{
_textRuns.Insert(listIndex, insertChpx);
}
}
}
public void AdjustForInsert(int listIndex, int Length)
{
int size = _textRuns.Count;
CHPX chpx = _textRuns[listIndex];
chpx.End = (chpx.End + Length);
for (int x = listIndex + 1; x < size; x++)
{
chpx = _textRuns[x];
chpx.Start = (chpx.Start + Length);
chpx.End = (chpx.End + Length);
}
}
public List<CHPX> GetTextRuns()
{
return _textRuns;
}
public void WriteTo(HWPFFileSystem sys, int fcMin)
{
HWPFStream docStream = sys.GetStream("WordDocument");
Stream tableStream = sys.GetStream("1Table");
PlexOfCps binTable = new PlexOfCps(4);
// each FKP must start on a 512 byte page.
int docOffset = docStream.Offset;
int mod = docOffset % POIFSConstants.SMALLER_BIG_BLOCK_SIZE;
if (mod != 0)
{
byte[] pAdding = new byte[POIFSConstants.SMALLER_BIG_BLOCK_SIZE - mod];
docStream.Write(pAdding);
}
// get the page number for the first fkp
docOffset = docStream.Offset;
int pageNum = docOffset / POIFSConstants.SMALLER_BIG_BLOCK_SIZE;
// get the ending fc
int endingFc = ((PropertyNode)_textRuns[_textRuns.Count - 1]).End;
endingFc += fcMin;
List<CHPX> overflow = _textRuns;
do
{
PropertyNode startingProp = (PropertyNode)overflow[0];
int start = startingProp.Start + fcMin;
CHPFormattedDiskPage cfkp = new CHPFormattedDiskPage();
cfkp.Fill(overflow);
byte[] bufFkp = cfkp.ToArray(fcMin);
docStream.Write(bufFkp);
overflow = cfkp.GetOverflow();
int end = endingFc;
if (overflow != null)
{
end = ((PropertyNode)overflow[0]).Start + fcMin;
}
byte[] intHolder = new byte[4];
LittleEndian.PutInt(intHolder, pageNum++);
binTable.AddProperty(new GenericPropertyNode(start, end, intHolder));
}
while (overflow != null);
byte[] bytes = binTable.ToByteArray();
tableStream.Write(bytes, 0, bytes.Length);
}
}
}
| |
/*
* 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 Directory = Lucene.Net.Store.Directory;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using StringHelper = Lucene.Net.Util.StringHelper;
using UnicodeUtil = Lucene.Net.Util.UnicodeUtil;
namespace Lucene.Net.Index
{
sealed class TermVectorsWriter
{
private IndexOutput tvx = null, tvd = null, tvf = null;
private FieldInfos fieldInfos;
internal UnicodeUtil.UTF8Result[] utf8Results = new UnicodeUtil.UTF8Result[]{new UnicodeUtil.UTF8Result(), new UnicodeUtil.UTF8Result()};
public TermVectorsWriter(Directory directory, System.String segment, FieldInfos fieldInfos)
{
// Open files for TermVector storage
tvx = directory.CreateOutput(segment + "." + IndexFileNames.VECTORS_INDEX_EXTENSION);
tvx.WriteInt(TermVectorsReader.FORMAT_CURRENT);
tvd = directory.CreateOutput(segment + "." + IndexFileNames.VECTORS_DOCUMENTS_EXTENSION);
tvd.WriteInt(TermVectorsReader.FORMAT_CURRENT);
tvf = directory.CreateOutput(segment + "." + IndexFileNames.VECTORS_FIELDS_EXTENSION);
tvf.WriteInt(TermVectorsReader.FORMAT_CURRENT);
this.fieldInfos = fieldInfos;
}
/// <summary> Add a complete document specified by all its term vectors. If document has no
/// term vectors, add value for tvx.
///
/// </summary>
/// <param name="vectors">
/// </param>
/// <throws> IOException </throws>
public void AddAllDocVectors(TermFreqVector[] vectors)
{
tvx.WriteLong(tvd.GetFilePointer());
tvx.WriteLong(tvf.GetFilePointer());
if (vectors != null)
{
int numFields = vectors.Length;
tvd.WriteVInt(numFields);
long[] fieldPointers = new long[numFields];
for (int i = 0; i < numFields; i++)
{
fieldPointers[i] = tvf.GetFilePointer();
int fieldNumber = fieldInfos.FieldNumber(vectors[i].GetField());
// 1st pass: write field numbers to tvd
tvd.WriteVInt(fieldNumber);
int numTerms = vectors[i].Size();
tvf.WriteVInt(numTerms);
TermPositionVector tpVector;
byte bits;
bool storePositions;
bool storeOffsets;
if (vectors[i] is TermPositionVector)
{
// May have positions & offsets
tpVector = (TermPositionVector) vectors[i];
storePositions = tpVector.Size() > 0 && tpVector.GetTermPositions(0) != null;
storeOffsets = tpVector.Size() > 0 && tpVector.GetOffsets(0) != null;
bits = (byte) ((storePositions?TermVectorsReader.STORE_POSITIONS_WITH_TERMVECTOR: (byte) 0) + (storeOffsets?TermVectorsReader.STORE_OFFSET_WITH_TERMVECTOR: (byte) 0));
}
else
{
tpVector = null;
bits = 0;
storePositions = false;
storeOffsets = false;
}
tvf.WriteVInt(bits);
System.String[] terms = vectors[i].GetTerms();
int[] freqs = vectors[i].GetTermFrequencies();
int utf8Upto = 0;
utf8Results[1].length = 0;
for (int j = 0; j < numTerms; j++)
{
UnicodeUtil.UTF16toUTF8(terms[j], 0, terms[j].Length, utf8Results[utf8Upto]);
int start = StringHelper.BytesDifference(utf8Results[1 - utf8Upto].result, utf8Results[1 - utf8Upto].length, utf8Results[utf8Upto].result, utf8Results[utf8Upto].length);
int length = utf8Results[utf8Upto].length - start;
tvf.WriteVInt(start); // write shared prefix length
tvf.WriteVInt(length); // write delta length
tvf.WriteBytes(utf8Results[utf8Upto].result, start, length); // write delta bytes
utf8Upto = 1 - utf8Upto;
int termFreq = freqs[j];
tvf.WriteVInt(termFreq);
if (storePositions)
{
int[] positions = tpVector.GetTermPositions(j);
if (positions == null)
throw new System.SystemException("Trying to write positions that are null!");
System.Diagnostics.Debug.Assert(positions.Length == termFreq);
// use delta encoding for positions
int lastPosition = 0;
for (int k = 0; k < positions.Length; k++)
{
int position = positions[k];
tvf.WriteVInt(position - lastPosition);
lastPosition = position;
}
}
if (storeOffsets)
{
TermVectorOffsetInfo[] offsets = tpVector.GetOffsets(j);
if (offsets == null)
throw new System.SystemException("Trying to write offsets that are null!");
System.Diagnostics.Debug.Assert(offsets.Length == termFreq);
// use delta encoding for offsets
int lastEndOffset = 0;
for (int k = 0; k < offsets.Length; k++)
{
int startOffset = offsets[k].GetStartOffset();
int endOffset = offsets[k].GetEndOffset();
tvf.WriteVInt(startOffset - lastEndOffset);
tvf.WriteVInt(endOffset - startOffset);
lastEndOffset = endOffset;
}
}
}
}
// 2nd pass: write field pointers to tvd
if (numFields > 1)
{
long lastFieldPointer = fieldPointers[0];
for (int i = 1; i < numFields; i++)
{
long fieldPointer = fieldPointers[i];
tvd.WriteVLong(fieldPointer - lastFieldPointer);
lastFieldPointer = fieldPointer;
}
}
}
else
tvd.WriteVInt(0);
}
/// <summary> Do a bulk copy of numDocs documents from reader to our
/// streams. This is used to expedite merging, if the
/// field numbers are congruent.
/// </summary>
internal void AddRawDocuments(TermVectorsReader reader, int[] tvdLengths, int[] tvfLengths, int numDocs)
{
long tvdPosition = tvd.GetFilePointer();
long tvfPosition = tvf.GetFilePointer();
long tvdStart = tvdPosition;
long tvfStart = tvfPosition;
for (int i = 0; i < numDocs; i++)
{
tvx.WriteLong(tvdPosition);
tvdPosition += tvdLengths[i];
tvx.WriteLong(tvfPosition);
tvfPosition += tvfLengths[i];
}
tvd.CopyBytes(reader.GetTvdStream(), tvdPosition - tvdStart);
tvf.CopyBytes(reader.GetTvfStream(), tvfPosition - tvfStart);
System.Diagnostics.Debug.Assert(tvd.GetFilePointer() == tvdPosition);
System.Diagnostics.Debug.Assert(tvf.GetFilePointer() == tvfPosition);
}
/// <summary>Close all streams. </summary>
internal void Close()
{
// make an effort to close all streams we can but remember and re-throw
// the first exception encountered in this process
System.IO.IOException keep = null;
if (tvx != null)
try
{
tvx.Close();
}
catch (System.IO.IOException e)
{
if (keep == null)
keep = e;
}
if (tvd != null)
try
{
tvd.Close();
}
catch (System.IO.IOException e)
{
if (keep == null)
keep = e;
}
if (tvf != null)
try
{
tvf.Close();
}
catch (System.IO.IOException e)
{
if (keep == null)
keep = e;
}
if (keep != null)
{
throw new System.IO.IOException(keep.StackTrace);
}
}
}
}
| |
using System;
using System.Threading;
using Microsoft.Extensions.Logging;
using Orleans.Messaging;
using Orleans.Serialization;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Hosting;
namespace Orleans.Runtime.Messaging
{
internal class MessageCenter : ISiloMessageCenter, IDisposable
{
private Gateway Gateway { get; set; }
private IncomingMessageAcceptor ima;
private readonly ILogger log;
private Action<Message> rerouteHandler;
internal Func<Message, bool> ShouldDrop;
// ReSharper disable NotAccessedField.Local
private IntValueStatistic sendQueueLengthCounter;
private IntValueStatistic receiveQueueLengthCounter;
// ReSharper restore NotAccessedField.Local
internal IOutboundMessageQueue OutboundQueue { get; set; }
internal IInboundMessageQueue InboundQueue { get; set; }
internal SocketManager SocketManager;
private readonly SerializationManager serializationManager;
private readonly MessageFactory messageFactory;
private readonly ILoggerFactory loggerFactory;
private readonly ExecutorService executorService;
private readonly Action<Message>[] localMessageHandlers;
internal bool IsBlockingApplicationMessages { get; private set; }
public bool IsProxying { get { return Gateway != null; } }
public bool TryDeliverToProxy(Message msg)
{
return msg.TargetGrain.IsClient && Gateway != null && Gateway.TryDeliverToProxy(msg);
}
// This is determined by the IMA but needed by the OMS, and so is kept here in the message center itself.
public SiloAddress MyAddress { get; private set; }
public MessageCenter(
ILocalSiloDetails siloDetails,
IOptions<EndpointOptions> endpointOptions,
IOptions<SiloMessagingOptions> messagingOptions,
IOptions<NetworkingOptions> networkingOptions,
SerializationManager serializationManager,
MessageFactory messageFactory,
Factory<MessageCenter, Gateway> gatewayFactory,
ExecutorService executorService,
ILoggerFactory loggerFactory)
{
this.loggerFactory = loggerFactory;
this.log = loggerFactory.CreateLogger<MessageCenter>();
this.serializationManager = serializationManager;
this.messageFactory = messageFactory;
this.executorService = executorService;
this.MyAddress = siloDetails.SiloAddress;
this.Initialize(endpointOptions, messagingOptions, networkingOptions);
if (siloDetails.GatewayAddress != null)
{
Gateway = gatewayFactory(this);
}
localMessageHandlers = new Action<Message>[Enum.GetValues(typeof(Message.Categories)).Length];
}
private void Initialize(IOptions<EndpointOptions> endpointOptions, IOptions<SiloMessagingOptions> messagingOptions, IOptions<NetworkingOptions> networkingOptions)
{
if(log.IsEnabled(LogLevel.Trace)) log.Trace("Starting initialization.");
SocketManager = new SocketManager(networkingOptions, this.loggerFactory);
var listeningEndpoint = endpointOptions.Value.GetListeningSiloEndpoint();
ima = new IncomingMessageAcceptor(this, listeningEndpoint, SocketDirection.SiloToSilo, this.messageFactory, this.serializationManager, this.executorService, this.loggerFactory);
InboundQueue = new InboundMessageQueue(this.loggerFactory);
OutboundQueue = new OutboundMessageQueue(this, messagingOptions, this.serializationManager, this.executorService, this.loggerFactory);
sendQueueLengthCounter = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGE_CENTER_SEND_QUEUE_LENGTH, () => SendQueueLength);
receiveQueueLengthCounter = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGE_CENTER_RECEIVE_QUEUE_LENGTH, () => ReceiveQueueLength);
if (log.IsEnabled(LogLevel.Trace)) log.Trace("Completed initialization.");
}
public void Start()
{
IsBlockingApplicationMessages = false;
ima.Start();
OutboundQueue.Start();
}
public void StartGateway(ClientObserverRegistrar clientRegistrar)
{
if (Gateway != null)
Gateway.Start(clientRegistrar);
}
public void PrepareToStop()
{
}
public void Stop()
{
IsBlockingApplicationMessages = true;
try
{
ima.Stop();
}
catch (Exception exc)
{
log.Error(ErrorCode.Runtime_Error_100108, "Stop failed.", exc);
}
StopAcceptingClientMessages();
try
{
OutboundQueue.Stop();
}
catch (Exception exc)
{
log.Error(ErrorCode.Runtime_Error_100110, "Stop failed.", exc);
}
try
{
SocketManager.Stop();
}
catch (Exception exc)
{
log.Error(ErrorCode.Runtime_Error_100111, "Stop failed.", exc);
}
}
public void StopAcceptingClientMessages()
{
if (log.IsEnabled(LogLevel.Debug)) log.Debug("StopClientMessages");
if (Gateway == null) return;
try
{
Gateway.Stop();
}
catch (Exception exc) { log.Error(ErrorCode.Runtime_Error_100109, "Stop failed.", exc); }
Gateway = null;
}
public Action<Message> RerouteHandler
{
set
{
if (rerouteHandler != null)
throw new InvalidOperationException("MessageCenter RerouteHandler already set");
rerouteHandler = value;
}
}
public void RerouteMessage(Message message)
{
if (rerouteHandler != null)
rerouteHandler(message);
else
SendMessage(message);
}
public Action<Message> SniffIncomingMessage
{
set
{
ima.SniffIncomingMessage = value;
}
}
public Func<SiloAddress, bool> SiloDeadOracle { get; set; }
public void SendMessage(Message msg)
{
// Note that if we identify or add other grains that are required for proper stopping, we will need to treat them as we do the membership table grain here.
if (IsBlockingApplicationMessages && (msg.Category == Message.Categories.Application) && (msg.Result != Message.ResponseTypes.Rejection)
&& !Constants.SystemMembershipTableId.Equals(msg.TargetGrain))
{
// Drop the message on the floor if it's an application message that isn't a rejection
}
else
{
if (msg.SendingSilo == null)
msg.SendingSilo = MyAddress;
OutboundQueue.SendMessage(msg);
}
}
public bool TrySendLocal(Message message)
{
if (!message.TargetSilo.Equals(MyAddress))
{
return false;
}
if (log.IsEnabled(LogLevel.Trace)) log.Trace("Message has been looped back to this silo: {0}", message);
MessagingStatisticsGroup.LocalMessagesSent.Increment();
var localHandler = localMessageHandlers[(int) message.Category];
if (localHandler != null)
{
localHandler(message);
}
else
{
InboundQueue.PostMessage(message);
}
return true;
}
internal void SendRejection(Message msg, Message.RejectionTypes rejectionType, string reason)
{
MessagingStatisticsGroup.OnRejectedMessage(msg);
if (string.IsNullOrEmpty(reason)) reason = string.Format("Rejection from silo {0} - Unknown reason.", MyAddress);
Message error = this.messageFactory.CreateRejectionResponse(msg, rejectionType, reason);
// rejection msgs are always originated in the local silo, they are never remote.
InboundQueue.PostMessage(error);
}
public Message WaitMessage(Message.Categories type, CancellationToken ct)
{
return InboundQueue.WaitMessage(type);
}
public void RegisterLocalMessageHandler(Message.Categories category, Action<Message> handler)
{
localMessageHandlers[(int) category] = handler;
}
public void Dispose()
{
if (ima != null)
{
ima.Dispose();
ima = null;
}
InboundQueue?.Dispose();
OutboundQueue?.Dispose();
GC.SuppressFinalize(this);
}
public int SendQueueLength { get { return OutboundQueue.Count; } }
public int ReceiveQueueLength { get { return InboundQueue.Count; } }
/// <summary>
/// Indicates that application messages should be blocked from being sent or received.
/// This method is used by the "fast stop" process.
/// <para>
/// Specifically, all outbound application messages are dropped, except for rejections and messages to the membership table grain.
/// Inbound application requests are rejected, and other inbound application messages are dropped.
/// </para>
/// </summary>
public void BlockApplicationMessages()
{
if(log.IsEnabled(LogLevel.Debug)) log.Debug("BlockApplicationMessages");
IsBlockingApplicationMessages = true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace Spark.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.
/******************************************************************************
* 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 BroadcastScalarToVector128Int32()
{
var test = new SimpleUnaryOpTest__BroadcastScalarToVector128Int32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.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 (Sse2.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();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.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 class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__BroadcastScalarToVector128Int32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int32> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__BroadcastScalarToVector128Int32 testClass)
{
var result = Avx2.BroadcastScalarToVector128(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__BroadcastScalarToVector128Int32 testClass)
{
fixed (Vector128<Int32>* pFld1 = &_fld1)
{
var result = Avx2.BroadcastScalarToVector128(
Sse2.LoadVector128((Int32*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Vector128<Int32> _clsVar1;
private Vector128<Int32> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__BroadcastScalarToVector128Int32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public SimpleUnaryOpTest__BroadcastScalarToVector128Int32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.BroadcastScalarToVector128(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.BroadcastScalarToVector128(
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.BroadcastScalarToVector128(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128), new Type[] { typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128), new Type[] { typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128), new Type[] { typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.BroadcastScalarToVector128(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int32>* pClsVar1 = &_clsVar1)
{
var result = Avx2.BroadcastScalarToVector128(
Sse2.LoadVector128((Int32*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var result = Avx2.BroadcastScalarToVector128(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var result = Avx2.BroadcastScalarToVector128(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr));
var result = Avx2.BroadcastScalarToVector128(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__BroadcastScalarToVector128Int32();
var result = Avx2.BroadcastScalarToVector128(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__BroadcastScalarToVector128Int32();
fixed (Vector128<Int32>* pFld1 = &test._fld1)
{
var result = Avx2.BroadcastScalarToVector128(
Sse2.LoadVector128((Int32*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.BroadcastScalarToVector128(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int32>* pFld1 = &_fld1)
{
var result = Avx2.BroadcastScalarToVector128(
Sse2.LoadVector128((Int32*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.BroadcastScalarToVector128(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.BroadcastScalarToVector128(
Sse2.LoadVector128((Int32*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> op1, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (firstOp[0] != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((firstOp[0] != result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.BroadcastScalarToVector128)}<Int32>(Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
namespace RJP.MultiUrlPicker.Models
{
using System;
using Newtonsoft.Json.Linq;
using Umbraco.Core.Models;
using Umbraco.Core;
using Umbraco.Web;
using Umbraco.Web.Extensions;
using Umbraco.Core.Models.PublishedContent;
public class Link
{
private readonly JToken _linkItem;
private bool _publishedContentInitialized = false;
private string _name;
private string _url;
private string _target;
private bool? _deleted;
private LinkType? _linkType;
private IPublishedContent _content;
private Udi _udi;
private int? _id;
public Link(JToken linkItem)
{
_linkItem = linkItem;
}
private IPublishedContent PublishedContent
{
get
{
InitPublishedContent();
return _content;
}
}
[Obsolete("Use Udi instead")]
public int? Id
{
get
{
if (_id == null)
{
_id = _linkItem.Value<int?>("id");
if (!_id.HasValue)
{
InitPublishedContent();
}
}
return _id;
}
}
public Udi Udi
{
get
{
if (_udi == null)
{
if (!Udi.TryParse(_linkItem.Value<string>("udi"), out _udi))
{
InitPublishedContent();
}
}
return _udi;
}
}
public string Name
{
get
{
if (string.IsNullOrEmpty(_name))
{
_name = _linkItem.Value<string>("name");
}
return _name;
}
}
internal bool Deleted
{
get
{
if (_deleted == null)
{
if (Id.HasValue || Udi != null)
{
_deleted = PublishedContent == null;
}
else
{
_deleted = false;
}
}
return (bool)_deleted;
}
}
public string Url
{
get
{
if (string.IsNullOrEmpty(_url))
{
_url = PublishedContent?.Url ?? _linkItem.Value<string>("url");
var qs = _linkItem.Value<string>("querystring");
if (!string.IsNullOrWhiteSpace(qs))
{
_url += qs;
}
}
return _url;
}
}
public string Target
{
get
{
if (string.IsNullOrEmpty(_target))
{
_target = _linkItem.Value<string>("target");
}
return _target == string.Empty ? null : _target;
}
}
public LinkType Type
{
get
{
if (_linkType == null)
{
if (Udi != null)
{
if (Udi.EntityType == Constants.UdiEntityType.Media)
{
_linkType = LinkType.Media;
}
else
{
_linkType = LinkType.Content;
}
}
else
{
_linkType = LinkType.External;
}
}
return _linkType.Value;
}
}
private void InitPublishedContent()
{
if (!_publishedContentInitialized)
{
_publishedContentInitialized = true;
if (UmbracoContext.Current == null)
{
return;
}
if (Udi.TryParse(_linkItem.Value<string>("udi"), out _udi))
{
_content = _udi.ToPublishedContent();
_id = _content?.Id;
}
else
{
// there were no Udi so let's try the legacy way
_id = _linkItem.Value<int?>("id");
if (_id.HasValue)
{
var helper = new UmbracoHelper(UmbracoContext.Current);
if (_linkItem.Value<bool>("isMedia"))
{
_content = helper.TypedMedia(_id.Value);
}
else
{
_content = helper.TypedContent(_id.Value);
}
SetUdi();
}
}
}
}
private void SetUdi()
{
if (_content != null && _udi == null)
{
Guid? key = _content.GetKey();
if (key == Guid.Empty)
{
// if the key is Guid.Empty the model might be created by the ModelsBuilder,
// if so it, by default, derives from PublishedContentModel.
// By calling UnWrap() we get the original content, which probably implements
// IPublishedContentWithKey, so we can get the key
key = (_content as PublishedContentWrapped)?.Unwrap().GetKey();
}
if (key.HasValue && key != Guid.Empty)
{
string udiType = _content.ItemType == PublishedItemType.Media ?
Constants.UdiEntityType.Media :
Constants.UdiEntityType.Document;
_udi = Udi.Create(udiType, key.Value);
}
}
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoad.Business.ERLevel
{
/// <summary>
/// A11_City_Child (editable child object).<br/>
/// This is a generated base class of <see cref="A11_City_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="A10_City"/> collection.
/// </remarks>
[Serializable]
public partial class A11_City_Child : BusinessBase<A11_City_Child>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int city_ID1 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="City_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> City_Child_NameProperty = RegisterProperty<string>(p => p.City_Child_Name, "City Child Name");
/// <summary>
/// Gets or sets the City Child Name.
/// </summary>
/// <value>The City Child Name.</value>
public string City_Child_Name
{
get { return GetProperty(City_Child_NameProperty); }
set { SetProperty(City_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="A11_City_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="A11_City_Child"/> object.</returns>
internal static A11_City_Child NewA11_City_Child()
{
return DataPortal.CreateChild<A11_City_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="A11_City_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="A11_City_Child"/> object.</returns>
internal static A11_City_Child GetA11_City_Child(SafeDataReader dr)
{
A11_City_Child obj = new A11_City_Child();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="A11_City_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public A11_City_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="A11_City_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="A11_City_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(City_Child_NameProperty, dr.GetString("City_Child_Name"));
// parent properties
city_ID1 = dr.GetInt32("City_ID1");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="A11_City_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(A10_City parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddA11_City_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@City_ID1", parent.City_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@City_Child_Name", ReadProperty(City_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="A11_City_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(A10_City parent)
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateA11_City_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@City_ID1", parent.City_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@City_Child_Name", ReadProperty(City_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="A11_City_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(A10_City parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteA11_City_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@City_ID1", parent.City_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Diagnostics {
using System.Text;
using System.Threading;
using System;
using System.Security;
using System.Security.Permissions;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
// READ ME:
// Modifying the order or fields of this object may require other changes
// to the unmanaged definition of the StackFrameHelper class, in
// VM\DebugDebugger.h. The binder will catch some of these layout problems.
[Serializable]
internal class StackFrameHelper
{
[NonSerialized]
private Thread targetThread;
private int[] rgiOffset;
private int[] rgiILOffset;
// this field is here only for backwards compatibility of serialization format
private MethodBase[] rgMethodBase;
#pragma warning disable 414 // Field is not used from managed.
// dynamicMethods is an array of System.Resolver objects, used to keep
// DynamicMethodDescs alive for the lifetime of StackFrameHelper.
private Object dynamicMethods;
#pragma warning restore 414
[NonSerialized]
private IntPtr[] rgMethodHandle;
private String[] rgFilename;
private int[] rgiLineNumber;
private int[] rgiColumnNumber;
#if FEATURE_EXCEPTIONDISPATCHINFO
[OptionalField]
private bool[] rgiLastFrameFromForeignExceptionStackTrace;
#endif // FEATURE_EXCEPTIONDISPATCHINFO
private int iFrameCount;
private bool fNeedFileInfo;
public StackFrameHelper(bool fNeedFileLineColInfo, Thread target)
{
targetThread = target;
rgMethodBase = null;
rgMethodHandle = null;
rgiOffset = null;
rgiILOffset = null;
rgFilename = null;
rgiLineNumber = null;
rgiColumnNumber = null;
dynamicMethods = null;
#if FEATURE_EXCEPTIONDISPATCHINFO
rgiLastFrameFromForeignExceptionStackTrace = null;
#endif // FEATURE_EXCEPTIONDISPATCHINFO
// 0 means capture all frames. For StackTraces from an Exception, the EE always
// captures all frames. For other uses of StackTraces, we can abort stack walking after
// some limit if we want to by setting this to a non-zero value. In Whidbey this was
// hard-coded to 512, but some customers complained. There shouldn't be any need to limit
// this as memory/CPU is no longer allocated up front. If there is some reason to provide a
// limit in the future, then we should expose it in the managed API so applications can
// override it.
iFrameCount = 0;
fNeedFileInfo = fNeedFileLineColInfo;
}
[System.Security.SecuritySafeCritical]
public virtual MethodBase GetMethodBase(int i)
{
// There may be a better way to do this.
// we got RuntimeMethodHandles here and we need to go to MethodBase
// but we don't know whether the reflection info has been initialized
// or not. So we call GetMethods and GetConstructors on the type
// and then we fetch the proper MethodBase!!
IntPtr mh = rgMethodHandle[i];
if (mh.IsNull())
return null;
IRuntimeMethodInfo mhReal = RuntimeMethodHandle.GetTypicalMethodDefinition(new RuntimeMethodInfoStub(mh, this));
return RuntimeType.GetMethodBase(mhReal);
}
public virtual int GetOffset(int i) { return rgiOffset[i];}
public virtual int GetILOffset(int i) { return rgiILOffset[i];}
public virtual String GetFilename(int i) { return rgFilename[i];}
public virtual int GetLineNumber(int i) { return rgiLineNumber[i];}
public virtual int GetColumnNumber(int i) { return rgiColumnNumber[i];}
#if FEATURE_EXCEPTIONDISPATCHINFO
public virtual bool IsLastFrameFromForeignExceptionStackTrace(int i)
{
return (rgiLastFrameFromForeignExceptionStackTrace == null)?false:rgiLastFrameFromForeignExceptionStackTrace[i];
}
#endif // FEATURE_EXCEPTIONDISPATCHINFO
public virtual int GetNumberOfFrames() { return iFrameCount;}
public virtual void SetNumberOfFrames(int i) { iFrameCount = i;}
//
// serialization implementation
//
[OnSerializing]
[SecuritySafeCritical]
void OnSerializing(StreamingContext context)
{
// this is called in the process of serializing this object.
// For compatibility with Everett we need to assign the rgMethodBase field as that is the field
// that will be serialized
rgMethodBase = (rgMethodHandle == null) ? null : new MethodBase[rgMethodHandle.Length];
if (rgMethodHandle != null)
{
for (int i = 0; i < rgMethodHandle.Length; i++)
{
if (!rgMethodHandle[i].IsNull())
rgMethodBase[i] = RuntimeType.GetMethodBase(new RuntimeMethodInfoStub(rgMethodHandle[i], this));
}
}
}
[OnSerialized]
void OnSerialized(StreamingContext context)
{
// after we are done serializing null the rgMethodBase field
rgMethodBase = null;
}
[OnDeserialized]
[SecuritySafeCritical]
void OnDeserialized(StreamingContext context)
{
// after we are done deserializing we need to transform the rgMethodBase in rgMethodHandle
rgMethodHandle = (rgMethodBase == null) ? null : new IntPtr[rgMethodBase.Length];
if (rgMethodBase != null)
{
for (int i = 0; i < rgMethodBase.Length; i++)
{
if (rgMethodBase[i] != null)
rgMethodHandle[i] = rgMethodBase[i].MethodHandle.Value;
}
}
rgMethodBase = null;
}
}
// Class which represents a description of a stack trace
// There is no good reason for the methods of this class to be virtual.
// In order to ensure trusted code can trust the data it gets from a
// StackTrace, we use an InheritanceDemand to prevent partially-trusted
// subclasses.
#if !FEATURE_CORECLR
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
#endif
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class StackTrace
{
private StackFrame[] frames;
private int m_iNumOfFrames;
public const int METHODS_TO_SKIP = 0;
private int m_iMethodsToSkip;
// Constructs a stack trace from the current location.
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
public StackTrace()
{
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, false, null, null);
}
// Constructs a stack trace from the current location.
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(bool fNeedFileInfo)
{
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, null);
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(int skipFrames)
{
if (skipFrames < 0)
throw new ArgumentOutOfRangeException("skipFrames",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(skipFrames+METHODS_TO_SKIP, false, null, null);
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(int skipFrames, bool fNeedFileInfo)
{
if (skipFrames < 0)
throw new ArgumentOutOfRangeException("skipFrames",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(skipFrames+METHODS_TO_SKIP, fNeedFileInfo, null, null);
}
// Constructs a stack trace from the current location.
public StackTrace(Exception e)
{
if (e == null)
throw new ArgumentNullException("e");
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, false, null, e);
}
// Constructs a stack trace from the current location.
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(Exception e, bool fNeedFileInfo)
{
if (e == null)
throw new ArgumentNullException("e");
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, e);
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(Exception e, int skipFrames)
{
if (e == null)
throw new ArgumentNullException("e");
if (skipFrames < 0)
throw new ArgumentOutOfRangeException("skipFrames",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(skipFrames+METHODS_TO_SKIP, false, null, e);
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(Exception e, int skipFrames, bool fNeedFileInfo)
{
if (e == null)
throw new ArgumentNullException("e");
if (skipFrames < 0)
throw new ArgumentOutOfRangeException("skipFrames",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(skipFrames+METHODS_TO_SKIP, fNeedFileInfo, null, e);
}
// Constructs a "fake" stack trace, just containing a single frame.
// Does not have the overhead of a full stack trace.
//
public StackTrace(StackFrame frame)
{
frames = new StackFrame[1];
frames[0] = frame;
m_iMethodsToSkip = 0;
m_iNumOfFrames = 1;
}
// Constructs a stack trace for the given thread
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
[Obsolete("This constructor has been deprecated. Please use a constructor that does not require a Thread parameter. http://go.microsoft.com/fwlink/?linkid=14202")]
public StackTrace(Thread targetThread, bool needFileInfo)
{
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, needFileInfo, targetThread, null);
}
[System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void GetStackFramesInternal(StackFrameHelper sfh, int iSkip, Exception e);
internal static int CalculateFramesToSkip(StackFrameHelper StackF, int iNumFrames)
{
int iRetVal = 0;
String PackageName = "System.Diagnostics";
// Check if this method is part of the System.Diagnostics
// package. If so, increment counter keeping track of
// System.Diagnostics functions
for (int i = 0; i < iNumFrames; i++)
{
MethodBase mb = StackF.GetMethodBase(i);
if (mb != null)
{
Type t = mb.DeclaringType;
if (t == null)
break;
String ns = t.Namespace;
if (ns == null)
break;
if (String.Compare(ns, PackageName, StringComparison.Ordinal) != 0)
break;
}
iRetVal++;
}
return iRetVal;
}
// Retrieves an object with stack trace information encoded.
// It leaves out the first "iSkip" lines of the stacktrace.
//
private void CaptureStackTrace(int iSkip, bool fNeedFileInfo, Thread targetThread,
Exception e)
{
m_iMethodsToSkip += iSkip;
StackFrameHelper StackF = new StackFrameHelper(fNeedFileInfo, targetThread);
GetStackFramesInternal(StackF, 0, e);
m_iNumOfFrames = StackF.GetNumberOfFrames();
if (m_iMethodsToSkip > m_iNumOfFrames)
m_iMethodsToSkip = m_iNumOfFrames;
if (m_iNumOfFrames != 0)
{
frames = new StackFrame[m_iNumOfFrames];
for (int i = 0; i < m_iNumOfFrames; i++)
{
bool fDummy1 = true;
bool fDummy2 = true;
StackFrame sfTemp = new StackFrame(fDummy1, fDummy2);
sfTemp.SetMethodBase(StackF.GetMethodBase(i));
sfTemp.SetOffset(StackF.GetOffset(i));
sfTemp.SetILOffset(StackF.GetILOffset(i));
#if FEATURE_EXCEPTIONDISPATCHINFO
sfTemp.SetIsLastFrameFromForeignExceptionStackTrace(StackF.IsLastFrameFromForeignExceptionStackTrace(i));
#endif // FEATURE_EXCEPTIONDISPATCHINFO
if (fNeedFileInfo)
{
sfTemp.SetFileName(StackF.GetFilename (i));
sfTemp.SetLineNumber(StackF.GetLineNumber(i));
sfTemp.SetColumnNumber(StackF.GetColumnNumber(i));
}
frames[i] = sfTemp;
}
// CalculateFramesToSkip skips all frames in the System.Diagnostics namespace,
// but this is not desired if building a stack trace from an exception.
if (e == null)
m_iMethodsToSkip += CalculateFramesToSkip(StackF, m_iNumOfFrames);
m_iNumOfFrames -= m_iMethodsToSkip;
if (m_iNumOfFrames < 0)
{
m_iNumOfFrames = 0;
}
}
// In case this is the same object being re-used, set frames to null
else
frames = null;
}
// Property to get the number of frames in the stack trace
//
public virtual int FrameCount
{
get { return m_iNumOfFrames;}
}
// Returns a given stack frame. Stack frames are numbered starting at
// zero, which is the last stack frame pushed.
//
public virtual StackFrame GetFrame(int index)
{
if ((frames != null) && (index < m_iNumOfFrames) && (index >= 0))
return frames[index+m_iMethodsToSkip];
return null;
}
// Returns an array of all stack frames for this stacktrace.
// The array is ordered and sized such that GetFrames()[i] == GetFrame(i)
// The nth element of this array is the same as GetFrame(n).
// The length of the array is the same as FrameCount.
//
[ComVisible(false)]
public virtual StackFrame [] GetFrames()
{
if (frames == null || m_iNumOfFrames <= 0)
return null;
// We have to return a subset of the array. Unfortunately this
// means we have to allocate a new array and copy over.
StackFrame [] array = new StackFrame[m_iNumOfFrames];
Array.Copy(frames, m_iMethodsToSkip, array, 0, m_iNumOfFrames);
return array;
}
// Builds a readable representation of the stack trace
//
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
public override String ToString()
{
// Include a trailing newline for backwards compatibility
return ToString(TraceFormat.TrailingNewLine);
}
// TraceFormat is Used to specify options for how the
// string-representation of a StackTrace should be generated.
internal enum TraceFormat
{
Normal,
TrailingNewLine, // include a trailing new line character
NoResourceLookup // to prevent infinite resource recusion
}
// Builds a readable representation of the stack trace, specifying
// the format for backwards compatibility.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal String ToString(TraceFormat traceFormat)
{
bool displayFilenames = true; // we'll try, but demand may fail
String word_At = "at";
String inFileLineNum = "in {0}:line {1}";
if(traceFormat != TraceFormat.NoResourceLookup)
{
word_At = Environment.GetResourceString("Word_At");
inFileLineNum = Environment.GetResourceString("StackTrace_InFileLineNumber");
}
bool fFirstFrame = true;
StringBuilder sb = new StringBuilder(255);
for (int iFrameIndex = 0; iFrameIndex < m_iNumOfFrames; iFrameIndex++)
{
StackFrame sf = GetFrame(iFrameIndex);
MethodBase mb = sf.GetMethod();
if (mb != null)
{
// We want a newline at the end of every line except for the last
if (fFirstFrame)
fFirstFrame = false;
else
sb.Append(Environment.NewLine);
sb.AppendFormat(CultureInfo.InvariantCulture, " {0} ", word_At);
Type t = mb.DeclaringType;
// if there is a type (non global method) print it
if (t != null)
{
// Append t.FullName, replacing '+' with '.'
string fullName = t.FullName;
for (int i = 0; i < fullName.Length; i++)
{
char ch = fullName[i];
sb.Append(ch == '+' ? '.' : ch);
}
sb.Append('.');
}
sb.Append(mb.Name);
// deal with the generic portion of the method
if (mb is MethodInfo && ((MethodInfo)mb).IsGenericMethod)
{
Type[] typars = ((MethodInfo)mb).GetGenericArguments();
sb.Append('[');
int k=0;
bool fFirstTyParam = true;
while (k < typars.Length)
{
if (fFirstTyParam == false)
sb.Append(',');
else
fFirstTyParam = false;
sb.Append(typars[k].Name);
k++;
}
sb.Append(']');
}
// arguments printing
sb.Append('(');
ParameterInfo[] pi = mb.GetParameters();
bool fFirstParam = true;
for (int j = 0; j < pi.Length; j++)
{
if (fFirstParam == false)
sb.Append(", ");
else
fFirstParam = false;
String typeName = "<UnknownType>";
if (pi[j].ParameterType != null)
typeName = pi[j].ParameterType.Name;
sb.Append(typeName);
sb.Append(' ');
sb.Append(pi[j].Name);
}
sb.Append(')');
// source location printing
if (displayFilenames && (sf.GetILOffset() != -1))
{
// If we don't have a PDB or PDB-reading is disabled for the module,
// then the file name will be null.
String fileName = null;
// Getting the filename from a StackFrame is a privileged operation - we won't want
// to disclose full path names to arbitrarily untrusted code. Rather than just omit
// this we could probably trim to just the filename so it's still mostly usefull.
try
{
fileName = sf.GetFileName();
}
#if FEATURE_CAS_POLICY
catch (NotSupportedException)
{
// Having a deprecated stack modifier on the callstack (such as Deny) will cause
// a NotSupportedException to be thrown. Since we don't know if the app can
// access the file names, we'll conservatively hide them.
displayFilenames = false;
}
#endif // FEATURE_CAS_POLICY
catch (SecurityException)
{
// If the demand for displaying filenames fails, then it won't
// succeed later in the loop. Avoid repeated exceptions by not trying again.
displayFilenames = false;
}
if (fileName != null)
{
// tack on " in c:\tmp\MyFile.cs:line 5"
sb.Append(' ');
sb.AppendFormat(CultureInfo.InvariantCulture, inFileLineNum, fileName, sf.GetFileLineNumber());
}
}
#if FEATURE_EXCEPTIONDISPATCHINFO
if (sf.GetIsLastFrameFromForeignExceptionStackTrace())
{
sb.Append(Environment.NewLine);
sb.Append(Environment.GetResourceString("Exception_EndStackTraceFromPreviousThrow"));
}
#endif // FEATURE_EXCEPTIONDISPATCHINFO
}
}
if(traceFormat == TraceFormat.TrailingNewLine)
sb.Append(Environment.NewLine);
return sb.ToString();
}
// This helper is called from within the EE to construct a string representation
// of the current stack trace.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
private static String GetManagedStackTraceStringHelper(bool fNeedFileInfo)
{
// Note all the frames in System.Diagnostics will be skipped when capturing
// a normal stack trace (not from an exception) so we don't need to explicitly
// skip the GetManagedStackTraceStringHelper frame.
StackTrace st = new StackTrace(0, fNeedFileInfo);
return st.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Debugger.Interop;
namespace NodeVsDebugger
{
using FIF = enum_FRAMEINFO_FLAGS;
// Represents a logical stack frame on the thread stack.
// Also implements the IDebugExpressionContext interface, which allows expression evaluation and watch windows.
class AD7StackFrame : IDebugStackFrame2, IDebugExpressionContext2
{
readonly AD7Engine m_engine;
readonly AD7Thread m_thread;
readonly NodeThreadContext m_threadContext;
private string m_functionName;
private uint m_lineNum;
private bool m_hasSource = true;
// An array of this frame's parameters
private Property[] m_parameters { get { return m_threadContext.Args; } }
// An array of this frame's locals
private Property[] m_locals { get { return m_threadContext.Locals; } }
public AD7StackFrame(AD7Engine engine, AD7Thread thread, NodeThreadContext threadContext)
{
m_engine = engine;
m_thread = thread;
m_threadContext = threadContext;
// Try to get source information for this location. If symbols for this file have not been found, this will fail.
m_functionName = m_threadContext.func.AnyName;
m_lineNum = (uint)m_threadContext.line;
}
#region Non-interface methods
// Construct a FRAMEINFO for this stack frame with the requested information.
public FRAMEINFO GetFrameInfo(FIF dwFieldSpec)
{
var frameInfo = new FRAMEINFO();
// TODO: were called:
// Modules.Add(mod);
// Callback.OnModuleLoad(mod);
// The debugger is asking for the formatted name of the function which is displayed in the callstack window.
// There are several optional parts to this name including the module, argument types and values, and line numbers.
// The optional information is requested by setting flags in the dwFieldSpec parameter.
if (dwFieldSpec.HasFlag(FIF.FIF_FUNCNAME)) {
// If there is source information, construct a string that contains the module name, function name, and optionally argument names and values.
if (m_hasSource) {
var funcName = new StringBuilder();
if (dwFieldSpec.HasFlag(FIF.FIF_FUNCNAME_MODULE))
funcName.Append(System.IO.Path.GetFileName(m_threadContext.script.Name) + "!");
funcName.Append(m_functionName);
if (dwFieldSpec.HasFlag(FIF.FIF_FUNCNAME_ARGS)) {
funcName.Append("(");
var format = GetArgumentFormat(dwFieldSpec);
funcName.Append(string.Join(", ", m_parameters
.Select(p => string.Format(format, p.m_typeName, string.IsNullOrEmpty(p.m_name) ? "?" : p.m_name, p.m_value))
));
funcName.Append(")");
}
if (dwFieldSpec.HasFlag(FIF.FIF_FUNCNAME_LINES))
funcName.AppendFormat(" Line {0}", m_lineNum);
frameInfo.m_bstrFuncName = funcName.ToString();
} else {
throw new NotImplementedException();
}
frameInfo.m_dwValidFields |= FIF.FIF_FUNCNAME;
}
// The debugger is requesting the name of the module for this stack frame.
if (dwFieldSpec.HasFlag(FIF.FIF_MODULE)) {
frameInfo.m_bstrModule = m_threadContext.script.Name;
frameInfo.m_dwValidFields |= FIF.FIF_MODULE;
}
// The debugger is requesting the IDebugStackFrame2 value for this frame info.
if (dwFieldSpec.HasFlag(FIF.FIF_FRAME)) {
frameInfo.m_pFrame = this;
frameInfo.m_dwValidFields |= FIF.FIF_FRAME;
}
// Does this stack frame of symbols loaded?
if (dwFieldSpec.HasFlag(FIF.FIF_DEBUGINFO)) {
frameInfo.m_fHasDebugInfo = m_hasSource ? 1 : 0;
frameInfo.m_dwValidFields |= FIF.FIF_DEBUGINFO;
}
// Is this frame stale?
if (dwFieldSpec.HasFlag(FIF.FIF_STALECODE)) {
frameInfo.m_fStaleCode = 0;
frameInfo.m_dwValidFields |= FIF.FIF_STALECODE;
}
return frameInfo;
}
private static string GetArgumentFormat(FIF dwFieldSpec)
{
switch (dwFieldSpec & FIF.FIF_FUNCNAME_ARGS_ALL) {
case FIF.FIF_FUNCNAME_ARGS_TYPES:
return "{0}";
case FIF.FIF_FUNCNAME_ARGS_NAMES:
return "{1}";
case FIF.FIF_FUNCNAME_ARGS_VALUES:
return "{2}";
case FIF.FIF_FUNCNAME_ARGS_TYPES | FIF.FIF_FUNCNAME_ARGS_NAMES:
return "{0} {1}";
case FIF.FIF_FUNCNAME_ARGS_TYPES | FIF.FIF_FUNCNAME_ARGS_VALUES:
return "{0} ={2}";
case FIF.FIF_FUNCNAME_ARGS_NAMES | FIF.FIF_FUNCNAME_ARGS_VALUES:
return "{1}={2}";
case FIF.FIF_FUNCNAME_ARGS_ALL:
return "{0} {1}={2}";
default:
return "";
}
}
#endregion
#region IDebugStackFrame2 Members
// Creates an enumerator for properties associated with the stack frame, such as local variables.
// The sample engine only supports returning locals and parameters. Other possible values include
// class fields (this pointer), registers, exceptions...
int IDebugStackFrame2.EnumProperties(enum_DEBUGPROP_INFO_FLAGS dwFields, uint nRadix, ref Guid guidFilter, uint dwTimeout, out uint elementsReturned, out IEnumDebugPropertyInfo2 enumObject)
{
int hr;
elementsReturned = 0;
enumObject = null;
try {
IEnumerable<Property> props = null;
hr = Constants.S_OK;
if (guidFilter == AD7Guids.guidFilterLocalsPlusArgs || guidFilter == AD7Guids.guidFilterAllLocalsPlusArgs || guidFilter == AD7Guids.guidFilterAllLocals) {
props = m_locals.Concat(m_parameters);
} else if (guidFilter == AD7Guids.guidFilterLocals) {
props = m_locals;
} else if (guidFilter == AD7Guids.guidFilterArgs) {
props = m_parameters;
} else {
hr = Constants.E_NOTIMPL;
}
if (props != null) {
var propInfos = props
.Select(p => new AD7Property(p).ConstructDebugPropertyInfo(dwFields))
.ToArray();
elementsReturned = (uint)propInfos.Length;
enumObject = new AD7PropertyInfoEnum(propInfos);
}
} catch (Exception e) {
return EngineUtils.UnexpectedException(e);
}
return hr;
}
// Gets the code context for this stack frame. The code context represents the current instruction pointer in this stack frame.
int IDebugStackFrame2.GetCodeContext(out IDebugCodeContext2 memoryAddress)
{
memoryAddress = null;
return Constants.S_FALSE;
}
// Gets a description of the properties of a stack frame.
// Calling the IDebugProperty2::EnumChildren method with appropriate filters can retrieve the local variables, method parameters, registers, and "this"
// pointer associated with the stack frame. The debugger calls EnumProperties to obtain these values in the sample.
int IDebugStackFrame2.GetDebugProperty(out IDebugProperty2 property)
{
property = null;
return Constants.S_FALSE;
}
// Gets the document context for this stack frame. The debugger will call this when the current stack frame is changed
// and will use it to open the correct source document for this stack frame.
int IDebugStackFrame2.GetDocumentContext(out IDebugDocumentContext2 docContext)
{
docContext = null;
try {
if (m_hasSource) {
// Assume all lines begin and end at the beginning of the line.
var documentName = m_engine.DebuggedProcess.GetLocalFile(m_threadContext.script, fetchIfNotExists: true);
docContext = new AD7DocumentContext(documentName, m_lineNum, m_lineNum);
return Constants.S_OK;
}
} catch (Exception e) {
return EngineUtils.UnexpectedException(e);
}
return Constants.S_FALSE;
}
// Gets an evaluation context for expression evaluation within the current context of a stack frame and thread.
// Generally, an expression evaluation context can be thought of as a scope for performing expression evaluation.
// Call the IDebugExpressionContext2::ParseText method to parse an expression and then call the resulting IDebugExpression2::EvaluateSync
// or IDebugExpression2::EvaluateAsync methods to evaluate the parsed expression.
int IDebugStackFrame2.GetExpressionContext(out IDebugExpressionContext2 ppExprCxt)
{
ppExprCxt = this;
return Constants.S_OK;
}
// Gets a description of the stack frame.
int IDebugStackFrame2.GetInfo(enum_FRAMEINFO_FLAGS dwFieldSpec, uint nRadix, FRAMEINFO[] pFrameInfo)
{
try {
pFrameInfo[0] = GetFrameInfo(dwFieldSpec);
return Constants.S_OK;
} catch (Exception e) {
return EngineUtils.UnexpectedException(e);
}
}
// Gets the language associated with this stack frame.
// In this sample, all the supported stack frames are C++
int IDebugStackFrame2.GetLanguageInfo(ref string pbstrLanguage, ref Guid pguidLanguage)
{
pbstrLanguage = "JavaScript";
pguidLanguage = AD7Guids.guidLanguageJs;
return Constants.S_OK;
}
// Gets the name of the stack frame.
// The name of a stack frame is typically the name of the method being executed.
int IDebugStackFrame2.GetName(out string name)
{
name = "IDebugStackFrame2.GetName";
return Constants.S_OK;
}
// Gets a machine-dependent representation of the range of physical addresses associated with a stack frame.
int IDebugStackFrame2.GetPhysicalStackRange(out ulong addrMin, out ulong addrMax)
{
addrMin = 0;
addrMax = 0;
return Constants.E_NOTIMPL;
}
// Gets the thread associated with a stack frame.
int IDebugStackFrame2.GetThread(out IDebugThread2 thread)
{
thread = m_thread;
return Constants.S_OK;
}
#endregion
#region IDebugExpressionContext2 Members
// Retrieves the name of the evaluation context.
// The name is the description of this evaluation context. It is typically something that can be parsed by an expression evaluator
// that refers to this exact evaluation context. For example, in C++ the name is as follows:
// "{ function-name, source-file-name, module-file-name }"
int IDebugExpressionContext2.GetName(out string pbstrName)
{
throw new NotImplementedException();
}
// Parses a text-based expression for evaluation.
// The engine sample only supports locals and parameters so the only task here is to check the names in those collections.
int IDebugExpressionContext2.ParseText(string pszCode, enum_PARSEFLAGS dwFlags, uint nRadix, out IDebugExpression2 ppExpr, out string pbstrError, out uint pichError)
{
pbstrError = "";
pichError = 0;
ppExpr = null;
try {
var localOrArg = m_parameters.Concat(m_locals).FirstOrDefault(v => String.CompareOrdinal(v.m_name, pszCode) == 0);
if (localOrArg != null) {
ppExpr = new AD7Property(localOrArg);
return Constants.S_OK;
}
var result = m_engine.DebuggedProcess.Evaluate(m_threadContext.index, pszCode, out pbstrError);
if (result != null) {
ppExpr = new AD7Property(result);
return Constants.S_OK;
}
pichError = (uint)pbstrError.Length;
return Constants.S_FALSE;
} catch (Exception e) {
return EngineUtils.UnexpectedException(e);
}
}
#endregion
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Backoffice_Referensi_SatuanKerja_List : System.Web.UI.Page
{
public int NoKe = 0;
protected string dsReportSessionName = "dsListRefSatuanKerja";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
int UserId = (int)Session["SIMRS.UserId"];
if (Session["SatuanKerjaManagement"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx");
}
else
{
btnNew.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + Resources.GetString("Referensi", "AddSatuanKerja");
}
btnSearch.Text = Resources.GetString("", "Search");
ImageButtonFirst.ImageUrl = Request.ApplicationPath + "/images/navigator/nbFirst.gif";
ImageButtonPrev.ImageUrl = Request.ApplicationPath + "/images/navigator/nbPrevpage.gif";
ImageButtonNext.ImageUrl = Request.ApplicationPath + "/images/navigator/nbNextpage.gif";
ImageButtonLast.ImageUrl = Request.ApplicationPath + "/images/navigator/nbLast.gif";
UpdateDataView(true);
}
}
#region .Update View Data
//////////////////////////////////////////////////////////////////////
// PhysicalDataRead
// ------------------------------------------------------------------
/// <summary>
/// This function is responsible for loading data from database.
/// </summary>
/// <returns>DataSet</returns>
public DataSet PhysicalDataRead()
{
// Local variables
DataSet oDS = new DataSet();
// Get Data
SIMRS.DataAccess.RS_SatuanKerja myObj = new SIMRS.DataAccess.RS_SatuanKerja();
DataTable myData = myObj.SelectAll();
oDS.Tables.Add(myData);
return oDS;
}
/// <summary>
/// This function is responsible for binding data to Datagrid.
/// </summary>
/// <param name="dv"></param>
private void BindData(DataView dv)
{
// Sets the sorting order
dv.Sort = DataGridList.Attributes["SortField"];
if (DataGridList.Attributes["SortAscending"] == "no")
dv.Sort += " DESC";
if (dv.Count > 0)
{
DataGridList.ShowFooter = false;
int intRowCount = dv.Count;
int intPageSaze = DataGridList.PageSize;
int intPageCount = intRowCount / intPageSaze;
if (intRowCount - (intPageCount * intPageSaze) > 0)
intPageCount = intPageCount + 1;
if (DataGridList.CurrentPageIndex >= intPageCount)
DataGridList.CurrentPageIndex = intPageCount - 1;
}
else
{
DataGridList.ShowFooter = true;
DataGridList.CurrentPageIndex = 0;
}
// Re-binds the grid
NoKe = DataGridList.PageSize * DataGridList.CurrentPageIndex;
DataGridList.DataSource = dv;
DataGridList.DataBind();
int CurrentPage = DataGridList.CurrentPageIndex + 1;
lblCurrentPage.Text = CurrentPage.ToString();
lblTotalPage.Text = DataGridList.PageCount.ToString();
lblTotalRecord.Text = dv.Count.ToString();
}
/// <summary>
/// This function is responsible for loading data from database and store to Session.
/// </summary>
/// <param name="strDataSessionName"></param>
public void DataFromSourceToMemory(String strDataSessionName)
{
// Gets rows from the data source
DataSet oDS = PhysicalDataRead();
// Stores it in the session cache
Session[strDataSessionName] = oDS;
}
/// <summary>
/// This function is responsible for update data view from datagrid.
/// </summary>
/// <param name="requery">true = get data from database, false= get data from session</param>
public void UpdateDataView(bool requery)
{
// Retrieves the data
if ((Session[dsReportSessionName] == null) || (requery))
{
if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
DataGridList.CurrentPageIndex = int.Parse(Request.QueryString["CurrentPage"].ToString());
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
public void UpdateDataView()
{
// Retrieves the data
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
#endregion
#region .Event DataGridList
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// HANDLERs //
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageChanged(Object sender, DataGridPageChangedEventArgs e)
{
DataGridList.CurrentPageIndex = e.NewPageIndex;
DataGridList.SelectedIndex = -1;
UpdateDataView();
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="nPageIndex"></param>
public void GoToPage(Object sender, int nPageIndex)
{
DataGridPageChangedEventArgs evPage;
evPage = new DataGridPageChangedEventArgs(sender, nPageIndex);
PageChanged(sender, evPage);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a first page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToFirst(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, 0);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a previous page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToPrev(Object sender, ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex > 0)
{
GoToPage(sender, DataGridList.CurrentPageIndex - 1);
}
else
{
GoToPage(sender, 0);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a next page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToNext(Object sender, System.Web.UI.ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex < (DataGridList.PageCount - 1))
{
GoToPage(sender, DataGridList.CurrentPageIndex + 1);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a last page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToLast(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, DataGridList.PageCount - 1);
}
/// <summary>
/// This function is invoked when you click on a column's header to
/// sort by that. It just saves the current sort field name and
/// refreshes the grid.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void SortByColumn(Object sender, DataGridSortCommandEventArgs e)
{
String strSortBy = DataGridList.Attributes["SortField"];
String strSortAscending = DataGridList.Attributes["SortAscending"];
// Sets the new sorting field
DataGridList.Attributes["SortField"] = e.SortExpression;
// Sets the order (defaults to ascending). If you click on the
// sorted column, the order reverts.
DataGridList.Attributes["SortAscending"] = "yes";
if (e.SortExpression == strSortBy)
DataGridList.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes");
// Refreshes the view
OnClearSelection(null, null);
UpdateDataView();
}
/// <summary>
/// The function gets invoked when a new item is being created in
/// the datagrid. This applies to pager, header, footer, regular
/// and alternating items.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageItemCreated(Object sender, DataGridItemEventArgs e)
{
// Get the newly created item
ListItemType itemType = e.Item.ItemType;
//////////////////////////////////////////////////////////
// Is it the HEADER?
if (itemType == ListItemType.Header)
{
for (int i = 0; i < DataGridList.Columns.Count; i++)
{
// draw to reflect sorting
if (DataGridList.Attributes["SortField"] == DataGridList.Columns[i].SortExpression)
{
//////////////////////////////////////////////
// Should be much easier this way:
// ------------------------------------------
// TableCell cell = e.Item.Cells[i];
// Label lblSorted = new Label();
// lblSorted.Font = "webdings";
// lblSorted.Text = strOrder;
// cell.Controls.Add(lblSorted);
//
// but it seems it doesn't work <g>
//////////////////////////////////////////////
// Add a non-clickable triangle to mean desc or asc.
// The </a> ensures that what follows is non-clickable
TableCell cell = e.Item.Cells[i];
LinkButton lb = (LinkButton)cell.Controls[0];
//lb.Text += "</a> <span style=font-family:webdings;>" + GetOrderSymbol() + "</span>";
lb.Text += "</a> <img src=" + Request.ApplicationPath + "/images/icons/" + GetOrderSymbol() + " >";
}
}
}
//////////////////////////////////////////////////////////
// Is it the PAGER?
if (itemType == ListItemType.Pager)
{
// There's just one control in the list...
TableCell pager = (TableCell)e.Item.Controls[0];
// Enumerates all the items in the pager...
for (int i = 0; i < pager.Controls.Count; i += 2)
{
// It can be either a Label or a Link button
try
{
Label l = (Label)pager.Controls[i];
l.Text = "Hal " + l.Text;
l.CssClass = "CurrentPage";
}
catch
{
LinkButton h = (LinkButton)pager.Controls[i];
h.Text = "[ " + h.Text + " ]";
h.CssClass = "HotLink";
}
}
}
}
/// <summary>
/// Verifies whether the current sort is ascending or descending and
/// returns an appropriate display text (i.e., a webding)
/// </summary>
/// <returns></returns>
private String GetOrderSymbol()
{
bool bDescending = (bool)(DataGridList.Attributes["SortAscending"] == "no");
//return (bDescending ? " 6" : " 5");
return (bDescending ? "downbr.gif" : "upbr.gif");
}
/// <summary>
/// When clicked clears the current selection if any
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnClearSelection(Object sender, EventArgs e)
{
DataGridList.SelectedIndex = -1;
}
#endregion
#region .Event Button
/// <summary>
/// When clicked, redirect to form add for inserts a new record to the database
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnNewRecord(Object sender, EventArgs e)
{
string CurrentPage = DataGridList.CurrentPageIndex.ToString();
Response.Redirect("Add.aspx?CurrentPage=" + CurrentPage);
}
/// <summary>
/// When clicked, filter data.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnSearch(Object sender, System.EventArgs e)
{
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
DataView dv = ds.Tables[0].DefaultView;
if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "Kode")
dv.RowFilter = " Kode LIKE '%" + txtSearch.Text + "%'";
else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "NamaSatker")
dv.RowFilter = " NamaSatker LIKE '%" + txtSearch.Text + "%'";
else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "Keterangan")
dv.RowFilter = " Keterangan LIKE '%" + txtSearch.Text + "%'";
else
dv.RowFilter = "";
BindData(dv);
}
#endregion
#region .Update Link Item Butom
/// <summary>
/// The function is responsible for get link button form.
/// </summary>
/// <param name="szId"></param>
/// <param name="CurrentPage"></param>
/// <returns></returns>
public string GetLinkButton(string Id, string Nama, string CurrentPage)
{
string szResult = "";
if (Session["SatuanKerjaManagement"] != null)
{
szResult += "<a class=\"toolbar\" href=\"Edit.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" ";
szResult += ">" + Resources.GetString("", "Edit") + "</a>";
szResult += "<a class=\"toolbar\" href=\"Delete.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" ";
szResult += ">" + Resources.GetString("", "Delete") + "</a>";
}
return szResult;
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftRightLogicalUInt6464()
{
var test = new ImmUnaryOpTest__ShiftRightLogicalUInt6464();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.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 (Sse2.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 (Sse2.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 class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
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 ImmUnaryOpTest__ShiftRightLogicalUInt6464
{
private struct TestStruct
{
public Vector128<UInt64> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalUInt6464 testClass)
{
var result = Sse2.ShiftRightLogical(_fld, 64);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data = new UInt64[Op1ElementCount];
private static Vector128<UInt64> _clsVar;
private Vector128<UInt64> _fld;
private SimpleUnaryOpTest__DataTable<UInt64, UInt64> _dataTable;
static ImmUnaryOpTest__ShiftRightLogicalUInt6464()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
}
public ImmUnaryOpTest__ShiftRightLogicalUInt6464()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt64, UInt64>(_data, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.ShiftRightLogical(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.ShiftRightLogical(
Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr)),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.ShiftRightLogical(
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr)),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr)),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr)),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.ShiftRightLogical(
_clsVar,
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr);
var result = Sse2.ShiftRightLogical(firstOp, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical(firstOp, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical(firstOp, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftRightLogicalUInt6464();
var result = Sse2.ShiftRightLogical(test._fld, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.ShiftRightLogical(_fld, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.ShiftRightLogical(test._fld, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<UInt64> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (0 != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (0 != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightLogical)}<UInt64>(Vector128<UInt64><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// ****************************************************************
// Copyright 2007, Charlie Poole, Rob Prouse
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
#if !NETSTANDARD1_3 && !NETSTANDARD1_6
using System.Collections.Generic;
using System.Reflection;
using NUnit.Compatibility;
using NUnit.Framework.Api;
using NUnit.Framework.Interfaces;
using NUnit.TestUtilities;
namespace NUnit.Framework.Internal
{
[TestFixture]
public class SetUpFixtureTests
{
private static readonly string testAssembly = AssemblyHelper.GetAssemblyPath(typeof(NUnit.TestData.SetupFixture.Namespace1.SomeFixture).GetTypeInfo().Assembly);
ITestAssemblyBuilder builder;
ITestAssemblyRunner runner;
#region SetUp
[SetUp]
public void SetUp()
{
TestUtilities.SimpleEventRecorder.Clear();
builder = new DefaultTestAssemblyBuilder();
runner = new NUnitTestAssemblyRunner(builder);
}
#endregion SetUp
private ITestResult runTests(string nameSpace)
{
return runTests(nameSpace, TestFilter.Empty);
}
private ITestResult runTests(string nameSpace, TestFilter filter)
{
IDictionary<string, object> options = new Dictionary<string, object>();
if (nameSpace != null)
options["LOAD"] = new string[] { nameSpace };
// No need for the overhead of parallel execution here
options["NumberOfTestWorkers"] = 0;
if (runner.Load(testAssembly, options) != null)
return runner.Run(TestListener.NULL, filter);
return null;
}
#region Builder Tests
/// <summary>
/// Tests that the TestSuiteBuilder correctly interprets a SetupFixture class as a 'virtual namespace' into which
/// all it's sibling classes are inserted.
/// </summary>
[NUnit.Framework.Test]
public void NamespaceSetUpFixtureReplacesNamespaceNodeInTree()
{
string nameSpace = "NUnit.TestData.SetupFixture.Namespace1";
IDictionary<string, object> options = new Dictionary<string, object>();
options["LOAD"] = new string[] { nameSpace };
ITest suite = builder.Build(testAssembly, options);
Assert.IsNotNull(suite);
Assert.AreEqual(testAssembly, suite.FullName);
Assert.AreEqual(1, suite.Tests.Count, "Error in top level test count");
string[] nameSpaceBits = nameSpace.Split('.');
for (int i = 0; i < nameSpaceBits.Length; i++)
{
suite = suite.Tests[0] as TestSuite;
Assert.AreEqual(nameSpaceBits[i], suite.Name);
Assert.AreEqual(1, suite.Tests.Count);
Assert.That(suite.RunState, Is.EqualTo(RunState.Runnable));
}
Assert.That(suite, Is.InstanceOf<SetUpFixture>());
suite = suite.Tests[0] as TestSuite;
Assert.AreEqual("SomeFixture", suite.Name);
Assert.AreEqual(1, suite.Tests.Count);
Assert.That(suite.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(suite.Tests[0].RunState, Is.EqualTo(RunState.Runnable));
}
/// <summary>
/// Tests that the TestSuiteBuilder correctly interprets a SetupFixture class with no parent namespace
/// as a 'virtual assembly' into which all it's sibling fixtures are inserted.
/// </summary>
[Test]
public void AssemblySetUpFixtureFollowsAssemblyNodeInTree()
{
IDictionary<string, object> options = new Dictionary<string, object>();
var rootSuite = builder.Build(testAssembly, options);
Assert.That(rootSuite, Is.TypeOf<TestAssembly>());
var setupFixture = rootSuite.Tests[0];
Assert.That(setupFixture, Is.TypeOf<SetUpFixture>());
var testFixture = TestFinder.Find("SomeFixture", (SetUpFixture)setupFixture, false);
Assert.NotNull(testFixture);
Assert.AreEqual(1, testFixture.Tests.Count);
}
[Test]
public void InvalidAssemblySetUpFixtureIsLoadedCorrectly()
{
string nameSpace = "NUnit.TestData.SetupFixture.Namespace6";
IDictionary<string, object> options = new Dictionary<string, object>();
options["LOAD"] = new string[] { nameSpace };
ITest suite = builder.Build(testAssembly, options);
Assert.IsNotNull(suite);
Assert.AreEqual(testAssembly, suite.FullName);
Assert.AreEqual(1, suite.Tests.Count, "Error in top level test count");
Assert.AreEqual(RunState.Runnable, suite.RunState);
string[] nameSpaceBits = nameSpace.Split('.');
for (int i = 0; i < nameSpaceBits.Length; i++)
{
suite = suite.Tests[0] as TestSuite;
Assert.AreEqual(nameSpaceBits[i], suite.Name);
Assert.AreEqual(1, suite.Tests.Count);
Assert.That(suite.RunState, Is.EqualTo(i < nameSpaceBits.Length - 1 ? RunState.Runnable : RunState.NotRunnable));
}
suite = suite.Tests[0] as TestSuite;
Assert.AreEqual("SomeFixture", suite.Name);
Assert.AreEqual(1, suite.Tests.Count);
Assert.That(suite.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(suite.Tests[0].RunState, Is.EqualTo(RunState.Runnable));
}
#endregion
#region Simple
[NUnit.Framework.Test]
public void NamespaceSetUpFixtureWrapsExecutionOfSingleTest()
{
Assert.That(runTests("NUnit.TestData.SetupFixture.Namespace1").ResultState.Status, Is.EqualTo(TestStatus.Passed));
TestUtilities.SimpleEventRecorder.Verify("NS1.OneTimeSetup",
"NS1.Fixture.SetUp",
"NS1.Test.SetUp",
"NS1.Test",
"NS1.Test.TearDown",
"NS1.Fixture.TearDown",
"NS1.OneTimeTearDown");
}
#endregion Simple
#region Static
[Test]
public void NamespaceSetUpMethodsMayBeStatic()
{
Assert.That(runTests("NUnit.TestData.SetupFixture.Namespace5").ResultState.Status, Is.EqualTo(TestStatus.Passed));
TestUtilities.SimpleEventRecorder.Verify("NS5.OneTimeSetUp",
"NS5.Fixture.SetUp",
"NS5.Test.SetUp",
"NS5.Test",
"NS5.Test.TearDown",
"NS5.Fixture.TearDown",
"NS5.OneTimeTearDown");
}
#endregion
#region TwoTestFixtures
[NUnit.Framework.Test]
public void NamespaceSetUpFixtureWrapsExecutionOfTwoTests()
{
Assert.That(runTests("NUnit.TestData.SetupFixture.Namespace2").ResultState.Status, Is.EqualTo(TestStatus.Passed));
// There are two fixtures but we can't be sure of the order of execution so they use the same events
TestUtilities.SimpleEventRecorder.Verify("NS2.OneTimeSetUp",
"NS2.Fixture.SetUp",
"NS2.Test.SetUp",
"NS2.Test",
"NS2.Test.TearDown",
"NS2.Fixture.TearDown",
"NS2.Fixture.SetUp",
"NS2.Test.SetUp",
"NS2.Test",
"NS2.Test.TearDown",
"NS2.Fixture.TearDown",
"NS2.OneTimeTearDown");
}
#endregion TwoTestFixtures
#region SubNamespace
[NUnit.Framework.Test]
public void NamespaceSetUpFixtureWrapsNestedNamespaceSetUpFixture()
{
Assert.That(runTests("NUnit.TestData.SetupFixture.Namespace3").ResultState.Status, Is.EqualTo(TestStatus.Passed));
TestUtilities.SimpleEventRecorder.Verify("NS3.OneTimeSetUp",
"NS3.Fixture.SetUp",
"NS3.Test.SetUp",
"NS3.Test",
"NS3.Test.TearDown",
"NS3.Fixture.TearDown",
"NS3.SubNamespace.OneTimeSetUp",
"NS3.SubNamespace.Fixture.SetUp",
"NS3.SubNamespace.Test.SetUp",
"NS3.SubNamespace.Test",
"NS3.SubNamespace.Test.TearDown",
"NS3.SubNamespace.Fixture.TearDown",
"NS3.SubNamespace.OneTimeTearDown",
"NS3.OneTimeTearDown");
}
#endregion SubNamespace
#region TwoSetUpFixtures
[NUnit.Framework.Test]
public void WithTwoSetUpFixturesBothAreUsed()
{
Assert.That(runTests("NUnit.TestData.SetupFixture.Namespace4").ResultState.Status, Is.EqualTo(TestStatus.Passed));
TestUtilities.SimpleEventRecorder.ExpectEvents("NS4.OneTimeSetUp1", "NS4.OneTimeSetUp2")
.AndThen("NS4.Fixture.SetUp")
.AndThen("NS4.Test.SetUp")
.AndThen("NS4.Test")
.AndThen("NS4.Test.TearDown")
.AndThen("NS4.Fixture.TearDown")
.AndThen("NS4.OneTimeTearDown1", "NS4.OneTimeTearDown2")
.Verify();
}
#endregion TwoSetUpFixtures
#region InvalidSetUpFixture
[Test]
public void InvalidSetUpFixtureTest()
{
Assert.That(runTests("NUnit.TestData.SetupFixture.Namespace6").ResultState.Status, Is.EqualTo(TestStatus.Failed));
TestUtilities.SimpleEventRecorder.Verify(new string[0]);
}
#endregion
#region NoNamespaceSetupFixture
[NUnit.Framework.Test]
public void AssemblySetupFixtureWrapsExecutionOfTest()
{
ITestResult result = runTests(null, new Filters.FullNameFilter("SomeFixture"));
Assert.AreEqual(1, result.PassCount);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
TestUtilities.SimpleEventRecorder.Verify("Assembly.OneTimeSetUp",
"NoNamespaceTest",
"Assembly.OneTimeTearDown");
}
#endregion NoNamespaceSetupFixture
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Internal.IL;
using Debug = System.Diagnostics.Debug;
using Internal.IL.Stubs;
namespace Internal.TypeSystem.Interop
{
public static class MarshalHelpers
{
public static bool IsStructMarshallingRequired(TypeDesc typeDesc)
{
if (typeDesc is ByRefType)
{
typeDesc = typeDesc.GetParameterType();
}
typeDesc = typeDesc.UnderlyingType;
// TODO: There are primitive types which require marshalling, such as bool, char.
if (typeDesc.IsPrimitive)
{
return false;
}
MetadataType type = typeDesc as MetadataType;
if (type == null)
{
return false;
}
//
// For struct marshalling it is required to have either Sequential
// or Explicit layout. For Auto layout the P/Invoke marshalling code
// will throw appropriate error message.
//
if (!type.IsSequentialLayout && !type.IsExplicitLayout)
return false;
// If it is not blittable we will need struct marshalling
return !MarshalUtils.IsBlittableType(type);
}
internal static TypeDesc GetNativeMethodParameterType(TypeDesc type, MarshalAsDescriptor marshalAs, InteropStateManager interopStateManager, bool isReturn, bool isAnsi)
{
MarshallerKind elementMarshallerKind;
MarshallerKind marshallerKind = MarshalHelpers.GetMarshallerKind(type,
marshalAs,
isReturn,
isAnsi,
MarshallerType.Argument,
out elementMarshallerKind);
return GetNativeTypeFromMarshallerKind(type,
marshallerKind,
elementMarshallerKind,
interopStateManager,
marshalAs);
}
internal static TypeDesc GetNativeStructFieldType(TypeDesc type, MarshalAsDescriptor marshalAs, InteropStateManager interopStateManager, bool isAnsi)
{
MarshallerKind elementMarshallerKind;
MarshallerKind marshallerKind = MarshalHelpers.GetMarshallerKind(type,
marshalAs,
false, /* isReturn */
isAnsi, /* isAnsi */
MarshallerType.Field,
out elementMarshallerKind);
return GetNativeTypeFromMarshallerKind(type,
marshallerKind,
elementMarshallerKind,
interopStateManager,
marshalAs);
}
internal static TypeDesc GetNativeTypeFromMarshallerKind(TypeDesc type,
MarshallerKind kind,
MarshallerKind elementMarshallerKind,
InteropStateManager interopStateManager,
MarshalAsDescriptor marshalAs,
bool isArrayElement = false)
{
TypeSystemContext context = type.Context;
NativeTypeKind nativeType = NativeTypeKind.Invalid;
if (marshalAs != null)
{
nativeType = isArrayElement ? marshalAs.ArraySubType : marshalAs.Type;
}
switch (kind)
{
case MarshallerKind.BlittableValue:
{
switch (nativeType)
{
case NativeTypeKind.I1:
return context.GetWellKnownType(WellKnownType.SByte);
case NativeTypeKind.U1:
return context.GetWellKnownType(WellKnownType.Byte);
case NativeTypeKind.I2:
return context.GetWellKnownType(WellKnownType.Int16);
case NativeTypeKind.U2:
return context.GetWellKnownType(WellKnownType.UInt16);
case NativeTypeKind.I4:
return context.GetWellKnownType(WellKnownType.Int32);
case NativeTypeKind.U4:
return context.GetWellKnownType(WellKnownType.UInt32);
case NativeTypeKind.I8:
return context.GetWellKnownType(WellKnownType.Int64);
case NativeTypeKind.U8:
return context.GetWellKnownType(WellKnownType.UInt64);
case NativeTypeKind.R4:
return context.GetWellKnownType(WellKnownType.Single);
case NativeTypeKind.R8:
return context.GetWellKnownType(WellKnownType.Double);
default:
return type.UnderlyingType;
}
}
case MarshallerKind.Bool:
return context.GetWellKnownType(WellKnownType.Int32);
case MarshallerKind.CBool:
return context.GetWellKnownType(WellKnownType.Byte);
case MarshallerKind.Enum:
case MarshallerKind.BlittableStruct:
case MarshallerKind.Decimal:
case MarshallerKind.VoidReturn:
return type;
case MarshallerKind.Struct:
return interopStateManager.GetStructMarshallingNativeType((MetadataType)type);
case MarshallerKind.BlittableStructPtr:
return type.MakePointerType();
case MarshallerKind.HandleRef:
return context.GetWellKnownType(WellKnownType.IntPtr);
case MarshallerKind.UnicodeChar:
if (nativeType == NativeTypeKind.U2)
return context.GetWellKnownType(WellKnownType.UInt16);
else
return context.GetWellKnownType(WellKnownType.Int16);
case MarshallerKind.OleDateTime:
return context.GetWellKnownType(WellKnownType.Double);
case MarshallerKind.SafeHandle:
case MarshallerKind.CriticalHandle:
return context.GetWellKnownType(WellKnownType.IntPtr);
case MarshallerKind.UnicodeString:
case MarshallerKind.UnicodeStringBuilder:
return context.GetWellKnownType(WellKnownType.Char).MakePointerType();
case MarshallerKind.AnsiString:
case MarshallerKind.AnsiStringBuilder:
case MarshallerKind.UTF8String:
return context.GetWellKnownType(WellKnownType.Byte).MakePointerType();
case MarshallerKind.BlittableArray:
case MarshallerKind.Array:
case MarshallerKind.AnsiCharArray:
{
ArrayType arrayType = type as ArrayType;
Debug.Assert(arrayType != null, "Expecting array");
//
// We need to construct the unsafe array from the right unsafe array element type
//
TypeDesc elementNativeType = GetNativeTypeFromMarshallerKind(
arrayType.ElementType,
elementMarshallerKind,
MarshallerKind.Unknown,
interopStateManager,
marshalAs,
isArrayElement: true);
return elementNativeType.MakePointerType();
}
case MarshallerKind.AnsiChar:
return context.GetWellKnownType(WellKnownType.Byte);
case MarshallerKind.FunctionPointer:
return context.GetWellKnownType(WellKnownType.IntPtr);
case MarshallerKind.ByValUnicodeString:
case MarshallerKind.ByValAnsiString:
{
var inlineArrayCandidate = GetInlineArrayCandidate(context.GetWellKnownType(WellKnownType.Char), elementMarshallerKind, interopStateManager, marshalAs);
return interopStateManager.GetInlineArrayType(inlineArrayCandidate);
}
case MarshallerKind.ByValAnsiCharArray:
case MarshallerKind.ByValArray:
{
ArrayType arrayType = type as ArrayType;
Debug.Assert(arrayType != null, "Expecting array");
var inlineArrayCandidate = GetInlineArrayCandidate(arrayType.ElementType, elementMarshallerKind, interopStateManager, marshalAs);
return interopStateManager.GetInlineArrayType(inlineArrayCandidate);
}
case MarshallerKind.Unknown:
default:
throw new NotSupportedException();
}
}
internal static InlineArrayCandidate GetInlineArrayCandidate(TypeDesc managedElementType, MarshallerKind elementMarshallerKind, InteropStateManager interopStateManager, MarshalAsDescriptor marshalAs)
{
TypeDesc nativeType = GetNativeTypeFromMarshallerKind(
managedElementType,
elementMarshallerKind,
MarshallerKind.Unknown,
interopStateManager,
null);
var elementNativeType = nativeType as MetadataType;
if (elementNativeType == null)
{
Debug.Assert(nativeType.IsPointer || nativeType.IsFunctionPointer);
// If it is a pointer type we will create InlineArray for IntPtr
elementNativeType = (MetadataType)managedElementType.Context.GetWellKnownType(WellKnownType.IntPtr);
}
Debug.Assert(marshalAs != null && marshalAs.SizeConst.HasValue);
// if SizeConst is not specified, we will default to 1.
// the marshaller will throw appropriate exception
uint size = 1;
if (marshalAs.SizeConst.HasValue)
{
size = marshalAs.SizeConst.Value;
}
return new InlineArrayCandidate(elementNativeType, size);
}
internal static MarshallerKind GetMarshallerKind(
TypeDesc type,
MarshalAsDescriptor marshalAs,
bool isReturn,
bool isAnsi,
MarshallerType marshallerType,
out MarshallerKind elementMarshallerKind)
{
if (type.IsByRef)
{
type = type.GetParameterType();
}
TypeSystemContext context = type.Context;
NativeTypeKind nativeType = NativeTypeKind.Invalid;
bool isField = marshallerType == MarshallerType.Field;
if (marshalAs != null)
nativeType = (NativeTypeKind)marshalAs.Type;
elementMarshallerKind = MarshallerKind.Invalid;
//
// Determine MarshalerKind
//
// This mostly resembles desktop CLR and .NET Native code as we need to match their behavior
//
if (type.IsPrimitive)
{
switch (type.Category)
{
case TypeFlags.Void:
return MarshallerKind.VoidReturn;
case TypeFlags.Boolean:
switch (nativeType)
{
case NativeTypeKind.Invalid:
case NativeTypeKind.Boolean:
return MarshallerKind.Bool;
case NativeTypeKind.U1:
case NativeTypeKind.I1:
return MarshallerKind.CBool;
default:
return MarshallerKind.Invalid;
}
case TypeFlags.Char:
switch (nativeType)
{
case NativeTypeKind.I1:
case NativeTypeKind.U1:
return MarshallerKind.AnsiChar;
case NativeTypeKind.I2:
case NativeTypeKind.U2:
return MarshallerKind.UnicodeChar;
case NativeTypeKind.Invalid:
if (isAnsi)
return MarshallerKind.AnsiChar;
else
return MarshallerKind.UnicodeChar;
default:
return MarshallerKind.Invalid;
}
case TypeFlags.SByte:
case TypeFlags.Byte:
if (nativeType == NativeTypeKind.I1 || nativeType == NativeTypeKind.U1 || nativeType == NativeTypeKind.Invalid)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Int16:
case TypeFlags.UInt16:
if (nativeType == NativeTypeKind.I2 || nativeType == NativeTypeKind.U2 || nativeType == NativeTypeKind.Invalid)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Int32:
case TypeFlags.UInt32:
if (nativeType == NativeTypeKind.I4 || nativeType == NativeTypeKind.U4 || nativeType == NativeTypeKind.Invalid)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Int64:
case TypeFlags.UInt64:
if (nativeType == NativeTypeKind.I8 || nativeType == NativeTypeKind.U8 || nativeType == NativeTypeKind.Invalid)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.IntPtr:
case TypeFlags.UIntPtr:
if (nativeType == NativeTypeKind.Invalid)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Single:
if (nativeType == NativeTypeKind.R4 || nativeType == NativeTypeKind.Invalid)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Double:
if (nativeType == NativeTypeKind.R8 || nativeType == NativeTypeKind.Invalid)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
default:
return MarshallerKind.Invalid;
}
}
else if (type.IsValueType)
{
if (type.IsEnum)
return MarshallerKind.Enum;
if (InteropTypes.IsSystemDateTime(context, type))
{
if (nativeType == NativeTypeKind.Invalid ||
nativeType == NativeTypeKind.Struct)
return MarshallerKind.OleDateTime;
else
return MarshallerKind.Invalid;
}
else if (InteropTypes.IsHandleRef(context, type))
{
if (nativeType == NativeTypeKind.Invalid)
return MarshallerKind.HandleRef;
else
return MarshallerKind.Invalid;
}
switch (nativeType)
{
case NativeTypeKind.Invalid:
case NativeTypeKind.Struct:
if (InteropTypes.IsSystemDecimal(context, type))
return MarshallerKind.Decimal;
break;
case NativeTypeKind.LPStruct:
if (InteropTypes.IsSystemGuid(context, type) ||
InteropTypes.IsSystemDecimal(context, type))
{
if (isField || isReturn)
return MarshallerKind.Invalid;
else
return MarshallerKind.BlittableStructPtr;
}
break;
default:
return MarshallerKind.Invalid;
}
if (type is MetadataType)
{
MetadataType metadataType = (MetadataType)type;
// the struct type need to be either sequential or explicit. If it is
// auto layout we will throw exception.
if (!metadataType.IsSequentialLayout && !metadataType.IsExplicitLayout)
{
throw new InvalidProgramException("The specified structure " + metadataType.Name + " has invalid StructLayout information. It must be either Sequential or Explicit.");
}
}
if (MarshalUtils.IsBlittableType(type))
{
return MarshallerKind.BlittableStruct;
}
else
{
return MarshallerKind.Struct;
}
}
else if (type.IsSzArray)
{
if (nativeType == NativeTypeKind.Invalid)
nativeType = NativeTypeKind.Array;
switch (nativeType)
{
case NativeTypeKind.Array:
{
if (isField || isReturn)
return MarshallerKind.Invalid;
var arrayType = (ArrayType)type;
elementMarshallerKind = GetArrayElementMarshallerKind(
arrayType,
marshalAs,
isAnsi);
// If element is invalid type, the array itself is invalid
if (elementMarshallerKind == MarshallerKind.Invalid)
return MarshallerKind.Invalid;
if (elementMarshallerKind == MarshallerKind.AnsiChar)
return MarshallerKind.AnsiCharArray;
else if (elementMarshallerKind == MarshallerKind.UnicodeChar // Arrays of unicode char should be marshalled as blittable arrays
|| elementMarshallerKind == MarshallerKind.Enum
|| elementMarshallerKind == MarshallerKind.BlittableValue)
return MarshallerKind.BlittableArray;
else
return MarshallerKind.Array;
}
case NativeTypeKind.ByValArray: // fix sized array
{
var arrayType = (ArrayType)type;
elementMarshallerKind = GetArrayElementMarshallerKind(
arrayType,
marshalAs,
isAnsi);
// If element is invalid type, the array itself is invalid
if (elementMarshallerKind == MarshallerKind.Invalid)
return MarshallerKind.Invalid;
if (elementMarshallerKind == MarshallerKind.AnsiChar)
return MarshallerKind.ByValAnsiCharArray;
else
return MarshallerKind.ByValArray;
}
default:
return MarshallerKind.Invalid;
}
}
else if (type.IsPointer || type.IsFunctionPointer)
{
if (nativeType == NativeTypeKind.Invalid)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
}
else if (type.IsDelegate)
{
if (nativeType == NativeTypeKind.Invalid || nativeType == NativeTypeKind.Func)
return MarshallerKind.FunctionPointer;
else
return MarshallerKind.Invalid;
}
else if (type.IsString)
{
switch (nativeType)
{
case NativeTypeKind.LPWStr:
return MarshallerKind.UnicodeString;
case NativeTypeKind.LPStr:
return MarshallerKind.AnsiString;
case NativeTypeKind.LPUTF8Str:
return MarshallerKind.UTF8String;
case NativeTypeKind.LPTStr:
return MarshallerKind.UnicodeString;
case NativeTypeKind.ByValTStr:
if (isAnsi)
{
elementMarshallerKind = MarshallerKind.AnsiChar;
return MarshallerKind.ByValAnsiString;
}
else
{
elementMarshallerKind = MarshallerKind.UnicodeChar;
return MarshallerKind.ByValUnicodeString;
}
case NativeTypeKind.Invalid:
if (isAnsi)
return MarshallerKind.AnsiString;
else
return MarshallerKind.UnicodeString;
default:
return MarshallerKind.Invalid;
}
}
// else if (type.IsObject)
// {
// if (nativeType == NativeTypeKind.Invalid)
// return MarshallerKind.Variant;
// else
// return MarshallerKind.Invalid;
// }
else if (InteropTypes.IsStringBuilder(context, type))
{
switch (nativeType)
{
case NativeTypeKind.Invalid:
if (isAnsi)
{
return MarshallerKind.AnsiStringBuilder;
}
else
{
return MarshallerKind.UnicodeStringBuilder;
}
case NativeTypeKind.LPStr:
return MarshallerKind.AnsiStringBuilder;
case NativeTypeKind.LPWStr:
return MarshallerKind.UnicodeStringBuilder;
default:
return MarshallerKind.Invalid;
}
}
else if (InteropTypes.IsSafeHandle(context, type))
{
if (nativeType == NativeTypeKind.Invalid)
return MarshallerKind.SafeHandle;
else
return MarshallerKind.Invalid;
}
else if (InteropTypes.IsCriticalHandle(context, type))
{
if (nativeType == NativeTypeKind.Invalid)
return MarshallerKind.CriticalHandle;
else
return MarshallerKind.Invalid;
}
else
{
return MarshallerKind.Invalid;
}
}
private static MarshallerKind GetArrayElementMarshallerKind(
ArrayType arrayType,
MarshalAsDescriptor marshalAs,
bool isAnsi)
{
TypeDesc elementType = arrayType.ElementType;
NativeTypeKind nativeType = NativeTypeKind.Invalid;
TypeSystemContext context = arrayType.Context;
if (marshalAs != null)
nativeType = (NativeTypeKind)marshalAs.ArraySubType;
if (elementType.IsPrimitive)
{
switch (elementType.Category)
{
case TypeFlags.Char:
switch (nativeType)
{
case NativeTypeKind.I1:
case NativeTypeKind.U1:
return MarshallerKind.AnsiChar;
case NativeTypeKind.I2:
case NativeTypeKind.U2:
return MarshallerKind.UnicodeChar;
default:
if (isAnsi)
return MarshallerKind.AnsiChar;
else
return MarshallerKind.UnicodeChar;
}
case TypeFlags.Boolean:
switch (nativeType)
{
case NativeTypeKind.Boolean:
return MarshallerKind.Bool;
case NativeTypeKind.I1:
case NativeTypeKind.U1:
return MarshallerKind.CBool;
case NativeTypeKind.Invalid:
default:
return MarshallerKind.Bool;
}
case TypeFlags.IntPtr:
case TypeFlags.UIntPtr:
return MarshallerKind.BlittableValue;
case TypeFlags.Void:
return MarshallerKind.Invalid;
case TypeFlags.SByte:
case TypeFlags.Int16:
case TypeFlags.Int32:
case TypeFlags.Int64:
case TypeFlags.Byte:
case TypeFlags.UInt16:
case TypeFlags.UInt32:
case TypeFlags.UInt64:
case TypeFlags.Single:
case TypeFlags.Double:
return MarshallerKind.BlittableValue;
default:
return MarshallerKind.Invalid;
}
}
else if (elementType.IsValueType)
{
if (elementType.IsEnum)
return MarshallerKind.Enum;
if (InteropTypes.IsSystemDecimal(context, elementType))
{
switch (nativeType)
{
case NativeTypeKind.Invalid:
case NativeTypeKind.Struct:
return MarshallerKind.Decimal;
case NativeTypeKind.LPStruct:
return MarshallerKind.BlittableStructPtr;
default:
return MarshallerKind.Invalid;
}
}
else if (InteropTypes.IsSystemGuid(context, elementType))
{
switch (nativeType)
{
case NativeTypeKind.Invalid:
case NativeTypeKind.Struct:
return MarshallerKind.BlittableValue;
case NativeTypeKind.LPStruct:
return MarshallerKind.BlittableStructPtr;
default:
return MarshallerKind.Invalid;
}
}
else if (InteropTypes.IsSystemDateTime(context, elementType))
{
if (nativeType == NativeTypeKind.Invalid ||
nativeType == NativeTypeKind.Struct)
{
return MarshallerKind.OleDateTime;
}
else
{
return MarshallerKind.Invalid;
}
}
else if (InteropTypes.IsHandleRef(context, elementType))
{
if (nativeType == NativeTypeKind.Invalid)
return MarshallerKind.HandleRef;
else
return MarshallerKind.Invalid;
}
else
{
if (MarshalUtils.IsBlittableType(elementType))
{
switch (nativeType)
{
case NativeTypeKind.Invalid:
case NativeTypeKind.Struct:
return MarshallerKind.BlittableStruct;
default:
return MarshallerKind.Invalid;
}
}
else
{
// TODO: Differentiate between struct and Union, we only need to support struct not union here
return MarshallerKind.Struct;
}
}
}
else if (elementType.IsPointer || elementType.IsFunctionPointer)
{
if (nativeType == NativeTypeKind.Invalid)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
}
else if (elementType.IsString)
{
switch (nativeType)
{
case NativeTypeKind.Invalid:
if (isAnsi)
return MarshallerKind.AnsiString;
else
return MarshallerKind.UnicodeString;
case NativeTypeKind.LPStr:
return MarshallerKind.AnsiString;
case NativeTypeKind.LPWStr:
return MarshallerKind.UnicodeString;
default:
return MarshallerKind.Invalid;
}
}
// else if (elementType.IsObject)
// {
// if (nativeType == NativeTypeKind.Invalid)
// return MarshallerKind.Variant;
// else
// return MarshallerKind.Invalid;
// }
else
{
return MarshallerKind.Invalid;
}
}
//TODO: https://github.com/dotnet/corert/issues/2675
// This exception messages need to localized
// TODO: Log as warning
public static MethodIL EmitExceptionBody(string message, MethodDesc method)
{
ILEmitter emitter = new ILEmitter();
TypeSystemContext context = method.Context;
MethodSignature ctorSignature = new MethodSignature(0, 0, context.GetWellKnownType(WellKnownType.Void),
new TypeDesc[] { context.GetWellKnownType(WellKnownType.String) });
MethodDesc exceptionCtor = method.Context.GetWellKnownType(WellKnownType.Exception).GetKnownMethod(".ctor", ctorSignature);
ILCodeStream codeStream = emitter.NewCodeStream();
codeStream.Emit(ILOpcode.ldstr, emitter.NewToken(message));
codeStream.Emit(ILOpcode.newobj, emitter.NewToken(exceptionCtor));
codeStream.Emit(ILOpcode.throw_);
return new PInvokeILStubMethodIL((ILStubMethodIL)emitter.Link(method), isStubRequired: true);
}
}
}
| |
// Copyright 2014 Adrian Chlubek. This file is part of GTA Multiplayer IV project.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Web;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
using MIVSDK;
namespace MIVClientGUI
{
public partial class ServerBrowser : Form
{
private static ServerBrowser instance;
public ServerBrowser()
{
instance = this;
InitializeComponent();
loadConfiguration();
}
public static void refreshStatic()
{
instance.refreshList();
}
private void button1_Click(object sender, EventArgs e)
{
saveConfiguration();
ServerInfo server = listView1.SelectedItems[0].Tag as ServerInfo;
if (server != null && server.GamePort > 1)
{
string ini = "timestamp=" + System.Diagnostics.Stopwatch.GetTimestamp().ToString() + "\r\n";
ini += "ip=" + server.IP + "\r\n";
ini += "port=" + server.GamePort + "\r\n";
ini += "nickname=" + textBox1.Text + "\r\n";
File.WriteAllText("_serverinit.ini", ini);
new GameLaunchedForm().ShowDialog();
}
}
private void button2_Click(object sender, EventArgs e)
{
new AddServerForm().ShowDialog();
}
private void button3_Click(object sender, EventArgs e)
{
listView1.SelectedItems[0].Remove();
System.IO.File.Delete("servers.list");
foreach (ListViewItem server in listView1.Items)
{
var info = (ServerInfo)server.Tag;
System.IO.File.AppendAllLines("servers.list", new string[1]{
info.IP + ":" + info.Port
});
}
refreshList();
}
private void button4_Click(object sender, EventArgs e)
{
refreshList();
}
private ListViewItem createListItem(string servername, string ip, string ports, string playercount)
{
ListViewItem item = new ListViewItem(new string[4]{
servername, ip, ports, playercount
});
//item.Font = new System.Drawing.Font(new FontFamily("Segoe UI"), 16.0f, FontStyle.Regular);
return item;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
string message = "Are you sure want to close MIV2?";
string caption = "Close MIV";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
result = MessageBox.Show(this, message, caption, buttons);
if (result == DialogResult.Yes)
{
this.Close();
}
}
private void listView1_Click(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
button1.Enabled = true;
button3.Enabled = true;
}
else
{
button1.Enabled = false;
button3.Enabled = false;
}
}
private void listView1_Leave(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
button1.Enabled = true;
button3.Enabled = true;
}
else
{
button1.Enabled = false;
button3.Enabled = false;
}
}
private void loadConfiguration()
{
if (System.IO.File.Exists("miv_client_config.ini"))
{
var ini = new INIReader(System.IO.File.ReadAllLines("miv_client_config.ini"));
textBox1.Text = ini.getString("nickname");
}
}
private List<ServerInfo> loadFromFile()
{
var servers = new List<ServerInfo>();
string[] lines = File.ReadAllLines("servers.list");
foreach (string line in lines)
{
if (line.Length > 0)
{
try
{
string[] split = line.Split(':');
servers.Add(new ServerInfo()
{
IP = split[0],
Port = short.Parse(split[1])
});
}
catch { }
}
}
return servers;
}
private void refreshList()
{
if (!File.Exists("servers.list"))
{
File.WriteAllText("servers.list", "");
}
listView1.Items.Clear();
var servers = loadFromFile();
foreach (ServerInfo server in servers)
{
new Task(new Action(delegate
{
try
{
var request = HttpWebRequest.CreateHttp("http://" + server.IP + ":" + server.Port.ToString() + "/get_server_data");
var response = (HttpWebResponse)request.GetResponse();
string ini = new StreamReader(response.GetResponseStream()).ReadToEnd();
INIReader reader = new INIReader(ini.Split('\n'));
response.Close();
server.GamePort = reader.getInt16("game_port");
ListViewItem item = createListItem(reader.getString("name"), server.IP, server.Port.ToString() + "." + server.GamePort.ToString(), reader.getString("players") + "/" + reader.getString("max_players"));
item.Tag = server;
listView1.Items.Add(item);
}
catch
{
ListViewItem item = createListItem("Offline", server.IP, server.Port.ToString() + "." + server.GamePort.ToString(), "-");
listView1.Items.Add(item);
}
})).Start();
}
}
private void runGameWithoutClientToolStripMenuItem_Click(object sender, EventArgs e)
{
FileSystemOverlay.prepareForSP();
Process gameProcess = new Process();
gameProcess.StartInfo = new ProcessStartInfo("LaunchGTAIV.exe");
gameProcess.Start();
}
private void saveConfiguration()
{
string ini = "nickname=" + textBox1.Text;
System.IO.File.WriteAllText("miv_client_config.ini", ini);
}
private void ServerBrowser_Load(object sender, EventArgs e)
{
refreshList();
FileSystemOverlay.prepareForSP();
}
private void textBox1_Leave(object sender, EventArgs e)
{
saveConfiguration();
}
class ServerInfo
{
public short GamePort;
public string IP;
public short Port;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using System.Web.Http.Filters;
using Apress.Recipes.WebApi.Areas.HelpPage.ModelDescriptions;
using Apress.Recipes.WebApi.Areas.HelpPage.Models;
namespace Apress.Recipes.WebApi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
if (apiDescription.ActionDescriptor.GetFilterPipeline().Any(x => x.Instance is IAuthorizationFilter))
apiModel.RequiresAuthorization = true;
if (apiDescription.ActionDescriptor.GetFilterPipeline().Any(x => x.Instance is CachedAttribute))
apiModel.IsCached = true;
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
if (complexTypeDescription != null)
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
namespace Zu.ChromeDevTools.CSS
{
using System;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Represents an adapter for the CSS domain to simplify the command interface.
/// </summary>
public class CSSAdapter
{
private readonly ChromeSession m_session;
public CSSAdapter(ChromeSession session)
{
m_session = session ?? throw new ArgumentNullException(nameof(session));
}
/// <summary>
/// Gets the ChromeSession associated with the adapter.
/// </summary>
public ChromeSession Session
{
get { return m_session; }
}
/// <summary>
/// Inserts a new rule with the given `ruleText` in a stylesheet with given `styleSheetId`, at the
/// position specified by `location`.
/// </summary>
public async Task<AddRuleCommandResponse> AddRule(AddRuleCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<AddRuleCommand, AddRuleCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Returns all class names from specified stylesheet.
/// </summary>
public async Task<CollectClassNamesCommandResponse> CollectClassNames(CollectClassNamesCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<CollectClassNamesCommand, CollectClassNamesCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Creates a new special "via-inspector" stylesheet in the frame with given `frameId`.
/// </summary>
public async Task<CreateStyleSheetCommandResponse> CreateStyleSheet(CreateStyleSheetCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<CreateStyleSheetCommand, CreateStyleSheetCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Disables the CSS agent for the given page.
/// </summary>
public async Task<DisableCommandResponse> Disable(DisableCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<DisableCommand, DisableCommandResponse>(command ?? new DisableCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Enables the CSS agent for the given page. Clients should not assume that the CSS agent has been
/// enabled until the result of this command is received.
/// </summary>
public async Task<EnableCommandResponse> Enable(EnableCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<EnableCommand, EnableCommandResponse>(command ?? new EnableCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Ensures that the given node will have specified pseudo-classes whenever its style is computed by
/// the browser.
/// </summary>
public async Task<ForcePseudoStateCommandResponse> ForcePseudoState(ForcePseudoStateCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<ForcePseudoStateCommand, ForcePseudoStateCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
///
/// </summary>
public async Task<GetBackgroundColorsCommandResponse> GetBackgroundColors(GetBackgroundColorsCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<GetBackgroundColorsCommand, GetBackgroundColorsCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Returns the computed style for a DOM node identified by `nodeId`.
/// </summary>
public async Task<GetComputedStyleForNodeCommandResponse> GetComputedStyleForNode(GetComputedStyleForNodeCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<GetComputedStyleForNodeCommand, GetComputedStyleForNodeCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Returns the styles defined inline (explicitly in the "style" attribute and implicitly, using DOM
/// attributes) for a DOM node identified by `nodeId`.
/// </summary>
public async Task<GetInlineStylesForNodeCommandResponse> GetInlineStylesForNode(GetInlineStylesForNodeCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<GetInlineStylesForNodeCommand, GetInlineStylesForNodeCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Returns requested styles for a DOM node identified by `nodeId`.
/// </summary>
public async Task<GetMatchedStylesForNodeCommandResponse> GetMatchedStylesForNode(GetMatchedStylesForNodeCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<GetMatchedStylesForNodeCommand, GetMatchedStylesForNodeCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Returns all media queries parsed by the rendering engine.
/// </summary>
public async Task<GetMediaQueriesCommandResponse> GetMediaQueries(GetMediaQueriesCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<GetMediaQueriesCommand, GetMediaQueriesCommandResponse>(command ?? new GetMediaQueriesCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Requests information about platform fonts which we used to render child TextNodes in the given
/// node.
/// </summary>
public async Task<GetPlatformFontsForNodeCommandResponse> GetPlatformFontsForNode(GetPlatformFontsForNodeCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<GetPlatformFontsForNodeCommand, GetPlatformFontsForNodeCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Returns the current textual content for a stylesheet.
/// </summary>
public async Task<GetStyleSheetTextCommandResponse> GetStyleSheetText(GetStyleSheetTextCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<GetStyleSheetTextCommand, GetStyleSheetTextCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Find a rule with the given active property for the given node and set the new value for this
/// property
/// </summary>
public async Task<SetEffectivePropertyValueForNodeCommandResponse> SetEffectivePropertyValueForNode(SetEffectivePropertyValueForNodeCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<SetEffectivePropertyValueForNodeCommand, SetEffectivePropertyValueForNodeCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Modifies the keyframe rule key text.
/// </summary>
public async Task<SetKeyframeKeyCommandResponse> SetKeyframeKey(SetKeyframeKeyCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<SetKeyframeKeyCommand, SetKeyframeKeyCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Modifies the rule selector.
/// </summary>
public async Task<SetMediaTextCommandResponse> SetMediaText(SetMediaTextCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<SetMediaTextCommand, SetMediaTextCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Modifies the rule selector.
/// </summary>
public async Task<SetRuleSelectorCommandResponse> SetRuleSelector(SetRuleSelectorCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<SetRuleSelectorCommand, SetRuleSelectorCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Sets the new stylesheet text.
/// </summary>
public async Task<SetStyleSheetTextCommandResponse> SetStyleSheetText(SetStyleSheetTextCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<SetStyleSheetTextCommand, SetStyleSheetTextCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Applies specified style edits one after another in the given order.
/// </summary>
public async Task<SetStyleTextsCommandResponse> SetStyleTexts(SetStyleTextsCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<SetStyleTextsCommand, SetStyleTextsCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Enables the selector recording.
/// </summary>
public async Task<StartRuleUsageTrackingCommandResponse> StartRuleUsageTracking(StartRuleUsageTrackingCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<StartRuleUsageTrackingCommand, StartRuleUsageTrackingCommandResponse>(command ?? new StartRuleUsageTrackingCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Stop tracking rule usage and return the list of rules that were used since last call to
/// `takeCoverageDelta` (or since start of coverage instrumentation)
/// </summary>
public async Task<StopRuleUsageTrackingCommandResponse> StopRuleUsageTracking(StopRuleUsageTrackingCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<StopRuleUsageTrackingCommand, StopRuleUsageTrackingCommandResponse>(command ?? new StopRuleUsageTrackingCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Obtain list of rules that became used since last call to this method (or since start of coverage
/// instrumentation)
/// </summary>
public async Task<TakeCoverageDeltaCommandResponse> TakeCoverageDelta(TakeCoverageDeltaCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<TakeCoverageDeltaCommand, TakeCoverageDeltaCommandResponse>(command ?? new TakeCoverageDeltaCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Fires whenever a web font is updated. A non-empty font parameter indicates a successfully loaded
/// web font
/// </summary>
public void SubscribeToFontsUpdatedEvent(Action<FontsUpdatedEvent> eventCallback)
{
m_session.Subscribe(eventCallback);
}
/// <summary>
/// Fires whenever a MediaQuery result changes (for example, after a browser window has been
/// resized.) The current implementation considers only viewport-dependent media features.
/// </summary>
public void SubscribeToMediaQueryResultChangedEvent(Action<MediaQueryResultChangedEvent> eventCallback)
{
m_session.Subscribe(eventCallback);
}
/// <summary>
/// Fired whenever an active document stylesheet is added.
/// </summary>
public void SubscribeToStyleSheetAddedEvent(Action<StyleSheetAddedEvent> eventCallback)
{
m_session.Subscribe(eventCallback);
}
/// <summary>
/// Fired whenever a stylesheet is changed as a result of the client operation.
/// </summary>
public void SubscribeToStyleSheetChangedEvent(Action<StyleSheetChangedEvent> eventCallback)
{
m_session.Subscribe(eventCallback);
}
/// <summary>
/// Fired whenever an active document stylesheet is removed.
/// </summary>
public void SubscribeToStyleSheetRemovedEvent(Action<StyleSheetRemovedEvent> eventCallback)
{
m_session.Subscribe(eventCallback);
}
}
}
| |
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
namespace Moscrif.IDE.Tool
{
class IniFile
{
private String iniFilePath;
public String IniPath
{
get { return iniFilePath; }
}
private static Char decSep = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator.ToCharArray()[0];
private static Regex keyValRegex = new Regex(@"((\s)*(?<Key>([^\=^\n]+))[\s^\n]*\=(\s)*(?<Value>([^\n]+(\n){0,1})))", RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static Regex secRegex = new Regex(@"(\[)*(?<Section>([^\]^\n]+))(\])", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private ArrayList newValues = new ArrayList();
struct sectKeyVal
{
public String section, key, value;
public sectKeyVal(String section, String key, String value)
{
this.section = section;
this.key = key;
this.value = value;
}
}
public IniFile(String iniFilePath)
{
this.iniFilePath = iniFilePath;
}
/*~IniFile()
{
Flush();
}*/
private bool isThisTheSection(String line, ref String sectionName)
{
Match match = secRegex.Match(line);
if (match.Success) {
String currSection = match.Groups["Section"].Value as String;
return (currSection != null && currSection.CompareTo(sectionName) == 0);
}
return false;
}
private bool isThisTheKey(String line, ref String key, ref String value)
{
Match match = keyValRegex.Match(line);
if (match.Success) {
String currKey = match.Groups["Key"].Value as String;
if (currKey != null && currKey.CompareTo(key) == 0) {
value = match.Groups["Value"].Value as String;
return true;
}
} else if (secRegex.Match(line).Success)
value = "Section";
// Oops, we're at the next section
return false;
}
public String ReadString(String section, String key, String defaultValue)
{
FileStream fileStream = new FileStream(iniFilePath, FileMode.OpenOrCreate, FileAccess.Read);
TextReader reader = new StreamReader(fileStream);
bool sectionFound = false;
String line;
while ((line = reader.ReadLine()) != null)
/* First we find our section,
then - the key */
if (!sectionFound)
sectionFound = isThisTheSection(line, ref section);
else {
String value = "";
if (isThisTheKey(line, ref key, ref value)) {
fileStream.Close();
return value;
}
}
fileStream.Close();
return defaultValue;
}
public int ReadInt(String section, String key, int defaultValue)
{
return Int32.Parse(ReadString(section, key, defaultValue.ToString()));
}
public Double ReadDouble(String section, String key, Double defaultValue)
{
return Double.Parse(ReadString(section, key, defaultValue.ToString()).Replace('.', decSep).Replace(',', decSep));
}
public void WriteString(String section, String key, String value)
{
int sameKeyNum = -1;
for (int i = 0; i < newValues.Count; i++) {
sectKeyVal s = (sectKeyVal)newValues[i];
if ((s.section == section) && (s.key == key))
sameKeyNum = i;
}
if (sameKeyNum != -1)
newValues.RemoveAt(sameKeyNum);
newValues.Add(new sectKeyVal(section, key, value));
}
public void Flush()
{
/* This is where all the magic is done
We read our INI file, parse the
new values and add them to the file
before we write it */
// First we read our file
FileStream fileStream = new FileStream(iniFilePath, FileMode.OpenOrCreate, FileAccess.Read);
TextReader reader = new StreamReader(fileStream);
String[] lines = reader.ReadToEnd().Replace('\r', '\0').Split('\n');
fileStream.Close();
// Create our work list and fill it
List<String> linesList = new List<String>();
foreach (String s in lines)
linesList.Add(s);
// linesList.Add(s);
foreach (sectKeyVal s in newValues) {
String section = s.section;
String key = s.key;
String value = s.value;
bool sectionFound = false, keyFound = false;
String keyval = "";
List<String> tempList = new List<String>();
for (int i = 0; i < linesList.Count; i++) {
String line = linesList[i];
// Did we find our section yet?
if (!sectionFound)
sectionFound = isThisTheSection(linesList[i], ref section);
else {
// Did we find our key?
if (isThisTheKey(linesList[i], ref key, ref keyval)) {
if (value != keyval)
line = key + "=" + value;
keyFound = true;
} else if (keyval == "Section" && !keyFound) {
/* We found the beginning of
the next section. */
keyval = "";
keyFound = true;
if (linesList[i - 1].Trim() == "")
tempList[tempList.Count - 1] = key + "=" + value;
else
tempList.Add(key + "=" + value);
tempList.Add("");
} else if (i == linesList.Count - 1 && !keyFound)
/* Looks like we're at the end of file
and we found our section */ tempList.Add(key + "=" + value);
}
tempList.Add(line.TrimEnd('\0'));
}
linesList = tempList;
/* The section or the key weren't found
so we add them */
if (!sectionFound && !keyFound) {
if (linesList.Count == 1 && linesList[linesList.Count - 1].Trim() == "")
linesList.RemoveAt(0);
else
linesList.Add("");
linesList.Add("[" + section + "]");
linesList.Add(key + "=" + value);
}
}
// Finally write our file
fileStream = new FileStream(iniFilePath, FileMode.Create, FileAccess.Write);
TextWriter writer = new StreamWriter(fileStream);
for (int i = 0; i < linesList.Count; i++)
if (!((i == linesList.Count - 1) && (linesList[i].Trim() == "")))
writer.WriteLine(linesList[i]);
writer.Flush();
fileStream.Close();
}
public void WriteInt(String section, String key, int value)
{
WriteString(section, key, value.ToString());
}
public void WriteDouble(String section, String key, Double value)
{
WriteString(section, key, value.ToString());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace ModestTree
{
public static class TypeExtensions
{
public static bool DerivesFrom<T>(this Type a)
{
return DerivesFrom(a, typeof(T));
}
// This seems easier to think about than IsAssignableFrom
public static bool DerivesFrom(this Type a, Type b)
{
return b != a && a.DerivesFromOrEqual(b);
}
public static bool DerivesFromOrEqual<T>(this Type a)
{
return DerivesFromOrEqual(a, typeof(T));
}
public static bool DerivesFromOrEqual(this Type a, Type b)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return b == a || b.GetTypeInfo().IsAssignableFrom(a.GetTypeInfo());
#else
return b == a || b.IsAssignableFrom(a);
#endif
}
public static bool IsEnum(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().IsEnum;
#else
return type.IsEnum;
#endif
}
public static bool IsValueType(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().IsValueType;
#else
return type.IsValueType;
#endif
}
public static MethodInfo[] DeclaredInstanceMethods(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetRuntimeMethods()
.Where(x => x.DeclaringType == type).ToArray();
#else
return type.GetMethods(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
#endif
}
public static PropertyInfo[] DeclaredInstanceProperties(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
// There doesn't appear to be an IsStatic member on PropertyInfo
return type.GetRuntimeProperties()
.Where(x => x.DeclaringType == type).ToArray();
#else
return type.GetProperties(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
#endif
}
public static FieldInfo[] DeclaredInstanceFields(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetRuntimeFields()
.Where(x => x.DeclaringType == type && !x.IsStatic).ToArray();
#else
return type.GetFields(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
#endif
}
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
public static bool IsAssignableFrom(this Type a, Type b)
{
return a.GetTypeInfo().IsAssignableFrom(b.GetTypeInfo());
}
#endif
public static Type BaseType(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().BaseType;
#else
return type.BaseType;
#endif
}
public static bool IsGenericType(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().IsGenericType;
#else
return type.IsGenericType;
#endif
}
public static bool IsGenericTypeDefinition(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().IsGenericTypeDefinition;
#else
return type.IsGenericType;
#endif
}
public static bool IsPrimitive(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().IsPrimitive;
#else
return type.IsPrimitive;
#endif
}
public static bool IsInterface(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().IsInterface;
#else
return type.IsInterface;
#endif
}
public static bool IsAbstract(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().IsAbstract;
#else
return type.IsAbstract;
#endif
}
public static MethodInfo Method(this Delegate del)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return del.GetMethodInfo();
#else
return del.Method;
#endif
}
public static Type[] GenericArguments(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().GenericTypeArguments;
#else
return type.GetGenericArguments();
#endif
}
public static Type[] Interfaces(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().ImplementedInterfaces.ToArray();
#else
return type.GetInterfaces();
#endif
}
public static ConstructorInfo[] Constructors(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().DeclaredConstructors.ToArray();
#else
return type.GetConstructors(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
#endif
}
public static object GetDefaultValue(this Type type)
{
if (type.IsValueType())
{
return Activator.CreateInstance(type);
}
return null;
}
// Returns name without generic arguments
public static string GetSimpleName(this Type type)
{
var name = type.Name;
var quoteIndex = name.IndexOf("`");
if (quoteIndex == -1)
{
return name;
}
// Remove the backtick
return name.Substring(0, quoteIndex);
}
public static IEnumerable<Type> GetParentTypes(this Type type)
{
if (type == null || type.BaseType() == null || type == typeof(object) || type.BaseType() == typeof(object))
{
yield break;
}
yield return type.BaseType();
foreach (var ancestor in type.BaseType().GetParentTypes())
{
yield return ancestor;
}
}
public static string NameWithParents(this Type type)
{
var typeList = type.GetParentTypes().Prepend(type).Select(x => x.Name()).ToArray();
return string.Join(":", typeList);
}
public static bool IsClosedGenericType(this Type type)
{
return type.IsGenericType() && type != type.GetGenericTypeDefinition();
}
public static bool IsOpenGenericType(this Type type)
{
return type.IsGenericType() && type == type.GetGenericTypeDefinition();
}
// Returns all instance fields, including private and public and also those in base classes
public static IEnumerable<FieldInfo> GetAllInstanceFields(this Type type)
{
foreach (var fieldInfo in type.DeclaredInstanceFields())
{
yield return fieldInfo;
}
if (type.BaseType() != null && type.BaseType() != typeof(object))
{
foreach (var fieldInfo in type.BaseType().GetAllInstanceFields())
{
yield return fieldInfo;
}
}
}
// Returns all instance properties, including private and public and also those in base classes
public static IEnumerable<PropertyInfo> GetAllInstanceProperties(this Type type)
{
foreach (var propInfo in type.DeclaredInstanceProperties())
{
yield return propInfo;
}
if (type.BaseType() != null && type.BaseType() != typeof(object))
{
foreach (var propInfo in type.BaseType().GetAllInstanceProperties())
{
yield return propInfo;
}
}
}
// Returns all instance methods, including private and public and also those in base classes
public static IEnumerable<MethodInfo> GetAllInstanceMethods(this Type type)
{
foreach (var methodInfo in type.DeclaredInstanceMethods())
{
yield return methodInfo;
}
if (type.BaseType() != null && type.BaseType() != typeof(object))
{
foreach (var methodInfo in type.BaseType().GetAllInstanceMethods())
{
yield return methodInfo;
}
}
}
public static string Name(this Type type)
{
if (type.IsArray)
{
return string.Format("{0}[]", type.GetElementType().Name());
}
return (type.DeclaringType == null ? "" : type.DeclaringType.Name() + ".") + GetCSharpTypeName(type.Name);
}
static string GetCSharpTypeName(string typeName)
{
switch (typeName)
{
case "String":
case "Object":
case "Void":
case "Byte":
case "Double":
case "Decimal":
return typeName.ToLower();
case "Int16":
return "short";
case "Int32":
return "int";
case "Int64":
return "long";
case "Single":
return "float";
case "Boolean":
return "bool";
default:
return typeName;
}
}
public static T GetAttribute<T>(this MemberInfo provider)
where T : Attribute
{
return provider.AllAttributes<T>().Single();
}
public static T TryGetAttribute<T>(this MemberInfo provider)
where T : Attribute
{
return provider.AllAttributes<T>().OnlyOrDefault();
}
public static bool HasAttribute(
this MemberInfo provider, params Type[] attributeTypes)
{
return provider.AllAttributes(attributeTypes).Any();
}
public static bool HasAttribute<T>(this MemberInfo provider)
where T : Attribute
{
return provider.AllAttributes(typeof(T)).Any();
}
public static IEnumerable<T> AllAttributes<T>(
this MemberInfo provider)
where T : Attribute
{
return provider.AllAttributes(typeof(T)).Cast<T>();
}
public static IEnumerable<Attribute> AllAttributes(
this MemberInfo provider, params Type[] attributeTypes)
{
var allAttributes = provider.GetCustomAttributes(true).Cast<Attribute>();
if (attributeTypes.Length == 0)
{
return allAttributes;
}
return allAttributes.Where(a => attributeTypes.Any(x => a.GetType().DerivesFromOrEqual(x)));
}
// We could avoid this duplication here by using ICustomAttributeProvider but this class
// does not exist on the WP8 platform
public static bool HasAttribute(
this ParameterInfo provider, params Type[] attributeTypes)
{
return provider.AllAttributes(attributeTypes).Any();
}
public static bool HasAttribute<T>(this ParameterInfo provider)
where T : Attribute
{
return provider.AllAttributes(typeof(T)).Any();
}
public static IEnumerable<T> AllAttributes<T>(
this ParameterInfo provider)
where T : Attribute
{
return provider.AllAttributes(typeof(T)).Cast<T>();
}
public static IEnumerable<Attribute> AllAttributes(
this ParameterInfo provider, params Type[] attributeTypes)
{
var allAttributes = provider.GetCustomAttributes(true).Cast<Attribute>();
if (attributeTypes.Length == 0)
{
return allAttributes;
}
return allAttributes.Where(a => attributeTypes.Any(x => a.GetType().DerivesFromOrEqual(x)));
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
namespace Microsoft.Live
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Web;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// This class is designed to help .Net app developers handle user authentication/authorization process.
/// </summary>
public class LiveAuthClient : INotifyPropertyChanged
{
private readonly LiveAuthClientCore authClient;
private LiveConnectSession session;
private bool sessionChanged;
private SynchronizationContextWrapper syncContext;
/// <summary>
/// Initializes an instance of LiveAuthClient class.
/// </summary>
/// <param name="clientId">The client Id of the app.</param>
/// <param name="clientSecret">The client secret of the app.</param>
public LiveAuthClient(string clientId)
: this(clientId, null)
{
}
/// <summary>
/// Initializes an instance of LiveAuthClient class.
/// </summary>
/// <param name="clientId">The client Id of the app.</param>
/// <param name="refreshTokenHandler">An IRefreshTokenHandler instance to handle refresh token persistency and retrieval.</param>
public LiveAuthClient(
string clientId,
IRefreshTokenHandler refreshTokenHandler)
{
LiveUtility.ValidateNotNullOrWhiteSpaceString(clientId, "clientId");
this.authClient = new LiveAuthClientCore(clientId, refreshTokenHandler, this);
this.syncContext = SynchronizationContextWrapper.Current;
}
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
#if DEBUG
/// <summary>
/// Allows the application to override the default auth server host name.
/// </summary>
public static string AuthEndpointOverride { get; set; }
#endif
/// <summary>
/// Gets the current session.
/// </summary>
public LiveConnectSession Session
{
get
{
return this.session;
}
internal set
{
if (this.session != value)
{
this.session = value;
this.sessionChanged = true;
}
}
}
/// <summary>
/// Initializes the LiveAuthClient instance by trying to retrieve an access token using refresh token
/// provided by the app via the IRefreshTokenHandler instance.
/// </summary>
/// <returns>An async Task instance</returns>
public Task<LiveLoginResult> InitializeAsync()
{
return this.InitializeAsync(new string[] { });
}
/// <summary>
/// Initializes the LiveAuthClient instance.
/// This will trigger retrieving token with refresh token process if the app provides the refresh token via
/// IRefreshTokenHandler.RetrieveRefreshTokenAsync method.
/// </summary>
/// <param name="scopes">The list of offers that the application is requesting user to consent for.</param>
/// <returns>An async Task instance.</returns>
public Task<LiveLoginResult> InitializeAsync(IEnumerable<string> scopes)
{
LiveUtility.ValidateNotNullParameter(scopes, "scopes");
return this.authClient.InitializeAsync(scopes);
}
/// <summary>
/// Exchange authentication code for access token.
/// </summary>
/// <param name="AuthenticationCode">The authentication code the app received from Microsoft authorization
/// server during the user authorization process.</param>
/// <returns></returns>
public Task<LiveConnectSession> ExchangeAuthCodeAsync(string authenticationCode)
{
LiveUtility.ValidateNotNullOrWhiteSpaceString(authenticationCode, "authenticationCode");
return this.authClient.ExchangeAuthCodeAsync(authenticationCode);
}
/// <summary>
/// Generates a consent URL that includes a set of provided parameters.
/// </summary>
/// <param name="scopes">A list of scope values that the user will need to authorize.</param>
/// <returns>The generated login URL value.</returns>
public string GetLoginUrl(IEnumerable<string> scopes)
{
return this.GetLoginUrl(scopes, null);
}
/// <summary>
/// Generates a consent URL that includes a set of provided parameters.
/// </summary>
/// <param name="scopes">A list of scope values that the user will need to authorize.</param>
/// <param name="options">A table of optional authorization parameters to be encoded into the URL.</param>
/// <returns>The generated login URL value.</returns>
public string GetLoginUrl(IEnumerable<string> scopes, IDictionary<string, string> options)
{
LiveUtility.ValidateNotEmptyStringEnumeratorArguement(scopes, "scopes");
string locale = null;
string state = null;
DisplayType display = DisplayType.WinDesktop;
ThemeType theme = ThemeType.Win8;
string redirectUrl = LiveAuthUtility.BuildDesktopRedirectUrl();
if (options != null)
{
if (options.ContainsKey(AuthConstants.Locale))
{
locale = options[AuthConstants.Locale];
}
if (options.ContainsKey(AuthConstants.ClientState))
{
state = options[AuthConstants.ClientState];
}
if (options.ContainsKey(AuthConstants.Display))
{
string displayStr = options[AuthConstants.Display];
if (!Enum.TryParse<DisplayType>(displayStr, true, out display))
{
throw new ArgumentException(ErrorText.ParameterInvalidDisplayValue, "display");
}
}
if (options.ContainsKey(AuthConstants.Theme))
{
string themeStr = options[AuthConstants.Theme];
if (!Enum.TryParse<ThemeType>(themeStr, true, out theme))
{
throw new ArgumentException(ErrorText.ParameterInvalidDisplayValue, "theme");
}
}
}
if (locale == null)
{
locale = CultureInfo.CurrentUICulture.ToString();
}
return this.authClient.GetLoginUrl(scopes, redirectUrl, display, theme, locale, state);
}
/// <summary>
/// Gets the logout URL.
/// </summary>
/// <returns>The logout URL.</returns>
public string GetLogoutUrl()
{
return LiveAuthUtility.BuildLogoutUrl();
}
/// <summary>
/// This method is used to ensure that the property changed event is only invoked once during the execution of
/// InitUserPresentAsync and InitUserAbsentAsync methods.
/// </summary>
internal void FirePendingPropertyChangedEvents()
{
if (this.sessionChanged)
{
this.OnPropertyChanged("Session");
this.sessionChanged = false;
}
}
internal bool RefreshToken(Action<LiveLoginResult> completionCallback)
{
bool noValidSession = (this.session == null || !this.session.IsValid);
if (noValidSession && this.authClient.CanRefreshToken)
{
this.authClient.TryRefreshToken(completionCallback);
return true;
}
return false;
}
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
this.syncContext.Post(() =>
{
handler(this, new PropertyChangedEventArgs(propertyName));
});
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using OpenSim.Region.Physics.Manager;
using PrimMesher;
namespace OpenSim.Region.Physics.Meshing
{
public class Mesh : IMesh
{
public List<Vertex> vertices;
public List<Triangle> triangles;
GCHandle pinnedVirtexes;
GCHandle pinnedIndex;
public PrimMesh primMesh = null;
public float[] normals;
public Mesh()
{
vertices = new List<Vertex>();
triangles = new List<Triangle>();
}
public Mesh Clone()
{
Mesh result = new Mesh();
foreach (Vertex v in vertices)
{
if (v == null)
result.vertices.Add(null);
else
result.vertices.Add(v.Clone());
}
foreach (Triangle t in triangles)
{
int iV1, iV2, iV3;
iV1 = vertices.IndexOf(t.v1);
iV2 = vertices.IndexOf(t.v2);
iV3 = vertices.IndexOf(t.v3);
Triangle newT = new Triangle(result.vertices[iV1], result.vertices[iV2], result.vertices[iV3]);
result.Add(newT);
}
return result;
}
public void Add(Triangle triangle)
{
int i;
i = vertices.IndexOf(triangle.v1);
if (i < 0)
throw new ArgumentException("Vertex v1 not known to mesh");
i = vertices.IndexOf(triangle.v2);
if (i < 0)
throw new ArgumentException("Vertex v2 not known to mesh");
i = vertices.IndexOf(triangle.v3);
if (i < 0)
throw new ArgumentException("Vertex v3 not known to mesh");
triangles.Add(triangle);
}
public void Add(Vertex v)
{
vertices.Add(v);
}
public void Remove(Vertex v)
{
int i;
// First, remove all triangles that are build on v
for (i = 0; i < triangles.Count; i++)
{
Triangle t = triangles[i];
if (t.v1 == v || t.v2 == v || t.v3 == v)
{
triangles.RemoveAt(i);
i--;
}
}
// Second remove v itself
vertices.Remove(v);
}
public void Add(List<Vertex> lv)
{
foreach (Vertex v in lv)
{
vertices.Add(v);
}
}
public void CalcNormals()
{
int iTriangles = triangles.Count;
this.normals = new float[iTriangles * 3];
int i = 0;
foreach (Triangle t in triangles)
{
float ux, uy, uz;
float vx, vy, vz;
float wx, wy, wz;
ux = t.v1.X;
uy = t.v1.Y;
uz = t.v1.Z;
vx = t.v2.X;
vy = t.v2.Y;
vz = t.v2.Z;
wx = t.v3.X;
wy = t.v3.Y;
wz = t.v3.Z;
// Vectors for edges
float e1x, e1y, e1z;
float e2x, e2y, e2z;
e1x = ux - vx;
e1y = uy - vy;
e1z = uz - vz;
e2x = ux - wx;
e2y = uy - wy;
e2z = uz - wz;
// Cross product for normal
float nx, ny, nz;
nx = e1y * e2z - e1z * e2y;
ny = e1z * e2x - e1x * e2z;
nz = e1x * e2y - e1y * e2x;
// Length
float l = (float)Math.Sqrt(nx * nx + ny * ny + nz * nz);
float lReciprocal = 1.0f / l;
// Normalized "normal"
//nx /= l;
//ny /= l;
//nz /= l;
normals[i] = nx * lReciprocal;
normals[i + 1] = ny * lReciprocal;
normals[i + 2] = nz * lReciprocal;
i += 3;
}
}
public List<PhysicsVector> getVertexList()
{
List<PhysicsVector> result = new List<PhysicsVector>();
foreach (Vertex v in vertices)
{
result.Add(v);
}
return result;
}
public float[] getVertexListAsFloatLocked()
{
float[] result;
if (primMesh == null)
{
result = new float[vertices.Count * 3];
for (int i = 0; i < vertices.Count; i++)
{
Vertex v = vertices[i];
if (v == null)
continue;
result[3 * i + 0] = v.X;
result[3 * i + 1] = v.Y;
result[3 * i + 2] = v.Z;
}
pinnedVirtexes = GCHandle.Alloc(result, GCHandleType.Pinned);
}
else
{
int count = primMesh.coords.Count;
result = new float[count * 3];
for (int i = 0; i < count; i++)
{
Coord c = primMesh.coords[i];
{
int resultIndex = 3 * i;
result[resultIndex] = c.X;
result[resultIndex + 1] = c.Y;
result[resultIndex + 2] = c.Z;
}
}
pinnedVirtexes = GCHandle.Alloc(result, GCHandleType.Pinned);
}
return result;
}
public int[] getIndexListAsInt()
{
int[] result;
if (primMesh == null)
{
result = new int[triangles.Count * 3];
for (int i = 0; i < triangles.Count; i++)
{
Triangle t = triangles[i];
result[3 * i + 0] = vertices.IndexOf(t.v1);
result[3 * i + 1] = vertices.IndexOf(t.v2);
result[3 * i + 2] = vertices.IndexOf(t.v3);
}
}
else
{
int numFaces = primMesh.faces.Count;
result = new int[numFaces * 3];
for (int i = 0; i < numFaces; i++)
{
Face f = primMesh.faces[i];
// Coord c1 = primMesh.coords[f.v1];
// Coord c2 = primMesh.coords[f.v2];
// Coord c3 = primMesh.coords[f.v3];
int resultIndex = i * 3;
result[resultIndex] = f.v1;
result[resultIndex + 1] = f.v2;
result[resultIndex + 2] = f.v3;
}
}
return result;
}
/// <summary>
/// creates a list of index values that defines triangle faces. THIS METHOD FREES ALL NON-PINNED MESH DATA
/// </summary>
/// <returns></returns>
public int[] getIndexListAsIntLocked()
{
int[] result = getIndexListAsInt();
pinnedIndex = GCHandle.Alloc(result, GCHandleType.Pinned);
return result;
}
public void releasePinned()
{
pinnedVirtexes.Free();
pinnedIndex.Free();
}
/// <summary>
/// frees up the source mesh data to minimize memory - call this method after calling get*Locked() functions
/// </summary>
public void releaseSourceMeshData()
{
triangles = null;
vertices = null;
primMesh = null;
}
public void Append(IMesh newMesh)
{
Mesh newMesh2;
if (newMesh is Mesh)
{
newMesh2 = (Mesh)newMesh;
}
else
{
return;
}
foreach (Vertex v in newMesh2.vertices)
vertices.Add(v);
foreach (Triangle t in newMesh2.triangles)
Add(t);
}
// Do a linear transformation of mesh.
public void TransformLinear(float[,] matrix, float[] offset)
{
foreach (Vertex v in vertices)
{
if (v == null)
continue;
float x, y, z;
x = v.X*matrix[0, 0] + v.Y*matrix[1, 0] + v.Z*matrix[2, 0];
y = v.X*matrix[0, 1] + v.Y*matrix[1, 1] + v.Z*matrix[2, 1];
z = v.X*matrix[0, 2] + v.Y*matrix[1, 2] + v.Z*matrix[2, 2];
v.X = x + offset[0];
v.Y = y + offset[1];
v.Z = z + offset[2];
}
}
public void DumpRaw(String path, String name, String title)
{
if (path == null)
return;
String fileName = name + "_" + title + ".raw";
String completePath = Path.Combine(path, fileName);
StreamWriter sw = new StreamWriter(completePath);
foreach (Triangle t in triangles)
{
String s = t.ToStringRaw();
sw.WriteLine(s);
}
sw.Close();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
namespace Erwine.Leonard.T.GDIPlus
{
/// <summary>
///
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct RgbColor32 : IEquatable<RgbColor32>, IEquatable<IRgbColorModel<float>>, IEquatable<IHsbColorModel<float>>, IRgbColorModel<byte>, IEquatable<int>, IConvertible
{
#region Fields
/// <summary>
///
/// </summary>
public static readonly Regex ParseRegex = new Regex(@"^((?<h>[a-f\d]{3}([a-f\d]([a-f\d]{2}|[a-f\d]{4})?)?)|rgba?\(\s*((?<v>(?<r>\d+)\s*,\s*(?<g>\d+)\s*,\s*(?<b>\d+))|(?<p>(?<h>\d+(\.\d+)?)\s*,\s*(?<s>\d+(\.\d+)?)%\s*,\s*(?<l>\d+(\.\d+)?)%))(\s*,\s*(?<a>\d+(\.\d+)?%?))?\s*\))$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
[FieldOffset(0)]
private readonly int _value;
[FieldOffset(0)]
private readonly byte _blue;
[FieldOffset(1)]
private readonly byte _green;
[FieldOffset(2)]
private readonly byte _red;
[FieldOffset(3)]
private readonly byte _alpha;
#endregion
#region Properties
/// <summary>
/// The opaqueness of the color.
/// </summary>
public byte Alpha { get { return _alpha; } }
/// <summary>
/// The intensity of the red layer.
/// </summary>
public byte Red { get { return _red; } }
/// <summary>
/// The intensity of the green layer.
/// </summary>
public byte Green { get { return _green; } }
/// <summary>
/// The intensity of the blue layer.
/// </summary>
public byte Blue { get { return _blue; } }
bool IColorModel.IsNormalized { get { return true; } }
ColorStringFormat IColorModel.DefaultStringFormat { get { return ColorStringFormat.RGBAHex; } }
#endregion
#region Constructors
/// <summary>
///
/// </summary>
/// <param name="red"></param>
/// <param name="green"></param>
/// <param name="blue"></param>
/// <param name="alpha"></param>
public RgbColor32(byte red, byte green, byte blue, byte alpha)
{
_value = 0;
_red = red;
_green = green;
_blue = blue;
_alpha = alpha;
}
/// <summary>
///
/// </summary>
/// <param name="red"></param>
/// <param name="green"></param>
/// <param name="blue"></param>
public RgbColor32(byte red, byte green, byte blue) : this(red, green, blue, 255) { }
/// <summary>
///
/// </summary>
/// <param name="value"></param>
public RgbColor32(RgbColorF value)
{
_value = 0;
_red = value.Red.FromPercentage();
_green = value.Green.FromPercentage();
_blue = value.Blue.FromPercentage();
_alpha = value.Alpha.FromPercentage();
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
public RgbColor32(IHsbColorModel<float> value)
{
_value = 0;
if (value == null)
throw new ArgumentNullException();
if (value.Alpha < 0f || value.Alpha > 1f)
throw new ArgumentOutOfRangeException("value", "Value for alpha is out of range");
try
{
ColorExtensions.HSBtoRGB(value.Hue, value.Saturation, value.Brightness, out float r, out float g, out float b);
_red = r.FromPercentage();
_green = g.FromPercentage();
_blue = b.FromPercentage();
}
catch (ArgumentOutOfRangeException exc) { throw new ArgumentOutOfRangeException("value", "Value for " + exc.ParamName + " is out of range"); }
_alpha = value.Alpha.FromPercentage();
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
public RgbColor32(IHsbColorModel<byte> value)
{
_value = 0;
if (value == null)
throw new ArgumentNullException();
ColorExtensions.HSBtoRGB(value.Hue.ToDegrees(), value.Saturation.ToPercentage(), value.Brightness.ToPercentage(), out float r, out float g, out float b);
_red = r.FromPercentage();
_green = g.FromPercentage();
_blue = b.FromPercentage();
_alpha = value.Alpha;
}
/// <summary>
///
/// </summary>
/// <param name="argb"></param>
public RgbColor32(int argb)
{
_red = _green = _blue = _alpha = 0;
_value = argb;
}
#endregion
#region As* Methods
/// <summary>
///
/// </summary>
/// <returns></returns>
public HsbColor32Normalized AsHsb32() { return new HsbColor32Normalized(this); }
IHsbColorModel<byte> IColorModel.AsHsb32() { return AsHsb32(); }
/// <summary>
///
/// </summary>
/// <returns></returns>
public HsbColorFNormalized AsHsbF() { return new HsbColorFNormalized(this); }
IHsbColorModel<float> IColorModel.AsHsbF() { return AsHsbF(); }
IRgbColorModel<byte> IColorModel.AsRgb32() { return this; }
/// <summary>
///
/// </summary>
/// <returns></returns>
public RgbColorF AsRgbF() { return new RgbColorF(this); }
IRgbColorModel<float> IColorModel.AsRgbF() { return AsRgbF(); }
IColorModel<byte> IColorModel<byte>.AsNormalized() { return this; }
IColorModel IColorModel.AsNormalized() { return this; }
#endregion
#region Equals Methods
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <param name="exact"></param>
/// <returns></returns>
public bool Equals(IHsbColorModel<byte> other, bool exact)
{
if (other == null || _alpha != other.Alpha)
return false;
float b;
if (exact)
{
ColorExtensions.RGBtoHSB(_red.ToPercentage(), _green.ToPercentage(), _blue.ToPercentage(), out float h, out float s, out b);
return other.Hue.ToDegrees() == h && other.Saturation.ToPercentage() == s && other.Brightness.ToPercentage() == b;
}
if (!other.IsNormalized)
other = other.AsNormalized();
ColorExtensions.HSBtoRGB(other.Hue, other.Saturation, other.Brightness, out float r, out float g, out b);
return _red == r.FromPercentage() && _green == g.FromPercentage() && _blue == b.FromPercentage();
}
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <param name="exact"></param>
/// <returns></returns>
public bool Equals(IHsbColorModel<float> other, bool exact)
{
if (other == null)
return false;
float b;
if (exact)
{
if (other.Alpha != _alpha.ToPercentage())
return false;
ColorExtensions.RGBtoHSB(_red.ToPercentage(), _green.ToPercentage(), _blue.ToPercentage(), out float h, out float s, out b);
return other.Hue == h && other.Saturation == s && other.Brightness == b;
}
if (other.Alpha.FromPercentage() != _alpha)
return false;
if (!other.IsNormalized)
other = other.AsNormalized();
ColorExtensions.HSBtoRGB(other.Hue, other.Saturation, other.Brightness, out float r, out float g, out b);
return _red == r.FromPercentage() && _green == g.FromPercentage() && _blue == b.FromPercentage();
}
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <param name="exact"></param>
/// <returns></returns>
public bool Equals(IRgbColorModel<float> other, bool exact)
{
if (other == null)
return false;
if (exact)
return _alpha.ToPercentage() == other.Alpha && _red.ToPercentage() == other.Red && _green.ToPercentage() == other.Green && _blue.ToPercentage() == other.Blue;
return _alpha == other.Alpha.FromPercentage() && _red == other.Red.FromPercentage() && _green == other.Green.FromPercentage() && _blue == other.Blue.FromPercentage();
}
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <param name="exact"></param>
/// <returns></returns>
public bool Equals(IColorModel other, bool exact)
{
if (other == null)
return false;
if (other is RgbColor32)
return Equals((RgbColor32)other);
if (other is IRgbColorModel<byte>)
return Equals((IRgbColorModel<byte>)other);
if (other is IRgbColorModel<float>)
return Equals((IRgbColorModel<float>)other, exact);
if (other is IHsbColorModel<byte>)
return Equals((IHsbColorModel<byte>)other, exact);
return other is IHsbColorModel<float> && Equals((IHsbColorModel<float>)other, exact);
}
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(RgbColor32 other) { return _value == other._value; }
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(IRgbColorModel<float> other) { return Equals(other, false); }
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(IHsbColorModel<float> other) { return Equals(other, false); }
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(IRgbColorModel<byte> other) { return other.Alpha == _alpha && other.Red == _red && other.Green == _green && other.Blue == _blue; }
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(IHsbColorModel<byte> other) { return Equals(other, false); }
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(IColorModel other) { return Equals(other, false); }
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(System.Drawing.Color other) { return other.A == _alpha && other.R == _red && other.G == _green && other.B == _blue; }
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(System.Windows.Media.Color other) { return other.A == _alpha && other.R == _red && other.G == _green && other.B == _blue; }
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(int other) { return _value == other; }
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
if (obj == null)
return false;
object value = (obj is PSObject) ? ((PSObject)obj).BaseObject : obj;
if (value is RgbColor32)
return Equals((RgbColor32)value);
if (value is IRgbColorModel<float>)
return Equals((IRgbColorModel<float>)value);
if (value is IRgbColorModel<byte>)
return Equals((IRgbColorModel<byte>)value);
if (value is IHsbColorModel<float>)
return Equals((IHsbColorModel<float>)value);
if (value is IHsbColorModel<float>)
return Equals((IHsbColorModel<float>)value, false);
if (value is int)
return Equals((int)value);
value = ColorExtensions.AsSimplestType(value);
if (value is string)
return (string)value == ToString();
if (value is int)
return ToARGB() == (int)value;
if (value is float)
return ToARGB() == (float)value;
if (obj is PSObject && ColorExtensions.TryGetColor((PSObject)obj, out IColorModel color))
return Equals(color.AsRgb32());
return false;
}
#endregion
/// <summary>
/// Returns the hash code for this value.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode() { return _value; }
#region MergeAverage Method
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public RgbColor32 MergeAverage(IEnumerable<IRgbColorModel<byte>> other)
{
if (other == null)
return this;
double r = _red.ToPercentage(), g = _green.ToPercentage(), b = _blue.ToPercentage(), a = _alpha.ToPercentage();
ColorExtensions.RGBtoHSB(_red.ToPercentage(), _green.ToPercentage(), _blue.ToPercentage(), out float h, out float s, out float bF);
double brightness = bF;
int count = 0;
foreach (IRgbColorModel<byte> item in other)
{
if (item != null)
{
count++;
r += (double)item.Red.ToPercentage();
g += (double)item.Green.ToPercentage();
b += (double)item.Blue.ToPercentage();
a += (double)item.Alpha.ToPercentage();
ColorExtensions.RGBtoHSB(item.Red.ToPercentage(), item.Green.ToPercentage(), item.Blue.ToPercentage(), out h, out s, out bF);
brightness += (double)bF;
}
}
if (count == 0)
return this;
ColorExtensions.RGBtoHSB((float)(r / (double)count), (float)(r / (double)count), (float)(r / (double)count), out h, out s, out bF);
ColorExtensions.HSBtoRGB(h, s, (float)(brightness / (double)count), out float red, out float green, out bF);
return new RgbColor32(red.FromPercentage(), green.FromPercentage(), bF.FromPercentage(), ((float)(a / (double)count)).FromPercentage());
}
IRgbColorModel<byte> IRgbColorModel<byte>.MergeAverage(IEnumerable<IRgbColorModel<byte>> other) { return MergeAverage(other); }
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public RgbColor32 MergeAverage(IEnumerable<IColorModel> other)
{
throw new NotImplementedException();
}
IColorModel IColorModel.MergeAverage(IEnumerable<IColorModel> other) { return MergeAverage(other); }
#endregion
#region ShiftHue Method
/// <summary>
/// Returns a <see cref="RgbColor32" /> value with the color hue adjusted.
/// </summary>
/// <param name="degrees">The number of degrees to shift the hue value, ranging from -360.0 to 360.0. A positive value shifts the hue in the red-to-cyan direction, and a negative value shifts the hue in the cyan-to-red direction.</param>
/// <returns>A <see cref="RgbColor32" /> value with the color hue adjusted.</returns>
/// <remarks>The values 0.0, -360.0 and 360.0 have no effect since they would result in no hue change.</remarks>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="degrees" /> is less than -360.0 or <paramref name="degrees" /> is greater than 360.0.</exception>
public RgbColor32 ShiftHue(float degrees)
{
if (degrees < -360f || degrees > 360f)
throw new ArgumentOutOfRangeException("degrees");
if (degrees == 0f || degrees == 360f || degrees == -360f)
return this;
ColorExtensions.RGBtoHSB(_red.ToPercentage(), _green.ToPercentage(), _blue.ToPercentage(), out float h, out float s, out float b);
h += degrees;
if (h < 0f)
h += 360f;
else if (h >= 360f)
h -= 360f;
ColorExtensions.HSBtoRGB(h, s, b, out float r, out float g, out b);
return new RgbColor32(r.FromPercentage(), g.FromPercentage(), b.FromPercentage(), _alpha);
}
IRgbColorModel<byte> IRgbColorModel<byte>.ShiftHue(float degrees) { return ShiftHue(degrees); }
IColorModel<byte> IColorModel<byte>.ShiftHue(float degrees) { return ShiftHue(degrees); }
IColorModel IColorModel.ShiftHue(float degrees) { return ShiftHue(degrees); }
#endregion
#region ShiftSaturation Method
/// <summary>
/// Returns a <see cref="RgbColor32" /> value with the color saturation adjusted.
/// </summary>
/// <param name="percentage">The percentage to saturate the color, ranging from -1.0 to 1.0. A positive value increases saturation, a negative value decreases saturation and a zero vale has no effect.</param>
/// <returns>A <see cref="RgbColor32" /> value with the color saturation adjusted.</returns>
/// <remarks>For positive values, the target saturation value is determined using the following formula: <c>saturation + (MAX_VALUE - saturation) * percentage</c>
/// <para>For negative values, the target saturation value is determined using the following formula: <c>saturation + saturation * percentage</c></para></remarks>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="percentage" /> is less than -1.0 or <paramref name="percentage" /> is greater than 1.0.</exception>
public RgbColor32 ShiftSaturation(float percentage)
{
if (percentage < -1f || percentage > 1f)
throw new ArgumentOutOfRangeException("percentage");
if (percentage == 0f)
return this;
ColorExtensions.RGBtoHSB(_red.ToPercentage(), _green.ToPercentage(), _blue.ToPercentage(), out float h, out float s, out float b);
if ((percentage == 1f) ? s == 1f : percentage == -1f && s == 0f)
return this;
ColorExtensions.HSBtoRGB(h, s + ((percentage > 0f) ? (1f - s) : s) * percentage, b, out float r, out float g, out b);
return new RgbColor32(r.FromPercentage(), g.FromPercentage(), b.FromPercentage(), _alpha);
}
IRgbColorModel<byte> IRgbColorModel<byte>.ShiftSaturation(float percentage) { return ShiftSaturation(percentage); }
IColorModel<byte> IColorModel<byte>.ShiftSaturation(float percentage) { return ShiftSaturation(percentage); }
IColorModel IColorModel.ShiftSaturation(float percentage) { return ShiftSaturation(percentage); }
#endregion
#region ShiftBrightness Method
/// <summary>
/// Returns a <see cref="RgbColor32" /> value with the color brightness adjusted.
/// </summary>
/// <param name="percentage">The percentage to saturate the color, ranging from -1.0 to 1.0. A positive value increases brightness, a negative value decreases brightness and a zero vale has no effect.</param>
/// <returns>A <see cref="RgbColor32" /> value with the color brightness adjusted.</returns>
/// <remarks>For positive values, the target brightness value is determined using the following formula: <c>brightness + (MAX_VALUE - brightness) * percentage</c>
/// <para>For negative values, the target brightness value is determined using the following formula: <c>brightness + brightness * percentage</c></para></remarks>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="percentage" /> is less than -1.0 or <paramref name="percentage" /> is greater than 1.0.</exception>
public RgbColor32 ShiftBrightness(float percentage)
{
if (percentage < -1f || percentage > 1f)
throw new ArgumentOutOfRangeException("percentage");
if (percentage == 0f)
return this;
ColorExtensions.RGBtoHSB(_red.ToPercentage(), _green.ToPercentage(), _blue.ToPercentage(), out float h, out float s, out float b);
if ((percentage == 1f) ? b == 1f : percentage == -1f && b == 0f)
return this;
ColorExtensions.HSBtoRGB(h, s, b + ((percentage > 0f) ? (1f - b) : b) * percentage, out float r, out float g, out b);
return new RgbColor32(r.FromPercentage(), g.FromPercentage(), b.FromPercentage(), _alpha);
}
IRgbColorModel<byte> IRgbColorModel<byte>.ShiftBrightness(float percentage) { return ShiftBrightness(percentage); }
IColorModel<byte> IColorModel<byte>.ShiftBrightness(float percentage) { return ShiftBrightness(percentage); }
IColorModel IColorModel.ShiftBrightness(float percentage) { return ShiftBrightness(percentage); }
#endregion
/// <summary>
/// Gets the ARGB integer value for the current <see cref="RgbColor32" /> value.
/// </summary>
/// <returns>The ARGB integer value for the current <see cref="RgbColor32" /> value.</returns>
public int ToARGB() { return _value; }
#region ToString Methods
/// <summary>
/// Gets formatted string representing the current color value.
/// </summary>
/// <param name="format">The color string format to use.</param>
/// <returns>The formatted string representing the current color value.</returns>
public string ToString(ColorStringFormat format)
{
float h, s, b;
switch (format)
{
case ColorStringFormat.HSLAHex:
ColorExtensions.RGBtoHSB(_red.ToPercentage(), _green.ToPercentage(), _blue.ToPercentage(), out h, out s, out b);
return HsbColor32.ToHexidecimalString(h.FromDegrees(), s.FromPercentage(), b.FromPercentage(), _alpha, false);
case ColorStringFormat.HSLAHexOpt:
ColorExtensions.RGBtoHSB(_red.ToPercentage(), _green.ToPercentage(), _blue.ToPercentage(), out h, out s, out b);
return HsbColor32.ToHexidecimalString(h.FromDegrees(), s.FromPercentage(), b.FromPercentage(), _alpha, true);
case ColorStringFormat.HSLAPercent:
ColorExtensions.RGBtoHSB(_red.ToPercentage(), _green.ToPercentage(), _blue.ToPercentage(), out h, out s, out b);
return HsbColorF.ToPercentParameterString(h, s, b, _alpha.ToPercentage());
case ColorStringFormat.HSLAValues:
ColorExtensions.RGBtoHSB(_red.ToPercentage(), _green.ToPercentage(), _blue.ToPercentage(), out h, out s, out b);
return HsbColor32.ToValueParameterString(h.FromDegrees(), s.FromPercentage(), b.FromPercentage(), _alpha);
case ColorStringFormat.HSLHex:
ColorExtensions.RGBtoHSB(_red.ToPercentage(), _green.ToPercentage(), _blue.ToPercentage(), out h, out s, out b);
return HsbColor32.ToHexidecimalString(h.FromDegrees(), s.FromPercentage(), b.FromPercentage(), false);
case ColorStringFormat.HSLHexOpt:
ColorExtensions.RGBtoHSB(_red.ToPercentage(), _green.ToPercentage(), _blue.ToPercentage(), out h, out s, out b);
return HsbColor32.ToHexidecimalString(h.FromDegrees(), s.FromPercentage(), b.FromPercentage(), true);
case ColorStringFormat.HSLPercent:
ColorExtensions.RGBtoHSB(_red.ToPercentage(), _green.ToPercentage(), _blue.ToPercentage(), out h, out s, out b);
return HsbColorF.ToPercentParameterString(h, s, b);
case ColorStringFormat.HSLValues:
ColorExtensions.RGBtoHSB(_red.ToPercentage(), _green.ToPercentage(), _blue.ToPercentage(), out h, out s, out b);
return HsbColor32.ToValueParameterString(h.FromDegrees(), s.FromPercentage(), b.FromPercentage());
case ColorStringFormat.RGBAHexOpt:
return ToHexidecimalString(_red, _green, _blue, _alpha, true);
case ColorStringFormat.RGBAPercent:
return RgbColorF.ToPercentParameterString(_red.ToPercentage(), _green.ToPercentage(), _blue.ToPercentage(), _alpha.ToPercentage());
case ColorStringFormat.RGBAValues:
return ToValueParameterString(_red, _green, _blue, _alpha);
case ColorStringFormat.RGBHex:
return ToHexidecimalString(_red, _green, _blue, false);
case ColorStringFormat.RGBHexOpt:
return ToHexidecimalString(_red, _green, _blue, true);
case ColorStringFormat.RGBPercent:
return RgbColorF.ToPercentParameterString(_red.ToPercentage(), _green.ToPercentage(), _blue.ToPercentage());
case ColorStringFormat.RGBValues:
return ToValueParameterString(_red, _green, _blue);
}
return _value.ToString("X8");
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString() { return _value.ToString("X8"); }
/// <summary>
///
/// </summary>
/// <param name="r"></param>
/// <param name="g"></param>
/// <param name="b"></param>
/// <param name="a"></param>
/// <param name="canShorten"></param>
/// <returns></returns>
public static string ToHexidecimalString(byte r, byte g, byte b, byte a, bool canShorten)
{
string result = r.ToString("X2") + g.ToString("X2") + b.ToString("X2") + a.ToString("X2");
if (canShorten && result[0] == result[1] && result[2] == result[3] && result[4] == result[5] && result[6] == result[7])
return new string(new char[] { result[0], result[2], result[4], result[6] });
return result;
}
/// <summary>
///
/// </summary>
/// <param name="r"></param>
/// <param name="g"></param>
/// <param name="b"></param>
/// <param name="a"></param>
/// <returns></returns>
public static string ToHexidecimalString(byte r, byte g, byte b, byte a) { return ToHexidecimalString(r, g, b, a, false); }
/// <summary>
///
/// </summary>
/// <param name="r"></param>
/// <param name="g"></param>
/// <param name="b"></param>
/// <param name="canShorten"></param>
/// <returns></returns>
public static string ToHexidecimalString(byte r, byte g, byte b, bool canShorten)
{
string result = r.ToString("X2") + g.ToString("X2") + b.ToString("X2");
if (canShorten && result[0] == result[1] && result[2] == result[3] && result[4] == result[5])
return new string(new char[] { result[0], result[2], result[4] });
return result;
}
/// <summary>
///
/// </summary>
/// <param name="r"></param>
/// <param name="g"></param>
/// <param name="b"></param>
/// <returns></returns>
public static string ToHexidecimalString(byte r, byte g, byte b) { return ToHexidecimalString(r, g, b, false); }
/// <summary>
///
/// </summary>
/// <param name="r"></param>
/// <param name="g"></param>
/// <param name="b"></param>
/// <param name="a"></param>
/// <returns></returns>
public static string ToValueParameterString(byte r, byte g, byte b, byte a)
{
return "rgba(" + r.ToString() + ", " + g.ToString() + ", " + b.ToString() + ", " + Math.Round(Convert.ToDouble(a) / 255.0, 2).ToString() + ")";
}
/// <summary>
///
/// </summary>
/// <param name="r"></param>
/// <param name="g"></param>
/// <param name="b"></param>
/// <returns></returns>
public static string ToValueParameterString(byte r, byte g, byte b)
{
return "rgb(" + r.ToString() + ", " + g.ToString() + ", " + b.ToString() + ")";
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="text"></param>
/// <param name="result"></param>
/// <returns></returns>
public static bool TryParse(string text, out RgbColor32 result) { return TryParse(text, false, out result); }
internal static bool TryParse(string text, bool strict, out RgbColor32 result)
{
if (text != null && (text = text.Trim()).Length > 0)
{
Match match = ParseRegex.Match(text);
if (match.Success)
{
try
{
if (match.Groups["h"].Success)
{
switch (text.Length)
{
case 3:
result = new RgbColor32(int.Parse(new string(new char[] { text[0], text[0], text[1], text[1], text[2], text[2]}), NumberStyles.HexNumber) << 8);
break;
case 4:
result = new RgbColor32(int.Parse(new string(new char[] { text[0], text[0], text[1], text[1], text[2], text[2]}), NumberStyles.HexNumber) << 8 | int.Parse(new string(new char[] { text[3], text[3] })));
break;
case 8:
result = new RgbColor32(int.Parse(text.Substring(0, 6), NumberStyles.HexNumber) << 8 | int.Parse(text.Substring(6), NumberStyles.HexNumber));
break;
default:
result = new RgbColor32(int.Parse(text, NumberStyles.HexNumber) << 8);
break;
}
return true;
}
float alpha = 100f;
if (!match.Groups["a"].Success || (((match.Groups["a"].Value.EndsWith("%")) ? (float.TryParse(match.Groups["a"].Value.Substring(0, match.Groups["a"].Length - 1), out alpha) && (alpha = alpha / 100f) <= 1f) : (float.TryParse(match.Groups["a"].Value, out alpha) && alpha <= 1f)) && alpha >= 0f))
{
if (match.Groups["v"].Success)
{
int r, g, b;
if (int.TryParse(match.Groups["r"].Value, out r) && r > -1 && r < 256 && int.TryParse(match.Groups["g"].Value, out g) && g > -1 && g < 256 &&
int.TryParse(match.Groups["b"].Value, out b) && b > -1 && b < 256)
{
result = new RgbColor32((byte)r, (byte)g, (byte)b, alpha.FromPercentage());
return true;
}
}
else if (float.TryParse(match.Groups["r"].Value, out float rF) && rF >= 0f && rF <= 100f &&
float.TryParse(match.Groups["g"].Value, out float gF) && gF >= 0f && gF <= 100f &&
float.TryParse(match.Groups["b"].Value, out float bF) && bF >= 0f && bF <= 100f)
{
result = new RgbColor32((rF / 100f).FromPercentage(), (gF / 100f).FromPercentage(), (bF / 100f).FromPercentage(), alpha.FromPercentage());
return true;
}
}
}
catch { }
}
else if (!strict && HsbColor32.TryParse(text, true, out HsbColor32 hsb))
{
result = hsb.AsRgb32();
return true;
}
}
result = default(RgbColor32);
return false;
}
#region IConvertible Members
TypeCode IConvertible.GetTypeCode() { return TypeCode.Int32; }
bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(_value, provider); }
char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(_value, provider); }
sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(_value, provider); }
byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(_value, provider); }
short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(_value, provider); }
ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(_value, provider); }
int IConvertible.ToInt32(IFormatProvider provider) { return _value; }
uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(_value, provider); }
long IConvertible.ToInt64(IFormatProvider provider) { return _value; }
ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(_value, provider); }
float IConvertible.ToSingle(IFormatProvider provider) { return _value; }
double IConvertible.ToDouble(IFormatProvider provider) { return _value; }
decimal IConvertible.ToDecimal(IFormatProvider provider) { return _value; }
DateTime IConvertible.ToDateTime(IFormatProvider provider) { return Convert.ToDateTime(_value, provider); }
string IConvertible.ToString(IFormatProvider provider) { return Convert.ToString(_value, provider); }
object IConvertible.ToType(Type conversionType, IFormatProvider provider) { return Convert.ChangeType(_value, conversionType, provider); }
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using CoreXml.Test.XLinq;
using Microsoft.Test.ModuleCore;
namespace XLinqTests
{
public class XAttributeEnumRemove : XLinqTestCase
{
#region Fields
private EventsHelper _eHelper;
private bool _runWithEvents;
#endregion
#region Public Methods and Operators
public override void AddChildren()
{
AddChild(new TestVariation(IdAttrsMultipleDocs) { Attribute = new VariationAttribute("attributes from multiple elements") { Priority = 1 } });
AddChild(new TestVariation(IdAttrs) { Attribute = new VariationAttribute("attributes from multiple documents") { Priority = 1 } });
AddChild(new TestVariation(OneElementNonNS) { Attribute = new VariationAttribute("All non-namespace attributes in one element") { Priority = 1 } });
AddChild(new TestVariation(OneElementNS) { Attribute = new VariationAttribute("All namespace attributes in one element") { Priority = 1 } });
AddChild(new TestVariation(OneElement) { Attribute = new VariationAttribute("All attributes in one element") { Priority = 0 } });
AddChild(new TestVariation(OneDocument) { Attribute = new VariationAttribute("All attributes in one document") { Priority = 1 } });
AddChild(new TestVariation(IdAttrsNulls) { Attribute = new VariationAttribute("All attributes in one document + nulls") { Priority = 1 } });
AddChild(new TestVariation(DuplicateAttributeInside) { Attribute = new VariationAttribute("Duplicate attribute in sequence") { Priority = 3 } });
AddChild(new TestVariation(EmptySequence) { Attribute = new VariationAttribute("Empty sequence") { Priority = 1 } });
}
// From the same element
// - all attributes
// - some attributes
// From different elements - the same document
// From different documents
// Enumerable + nulls
//[Variation(Priority = 1, Desc = "attributes from multiple elements")]
//[Variation(Priority = 3, Desc = "Duplicate attribute in sequence")]
public void DuplicateAttributeInside()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D id='x' datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Root.Attributes().Concat(doc.Root.Attributes());
try
{
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count();
}
allAttributes.Remove(); // should throw because of snapshot logic
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
TestLog.Compare(false, "exception expected here");
}
catch (InvalidOperationException)
{
}
}
//[Variation(Priority = 1, Desc = "Empty sequence")]
public void EmptySequence()
{
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D id='x' datrt='dat'/></A>");
IEnumerable<XAttribute> noAttributes = doc.Descendants().Where(x => !x.HasAttributes).Attributes();
TestLog.Compare(noAttributes.IsEmpty(), "should be empty sequence");
var ms1 = new MemoryStream();
doc.Save(new StreamWriter(ms1));
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
}
noAttributes.Remove();
if (_runWithEvents)
{
_eHelper.Verify(0);
}
var ms2 = new MemoryStream();
doc.Save(new StreamWriter(ms2));
TestLog.Compare(ms1.ToArray().SequenceEqual(ms2.ToArray()), "Documents different");
}
public void IdAttrs()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D id='x' datrt='dat'/></A>");
XElement e = XElement.Parse(@"<X id='z'><Z xmlns='a' id='z'/></X>");
IEnumerable<XAttribute> allAttributes = doc.Descendants().Attributes().Concat(e.Descendants().Attributes()).Where(a => a.Name == "id");
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = doc.Descendants().Attributes().Where(a => a.Name == "id").Count();
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
}
public void IdAttrsMultipleDocs()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D id='x' datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Descendants().Attributes().Where(a => a.Name == "id");
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count();
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
}
public void IdAttrsNulls()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D id='x' datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Descendants().Attributes().Where(a => a.Name == "id").InsertNulls(1);
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
// null attribute will not cause the remove event.
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count() / 2;
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
}
public void OneDocument()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Descendants().Attributes();
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count();
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
}
public void OneElement()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Root.Element("{nbs}B").Attributes();
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count();
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
}
public void OneElementNS()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Root.Element("{nbs}B").Attributes().Where(a => a.IsNamespaceDeclaration);
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count();
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
VerifyDeleteAttributes(allAttributes);
}
public void OneElementNonNS()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Root.Element("{nbs}B").Attributes().Where(a => !a.IsNamespaceDeclaration);
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count();
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
}
#endregion
#region Methods
private void VerifyDeleteAttributes(IEnumerable<XAttribute> allAttributes)
{
// specify enum + make copy of it
IEnumerable<XAttribute> copyAllAttributes = allAttributes.ToList();
// calculate parents + make copy
IEnumerable<XElement> parents = allAttributes.Select(a => a == null ? null : a.Parent).ToList();
// calculate the expected results for the parents of the processed elements
var expectedAttrsForParent = new Dictionary<XElement, List<ExpectedValue>>();
foreach (XElement p in parents)
{
if (p != null && !expectedAttrsForParent.ContainsKey(p))
{
expectedAttrsForParent.Add(p, p.Attributes().Except(copyAllAttributes.Where(x => x != null)).Select(a => new ExpectedValue(true, a)).ToList());
}
}
// enum.Remove ()
allAttributes.Remove();
// verify properties of the deleted attrs
TestLog.Compare(allAttributes.IsEmpty(), "There should be no attributes left");
IEnumerator<XAttribute> copyAttrib = copyAllAttributes.GetEnumerator();
IEnumerator<XElement> parentsEnum = parents.GetEnumerator();
// verify on parents: deleted elements should not be found
while (copyAttrib.MoveNext() && parentsEnum.MoveNext())
{
XAttribute a = copyAttrib.Current;
if (a != null)
{
XElement parent = parentsEnum.Current;
a.Verify();
parent.Verify();
TestLog.Compare(a.Parent, null, "Parent of deleted");
TestLog.Compare(a.NextAttribute, null, "NextAttribute of deleted");
TestLog.Compare(a.PreviousAttribute, null, "PreviousAttribute of deleted");
if (parent != null)
{
TestLog.Compare(parent.Attribute(a.Name), null, "Attribute lookup");
TestLog.Compare(parent.Attributes().Where(x => x.Name == a.Name).IsEmpty(), "Attributes node");
// Compare the rest of the elements
TestLog.Compare(expectedAttrsForParent[parent].EqualAllAttributes(parent.Attributes(), Helpers.MyAttributeComparer), "The rest of ther attributes");
}
}
}
}
#endregion
// Type is CoreXml.Test.XLinq.FunctionalTests+TreeManipulationTests+XAttributeEnumRemove
// Test Case
}
}
| |
using Antlr.Runtime;
using Antlr.Runtime.Tree;
using NUnit.Framework;
using SheepAspect.Saql.Ast;
using FluentAssertions;
using SheepAspect.Saql.Exceptions;
using SheepAspect.UnitTest.TestHelper;
namespace SheepAspect.UnitTest.SaqlTests
{
[TestFixture]
public class SaqlParsingTest
{
[Assert]
public void HenTest()
{
var str = string.Empty;
var lexer = new PointcutLexer(new ANTLRStringStream(str));
var parser = new PointcutParser(new CommonTokenStream(lexer));
var q = parser.pointcut();
new DumpAstVisitor().visit((ITree) q.Tree);
}
[Assert]
public void Empty()
{
Process("").Should().BeNull();
}
[Assert]
public void SimpleCriteria()
{
Process("Name: 'Sheep'")
.ShouldBeCriteria("Name")
.Value.ShouldBeLiteral("Sheep");
}
[Assert]
public void ArgumentlessCriteria()
{
Process("IsStatic")
.ShouldBeCriteria("IsStatic")
.Value.Should().BeNull();
}
[Assert]
public void SimpleLiteralValue()
{
Process("'void Hello()'")
.ShouldBeLiteral("void Hello()");
}
[Assert]
public void CriteriaWithinCriteria()
{
Process("WeavedType: (Name: 'Sheep')")
.ShouldBeCriteria("WeavedType")
.Value.ShouldBeCriteria("Name")
.Value.ShouldBeLiteral("Sheep");
}
[Assert]
public void NegationOnLiteral()
{
Process("Implements: !'String'").ShouldBeCriteria("Implements")
.Value.ShouldBeCriteria("Not")
.Value.ShouldBeLiteral("String");
}
[Assert]
public void NegationOnCriteria()
{
Process("!Implements: 'String'").ShouldBeCriteria("Not")
.Value.ShouldBeCriteria("Implements")
.Value.ShouldBeLiteral("String");
}
[Assert]
public void CriteriaAndCriteriaAndLiteral()
{
var and = Process("Name: 'Sheep' & WeavedType: 'Bull'").Should().CastTo<AndCompoundNode>();
and.Left.ShouldBeCriteria("Name")
.Value.ShouldBeLiteral("Sheep");
and.Right.ShouldBeCriteria("WeavedType")
.Value.ShouldBeLiteral("Bull");
}
[Assert]
public void ArgumentlessCriteriaAndArgumentlessCriteria()
{
var and = Process("Private & Public").Should().CastTo<AndCompoundNode>();
and.Left.ShouldBeCriteria("Private")
.Value.Should().BeNull();
and.Right.ShouldBeCriteria("Public")
.Value.Should().BeNull();
}
[Assert]
public void LiteralAndCriteriaWithinCriteria()
{
var and = Process("WeavedType: (Name: 'Sheep' & Assembly: 'Bull')")
.ShouldBeCriteria("WeavedType")
.Value.Should().CastTo<AndCompoundNode>();
and.Left.ShouldBeCriteria("Name")
.Value.ShouldBeLiteral("Sheep");
and.Right.ShouldBeCriteria("Assembly")
.Value.ShouldBeLiteral("Bull");
}
[Assert]
public void CriteriaOrCriteria()
{
var or = Process("Name: 'Sheep' | WeavedType: 'Bull'").Should().CastTo<OrCompoundNode>();
or.Left.ShouldBeCriteria("Name")
.Value.ShouldBeLiteral("Sheep");
or.Right.ShouldBeCriteria("WeavedType")
.Value.ShouldBeLiteral("Bull");
}
[Assert]
public void ComplexAndOr()
{
var andSix = Process("'One' & 'Two' & 'Three' | 'Four' | 'Five' & 'Six'").Should().CastTo<AndCompoundNode>();
andSix.Right.ShouldBeLiteral("Six");
var orFive = andSix.Left.Should().CastTo<OrCompoundNode>();
orFive.Right.ShouldBeLiteral("Five");
var orFour = orFive.Left.Should().CastTo<OrCompoundNode>();
orFour.Right.ShouldBeLiteral("Four");
var andThree = orFour.Left.Should().CastTo<AndCompoundNode>();
andThree.Right.ShouldBeLiteral("Three");
var andTwo = andThree.Left.Should().CastTo<AndCompoundNode>();
andTwo.Right.ShouldBeLiteral("Two");
andTwo.Left.ShouldBeLiteral("One");
}
[Assert]
public void SimpleArrayValue()
{
var values = Process("('Sheep', 'Bull')").Should().CastTo<ArrayValueNode>().Values;
values[0].ShouldBeLiteral("Sheep");
values[1].ShouldBeLiteral("Bull");
}
[Assert]
public void CriteriaWithArrayValue()
{
var values = Process("Args: ('Sheep', 'Bull')")
.ShouldBeCriteria("Args")
.Value.Should().CastTo<ArrayValueNode>().Values;
values[0].ShouldBeLiteral("Sheep");
values[1].ShouldBeLiteral("Bull");
}
[Assert]
public void CriteriaWithPointcutRef()
{
Process("WeavedType: @MyOtherPointcut")
.ShouldBeCriteria("WeavedType")
.Value.Should().CastTo<PointcutRefNode>()
.PointcutName.Should().Be("MyOtherPointcut");
}
[Assert]
public void CriteriaWithArrayOfPointcuts()
{
var values = Process("Args: (@Pointcut1, @Pointcut2)")
.ShouldBeCriteria("Args")
.Value.Should().CastTo<ArrayValueNode>().Values;
values[0].Should().CastTo<PointcutRefNode>()
.PointcutName.Should().Be("Pointcut1");
values[1].Should().CastTo<PointcutRefNode>()
.PointcutName.Should().Be("Pointcut2");
}
[Assert]
[ExpectedException(typeof(UnexpectedTokenSaqlException))]
public void InvalidSaql_ShouldThrowException()
{
Process("Name: 'Sheep"); //No closing quote
}
private static IPointcutValueNode Process(string text)
{
var lexer = new PointcutLexer(new ANTLRStringStream(text));
var parser = new PointcutParser(new CommonTokenStream(lexer));
//new DumpAstVisitor().visit((ITree)parser.pointcut().Tree);
var walker = new PointcutWalker(new CommonTreeNodeStream(parser.pointcut().Tree));
return walker.pointcut().value;
}
}
}
| |
using System;
using System.Threading;
using System.Xml.Serialization;
using NationalInstruments.DAQmx;
using DAQ.Environment;
using DAQ.FakeData;
using DAQ.HAL;
using Data;
using ScanMaster.Acquire.Plugin;
namespace ScanMaster.Acquire.Plugins
{
/// <summary>
/// A plugin to capture time-resolved data by buffered event counting.
/// - Each element of the buffer will contain the number of edges present at the source pin of the counter
/// in the time interval between two successive edges at the gate pin of the same counter. The counts are
/// gated into the buffer by a sample clock. The number of samples collected is set by the gateLength setting.
/// - The sample clock is also set up in this class. The sample clock will appear on the out pin of a
/// second counter. This clock signal should be routed to the gate pin of the first counter. The frequency
/// of this sample clock is determined by the sampleRate setting.
/// - This plugin can be used either in triggered or un-triggered mode. In untriggered mode, the
/// data collection is not synchronized to anything. In triggered mode, data collection is synchronized
/// to a trigger which should appear on the gate pin of the sample clock.
/// - The count data is converted to a frequency (kHz).
///
/// Signal Connections
/// -----------------
/// Route the signal to be counted to the source pin of a counter (I'll call it counter A)
/// Route the output of the second counter (counter B, the sample clock) to the gate pin of counter A
/// To trigger the data acquisition, route a trigger signal to the analog input standard trigger (PFI0 - for compatibility with analog shot gathering)
/// To take modulated (on/off) data, you should have two separate triggers from the PG - one for the off shots and the other for the
/// on shots. Route the second trigger to PFI1.
/// Beware of cross-talk between the source and gate pins - this will upset everything!
/// </summary>
[Serializable]
public class BufferedEventCountingShotGathererPlugin : ShotGathererPlugin
{
[NonSerialized]
private Task countingTask;
[NonSerialized]
private Task freqOutTask1;
[NonSerialized]
private Task freqOutTask2;
[NonSerialized]
private CounterReader countReader;
[NonSerialized]
private double[] latestData;
protected override void InitialiseSettings()
{
settings["triggerActive"] = true;
}
public override void AcquisitionStarting()
{
//set up an edge-counting task
countingTask = new Task("buffered edge counter gatherer " + (string)settings["channel"]);
//count upwards on rising edges starting from zero
countingTask.CIChannels.CreateCountEdgesChannel(
((CounterChannel)Environs.Hardware.CounterChannels[(string)settings["channel"]]).PhysicalChannel,
"edge counter",
CICountEdgesActiveEdge.Rising,
0,
CICountEdgesCountDirection.Up);
//The counting buffer is triggered by a sample clock, which will be routed to the gate pin of ctr0 (PFI9)
//The number of samples to collect is determined by the "gateLength" setting. We add 1 to this,
// since the first count is not synchronized to anything and will be discarded
countingTask.Timing.ConfigureSampleClock(
(string)Environs.Hardware.Boards["daq"] + "/PFI9",
(int)settings["sampleRate"],
SampleClockActiveEdge.Rising,
SampleQuantityMode.FiniteSamples,
(int)settings["gateLength"] + 1);
countingTask.Control(TaskAction.Verify);
// set up two taska to generate the sample clock on the second counter
freqOutTask1 = new Task("buffered event counter clock generation 1");
freqOutTask2 = new Task("buffered event counter clock generation 2");
//the frequency of the clock is set by the "sampleRate" setting and the duty cycle is set to 0.5
//the two output tasks have the same settings
freqOutTask1.COChannels.CreatePulseChannelFrequency(
((CounterChannel)Environs.Hardware.CounterChannels["sample clock"]).PhysicalChannel,
"photon counter clocking signal",
COPulseFrequencyUnits.Hertz,
COPulseIdleState.Low,
0,
(int)settings["sampleRate"],
0.5);
freqOutTask1.Timing.ConfigureImplicit(SampleQuantityMode.ContinuousSamples, 1000);
freqOutTask2.COChannels.CreatePulseChannelFrequency(
((CounterChannel)Environs.Hardware.CounterChannels["sample clock"]).PhysicalChannel,
"photon counter clocking signal",
COPulseFrequencyUnits.Hertz,
COPulseIdleState.Low,
0,
(int)settings["sampleRate"],
0.5);
freqOutTask2.Timing.ConfigureImplicit(SampleQuantityMode.ContinuousSamples, 1000);
// if we're using a hardware trigger to synchronize data acquisition, we need to set up the
// trigger parameters on the sample clock.
// The first output task is triggered on PFI0 and the second is triggered on PFI1
if((bool)settings["triggerActive"])
{
freqOutTask1.Triggers.StartTrigger.Type = StartTriggerType.DigitalEdge;
freqOutTask1.Triggers.StartTrigger.DigitalEdge.Edge = DigitalEdgeStartTriggerEdge.Rising;
freqOutTask2.Triggers.StartTrigger.Type = StartTriggerType.DigitalEdge;
freqOutTask2.Triggers.StartTrigger.DigitalEdge.Edge = DigitalEdgeStartTriggerEdge.Rising;
// the trigger is expected to appear on PFI0
freqOutTask1.Triggers.StartTrigger.DigitalEdge.Source = (string)Environs.Hardware.Boards["daq"] + "/PFI0";
// the trigger is expected to appear on PFI1
freqOutTask2.Triggers.StartTrigger.DigitalEdge.Source = (string)Environs.Hardware.Boards["daq"] + "/PFI1";
}
// set up a reader for the edge counter
countReader = new CounterReader(countingTask.Stream);
}
public override void ScanStarting()
{
}
public override void ScanFinished()
{
}
public override void AcquisitionFinished()
{
countingTask.Dispose();
if (config.switchPlugin.State)
{
freqOutTask1.Stop();
}
else
{
freqOutTask2.Stop();
}
freqOutTask1.Dispose();
freqOutTask2.Dispose();
}
public override void ArmAndWait()
{
lock(this)
{
//Get the counter ready. Nothing will happen until there is output on the sample clock
countingTask.Start();
// Get the sample clock ready. If the trigger is inactive, the clock will start its output immediately.
// If the trigger is active, there is no output until the counter is triggered
// Which output task runs depends on the switch-state.
if (config.switchPlugin.State)
{
freqOutTask1.Start();
}
else
{
freqOutTask2.Start();
}
// read the data into a temporary array once all the samples have been acquired
double[] tempdata = countReader.ReadMultiSampleDouble(-1);
// stop the counter; the job's done
countingTask.Stop();
// stop the sample clock
if (config.switchPlugin.State)
{
freqOutTask1.Stop();
}
else
{
freqOutTask2.Stop();
}
// Each element of the buffer holds the incremental count. Discard the first value and calculate
// the counts per bin by subtracting the count in each bin by the count in the previous bin.
// Calculate the rate in kHz.
latestData = new double[tempdata.Length - 1];
for (int k = 0; k < latestData.Length; k++)
latestData[k] = (tempdata[k + 1] - tempdata[k])*(int)settings["sampleRate"]/1000;
}
}
public override Shot Shot
{
get
{
lock(this)
{
Shot s = new Shot();
TOF t = new TOF();
t.ClockPeriod = (int)settings["clockPeriod"];
t.GateStartTime = (int)settings["gateStartTime"];
if (!Environs.Debug)
{
t.Data = latestData;
s.TOFs.Add(t);
return s;
}
else
{
Thread.Sleep(50);
return DataFaker.GetFakeShot((int)settings["gateStartTime"], (int)settings["gateLength"],
(int)settings["clockPeriod"], 1, 1);
}
}
}
}
}
}
| |
// 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 BlendVariableUInt64()
{
var test = new SimpleTernaryOpTest__BlendVariableUInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.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 (Sse2.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();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.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 class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__BlendVariableUInt64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt64[] inArray1, UInt64[] inArray2, UInt64[] inArray3, UInt64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt64, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<UInt64> _fld1;
public Vector128<UInt64> _fld2;
public Vector128<UInt64> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToUInt64("0xFFFFFFFFFFFFFFFF", 16): (ulong)0); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__BlendVariableUInt64 testClass)
{
var result = Sse41.BlendVariable(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__BlendVariableUInt64 testClass)
{
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
fixed (Vector128<UInt64>* pFld3 = &_fld3)
{
var result = Sse41.BlendVariable(
Sse2.LoadVector128((UInt64*)(pFld1)),
Sse2.LoadVector128((UInt64*)(pFld2)),
Sse2.LoadVector128((UInt64*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static UInt64[] _data3 = new UInt64[Op3ElementCount];
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private static Vector128<UInt64> _clsVar3;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private Vector128<UInt64> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__BlendVariableUInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToUInt64("0xFFFFFFFFFFFFFFFF", 16): (ulong)0); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar3), ref Unsafe.As<UInt64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
}
public SimpleTernaryOpTest__BlendVariableUInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToUInt64("0xFFFFFFFFFFFFFFFF", 16): (ulong)0); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld3), ref Unsafe.As<UInt64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToUInt64("0xFFFFFFFFFFFFFFFF", 16): (ulong)0); }
_dataTable = new DataTable(_data1, _data2, _data3, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.BlendVariable(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.BlendVariable(
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.BlendVariable(
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.BlendVariable(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt64>* pClsVar2 = &_clsVar2)
fixed (Vector128<UInt64>* pClsVar3 = &_clsVar3)
{
var result = Sse41.BlendVariable(
Sse2.LoadVector128((UInt64*)(pClsVar1)),
Sse2.LoadVector128((UInt64*)(pClsVar2)),
Sse2.LoadVector128((UInt64*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray3Ptr);
var result = Sse41.BlendVariable(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var op3 = Sse2.LoadVector128((UInt64*)(_dataTable.inArray3Ptr));
var result = Sse41.BlendVariable(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr));
var op3 = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray3Ptr));
var result = Sse41.BlendVariable(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__BlendVariableUInt64();
var result = Sse41.BlendVariable(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__BlendVariableUInt64();
fixed (Vector128<UInt64>* pFld1 = &test._fld1)
fixed (Vector128<UInt64>* pFld2 = &test._fld2)
fixed (Vector128<UInt64>* pFld3 = &test._fld3)
{
var result = Sse41.BlendVariable(
Sse2.LoadVector128((UInt64*)(pFld1)),
Sse2.LoadVector128((UInt64*)(pFld2)),
Sse2.LoadVector128((UInt64*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.BlendVariable(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
fixed (Vector128<UInt64>* pFld3 = &_fld3)
{
var result = Sse41.BlendVariable(
Sse2.LoadVector128((UInt64*)(pFld1)),
Sse2.LoadVector128((UInt64*)(pFld2)),
Sse2.LoadVector128((UInt64*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.BlendVariable(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse41.BlendVariable(
Sse2.LoadVector128((UInt64*)(&test._fld1)),
Sse2.LoadVector128((UInt64*)(&test._fld2)),
Sse2.LoadVector128((UInt64*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<UInt64> op1, Vector128<UInt64> op2, Vector128<UInt64> op3, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] inArray3 = new UInt64[Op3ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] inArray3 = new UInt64[Op3ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(UInt64[] firstOp, UInt64[] secondOp, UInt64[] thirdOp, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((thirdOp[0] != 0) ? secondOp[0] != result[0] : firstOp[0] != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((thirdOp[i] != 0) ? secondOp[i] != result[i] : firstOp[i] != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.BlendVariable)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>, Vector128<UInt64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Reflection
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
using System.Threading;
//
// Invocation cached flags. Those are used in unmanaged code as well
// so be careful if you change them
//
[Flags]
internal enum INVOCATION_FLAGS : uint
{
INVOCATION_FLAGS_UNKNOWN = 0x00000000,
INVOCATION_FLAGS_INITIALIZED = 0x00000001,
// it's used for both method and field to signify that no access is allowed
INVOCATION_FLAGS_NO_INVOKE = 0x00000002,
INVOCATION_FLAGS_NEED_SECURITY = 0x00000004,
// Set for static ctors and ctors on abstract types, which
// can be invoked only if the "this" object is provided (even if it's null).
INVOCATION_FLAGS_NO_CTOR_INVOKE = 0x00000008,
// because field and method are different we can reuse the same bits
// method
INVOCATION_FLAGS_IS_CTOR = 0x00000010,
INVOCATION_FLAGS_RISKY_METHOD = 0x00000020,
INVOCATION_FLAGS_NON_W8P_FX_API = 0x00000040,
INVOCATION_FLAGS_IS_DELEGATE_CTOR = 0x00000080,
INVOCATION_FLAGS_CONTAINS_STACK_POINTERS = 0x00000100,
// field
INVOCATION_FLAGS_SPECIAL_FIELD = 0x00000010,
INVOCATION_FLAGS_FIELD_SPECIAL_CAST = 0x00000020,
// temporary flag used for flagging invocation of method vs ctor
// this flag never appears on the instance m_invocationFlag and is simply
// passed down from within ConstructorInfo.Invoke()
INVOCATION_FLAGS_CONSTRUCTOR_INVOKE = 0x10000000,
}
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_MethodBase))]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
#pragma warning restore 618
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class MethodBase : MemberInfo, _MethodBase
{
#region Static Members
public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle)
{
if (handle.IsNullHandle())
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"));
MethodBase m = RuntimeType.GetMethodBase(handle.GetMethodInfo());
Type declaringType = m.DeclaringType;
if (declaringType != null && declaringType.IsGenericType)
throw new ArgumentException(String.Format(
CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_MethodDeclaringTypeGeneric"),
m, declaringType.GetGenericTypeDefinition()));
return m;
}
[System.Runtime.InteropServices.ComVisible(false)]
public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle, RuntimeTypeHandle declaringType)
{
if (handle.IsNullHandle())
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"));
return RuntimeType.GetMethodBase(declaringType.GetRuntimeType(), handle.GetMethodInfo());
}
[System.Security.DynamicSecurityMethod] // Specify DynamicSecurityMethod attribute to prevent inlining of the caller.
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static MethodBase GetCurrentMethod()
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return RuntimeMethodInfo.InternalGetCurrentMethod(ref stackMark);
}
#endregion
#region Constructor
protected MethodBase() { }
#endregion
#if !FEATURE_CORECLR
public static bool operator ==(MethodBase left, MethodBase right)
{
if (ReferenceEquals(left, right))
return true;
if ((object)left == null || (object)right == null)
return false;
MethodInfo method1, method2;
ConstructorInfo constructor1, constructor2;
if ((method1 = left as MethodInfo) != null && (method2 = right as MethodInfo) != null)
return method1 == method2;
else if ((constructor1 = left as ConstructorInfo) != null && (constructor2 = right as ConstructorInfo) != null)
return constructor1 == constructor2;
return false;
}
public static bool operator !=(MethodBase left, MethodBase right)
{
return !(left == right);
}
#endif // !FEATURE_CORECLR
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region Internal Members
// used by EE
[System.Security.SecurityCritical]
private IntPtr GetMethodDesc() { return MethodHandle.Value; }
#if FEATURE_APPX
// The C# dynamic and VB late bound binders need to call this API. Since we don't have time to make this
// public in Dev11, the C# and VB binders currently call this through a delegate.
// When we make this API public (hopefully) in Dev12 we need to change the C# and VB binders to call this
// probably statically. The code is located in:
// C#: ndp\fx\src\CSharp\Microsoft\CSharp\SymbolTable.cs - Microsoft.CSharp.RuntimeBinder.SymbolTable..cctor
// VB: vb\runtime\msvbalib\helpers\Symbols.vb - Microsoft.VisualBasic.CompilerServices.Symbols..cctor
internal virtual bool IsDynamicallyInvokable
{
get
{
return true;
}
}
#endif
#endregion
#region Public Abstract\Virtual Members
internal virtual ParameterInfo[] GetParametersNoCopy() { return GetParameters (); }
[System.Diagnostics.Contracts.Pure]
public abstract ParameterInfo[] GetParameters();
public virtual MethodImplAttributes MethodImplementationFlags
{
get
{
return GetMethodImplementationFlags();
}
}
public abstract MethodImplAttributes GetMethodImplementationFlags();
public abstract RuntimeMethodHandle MethodHandle { get; }
public abstract MethodAttributes Attributes { get; }
public abstract Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);
public virtual CallingConventions CallingConvention { get { return CallingConventions.Standard; } }
[System.Runtime.InteropServices.ComVisible(true)]
public virtual Type[] GetGenericArguments() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
public virtual bool IsGenericMethodDefinition { get { return false; } }
public virtual bool ContainsGenericParameters { get { return false; } }
public virtual bool IsGenericMethod { get { return false; } }
public virtual bool IsSecurityCritical { get { throw new NotImplementedException(); } }
public virtual bool IsSecuritySafeCritical { get { throw new NotImplementedException(); } }
public virtual bool IsSecurityTransparent { get { throw new NotImplementedException(); } }
#endregion
#region Public Members
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public Object Invoke(Object obj, Object[] parameters)
{
// Theoretically we should set up a LookForMyCaller stack mark here and pass that along.
// But to maintain backward compatibility we can't switch to calling an
// internal overload that takes a stack mark.
// Fortunately the stack walker skips all the reflection invocation frames including this one.
// So this method will never be returned by the stack walker as the caller.
// See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp.
return Invoke(obj, BindingFlags.Default, null, parameters, null);
}
public bool IsPublic { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public; } }
public bool IsPrivate { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private; } }
public bool IsFamily { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Family; } }
public bool IsAssembly { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Assembly; } }
public bool IsFamilyAndAssembly { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamANDAssem; } }
public bool IsFamilyOrAssembly { get {return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamORAssem; } }
public bool IsStatic { get { return(Attributes & MethodAttributes.Static) != 0; } }
public bool IsFinal { get { return(Attributes & MethodAttributes.Final) != 0; }
}
public bool IsVirtual { get { return(Attributes & MethodAttributes.Virtual) != 0; }
}
public bool IsHideBySig { get { return(Attributes & MethodAttributes.HideBySig) != 0; } }
public bool IsAbstract { get { return(Attributes & MethodAttributes.Abstract) != 0; } }
public bool IsSpecialName { get { return(Attributes & MethodAttributes.SpecialName) != 0; } }
[System.Runtime.InteropServices.ComVisible(true)]
public bool IsConstructor
{
get
{
// To be backward compatible we only return true for instance RTSpecialName ctors.
return (this is ConstructorInfo &&
!IsStatic &&
((Attributes & MethodAttributes.RTSpecialName) == MethodAttributes.RTSpecialName));
}
}
[System.Security.SecuritySafeCritical]
#pragma warning disable 618
[ReflectionPermissionAttribute(SecurityAction.Demand, Flags=ReflectionPermissionFlag.MemberAccess)]
#pragma warning restore 618
public virtual MethodBody GetMethodBody()
{
throw new InvalidOperationException();
}
#endregion
#region Internal Methods
// helper method to construct the string representation of the parameter list
internal static string ConstructParameters(Type[] parameterTypes, CallingConventions callingConvention, bool serialization)
{
StringBuilder sbParamList = new StringBuilder();
string comma = "";
for (int i = 0; i < parameterTypes.Length; i++)
{
Type t = parameterTypes[i];
sbParamList.Append(comma);
string typeName = t.FormatTypeName(serialization);
// Legacy: Why use "ByRef" for by ref parameters? What language is this?
// VB uses "ByRef" but it should precede (not follow) the parameter name.
// Why don't we just use "&"?
if (t.IsByRef && !serialization)
{
sbParamList.Append(typeName.TrimEnd(new char[] { '&' }));
sbParamList.Append(" ByRef");
}
else
{
sbParamList.Append(typeName);
}
comma = ", ";
}
if ((callingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
{
sbParamList.Append(comma);
sbParamList.Append("...");
}
return sbParamList.ToString();
}
internal string FullName
{
get
{
return String.Format("{0}.{1}", DeclaringType.FullName, FormatNameAndSig());
}
}
internal string FormatNameAndSig()
{
return FormatNameAndSig(false);
}
internal virtual string FormatNameAndSig(bool serialization)
{
// Serialization uses ToString to resolve MethodInfo overloads.
StringBuilder sbName = new StringBuilder(Name);
sbName.Append("(");
sbName.Append(ConstructParameters(GetParameterTypes(), CallingConvention, serialization));
sbName.Append(")");
return sbName.ToString();
}
internal virtual Type[] GetParameterTypes()
{
ParameterInfo[] paramInfo = GetParametersNoCopy();
Type[] parameterTypes = new Type[paramInfo.Length];
for (int i = 0; i < paramInfo.Length; i++)
parameterTypes[i] = paramInfo[i].ParameterType;
return parameterTypes;
}
[System.Security.SecuritySafeCritical]
internal Object[] CheckArguments(Object[] parameters, Binder binder,
BindingFlags invokeAttr, CultureInfo culture, Signature sig)
{
// copy the arguments in a different array so we detach from any user changes
Object[] copyOfParameters = new Object[parameters.Length];
ParameterInfo[] p = null;
for (int i = 0; i < parameters.Length; i++)
{
Object arg = parameters[i];
RuntimeType argRT = sig.Arguments[i];
if (arg == Type.Missing)
{
if (p == null)
p = GetParametersNoCopy();
if (p[i].DefaultValue == System.DBNull.Value)
throw new ArgumentException(Environment.GetResourceString("Arg_VarMissNull"),"parameters");
arg = p[i].DefaultValue;
}
copyOfParameters[i] = argRT.CheckValue(arg, binder, culture, invokeAttr);
}
return copyOfParameters;
}
#endregion
#region _MethodBase Implementation
#if !FEATURE_CORECLR
Type _MethodBase.GetType() { return base.GetType(); }
bool _MethodBase.IsPublic { get { return IsPublic; } }
bool _MethodBase.IsPrivate { get { return IsPrivate; } }
bool _MethodBase.IsFamily { get { return IsFamily; } }
bool _MethodBase.IsAssembly { get { return IsAssembly; } }
bool _MethodBase.IsFamilyAndAssembly { get { return IsFamilyAndAssembly; } }
bool _MethodBase.IsFamilyOrAssembly { get { return IsFamilyOrAssembly; } }
bool _MethodBase.IsStatic { get { return IsStatic; } }
bool _MethodBase.IsFinal { get { return IsFinal; } }
bool _MethodBase.IsVirtual { get { return IsVirtual; } }
bool _MethodBase.IsHideBySig { get { return IsHideBySig; } }
bool _MethodBase.IsAbstract { get { return IsAbstract; } }
bool _MethodBase.IsSpecialName { get { return IsSpecialName; } }
bool _MethodBase.IsConstructor { get { return IsConstructor; } }
void _MethodBase.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _MethodBase.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _MethodBase.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
// If you implement this method, make sure to include _MethodBase.Invoke in VM\DangerousAPIs.h and
// include _MethodBase in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
void _MethodBase.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests
{
public class ThenByTests : EnumerableTests
{
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q = from x1 in new int[] { 1, 6, 0, -1, 3 }
from x2 in new int[] { 55, 49, 9, -100, 24, 25 }
select new { a1 = x1, a2 = x2 };
Assert.Equal(
q.OrderByDescending(e => e.a1).ThenBy(f => f.a2),
q.OrderByDescending(e => e.a1).ThenBy(f => f.a2)
);
}
[Fact]
public void SameResultsRepeatCallsStringQuery()
{
var q = from x1 in new[] { 55, 49, 9, -100, 24, 25, -1, 0 }
from x2 in new[] { "!@#$%^", "C", "AAA", "", null, "Calling Twice", "SoS", string.Empty }
where !string.IsNullOrEmpty(x2)
select new { a1 = x1, a2 = x2 };
Assert.Equal(
q.OrderBy(e => e.a2).ThenBy(f => f.a1),
q.OrderBy(e => e.a2).ThenBy(f => f.a1)
);
}
[Fact]
public void SourceEmpty()
{
int[] source = { };
Assert.Empty(source.OrderBy(e => e).ThenBy(e => e));
}
[Fact]
public void SecondaryKeysAreUnique()
{
var source = new[]
{
new { Name = "Jim", City = "Minneapolis", Country = "USA" },
new { Name = "Tim", City = "Seattle", Country = "USA" },
new { Name = "Philip", City = "Orlando", Country = "USA" },
new { Name = "Chris", City = "London", Country = "UK" },
new { Name = "Rob", City = "Kent", Country = "UK" }
};
var expected = new[]
{
new { Name = "Rob", City = "Kent", Country = "UK" },
new { Name = "Chris", City = "London", Country = "UK" },
new { Name = "Jim", City = "Minneapolis", Country = "USA" },
new { Name = "Philip", City = "Orlando", Country = "USA" },
new { Name = "Tim", City = "Seattle", Country = "USA" }
};
Assert.Equal(expected, source.OrderBy(e => e.Country).ThenBy(e => e.City));
}
[Fact]
public void OrderByAndThenByOnSameField()
{
var source = new[]
{
new { Name = "Jim", City = "Minneapolis", Country = "USA" },
new { Name = "Prakash", City = "Chennai", Country = "India" },
new { Name = "Rob", City = "Kent", Country = "UK" }
};
var expected = new[]
{
new { Name = "Prakash", City = "Chennai", Country = "India" },
new { Name = "Rob", City = "Kent", Country = "UK" },
new { Name = "Jim", City = "Minneapolis", Country = "USA" }
};
Assert.Equal(expected, source.OrderBy(e => e.Country).ThenBy(e => e.Country, null));
}
[Fact]
public void SecondKeyRepeatAcrossDifferentPrimary()
{
var source = new []
{
new { Name = "Jim", City = "Minneapolis", Country = "USA" },
new { Name = "Tim", City = "Seattle", Country = "USA" },
new { Name = "Philip", City = "Orlando", Country = "USA" },
new { Name = "Chris", City = "Minneapolis", Country = "USA" },
new { Name = "Rob", City = "Seattle", Country = "USA" }
};
var expected = new []
{
new { Name = "Chris", City = "Minneapolis", Country = "USA" },
new { Name = "Jim", City = "Minneapolis", Country = "USA" },
new { Name = "Philip", City = "Orlando", Country = "USA" },
new { Name = "Rob", City = "Seattle", Country = "USA" },
new { Name = "Tim", City = "Seattle", Country = "USA" }
};
Assert.Equal(expected, source.OrderBy(e => e.Name).ThenBy(e => e.City, null));
}
[Fact]
public void OrderIsStable()
{
var source = @"Because I could not stop for Death -
He kindly stopped for me -
The Carriage held but just Ourselves -
And Immortality.".Split(new[] { ' ', '\n', '\r', '-' }, StringSplitOptions.RemoveEmptyEntries);
var expected = new[]
{
"me", "not", "for", "for", "but", "stop", "held", "just", "could", "kindly", "stopped",
"I", "He", "The", "And", "Death", "Because", "Carriage", "Ourselves", "Immortality."
};
Assert.Equal(expected, source.OrderBy(word => char.IsUpper(word[0])).ThenBy(word => word.Length));
}
[Fact]
public void RunOnce()
{
var source = @"Because I could not stop for Death -
He kindly stopped for me -
The Carriage held but just Ourselves -
And Immortality.".Split(new[] { ' ', '\n', '\r', '-' }, StringSplitOptions.RemoveEmptyEntries);
var expected = new[]
{
"me", "not", "for", "for", "but", "stop", "held", "just", "could", "kindly", "stopped",
"I", "He", "The", "And", "Death", "Because", "Carriage", "Ourselves", "Immortality."
};
Assert.Equal(expected, source.RunOnce().OrderBy(word => char.IsUpper(word[0])).ThenBy(word => word.Length));
}
[Fact]
public void NullSource()
{
IOrderedEnumerable<int> source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.ThenBy(i => i));
}
[Fact]
public void NullKeySelector()
{
Func<DateTime, int> keySelector = null;
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => Enumerable.Empty<DateTime>().OrderBy(e => e).ThenBy(keySelector));
}
[Fact]
public void NullSourceComparer()
{
IOrderedEnumerable<int> source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.ThenBy(i => i, null));
}
[Fact]
public void NullKeySelectorComparer()
{
Func<DateTime, int> keySelector = null;
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => Enumerable.Empty<DateTime>().OrderBy(e => e).ThenBy(keySelector, null));
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public void SortsLargeAscendingEnumerableCorrectly(int thenBys)
{
const int Items = 100_000;
IEnumerable<int> expected = NumberRangeGuaranteedNotCollectionType(0, Items);
IEnumerable<int> unordered = expected.Select(i => i);
IOrderedEnumerable<int> ordered = unordered.OrderBy(_ => 0);
switch (thenBys)
{
case 1: ordered = ordered.ThenBy(i => i); break;
case 2: ordered = ordered.ThenBy(i => 0).ThenBy(i => i); break;
case 3: ordered = ordered.ThenBy(i => 0).ThenBy(i => 0).ThenBy(i => i); break;
}
Assert.Equal(expected, ordered);
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public void SortsLargeDescendingEnumerableCorrectly(int thenBys)
{
const int Items = 100_000;
IEnumerable<int> expected = NumberRangeGuaranteedNotCollectionType(0, Items);
IEnumerable<int> unordered = expected.Select(i => Items - i - 1);
IOrderedEnumerable<int> ordered = unordered.OrderBy(_ => 0);
switch (thenBys)
{
case 1: ordered = ordered.ThenBy(i => i); break;
case 2: ordered = ordered.ThenBy(i => 0).ThenBy(i => i); break;
case 3: ordered = ordered.ThenBy(i => 0).ThenBy(i => 0).ThenBy(i => i); break;
}
Assert.Equal(expected, ordered);
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public void SortsLargeRandomizedEnumerableCorrectly(int thenBys)
{
const int Items = 100_000;
var r = new Random(42);
int[] randomized = Enumerable.Range(0, Items).Select(i => r.Next()).ToArray();
IOrderedEnumerable<int> orderedEnumerable = randomized.OrderBy(_ => 0);
switch (thenBys)
{
case 1: orderedEnumerable = orderedEnumerable.ThenBy(i => i); break;
case 2: orderedEnumerable = orderedEnumerable.ThenBy(i => 0).ThenBy(i => i); break;
case 3: orderedEnumerable = orderedEnumerable.ThenBy(i => 0).ThenBy(i => 0).ThenBy(i => i); break;
}
int[] ordered = orderedEnumerable.ToArray();
Array.Sort(randomized, (a, b) => a - b);
Assert.Equal(randomized, orderedEnumerable);
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Media.Imaging.BitmapMetadata.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Media.Imaging
{
public partial class BitmapMetadata : System.Windows.Media.ImageMetadata, IEnumerable<string>, System.Collections.IEnumerable
{
#region Methods and constructors
public BitmapMetadata(string containerFormat)
{
}
public System.Windows.Media.Imaging.BitmapMetadata Clone()
{
return default(System.Windows.Media.Imaging.BitmapMetadata);
}
protected override void CloneCore(System.Windows.Freezable sourceFreezable)
{
}
protected override void CloneCurrentValueCore(System.Windows.Freezable sourceFreezable)
{
}
public bool ContainsQuery(string query)
{
return default(bool);
}
protected override System.Windows.Freezable CreateInstanceCore()
{
return default(System.Windows.Freezable);
}
protected override void GetAsFrozenCore(System.Windows.Freezable sourceFreezable)
{
}
protected override void GetCurrentValueAsFrozenCore(System.Windows.Freezable sourceFreezable)
{
}
public Object GetQuery(string query)
{
return default(Object);
}
public void RemoveQuery(string query)
{
}
public void SetQuery(string query, Object value)
{
}
IEnumerator<string> System.Collections.Generic.IEnumerable<System.String>.GetEnumerator()
{
return default(IEnumerator<string>);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return default(System.Collections.IEnumerator);
}
#endregion
#region Properties and indexers
public string ApplicationName
{
get
{
return default(string);
}
set
{
}
}
public System.Collections.ObjectModel.ReadOnlyCollection<string> Author
{
get
{
return default(System.Collections.ObjectModel.ReadOnlyCollection<string>);
}
set
{
}
}
public string CameraManufacturer
{
get
{
return default(string);
}
set
{
}
}
public string CameraModel
{
get
{
return default(string);
}
set
{
}
}
public string Comment
{
get
{
return default(string);
}
set
{
}
}
public string Copyright
{
get
{
return default(string);
}
set
{
}
}
public string DateTaken
{
get
{
return default(string);
}
set
{
}
}
public string Format
{
get
{
return default(string);
}
}
public bool IsFixedSize
{
get
{
return default(bool);
}
}
public bool IsReadOnly
{
get
{
return default(bool);
}
}
public System.Collections.ObjectModel.ReadOnlyCollection<string> Keywords
{
get
{
return default(System.Collections.ObjectModel.ReadOnlyCollection<string>);
}
set
{
}
}
public string Location
{
get
{
return default(string);
}
}
public int Rating
{
get
{
return default(int);
}
set
{
}
}
public string Subject
{
get
{
return default(string);
}
set
{
}
}
public string Title
{
get
{
return default(string);
}
set
{
}
}
#endregion
}
}
| |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Neo.Compiler.MSIL.UnitTests.Utils;
using Neo.VM;
using Neo.VM.Types;
using System.Linq;
namespace Neo.Compiler.MSIL.UnitTests
{
[TestClass]
public class UnitTest_Types
{
#region Unsupported Types
[TestMethod]
public void float_Test()
{
var testengine = new TestEngine();
var ex = Assert.ThrowsException<System.Exception>(() => testengine.AddEntryScript("./TestClasses/Contract_Types_Float.cs"));
Assert.IsTrue(ex.InnerException.Message.Contains("unsupported instruction"));
}
[TestMethod]
public void decimal_Test()
{
var testengine = new TestEngine();
try
{
testengine.AddEntryScript("./TestClasses/Contract_Types_Decimal.cs");
Assert.Fail("must be fault.");
}
catch (System.Exception ex)
{
Assert.IsTrue(ex.InnerException.Message.Contains("unsupported"));
return;
}
}
[TestMethod]
public void double_Test()
{
var testengine = new TestEngine();
var ex = Assert.ThrowsException<System.Exception>(() => testengine.AddEntryScript("./TestClasses/Contract_Types_Double.cs"));
Assert.IsTrue(ex.InnerException.Message.Contains("unsupported instruction"));
}
#endregion
[TestMethod]
public void null_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkNull");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Null));
}
[TestMethod]
public void bool_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkBoolTrue");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Integer));
Assert.AreEqual(1, ((Integer)item).GetInteger());
testengine.Reset();
result = testengine.ExecuteTestCaseStandard("checkBoolFalse");
item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Integer));
Assert.AreEqual(0, ((Integer)item).GetInteger());
}
[TestMethod]
public void sbyte_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkSbyte");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Integer));
Assert.AreEqual(5, ((Integer)item).GetInteger());
}
[TestMethod]
public void byte_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkByte");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Integer));
Assert.AreEqual(5, ((Integer)item).GetInteger());
}
[TestMethod]
public void short_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkShort");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Integer));
Assert.AreEqual(5, ((Integer)item).GetInteger());
}
[TestMethod]
public void ushort_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkUshort");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Integer));
Assert.AreEqual(5, ((Integer)item).GetInteger());
}
[TestMethod]
public void int_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkInt");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Integer));
Assert.AreEqual(5, ((Integer)item).GetInteger());
}
[TestMethod]
public void uint_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkUint");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Integer));
Assert.AreEqual(5, ((Integer)item).GetInteger());
}
[TestMethod]
public void long_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkLong");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Integer));
Assert.AreEqual(5, ((Integer)item).GetInteger());
}
[TestMethod]
public void ulong_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkUlong");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Integer));
Assert.AreEqual(5, ((Integer)item).GetInteger());
}
[TestMethod]
public void bigInteger_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkBigInteger");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Integer));
Assert.AreEqual(5, ((Integer)item).GetInteger());
}
[TestMethod]
public void byteArray_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkByteArray");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Buffer));
CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, ((Buffer)item).GetSpan().ToArray());
}
[TestMethod]
public void char_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkChar");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Integer));
Assert.AreEqual((int)'n', ((Integer)item).GetInteger());
}
[TestMethod]
public void string_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkString");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(ByteString));
Assert.AreEqual("neo", ((ByteString)item).GetString());
}
[TestMethod]
public void arrayObj_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkArrayObj");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Array));
Assert.AreEqual(1, ((Array)item).Count);
Assert.AreEqual("neo", (((Array)item)[0] as ByteString).GetString());
}
[TestMethod]
public void enum_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkEnum");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Integer));
Assert.AreEqual(5, ((Integer)item).GetInteger());
}
[TestMethod]
public void class_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkClass");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Array));
Assert.AreEqual(1, ((Array)item).Count);
Assert.AreEqual("neo", (((Array)item)[0] as ByteString).GetString());
}
[TestMethod]
public void struct_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkStruct");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Struct));
Assert.AreEqual(1, ((Struct)item).Count);
Assert.AreEqual("neo", (((Struct)item)[0] as ByteString).GetString());
}
[TestMethod]
public void tuple_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkTuple");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Array));
Assert.AreEqual(2, ((Array)item).Count);
Assert.AreEqual("neo", (((Array)item)[0] as ByteString).GetString());
Assert.AreEqual("smart economy", (((Array)item)[1] as ByteString).GetString());
}
[TestMethod]
public void tuple2_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkTuple2");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Array));
Assert.AreEqual(2, ((Array)item).Count);
Assert.AreEqual("neo", (((Array)item)[0] as ByteString).GetString());
Assert.AreEqual("smart economy", (((Array)item)[1] as ByteString).GetString());
}
[TestMethod]
public void tuple3_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkTuple3");
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Array));
Assert.AreEqual(2, ((Array)item).Count);
Assert.AreEqual("neo", (((Array)item)[0] as ByteString).GetString());
Assert.AreEqual("smart economy", (((Array)item)[1] as ByteString).GetString());
}
[TestMethod]
public void event_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkEvent");
Assert.AreEqual(0, result.Count);
Assert.AreEqual(1, testengine.Notifications.Count);
var item = testengine.Notifications.First();
Assert.AreEqual(1, item.State.Count);
Assert.AreEqual("dummyEvent", item.EventName);
Assert.AreEqual("neo", (item.State[0] as ByteString).GetString());
}
[TestMethod]
public void lambda_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkLambda");
Assert.AreEqual(1, result.Count);
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Pointer));
}
[TestMethod]
public void delegate_Test()
{
var testengine = new TestEngine();
testengine.AddEntryScript("./TestClasses/Contract_Types.cs");
var result = testengine.ExecuteTestCaseStandard("checkDelegate");
Assert.AreEqual(1, result.Count);
var item = result.Pop();
Assert.IsInstanceOfType(item, typeof(Pointer));
}
}
}
| |
#region Copyright notice and license
// Copyright 2015-2016 gRPC 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 Grpc.Core.Interceptors;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// Generic base class for client-side stubs.
/// </summary>
public abstract class ClientBase<T> : ClientBase
where T : ClientBase<T>
{
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class that
/// throws <c>NotImplementedException</c> upon invocation of any RPC.
/// This constructor is only provided to allow creation of test doubles
/// for client classes (e.g. mocking requires a parameterless constructor).
/// </summary>
protected ClientBase() : base()
{
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="configuration">The configuration.</param>
protected ClientBase(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="channel">The channel to use for remote call invocation.</param>
public ClientBase(Channel channel) : base(channel)
{
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="callInvoker">The <c>CallInvoker</c> for remote call invocation.</param>
public ClientBase(CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>
/// Creates a new client that sets host field for calls explicitly.
/// gRPC supports multiple "hosts" being served by a single server.
/// By default (if a client was not created by calling this method),
/// host <c>null</c> with the meaning "use default host" is used.
/// </summary>
public T WithHost(string host)
{
var newConfiguration = this.Configuration.WithHost(host);
return NewInstance(newConfiguration);
}
/// <summary>
/// Creates a new instance of client from given <c>ClientBaseConfiguration</c>.
/// </summary>
protected abstract T NewInstance(ClientBaseConfiguration configuration);
}
/// <summary>
/// Base class for client-side stubs.
/// </summary>
public abstract class ClientBase
{
readonly ClientBaseConfiguration configuration;
readonly CallInvoker callInvoker;
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class that
/// throws <c>NotImplementedException</c> upon invocation of any RPC.
/// This constructor is only provided to allow creation of test doubles
/// for client classes (e.g. mocking requires a parameterless constructor).
/// </summary>
protected ClientBase() : this(new UnimplementedCallInvoker())
{
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="configuration">The configuration.</param>
protected ClientBase(ClientBaseConfiguration configuration)
{
this.configuration = GrpcPreconditions.CheckNotNull(configuration, "configuration");
this.callInvoker = configuration.CreateDecoratedCallInvoker();
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="channel">The channel to use for remote call invocation.</param>
public ClientBase(Channel channel) : this(new DefaultCallInvoker(channel))
{
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="callInvoker">The <c>CallInvoker</c> for remote call invocation.</param>
public ClientBase(CallInvoker callInvoker) : this(new ClientBaseConfiguration(callInvoker, null))
{
}
/// <summary>
/// Gets the call invoker.
/// </summary>
protected CallInvoker CallInvoker
{
get { return this.callInvoker; }
}
/// <summary>
/// Gets the configuration.
/// </summary>
internal ClientBaseConfiguration Configuration
{
get { return this.configuration; }
}
/// <summary>
/// Represents configuration of ClientBase. The class itself is visible to
/// subclasses, but contents are marked as internal to make the instances opaque.
/// The verbose name of this class was chosen to make name clash in generated code
/// less likely.
/// </summary>
protected internal class ClientBaseConfiguration
{
private class ClientBaseConfigurationInterceptor : Interceptor
{
readonly Func<IMethod, string, CallOptions, Tuple<string, CallOptions>> interceptor;
/// <summary>
/// Creates a new instance of ClientBaseConfigurationInterceptor given the specified header and host interceptor function.
/// </summary>
public ClientBaseConfigurationInterceptor(Func<IMethod, string, CallOptions, Tuple<string, CallOptions>> interceptor)
{
this.interceptor = GrpcPreconditions.CheckNotNull(interceptor, nameof(interceptor));
}
private ClientInterceptorContext<TRequest, TResponse> GetNewContext<TRequest, TResponse>(ClientInterceptorContext<TRequest, TResponse> context)
where TRequest : class
where TResponse : class
{
var newHostAndCallOptions = interceptor(context.Method, context.Host, context.Options);
return new ClientInterceptorContext<TRequest, TResponse>(context.Method, newHostAndCallOptions.Item1, newHostAndCallOptions.Item2);
}
public override TResponse BlockingUnaryCall<TRequest, TResponse>(TRequest request, ClientInterceptorContext<TRequest, TResponse> context, BlockingUnaryCallContinuation<TRequest, TResponse> continuation)
{
return continuation(request, GetNewContext(context));
}
public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(TRequest request, ClientInterceptorContext<TRequest, TResponse> context, AsyncUnaryCallContinuation<TRequest, TResponse> continuation)
{
return continuation(request, GetNewContext(context));
}
public override AsyncServerStreamingCall<TResponse> AsyncServerStreamingCall<TRequest, TResponse>(TRequest request, ClientInterceptorContext<TRequest, TResponse> context, AsyncServerStreamingCallContinuation<TRequest, TResponse> continuation)
{
return continuation(request, GetNewContext(context));
}
public override AsyncClientStreamingCall<TRequest, TResponse> AsyncClientStreamingCall<TRequest, TResponse>(ClientInterceptorContext<TRequest, TResponse> context, AsyncClientStreamingCallContinuation<TRequest, TResponse> continuation)
{
return continuation(GetNewContext(context));
}
public override AsyncDuplexStreamingCall<TRequest, TResponse> AsyncDuplexStreamingCall<TRequest, TResponse>(ClientInterceptorContext<TRequest, TResponse> context, AsyncDuplexStreamingCallContinuation<TRequest, TResponse> continuation)
{
return continuation(GetNewContext(context));
}
}
readonly CallInvoker undecoratedCallInvoker;
readonly string host;
internal ClientBaseConfiguration(CallInvoker undecoratedCallInvoker, string host)
{
this.undecoratedCallInvoker = GrpcPreconditions.CheckNotNull(undecoratedCallInvoker);
this.host = host;
}
internal CallInvoker CreateDecoratedCallInvoker()
{
return undecoratedCallInvoker.Intercept(new ClientBaseConfigurationInterceptor((method, host, options) => Tuple.Create(this.host, options)));
}
internal ClientBaseConfiguration WithHost(string host)
{
GrpcPreconditions.CheckNotNull(host, nameof(host));
return new ClientBaseConfiguration(this.undecoratedCallInvoker, host);
}
}
}
}
| |
//
// Encog(tm) Core v3.2 - .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.Text;
using Encog.App.Analyst.Util;
using Encog.Util.CSV;
namespace Encog.App.Analyst.Script.Prop
{
/// <summary>
/// A property entry for the Encog Analyst. Properties have a name and section.
/// </summary>
public class PropertyEntry : IComparable<PropertyEntry>
{
/// <summary>
/// The type of property.
/// </summary>
private readonly PropertyType _entryType;
/// <summary>
/// The name of the property.
/// </summary>
private readonly String _name;
/// <summary>
/// The section of the property.
/// </summary>
private readonly String _section;
/// <summary>
/// Construct a property entry.
/// </summary>
/// <param name="theEntryType">The entry type.</param>
/// <param name="theName">The name of the property.</param>
/// <param name="theSection">The section of the property.</param>
public PropertyEntry(PropertyType theEntryType, String theName,
String theSection)
{
_entryType = theEntryType;
_name = theName;
_section = theSection;
}
/// <value>the entryType</value>
public PropertyType EntryType
{
get { return _entryType; }
}
/// <value>The key.</value>
public String Key
{
get { return _section + "_" + _name; }
}
/// <value>the name</value>
public String Name
{
get { return _name; }
}
/// <value>the section</value>
public String Section
{
get { return _section; }
}
#region IComparable<PropertyEntry> Members
/// <summary>
/// </summary>
public int CompareTo(PropertyEntry o)
{
return String.CompareOrdinal(_name, o._name);
}
#endregion
/// <summary>
/// Put a property in dot form, which is "section.subsection.name".
/// </summary>
/// <param name="section">The section.</param>
/// <param name="subSection">The subsection.</param>
/// <param name="name">The name.</param>
/// <returns>The property in dot form.</returns>
public static String DotForm(String section, String subSection,
String name)
{
var result = new StringBuilder();
result.Append(section);
result.Append('.');
result.Append(subSection);
result.Append('.');
result.Append(name);
return result.ToString();
}
/// <summary>
/// </summary>
public override sealed String ToString()
{
var result = new StringBuilder("[");
result.Append(GetType().Name);
result.Append(" name=");
result.Append(_name);
result.Append(", section=");
result.Append(_section);
result.Append("]");
return result.ToString();
}
/// <summary>
/// Validate the specified property.
/// </summary>
/// <param name="theSection">The section.</param>
/// <param name="subSection">The sub section.</param>
/// <param name="theName">The name of the property.</param>
/// <param name="v">The value of the property.</param>
public void Validate(String theSection,
String subSection, String theName, String v)
{
if (string.IsNullOrEmpty(v))
{
return;
}
try
{
switch (EntryType)
{
case PropertyType.TypeBoolean:
if ((Char.ToUpper(v[0]) != 'T')
&& (Char.ToUpper(v[0]) != 'F'))
{
var result = new StringBuilder();
result.Append("Illegal boolean for ");
result.Append(DotForm(_section, subSection,
_name));
result.Append(", value is ");
result.Append(v);
result.Append(".");
throw new AnalystError(result.ToString());
}
break;
case PropertyType.TypeDouble:
CSVFormat.EgFormat.Parse(v);
break;
case PropertyType.TypeFormat:
if (ConvertStringConst.String2AnalystFileFormat(v) == AnalystFileFormat.Unknown)
{
var result = new StringBuilder();
result.Append("Invalid file format for ");
result.Append(DotForm(_section, subSection,
_name));
result.Append(", value is ");
result.Append(v);
result.Append(".");
throw new AnalystError(result.ToString());
}
break;
case PropertyType.TypeInteger:
Int32.Parse(v);
break;
case PropertyType.TypeListString:
break;
case PropertyType.TypeString:
break;
default:
throw new AnalystError("Unsupported property type.");
}
}
catch (FormatException)
{
var result = new StringBuilder();
result.Append("Illegal value for ");
result.Append(DotForm(_section, subSection, _name));
result.Append(", expecting a ");
result.Append(EntryType.ToString());
result.Append(", but got ");
result.Append(v);
result.Append(".");
throw new AnalystError(result.ToString());
}
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// A VLAN mux/demux
/// First published in XenServer 4.1.
/// </summary>
public partial class VLAN : XenObject<VLAN>
{
#region Constructors
public VLAN()
{
}
public VLAN(string uuid,
XenRef<PIF> tagged_PIF,
XenRef<PIF> untagged_PIF,
long tag,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.tagged_PIF = tagged_PIF;
this.untagged_PIF = untagged_PIF;
this.tag = tag;
this.other_config = other_config;
}
/// <summary>
/// Creates a new VLAN from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public VLAN(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new VLAN from a Proxy_VLAN.
/// </summary>
/// <param name="proxy"></param>
public VLAN(Proxy_VLAN proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given VLAN.
/// </summary>
public override void UpdateFrom(VLAN update)
{
uuid = update.uuid;
tagged_PIF = update.tagged_PIF;
untagged_PIF = update.untagged_PIF;
tag = update.tag;
other_config = update.other_config;
}
internal void UpdateFrom(Proxy_VLAN proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
tagged_PIF = proxy.tagged_PIF == null ? null : XenRef<PIF>.Create(proxy.tagged_PIF);
untagged_PIF = proxy.untagged_PIF == null ? null : XenRef<PIF>.Create(proxy.untagged_PIF);
tag = proxy.tag == null ? 0 : long.Parse(proxy.tag);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_VLAN ToProxy()
{
Proxy_VLAN result_ = new Proxy_VLAN();
result_.uuid = uuid ?? "";
result_.tagged_PIF = tagged_PIF ?? "";
result_.untagged_PIF = untagged_PIF ?? "";
result_.tag = tag.ToString();
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this VLAN
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("tagged_PIF"))
tagged_PIF = Marshalling.ParseRef<PIF>(table, "tagged_PIF");
if (table.ContainsKey("untagged_PIF"))
untagged_PIF = Marshalling.ParseRef<PIF>(table, "untagged_PIF");
if (table.ContainsKey("tag"))
tag = Marshalling.ParseLong(table, "tag");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(VLAN other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._tagged_PIF, other._tagged_PIF) &&
Helper.AreEqual2(this._untagged_PIF, other._untagged_PIF) &&
Helper.AreEqual2(this._tag, other._tag) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
internal static List<VLAN> ProxyArrayToObjectList(Proxy_VLAN[] input)
{
var result = new List<VLAN>();
foreach (var item in input)
result.Add(new VLAN(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, VLAN server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
VLAN.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given VLAN.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
public static VLAN get_record(Session session, string _vlan)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_get_record(session.opaque_ref, _vlan);
else
return new VLAN(session.XmlRpcProxy.vlan_get_record(session.opaque_ref, _vlan ?? "").parse());
}
/// <summary>
/// Get a reference to the VLAN instance with the specified UUID.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VLAN> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<VLAN>.Create(session.XmlRpcProxy.vlan_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given VLAN.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
public static string get_uuid(Session session, string _vlan)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_get_uuid(session.opaque_ref, _vlan);
else
return session.XmlRpcProxy.vlan_get_uuid(session.opaque_ref, _vlan ?? "").parse();
}
/// <summary>
/// Get the tagged_PIF field of the given VLAN.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
public static XenRef<PIF> get_tagged_PIF(Session session, string _vlan)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_get_tagged_pif(session.opaque_ref, _vlan);
else
return XenRef<PIF>.Create(session.XmlRpcProxy.vlan_get_tagged_pif(session.opaque_ref, _vlan ?? "").parse());
}
/// <summary>
/// Get the untagged_PIF field of the given VLAN.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
public static XenRef<PIF> get_untagged_PIF(Session session, string _vlan)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_get_untagged_pif(session.opaque_ref, _vlan);
else
return XenRef<PIF>.Create(session.XmlRpcProxy.vlan_get_untagged_pif(session.opaque_ref, _vlan ?? "").parse());
}
/// <summary>
/// Get the tag field of the given VLAN.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
public static long get_tag(Session session, string _vlan)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_get_tag(session.opaque_ref, _vlan);
else
return long.Parse(session.XmlRpcProxy.vlan_get_tag(session.opaque_ref, _vlan ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given VLAN.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
public static Dictionary<string, string> get_other_config(Session session, string _vlan)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_get_other_config(session.opaque_ref, _vlan);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.vlan_get_other_config(session.opaque_ref, _vlan ?? "").parse());
}
/// <summary>
/// Set the other_config field of the given VLAN.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _vlan, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vlan_set_other_config(session.opaque_ref, _vlan, _other_config);
else
session.XmlRpcProxy.vlan_set_other_config(session.opaque_ref, _vlan ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given VLAN.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _vlan, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vlan_add_to_other_config(session.opaque_ref, _vlan, _key, _value);
else
session.XmlRpcProxy.vlan_add_to_other_config(session.opaque_ref, _vlan ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given VLAN. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _vlan, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vlan_remove_from_other_config(session.opaque_ref, _vlan, _key);
else
session.XmlRpcProxy.vlan_remove_from_other_config(session.opaque_ref, _vlan ?? "", _key ?? "").parse();
}
/// <summary>
/// Create a VLAN mux/demuxer
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tagged_pif">PIF which receives the tagged traffic</param>
/// <param name="_tag">VLAN tag to use</param>
/// <param name="_network">Network to receive the untagged traffic</param>
public static XenRef<VLAN> create(Session session, string _tagged_pif, long _tag, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_create(session.opaque_ref, _tagged_pif, _tag, _network);
else
return XenRef<VLAN>.Create(session.XmlRpcProxy.vlan_create(session.opaque_ref, _tagged_pif ?? "", _tag.ToString(), _network ?? "").parse());
}
/// <summary>
/// Create a VLAN mux/demuxer
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tagged_pif">PIF which receives the tagged traffic</param>
/// <param name="_tag">VLAN tag to use</param>
/// <param name="_network">Network to receive the untagged traffic</param>
public static XenRef<Task> async_create(Session session, string _tagged_pif, long _tag, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vlan_create(session.opaque_ref, _tagged_pif, _tag, _network);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_vlan_create(session.opaque_ref, _tagged_pif ?? "", _tag.ToString(), _network ?? "").parse());
}
/// <summary>
/// Destroy a VLAN mux/demuxer
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
public static void destroy(Session session, string _vlan)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vlan_destroy(session.opaque_ref, _vlan);
else
session.XmlRpcProxy.vlan_destroy(session.opaque_ref, _vlan ?? "").parse();
}
/// <summary>
/// Destroy a VLAN mux/demuxer
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vlan">The opaque_ref of the given vlan</param>
public static XenRef<Task> async_destroy(Session session, string _vlan)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vlan_destroy(session.opaque_ref, _vlan);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_vlan_destroy(session.opaque_ref, _vlan ?? "").parse());
}
/// <summary>
/// Return a list of all the VLANs known to the system.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<VLAN>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_get_all(session.opaque_ref);
else
return XenRef<VLAN>.Create(session.XmlRpcProxy.vlan_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the VLAN Records at once, in a single XML RPC call
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<VLAN>, VLAN> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vlan_get_all_records(session.opaque_ref);
else
return XenRef<VLAN>.Create<Proxy_VLAN>(session.XmlRpcProxy.vlan_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// interface on which traffic is tagged
/// </summary>
[JsonConverter(typeof(XenRefConverter<PIF>))]
public virtual XenRef<PIF> tagged_PIF
{
get { return _tagged_PIF; }
set
{
if (!Helper.AreEqual(value, _tagged_PIF))
{
_tagged_PIF = value;
NotifyPropertyChanged("tagged_PIF");
}
}
}
private XenRef<PIF> _tagged_PIF = new XenRef<PIF>(Helper.NullOpaqueRef);
/// <summary>
/// interface on which traffic is untagged
/// </summary>
[JsonConverter(typeof(XenRefConverter<PIF>))]
public virtual XenRef<PIF> untagged_PIF
{
get { return _untagged_PIF; }
set
{
if (!Helper.AreEqual(value, _untagged_PIF))
{
_untagged_PIF = value;
NotifyPropertyChanged("untagged_PIF");
}
}
}
private XenRef<PIF> _untagged_PIF = new XenRef<PIF>(Helper.NullOpaqueRef);
/// <summary>
/// VLAN tag in use
/// </summary>
public virtual long tag
{
get { return _tag; }
set
{
if (!Helper.AreEqual(value, _tag))
{
_tag = value;
NotifyPropertyChanged("tag");
}
}
}
private long _tag = -1;
/// <summary>
/// additional configuration
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
}
}
| |
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace WeifenLuo.WinFormsUI.Docking
{
internal class VS2012LightAutoHideStrip : AutoHideStripBase
{
private class TabVS2012Light : Tab
{
internal TabVS2012Light(IDockContent content)
: base(content)
{
}
private int m_tabX = 0;
public int TabX
{
get { return m_tabX; }
set { m_tabX = value; }
}
private int m_tabWidth = 0;
public int TabWidth
{
get { return m_tabWidth; }
set { m_tabWidth = value; }
}
public bool IsMouseOver { get; set; }
}
private const int _ImageHeight = 16;
private const int _ImageWidth = 0;
private const int _ImageGapTop = 2;
private const int _ImageGapLeft = 4;
private const int _ImageGapRight = 2;
private const int _ImageGapBottom = 2;
private const int _TextGapLeft = 0;
private const int _TextGapRight = 0;
private const int _TabGapTop = 3;
private const int _TabGapBottom = 8;
private const int _TabGapLeft = 4;
private const int _TabGapBetween = 10;
#region Customizable Properties
public Font TextFont
{
get { return DockPanel.Skin.AutoHideStripSkin.TextFont; }
}
private static StringFormat _stringFormatTabHorizontal;
private StringFormat StringFormatTabHorizontal
{
get
{
if (_stringFormatTabHorizontal == null)
{
_stringFormatTabHorizontal = new StringFormat();
_stringFormatTabHorizontal.Alignment = StringAlignment.Near;
_stringFormatTabHorizontal.LineAlignment = StringAlignment.Center;
_stringFormatTabHorizontal.FormatFlags = StringFormatFlags.NoWrap;
_stringFormatTabHorizontal.Trimming = StringTrimming.None;
}
if (RightToLeft == RightToLeft.Yes)
_stringFormatTabHorizontal.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
else
_stringFormatTabHorizontal.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft;
return _stringFormatTabHorizontal;
}
}
private static StringFormat _stringFormatTabVertical;
private StringFormat StringFormatTabVertical
{
get
{
if (_stringFormatTabVertical == null)
{
_stringFormatTabVertical = new StringFormat();
_stringFormatTabVertical.Alignment = StringAlignment.Near;
_stringFormatTabVertical.LineAlignment = StringAlignment.Center;
_stringFormatTabVertical.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical;
_stringFormatTabVertical.Trimming = StringTrimming.None;
}
if (RightToLeft == RightToLeft.Yes)
_stringFormatTabVertical.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
else
_stringFormatTabVertical.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft;
return _stringFormatTabVertical;
}
}
private static int ImageHeight
{
get { return _ImageHeight; }
}
private static int ImageWidth
{
get { return _ImageWidth; }
}
private static int ImageGapTop
{
get { return _ImageGapTop; }
}
private static int ImageGapLeft
{
get { return _ImageGapLeft; }
}
private static int ImageGapRight
{
get { return _ImageGapRight; }
}
private static int ImageGapBottom
{
get { return _ImageGapBottom; }
}
private static int TextGapLeft
{
get { return _TextGapLeft; }
}
private static int TextGapRight
{
get { return _TextGapRight; }
}
private static int TabGapTop
{
get { return _TabGapTop; }
}
private static int TabGapBottom
{
get { return _TabGapBottom; }
}
private static int TabGapLeft
{
get { return _TabGapLeft; }
}
private static int TabGapBetween
{
get { return _TabGapBetween; }
}
private static Pen PenTabBorder
{
get { return SystemPens.GrayText; }
}
#endregion
private static Matrix _matrixIdentity = new Matrix();
private static Matrix MatrixIdentity
{
get { return _matrixIdentity; }
}
private static DockState[] _dockStates;
private static DockState[] DockStates
{
get
{
if (_dockStates == null)
{
_dockStates = new DockState[4];
_dockStates[0] = DockState.DockLeftAutoHide;
_dockStates[1] = DockState.DockRightAutoHide;
_dockStates[2] = DockState.DockTopAutoHide;
_dockStates[3] = DockState.DockBottomAutoHide;
}
return _dockStates;
}
}
private static GraphicsPath _graphicsPath;
internal static GraphicsPath GraphicsPath
{
get
{
if (_graphicsPath == null)
_graphicsPath = new GraphicsPath();
return _graphicsPath;
}
}
public VS2012LightAutoHideStrip(DockPanel panel)
: base(panel)
{
SetStyle(ControlStyles.ResizeRedraw |
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer, true);
BackColor = SystemColors.ControlLight;
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
g.FillRectangle(SystemBrushes.Control, ClientRectangle);
DrawTabStrip(g);
}
protected override void OnLayout(LayoutEventArgs levent)
{
CalculateTabs();
base.OnLayout(levent);
}
private void DrawTabStrip(Graphics g)
{
DrawTabStrip(g, DockState.DockTopAutoHide);
DrawTabStrip(g, DockState.DockBottomAutoHide);
DrawTabStrip(g, DockState.DockLeftAutoHide);
DrawTabStrip(g, DockState.DockRightAutoHide);
}
private void DrawTabStrip(Graphics g, DockState dockState)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
if (rectTabStrip.IsEmpty)
return;
Matrix matrixIdentity = g.Transform;
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
{
Matrix matrixRotated = new Matrix();
matrixRotated.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2,
(float)rectTabStrip.Y + (float)rectTabStrip.Height / 2));
g.Transform = matrixRotated;
}
foreach (Pane pane in GetPanes(dockState))
{
foreach (TabVS2012Light tab in pane.AutoHideTabs)
DrawTab(g, tab);
}
g.Transform = matrixIdentity;
}
private void CalculateTabs()
{
CalculateTabs(DockState.DockTopAutoHide);
CalculateTabs(DockState.DockBottomAutoHide);
CalculateTabs(DockState.DockLeftAutoHide);
CalculateTabs(DockState.DockRightAutoHide);
}
private void CalculateTabs(DockState dockState)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
int imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom;
int imageWidth = ImageWidth;
if (imageHeight > ImageHeight)
imageWidth = ImageWidth * (imageHeight / ImageHeight);
int x = TabGapLeft + rectTabStrip.X;
foreach (Pane pane in GetPanes(dockState))
{
foreach (TabVS2012Light tab in pane.AutoHideTabs)
{
int width = imageWidth + ImageGapLeft + ImageGapRight +
TextRenderer.MeasureText(tab.Content.DockHandler.TabText, TextFont).Width +
TextGapLeft + TextGapRight;
tab.TabX = x;
tab.TabWidth = width;
x += width;
}
x += TabGapBetween;
}
}
private Rectangle RtlTransform(Rectangle rect, DockState dockState)
{
Rectangle rectTransformed;
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
rectTransformed = rect;
else
rectTransformed = DrawHelper.RtlTransform(this, rect);
return rectTransformed;
}
private GraphicsPath GetTabOutline(TabVS2012Light tab, bool transformed, bool rtlTransform)
{
DockState dockState = tab.Content.DockHandler.DockState;
Rectangle rectTab = GetTabRectangle(tab, transformed);
if (rtlTransform)
rectTab = RtlTransform(rectTab, dockState);
if (GraphicsPath != null)
{
GraphicsPath.Reset();
GraphicsPath.AddRectangle(rectTab);
}
return GraphicsPath;
}
private void DrawTab(Graphics g, TabVS2012Light tab)
{
Rectangle rectTabOrigin = GetTabRectangle(tab);
if (rectTabOrigin.IsEmpty)
return;
DockState dockState = tab.Content.DockHandler.DockState;
IDockContent content = tab.Content;
Color textColor;
if (tab.Content.DockHandler.IsActivated || tab.IsMouseOver)
textColor = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.StartColor;
else
textColor = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.EndColor;
Rectangle rectThickLine = rectTabOrigin;
rectThickLine.X += _TabGapLeft + _TextGapLeft + _ImageGapLeft + _ImageWidth;
rectThickLine.Width = TextRenderer.MeasureText(tab.Content.DockHandler.TabText, TextFont).Width - 8;
rectThickLine.Height = Measures.AutoHideTabLineWidth;
if (dockState == DockState.DockBottomAutoHide || dockState == DockState.DockLeftAutoHide)
rectThickLine.Y += rectTabOrigin.Height - Measures.AutoHideTabLineWidth;
else
if (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide)
rectThickLine.Y += 0;
g.FillRectangle(new SolidBrush(textColor), rectThickLine);
//Set no rotate for drawing icon and text
Matrix matrixRotate = g.Transform;
g.Transform = MatrixIdentity;
// Draw the icon
Rectangle rectImage = rectTabOrigin;
rectImage.X += ImageGapLeft;
rectImage.Y += ImageGapTop;
int imageHeight = rectTabOrigin.Height - ImageGapTop - ImageGapBottom;
int imageWidth = ImageWidth;
if (imageHeight > ImageHeight)
imageWidth = ImageWidth * (imageHeight / ImageHeight);
rectImage.Height = imageHeight;
rectImage.Width = imageWidth;
rectImage = GetTransformedRectangle(dockState, rectImage);
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
{
// The DockState is DockLeftAutoHide or DockRightAutoHide, so rotate the image 90 degrees to the right.
Rectangle rectTransform = RtlTransform(rectImage, dockState);
Point[] rotationPoints =
{
new Point(rectTransform.X + rectTransform.Width, rectTransform.Y),
new Point(rectTransform.X + rectTransform.Width, rectTransform.Y + rectTransform.Height),
new Point(rectTransform.X, rectTransform.Y)
};
using (Icon rotatedIcon = new Icon(((Form)content).Icon, 16, 16))
{
g.DrawImage(rotatedIcon.ToBitmap(), rotationPoints);
}
}
else
{
// Draw the icon normally without any rotation.
g.DrawIcon(((Form)content).Icon, RtlTransform(rectImage, dockState));
}
// Draw the text
Rectangle rectText = rectTabOrigin;
rectText.X += ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft;
rectText.Width -= ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft;
rectText = RtlTransform(GetTransformedRectangle(dockState, rectText), dockState);
if (DockPanel.ActiveContent == content || tab.IsMouseOver)
textColor = DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor;
else
textColor = DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor;
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, StringFormatTabVertical);
else
g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, StringFormatTabHorizontal);
// Set rotate back
g.Transform = matrixRotate;
}
private Rectangle GetLogicalTabStripRectangle(DockState dockState)
{
return GetLogicalTabStripRectangle(dockState, false);
}
private Rectangle GetLogicalTabStripRectangle(DockState dockState, bool transformed)
{
if (!DockHelper.IsDockStateAutoHide(dockState))
return Rectangle.Empty;
int leftPanes = GetPanes(DockState.DockLeftAutoHide).Count;
int rightPanes = GetPanes(DockState.DockRightAutoHide).Count;
int topPanes = GetPanes(DockState.DockTopAutoHide).Count;
int bottomPanes = GetPanes(DockState.DockBottomAutoHide).Count;
int x, y, width, height;
height = MeasureHeight();
if (dockState == DockState.DockLeftAutoHide && leftPanes > 0)
{
x = 0;
y = (topPanes == 0) ? 0 : height;
width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height);
}
else if (dockState == DockState.DockRightAutoHide && rightPanes > 0)
{
x = Width - height;
if (leftPanes != 0 && x < height)
x = height;
y = (topPanes == 0) ? 0 : height;
width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height);
}
else if (dockState == DockState.DockTopAutoHide && topPanes > 0)
{
x = leftPanes == 0 ? 0 : height;
y = 0;
width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height);
}
else if (dockState == DockState.DockBottomAutoHide && bottomPanes > 0)
{
x = leftPanes == 0 ? 0 : height;
y = Height - height;
if (topPanes != 0 && y < height)
y = height;
width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height);
}
else
return Rectangle.Empty;
if (width == 0 || height == 0)
{
return Rectangle.Empty;
}
var rect = new Rectangle(x, y, width, height);
return transformed ? GetTransformedRectangle(dockState, rect) : rect;
}
private Rectangle GetTabRectangle(TabVS2012Light tab)
{
return GetTabRectangle(tab, false);
}
private Rectangle GetTabRectangle(TabVS2012Light tab, bool transformed)
{
DockState dockState = tab.Content.DockHandler.DockState;
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
if (rectTabStrip.IsEmpty)
return Rectangle.Empty;
int x = tab.TabX;
int y = rectTabStrip.Y +
(dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide ?
0 : TabGapTop);
int width = tab.TabWidth;
int height = rectTabStrip.Height - TabGapTop;
if (!transformed)
return new Rectangle(x, y, width, height);
else
return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height));
}
private Rectangle GetTransformedRectangle(DockState dockState, Rectangle rect)
{
if (dockState != DockState.DockLeftAutoHide && dockState != DockState.DockRightAutoHide)
return rect;
PointF[] pts = new PointF[1];
// the center of the rectangle
pts[0].X = (float)rect.X + (float)rect.Width / 2;
pts[0].Y = (float)rect.Y + (float)rect.Height / 2;
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
Matrix matrix = new Matrix();
matrix.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2,
(float)rectTabStrip.Y + (float)rectTabStrip.Height / 2));
matrix.TransformPoints(pts);
return new Rectangle((int)(pts[0].X - (float)rect.Height / 2 + .5F),
(int)(pts[0].Y - (float)rect.Width / 2 + .5F),
rect.Height, rect.Width);
}
protected override IDockContent HitTest(Point ptMouse)
{
Tab tab = TabHitTest(ptMouse);
if (tab != null)
return tab.Content;
else
return null;
}
protected Tab TabHitTest(Point ptMouse)
{
foreach (DockState state in DockStates)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(state, true);
if (!rectTabStrip.Contains(ptMouse))
continue;
foreach (Pane pane in GetPanes(state))
{
foreach (TabVS2012Light tab in pane.AutoHideTabs)
{
GraphicsPath path = GetTabOutline(tab, true, true);
if (path.IsVisible(ptMouse))
return tab;
}
}
}
return null;
}
private TabVS2012Light lastSelectedTab = null;
protected override void OnMouseHover(EventArgs e)
{
var tab = (TabVS2012Light)TabHitTest(PointToClient(MousePosition));
if (tab != null)
{
tab.IsMouseOver = true;
Invalidate();
}
if (lastSelectedTab != tab)
{
if (lastSelectedTab != null)
lastSelectedTab.IsMouseOver = false;
lastSelectedTab = tab;
}
base.OnMouseHover(e);
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
if (lastSelectedTab != null)
lastSelectedTab.IsMouseOver = false;
Invalidate();
}
protected internal override int MeasureHeight()
{
return Math.Max(ImageGapBottom +
ImageGapTop + ImageHeight,
TextFont.Height) + TabGapTop + TabGapBottom;
}
protected override void OnRefreshChanges()
{
CalculateTabs();
Invalidate();
}
protected override AutoHideStripBase.Tab CreateTab(IDockContent content)
{
return new TabVS2012Light(content);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.