context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using SIL.Windows.Forms.Widgets;
namespace SIL.Windows.Forms.WritingSystems
{
partial class WSFontControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this._fontComboBox = new System.Windows.Forms.ComboBox();
this._fontSizeComboBox = new System.Windows.Forms.ComboBox();
this._fontLabel = new System.Windows.Forms.Label();
this._sizeLabel = new System.Windows.Forms.Label();
this._rightToLeftCheckBox = new System.Windows.Forms.CheckBox();
this._tableLayoutPanelMain = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanelTestArea = new System.Windows.Forms.TableLayoutPanel();
this._testArea = new System.Windows.Forms.TextBox();
this._testAreaLabel = new System.Windows.Forms.Label();
this._fontNotAvailableLabel = new System.Windows.Forms.Label();
this._promptForFontTestArea = new SIL.Windows.Forms.Widgets.Prompt();
this._l10NSharpExtender = new L10NSharp.UI.L10NSharpExtender(this.components);
this._tableLayoutPanelMain.SuspendLayout();
this.tableLayoutPanelTestArea.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this._l10NSharpExtender)).BeginInit();
this.SuspendLayout();
//
// _fontComboBox
//
this._fontComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._fontComboBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append;
this._fontComboBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this._fontComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.Simple;
this._fontComboBox.FormattingEnabled = true;
this._fontComboBox.IntegralHeight = false;
this._l10NSharpExtender.SetLocalizableToolTip(this._fontComboBox, null);
this._l10NSharpExtender.SetLocalizationComment(this._fontComboBox, null);
this._l10NSharpExtender.SetLocalizationPriority(this._fontComboBox, L10NSharp.LocalizationPriority.NotLocalizable);
this._l10NSharpExtender.SetLocalizingId(this._fontComboBox, "WSFontControl._fontComboBox");
this._fontComboBox.Location = new System.Drawing.Point(3, 19);
this._fontComboBox.Name = "_fontComboBox";
this._fontComboBox.Size = new System.Drawing.Size(292, 143);
this._fontComboBox.TabIndex = 1;
this._fontComboBox.TextChanged += new System.EventHandler(this.FontComboBox_TextChanged);
//
// _fontSizeComboBox
//
this._fontSizeComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._fontSizeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.Simple;
this._fontSizeComboBox.FormatString = "N2";
this._fontSizeComboBox.FormattingEnabled = true;
this._fontSizeComboBox.IntegralHeight = false;
this._fontSizeComboBox.Items.AddRange(new object[] {
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23",
"24"});
this._l10NSharpExtender.SetLocalizableToolTip(this._fontSizeComboBox, null);
this._l10NSharpExtender.SetLocalizationComment(this._fontSizeComboBox, null);
this._l10NSharpExtender.SetLocalizationPriority(this._fontSizeComboBox, L10NSharp.LocalizationPriority.NotLocalizable);
this._l10NSharpExtender.SetLocalizingId(this._fontSizeComboBox, "WSFontControl._fontSizeComboBox");
this._fontSizeComboBox.Location = new System.Drawing.Point(301, 19);
this._fontSizeComboBox.Name = "_fontSizeComboBox";
this._fontSizeComboBox.Size = new System.Drawing.Size(174, 143);
this._fontSizeComboBox.TabIndex = 3;
this._fontSizeComboBox.TextChanged += new System.EventHandler(this.FontSizeComboBox_TextChanged);
//
// _fontLabel
//
this._fontLabel.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this._l10NSharpExtender.SetLocalizableToolTip(this._fontLabel, null);
this._l10NSharpExtender.SetLocalizationComment(this._fontLabel, null);
this._l10NSharpExtender.SetLocalizingId(this._fontLabel, "WSFontControl.Font");
this._fontLabel.Location = new System.Drawing.Point(3, 0);
this._fontLabel.Name = "_fontLabel";
this._fontLabel.Size = new System.Drawing.Size(292, 16);
this._fontLabel.TabIndex = 0;
this._fontLabel.Text = "&Font:";
//
// _sizeLabel
//
this._sizeLabel.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this._l10NSharpExtender.SetLocalizableToolTip(this._sizeLabel, null);
this._l10NSharpExtender.SetLocalizationComment(this._sizeLabel, null);
this._l10NSharpExtender.SetLocalizingId(this._sizeLabel, "WSFontControl.Size");
this._sizeLabel.Location = new System.Drawing.Point(301, 0);
this._sizeLabel.Name = "_sizeLabel";
this._sizeLabel.Size = new System.Drawing.Size(170, 14);
this._sizeLabel.TabIndex = 2;
this._sizeLabel.Text = "&Size:";
//
// _rightToLeftCheckBox
//
this._tableLayoutPanelMain.SetColumnSpan(this._rightToLeftCheckBox, 2);
this._l10NSharpExtender.SetLocalizableToolTip(this._rightToLeftCheckBox, null);
this._l10NSharpExtender.SetLocalizationComment(this._rightToLeftCheckBox, null);
this._l10NSharpExtender.SetLocalizingId(this._rightToLeftCheckBox, "WSFontControl.RightToLeftWS");
this._rightToLeftCheckBox.Location = new System.Drawing.Point(3, 168);
this._rightToLeftCheckBox.Name = "_rightToLeftCheckBox";
this._rightToLeftCheckBox.Size = new System.Drawing.Size(472, 24);
this._rightToLeftCheckBox.TabIndex = 3;
this._rightToLeftCheckBox.Text = "This is a &right-to-left writing system.";
this._rightToLeftCheckBox.UseVisualStyleBackColor = false;
this._rightToLeftCheckBox.CheckedChanged += new System.EventHandler(this.RightToLeftCheckBox_CheckedChanged);
//
// _tableLayoutPanelMain
//
this._tableLayoutPanelMain.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._tableLayoutPanelMain.ColumnCount = 2;
this._tableLayoutPanelMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 298F));
this._tableLayoutPanelMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this._tableLayoutPanelMain.Controls.Add(this._rightToLeftCheckBox, 0, 2);
this._tableLayoutPanelMain.Controls.Add(this._fontSizeComboBox, 1, 1);
this._tableLayoutPanelMain.Controls.Add(this._fontComboBox, 0, 1);
this._tableLayoutPanelMain.Controls.Add(this._fontLabel, 0, 0);
this._tableLayoutPanelMain.Controls.Add(this._sizeLabel, 1, 0);
this._tableLayoutPanelMain.Controls.Add(this.tableLayoutPanelTestArea, 0, 3);
this._tableLayoutPanelMain.Location = new System.Drawing.Point(0, 0);
this._tableLayoutPanelMain.Name = "_tableLayoutPanelMain";
this._tableLayoutPanelMain.RowCount = 4;
this._tableLayoutPanelMain.RowStyles.Add(new System.Windows.Forms.RowStyle());
this._tableLayoutPanelMain.RowStyles.Add(new System.Windows.Forms.RowStyle());
this._tableLayoutPanelMain.RowStyles.Add(new System.Windows.Forms.RowStyle());
this._tableLayoutPanelMain.RowStyles.Add(new System.Windows.Forms.RowStyle());
this._tableLayoutPanelMain.Size = new System.Drawing.Size(478, 303);
this._tableLayoutPanelMain.TabIndex = 0;
//
// tableLayoutPanelTestArea
//
this.tableLayoutPanelTestArea.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanelTestArea.AutoSize = true;
this.tableLayoutPanelTestArea.ColumnCount = 2;
this._tableLayoutPanelMain.SetColumnSpan(this.tableLayoutPanelTestArea, 2);
this.tableLayoutPanelTestArea.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanelTestArea.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanelTestArea.Controls.Add(this._testAreaLabel, 0, 0);
this.tableLayoutPanelTestArea.Controls.Add(this._fontNotAvailableLabel, 1, 0);
this.tableLayoutPanelTestArea.Controls.Add(this._testArea, 0, 1);
this.tableLayoutPanelTestArea.Location = new System.Drawing.Point(3, 198);
this.tableLayoutPanelTestArea.Name = "tableLayoutPanelTestArea";
this.tableLayoutPanelTestArea.RowCount = 2;
this.tableLayoutPanelTestArea.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanelTestArea.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanelTestArea.Size = new System.Drawing.Size(472, 102);
this.tableLayoutPanelTestArea.TabIndex = 4;
//
// _testArea
//
this._testArea.AcceptsReturn = true;
this._testArea.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanelTestArea.SetColumnSpan(this._testArea, 2);
this._l10NSharpExtender.SetLocalizableToolTip(this._testArea, null);
this._l10NSharpExtender.SetLocalizationComment(this._testArea, null);
this._l10NSharpExtender.SetLocalizationPriority(this._testArea, L10NSharp.LocalizationPriority.NotLocalizable);
this._l10NSharpExtender.SetLocalizingId(this._testArea, "WSFontControl._testArea");
this._testArea.Location = new System.Drawing.Point(3, 16);
this._testArea.Multiline = true;
this._testArea.Name = "_testArea";
this._testArea.Size = new System.Drawing.Size(466, 83);
this._testArea.TabIndex = 5;
this._testArea.Enter += new System.EventHandler(this._testArea_Enter);
this._testArea.Leave += new System.EventHandler(this._testArea_Leave);
//
// _testAreaLabel
//
this._testAreaLabel.AutoSize = true;
this._l10NSharpExtender.SetLocalizableToolTip(this._testAreaLabel, null);
this._l10NSharpExtender.SetLocalizationComment(this._testAreaLabel, null);
this._l10NSharpExtender.SetLocalizingId(this._testAreaLabel, "WSFontControl.TestArea");
this._testAreaLabel.Location = new System.Drawing.Point(3, 0);
this._testAreaLabel.Name = "_testAreaLabel";
this._testAreaLabel.Size = new System.Drawing.Size(56, 13);
this._testAreaLabel.TabIndex = 0;
this._testAreaLabel.Text = "&Test Area:";
//
// _fontNotAvailableLabel
//
this._fontNotAvailableLabel.AutoSize = true;
this._fontNotAvailableLabel.ForeColor = System.Drawing.Color.Red;
this._l10NSharpExtender.SetLocalizableToolTip(this._fontNotAvailableLabel, null);
this._l10NSharpExtender.SetLocalizationComment(this._fontNotAvailableLabel, null);
this._l10NSharpExtender.SetLocalizingId(this._fontNotAvailableLabel, "WSFontControl.FontNotAvailable");
this._fontNotAvailableLabel.Location = new System.Drawing.Point(65, 0);
this._fontNotAvailableLabel.Name = "_fontNotAvailableLabel";
this._fontNotAvailableLabel.Size = new System.Drawing.Size(317, 13);
this._fontNotAvailableLabel.TabIndex = 1;
this._fontNotAvailableLabel.Text = "(The selected font is not available on this machine. Using default.)";
this._fontNotAvailableLabel.Visible = false;
//
// _l10NSharpExtender
//
this._l10NSharpExtender.LocalizationManagerId = "Palaso";
this._l10NSharpExtender.PrefixForNewItems = "WSFontControl";
//
// WSFontControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this._tableLayoutPanelMain);
this._l10NSharpExtender.SetLocalizableToolTip(this, null);
this._l10NSharpExtender.SetLocalizationComment(this, null);
this._l10NSharpExtender.SetLocalizationPriority(this, L10NSharp.LocalizationPriority.NotLocalizable);
this._l10NSharpExtender.SetLocalizingId(this, "WSFontControl.WSFontControl");
this.Name = "WSFontControl";
this.Size = new System.Drawing.Size(478, 303);
this._tableLayoutPanelMain.ResumeLayout(false);
this._tableLayoutPanelMain.PerformLayout();
this.tableLayoutPanelTestArea.ResumeLayout(false);
this.tableLayoutPanelTestArea.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this._l10NSharpExtender)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ComboBox _fontComboBox;
private System.Windows.Forms.ComboBox _fontSizeComboBox;
private System.Windows.Forms.Label _fontLabel;
private System.Windows.Forms.Label _sizeLabel;
private System.Windows.Forms.CheckBox _rightToLeftCheckBox;
private Prompt _promptForFontTestArea;
private System.Windows.Forms.TableLayoutPanel _tableLayoutPanelMain;
private L10NSharp.UI.L10NSharpExtender _l10NSharpExtender;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanelTestArea;
private System.Windows.Forms.Label _testAreaLabel;
private System.Windows.Forms.Label _fontNotAvailableLabel;
private System.Windows.Forms.TextBox _testArea;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Drawing.Drawing2D.LinearGradientBrush.cs
//
// Authors:
// Dennis Hayes (dennish@Raytek.com)
// Ravindra (rkumar@novell.com)
//
// Copyright (C) 2002/3 Ximian, Inc. http://www.ximian.com
// Copyright (C) 2004,2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace System.Drawing.Drawing2D
{
public sealed class LinearGradientBrush : Brush
{
RectangleF rectangle;
internal LinearGradientBrush(IntPtr native)
{
Status status = SafeNativeMethods.Gdip.GdipGetLineRect(native, out rectangle);
SetNativeBrush(native);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public LinearGradientBrush(Point point1, Point point2, Color color1, Color color2)
{
IntPtr nativeObject;
Status status = SafeNativeMethods.Gdip.GdipCreateLineBrushI(ref point1, ref point2, color1.ToArgb(), color2.ToArgb(), WrapMode.Tile, out nativeObject);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrush(nativeObject);
status = SafeNativeMethods.Gdip.GdipGetLineRect(nativeObject, out rectangle);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public LinearGradientBrush(PointF point1, PointF point2, Color color1, Color color2)
{
IntPtr nativeObject;
Status status = SafeNativeMethods.Gdip.GdipCreateLineBrush(ref point1, ref point2, color1.ToArgb(), color2.ToArgb(), WrapMode.Tile, out nativeObject);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrush(nativeObject);
status = SafeNativeMethods.Gdip.GdipGetLineRect(nativeObject, out rectangle);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public LinearGradientBrush(Rectangle rect, Color color1, Color color2, LinearGradientMode linearGradientMode)
{
IntPtr nativeObject;
Status status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRectI(ref rect, color1.ToArgb(), color2.ToArgb(), linearGradientMode, WrapMode.Tile, out nativeObject);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrush(nativeObject);
rectangle = (RectangleF)rect;
}
public LinearGradientBrush(Rectangle rect, Color color1, Color color2, float angle) : this(rect, color1, color2, angle, false)
{
}
public LinearGradientBrush(RectangleF rect, Color color1, Color color2, LinearGradientMode linearGradientMode)
{
IntPtr nativeObject;
Status status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRect(ref rect, color1.ToArgb(), color2.ToArgb(), linearGradientMode, WrapMode.Tile, out nativeObject);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrush(nativeObject);
rectangle = rect;
}
public LinearGradientBrush(RectangleF rect, Color color1, Color color2, float angle) : this(rect, color1, color2, angle, false)
{
}
public LinearGradientBrush(Rectangle rect, Color color1, Color color2, float angle, bool isAngleScaleable)
{
IntPtr nativeObject;
Status status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRectWithAngleI(ref rect, color1.ToArgb(), color2.ToArgb(), angle, isAngleScaleable, WrapMode.Tile, out nativeObject);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrush(nativeObject);
rectangle = (RectangleF)rect;
}
public LinearGradientBrush(RectangleF rect, Color color1, Color color2, float angle, bool isAngleScaleable)
{
IntPtr nativeObject;
Status status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRectWithAngle(ref rect, color1.ToArgb(), color2.ToArgb(), angle, isAngleScaleable, WrapMode.Tile, out nativeObject);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrush(nativeObject);
rectangle = rect;
}
// Public Properties
public Blend Blend
{
get
{
int count;
Status status = SafeNativeMethods.Gdip.GdipGetLineBlendCount(NativeBrush, out count);
SafeNativeMethods.Gdip.CheckStatus(status);
float[] factors = new float[count];
float[] positions = new float[count];
status = SafeNativeMethods.Gdip.GdipGetLineBlend(NativeBrush, factors, positions, count);
SafeNativeMethods.Gdip.CheckStatus(status);
Blend blend = new Blend();
blend.Factors = factors;
blend.Positions = positions;
return blend;
}
set
{
// no null check, MS throws a NullReferenceException here
int count;
float[] factors = value.Factors;
float[] positions = value.Positions;
count = factors.Length;
if (count == 0 || positions.Length == 0)
throw new ArgumentException("Invalid Blend object. It should have at least 2 elements in each of the factors and positions arrays.");
if (count != positions.Length)
throw new ArgumentException("Invalid Blend object. It should contain the same number of factors and positions values.");
if (positions[0] != 0.0F)
throw new ArgumentException("Invalid Blend object. The positions array must have 0.0 as its first element.");
if (positions[count - 1] != 1.0F)
throw new ArgumentException("Invalid Blend object. The positions array must have 1.0 as its last element.");
Status status = SafeNativeMethods.Gdip.GdipSetLineBlend(NativeBrush, factors, positions, count);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
[MonoTODO("The GammaCorrection value is ignored when using libgdiplus.")]
public bool GammaCorrection
{
get
{
bool gammaCorrection;
Status status = SafeNativeMethods.Gdip.GdipGetLineGammaCorrection(NativeBrush, out gammaCorrection);
SafeNativeMethods.Gdip.CheckStatus(status);
return gammaCorrection;
}
set
{
Status status = SafeNativeMethods.Gdip.GdipSetLineGammaCorrection(NativeBrush, value);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
public ColorBlend InterpolationColors
{
get
{
int count;
Status status = SafeNativeMethods.Gdip.GdipGetLinePresetBlendCount(NativeBrush, out count);
SafeNativeMethods.Gdip.CheckStatus(status);
int[] intcolors = new int[count];
float[] positions = new float[count];
status = SafeNativeMethods.Gdip.GdipGetLinePresetBlend(NativeBrush, intcolors, positions, count);
SafeNativeMethods.Gdip.CheckStatus(status);
ColorBlend interpolationColors = new ColorBlend();
Color[] colors = new Color[count];
for (int i = 0; i < count; i++)
colors[i] = Color.FromArgb(intcolors[i]);
interpolationColors.Colors = colors;
interpolationColors.Positions = positions;
return interpolationColors;
}
set
{
if (value == null)
throw new ArgumentException("InterpolationColors is null");
int count;
Color[] colors = value.Colors;
float[] positions = value.Positions;
count = colors.Length;
if (count == 0 || positions.Length == 0)
throw new ArgumentException("Invalid ColorBlend object. It should have at least 2 elements in each of the colors and positions arrays.");
if (count != positions.Length)
throw new ArgumentException("Invalid ColorBlend object. It should contain the same number of positions and color values.");
if (positions[0] != 0.0F)
throw new ArgumentException("Invalid ColorBlend object. The positions array must have 0.0 as its first element.");
if (positions[count - 1] != 1.0F)
throw new ArgumentException("Invalid ColorBlend object. The positions array must have 1.0 as its last element.");
int[] blend = new int[colors.Length];
for (int i = 0; i < colors.Length; i++)
blend[i] = colors[i].ToArgb();
Status status = SafeNativeMethods.Gdip.GdipSetLinePresetBlend(NativeBrush, blend, positions, count);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
public Color[] LinearColors
{
get
{
int[] colors = new int[2];
Status status = SafeNativeMethods.Gdip.GdipGetLineColors(NativeBrush, colors);
SafeNativeMethods.Gdip.CheckStatus(status);
Color[] linearColors = new Color[2];
linearColors[0] = Color.FromArgb(colors[0]);
linearColors[1] = Color.FromArgb(colors[1]);
return linearColors;
}
set
{
// no null check, MS throws a NullReferenceException here
Status status = SafeNativeMethods.Gdip.GdipSetLineColors(NativeBrush, value[0].ToArgb(), value[1].ToArgb());
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
public RectangleF Rectangle
{
get
{
return rectangle;
}
}
public Matrix Transform
{
get
{
Matrix matrix = new Matrix();
Status status = SafeNativeMethods.Gdip.GdipGetLineTransform(NativeBrush, matrix.nativeMatrix);
SafeNativeMethods.Gdip.CheckStatus(status);
return matrix;
}
set
{
if (value == null)
throw new ArgumentNullException("Transform");
Status status = SafeNativeMethods.Gdip.GdipSetLineTransform(NativeBrush, value.nativeMatrix);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
public WrapMode WrapMode
{
get
{
WrapMode wrapMode;
Status status = SafeNativeMethods.Gdip.GdipGetLineWrapMode(NativeBrush, out wrapMode);
SafeNativeMethods.Gdip.CheckStatus(status);
return wrapMode;
}
set
{
// note: Clamp isn't valid (context wise) but it is checked in libgdiplus
if ((value < WrapMode.Tile) || (value > WrapMode.Clamp))
throw new InvalidEnumArgumentException("WrapMode");
Status status = SafeNativeMethods.Gdip.GdipSetLineWrapMode(NativeBrush, value);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
// Public Methods
public void MultiplyTransform(Matrix matrix)
{
MultiplyTransform(matrix, MatrixOrder.Prepend);
}
public void MultiplyTransform(Matrix matrix, MatrixOrder order)
{
if (matrix == null)
throw new ArgumentNullException("matrix");
Status status = SafeNativeMethods.Gdip.GdipMultiplyLineTransform(NativeBrush, matrix.nativeMatrix, order);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void ResetTransform()
{
Status status = SafeNativeMethods.Gdip.GdipResetLineTransform(NativeBrush);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void RotateTransform(float angle)
{
RotateTransform(angle, MatrixOrder.Prepend);
}
public void RotateTransform(float angle, MatrixOrder order)
{
Status status = SafeNativeMethods.Gdip.GdipRotateLineTransform(NativeBrush, angle, order);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void ScaleTransform(float sx, float sy)
{
ScaleTransform(sx, sy, MatrixOrder.Prepend);
}
public void ScaleTransform(float sx, float sy, MatrixOrder order)
{
Status status = SafeNativeMethods.Gdip.GdipScaleLineTransform(NativeBrush, sx, sy, order);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void SetBlendTriangularShape(float focus)
{
SetBlendTriangularShape(focus, 1.0F);
}
public void SetBlendTriangularShape(float focus, float scale)
{
if (focus < 0 || focus > 1 || scale < 0 || scale > 1)
throw new ArgumentException("Invalid parameter passed.");
Status status = SafeNativeMethods.Gdip.GdipSetLineLinearBlend(NativeBrush, focus, scale);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void SetSigmaBellShape(float focus)
{
SetSigmaBellShape(focus, 1.0F);
}
public void SetSigmaBellShape(float focus, float scale)
{
if (focus < 0 || focus > 1 || scale < 0 || scale > 1)
throw new ArgumentException("Invalid parameter passed.");
Status status = SafeNativeMethods.Gdip.GdipSetLineSigmaBlend(NativeBrush, focus, scale);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void TranslateTransform(float dx, float dy)
{
TranslateTransform(dx, dy, MatrixOrder.Prepend);
}
public void TranslateTransform(float dx, float dy, MatrixOrder order)
{
Status status = SafeNativeMethods.Gdip.GdipTranslateLineTransform(NativeBrush, dx, dy, order);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public override object Clone()
{
IntPtr clonePtr;
int status = SafeNativeMethods.Gdip.GdipCloneBrush(new HandleRef(this, NativeBrush), out clonePtr);
SafeNativeMethods.Gdip.CheckStatus(status);
return new LinearGradientBrush(clonePtr);
}
}
}
| |
// Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt)
using System;
using UnityEngine;
namespace UnityEditor
{
internal class PbrShaderGUI : ShaderGUI
{
private enum WorkflowMode
{
SpecularGlossiness,
MetallicRoughness,
Unlit
}
public enum BlendMode
{
Opaque,
Mask,
Blend
}
private static class Styles
{
public static GUIContent albedoText = new GUIContent("Base Color", "Albedo (RGB) and Transparency (A)");
public static GUIContent vertexColorText = new GUIContent("Apply Vertex Colors", "Process vertex colors");
public static GUIContent alphaCutoffText = new GUIContent("Alpha Cutoff", "Threshold for alpha cutoff");
public static GUIContent specularMapText = new GUIContent("Spec Gloss", "Specular (RGB) and Glossiness (A)");
public static GUIContent metallicMapText = new GUIContent("Metal Rough", "Metallic (B) and Roughness (G)");
public static GUIContent metallicText = new GUIContent("Metallic", "Metallic value");
public static GUIContent metallicScaleText = new GUIContent("Metallic", "Metallic scale factor");
public static GUIContent roughnessText = new GUIContent("Roughness", "Roughness value");
public static GUIContent roughnessScaleText = new GUIContent("Roughness", "Roughness scale factor");
public static GUIContent glossinessText = new GUIContent("Glossiness", "Glossiness value");
public static GUIContent glossinessScaleText = new GUIContent("Glossiness", "Glossiness scale factor");
public static GUIContent normalMapText = new GUIContent("Normal Map", "Normal Map");
public static GUIContent occlusionText = new GUIContent("Occlusion", "Occlusion (R)");
public static GUIContent emissionText = new GUIContent("Emissive", "Emissive (RGB)");
public static string primaryMapsText = "Main Maps";
public static string renderingMode = "Rendering Mode";
public static GUIContent emissiveWarning = new GUIContent("Emissive value is animated but the material has not been configured to support emissive. Please make sure the material itself has some amount of emissive.");
public static readonly string[] blendNames = Enum.GetNames(typeof(BlendMode));
}
MaterialProperty blendMode = null;
MaterialProperty albedoMap = null;
MaterialProperty albedoColor = null;
MaterialProperty vertexColors = null;
MaterialProperty alphaCutoff = null;
MaterialProperty specularMap = null;
MaterialProperty specularColor = null;
MaterialProperty metallicMap = null;
MaterialProperty metallic = null;
MaterialProperty smoothness = null;
MaterialProperty bumpScale = null;
MaterialProperty bumpMap = null;
MaterialProperty occlusionStrength = null;
MaterialProperty occlusionMap = null;
MaterialProperty emissionColor = null;
MaterialProperty emissionMap = null;
MaterialEditor m_MaterialEditor;
WorkflowMode m_WorkflowMode = WorkflowMode.MetallicRoughness;
bool m_FirstTimeApply = true;
public void FindProperties(MaterialProperty[] props)
{
blendMode = FindProperty("_Mode", props);
albedoMap = FindProperty("_MainTex", props);
albedoColor = FindProperty("_Color", props);
vertexColors = FindProperty("_VertexColors", props);
alphaCutoff = FindProperty("_Cutoff", props);
specularMap = FindProperty("_SpecGlossMap", props, false);
specularColor = FindProperty("_SpecColor", props, false);
metallicMap = FindProperty("_MetallicGlossMap", props, false);
metallic = FindProperty("_Metallic", props, false);
if (specularMap != null && specularColor != null)
m_WorkflowMode = WorkflowMode.SpecularGlossiness;
else if (metallicMap != null && metallic != null)
m_WorkflowMode = WorkflowMode.MetallicRoughness;
else
m_WorkflowMode = WorkflowMode.Unlit;
smoothness = FindProperty("_Glossiness", props);
bumpScale = FindProperty("_BumpScale", props);
bumpMap = FindProperty("_BumpMap", props);
occlusionStrength = FindProperty("_OcclusionStrength", props);
occlusionMap = FindProperty("_OcclusionMap", props);
emissionColor = FindProperty("_EmissionColor", props);
emissionMap = FindProperty("_EmissionMap", props);
}
public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props)
{
FindProperties(props); // MaterialProperties can be animated so we do not cache them but fetch them every event to ensure animated values are updated correctly
m_MaterialEditor = materialEditor;
Material material = materialEditor.target as Material;
// Make sure that needed setup (ie keywords/renderqueue) are set up if we're switching some existing
// material to a standard shader.
// Do this before any GUI code has been issued to prevent layout issues in subsequent GUILayout statements (case 780071)
if (m_FirstTimeApply)
{
MaterialChanged(material, m_WorkflowMode);
m_FirstTimeApply = false;
}
ShaderPropertiesGUI(material);
}
public void ShaderPropertiesGUI(Material material)
{
// Use default labelWidth
EditorGUIUtility.labelWidth = 0f;
// Detect any changes to the material
EditorGUI.BeginChangeCheck();
{
BlendModePopup();
// Primary properties
GUILayout.Label(Styles.primaryMapsText, EditorStyles.boldLabel);
DoAlbedoArea(material);
DoSpecularMetallicArea();
m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, bumpMap, bumpMap.textureValue != null ? bumpScale : null);
m_MaterialEditor.TexturePropertySingleLine(Styles.occlusionText, occlusionMap, occlusionMap.textureValue != null ? occlusionStrength : null);
DoEmissionArea(material);
EditorGUILayout.Space();
}
if (EditorGUI.EndChangeCheck())
{
foreach (var obj in blendMode.targets)
MaterialChanged((Material)obj, m_WorkflowMode);
}
}
internal void DetermineWorkflow(MaterialProperty[] props)
{
if (FindProperty("_SpecGlossMap", props, false) != null && FindProperty("_SpecColor", props, false) != null)
m_WorkflowMode = WorkflowMode.SpecularGlossiness;
else if (FindProperty("_MetallicGlossMap", props, false) != null && FindProperty("_Metallic", props, false) != null)
m_WorkflowMode = WorkflowMode.MetallicRoughness;
else
m_WorkflowMode = WorkflowMode.Unlit;
}
void BlendModePopup()
{
EditorGUI.showMixedValue = blendMode.hasMixedValue;
var mode = (BlendMode)blendMode.floatValue;
EditorGUI.BeginChangeCheck();
mode = (BlendMode)EditorGUILayout.Popup(Styles.renderingMode, (int)mode, Styles.blendNames);
if (EditorGUI.EndChangeCheck())
{
m_MaterialEditor.RegisterPropertyChangeUndo("Rendering Mode");
blendMode.floatValue = (float)mode;
}
EditorGUI.showMixedValue = false;
}
void DoAlbedoArea(Material material)
{
m_MaterialEditor.TexturePropertySingleLine(Styles.albedoText, albedoMap, albedoColor);
m_MaterialEditor.ShaderProperty(vertexColors, Styles.vertexColorText, MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1);
if (((BlendMode)material.GetFloat("_Mode") == BlendMode.Mask))
{
m_MaterialEditor.ShaderProperty(alphaCutoff, Styles.alphaCutoffText.text, MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1);
}
}
void DoEmissionArea(Material material)
{
bool hadEmissionTexture = emissionMap.textureValue != null;
// Texture and HDR color controls
m_MaterialEditor.TexturePropertySingleLine(Styles.emissionText, emissionMap, emissionColor);
// If texture was assigned and color was black set color to white
float brightness = emissionColor.colorValue.maxColorComponent;
if (emissionMap.textureValue != null && !hadEmissionTexture && brightness <= 0f)
emissionColor.colorValue = Color.white;
}
void DoSpecularMetallicArea()
{
bool hasGlossMap = false;
if (m_WorkflowMode == WorkflowMode.SpecularGlossiness)
{
hasGlossMap = specularMap.textureValue != null;
m_MaterialEditor.TexturePropertySingleLine(Styles.specularMapText, specularMap, hasGlossMap ? null : specularColor);
m_MaterialEditor.ShaderProperty(smoothness, hasGlossMap ? Styles.glossinessScaleText : Styles.glossinessText, 2);
}
else if (m_WorkflowMode == WorkflowMode.MetallicRoughness)
{
hasGlossMap = metallicMap.textureValue != null;
m_MaterialEditor.TexturePropertySingleLine(Styles.metallicMapText, metallicMap);
m_MaterialEditor.ShaderProperty(metallic, hasGlossMap ? Styles.metallicScaleText : Styles.metallicText, 2);
m_MaterialEditor.ShaderProperty(smoothness, hasGlossMap ? Styles.roughnessScaleText : Styles.roughnessText, 2);
}
}
public static void SetupMaterialWithBlendMode(Material material, BlendMode blendMode, float alphaCutoff)
{
switch (blendMode)
{
case BlendMode.Opaque:
material.SetOverrideTag("RenderType", "Opaque");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
material.DisableKeyword("_ALPHATEST_ON");
material.DisableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Geometry;
break;
case BlendMode.Mask:
material.SetOverrideTag("RenderType", "TransparentCutout");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
material.EnableKeyword("_ALPHATEST_ON");
material.DisableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest;
material.SetFloat("_Cutoff", alphaCutoff);
break;
case BlendMode.Blend:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt("_ZWrite", 0);
material.DisableKeyword("_ALPHATEST_ON");
material.EnableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
break;
}
material.SetFloat("_Mode", (float)blendMode);
}
static void SetMaterialKeywords(Material material, WorkflowMode workflowMode)
{
// Note: keywords must be based on Material value not on MaterialProperty due to multi-edit & material animation
// (MaterialProperty value might come from renderer material property block)
SetKeyword(material, "_NORMALMAP", material.GetTexture("_BumpMap"));
if (workflowMode == WorkflowMode.SpecularGlossiness)
SetKeyword(material, "_SPECGLOSSMAP", material.GetTexture("_SpecGlossMap"));
else if (workflowMode == WorkflowMode.MetallicRoughness)
SetKeyword(material, "_METALLICGLOSSMAP", material.GetTexture("_MetallicGlossMap"));
bool shouldEmissionBeEnabled = material.GetColor("_EmissionColor") != Color.black;
SetKeyword(material, "_EMISSION", shouldEmissionBeEnabled);
}
static void MaterialChanged(Material material, WorkflowMode workflowMode)
{
SetupMaterialWithBlendMode(material, (BlendMode)material.GetFloat("_Mode"), material.GetFloat("_Cutoff"));
SetMaterialKeywords(material, workflowMode);
}
static void SetKeyword(Material m, string keyword, bool state)
{
if (state)
m.EnableKeyword(keyword);
else
m.DisableKeyword(keyword);
}
}
} // namespace UnityEditor
| |
using J2N.Runtime.CompilerServices;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using JCG = J2N.Collections.Generic;
namespace YAF.Lucene.Net.Codecs.PerField
{
/*
* 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 BinaryDocValues = YAF.Lucene.Net.Index.BinaryDocValues;
using BytesRef = YAF.Lucene.Net.Util.BytesRef;
using FieldInfo = YAF.Lucene.Net.Index.FieldInfo;
using IBits = YAF.Lucene.Net.Util.IBits;
using IOUtils = YAF.Lucene.Net.Util.IOUtils;
using NumericDocValues = YAF.Lucene.Net.Index.NumericDocValues;
using RamUsageEstimator = YAF.Lucene.Net.Util.RamUsageEstimator;
using SegmentReadState = YAF.Lucene.Net.Index.SegmentReadState;
using SegmentWriteState = YAF.Lucene.Net.Index.SegmentWriteState;
using SortedDocValues = YAF.Lucene.Net.Index.SortedDocValues;
using SortedSetDocValues = YAF.Lucene.Net.Index.SortedSetDocValues;
/// <summary>
/// Enables per field docvalues support.
/// <para/>
/// Note, when extending this class, the name (<see cref="DocValuesFormat.Name"/>) is
/// written into the index. In order for the field to be read, the
/// name must resolve to your implementation via <see cref="DocValuesFormat.ForName(string)"/>.
/// This method uses <see cref="IDocValuesFormatFactory.GetDocValuesFormat(string)"/> to resolve format names.
/// See <see cref="DefaultDocValuesFormatFactory"/> for information about how to implement your own <see cref="DocValuesFormat"/>.
/// <para/>
/// Files written by each docvalues format have an additional suffix containing the
/// format name. For example, in a per-field configuration instead of <c>_1.dat</c>
/// filenames would look like <c>_1_Lucene40_0.dat</c>.
/// <para/>
/// @lucene.experimental
/// </summary>
/// <seealso cref="IDocValuesFormatFactory"/>
/// <seealso cref="DefaultDocValuesFormatFactory"/>
[DocValuesFormatName("PerFieldDV40")]
public abstract class PerFieldDocValuesFormat : DocValuesFormat
{
// LUCENENET specific: Removing this static variable, since name is now determined by the DocValuesFormatNameAttribute.
///// <summary>
///// Name of this <seealso cref="PostingsFormat"/>. </summary>
//public static readonly string PER_FIELD_NAME = "PerFieldDV40";
/// <summary>
/// <see cref="FieldInfo"/> attribute name used to store the
/// format name for each field.
/// </summary>
public static readonly string PER_FIELD_FORMAT_KEY = typeof(PerFieldDocValuesFormat).Name + ".format";
/// <summary>
/// <see cref="FieldInfo"/> attribute name used to store the
/// segment suffix name for each field.
/// </summary>
public static readonly string PER_FIELD_SUFFIX_KEY = typeof(PerFieldDocValuesFormat).Name + ".suffix";
/// <summary>
/// Sole constructor. </summary>
public PerFieldDocValuesFormat()
: base()
{
}
public override sealed DocValuesConsumer FieldsConsumer(SegmentWriteState state)
{
return new FieldsWriter(this, state);
}
internal class ConsumerAndSuffix : IDisposable
{
internal DocValuesConsumer Consumer { get; set; }
internal int Suffix { get; set; }
public void Dispose()
{
Consumer.Dispose();
}
}
private class FieldsWriter : DocValuesConsumer
{
private readonly PerFieldDocValuesFormat outerInstance;
internal readonly IDictionary<DocValuesFormat, ConsumerAndSuffix> formats = new Dictionary<DocValuesFormat, ConsumerAndSuffix>();
internal readonly IDictionary<string, int?> suffixes = new Dictionary<string, int?>();
internal readonly SegmentWriteState segmentWriteState;
public FieldsWriter(PerFieldDocValuesFormat outerInstance, SegmentWriteState state)
{
this.outerInstance = outerInstance;
segmentWriteState = state;
}
public override void AddNumericField(FieldInfo field, IEnumerable<long?> values)
{
GetInstance(field).AddNumericField(field, values);
}
public override void AddBinaryField(FieldInfo field, IEnumerable<BytesRef> values)
{
GetInstance(field).AddBinaryField(field, values);
}
public override void AddSortedField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrd)
{
GetInstance(field).AddSortedField(field, values, docToOrd);
}
public override void AddSortedSetField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrdCount, IEnumerable<long?> ords)
{
GetInstance(field).AddSortedSetField(field, values, docToOrdCount, ords);
}
internal virtual DocValuesConsumer GetInstance(FieldInfo field)
{
DocValuesFormat format = null;
if (field.DocValuesGen != -1)
{
string formatName = field.GetAttribute(PER_FIELD_FORMAT_KEY);
// this means the field never existed in that segment, yet is applied updates
if (formatName != null)
{
format = DocValuesFormat.ForName(formatName);
}
}
if (format == null)
{
format = outerInstance.GetDocValuesFormatForField(field.Name);
}
if (format == null)
{
throw new InvalidOperationException("invalid null DocValuesFormat for field=\"" + field.Name + "\"");
}
string formatName_ = format.Name;
string previousValue = field.PutAttribute(PER_FIELD_FORMAT_KEY, formatName_);
Debug.Assert(field.DocValuesGen != -1 || previousValue == null, "formatName=" + formatName_ + " prevValue=" + previousValue);
int? suffix = null;
ConsumerAndSuffix consumer;
if (!formats.TryGetValue(format, out consumer) || consumer == null)
{
// First time we are seeing this format; create a new instance
if (field.DocValuesGen != -1)
{
string suffixAtt = field.GetAttribute(PER_FIELD_SUFFIX_KEY);
// even when dvGen is != -1, it can still be a new field, that never
// existed in the segment, and therefore doesn't have the recorded
// attributes yet.
if (suffixAtt != null)
{
suffix = Convert.ToInt32(suffixAtt, CultureInfo.InvariantCulture);
}
}
if (suffix == null)
{
// bump the suffix
if (!suffixes.TryGetValue(formatName_, out suffix) || suffix == null)
{
suffix = 0;
}
else
{
suffix = suffix + 1;
}
}
suffixes[formatName_] = suffix;
string segmentSuffix = GetFullSegmentSuffix(segmentWriteState.SegmentSuffix, GetSuffix(formatName_, Convert.ToString(suffix, CultureInfo.InvariantCulture)));
consumer = new ConsumerAndSuffix();
consumer.Consumer = format.FieldsConsumer(new SegmentWriteState(segmentWriteState, segmentSuffix));
consumer.Suffix = suffix.Value; // LUCENENET NOTE: At this point suffix cannot be null
formats[format] = consumer;
}
else
{
// we've already seen this format, so just grab its suffix
Debug.Assert(suffixes.ContainsKey(formatName_));
suffix = consumer.Suffix;
}
previousValue = field.PutAttribute(PER_FIELD_SUFFIX_KEY, Convert.ToString(suffix, CultureInfo.InvariantCulture));
Debug.Assert(field.DocValuesGen != -1 || previousValue == null, "suffix=" + Convert.ToString(suffix, CultureInfo.InvariantCulture) + " prevValue=" + previousValue);
// TODO: we should only provide the "slice" of FIS
// that this DVF actually sees ...
return consumer.Consumer;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Close all subs
IOUtils.Dispose(formats.Values);
}
}
}
internal static string GetSuffix(string formatName, string suffix)
{
return formatName + "_" + suffix;
}
internal static string GetFullSegmentSuffix(string outerSegmentSuffix, string segmentSuffix)
{
if (outerSegmentSuffix.Length == 0)
{
return segmentSuffix;
}
else
{
return outerSegmentSuffix + "_" + segmentSuffix;
}
}
private class FieldsReader : DocValuesProducer
{
private readonly PerFieldDocValuesFormat outerInstance;
// LUCENENET specific: Use StringComparer.Ordinal to get the same ordering as Java
internal readonly IDictionary<string, DocValuesProducer> fields = new JCG.SortedDictionary<string, DocValuesProducer>(StringComparer.Ordinal);
internal readonly IDictionary<string, DocValuesProducer> formats = new Dictionary<string, DocValuesProducer>();
public FieldsReader(PerFieldDocValuesFormat outerInstance, SegmentReadState readState)
{
this.outerInstance = outerInstance;
// Read _X.per and init each format:
bool success = false;
try
{
// Read field name -> format name
foreach (FieldInfo fi in readState.FieldInfos)
{
if (fi.HasDocValues)
{
string fieldName = fi.Name;
string formatName = fi.GetAttribute(PER_FIELD_FORMAT_KEY);
if (formatName != null)
{
// null formatName means the field is in fieldInfos, but has no docvalues!
string suffix = fi.GetAttribute(PER_FIELD_SUFFIX_KEY);
Debug.Assert(suffix != null);
DocValuesFormat format = DocValuesFormat.ForName(formatName);
string segmentSuffix = GetFullSegmentSuffix(readState.SegmentSuffix, GetSuffix(formatName, suffix));
// LUCENENET: Eliminated extra lookup by using TryGetValue instead of ContainsKey
if (!formats.TryGetValue(segmentSuffix, out DocValuesProducer field))
{
formats[segmentSuffix] = field = format.FieldsProducer(new SegmentReadState(readState, segmentSuffix));
}
fields[fieldName] = field;
}
}
}
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(formats.Values);
}
}
}
internal FieldsReader(PerFieldDocValuesFormat outerInstance, FieldsReader other)
{
this.outerInstance = outerInstance;
IDictionary<DocValuesProducer, DocValuesProducer> oldToNew = new JCG.Dictionary<DocValuesProducer, DocValuesProducer>(IdentityEqualityComparer<DocValuesProducer>.Default);
// First clone all formats
foreach (KeyValuePair<string, DocValuesProducer> ent in other.formats)
{
DocValuesProducer values = ent.Value;
formats[ent.Key] = values;
oldToNew[ent.Value] = values;
}
// Then rebuild fields:
foreach (KeyValuePair<string, DocValuesProducer> ent in other.fields)
{
DocValuesProducer producer;
oldToNew.TryGetValue(ent.Value, out producer);
Debug.Assert(producer != null);
fields[ent.Key] = producer;
}
}
public override NumericDocValues GetNumeric(FieldInfo field)
{
DocValuesProducer producer;
if (fields.TryGetValue(field.Name, out producer) && producer != null)
{
return producer.GetNumeric(field);
}
return null;
}
public override BinaryDocValues GetBinary(FieldInfo field)
{
DocValuesProducer producer;
if (fields.TryGetValue(field.Name, out producer) && producer != null)
{
return producer.GetBinary(field);
}
return null;
}
public override SortedDocValues GetSorted(FieldInfo field)
{
DocValuesProducer producer;
if (fields.TryGetValue(field.Name, out producer) && producer != null)
{
return producer.GetSorted(field);
}
return null;
}
public override SortedSetDocValues GetSortedSet(FieldInfo field)
{
DocValuesProducer producer;
if (fields.TryGetValue(field.Name, out producer) && producer != null)
{
return producer.GetSortedSet(field);
}
return null;
}
public override IBits GetDocsWithField(FieldInfo field)
{
DocValuesProducer producer;
if (fields.TryGetValue(field.Name, out producer) && producer != null)
{
return producer.GetDocsWithField(field);
}
return null;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
IOUtils.Dispose(formats.Values);
}
}
public object Clone()
{
return new FieldsReader(outerInstance, this);
}
public override long RamBytesUsed()
{
long size = 0;
foreach (KeyValuePair<string, DocValuesProducer> entry in formats)
{
size += (entry.Key.Length * RamUsageEstimator.NUM_BYTES_CHAR)
+ entry.Value.RamBytesUsed();
}
return size;
}
public override void CheckIntegrity()
{
foreach (DocValuesProducer format in formats.Values)
{
format.CheckIntegrity();
}
}
}
public override sealed DocValuesProducer FieldsProducer(SegmentReadState state)
{
return new FieldsReader(this, state);
}
/// <summary>
/// Returns the doc values format that should be used for writing
/// new segments of <paramref name="field"/>.
/// <para/>
/// The field to format mapping is written to the index, so
/// this method is only invoked when writing, not when reading.
/// </summary>
public abstract DocValuesFormat GetDocValuesFormatForField(string field);
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Publishing;
namespace Umbraco.Core.Services
{
/// <summary>
/// A temporary interface until we are in v8, this is used to return a different result for the same method and this interface gets implemented
/// explicitly. These methods will replace the normal ones in IContentService in v8 and this will be removed.
/// </summary>
public interface IContentServiceOperations
{
//TODO: Remove this class in v8
//TODO: There's probably more that needs to be added like the EmptyRecycleBin, etc...
/// <summary>
/// Saves a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to save</param>
/// <param name="userId">Optional Id of the User saving the Content</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param>
Attempt<OperationStatus> Save(IContent content, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Saves a collection of <see cref="IContent"/> objects.
/// </summary>
/// <param name="contents">Collection of <see cref="IContent"/> to save</param>
/// <param name="userId">Optional Id of the User saving the Content</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param>
Attempt<OperationStatus> Save(IEnumerable<IContent> contents, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Permanently deletes an <see cref="IContent"/> object.
/// </summary>
/// <remarks>
/// This method will also delete associated media files, child content and possibly associated domains.
/// </remarks>
/// <remarks>Please note that this method will completely remove the Content from the database</remarks>
/// <param name="content">The <see cref="IContent"/> to delete</param>
/// <param name="userId">Optional Id of the User deleting the Content</param>
Attempt<OperationStatus> Delete(IContent content, int userId = 0);
/// <summary>
/// Publishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>The published status attempt</returns>
Attempt<PublishStatus> Publish(IContent content, int userId = 0);
/// <summary>
/// Publishes a <see cref="IContent"/> object and all its children
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish along with its children</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <param name="includeUnpublished"></param>
/// <returns>The list of statuses for all published items</returns>
IEnumerable<Attempt<PublishStatus>> PublishWithChildren(IContent content, int userId = 0, bool includeUnpublished = false);
/// <summary>
/// Saves and Publishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to save and publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise save events.</param>
/// <returns>True if publishing succeeded, otherwise False</returns>
Attempt<PublishStatus> SaveAndPublish(IContent content, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Deletes an <see cref="IContent"/> object by moving it to the Recycle Bin
/// </summary>
/// <remarks>Move an item to the Recycle Bin will result in the item being unpublished</remarks>
/// <param name="content">The <see cref="IContent"/> to delete</param>
/// <param name="userId">Optional Id of the User deleting the Content</param>
Attempt<OperationStatus> MoveToRecycleBin(IContent content, int userId = 0);
/// <summary>
/// UnPublishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>True if unpublishing succeeded, otherwise False</returns>
Attempt<UnPublishStatus> UnPublish(IContent content, int userId = 0);
}
/// <summary>
/// Defines the ContentService, which is an easy access to operations involving <see cref="IContent"/>
/// </summary>
public interface IContentService : IService
{
/// <summary>
/// This builds the Xml document used for the XML cache
/// </summary>
/// <returns></returns>
XmlDocument BuildXmlCache();
/// <summary>
/// Rebuilds all xml content in the cmsContentXml table for all documents
/// </summary>
/// <param name="contentTypeIds">
/// Only rebuild the xml structures for the content type ids passed in, if none then rebuilds the structures
/// for all content
/// </param>
void RebuildXmlStructures(params int[] contentTypeIds);
int CountPublished(string contentTypeAlias = null);
int Count(string contentTypeAlias = null);
int CountChildren(int parentId, string contentTypeAlias = null);
int CountDescendants(int parentId, string contentTypeAlias = null);
/// <summary>
/// Used to bulk update the permissions set for a content item. This will replace all permissions
/// assigned to an entity with a list of user id & permission pairs.
/// </summary>
/// <param name="permissionSet"></param>
void ReplaceContentPermissions(EntityPermissionSet permissionSet);
/// <summary>
/// Assigns a single permission to the current content item for the specified user ids
/// </summary>
/// <param name="entity"></param>
/// <param name="permission"></param>
/// <param name="userIds"></param>
void AssignContentPermission(IContent entity, char permission, IEnumerable<int> userIds);
/// <summary>
/// Gets the list of permissions for the content item
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
IEnumerable<EntityPermission> GetPermissionsForEntity(IContent content);
bool SendToPublication(IContent content, int userId = 0);
IEnumerable<IContent> GetByIds(IEnumerable<int> ids);
/// <summary>
/// Creates an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/>
/// that this Content should based on.
/// </summary>
/// <remarks>
/// Note that using this method will simply return a new IContent without any identity
/// as it has not yet been persisted. It is intended as a shortcut to creating new content objects
/// that does not invoke a save operation against the database.
/// </remarks>
/// <param name="name">Name of the Content object</param>
/// <param name="parentId">Id of Parent for the new Content</param>
/// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param>
/// <param name="userId">Optional id of the user creating the content</param>
/// <returns><see cref="IContent"/></returns>
IContent CreateContent(string name, int parentId, string contentTypeAlias, int userId = 0);
/// <summary>
/// Creates an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/>
/// that this Content should based on.
/// </summary>
/// <remarks>
/// Note that using this method will simply return a new IContent without any identity
/// as it has not yet been persisted. It is intended as a shortcut to creating new content objects
/// that does not invoke a save operation against the database.
/// </remarks>
/// <param name="name">Name of the Content object</param>
/// <param name="parent">Parent <see cref="IContent"/> object for the new Content</param>
/// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param>
/// <param name="userId">Optional id of the user creating the content</param>
/// <returns><see cref="IContent"/></returns>
IContent CreateContent(string name, IContent parent, string contentTypeAlias, int userId = 0);
/// <summary>
/// Gets an <see cref="IContent"/> object by Id
/// </summary>
/// <param name="id">Id of the Content to retrieve</param>
/// <returns><see cref="IContent"/></returns>
IContent GetById(int id);
/// <summary>
/// Gets an <see cref="IContent"/> object by its 'UniqueId'
/// </summary>
/// <param name="key">Guid key of the Content to retrieve</param>
/// <returns><see cref="IContent"/></returns>
IContent GetById(Guid key);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by the Id of the <see cref="IContentType"/>
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/></param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetContentOfContentType(int id);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Level
/// </summary>
/// <param name="level">The level to retrieve Content from</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetByLevel(int level);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Children from</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetChildren(int id);
[Obsolete("Use the overload with 'long' parameter types instead")]
[EditorBrowsable(EditorBrowsableState.Never)]
IEnumerable<IContent> GetPagedChildren(int id, int pageIndex, int pageSize, out int totalRecords,
string orderBy = "SortOrder", Direction orderDirection = Direction.Ascending, string filter = "");
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Children from</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records query would return without paging</param>
/// <param name="orderBy">Field to order by</param>
/// <param name="orderDirection">Direction to order by</param>
/// <param name="filter">Search text filter</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetPagedChildren(int id, long pageIndex, int pageSize, out long totalRecords,
string orderBy = "SortOrder", Direction orderDirection = Direction.Ascending, string filter = "");
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Children from</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records query would return without paging</param>
/// <param name="orderBy">Field to order by</param>
/// <param name="orderDirection">Direction to order by</param>
/// <param name="orderBySystemField">Flag to indicate when ordering by system field</param>
/// <param name="filter">Search text filter</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetPagedChildren(int id, long pageIndex, int pageSize, out long totalRecords,
string orderBy, Direction orderDirection, bool orderBySystemField, string filter);
[Obsolete("Use the overload with 'long' parameter types instead")]
[EditorBrowsable(EditorBrowsableState.Never)]
IEnumerable<IContent> GetPagedDescendants(int id, int pageIndex, int pageSize, out int totalRecords,
string orderBy = "Path", Direction orderDirection = Direction.Ascending, string filter = "");
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Descendants from</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records query would return without paging</param>
/// <param name="orderBy">Field to order by</param>
/// <param name="orderDirection">Direction to order by</param>
/// <param name="filter">Search text filter</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetPagedDescendants(int id, long pageIndex, int pageSize, out long totalRecords,
string orderBy = "Path", Direction orderDirection = Direction.Ascending, string filter = "");
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Descendants from</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records query would return without paging</param>
/// <param name="orderBy">Field to order by</param>
/// <param name="orderDirection">Direction to order by</param>
/// <param name="orderBySystemField">Flag to indicate when ordering by system field</param>
/// <param name="filter">Search text filter</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetPagedDescendants(int id, long pageIndex, int pageSize, out long totalRecords,
string orderBy, Direction orderDirection, bool orderBySystemField, string filter);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Descendants from</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records query would return without paging</param>
/// <param name="orderBy">Field to order by</param>
/// <param name="orderDirection">Direction to order by</param>
/// <param name="orderBySystemField">Flag to indicate when ordering by system field</param>
/// <param name="filter"></param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetPagedDescendants(int id, long pageIndex, int pageSize, out long totalRecords,
string orderBy, Direction orderDirection, bool orderBySystemField, IQuery<IContent> filter);
/// <summary>
/// Gets a collection of an <see cref="IContent"/> objects versions by its Id
/// </summary>
/// <param name="id"></param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetVersions(int id);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects, which reside at the first level / root
/// </summary>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetRootContent();
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects, which has an expiration date greater then today
/// </summary>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetContentForExpiration();
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects, which has a release date greater then today
/// </summary>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetContentForRelease();
/// <summary>
/// Gets a collection of an <see cref="IContent"/> objects, which resides in the Recycle Bin
/// </summary>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetContentInRecycleBin();
/// <summary>
/// Saves a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to save</param>
/// <param name="userId">Optional Id of the User saving the Content</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param>
void Save(IContent content, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Saves a collection of <see cref="IContent"/> objects.
/// </summary>
/// <param name="contents">Collection of <see cref="IContent"/> to save</param>
/// <param name="userId">Optional Id of the User saving the Content</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param>
void Save(IEnumerable<IContent> contents, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Deletes all content of specified type. All children of deleted content is moved to Recycle Bin.
/// </summary>
/// <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks>
/// <param name="contentTypeId">Id of the <see cref="IContentType"/></param>
/// <param name="userId">Optional Id of the user issueing the delete operation</param>
void DeleteContentOfType(int contentTypeId, int userId = 0);
/// <summary>
/// Permanently deletes versions from an <see cref="IContent"/> object prior to a specific date.
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/> object to delete versions from</param>
/// <param name="versionDate">Latest version date</param>
/// <param name="userId">Optional Id of the User deleting versions of a Content object</param>
void DeleteVersions(int id, DateTime versionDate, int userId = 0);
/// <summary>
/// Permanently deletes a specific version from an <see cref="IContent"/> object.
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/> object to delete a version from</param>
/// <param name="versionId">Id of the version to delete</param>
/// <param name="deletePriorVersions">Boolean indicating whether to delete versions prior to the versionId</param>
/// <param name="userId">Optional Id of the User deleting versions of a Content object</param>
void DeleteVersion(int id, Guid versionId, bool deletePriorVersions, int userId = 0);
/// <summary>
/// Deletes an <see cref="IContent"/> object by moving it to the Recycle Bin
/// </summary>
/// <remarks>Move an item to the Recycle Bin will result in the item being unpublished</remarks>
/// <param name="content">The <see cref="IContent"/> to delete</param>
/// <param name="userId">Optional Id of the User deleting the Content</param>
void MoveToRecycleBin(IContent content, int userId = 0);
/// <summary>
/// Moves an <see cref="IContent"/> object to a new location
/// </summary>
/// <param name="content">The <see cref="IContent"/> to move</param>
/// <param name="parentId">Id of the Content's new Parent</param>
/// <param name="userId">Optional Id of the User moving the Content</param>
void Move(IContent content, int parentId, int userId = 0);
/// <summary>
/// Empties the Recycle Bin by deleting all <see cref="IContent"/> that resides in the bin
/// </summary>
void EmptyRecycleBin();
/// <summary>
/// Rollback an <see cref="IContent"/> object to a previous version.
/// This will create a new version, which is a copy of all the old data.
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/>being rolled back</param>
/// <param name="versionId">Id of the version to rollback to</param>
/// <param name="userId">Optional Id of the User issueing the rollback of the Content</param>
/// <returns>The newly created <see cref="IContent"/> object</returns>
IContent Rollback(int id, Guid versionId, int userId = 0);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by its name or partial name
/// </summary>
/// <param name="parentId">Id of the Parent to retrieve Children from</param>
/// <param name="name">Full or partial name of the children</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetChildrenByName(int parentId, string name);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Descendants from</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetDescendants(int id);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Parent Id
/// </summary>
/// <param name="content"><see cref="IContent"/> item to retrieve Descendants from</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetDescendants(IContent content);
/// <summary>
/// Gets a specific version of an <see cref="IContent"/> item.
/// </summary>
/// <param name="versionId">Id of the version to retrieve</param>
/// <returns>An <see cref="IContent"/> item</returns>
IContent GetByVersion(Guid versionId);
/// <summary>
/// Gets the published version of an <see cref="IContent"/> item
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/> to retrieve version from</param>
/// <returns>An <see cref="IContent"/> item</returns>
IContent GetPublishedVersion(int id);
/// <summary>
/// Gets the published version of a <see cref="IContent"/> item.
/// </summary>
/// <param name="content">The content item.</param>
/// <returns>The published version, if any; otherwise, null.</returns>
IContent GetPublishedVersion(IContent content);
/// <summary>
/// Checks whether an <see cref="IContent"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/></param>
/// <returns>True if the content has any children otherwise False</returns>
bool HasChildren(int id);
/// <summary>
/// Checks whether an <see cref="IContent"/> item has any published versions
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/></param>
/// <returns>True if the content has any published version otherwise False</returns>
bool HasPublishedVersion(int id);
/// <summary>
/// Re-Publishes all Content
/// </summary>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>True if publishing succeeded, otherwise False</returns>
bool RePublishAll(int userId = 0);
/// <summary>
/// Publishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>True if publishing succeeded, otherwise False</returns>
bool Publish(IContent content, int userId = 0);
/// <summary>
/// Publishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>The published status attempt</returns>
Attempt<PublishStatus> PublishWithStatus(IContent content, int userId = 0);
/// <summary>
/// Publishes a <see cref="IContent"/> object and all its children
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish along with its children</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>True if publishing succeeded, otherwise False</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use PublishWithChildrenWithStatus instead, that method will provide more detailed information on the outcome and also allows the includeUnpublished flag")]
bool PublishWithChildren(IContent content, int userId = 0);
/// <summary>
/// Publishes a <see cref="IContent"/> object and all its children
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish along with its children</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <param name="includeUnpublished"></param>
/// <returns>The list of statuses for all published items</returns>
IEnumerable<Attempt<PublishStatus>> PublishWithChildrenWithStatus(IContent content, int userId = 0, bool includeUnpublished = false);
/// <summary>
/// UnPublishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>True if unpublishing succeeded, otherwise False</returns>
bool UnPublish(IContent content, int userId = 0);
/// <summary>
/// Saves and Publishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to save and publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise save events.</param>
/// <returns>True if publishing succeeded, otherwise False</returns>
[Obsolete("Use SaveAndPublishWithStatus instead, that method will provide more detailed information on the outcome")]
[EditorBrowsable(EditorBrowsableState.Never)]
bool SaveAndPublish(IContent content, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Saves and Publishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to save and publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise save events.</param>
/// <returns>True if publishing succeeded, otherwise False</returns>
Attempt<PublishStatus> SaveAndPublishWithStatus(IContent content, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Permanently deletes an <see cref="IContent"/> object.
/// </summary>
/// <remarks>
/// This method will also delete associated media files, child content and possibly associated domains.
/// </remarks>
/// <remarks>Please note that this method will completely remove the Content from the database</remarks>
/// <param name="content">The <see cref="IContent"/> to delete</param>
/// <param name="userId">Optional Id of the User deleting the Content</param>
void Delete(IContent content, int userId = 0);
/// <summary>
/// Copies an <see cref="IContent"/> object by creating a new Content object of the same type and copies all data from the current
/// to the new copy, which is returned. Recursively copies all children.
/// </summary>
/// <param name="content">The <see cref="IContent"/> to copy</param>
/// <param name="parentId">Id of the Content's new Parent</param>
/// <param name="relateToOriginal">Boolean indicating whether the copy should be related to the original</param>
/// <param name="userId">Optional Id of the User copying the Content</param>
/// <returns>The newly created <see cref="IContent"/> object</returns>
IContent Copy(IContent content, int parentId, bool relateToOriginal, int userId = 0);
/// <summary>
/// Copies an <see cref="IContent"/> object by creating a new Content object of the same type and copies all data from the current
/// to the new copy which is returned.
/// </summary>
/// <param name="content">The <see cref="IContent"/> to copy</param>
/// <param name="parentId">Id of the Content's new Parent</param>
/// <param name="relateToOriginal">Boolean indicating whether the copy should be related to the original</param>
/// <param name="recursive">A value indicating whether to recursively copy children.</param>
/// <param name="userId">Optional Id of the User copying the Content</param>
/// <returns>The newly created <see cref="IContent"/> object</returns>
IContent Copy(IContent content, int parentId, bool relateToOriginal, bool recursive, int userId = 0);
/// <summary>
/// Checks if the passed in <see cref="IContent"/> can be published based on the anscestors publish state.
/// </summary>
/// <param name="content"><see cref="IContent"/> to check if anscestors are published</param>
/// <returns>True if the Content can be published, otherwise False</returns>
bool IsPublishable(IContent content);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects, which are ancestors of the current content.
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/> to retrieve ancestors for</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetAncestors(int id);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects, which are ancestors of the current content.
/// </summary>
/// <param name="content"><see cref="IContent"/> to retrieve ancestors for</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetAncestors(IContent content);
/// <summary>
/// Sorts a collection of <see cref="IContent"/> objects by updating the SortOrder according
/// to the ordering of items in the passed in <see cref="IEnumerable{T}"/>.
/// </summary>
/// <remarks>
/// Using this method will ensure that the Published-state is maintained upon sorting
/// so the cache is updated accordingly - as needed.
/// </remarks>
/// <param name="items"></param>
/// <param name="userId"></param>
/// <param name="raiseEvents"></param>
/// <returns>True if sorting succeeded, otherwise False</returns>
bool Sort(IEnumerable<IContent> items, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Gets the parent of the current content as an <see cref="IContent"/> item.
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/> to retrieve the parent from</param>
/// <returns>Parent <see cref="IContent"/> object</returns>
IContent GetParent(int id);
/// <summary>
/// Gets the parent of the current content as an <see cref="IContent"/> item.
/// </summary>
/// <param name="content"><see cref="IContent"/> to retrieve the parent from</param>
/// <returns>Parent <see cref="IContent"/> object</returns>
IContent GetParent(IContent content);
/// <summary>
/// Creates and saves an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/>
/// that this Content should based on.
/// </summary>
/// <remarks>
/// This method returns an <see cref="IContent"/> object that has been persisted to the database
/// and therefor has an identity.
/// </remarks>
/// <param name="name">Name of the Content object</param>
/// <param name="parent">Parent <see cref="IContent"/> object for the new Content</param>
/// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param>
/// <param name="userId">Optional id of the user creating the content</param>
/// <returns><see cref="IContent"/></returns>
IContent CreateContentWithIdentity(string name, IContent parent, string contentTypeAlias, int userId = 0);
/// <summary>
/// Creates and saves an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/>
/// that this Content should based on.
/// </summary>
/// <remarks>
/// This method returns an <see cref="IContent"/> object that has been persisted to the database
/// and therefor has an identity.
/// </remarks>
/// <param name="name">Name of the Content object</param>
/// <param name="parentId">Id of Parent for the new Content</param>
/// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param>
/// <param name="userId">Optional id of the user creating the content</param>
/// <returns><see cref="IContent"/></returns>
IContent CreateContentWithIdentity(string name, int parentId, string contentTypeAlias, int userId = 0);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
#if WINDOWS_APP
using Windows.UI.ApplicationSettings;
#endif
using Windows.ApplicationModel;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.ApplicationModel.Resources;
using Prism.Mvvm.Interfaces;
#if WINDOWS_PHONE_APP
using Windows.Phone.UI.Input;
#endif
namespace Prism.Mvvm
{
public abstract class MvvmAppBase : Application
{
private bool _isRestoringFromTermination;
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
protected MvvmAppBase()
{
this.Suspending += OnSuspending;
}
/// <summary>
/// Gets or sets the session state service.
/// </summary>
/// <value>
/// The session state service.
/// </value>
protected ISessionStateService SessionStateService { get; set; }
/// <summary>
/// Gets or sets the navigation service.
/// </summary>
/// <value>
/// The navigation service.
/// </value>
protected INavigationService NavigationService { get; set; }
/// <summary>
/// Factory for creating the ExtendedSplashScreen instance.
/// </summary>
/// <value>
/// The Func that creates the ExtendedSplashScreen. It requires a SplashScreen parameter,
/// and must return a Page instance.
/// </value>
protected Func<SplashScreen, Page> ExtendedSplashScreenFactory { get; set; }
/// <summary>
/// Gets a value indicating whether the application is suspending.
/// </summary>
/// <value>
/// <c>true</c> if the application is suspending; otherwise, <c>false</c>.
/// </value>
public bool IsSuspending { get; private set; }
/// <summary>
/// Override this method with logic that will be performed after the application is initialized. For example, navigating to the application's home page.
/// </summary>
/// <param name="args">The <see cref="LaunchActivatedEventArgs"/> instance containing the event data.</param>
protected abstract Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args);
/// <summary>
/// Gets the type of the page based on a page token.
/// </summary>
/// <param name="pageToken">The page token.</param>
/// <returns>The type of the page which corresponds to the specified token.</returns>
protected virtual Type GetPageType(string pageToken)
{
var assemblyQualifiedAppType = this.GetType().GetTypeInfo().AssemblyQualifiedName;
var pageNameWithParameter = assemblyQualifiedAppType.Replace(this.GetType().FullName, this.GetType().Namespace + ".Views.{0}Page");
var viewFullName = string.Format(CultureInfo.InvariantCulture, pageNameWithParameter, pageToken);
var viewType = Type.GetType(viewFullName);
if (viewType == null)
{
var resourceLoader = ResourceLoader.GetForCurrentView(PrismConstants.PrismInfrastructureResourceMapId);
throw new ArgumentException(
string.Format(CultureInfo.InvariantCulture, resourceLoader.GetString("DefaultPageTypeLookupErrorMessage"), pageToken, this.GetType().Namespace + ".Views"),
"pageToken");
}
return viewType;
}
/// <summary>
/// Used for setting up the list of known types for the SessionStateService, using the RegisterKnownType method.
/// </summary>
protected virtual void OnRegisterKnownTypesForSerialization() { }
/// <summary>
/// Override this method with the initialization logic of your application. Here you can initialize services, repositories, and so on.
/// </summary>
/// <param name="args">The <see cref="IActivatedEventArgs"/> instance containing the event data.</param>
protected virtual Task OnInitializeAsync(IActivatedEventArgs args)
{
return Task.FromResult<object>(null);
}
/// <summary>
/// Resolves the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>A concrete instance of the specified type.</returns>
protected virtual object Resolve(Type type)
{
return Activator.CreateInstance(type);
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used when the application is launched to open a specific file, to display
/// search results, and so forth.
/// </summary>
/// <param name="args">Details about the launch request and process.</param>
protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
var rootFrame = await InitializeFrameAsync(args);
// If the app is launched via the app's primary tile, the args.TileId property
// will have the same value as the AppUserModelId, which is set in the Package.appxmanifest.
// See http://go.microsoft.com/fwlink/?LinkID=288842
string tileId = AppManifestHelper.GetApplicationId();
if (rootFrame != null && (!_isRestoringFromTermination || (args != null && args.TileId != tileId)))
{
await OnLaunchApplicationAsync(args);
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Initializes the Frame and its content.
/// </summary>
/// <param name="args">The <see cref="IActivatedEventArgs"/> instance containing the event data.</param>
/// <returns>A task of a Frame that holds the app content.</returns>
protected async Task<Frame> InitializeFrameAsync(IActivatedEventArgs args)
{
var rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
if (ExtendedSplashScreenFactory != null)
{
Page extendedSplashScreen = this.ExtendedSplashScreenFactory.Invoke(args.SplashScreen);
rootFrame.Content = extendedSplashScreen;
}
var frameFacade = new FrameFacadeAdapter(rootFrame);
//Initialize MvvmAppBase common services
SessionStateService = new SessionStateService();
//Configure VisualStateAwarePage with the ability to get the session state for its frame
VisualStateAwarePage.GetSessionStateForFrame =
frame => SessionStateService.GetSessionStateForFrame(frameFacade);
//Associate the frame with a key
SessionStateService.RegisterFrame(frameFacade, "AppFrame");
NavigationService = CreateNavigationService(frameFacade, SessionStateService);
#if WINDOWS_APP
SettingsPane.GetForCurrentView().CommandsRequested += OnCommandsRequested;
#endif
#if WINDOWS_PHONE_APP
HardwareButtons.BackPressed += OnHardwareButtonsBackPressed;
#endif
// Set a factory for the ViewModelLocator to use the default resolution mechanism to construct view models
ViewModelLocationProvider.SetDefaultViewModelFactory(Resolve);
OnRegisterKnownTypesForSerialization();
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
await SessionStateService.RestoreSessionStateAsync();
}
await OnInitializeAsync(args);
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
// Restore the saved session state and navigate to the last page visited
try
{
SessionStateService.RestoreFrameState();
NavigationService.RestoreSavedNavigation();
_isRestoringFromTermination = true;
}
catch (SessionStateServiceException)
{
// Something went wrong restoring state.
// Assume there is no state and continue
}
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
return rootFrame;
}
/// <summary>
/// Creates the navigation service.
/// </summary>
/// <param name="rootFrame">The root frame.</param>
/// <param name="sessionStateService">The session state service.</param>
/// <returns>The initialized navigation service.</returns>
private INavigationService CreateNavigationService(IFrameFacade rootFrame, ISessionStateService sessionStateService)
{
var navigationService = new FrameNavigationService(rootFrame, GetPageType, sessionStateService);
return navigationService;
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private async void OnSuspending(object sender, SuspendingEventArgs e)
{
IsSuspending = true;
try
{
var deferral = e.SuspendingOperation.GetDeferral();
//Bootstrap inform navigation service that app is suspending.
NavigationService.Suspending();
// Save application state
await SessionStateService.SaveAsync();
deferral.Complete();
}
finally
{
IsSuspending = false;
}
}
#if WINDOWS_APP
/// <summary>
/// Gets the Settings charm action items.
/// </summary>
/// <returns>The list of Setting charm action items that will populate the Settings pane.</returns>
protected virtual IList<SettingsCommand> GetSettingsCommands()
{
return new List<SettingsCommand>();
}
#endif
#if WINDOWS_PHONE_APP
protected virtual void OnHardwareButtonsBackPressed(object sender, BackPressedEventArgs e)
{
if (NavigationService.CanGoBack())
{
NavigationService.GoBack();
e.Handled = true;
}
else this.Exit();
}
#endif
#if WINDOWS_APP
/// <summary>
/// Called when the Settings charm is invoked, this handler populates the Settings charm with the charm items returned by the GetSettingsCommands function.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="args">The <see cref="SettingsPaneCommandsRequestedEventArgs"/> instance containing the event data.</param>
private void OnCommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
{
if (args == null || args.Request == null || args.Request.ApplicationCommands == null)
{
return;
}
var applicationCommands = args.Request.ApplicationCommands;
var settingsCommands = GetSettingsCommands();
foreach (var settingsCommand in settingsCommands)
{
applicationCommands.Add(settingsCommand);
}
}
#endif
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Xunit;
namespace System.Threading.Tasks.Dataflow.Tests
{
public class TransformManyBlockTests
{
[Fact]
public async Task TestCtor()
{
var blocks = new[] {
new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable),
new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable, new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1 }),
new TransformManyBlock<int, int>(i => Task.Run(() => DataflowTestHelpers.ToEnumerable(i)), new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1 })
};
foreach (var block in blocks)
{
Assert.Equal(expected: 0, actual: block.InputCount);
Assert.Equal(expected: 0, actual: block.OutputCount);
Assert.False(block.Completion.IsCompleted);
}
blocks = new[] {
new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable,
new ExecutionDataflowBlockOptions { CancellationToken = new CancellationToken(true) }),
new TransformManyBlock<int, int>(i => Task.Run(() => DataflowTestHelpers.ToEnumerable(i)),
new ExecutionDataflowBlockOptions { CancellationToken = new CancellationToken(true) })
};
foreach (var block in blocks)
{
Assert.Equal(expected: 0, actual: block.InputCount);
Assert.Equal(expected: 0, actual: block.OutputCount);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => block.Completion);
}
}
[Fact]
public void TestArgumentExceptions()
{
Assert.Throws<ArgumentNullException>(() => new TransformManyBlock<int, int>((Func<int, IEnumerable<int>>)null));
Assert.Throws<ArgumentNullException>(() => new TransformManyBlock<int, int>((Func<int, Task<IEnumerable<int>>>)null));
Assert.Throws<ArgumentNullException>(() => new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable, null));
Assert.Throws<ArgumentNullException>(() => new TransformManyBlock<int, int>(i => Task.Run(() => DataflowTestHelpers.ToEnumerable(i)), null));
DataflowTestHelpers.TestArgumentsExceptions(new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable));
}
[Fact]
public void TestToString()
{
DataflowTestHelpers.TestToString(nameFormat =>
nameFormat != null ?
new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable, new ExecutionDataflowBlockOptions() { NameFormat = nameFormat }) :
new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable));
}
[Fact]
public async Task TestOfferMessage()
{
var generators = new Func<TransformManyBlock<int, int>>[]
{
() => new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable),
() => new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable, new ExecutionDataflowBlockOptions { BoundedCapacity = 10 }),
() => new TransformManyBlock<int, int>(i => Task.Run(() => DataflowTestHelpers.ToEnumerable(i)), new ExecutionDataflowBlockOptions { BoundedCapacity = 10, MaxMessagesPerTask = 1 })
};
foreach (var generator in generators)
{
DataflowTestHelpers.TestOfferMessage_ArgumentValidation(generator());
var target = generator();
DataflowTestHelpers.TestOfferMessage_AcceptsDataDirectly(target);
DataflowTestHelpers.TestOfferMessage_CompleteAndOffer(target);
target = generator();
await DataflowTestHelpers.TestOfferMessage_AcceptsViaLinking(target);
DataflowTestHelpers.TestOfferMessage_CompleteAndOffer(target);
}
}
[Fact]
public void TestPost()
{
foreach (bool bounded in DataflowTestHelpers.BooleanValues)
foreach (var tb in new[] {
new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable, new ExecutionDataflowBlockOptions { BoundedCapacity = bounded ? 1 : -1 }),
new TransformManyBlock<int, int>(i => Task.Run(() => DataflowTestHelpers.ToEnumerable(i)), new ExecutionDataflowBlockOptions { BoundedCapacity = bounded ? 1 : -1 })})
{
Assert.True(tb.Post(0));
tb.Complete();
Assert.False(tb.Post(0));
}
}
[Fact]
public Task TestCompletionTask()
{
return DataflowTestHelpers.TestCompletionTask(() => new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable));
}
[Fact]
public async Task TestLinkToOptions()
{
const int Messages = 1;
foreach (bool append in DataflowTestHelpers.BooleanValues)
foreach (var tb in new[] {
new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable),
new TransformManyBlock<int, int>(i => Task.Run(() => DataflowTestHelpers.ToEnumerable(i))) })
{
var values = new int[Messages];
var targets = new ActionBlock<int>[Messages];
for (int i = 0; i < Messages; i++)
{
int slot = i;
targets[i] = new ActionBlock<int>(item => values[slot] = item);
tb.LinkTo(targets[i], new DataflowLinkOptions { MaxMessages = 1, Append = append });
}
tb.PostRange(0, Messages);
tb.Complete();
await tb.Completion;
for (int i = 0; i < Messages; i++)
{
Assert.Equal(
expected: append ? i : Messages - i - 1,
actual: values[i]);
}
}
}
[Fact]
public async Task TestReceives()
{
for (int test = 0; test < 2; test++)
{
foreach (var tb in new[] {
new TransformManyBlock<int, int>(i => Enumerable.Repeat(i * 2, 1)),
new TransformManyBlock<int, int>(i => Task.Run(() => Enumerable.Repeat(i * 2, 1))) })
{
tb.PostRange(0, 5);
for (int i = 0; i < 5; i++)
{
Assert.Equal(expected: i * 2, actual: await tb.ReceiveAsync());
}
int item;
IList<int> items;
Assert.False(tb.TryReceive(out item));
Assert.False(tb.TryReceiveAll(out items));
}
}
}
[Fact]
public async Task TestCircularLinking()
{
const int Iters = 200;
foreach (bool sync in DataflowTestHelpers.BooleanValues)
{
var tcs = new TaskCompletionSource<bool>();
Func<int, IEnumerable<int>> body = i => {
if (i >= Iters) tcs.SetResult(true);
return Enumerable.Repeat(i + 1, 1);
};
TransformManyBlock<int, int> tb = sync ?
new TransformManyBlock<int, int>(body) :
new TransformManyBlock<int, int>(i => Task.Run(() => body(i)));
using (tb.LinkTo(tb))
{
tb.Post(0);
await tcs.Task;
tb.Complete();
}
}
}
[Fact]
public async Task TestProducerConsumer()
{
foreach (TaskScheduler scheduler in new[] { TaskScheduler.Default, new ConcurrentExclusiveSchedulerPair().ConcurrentScheduler })
foreach (int maxMessagesPerTask in new[] { DataflowBlockOptions.Unbounded, 1, 2 })
foreach (int boundedCapacity in new[] { DataflowBlockOptions.Unbounded, 1, 2 })
foreach (int dop in new[] { 1, 2 })
foreach (int elementsPerItem in new[] { 1, 3, 5 })
foreach (bool sync in DataflowTestHelpers.BooleanValues)
{
const int Messages = 50;
var options = new ExecutionDataflowBlockOptions
{
BoundedCapacity = boundedCapacity,
MaxDegreeOfParallelism = dop,
MaxMessagesPerTask = maxMessagesPerTask,
TaskScheduler = scheduler
};
TransformManyBlock<int, int> tb = sync ?
new TransformManyBlock<int, int>(i => Enumerable.Repeat(i, elementsPerItem), options) :
new TransformManyBlock<int, int>(i => Task.Run(() => Enumerable.Repeat(i, elementsPerItem)), options);
await Task.WhenAll(
Task.Run(async delegate { // consumer
int i = 0;
int processed = 0;
while (await tb.OutputAvailableAsync())
{
Assert.Equal(expected: i, actual: await tb.ReceiveAsync());
processed++;
if (processed % elementsPerItem == 0)
{
i++;
}
}
}),
Task.Run(async delegate { // producer
for (int i = 0; i < Messages; i++)
{
await tb.SendAsync(i);
}
tb.Complete();
}));
}
}
[Fact]
public async Task TestMessagePostponement()
{
const int Excess = 10;
foreach (int boundedCapacity in new[] { 1, 3 })
{
var options = new ExecutionDataflowBlockOptions { BoundedCapacity = boundedCapacity };
foreach (var tb in new[] {
new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable, options),
new TransformManyBlock<int, int>(i => Task.Run(() => DataflowTestHelpers.ToEnumerable(i)), options) })
{
var sendAsync = new Task<bool>[boundedCapacity + Excess];
for (int i = 0; i < boundedCapacity + Excess; i++)
{
sendAsync[i] = tb.SendAsync(i);
}
tb.Complete();
for (int i = 0; i < boundedCapacity; i++)
{
Assert.True(sendAsync[i].IsCompleted);
Assert.True(sendAsync[i].Result);
}
for (int i = 0; i < Excess; i++)
{
Assert.False(await sendAsync[boundedCapacity + i]);
}
}
}
}
[Fact]
public async Task TestMultipleYields()
{
const int Messages = 10;
var t = new TransformManyBlock<int, int>(i => Enumerable.Range(0, Messages));
t.Post(42);
t.Complete();
for (int i = 0; i < Messages; i++)
{
Assert.False(t.Completion.IsCompleted);
Assert.Equal(expected: i, actual: await t.ReceiveAsync());
}
await t.Completion;
}
[Fact]
public async Task TestReserveReleaseConsume()
{
var tb = new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable);
tb.Post(1);
await DataflowTestHelpers.TestReserveAndRelease(tb);
tb = new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable);
tb.Post(2);
await DataflowTestHelpers.TestReserveAndConsume(tb);
}
[Fact]
public async Task TestCountZeroAtCompletion()
{
var cts = new CancellationTokenSource();
var tb = new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable, new ExecutionDataflowBlockOptions() { CancellationToken = cts.Token });
tb.Post(1);
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => tb.Completion);
Assert.Equal(expected: 0, actual: tb.InputCount);
Assert.Equal(expected: 0, actual: tb.OutputCount);
cts = new CancellationTokenSource();
tb = new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable);
tb.Post(1);
((IDataflowBlock)tb).Fault(new InvalidOperationException());
await Assert.ThrowsAnyAsync<InvalidOperationException>(() => tb.Completion);
Assert.Equal(expected: 0, actual: tb.InputCount);
Assert.Equal(expected: 0, actual: tb.OutputCount);
}
[Fact]
public void TestInputCount()
{
foreach (bool sync in DataflowTestHelpers.BooleanValues)
{
Barrier barrier1 = new Barrier(2), barrier2 = new Barrier(2);
Func<int, IEnumerable<int>> body = item => {
barrier1.SignalAndWait();
// will test InputCount here
barrier2.SignalAndWait();
return new[] { item };
};
TransformManyBlock<int, int> tb = sync ?
new TransformManyBlock<int, int>(body) :
new TransformManyBlock<int, int>(i => Task.Run(() => body(i)));
for (int iter = 0; iter < 2; iter++)
{
tb.PostItems(1, 2);
for (int i = 1; i >= 0; i--)
{
barrier1.SignalAndWait();
Assert.Equal(expected: i, actual: tb.InputCount);
barrier2.SignalAndWait();
}
}
}
}
[Fact]
[OuterLoop] // spins waiting for a condition to be true, though it should happen very quickly
public async Task TestCount()
{
var tb = new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable);
Assert.Equal(expected: 0, actual: tb.InputCount);
Assert.Equal(expected: 0, actual: tb.OutputCount);
tb.PostRange(1, 11);
await Task.Run(() => SpinWait.SpinUntil(() => tb.OutputCount == 10));
for (int i = 10; i > 0; i--)
{
int item;
Assert.True(tb.TryReceive(out item));
Assert.Equal(expected: 11 - i, actual: item);
Assert.Equal(expected: i - 1, actual: tb.OutputCount);
}
}
[Fact]
public async Task TestChainedSendReceive()
{
foreach (bool post in DataflowTestHelpers.BooleanValues)
foreach (bool sync in DataflowTestHelpers.BooleanValues)
{
Func<TransformManyBlock<int, int>> func = sync ?
(Func<TransformManyBlock<int, int>>)(() => new TransformManyBlock<int, int>(i => new[] { i * 2 })) :
(Func<TransformManyBlock<int, int>>)(() => new TransformManyBlock<int, int>(i => Task.Run(() => Enumerable.Repeat(i * 2, 1))));
var network = DataflowTestHelpers.Chain<TransformManyBlock<int, int>, int>(4, func);
const int Iters = 10;
for (int i = 0; i < Iters; i++)
{
if (post)
{
network.Post(i);
}
else
{
await network.SendAsync(i);
}
Assert.Equal(expected: i * 16, actual: await network.ReceiveAsync());
}
}
}
[Fact]
public async Task TestSendAllThenReceive()
{
foreach (bool post in DataflowTestHelpers.BooleanValues)
foreach (bool sync in DataflowTestHelpers.BooleanValues)
{
Func<TransformManyBlock<int, int>> func = sync ?
(Func<TransformManyBlock<int, int>>)(() => new TransformManyBlock<int, int>(i => new[] { i * 2 })) :
(Func<TransformManyBlock<int, int>>)(() => new TransformManyBlock<int, int>(i => Task.Run(() => Enumerable.Repeat(i * 2, 1))));
var network = DataflowTestHelpers.Chain<TransformManyBlock<int, int>, int>(4, func);
const int Iters = 10;
if (post)
{
network.PostRange(0, Iters);
}
else
{
await Task.WhenAll(from i in Enumerable.Range(0, Iters) select network.SendAsync(i));
}
for (int i = 0; i < Iters; i++)
{
Assert.Equal(expected: i * 16, actual: await network.ReceiveAsync());
}
}
}
[Fact]
public async Task TestPrecanceled()
{
var bb = new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable,
new ExecutionDataflowBlockOptions { CancellationToken = new CancellationToken(canceled: true) });
int ignoredValue;
IList<int> ignoredValues;
IDisposable link = bb.LinkTo(DataflowBlock.NullTarget<int>());
Assert.NotNull(link);
link.Dispose();
Assert.False(bb.Post(42));
var t = bb.SendAsync(42);
Assert.True(t.IsCompleted);
Assert.False(t.Result);
Assert.False(bb.TryReceiveAll(out ignoredValues));
Assert.False(bb.TryReceive(out ignoredValue));
Assert.NotNull(bb.Completion);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => bb.Completion);
bb.Complete(); // just make sure it doesn't throw
}
[Fact]
public async Task TestExceptions()
{
var tb1 = new TransformManyBlock<int, int>((Func<int, IEnumerable<int>>)(i => { throw new InvalidCastException(); }));
var tb2 = new TransformManyBlock<int, int>((Func<int, Task<IEnumerable<int>>>)(i => { throw new InvalidProgramException(); }));
var tb3 = new TransformManyBlock<int, int>((Func<int, Task<IEnumerable<int>>>)(i => Task.Run((Func<IEnumerable<int>>)(() => { throw new InvalidTimeZoneException(); }))));
var tb4 = new TransformManyBlock<int, int>(i => ExceptionAfter(3));
var tb5 = new TransformManyBlock<int, int>(i => Task.Run(() => ExceptionAfter(3)));
for (int i = 0; i < 3; i++)
{
tb1.Post(i);
tb2.Post(i);
tb3.Post(i);
tb4.Post(i);
tb5.Post(i);
}
await Assert.ThrowsAsync<InvalidCastException>(() => tb1.Completion);
await Assert.ThrowsAsync<InvalidProgramException>(() => tb2.Completion);
await Assert.ThrowsAsync<InvalidTimeZoneException>(() => tb3.Completion);
await Assert.ThrowsAsync<FormatException>(() => tb4.Completion);
await Assert.ThrowsAsync<FormatException>(() => tb5.Completion);
Assert.All(new[] { tb1, tb2, tb3 }, tb => Assert.True(tb.InputCount == 0 && tb.OutputCount == 0));
}
private IEnumerable<int> ExceptionAfter(int iterations)
{
for (int i = 0; i < iterations; i++)
{
yield return i;
}
throw new FormatException();
}
[Fact]
public async Task TestFaultingAndCancellation()
{
foreach (bool fault in DataflowTestHelpers.BooleanValues)
{
var cts = new CancellationTokenSource();
var tb = new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable, new ExecutionDataflowBlockOptions { CancellationToken = cts.Token });
tb.PostRange(0, 4);
Assert.Equal(expected: 0, actual: await tb.ReceiveAsync());
Assert.Equal(expected: 1, actual: await tb.ReceiveAsync());
if (fault)
{
Assert.Throws<ArgumentNullException>(() => ((IDataflowBlock)tb).Fault(null));
((IDataflowBlock)tb).Fault(new InvalidCastException());
await Assert.ThrowsAsync<InvalidCastException>(() => tb.Completion);
}
else
{
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => tb.Completion);
}
Assert.Equal(expected: 0, actual: tb.InputCount);
Assert.Equal(expected: 0, actual: tb.OutputCount);
}
}
[Fact]
public async Task TestCancellationExceptionsIgnored()
{
foreach (bool sync in DataflowTestHelpers.BooleanValues)
{
Func<int, IEnumerable<int>> body = i => {
if ((i % 2) == 0) throw new OperationCanceledException();
return new[] { i };
};
TransformManyBlock<int, int> t = sync ?
new TransformManyBlock<int, int>(body) :
new TransformManyBlock<int, int>(async i => await Task.Run(() => body(i)));
t.PostRange(0, 2);
t.Complete();
for (int i = 0; i < 2; i++)
{
if ((i % 2) != 0)
{
Assert.Equal(expected: i, actual: await t.ReceiveAsync());
}
}
await t.Completion;
}
}
[Fact]
public async Task TestNullTasksIgnored()
{
foreach (int dop in new[] { DataflowBlockOptions.Unbounded, 1, 2 })
{
var tb = new TransformManyBlock<int, int>(i => {
if ((i % 2) == 0) return null;
return Task.Run(() => (IEnumerable<int>)new[] { i });
}, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop });
const int Iters = 100;
tb.PostRange(0, Iters);
tb.Complete();
for (int i = 0; i < Iters; i++)
{
if ((i % 2) != 0)
{
Assert.Equal(expected: i, actual: await tb.ReceiveAsync());
}
}
await tb.Completion;
}
}
[Fact]
public async Task TestYieldingNoResults()
{
foreach (int dop in new[] { 1, Environment.ProcessorCount })
foreach (int boundedCapacity in new[] { DataflowBlockOptions.Unbounded, 1, 2 })
{
const int Modes = 3, Iters = 100;
var tb = new TransformManyBlock<int, int>(i => {
switch (i % Modes)
{
default:
case 0:
return new List<int> { i };
case 1:
return new int[0];
case 2:
return new Collection<int> { i, i + 1 };
}
}, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop, BoundedCapacity = boundedCapacity });
var source = new BufferBlock<int>();
source.PostRange(0, Modes * Iters);
source.Complete();
source.LinkTo(tb, new DataflowLinkOptions { PropagateCompletion = true });
int received = 0;
while (await tb.OutputAvailableAsync())
{
await tb.ReceiveAsync();
received++;
}
Assert.Equal(expected: Modes * Iters, actual: received);
}
}
[Fact]
public async Task TestArrayListReusePossibleForDop1()
{
foreach (int boundedCapacity in new[] { DataflowBlockOptions.Unbounded, 2 })
foreach (bool sync in DataflowTestHelpers.BooleanValues)
{
foreach (int dop in new[] { 1, Environment.ProcessorCount })
{
var dbo = new ExecutionDataflowBlockOptions { BoundedCapacity = boundedCapacity, MaxDegreeOfParallelism = dop };
foreach (IList<int> list in new IList<int>[] { new int[1], new List<int> { 0 }, new Collection<int> { 0 } })
{
int nextExpectedValue = 1;
TransformManyBlock<int, int> transform = null;
Func<int, IEnumerable<int>> body = i => {
if (i == 100) // we're done iterating
{
transform.Complete();
return (IEnumerable<int>)null;
}
else if (dop == 1)
{
list[0] = i + 1; // reuse the list over and over, but only at dop == 1
return (IEnumerable<int>)list;
}
else if (list is int[])
{
return new int[1] { i + 1 };
}
else if (list is List<int>)
{
return new List<int>() { i + 1 };
}
else
{
return new Collection<int>() { i + 1 };
}
};
transform = sync ?
new TransformManyBlock<int, int>(body, dbo) :
new TransformManyBlock<int, int>(i => Task.Run(() => body(i)), dbo);
TransformBlock<int, int> verifier = new TransformBlock<int, int>(i => {
Assert.Equal(expected: nextExpectedValue, actual: i);
nextExpectedValue++;
return i;
});
transform.LinkTo(verifier);
verifier.LinkTo(transform);
await transform.SendAsync(0);
await transform.Completion;
}
}
}
}
[Fact]
public async Task TestOrdering()
{
const int iters = 9999;
foreach (int mmpt in new[] { DataflowBlockOptions.Unbounded, 1 })
foreach (int dop in new[] { 1, 2, DataflowBlockOptions.Unbounded })
{
var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop, MaxMessagesPerTask = mmpt };
var tb = new TransformManyBlock<int, int>(i => new[] { i, i + 1, i + 2 }, options);
for (int i = 0; i < iters; i += 3)
{
Assert.True(tb.Post(i));
}
for (int i = 0; i < iters; i++)
{
Assert.Equal(expected: i, actual: await tb.ReceiveAsync());
}
tb.Complete();
await tb.Completion;
}
}
}
}
| |
using BitmapFont = FlatRedBall.Graphics.BitmapFont;
using Cursor = FlatRedBall.Gui.Cursor;
using GuiManager = FlatRedBall.Gui.GuiManager;
// Generated Usings
using FrbDemoDuckHunt.Screens;
using FlatRedBall.Graphics;
using FlatRedBall.Math;
using FrbDemoDuckHunt.Entities;
using FlatRedBall;
using FlatRedBall.Screens;
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall.Math.Geometry;
using FlatRedBall.Graphics.Animation;
#if XNA4 || WINDOWS_8
using Color = Microsoft.Xna.Framework.Color;
#elif FRB_MDX
using Color = System.Drawing.Color;
#else
using Color = Microsoft.Xna.Framework.Graphics.Color;
#endif
#if FRB_XNA || SILVERLIGHT
using Keys = Microsoft.Xna.Framework.Input.Keys;
using Vector3 = Microsoft.Xna.Framework.Vector3;
using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D;
#endif
#if FRB_XNA && !MONODROID
using Model = Microsoft.Xna.Framework.Graphics.Model;
#endif
namespace FrbDemoDuckHunt.Entities
{
public partial class Duck : PositionedObject, IDestroyable
{
// This is made global so that static lazy-loaded content can access it.
public static string ContentManagerName
{
get;
set;
}
// Generated Fields
#if DEBUG
static bool HasBeenLoadedWithGlobalContentManager = false;
#endif
public enum VariableState
{
Uninitialized = 0, //This exists so that the first set call actually does something
Unknown = 1, //This exists so that if the entity is actually a child entity and has set a child state, you will get this
FlyRight = 2,
FlyLeft = 3,
Fall = 4,
FlyUpLeft = 5,
FlyUpRight = 6,
HitLeft = 7,
HitRight = 8,
FlyAway = 9
}
protected int mCurrentState = 0;
public VariableState CurrentState
{
get
{
if (Enum.IsDefined(typeof(VariableState), mCurrentState))
{
return (VariableState)mCurrentState;
}
else
{
return VariableState.Unknown;
}
}
set
{
mCurrentState = (int)value;
switch(CurrentState)
{
case VariableState.Uninitialized:
break;
case VariableState.Unknown:
break;
case VariableState.FlyRight:
VisibleInstanceCurrentChainName = "FlyRight";
break;
case VariableState.FlyLeft:
VisibleInstanceCurrentChainName = "FlyLeft";
break;
case VariableState.Fall:
VisibleInstanceCurrentChainName = "Fall";
break;
case VariableState.FlyUpLeft:
VisibleInstanceCurrentChainName = "FlyUpLeft";
break;
case VariableState.FlyUpRight:
VisibleInstanceCurrentChainName = "FlyUpRight";
break;
case VariableState.HitLeft:
VisibleInstanceCurrentChainName = "HitLeft";
break;
case VariableState.HitRight:
VisibleInstanceCurrentChainName = "HitRight";
break;
case VariableState.FlyAway:
VisibleInstanceCurrentChainName = "FlyAway";
break;
}
}
}
static object mLockObject = new object();
static List<string> mRegisteredUnloads = new List<string>();
static List<string> LoadedContentManagers = new List<string>();
protected static FlatRedBall.Graphics.Animation.AnimationChainList AnimationChainListFileBlack;
protected static FlatRedBall.Graphics.Animation.AnimationChainList AnimationChainListFileBlue;
protected static FlatRedBall.Graphics.Animation.AnimationChainList AnimationChainListFileRed;
private FlatRedBall.Math.Geometry.Circle mCollisionCircle;
public FlatRedBall.Math.Geometry.Circle CollisionCircle
{
get
{
return mCollisionCircle;
}
}
private FlatRedBall.Sprite VisibleInstance;
public string VisibleInstanceCurrentChainName
{
get
{
return VisibleInstance.CurrentChainName;
}
set
{
VisibleInstance.CurrentChainName = value;
}
}
public bool Visible
{
get
{
return VisibleInstance.Visible;
}
set
{
VisibleInstance.Visible = value;
}
}
public float FlyAwayY = 200f;
public float TimeHit = 0.7f;
public float FallSpeed = -100f;
public float FallPointY = -60f;
public bool IsEscaped;
public bool IsShot;
public bool SetNewPoint;
public bool HasEscaped;
public bool HasFallen;
public static float SpeedMultiplierPerLevel = 0.05f;
protected Layer LayerProvidedByContainer = null;
public Duck(string contentManagerName) :
this(contentManagerName, true)
{
}
public Duck(string contentManagerName, bool addToManagers) :
base()
{
// Don't delete this:
ContentManagerName = contentManagerName;
InitializeEntity(addToManagers);
}
protected virtual void InitializeEntity(bool addToManagers)
{
// Generated Initialize
LoadStaticContent(ContentManagerName);
mCollisionCircle = new FlatRedBall.Math.Geometry.Circle();
VisibleInstance = new FlatRedBall.Sprite();
PostInitialize();
if (addToManagers)
{
AddToManagers(null);
}
}
// Generated AddToManagers
public virtual void AddToManagers (Layer layerToAddTo)
{
LayerProvidedByContainer = layerToAddTo;
SpriteManager.AddPositionedObject(this);
AddToManagersBottomUp(layerToAddTo);
CustomInitialize();
}
public virtual void Activity()
{
// Generated Activity
CustomActivity();
// After Custom Activity
}
public virtual void Destroy()
{
// Generated Destroy
SpriteManager.RemovePositionedObject(this);
if (CollisionCircle != null)
{
CollisionCircle.Detach(); ShapeManager.Remove(CollisionCircle);
}
if (VisibleInstance != null)
{
VisibleInstance.Detach(); SpriteManager.RemoveSprite(VisibleInstance);
}
CustomDestroy();
}
// Generated Methods
public virtual void PostInitialize ()
{
bool oldShapeManagerSuppressAdd = FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue;
FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue = true;
if (mCollisionCircle.Parent == null)
{
mCollisionCircle.CopyAbsoluteToRelative();
mCollisionCircle.AttachTo(this, false);
}
CollisionCircle.Radius = 12f;
if (VisibleInstance.Parent == null)
{
VisibleInstance.CopyAbsoluteToRelative();
VisibleInstance.AttachTo(this, false);
}
VisibleInstance.PixelSize = 0.4f;
VisibleInstance.AnimationChains = AnimationChainListFileBlue;
VisibleInstance.CurrentChainName = "FlyRight";
VisibleInstance.UseAnimationRelativePosition = false;
FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue = oldShapeManagerSuppressAdd;
}
public virtual void AddToManagersBottomUp (Layer layerToAddTo)
{
// We move this back to the origin and unrotate it so that anything attached to it can just use its absolute position
float oldRotationX = RotationX;
float oldRotationY = RotationY;
float oldRotationZ = RotationZ;
float oldX = X;
float oldY = Y;
float oldZ = Z;
X = 0;
Y = 0;
Z = 0;
RotationX = 0;
RotationY = 0;
RotationZ = 0;
ShapeManager.AddToLayer(mCollisionCircle, layerToAddTo);
mCollisionCircle.Radius = 12f;
SpriteManager.AddToLayer(VisibleInstance, layerToAddTo);
VisibleInstance.PixelSize = 0.4f;
VisibleInstance.AnimationChains = AnimationChainListFileBlue;
VisibleInstance.CurrentChainName = "FlyRight";
VisibleInstance.UseAnimationRelativePosition = false;
X = oldX;
Y = oldY;
Z = oldZ;
RotationX = oldRotationX;
RotationY = oldRotationY;
RotationZ = oldRotationZ;
VisibleInstanceCurrentChainName = "FlyRight";
if (Parent == null)
{
Y = 0f;
}
else
{
RelativeY = 0f;
}
if (Parent == null)
{
X = 0f;
}
else
{
RelativeX = 0f;
}
Visible = true;
if (Parent == null)
{
Z = 0f;
}
else if (Parent is Camera)
{
RelativeZ = 0f - 40.0f;
}
else
{
RelativeZ = 0f;
}
FlyAwayY = 200f;
TimeHit = 0.7f;
FallSpeed = -100f;
FallPointY = -60f;
}
public virtual void ConvertToManuallyUpdated ()
{
this.ForceUpdateDependenciesDeep();
SpriteManager.ConvertToManuallyUpdated(this);
SpriteManager.ConvertToManuallyUpdated(VisibleInstance);
}
public static void LoadStaticContent (string contentManagerName)
{
if (string.IsNullOrEmpty(contentManagerName))
{
throw new ArgumentException("contentManagerName cannot be empty or null");
}
ContentManagerName = contentManagerName;
#if DEBUG
if (contentManagerName == FlatRedBallServices.GlobalContentManager)
{
HasBeenLoadedWithGlobalContentManager = true;
}
else if (HasBeenLoadedWithGlobalContentManager)
{
throw new Exception("This type has been loaded with a Global content manager, then loaded with a non-global. This can lead to a lot of bugs");
}
#endif
bool registerUnload = false;
if (LoadedContentManagers.Contains(contentManagerName) == false)
{
LoadedContentManagers.Add(contentManagerName);
lock (mLockObject)
{
if (!mRegisteredUnloads.Contains(ContentManagerName) && ContentManagerName != FlatRedBallServices.GlobalContentManager)
{
FlatRedBallServices.GetContentManagerByName(ContentManagerName).AddUnloadMethod("DuckStaticUnload", UnloadStaticContent);
mRegisteredUnloads.Add(ContentManagerName);
}
}
if (!FlatRedBallServices.IsLoaded<FlatRedBall.Graphics.Animation.AnimationChainList>(@"content/entities/duck/animationchainlistfileblack.achx", ContentManagerName))
{
registerUnload = true;
}
AnimationChainListFileBlack = FlatRedBallServices.Load<FlatRedBall.Graphics.Animation.AnimationChainList>(@"content/entities/duck/animationchainlistfileblack.achx", ContentManagerName);
if (!FlatRedBallServices.IsLoaded<FlatRedBall.Graphics.Animation.AnimationChainList>(@"content/entities/duck/animationchainlistfileblue.achx", ContentManagerName))
{
registerUnload = true;
}
AnimationChainListFileBlue = FlatRedBallServices.Load<FlatRedBall.Graphics.Animation.AnimationChainList>(@"content/entities/duck/animationchainlistfileblue.achx", ContentManagerName);
if (!FlatRedBallServices.IsLoaded<FlatRedBall.Graphics.Animation.AnimationChainList>(@"content/entities/duck/animationchainlistfilered.achx", ContentManagerName))
{
registerUnload = true;
}
AnimationChainListFileRed = FlatRedBallServices.Load<FlatRedBall.Graphics.Animation.AnimationChainList>(@"content/entities/duck/animationchainlistfilered.achx", ContentManagerName);
}
if (registerUnload && ContentManagerName != FlatRedBallServices.GlobalContentManager)
{
lock (mLockObject)
{
if (!mRegisteredUnloads.Contains(ContentManagerName) && ContentManagerName != FlatRedBallServices.GlobalContentManager)
{
FlatRedBallServices.GetContentManagerByName(ContentManagerName).AddUnloadMethod("DuckStaticUnload", UnloadStaticContent);
mRegisteredUnloads.Add(ContentManagerName);
}
}
}
CustomLoadStaticContent(contentManagerName);
}
public static void UnloadStaticContent ()
{
if (LoadedContentManagers.Count != 0)
{
LoadedContentManagers.RemoveAt(0);
mRegisteredUnloads.RemoveAt(0);
}
if (LoadedContentManagers.Count == 0)
{
if (AnimationChainListFileBlack != null)
{
AnimationChainListFileBlack= null;
}
if (AnimationChainListFileBlue != null)
{
AnimationChainListFileBlue= null;
}
if (AnimationChainListFileRed != null)
{
AnimationChainListFileRed= null;
}
}
}
static VariableState mLoadingState = VariableState.Uninitialized;
public static VariableState LoadingState
{
get
{
return mLoadingState;
}
set
{
mLoadingState = value;
}
}
public FlatRedBall.Instructions.Instruction InterpolateToState (VariableState stateToInterpolateTo, double secondsToTake)
{
switch(stateToInterpolateTo)
{
case VariableState.FlyRight:
break;
case VariableState.FlyLeft:
break;
case VariableState.Fall:
break;
case VariableState.FlyUpLeft:
break;
case VariableState.FlyUpRight:
break;
case VariableState.HitLeft:
break;
case VariableState.HitRight:
break;
case VariableState.FlyAway:
break;
}
var instruction = new FlatRedBall.Instructions.DelegateInstruction<VariableState>(StopStateInterpolation, stateToInterpolateTo);
instruction.TimeToExecute = FlatRedBall.TimeManager.CurrentTime + secondsToTake;
this.Instructions.Add(instruction);
return instruction;
}
public void StopStateInterpolation (VariableState stateToStop)
{
switch(stateToStop)
{
case VariableState.FlyRight:
break;
case VariableState.FlyLeft:
break;
case VariableState.Fall:
break;
case VariableState.FlyUpLeft:
break;
case VariableState.FlyUpRight:
break;
case VariableState.HitLeft:
break;
case VariableState.HitRight:
break;
case VariableState.FlyAway:
break;
}
CurrentState = stateToStop;
}
public void InterpolateBetween (VariableState firstState, VariableState secondState, float interpolationValue)
{
#if DEBUG
if (float.IsNaN(interpolationValue))
{
throw new Exception("interpolationValue cannot be NaN");
}
#endif
switch(firstState)
{
case VariableState.FlyRight:
if (interpolationValue < 1)
{
this.VisibleInstanceCurrentChainName = "FlyRight";
}
break;
case VariableState.FlyLeft:
if (interpolationValue < 1)
{
this.VisibleInstanceCurrentChainName = "FlyLeft";
}
break;
case VariableState.Fall:
if (interpolationValue < 1)
{
this.VisibleInstanceCurrentChainName = "Fall";
}
break;
case VariableState.FlyUpLeft:
if (interpolationValue < 1)
{
this.VisibleInstanceCurrentChainName = "FlyUpLeft";
}
break;
case VariableState.FlyUpRight:
if (interpolationValue < 1)
{
this.VisibleInstanceCurrentChainName = "FlyUpRight";
}
break;
case VariableState.HitLeft:
if (interpolationValue < 1)
{
this.VisibleInstanceCurrentChainName = "HitLeft";
}
break;
case VariableState.HitRight:
if (interpolationValue < 1)
{
this.VisibleInstanceCurrentChainName = "HitRight";
}
break;
case VariableState.FlyAway:
if (interpolationValue < 1)
{
this.VisibleInstanceCurrentChainName = "FlyAway";
}
break;
}
switch(secondState)
{
case VariableState.FlyRight:
if (interpolationValue >= 1)
{
this.VisibleInstanceCurrentChainName = "FlyRight";
}
break;
case VariableState.FlyLeft:
if (interpolationValue >= 1)
{
this.VisibleInstanceCurrentChainName = "FlyLeft";
}
break;
case VariableState.Fall:
if (interpolationValue >= 1)
{
this.VisibleInstanceCurrentChainName = "Fall";
}
break;
case VariableState.FlyUpLeft:
if (interpolationValue >= 1)
{
this.VisibleInstanceCurrentChainName = "FlyUpLeft";
}
break;
case VariableState.FlyUpRight:
if (interpolationValue >= 1)
{
this.VisibleInstanceCurrentChainName = "FlyUpRight";
}
break;
case VariableState.HitLeft:
if (interpolationValue >= 1)
{
this.VisibleInstanceCurrentChainName = "HitLeft";
}
break;
case VariableState.HitRight:
if (interpolationValue >= 1)
{
this.VisibleInstanceCurrentChainName = "HitRight";
}
break;
case VariableState.FlyAway:
if (interpolationValue >= 1)
{
this.VisibleInstanceCurrentChainName = "FlyAway";
}
break;
}
if (interpolationValue < 1)
{
mCurrentState = (int)firstState;
}
else
{
mCurrentState = (int)secondState;
}
}
public static void PreloadStateContent (VariableState state, string contentManagerName)
{
ContentManagerName = contentManagerName;
switch(state)
{
case VariableState.FlyRight:
{
object throwaway = "FlyRight";
}
break;
case VariableState.FlyLeft:
{
object throwaway = "FlyLeft";
}
break;
case VariableState.Fall:
{
object throwaway = "Fall";
}
break;
case VariableState.FlyUpLeft:
{
object throwaway = "FlyUpLeft";
}
break;
case VariableState.FlyUpRight:
{
object throwaway = "FlyUpRight";
}
break;
case VariableState.HitLeft:
{
object throwaway = "HitLeft";
}
break;
case VariableState.HitRight:
{
object throwaway = "HitRight";
}
break;
case VariableState.FlyAway:
{
object throwaway = "FlyAway";
}
break;
}
}
[System.Obsolete("Use GetFile instead")]
public static object GetStaticMember (string memberName)
{
switch(memberName)
{
case "AnimationChainListFileBlack":
return AnimationChainListFileBlack;
case "AnimationChainListFileBlue":
return AnimationChainListFileBlue;
case "AnimationChainListFileRed":
return AnimationChainListFileRed;
}
return null;
}
public static object GetFile (string memberName)
{
switch(memberName)
{
case "AnimationChainListFileBlack":
return AnimationChainListFileBlack;
case "AnimationChainListFileBlue":
return AnimationChainListFileBlue;
case "AnimationChainListFileRed":
return AnimationChainListFileRed;
}
return null;
}
object GetMember (string memberName)
{
switch(memberName)
{
case "AnimationChainListFileBlack":
return AnimationChainListFileBlack;
case "AnimationChainListFileBlue":
return AnimationChainListFileBlue;
case "AnimationChainListFileRed":
return AnimationChainListFileRed;
}
return null;
}
protected bool mIsPaused;
public override void Pause (FlatRedBall.Instructions.InstructionList instructions)
{
base.Pause(instructions);
mIsPaused = true;
}
public virtual void SetToIgnorePausing ()
{
FlatRedBall.Instructions.InstructionManager.IgnorePausingFor(this);
FlatRedBall.Instructions.InstructionManager.IgnorePausingFor(CollisionCircle);
FlatRedBall.Instructions.InstructionManager.IgnorePausingFor(VisibleInstance);
}
public virtual void MoveToLayer (Layer layerToMoveTo)
{
if (LayerProvidedByContainer != null)
{
LayerProvidedByContainer.Remove(VisibleInstance);
}
SpriteManager.AddToLayer(VisibleInstance, layerToMoveTo);
LayerProvidedByContainer = layerToMoveTo;
}
}
// Extra classes
public static class DuckExtensionMethods
{
}
}
| |
using System;
using System.Globalization;
using System.Xml;
using JetBrains.Annotations;
using Orchard.Comments.Models;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.Aspects;
using Orchard.Services;
using Orchard.Localization;
using Orchard.Comments.Services;
using Orchard.UI.Notify;
namespace Orchard.Comments.Drivers {
[UsedImplicitly]
public class CommentPartDriver : ContentPartDriver<CommentPart> {
private readonly IContentManager _contentManager;
private readonly IWorkContextAccessor _workContextAccessor;
private readonly IClock _clock;
private readonly ICommentService _commentService;
private readonly IOrchardServices _orchardServices;
protected override string Prefix { get { return "Comments"; } }
public Localizer T { get; set; }
public CommentPartDriver(
IContentManager contentManager,
IWorkContextAccessor workContextAccessor,
IClock clock,
ICommentService commentService,
IOrchardServices orchardServices) {
_contentManager = contentManager;
_workContextAccessor = workContextAccessor;
_clock = clock;
_commentService = commentService;
_orchardServices = orchardServices;
T = NullLocalizer.Instance;
}
protected override DriverResult Display(CommentPart part, string displayType, dynamic shapeHelper) {
return Combined(
ContentShape("Parts_Comment", () => shapeHelper.Parts_Comment()),
ContentShape("Parts_Comment_SummaryAdmin", () => shapeHelper.Parts_Comment_SummaryAdmin())
);
}
// GET
protected override DriverResult Editor(CommentPart part, dynamic shapeHelper) {
if (UI.Admin.AdminFilter.IsApplied(_workContextAccessor.GetContext().HttpContext.Request.RequestContext)) {
return ContentShape("Parts_Comment_AdminEdit",
() => shapeHelper.EditorTemplate(TemplateName: "Parts.Comment.AdminEdit", Model: part, Prefix: Prefix));
}
else {
return ContentShape("Parts_Comment_Edit",
() => shapeHelper.EditorTemplate(TemplateName: "Parts.Comment", Model: part, Prefix: Prefix));
}
}
// POST
protected override DriverResult Editor(CommentPart part, IUpdateModel updater, dynamic shapeHelper) {
updater.TryUpdateModel(part, Prefix, null, null);
var workContext = _workContextAccessor.GetContext();
// applying moderate/approve actions
var httpContext = workContext.HttpContext;
var name = httpContext.Request.Form["submit.Save"];
if (!string.IsNullOrEmpty(name) && String.Equals(name, "moderate", StringComparison.OrdinalIgnoreCase)) {
if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) {
_commentService.UnapproveComment(part.Id);
_orchardServices.Notifier.Information(T("Comment successfully moderated."));
return Editor(part, shapeHelper);
}
}
if (!string.IsNullOrEmpty(name) && String.Equals(name, "approve", StringComparison.OrdinalIgnoreCase)) {
if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't approve comment"))) {
_commentService.ApproveComment(part.Id);
_orchardServices.Notifier.Information(T("Comment approved."));
return Editor(part, shapeHelper);
}
}
if (!string.IsNullOrEmpty(name) && String.Equals(name, "delete", StringComparison.OrdinalIgnoreCase)) {
if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment"))) {
_commentService.DeleteComment(part.Id);
_orchardServices.Notifier.Information(T("Comment successfully deleted."));
return Editor(part, shapeHelper);
}
}
// if editing from the admin, don't update the owner or the status
if (!string.IsNullOrEmpty(name) && String.Equals(name, "save", StringComparison.OrdinalIgnoreCase)) {
_orchardServices.Notifier.Information(T("Comment saved."));
return Editor(part, shapeHelper);
}
part.CommentDateUtc = _clock.UtcNow;
if (!String.IsNullOrEmpty(part.SiteName) && !part.SiteName.StartsWith("http://") && !part.SiteName.StartsWith("https://")) {
part.SiteName = "http://" + part.SiteName;
}
var currentUser = workContext.CurrentUser;
part.UserName = (currentUser != null ? currentUser.UserName : null);
if (currentUser != null)
part.Author = currentUser.UserName;
else if (string.IsNullOrWhiteSpace(part.Author)) {
updater.AddModelError("Comments.Author", T("Name is mandatory"));
}
var moderateComments = workContext.CurrentSite.As<CommentSettingsPart>().ModerateComments;
part.Status = moderateComments ? CommentStatus.Pending : CommentStatus.Approved;
var commentedOn = _contentManager.Get<ICommonPart>(part.CommentedOn);
// prevent users from commenting on a closed thread by hijacking the commentedOn property
var commentsPart = commentedOn.As<CommentsPart>();
if (commentsPart == null || !commentsPart.CommentsActive) {
_orchardServices.TransactionManager.Cancel();
return Editor(part, shapeHelper);
}
if (commentedOn != null && commentedOn.Container != null) {
part.CommentedOnContainer = commentedOn.Container.ContentItem.Id;
}
commentsPart.Record.CommentPartRecords.Add(part.Record);
return Editor(part, shapeHelper);
}
protected override void Importing(CommentPart part, ContentManagement.Handlers.ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "Author", author =>
part.Record.Author = author
);
context.ImportAttribute(part.PartDefinition.Name, "SiteName", siteName =>
part.Record.SiteName = siteName
);
context.ImportAttribute(part.PartDefinition.Name, "UserName", userName =>
part.Record.UserName = userName
);
context.ImportAttribute(part.PartDefinition.Name, "Email", email =>
part.Record.Email = email
);
context.ImportAttribute(part.PartDefinition.Name, "Position", position =>
part.Record.Position = decimal.Parse(position, CultureInfo.InvariantCulture)
);
context.ImportAttribute(part.PartDefinition.Name, "Status", status =>
part.Record.Status = (CommentStatus)Enum.Parse(typeof(CommentStatus), status)
);
context.ImportAttribute(part.PartDefinition.Name, "CommentDateUtc", commentDate =>
part.Record.CommentDateUtc = XmlConvert.ToDateTime(commentDate, XmlDateTimeSerializationMode.Utc)
);
context.ImportAttribute(part.PartDefinition.Name, "CommentText", text =>
part.Record.CommentText = text
);
context.ImportAttribute(part.PartDefinition.Name, "CommentedOn", commentedOn => {
var contentItem = context.GetItemFromSession(commentedOn);
if (contentItem != null) {
part.Record.CommentedOn = contentItem.Id;
}
contentItem.As<CommentsPart>().Record.CommentPartRecords.Add(part.Record);
});
context.ImportAttribute(part.PartDefinition.Name, "RepliedOn", repliedOn => {
var contentItem = context.GetItemFromSession(repliedOn);
if (contentItem != null) {
part.Record.RepliedOn = contentItem.Id;
}
});
context.ImportAttribute(part.PartDefinition.Name, "CommentedOnContainer", commentedOnContainer => {
var container = context.GetItemFromSession(commentedOnContainer);
if (container != null) {
part.Record.CommentedOnContainer = container.Id;
}
});
}
protected override void Exporting(CommentPart part, ContentManagement.Handlers.ExportContentContext context) {
context.Element(part.PartDefinition.Name).SetAttributeValue("Author", part.Record.Author);
context.Element(part.PartDefinition.Name).SetAttributeValue("SiteName", part.Record.SiteName);
context.Element(part.PartDefinition.Name).SetAttributeValue("UserName", part.Record.UserName);
context.Element(part.PartDefinition.Name).SetAttributeValue("Email", part.Record.Email);
context.Element(part.PartDefinition.Name).SetAttributeValue("Position", part.Record.Position.ToString(CultureInfo.InvariantCulture));
context.Element(part.PartDefinition.Name).SetAttributeValue("Status", part.Record.Status.ToString());
if (part.Record.CommentDateUtc != null) {
context.Element(part.PartDefinition.Name)
.SetAttributeValue("CommentDateUtc", XmlConvert.ToString(part.Record.CommentDateUtc.Value, XmlDateTimeSerializationMode.Utc));
}
context.Element(part.PartDefinition.Name).SetAttributeValue("CommentText", part.Record.CommentText);
var commentedOn = _contentManager.Get(part.Record.CommentedOn);
if (commentedOn != null) {
var commentedOnIdentity = _contentManager.GetItemMetadata(commentedOn).Identity;
context.Element(part.PartDefinition.Name).SetAttributeValue("CommentedOn", commentedOnIdentity.ToString());
}
var commentedOnContainer = _contentManager.Get(part.Record.CommentedOnContainer);
if (commentedOnContainer != null) {
var commentedOnContainerIdentity = _contentManager.GetItemMetadata(commentedOnContainer).Identity;
context.Element(part.PartDefinition.Name).SetAttributeValue("CommentedOnContainer", commentedOnContainerIdentity.ToString());
}
if (part.Record.RepliedOn.HasValue) {
var repliedOn = _contentManager.Get(part.Record.RepliedOn.Value);
if (repliedOn != null) {
var repliedOnIdentity = _contentManager.GetItemMetadata(repliedOn).Identity;
context.Element(part.PartDefinition.Name).SetAttributeValue("RepliedOn", repliedOnIdentity.ToString());
}
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gcgv = Google.Cloud.Gaming.V1Beta;
using sys = System;
namespace Google.Cloud.Gaming.V1Beta
{
/// <summary>Resource name for the <c>GameServerDeployment</c> resource.</summary>
public sealed partial class GameServerDeploymentName : gax::IResourceName, sys::IEquatable<GameServerDeploymentName>
{
/// <summary>The possible contents of <see cref="GameServerDeploymentName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>.
/// </summary>
ProjectLocationDeployment = 1,
}
private static gax::PathTemplate s_projectLocationDeployment = new gax::PathTemplate("projects/{project}/locations/{location}/gameServerDeployments/{deployment}");
/// <summary>Creates a <see cref="GameServerDeploymentName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="GameServerDeploymentName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static GameServerDeploymentName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new GameServerDeploymentName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="GameServerDeploymentName"/> with the pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="GameServerDeploymentName"/> constructed from the provided ids.
/// </returns>
public static GameServerDeploymentName FromProjectLocationDeployment(string projectId, string locationId, string deploymentId) =>
new GameServerDeploymentName(ResourceNameType.ProjectLocationDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="GameServerDeploymentName"/> with pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="GameServerDeploymentName"/> with pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string deploymentId) =>
FormatProjectLocationDeployment(projectId, locationId, deploymentId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="GameServerDeploymentName"/> with pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="GameServerDeploymentName"/> with pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>.
/// </returns>
public static string FormatProjectLocationDeployment(string projectId, string locationId, string deploymentId) =>
s_projectLocationDeployment.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="GameServerDeploymentName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="gameServerDeploymentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="GameServerDeploymentName"/> if successful.</returns>
public static GameServerDeploymentName Parse(string gameServerDeploymentName) =>
Parse(gameServerDeploymentName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="GameServerDeploymentName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="gameServerDeploymentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="GameServerDeploymentName"/> if successful.</returns>
public static GameServerDeploymentName Parse(string gameServerDeploymentName, bool allowUnparsed) =>
TryParse(gameServerDeploymentName, allowUnparsed, out GameServerDeploymentName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="GameServerDeploymentName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="gameServerDeploymentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="GameServerDeploymentName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string gameServerDeploymentName, out GameServerDeploymentName result) =>
TryParse(gameServerDeploymentName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="GameServerDeploymentName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="gameServerDeploymentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="GameServerDeploymentName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string gameServerDeploymentName, bool allowUnparsed, out GameServerDeploymentName result)
{
gax::GaxPreconditions.CheckNotNull(gameServerDeploymentName, nameof(gameServerDeploymentName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationDeployment.TryParseName(gameServerDeploymentName, out resourceName))
{
result = FromProjectLocationDeployment(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(gameServerDeploymentName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private GameServerDeploymentName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string deploymentId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
DeploymentId = deploymentId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="GameServerDeploymentName"/> class from the component parts of
/// pattern <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
public GameServerDeploymentName(string projectId, string locationId, string deploymentId) : this(ResourceNameType.ProjectLocationDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Deployment</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string DeploymentId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationDeployment: return s_projectLocationDeployment.Expand(ProjectId, LocationId, DeploymentId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as GameServerDeploymentName);
/// <inheritdoc/>
public bool Equals(GameServerDeploymentName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(GameServerDeploymentName a, GameServerDeploymentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(GameServerDeploymentName a, GameServerDeploymentName b) => !(a == b);
}
/// <summary>Resource name for the <c>GameServerDeploymentRollout</c> resource.</summary>
public sealed partial class GameServerDeploymentRolloutName : gax::IResourceName, sys::IEquatable<GameServerDeploymentRolloutName>
{
/// <summary>The possible contents of <see cref="GameServerDeploymentRolloutName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>.
/// </summary>
ProjectLocationDeployment = 1,
}
private static gax::PathTemplate s_projectLocationDeployment = new gax::PathTemplate("projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout");
/// <summary>
/// Creates a <see cref="GameServerDeploymentRolloutName"/> containing an unparsed resource name.
/// </summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="GameServerDeploymentRolloutName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static GameServerDeploymentRolloutName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new GameServerDeploymentRolloutName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="GameServerDeploymentRolloutName"/> with the pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="GameServerDeploymentRolloutName"/> constructed from the provided ids.
/// </returns>
public static GameServerDeploymentRolloutName FromProjectLocationDeployment(string projectId, string locationId, string deploymentId) =>
new GameServerDeploymentRolloutName(ResourceNameType.ProjectLocationDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="GameServerDeploymentRolloutName"/> with
/// pattern <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="GameServerDeploymentRolloutName"/> with pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>.
/// </returns>
public static string Format(string projectId, string locationId, string deploymentId) =>
FormatProjectLocationDeployment(projectId, locationId, deploymentId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="GameServerDeploymentRolloutName"/> with
/// pattern <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="GameServerDeploymentRolloutName"/> with pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>.
/// </returns>
public static string FormatProjectLocationDeployment(string projectId, string locationId, string deploymentId) =>
s_projectLocationDeployment.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="GameServerDeploymentRolloutName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="gameServerDeploymentRolloutName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <returns>The parsed <see cref="GameServerDeploymentRolloutName"/> if successful.</returns>
public static GameServerDeploymentRolloutName Parse(string gameServerDeploymentRolloutName) =>
Parse(gameServerDeploymentRolloutName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="GameServerDeploymentRolloutName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="gameServerDeploymentRolloutName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="GameServerDeploymentRolloutName"/> if successful.</returns>
public static GameServerDeploymentRolloutName Parse(string gameServerDeploymentRolloutName, bool allowUnparsed) =>
TryParse(gameServerDeploymentRolloutName, allowUnparsed, out GameServerDeploymentRolloutName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="GameServerDeploymentRolloutName"/>
/// instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="gameServerDeploymentRolloutName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="GameServerDeploymentRolloutName"/>, or <c>null</c> if
/// parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string gameServerDeploymentRolloutName, out GameServerDeploymentRolloutName result) =>
TryParse(gameServerDeploymentRolloutName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="GameServerDeploymentRolloutName"/>
/// instance; optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="gameServerDeploymentRolloutName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="GameServerDeploymentRolloutName"/>, or <c>null</c> if
/// parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string gameServerDeploymentRolloutName, bool allowUnparsed, out GameServerDeploymentRolloutName result)
{
gax::GaxPreconditions.CheckNotNull(gameServerDeploymentRolloutName, nameof(gameServerDeploymentRolloutName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationDeployment.TryParseName(gameServerDeploymentRolloutName, out resourceName))
{
result = FromProjectLocationDeployment(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(gameServerDeploymentRolloutName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private GameServerDeploymentRolloutName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string deploymentId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
DeploymentId = deploymentId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="GameServerDeploymentRolloutName"/> class from the component parts
/// of pattern <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
public GameServerDeploymentRolloutName(string projectId, string locationId, string deploymentId) : this(ResourceNameType.ProjectLocationDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Deployment</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string DeploymentId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationDeployment: return s_projectLocationDeployment.Expand(ProjectId, LocationId, DeploymentId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as GameServerDeploymentRolloutName);
/// <inheritdoc/>
public bool Equals(GameServerDeploymentRolloutName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(GameServerDeploymentRolloutName a, GameServerDeploymentRolloutName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(GameServerDeploymentRolloutName a, GameServerDeploymentRolloutName b) => !(a == b);
}
public partial class ListGameServerDeploymentsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetGameServerDeploymentRequest
{
/// <summary>
/// <see cref="gcgv::GameServerDeploymentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::GameServerDeploymentName GameServerDeploymentName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::GameServerDeploymentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetGameServerDeploymentRolloutRequest
{
/// <summary>
/// <see cref="gcgv::GameServerDeploymentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::GameServerDeploymentName GameServerDeploymentName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::GameServerDeploymentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateGameServerDeploymentRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteGameServerDeploymentRequest
{
/// <summary>
/// <see cref="gcgv::GameServerDeploymentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::GameServerDeploymentName GameServerDeploymentName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::GameServerDeploymentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GameServerDeployment
{
/// <summary>
/// <see cref="gcgv::GameServerDeploymentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::GameServerDeploymentName GameServerDeploymentName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::GameServerDeploymentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GameServerDeploymentRollout
{
/// <summary>
/// <see cref="gcgv::GameServerDeploymentRolloutName"/>-typed view over the <see cref="Name"/> resource name
/// property.
/// </summary>
public gcgv::GameServerDeploymentRolloutName GameServerDeploymentRolloutName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::GameServerDeploymentRolloutName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Mike Gorse <mgorse@novell.com>
//
using System;
using System.Collections.Generic;
using NDesk.DBus;
using org.freedesktop.DBus;
namespace Atspi
{
public class Application : IDisposable
{
internal const string SPI_PATH_ROOT = "/org/a11y/atspi/accessible/root";
internal const string SPI_PATH_NULL = "/org/a11y/atspi/null";
internal string name;
private ICache proxy;
private Properties properties;
protected Dictionary<string, Accessible> accessibles;
public bool Disposed {
get; private set;
}
private const string IFACE = "org.a11y.atspi.Application";
internal Application (string name)
{
this.name = name;
accessibles = new Dictionary<string, Accessible> ();
accessibles [SPI_PATH_NULL] = null;
}
internal void PostInit ()
{
if (Registry.SuspendDBusCalls) {
Registry.pendingCalls.Enqueue (() =>
PostInit ());
return;
}
proxy = Registry.Bus.GetObject<ICache> (name, new ObjectPath ("/org/a11y/atspi/cache"));
proxy.AddAccessible += OnAddAccessible;
proxy.RemoveAccessible += OnRemoveAccessible;
ObjectPath op = new ObjectPath (SPI_PATH_ROOT);
properties = Registry.Bus.GetObject<Properties> (name, op);
if (!(this is Registry)) {
AccessibleProxy [] elements;
try {
elements = proxy.GetItems ();
} catch (System.Exception) {
return;
}
AddAccessibles (elements);
}
}
public void Dispose ()
{
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
if (Disposed)
return;
if (proxy != null) {
proxy.RemoveAccessible -= OnRemoveAccessible;
proxy.AddAccessible -= OnAddAccessible;
}
Disposed = true;
foreach (Accessible a in accessibles.Values)
if (a != null)
a.Dispose ();
}
void AddAccessibles (AccessibleProxy [] elements)
{
foreach (AccessibleProxy e in elements)
GetElement (e);
}
Accessible GetElement (AccessibleProxy e)
{
Accessible obj = GetElement (e.path.path, true);
obj.Update (e);
return obj;
}
void OnAddAccessible (AccessibleProxy nodeAdded)
{
GetElement (nodeAdded);
}
void OnRemoveAccessible (ObjectPath nodeRemoved)
{
Accessible a = GetElement (nodeRemoved);
if (a != null)
a.Dispose ();
}
internal Accessible GetElement (string path, bool create)
{
Accessible obj;
if (accessibles.TryGetValue (path, out obj))
return obj;
if (!create)
return null;
obj = new Accessible (this, path);
accessibles [path] = obj;
// Events must be initialized after insertion into
// hash, since we need to gracefully handle reentrancy
obj.InitEvents ();
return obj;
}
internal Accessible GetElement (ObjectPath op)
{
return GetElement (op, false);
}
internal Accessible GetElement (ObjectPath op, bool create)
{
return GetElement (op.ToString (), create);
}
internal string Name {
get { return name; }
}
internal Accessible Root {
get {
return GetElement ("/org/a11y/atspi/accessible/root", true);
}
}
public string ToolkitName {
get {
return (string) properties.Get (IFACE, "ToolkitName");
}
}
public uint Pid {
get {
return Registry.BusProxy.GetConnectionUnixProcessID (name);
}
}
}
[Interface ("org.a11y.atspi.Cache")]
interface ICache : Introspectable
{
AccessibleProxy [] GetItems ();
event AddAccessibleHandler AddAccessible;
event RemoveAccessibleHandler RemoveAccessible;
}
delegate void AddAccessibleHandler (AccessibleProxy nodeAdded);
delegate void RemoveAccessibleHandler (ObjectPath nodeRemoved);
internal struct AccessiblePath
{
internal string bus_name;
internal ObjectPath path;
}
struct AccessibleProxy
{
public AccessiblePath path;
public AccessiblePath app_root;
public AccessiblePath parent;
public AccessiblePath [] children;
public string [] interfaces;
public string name;
public uint role;
public string description;
public uint [] states; // 2 32-bit flags
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.SqlDatabase.Database.Cmdlet
{
using System;
using System.Globalization;
using System.Management.Automation;
using Microsoft.WindowsAzure.Management.SqlDatabase.Properties;
using Microsoft.WindowsAzure.Management.SqlDatabase.Services.Common;
using Microsoft.WindowsAzure.Management.SqlDatabase.Services.Server;
using Microsoft.WindowsAzure.Management.Utilities.Common;
/// <summary>
/// Update settings for an existing Windows Azure SQL Database in the given server context.
/// </summary>
[Cmdlet(VerbsCommon.Set, "AzureSqlDatabase", SupportsShouldProcess = true,
ConfirmImpact = ConfirmImpact.Medium)]
public class SetAzureSqlDatabase : PSCmdlet
{
#region Parameter sets
/// <summary>
/// Parameter set name for updating by name with a connection context
/// </summary>
internal const string ByNameWithConnectionContext =
"ByNameWithConnectionContext";
/// <summary>
/// Parameter set name for updating by name using azure subscription
/// </summary>
internal const string ByNameWithServerName =
"ByNameWithServerName";
/// <summary>
/// Parameter set name for updating by input object with a connection context
/// </summary>
internal const string ByObjectWithConnectionContext =
"ByObjectWithConnectionContext";
/// <summary>
/// Parameter set name for updating by input object with a azure subscription
/// </summary>
internal const string ByObjectWithServerName =
"ByObjectWithServerName";
#endregion
#region Parameters
/// <summary>
/// Gets or sets the server connection context.
/// </summary>
[Alias("Context")]
[Parameter(Mandatory = true, Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = ByNameWithConnectionContext,
HelpMessage = "The connection context to the specified server.")]
[Parameter(Mandatory = true, Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = ByObjectWithConnectionContext,
HelpMessage = "The connection context to the specified server.")]
[ValidateNotNull]
public IServerDataServiceContext ConnectionContext { get; set; }
/// <summary>
/// Gets or sets the name of the server to connect to
/// </summary>
[Parameter(Mandatory = true, Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = ByNameWithServerName,
HelpMessage = "The name of the server to connect to")]
[Parameter(Mandatory = true, Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = ByObjectWithServerName,
HelpMessage = "The name of the server to connect to")]
[ValidateNotNullOrEmpty]
public string ServerName { get; set; }
/// <summary>
/// Gets or sets the database.
/// </summary>
[Parameter(Mandatory = true, Position = 1,
ParameterSetName = ByObjectWithConnectionContext,
ValueFromPipeline = true)]
[Parameter(Mandatory = true, Position = 1,
ParameterSetName = ByObjectWithServerName,
ValueFromPipeline = true)]
[ValidateNotNull]
public Database Database { get; set; }
/// <summary>
/// Gets or sets the database name.
/// </summary>
[Parameter(Mandatory = true, Position = 1,
ParameterSetName = ByNameWithConnectionContext)]
[Parameter(Mandatory = true, Position = 1,
ParameterSetName = ByNameWithServerName)]
[ValidateNotNullOrEmpty]
public string DatabaseName { get; set; }
/// <summary>
/// Gets or sets the new name for the database.
/// </summary>
[Alias("NewName")]
[Parameter(Mandatory = false, HelpMessage = "The new name for the database.")]
[ValidateNotNullOrEmpty]
public string NewDatabaseName { get; set; }
/// <summary>
/// Gets or sets the new Edition value for the database.
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "The new edition for the database.")]
public DatabaseEdition Edition { get; set; }
/// <summary>
/// Gets or sets the new maximum size for the database in GB.
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "The new maximum size for the database in GB.")]
public int MaxSizeGB { get; set; }
/// <summary>
/// Gets or sets the new ServiceObjective for this database.
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "The new ServiceObjective for the database.")]
[ValidateNotNull]
public ServiceObjective ServiceObjective { get; set; }
/// <summary>
/// Gets or sets the switch to output the target object to the pipeline.
/// </summary>
[Parameter(HelpMessage = "Pass through the input object to the output pipeline")]
public SwitchParameter PassThru { get; set; }
/// <summary>
/// Gets or sets the switch to not confirm on the altering of the database.
/// </summary>
[Parameter(HelpMessage = "Do not confirm on the altering of the database")]
public SwitchParameter Force { get; set; }
#endregion
/// <summary>
/// Process the command.
/// </summary>
protected override void ProcessRecord()
{
// Obtain the database name from the given parameters.
string databaseName = null;
if (this.MyInvocation.BoundParameters.ContainsKey("Database"))
{
databaseName = this.Database.Name;
}
else if (this.MyInvocation.BoundParameters.ContainsKey("DatabaseName"))
{
databaseName = this.DatabaseName;
}
// Obtain the name of the server
string serverName = null;
if (this.MyInvocation.BoundParameters.ContainsKey("ServerName"))
{
serverName = this.ServerName;
}
else
{
serverName = this.ConnectionContext.ServerName;
}
// Determine the max size of the db
int? maxSizeGb = null;
if (this.MyInvocation.BoundParameters.ContainsKey("MaxSizeGB"))
{
maxSizeGb = this.MaxSizeGB;
}
// Determine the edition for the db
DatabaseEdition? edition = null;
if (this.MyInvocation.BoundParameters.ContainsKey("Edition"))
{
edition = this.Edition;
}
string actionDescription = string.Format(
CultureInfo.InvariantCulture,
Resources.SetAzureSqlDatabaseDescription,
serverName,
databaseName);
string actionWarning = string.Format(
CultureInfo.InvariantCulture,
Resources.SetAzureSqlDatabaseWarning,
serverName,
databaseName);
this.WriteVerbose(actionDescription);
// Do nothing if force is not specified and user cancelled the operation
if (!this.Force.IsPresent &&
!this.ShouldProcess(actionDescription, actionWarning, Resources.ShouldProcessCaption))
{
return;
}
// If service objective is specified, ask the user to confirm the change
if (!this.Force.IsPresent &&
this.ServiceObjective != null)
{
string serviceObjectiveWarning = string.Format(
CultureInfo.InvariantCulture,
Resources.SetAzureSqlDatabaseServiceObjectiveWarning,
this.ConnectionContext.ServerName,
databaseName);
if (!this.ShouldContinue(
serviceObjectiveWarning,
Resources.ShouldProcessCaption))
{
return;
}
}
switch (this.ParameterSetName)
{
case ByNameWithConnectionContext:
case ByObjectWithConnectionContext:
this.ProcessWithConnectionContext(databaseName, maxSizeGb, edition);
break;
case ByNameWithServerName:
case ByObjectWithServerName:
this.ProcessWithServerName(databaseName, maxSizeGb, edition);
break;
}
}
/// <summary>
/// Process the request using a temporary connection context using certificate authentication
/// </summary>
/// <param name="databaseName">The name of the database to update</param>
/// <param name="maxSizeGb">the new size for the database or null</param>
/// <param name="edition">the new edition for the database or null</param>
private void ProcessWithServerName(string databaseName, int? maxSizeGb, DatabaseEdition? edition)
{
string clientRequestId = null;
try
{
// Get the current subscription data.
SubscriptionData subscriptionData = this.GetCurrentSubscription();
// Create a temporary context
ServerDataServiceCertAuth context =
ServerDataServiceCertAuth.Create(this.ServerName, subscriptionData);
clientRequestId = context.ClientRequestId;
// Remove the database with the specified name
Database database = context.UpdateDatabase(
databaseName,
this.NewDatabaseName,
maxSizeGb,
edition,
this.ServiceObjective);
// If PassThru was specified, write back the updated object to the pipeline
if (this.PassThru.IsPresent)
{
this.WriteObject(database);
}
if (this.MyInvocation.BoundParameters.ContainsKey("Database"))
{
this.Database.CopyFields(database);
}
}
catch (Exception ex)
{
SqlDatabaseExceptionHandler.WriteErrorDetails(
this,
clientRequestId,
ex);
}
}
/// <summary>
/// process the request using the connection context.
/// </summary>
/// <param name="databaseName">the name of the database to alter</param>
/// <param name="maxSizeGb">the new maximum size for the database</param>
/// <param name="edition">the new edition for the database</param>
private void ProcessWithConnectionContext(string databaseName, int? maxSizeGb, DatabaseEdition? edition)
{
try
{
// Update the database with the specified name
Database database = this.ConnectionContext.UpdateDatabase(
databaseName,
this.NewDatabaseName,
maxSizeGb,
edition,
this.ServiceObjective);
// If PassThru was specified, write back the updated object to the pipeline
if (this.PassThru.IsPresent)
{
this.WriteObject(database);
}
if (this.ConnectionContext.GetType() == typeof(ServerDataServiceCertAuth))
{
if (this.MyInvocation.BoundParameters.ContainsKey("Database"))
{
this.Database.CopyFields(database);
}
}
}
catch (Exception ex)
{
SqlDatabaseExceptionHandler.WriteErrorDetails(
this,
this.ConnectionContext.ClientRequestId,
ex);
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.IO;
using System.Globalization;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Xml;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System.Text;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Diagnostics.CodeAnalysis;
#if HAVE_XLINQ
using System.Xml.Linq;
#endif
namespace Newtonsoft.Json
{
/// <summary>
/// Provides methods for converting between .NET types and JSON types.
/// </summary>
/// <example>
/// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\SerializationTests.cs" region="SerializeObject" title="Serializing and Deserializing JSON with JsonConvert" />
/// </example>
public static class JsonConvert
{
/// <summary>
/// Gets or sets a function that creates default <see cref="JsonSerializerSettings"/>.
/// Default settings are automatically used by serialization methods on <see cref="JsonConvert"/>,
/// and <see cref="JToken.ToObject{T}()"/> and <see cref="JToken.FromObject(object)"/> on <see cref="JToken"/>.
/// To serialize without using any default settings create a <see cref="JsonSerializer"/> with
/// <see cref="JsonSerializer.Create()"/>.
/// </summary>
public static Func<JsonSerializerSettings>? DefaultSettings { get; set; }
/// <summary>
/// Represents JavaScript's boolean value <c>true</c> as a string. This field is read-only.
/// </summary>
public static readonly string True = "true";
/// <summary>
/// Represents JavaScript's boolean value <c>false</c> as a string. This field is read-only.
/// </summary>
public static readonly string False = "false";
/// <summary>
/// Represents JavaScript's <c>null</c> as a string. This field is read-only.
/// </summary>
public static readonly string Null = "null";
/// <summary>
/// Represents JavaScript's <c>undefined</c> as a string. This field is read-only.
/// </summary>
public static readonly string Undefined = "undefined";
/// <summary>
/// Represents JavaScript's positive infinity as a string. This field is read-only.
/// </summary>
public static readonly string PositiveInfinity = "Infinity";
/// <summary>
/// Represents JavaScript's negative infinity as a string. This field is read-only.
/// </summary>
public static readonly string NegativeInfinity = "-Infinity";
/// <summary>
/// Represents JavaScript's <c>NaN</c> as a string. This field is read-only.
/// </summary>
public static readonly string NaN = "NaN";
/// <summary>
/// Converts the <see cref="DateTime"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
public static string ToString(DateTime value)
{
return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
}
/// <summary>
/// Converts the <see cref="DateTime"/> to its JSON string representation using the <see cref="DateFormatHandling"/> specified.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="format">The format the date will be converted to.</param>
/// <param name="timeZoneHandling">The time zone handling when the date is converted to a string.</param>
/// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
{
DateTime updatedDateTime = DateTimeUtils.EnsureDateTime(value, timeZoneHandling);
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
writer.Write('"');
DateTimeUtils.WriteDateTimeString(writer, updatedDateTime, format, null, CultureInfo.InvariantCulture);
writer.Write('"');
return writer.ToString();
}
}
#if HAVE_DATE_TIME_OFFSET
/// <summary>
/// Converts the <see cref="DateTimeOffset"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns>
public static string ToString(DateTimeOffset value)
{
return ToString(value, DateFormatHandling.IsoDateFormat);
}
/// <summary>
/// Converts the <see cref="DateTimeOffset"/> to its JSON string representation using the <see cref="DateFormatHandling"/> specified.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="format">The format the date will be converted to.</param>
/// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns>
public static string ToString(DateTimeOffset value, DateFormatHandling format)
{
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
writer.Write('"');
DateTimeUtils.WriteDateTimeOffsetString(writer, value, format, null, CultureInfo.InvariantCulture);
writer.Write('"');
return writer.ToString();
}
}
#endif
/// <summary>
/// Converts the <see cref="Boolean"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Boolean"/>.</returns>
public static string ToString(bool value)
{
return (value) ? True : False;
}
/// <summary>
/// Converts the <see cref="Char"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Char"/>.</returns>
public static string ToString(char value)
{
return ToString(char.ToString(value));
}
/// <summary>
/// Converts the <see cref="Enum"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Enum"/>.</returns>
public static string ToString(Enum value)
{
return value.ToString("D");
}
/// <summary>
/// Converts the <see cref="Int32"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int32"/>.</returns>
public static string ToString(int value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int16"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int16"/>.</returns>
public static string ToString(short value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt16"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt16"/>.</returns>
[CLSCompliant(false)]
public static string ToString(ushort value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt32"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt32"/>.</returns>
[CLSCompliant(false)]
public static string ToString(uint value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int64"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int64"/>.</returns>
public static string ToString(long value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
#if HAVE_BIG_INTEGER
private static string ToStringInternal(BigInteger value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
#endif
/// <summary>
/// Converts the <see cref="UInt64"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt64"/>.</returns>
[CLSCompliant(false)]
public static string ToString(ulong value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Single"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Single"/>.</returns>
public static string ToString(float value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
}
private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
if (floatFormatHandling == FloatFormatHandling.Symbol || !(double.IsInfinity(value) || double.IsNaN(value)))
{
return text;
}
if (floatFormatHandling == FloatFormatHandling.DefaultValue)
{
return (!nullable) ? "0.0" : Null;
}
return quoteChar + text + quoteChar;
}
/// <summary>
/// Converts the <see cref="Double"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Double"/>.</returns>
public static string ToString(double value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
}
private static string EnsureDecimalPlace(double value, string text)
{
if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1)
{
return text;
}
return text + ".0";
}
private static string EnsureDecimalPlace(string text)
{
if (text.IndexOf('.') != -1)
{
return text;
}
return text + ".0";
}
/// <summary>
/// Converts the <see cref="Byte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Byte"/>.</returns>
public static string ToString(byte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="SByte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
[CLSCompliant(false)]
public static string ToString(sbyte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Decimal"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Decimal"/>.</returns>
public static string ToString(decimal value)
{
return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
}
/// <summary>
/// Converts the <see cref="Guid"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Guid"/>.</returns>
public static string ToString(Guid value)
{
return ToString(value, '"');
}
internal static string ToString(Guid value, char quoteChar)
{
string text;
string qc;
#if HAVE_CHAR_TO_STRING_WITH_CULTURE
text = value.ToString("D", CultureInfo.InvariantCulture);
qc = quoteChar.ToString(CultureInfo.InvariantCulture);
#else
text = value.ToString("D");
qc = quoteChar.ToString();
#endif
return qc + text + qc;
}
/// <summary>
/// Converts the <see cref="TimeSpan"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="TimeSpan"/>.</returns>
public static string ToString(TimeSpan value)
{
return ToString(value, '"');
}
internal static string ToString(TimeSpan value, char quoteChar)
{
return ToString(value.ToString(), quoteChar);
}
/// <summary>
/// Converts the <see cref="Uri"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Uri"/>.</returns>
public static string ToString(Uri? value)
{
if (value == null)
{
return Null;
}
return ToString(value, '"');
}
internal static string ToString(Uri value, char quoteChar)
{
return ToString(value.OriginalString, quoteChar);
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string? value)
{
return ToString(value, '"');
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="delimiter">The string delimiter character.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string? value, char delimiter)
{
return ToString(value, delimiter, StringEscapeHandling.Default);
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="delimiter">The string delimiter character.</param>
/// <param name="stringEscapeHandling">The string escape handling.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string? value, char delimiter, StringEscapeHandling stringEscapeHandling)
{
if (delimiter != '"' && delimiter != '\'')
{
throw new ArgumentException("Delimiter must be a single or double quote.", nameof(delimiter));
}
return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, true, stringEscapeHandling);
}
/// <summary>
/// Converts the <see cref="Object"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Object"/>.</returns>
public static string ToString(object? value)
{
if (value == null)
{
return Null;
}
PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(value.GetType());
switch (typeCode)
{
case PrimitiveTypeCode.String:
return ToString((string)value);
case PrimitiveTypeCode.Char:
return ToString((char)value);
case PrimitiveTypeCode.Boolean:
return ToString((bool)value);
case PrimitiveTypeCode.SByte:
return ToString((sbyte)value);
case PrimitiveTypeCode.Int16:
return ToString((short)value);
case PrimitiveTypeCode.UInt16:
return ToString((ushort)value);
case PrimitiveTypeCode.Int32:
return ToString((int)value);
case PrimitiveTypeCode.Byte:
return ToString((byte)value);
case PrimitiveTypeCode.UInt32:
return ToString((uint)value);
case PrimitiveTypeCode.Int64:
return ToString((long)value);
case PrimitiveTypeCode.UInt64:
return ToString((ulong)value);
case PrimitiveTypeCode.Single:
return ToString((float)value);
case PrimitiveTypeCode.Double:
return ToString((double)value);
case PrimitiveTypeCode.DateTime:
return ToString((DateTime)value);
case PrimitiveTypeCode.Decimal:
return ToString((decimal)value);
#if HAVE_DB_NULL_TYPE_CODE
case PrimitiveTypeCode.DBNull:
return Null;
#endif
#if HAVE_DATE_TIME_OFFSET
case PrimitiveTypeCode.DateTimeOffset:
return ToString((DateTimeOffset)value);
#endif
case PrimitiveTypeCode.Guid:
return ToString((Guid)value);
case PrimitiveTypeCode.Uri:
return ToString((Uri)value);
case PrimitiveTypeCode.TimeSpan:
return ToString((TimeSpan)value);
#if HAVE_BIG_INTEGER
case PrimitiveTypeCode.BigInteger:
return ToStringInternal((BigInteger)value);
#endif
}
throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
#region Serialize
/// <summary>
/// Serializes the specified object to a JSON string.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <returns>A JSON string representation of the object.</returns>
[DebuggerStepThrough]
public static string SerializeObject(object? value)
{
return SerializeObject(value, null, (JsonSerializerSettings?)null);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object? value, Formatting formatting)
{
return SerializeObject(value, formatting, (JsonSerializerSettings?)null);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="converters">A collection of converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
[DebuggerStepThrough]
public static string SerializeObject(object? value, params JsonConverter[] converters)
{
JsonSerializerSettings? settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return SerializeObject(value, null, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting and a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="converters">A collection of converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
[DebuggerStepThrough]
public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters)
{
JsonSerializerSettings? settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return SerializeObject(value, null, formatting, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is <c>null</c>, default serialization settings will be used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object? value, JsonSerializerSettings? settings)
{
return SerializeObject(value, null, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using a type, formatting and <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is <c>null</c>, default serialization settings will be used.</param>
/// <param name="type">
/// The type of the value being serialized.
/// This parameter is used when <see cref="JsonSerializer.TypeNameHandling"/> is <see cref="TypeNameHandling.Auto"/> to write out the type name if the type of the value does not match.
/// Specifying the type is optional.
/// </param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
return SerializeObjectInternal(value, type, jsonSerializer);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting and <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is <c>null</c>, default serialization settings will be used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings)
{
return SerializeObject(value, null, formatting, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using a type, formatting and <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is <c>null</c>, default serialization settings will be used.</param>
/// <param name="type">
/// The type of the value being serialized.
/// This parameter is used when <see cref="JsonSerializer.TypeNameHandling"/> is <see cref="TypeNameHandling.Auto"/> to write out the type name if the type of the value does not match.
/// Specifying the type is optional.
/// </param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
jsonSerializer.Formatting = formatting;
return SerializeObjectInternal(value, type, jsonSerializer);
}
private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer)
{
StringBuilder sb = new StringBuilder(256);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = jsonSerializer.Formatting;
jsonSerializer.Serialize(jsonWriter, value, type);
}
return sw.ToString();
}
#endregion
#region Deserialize
/// <summary>
/// Deserializes the JSON to a .NET object.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static object? DeserializeObject(string value)
{
return DeserializeObject(value, null, (JsonSerializerSettings?)null);
}
/// <summary>
/// Deserializes the JSON to a .NET object using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static object? DeserializeObject(string value, JsonSerializerSettings settings)
{
return DeserializeObject(value, null, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static object? DeserializeObject(string value, Type type)
{
return DeserializeObject(value, type, (JsonSerializerSettings?)null);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static T? DeserializeObject<T>(string value)
{
return DeserializeObject<T>(value, (JsonSerializerSettings?)null);
}
/// <summary>
/// Deserializes the JSON to the given anonymous type.
/// </summary>
/// <typeparam name="T">
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be inferred from the anonymous type passed
/// as a parameter.
/// </typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="anonymousTypeObject">The anonymous type object.</param>
/// <returns>The deserialized anonymous type from the JSON string.</returns>
[DebuggerStepThrough]
public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
{
return DeserializeObject<T>(value);
}
/// <summary>
/// Deserializes the JSON to the given anonymous type using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <typeparam name="T">
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be inferred from the anonymous type passed
/// as a parameter.
/// </typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="anonymousTypeObject">The anonymous type object.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
/// <returns>The deserialized anonymous type from the JSON string.</returns>
[DebuggerStepThrough]
public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings)
{
return DeserializeObject<T>(value, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static T? DeserializeObject<T>(string value, params JsonConverter[] converters)
{
return (T?)DeserializeObject(value, typeof(T), converters);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The object to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static T? DeserializeObject<T>(string value, JsonSerializerSettings? settings)
{
return (T?)DeserializeObject(value, typeof(T), settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters)
{
JsonSerializerSettings? settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return DeserializeObject(value, type, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize to.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings)
{
ValidationUtils.ArgumentNotNull(value, nameof(value));
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
// by default DeserializeObject should check for additional content
if (!jsonSerializer.IsCheckAdditionalContentSet())
{
jsonSerializer.CheckAdditionalContent = true;
}
using (JsonTextReader reader = new JsonTextReader(new StringReader(value)))
{
return jsonSerializer.Deserialize(reader, type);
}
}
#endregion
#region Populate
/// <summary>
/// Populates the object with values from the JSON string.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
[DebuggerStepThrough]
public static void PopulateObject(string value, object target)
{
PopulateObject(value, target, null);
}
/// <summary>
/// Populates the object with values from the JSON string using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
public static void PopulateObject(string value, object target, JsonSerializerSettings? settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
using (JsonReader jsonReader = new JsonTextReader(new StringReader(value)))
{
jsonSerializer.Populate(jsonReader, target);
if (settings != null && settings.CheckAdditionalContent)
{
while (jsonReader.Read())
{
if (jsonReader.TokenType != JsonToken.Comment)
{
throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object.");
}
}
}
}
}
#endregion
#region Xml
#if HAVE_XML_DOCUMENT
/// <summary>
/// Serializes the <see cref="XmlNode"/> to a JSON string.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <returns>A JSON string of the <see cref="XmlNode"/>.</returns>
public static string SerializeXmlNode(XmlNode? node)
{
return SerializeXmlNode(node, Formatting.None);
}
/// <summary>
/// Serializes the <see cref="XmlNode"/> to a JSON string using formatting.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <returns>A JSON string of the <see cref="XmlNode"/>.</returns>
public static string SerializeXmlNode(XmlNode? node, Formatting formatting)
{
XmlNodeConverter converter = new XmlNodeConverter();
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Serializes the <see cref="XmlNode"/> to a JSON string using formatting and omits the root object if <paramref name="omitRootObject"/> is <c>true</c>.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the <see cref="XmlNode"/>.</returns>
public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject)
{
XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject };
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Deserializes the <see cref="XmlNode"/> from a JSON string.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns>
public static XmlDocument? DeserializeXmlNode(string value)
{
return DeserializeXmlNode(value, null);
}
/// <summary>
/// Deserializes the <see cref="XmlNode"/> from a JSON string nested in a root element specified by <paramref name="deserializeRootElementName"/>.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns>
public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName)
{
return DeserializeXmlNode(value, deserializeRootElementName, false);
}
/// <summary>
/// Deserializes the <see cref="XmlNode"/> from a JSON string nested in a root element specified by <paramref name="deserializeRootElementName"/>
/// and writes a Json.NET array attribute for collections.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns>
public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute)
{
return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, false);
}
/// <summary>
/// Deserializes the <see cref="XmlNode"/> from a JSON string nested in a root element specified by <paramref name="deserializeRootElementName"/>,
/// writes a Json.NET array attribute for collections, and encodes special characters.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <param name="encodeSpecialCharacters">
/// A value to indicate whether to encode special characters when converting JSON to XML.
/// If <c>true</c>, special characters like ':', '@', '?', '#' and '$' in JSON property names aren't used to specify
/// XML namespaces, attributes or processing directives. Instead special characters are encoded and written
/// as part of the XML element name.
/// </param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns>
public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
{
XmlNodeConverter converter = new XmlNodeConverter();
converter.DeserializeRootElementName = deserializeRootElementName;
converter.WriteArrayAttribute = writeArrayAttribute;
converter.EncodeSpecialCharacters = encodeSpecialCharacters;
return (XmlDocument?)DeserializeObject(value, typeof(XmlDocument), converter);
}
#endif
#if HAVE_XLINQ
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string.
/// </summary>
/// <param name="node">The node to convert to JSON.</param>
/// <returns>A JSON string of the <see cref="XNode"/>.</returns>
public static string SerializeXNode(XObject? node)
{
return SerializeXNode(node, Formatting.None);
}
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string using formatting.
/// </summary>
/// <param name="node">The node to convert to JSON.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <returns>A JSON string of the <see cref="XNode"/>.</returns>
public static string SerializeXNode(XObject? node, Formatting formatting)
{
return SerializeXNode(node, formatting, false);
}
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string using formatting and omits the root object if <paramref name="omitRootObject"/> is <c>true</c>.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the <see cref="XNode"/>.</returns>
public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject)
{
XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject };
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <returns>The deserialized <see cref="XNode"/>.</returns>
public static XDocument? DeserializeXNode(string value)
{
return DeserializeXNode(value, null);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root element specified by <paramref name="deserializeRootElementName"/>.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized <see cref="XNode"/>.</returns>
public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName)
{
return DeserializeXNode(value, deserializeRootElementName, false);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root element specified by <paramref name="deserializeRootElementName"/>
/// and writes a Json.NET array attribute for collections.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized <see cref="XNode"/>.</returns>
public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute)
{
return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, false);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root element specified by <paramref name="deserializeRootElementName"/>,
/// writes a Json.NET array attribute for collections, and encodes special characters.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <param name="encodeSpecialCharacters">
/// A value to indicate whether to encode special characters when converting JSON to XML.
/// If <c>true</c>, special characters like ':', '@', '?', '#' and '$' in JSON property names aren't used to specify
/// XML namespaces, attributes or processing directives. Instead special characters are encoded and written
/// as part of the XML element name.
/// </param>
/// <returns>The deserialized <see cref="XNode"/>.</returns>
public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
{
XmlNodeConverter converter = new XmlNodeConverter();
converter.DeserializeRootElementName = deserializeRootElementName;
converter.WriteArrayAttribute = writeArrayAttribute;
converter.EncodeSpecialCharacters = encodeSpecialCharacters;
return (XDocument?)DeserializeObject(value, typeof(XDocument), converter);
}
#endif
#endregion
}
}
| |
//
// BestEncodingFilter.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013 Jeffrey Stedfast
//
// 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;
namespace MimeKit.IO.Filters {
/// <summary>
/// A filter that can be used to determine the most efficient Content-Transfer-Encoding.
/// </summary>
/// <remarks>
/// Keeps track of the content that gets passed through the filter in order to
/// determine the most efficient <see cref="ContentEncoding"/> to use.
/// </remarks>
public class BestEncodingFilter : IMimeFilter
{
readonly byte[] marker = new byte[6];
bool midline, hasMarker;
int maxline, linelen;
int count0, count8;
int markerLength;
int total;
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.IO.Filters.BestEncodingFilter"/> class.
/// </summary>
public BestEncodingFilter ()
{
}
/// <summary>
/// Gets the best encoding given the specified constraints.
/// </summary>
/// <returns>The best encoding.</returns>
/// <param name="constraint">The encoding constraint.</param>
public ContentEncoding GetBestEncoding (EncodingConstraint constraint)
{
switch (constraint) {
case EncodingConstraint.SevenBit:
if (count0 > 0)
return ContentEncoding.Base64;
if (count8 > 0) {
if (count8 >= (int) (total * (17.0 / 100.0)))
return ContentEncoding.Base64;
return ContentEncoding.QuotedPrintable;
}
if (maxline > 998)
return ContentEncoding.QuotedPrintable;
break;
case EncodingConstraint.EightBit:
if (count0 > 0)
return ContentEncoding.Base64;
if (maxline > 998)
return ContentEncoding.QuotedPrintable;
if (count8 > 0)
return ContentEncoding.EightBit;
break;
case EncodingConstraint.None:
if (count0 > 0)
return ContentEncoding.Binary;
if (count8 > 0)
return ContentEncoding.EightBit;
break;
}
if (hasMarker)
return ContentEncoding.QuotedPrintable;
return ContentEncoding.SevenBit;
}
#region IMimeFilter implementation
static unsafe bool IsMboxMarker (byte[] marker)
{
const uint FromMask = 0xFFFFFFFF;
const uint From = 0x6D6F7246;
fixed (byte* buf = marker) {
uint* word = (uint*) buf;
if ((*word & FromMask) != From)
return false;
return *(buf + 4) == (byte) ' ';
}
}
unsafe void Scan (byte* inptr, byte* inend)
{
while (inptr < inend) {
if (midline) {
byte c = 0;
while (inptr < inend && (c = *inptr++) != (byte) '\n') {
if (c == 0)
count0++;
else if ((c & 0x80) != 0)
count8++;
if (!hasMarker && markerLength > 0 && markerLength < 5)
marker[markerLength++] = c;
linelen++;
}
if (c == (byte) '\n') {
maxline = Math.Max (maxline, linelen);
midline = false;
linelen = 0;
}
}
// check our from-save buffer for "From "
if (!hasMarker && markerLength == 5 && IsMboxMarker (marker))
hasMarker = true;
markerLength = 0;
midline = true;
}
}
static void ValidateArguments (byte[] input, int startIndex, int length)
{
if (input == null)
throw new ArgumentNullException ("input");
if (startIndex < 0 || startIndex > input.Length)
throw new ArgumentOutOfRangeException ("startIndex");
if (length < 0 || startIndex + length > input.Length)
throw new ArgumentOutOfRangeException ("length");
}
/// <summary>
/// Filters the specified input.
/// </summary>
/// <param name='input'>The input buffer.</param>
/// <param name='startIndex'>The starting index of the input buffer.</param>
/// <param name='length'>The number of bytes of the input to filter.</param>
/// <param name='outputIndex'>The starting index of the output in the returned buffer.</param>
/// <param name='outputLength'>The length of the output buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="input"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the <paramref name="input"/> byte array.
/// </exception>
public byte[] Filter (byte[] input, int startIndex, int length, out int outputIndex, out int outputLength)
{
ValidateArguments (input, startIndex, length);
unsafe {
fixed (byte* inptr = input) {
Scan (inptr + startIndex, inptr + startIndex + length);
}
}
maxline = Math.Max (maxline, linelen);
total += length;
outputIndex = startIndex;
outputLength = length;
return input;
}
/// <summary>
/// Filters the specified input, flushing all internally buffered data to the output.
/// </summary>
/// <param name='input'>The input buffer.</param>
/// <param name='startIndex'>The starting index of the input buffer.</param>
/// <param name='length'>The number of bytes of the input to filter.</param>
/// <param name='outputIndex'>The starting index of the output in the returned buffer.</param>
/// <param name='outputLength'>The length of the output buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="input"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the <paramref name="input"/> byte array.
/// </exception>
public byte[] Flush (byte[] input, int startIndex, int length, out int outputIndex, out int outputLength)
{
return Filter (input, startIndex, length, out outputIndex, out outputLength);
}
/// <summary>
/// Resets the filter.
/// </summary>
public void Reset ()
{
hasMarker = false;
markerLength = 0;
midline = false;
linelen = 0;
maxline = 0;
count0 = 0;
count8 = 0;
total = 0;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyComplex
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
public static partial class PolymorphismExtensions
{
/// <summary>
/// Get complex types that are polymorphic
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Fish GetValid(this IPolymorphism operations)
{
return Task.Factory.StartNew(s => ((IPolymorphism)s).GetValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types that are polymorphic
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Fish> GetValidAsync( this IPolymorphism operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Fish> result = await operations.GetValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Put complex types that are polymorphic
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put a salmon that looks like this:
/// {
/// 'dtype':'Salmon',
/// 'location':'alaska',
/// 'iswild':true,
/// 'species':'king',
/// 'length':1.0,
/// 'siblings':[
/// {
/// 'dtype':'Shark',
/// 'age':6,
/// 'birthday': '2012-01-05T01:00:00Z',
/// 'length':20.0,
/// 'species':'predator',
/// },
/// {
/// 'dtype':'Sawshark',
/// 'age':105,
/// 'birthday': '1900-01-05T01:00:00Z',
/// 'length':10.0,
/// 'picture': new Buffer([255, 255, 255, 255,
/// 254]).toString('base64'),
/// 'species':'dangerous',
/// }
/// ]
/// };
/// </param>
public static void PutValid(this IPolymorphism operations, Fish complexBody)
{
Task.Factory.StartNew(s => ((IPolymorphism)s).PutValidAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types that are polymorphic
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put a salmon that looks like this:
/// {
/// 'dtype':'Salmon',
/// 'location':'alaska',
/// 'iswild':true,
/// 'species':'king',
/// 'length':1.0,
/// 'siblings':[
/// {
/// 'dtype':'Shark',
/// 'age':6,
/// 'birthday': '2012-01-05T01:00:00Z',
/// 'length':20.0,
/// 'species':'predator',
/// },
/// {
/// 'dtype':'Sawshark',
/// 'age':105,
/// 'birthday': '1900-01-05T01:00:00Z',
/// 'length':10.0,
/// 'picture': new Buffer([255, 255, 255, 255,
/// 254]).toString('base64'),
/// 'species':'dangerous',
/// }
/// ]
/// };
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutValidAsync( this IPolymorphism operations, Fish complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutValidWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put complex types that are polymorphic, attempting to omit required
/// 'birthday' field - the request should not be allowed from the client
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please attempt put a sawshark that looks like this, the client should not
/// allow this data to be sent:
/// {
/// "dtype": "sawshark",
/// "species": "snaggle toothed",
/// "length": 18.5,
/// "age": 2,
/// "birthday": "2013-06-01T01:00:00Z",
/// "location": "alaska",
/// "picture": base64(FF FF FF FF FE),
/// "siblings": [
/// {
/// "dtype": "shark",
/// "species": "predator",
/// "birthday": "2012-01-05T01:00:00Z",
/// "length": 20,
/// "age": 6
/// },
/// {
/// "dtype": "sawshark",
/// "species": "dangerous",
/// "picture": base64(FF FF FF FF FE),
/// "length": 10,
/// "age": 105
/// }
/// ]
/// }
/// </param>
public static void PutValidMissingRequired(this IPolymorphism operations, Fish complexBody)
{
Task.Factory.StartNew(s => ((IPolymorphism)s).PutValidMissingRequiredAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types that are polymorphic, attempting to omit required
/// 'birthday' field - the request should not be allowed from the client
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please attempt put a sawshark that looks like this, the client should not
/// allow this data to be sent:
/// {
/// "dtype": "sawshark",
/// "species": "snaggle toothed",
/// "length": 18.5,
/// "age": 2,
/// "birthday": "2013-06-01T01:00:00Z",
/// "location": "alaska",
/// "picture": base64(FF FF FF FF FE),
/// "siblings": [
/// {
/// "dtype": "shark",
/// "species": "predator",
/// "birthday": "2012-01-05T01:00:00Z",
/// "length": 20,
/// "age": 6
/// },
/// {
/// "dtype": "sawshark",
/// "species": "dangerous",
/// "picture": base64(FF FF FF FF FE),
/// "length": 10,
/// "age": 105
/// }
/// ]
/// }
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutValidMissingRequiredAsync( this IPolymorphism operations, Fish complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutValidMissingRequiredWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
#define COHERENT_UI_PRO_UNITY3D
#if UNITY_STANDALONE || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX
#define COHERENT_UNITY_STANDALONE
#endif
#if UNITY_2_6 || UNITY_2_6_1 || UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
#define COHERENT_UNITY_PRE_4_0
#endif
#if UNITY_NACL || UNITY_WEBPLAYER
#define COHERENT_UNITY_UNSUPPORTED_PLATFORM
#endif
#if UNITY_EDITOR && (UNITY_IPHONE || UNITY_ANDROID)
#define COHERENT_SIMULATE_MOBILE_IN_EDITOR
#endif
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
#if UNITY_EDITOR || COHERENT_UNITY_STANDALONE || COHERENT_UNITY_UNSUPPORTED_PLATFORM
using Coherent.UI;
using Coherent.UI.Binding;
using CoherentUI = Coherent.UI;
#elif UNITY_IPHONE || UNITY_ANDROID
using Coherent.UI.Mobile;
using Coherent.UI.Mobile.Binding;
using CoherentUI = Coherent.UI.Mobile;
#endif
/// <summary>
/// Component containing a Coherent UI view.
/// </summary>
[AddComponentMenu("Coherent UI/UI View")]
public class CoherentUIView : MonoBehaviour {
[HideInInspector]
[SerializeField]
private string m_Page = "http://google.com";
/// <summary>
/// Gets or sets the URL of the view
/// </summary>
/// <value>
/// The loaded URL of view
/// </value>
[CoherentExposeProperty(Category = CoherentExposePropertyInfo.FoldoutType.General,
PrettyName = "URL",
Tooltip="Indicates the URL that will be initially loaded",
IsStatic=false)]
public string Page
{
get {
return m_Page;
}
set {
if(m_Page == value || value == null)
return;
m_Page = value;
var view = View;
if(view != null)
{
view.Load(m_Page);
}
}
}
[HideInInspector]
[SerializeField]
private int m_Width = 1024;
/// <summary>
/// Gets or sets the width of the view.
/// </summary>
/// <value>
/// The width.
/// </value>
[CoherentExposeProperty(Category = CoherentExposePropertyInfo.FoldoutType.General,
PrettyName = "Width",
Tooltip="Indicates the width of the View",
IsStatic=false)]
public int Width
{
get {
return m_Width;
}
set {
if(m_Width == value)
return;
m_Width = value;
Resize(m_Width, m_Height);
}
}
[HideInInspector]
[SerializeField]
private int m_Height = 512;
/// <summary>
/// Gets or sets the height of the view.
/// </summary>
/// <value>
/// The height.
/// </value>
[CoherentExposeProperty(Category = CoherentExposePropertyInfo.FoldoutType.General,
PrettyName = "Height",
Tooltip="Indicates the height of the View",
IsStatic=false)]
public int Height
{
get {
return m_Height;
}
set {
if(m_Height == value)
return;
m_Height = value;
Resize(m_Width, m_Height);
}
}
[HideInInspector]
[SerializeField]
private int m_XPos = 0;
/// <summary>
/// Gets or sets the X position of the overlay view.
/// </summary>
/// <value>
/// The X position.
/// </value>
[CoherentExposePropertyiOS(Category = CoherentExposePropertyInfo.FoldoutType.General,
PrettyName = "X Position",
Tooltip="The X coordinate of the origin of the View",
IsStatic=false)]
public int XPos
{
get {
return m_XPos;
}
set {
if(m_XPos == value)
return;
m_XPos = value;
#if (UNITY_IPHONE || UNITY_ANDROID) && !UNITY_EDITOR
Move(m_XPos, m_YPos);
#endif
}
}
[HideInInspector]
[SerializeField]
private int m_YPos = 0;
/// <summary>
/// Gets or sets the Y position of the overlay view.
/// </summary>
/// <value>
/// The Y position.
/// </value>
[CoherentExposePropertyiOS(Category = CoherentExposePropertyInfo.FoldoutType.General,
PrettyName = "Y Position",
Tooltip="The Y coordinate of the origin of the View",
IsStatic=false)]
public int YPos
{
get {
return m_YPos;
}
set {
if(m_YPos == value)
return;
m_YPos = value;
#if (UNITY_IPHONE || UNITY_ANDROID) && !UNITY_EDITOR
Move(m_XPos, m_YPos);
#endif
}
}
[HideInInspector]
[SerializeField]
private bool m_ScaleToFit = false;
/// <summary>
/// Gets or sets if the view will scale it's content to fit it's size.
/// </summary>
/// <value>
/// The scale-to-fit property.
/// </value>
[CoherentExposePropertyiOS(Category = CoherentExposePropertyInfo.FoldoutType.Rendering,
PrettyName = "Retina rescale",
Tooltip="If set the content will be scaled to fit the View",
IsStatic=true)]
public bool ScaleToFit
{
get {
return m_ScaleToFit;
}
set {
m_ScaleToFit = value;
}
}
[HideInInspector]
[SerializeField]
private bool m_EnableWebGLSupport = false;
/// <summary>
/// If enabled, WebGL will be supported in the view.
/// </summary>
/// <value>
/// The EnableWebGLSupport property.
/// </value>
[CoherentExposePropertyiOS(Category = CoherentExposePropertyInfo.FoldoutType.Rendering,
PrettyName = "Enable WebGL support",
Tooltip="If set to true, the view will be created with WebGL support.",
IsStatic=true)]
public bool EnableWebGLSupport
{
get {
return m_EnableWebGLSupport;
}
set {
m_EnableWebGLSupport = value;
}
}
[HideInInspector]
[SerializeField]
private string m_InitialScript;
/// <summary>
/// Gets or sets the initial JavaScript code to be executed when the view JavaScript engine is created.
/// </summary>
/// <value>
/// The script.
/// </value>
[CoherentExposeProperty(Category = CoherentExposePropertyInfo.FoldoutType.Scripting,
PrettyName = "Pre-load script",
Tooltip="The script will be executed before any other code in the UI View",
IsStatic=true)]
public string InitialScript
{
get {
return m_InitialScript;
}
set {
m_InitialScript = value;
}
}
public enum CoherentViewInputState {
TakeAll = 0,
TakeNone,
Transparent
}
[HideInInspector]
[SerializeField]
private CoherentViewInputState m_ViewInputState = CoherentViewInputState.Transparent;
/// <summary>
/// Gets or sets the inbput state of the overlay view.
/// </summary>
/// <value>
/// The new input state.
/// </value>
[CoherentExposePropertyiOS(Category = CoherentExposePropertyInfo.FoldoutType.Input,
PrettyName = "Input behavior",
Tooltip="How the View will handle incoming touches",
IsStatic=false)]
public CoherentViewInputState InputState
{
get {
return m_ViewInputState;
}
set {
if(m_ViewInputState == value)
return;
m_ViewInputState = value;
#if (UNITY_IPHONE || UNITY_ANDROID) && !UNITY_EDITOR
SetInputState(m_ViewInputState);
#elif COHERENT_SIMULATE_MOBILE_IN_EDITOR || COHERENT_SIMULATE_MOBILE_IN_PLAYER
if (View != null && IsReadyForBindings)
{
View.ExecuteScript("__couiMobileEmulator.inputState = " +
(int)value);
}
#endif
}
}
[HideInInspector]
[SerializeField]
private bool m_IsTransparent = false;
/// <summary>
/// Gets or sets a value indicating whether the view is transparent.
/// </summary>
/// <value>
/// <c>true</c> if this instance is transparent; otherwise, <c>false</c>.
/// </value>
/// <exception cref='System.ApplicationException'>
/// Is thrown when the property is modified and the view has already been created
/// </exception>
[CoherentExposeProperty(Category = CoherentExposePropertyInfo.FoldoutType.General,
PrettyName = "Transparent",
Tooltip="Toggles the View opacity",
IsStatic=true)]
public bool IsTransparent
{
get {
return m_IsTransparent;
}
set {
if(m_IsTransparent == value)
return;
#if !UNITY_EDITOR
if(View != null) {
throw new System.ApplicationException("The transparency of a View can't be modified if it's already been created");
}
#endif
m_IsTransparent = value;
}
}
[HideInInspector]
[SerializeField]
private bool m_SupportClickThrough = false;
/// <summary>
/// Gets or sets a value indicating whether this view <see cref="CoherentUIView"/> supports click through.
/// </summary>
/// <value>
/// <c>true</c> if supports click through; otherwise, <c>false</c>.
/// </value>
/// <exception cref='System.ApplicationException'>
/// Is thrown when the property is modified and the view has already been created
/// </exception>
[CoherentExposeProperty(Category = CoherentExposePropertyInfo.FoldoutType.Input,
PrettyName = "Smart input",
Tooltip="The View will be able to determine if a pixel is on the UI or the game",
IsStatic=true)]
public bool SupportClickThrough
{
get {
return m_SupportClickThrough;
}
set {
if(m_SupportClickThrough == value)
return;
#if !UNITY_EDITOR
if(View != null) {
throw new System.ApplicationException("The click-through support of a View can't be modified if it's already been created");
}
#endif
m_SupportClickThrough = value;
}
}
[HideInInspector]
[SerializeField]
private float m_ClickThroughAlphaThreshold = 0;
/// <summary>
/// Gets or sets the alpha threshold for click through checks.
/// </summary>
/// <value>
/// The alpha threshold for click through checks.
/// </value>
[CoherentExposePropertyStandalone(Category = CoherentExposePropertyInfo.FoldoutType.Input,
PrettyName = "Smart input alpha",
Tooltip="Alpha threshold value used to distinguish UI opaque pixels",
IsStatic=true)]
public float ClickThroughAlphaThreshold
{
get {
return m_ClickThroughAlphaThreshold;
}
set {
if(m_ClickThroughAlphaThreshold == value)
return;
m_ClickThroughAlphaThreshold = value;
var view = View;
if(view != null)
{
#if UNITY_EDITOR || COHERENT_UNITY_STANDALONE
view.SetClickThroughAlphaThreshold(m_ClickThroughAlphaThreshold);
#endif
}
}
}
[HideInInspector]
[SerializeField]
private bool m_ClickToFocus = false;
/// <summary>
/// When enabled, allows a view to take input focus when clicked with the left mouse button.
/// </summary>
/// <value>
/// <c>true</c> if this view takes input focus when clicked; otherwise, <c>false</c>.
/// </value>
[CoherentExposePropertyStandalone(Category = CoherentExposePropertyInfo.FoldoutType.Input,
PrettyName = "Lockable focus",
Tooltip="Users should click on a View for it to become focused",
IsStatic=true)]
public bool ClickToFocus
{
get {
return m_ClickToFocus;
}
set {
m_ClickToFocus = value;
}
}
#if COHERENT_UI_PRO_UNITY3D && (UNITY_EDITOR || COHERENT_UNITY_STANDALONE)
[HideInInspector]
[SerializeField]
private bool m_IsOnDemand = false;
/// <summary>
/// Gets or sets a value indicating whether this view is an "on demand" view
/// </summary>
/// <value>
/// <c>true</c> if this view is an "on demand" view; otherwise, <c>false</c>.
/// </value>
/// <exception cref='System.ApplicationException'>
/// Is thrown when the property is modified and the view has already been created
/// </exception>
[CoherentExposePropertyStandalone(Category = CoherentExposePropertyInfo.FoldoutType.AdvancedRendering,
PrettyName = "On-demand",
Tooltip="UI is perfectly synced with the game",
IsStatic=true)]
public bool IsOnDemand
{
get {
return m_IsOnDemand;
}
set {
if(m_IsOnDemand == value)
return;
#if !UNITY_EDITOR
if(View != null) {
throw new System.ApplicationException("The type of a View can't be modified if it's already been created");
}
#endif
m_IsOnDemand = value;
}
}
[HideInInspector]
[SerializeField]
private bool m_ControlTimeOnDemand = false;
/// <summary>
/// Defines if the client controls the time of on-demand view himself. If not Coherent UI will update
/// the timers in 'View::RequestFrame'. This option allows for perfect time-sync between the game and the UI.
/// </summary>
/// <value>
/// <c>true</c> if this view is time-controlled by the user; otherwise, <c>false</c>.
/// </value>
/// <exception cref='System.ApplicationException'>
/// Is thrown when the property is modified and the view has already been created
/// </exception>
[CoherentExposePropertyStandalone(Category = CoherentExposePropertyInfo.FoldoutType.AdvancedRendering,
PrettyName = "Timer override",
Tooltip="The UI uses the in-game timer (requires On-demand)",
IsStatic=true)]
public bool ControlTimeOnDemand
{
get {
return m_ControlTimeOnDemand;
}
set {
if(m_ControlTimeOnDemand == value)
return;
#if !UNITY_EDITOR
if(View != null) {
throw new System.ApplicationException("The type of a View can't be modified if it's already been created");
}
#endif
m_ControlTimeOnDemand = value;
}
}
[HideInInspector]
[SerializeField]
private int m_TargetFramerate = 60;
/// <summary>
/// Gets or sets the target framerate for the view.
/// </summary>
/// <value>
/// The target framerate.
/// </value>
[CoherentExposePropertyStandalone(Category = CoherentExposePropertyInfo.FoldoutType.AdvancedRendering,
PrettyName = "Max. frame-rate",
Tooltip="The maximum frame-rate that the UI will achieve",
IsStatic=true)]
public int TargetFramerate
{
get {
return m_TargetFramerate;
}
set {
if(m_TargetFramerate == value)
return;
m_TargetFramerate = value;
var view = View;
if(view != null)
{
view.SetTargetFramerate(m_TargetFramerate);
}
}
}
#endif
public enum DrawOrder {
Normal,
AfterPostEffects
}
[HideInInspector]
[SerializeField]
private DrawOrder m_DrawAfterPostEffects = DrawOrder.Normal;
/// <summary>
/// Gets or sets a value indicating whether this view is drawn after post effects.
/// </summary>
/// <value>
/// <c>AfterPostEffects</c> if the view is drawn after post effects; otherwise, <c>false</c>.
/// </value>
/// <exception cref='System.ApplicationException'>
/// Is thrown when the application exception.
/// </exception>
[CoherentExposePropertyStandalone(Category = CoherentExposePropertyInfo.FoldoutType.Rendering,
PrettyName = "Draw order",
Tooltip="When to draw the View (camera Views only)",
IsStatic=true)]
public DrawOrder DrawAfterPostEffects
{
get {
return m_DrawAfterPostEffects;
}
set {
if(m_DrawAfterPostEffects == value)
return;
#if !UNITY_EDITOR
if(View != null) {
throw new System.ApplicationException("The draw order of a View can't be modified if it's already been created");
}
#endif
m_DrawAfterPostEffects = value;
}
}
[HideInInspector]
[SerializeField]
private bool m_FlipY = false;
/// <summary>
/// Gets or sets a value indicating whether the Y axis of this view should be flipped.
/// </summary>
/// <value>
/// <c>true</c> if the Y axis is flipped; otherwise, <c>false</c>.
/// </value>
[CoherentExposePropertyStandalone(Category = CoherentExposePropertyInfo.FoldoutType.Rendering,
PrettyName = "Flip Y",
Tooltip="Will flip the View vertically",
IsStatic=false)]
public bool FlipY
{
get {
return m_FlipY;
}
set {
if(m_FlipY == value)
return;
m_FlipY = value;
if (m_Listener != null && m_Listener.ViewRenderer != null)
{
m_Listener.ViewRenderer.FlipY = ForceInvertY() ? !m_FlipY : m_FlipY;
}
}
}
#if UNITY_EDITOR || COHERENT_UNITY_STANDALONE
[HideInInspector]
[SerializeField]
private CoherentUISystem.CoherentFilteringModes m_Filtering =
CoherentUISystem.CoherentFilteringModes.PointFiltering;
[CoherentExposePropertyStandalone(Category = CoherentExposePropertyInfo.FoldoutType.Rendering,
PrettyName = "Texture filtering",
Tooltip="Defines the way the Coherent UI texture will be filtered on the final Unity texture",
IsStatic=false)]
public CoherentUISystem.CoherentFilteringModes Filtering
{
get {
return m_Filtering;
}
set {
if(m_Filtering == value)
{
return;
}
m_Filtering = value;
if(m_Listener != null && m_Listener.ViewRenderer != null)
{
m_Listener.ViewRenderer.FilteringMode = value;
}
}
}
#endif
// Invert flipping on camera-attached views on OpenGL
internal bool ForceInvertY()
{
return GetComponent<Camera>() != null
&& SystemInfo.graphicsDeviceVersion.Contains("Open")
&& Application.platform != RuntimePlatform.WindowsEditor;
}
[HideInInspector]
[SerializeField]
private bool m_ReceivesInput = false;
/// <summary>
/// Gets or sets a value indicating whether this view receives input.
/// All automatic processing and reading of this property is done in the
/// `LateUpdate()` / `OnGUI()` callbacks in Unity, letting you do all your logic
/// for View focus in `Update()`.
/// </summary>
/// <value>
/// <c>true</c> if this view receives input; otherwise, <c>false</c>.
/// </value>
public virtual bool ReceivesInput
{
get {
return m_ReceivesInput;
}
set {
if (m_System != null && !m_System.IsUpdating && this.ClickToFocus) {
Debug.LogWarning("You're setting the CoherentUIView.ReceivesInput property on a view that manages input focus on its own. " +
"To avoid this, before setting the ReceivesInput property, check if the ClickToFocus property is set to false.");
}
m_ReceivesInput = value;
}
}
protected UnityViewListener m_Listener;
protected CoherentUISystem m_System;
[HideInInspector]
[SerializeField]
private bool m_InterceptAllEvents = false;
/// <summary>
/// Gets or sets a value indicating whether this view intercepts all events and sends a message for each event.
/// </summary>
/// <value>
/// <c>true</c> if view intercepts all events; otherwise, <c>false</c>.
/// </value>
/// <exception cref='System.ApplicationException'>
/// Is thrown when the property is modified and the view has already been created
/// </exception>
[CoherentExposeProperty(Category = CoherentExposePropertyInfo.FoldoutType.Scripting,
PrettyName = "Auto UI messages",
Tooltip="Events triggered in the UI will fire Unity messages",
IsStatic=true)]
public bool InterceptAllEvents
{
get {
return m_InterceptAllEvents;
}
set {
if(m_InterceptAllEvents == value)
return;
#if !UNITY_EDITOR
if(View != null) {
throw new System.ApplicationException("Intercepting all events can't be changed if the view has already been created");
}
#endif
m_InterceptAllEvents = value;
}
}
[HideInInspector]
[SerializeField]
private bool m_EnableBindingAttribute = true;
/// <summary>
/// Gets or sets a value indicating whether this <see cref="CoherentUIView"/> enables usage of the CoherentMethod attribute
/// in components in the host GameObject.
/// When true, the all components in the host GameObject are inspected for the CoherentMethod attribute (in the Awake() function)
/// and the decorated methods are automatically bound when the ReadyForBindings event is received.
/// When false, the attribute does nothing.
/// </summary>
/// <value>
/// <c>true</c> if usage of the CoherentMethod is enabled; otherwise, <c>false</c>.
/// </value>
[CoherentExposeProperty(Category = CoherentExposePropertyInfo.FoldoutType.Scripting,
PrettyName = "Enable [CoherentMethodAttribute]",
Tooltip="Allows automatic binding of methods to the UI",
IsStatic=true)]
public bool EnableBindingAttribute
{
get {
return m_EnableBindingAttribute;
}
set {
m_EnableBindingAttribute = value;
}
}
[HideInInspector]
[SerializeField]
private bool m_IsIndependentOfZBuffer = false;
/// <summary>
/// Gets or sets a value indicating whether this view is z-buffer independent. If it is set to true, the view is rendered on top of everything.
/// </summary>
/// <value>
/// <c>true</c> if it is independent; otherwise <c>false</c>.
/// </value>
[CoherentExposePropertyStandalone(Category = CoherentExposePropertyInfo.FoldoutType.AdvancedRendering,
PrettyName = "Always on top",
Tooltip="Ignores the content of the depth buffer",
IsStatic=true)]
public bool IsIndependentOfZBuffer
{
get
{
return m_IsIndependentOfZBuffer;
}
set
{
m_IsIndependentOfZBuffer = value;
}
}
[HideInInspector]
[SerializeField]
private bool m_ShowJavaScriptDialogs = true;
/// <summary>
/// Gets or sets a value indicating whether dialogs will be drawn when a JavaScript message is received (e.g. alert, prompt, auth credentials).
/// </summary>
/// <value>
/// <c>true</c> if a dialog is to be shown automatically; otherwise <c>false</c>.
/// </value>
[CoherentExposePropertyStandalone(Category = CoherentExposePropertyInfo.FoldoutType.Scripting,
PrettyName = "Show JS dialogs",
Tooltip="Shows JS alerts, prompts, auths, confirmations",
IsStatic=false)]
public bool ShowJavaScriptDialogs
{
get
{
return m_ShowJavaScriptDialogs;
}
set
{
m_ShowJavaScriptDialogs = value;
}
}
[HideInInspector]
[SerializeField]
private bool m_ForceSoftwareRendering = false;
/// <summary>
/// Forces the view to use software rendering. For GPU-bound applications software views might be a good choice.
/// CSS 3D transforms, WebGL and accelerated Canvas don't work with software views. This option doesn't work with OnDemand.
///
/// Not available for iOS.
/// </summary>
/// <value>
/// <c>true</c> if the view is to use software rendering; otherwise <c>false</c>.
/// </value>
[CoherentExposeProperty(
Category = CoherentExposePropertyInfo.FoldoutType.Rendering,
PrettyName = "Software only rendering",
Tooltip = "The view will be rendered without hardware acceleration",
IsStatic = true)]
public bool ForceSoftwareRendering
{
get
{
return m_ForceSoftwareRendering;
}
set
{
m_ForceSoftwareRendering = value;
}
}
private Camera m_Camera;
private bool m_QueueCreateView = false;
[HideInInspector]
[SerializeField]
private bool m_UseCameraDimensions = true;
/// <summary>
/// If checked, the view will use the camera's width and height
/// </summary>
/// <value>
/// <c>true</c> if we want to use camera's width and height; otherwise <c>false</c>.
/// </value>
[CoherentExposeProperty(Category = CoherentExposePropertyInfo.FoldoutType.Rendering,
PrettyName = "Match camera size",
Tooltip="The View will be automatically resized to always match the size of the camera",
IsStatic=true)]
public bool UseCameraDimensions
{
get {
return m_UseCameraDimensions;
}
set {
m_UseCameraDimensions = value;
}
}
[HideInInspector]
[SerializeField]
private bool m_CorrectGamma = false;
/// <summary>
/// Gets or sets a value indicating whether this view should have gamma
/// corrected.
/// </summary>
/// <value>
/// <c>true</c> if gamma is corrected; otherwise, <c>false</c>.
/// </value>
[CoherentExposePropertyStandalone(
Category = CoherentExposePropertyInfo.FoldoutType.AdvancedRendering,
PrettyName = "Compensate gamma",
Tooltip="The view will compensate for gamma correction",
IsStatic=true)]
public bool CorrectGamma
{
get
{
return m_CorrectGamma;
}
set
{
if (m_CorrectGamma != value)
{
m_CorrectGamma = value;
if (m_Listener != null && m_Listener.ViewRenderer != null)
{
m_Listener.ViewRenderer.ShouldCorrectGamma = m_CorrectGamma;
}
}
}
}
[HideInInspector]
[SerializeField]
private bool m_EnableIME = false;
/// <summary>
/// Gets or sets a value indicating whether the view should have IME enabled
/// </summary>
/// <value>
/// <c>true</c> if IME is enabled; otherwise, <c>false</c>.
/// </value>
[CoherentExposePropertyStandalone(Category =
CoherentExposePropertyInfo.FoldoutType.Input,
PrettyName = "Enable IME",
Tooltip="The view will have IME enabled",
IsStatic=false)]
public bool EnableIME
{
get {
return m_EnableIME;
}
set {
#if UNITY_EDITOR || COHERENT_UNITY_STANDALONE
if(m_EnableIME != value)
{
m_EnableIME = value;
var imeComponent = gameObject.GetComponent<IMEHandler>();
if(imeComponent == null)
{
imeComponent = gameObject.AddComponent<IMEHandler>();
}
imeComponent.enabled = m_EnableIME;
}
#endif
}
}
internal int MouseX { get; set; }
internal int MouseY { get; set; }
public bool IsReadyForBindings { get; private set; }
private List<CoherentMethodBindingInfo> m_CoherentMethods;
/// <summary>
/// Sets the mouse position. Note Coherent UI (0,0) is the upper left corner of the screen.
/// </summary>
/// <param name='x'>
/// X coordinate of the mouse.
/// </param>
/// <param name='y'>
/// Y coordinate of the mouse.
/// </param>
public void SetMousePosition(int x, int y)
{
MouseX = x;
MouseY = y;
}
void Awake () {
MouseX = -1;
MouseY = -1;
m_System = CoherentUISystem.Instance;
m_CoherentMethods = new List<CoherentMethodBindingInfo>();
if (EnableBindingAttribute)
{
RegisterMethodsForBinding();
}
m_Listener = new UnityViewListener(this, this.m_Width, this.m_Height);
m_Listener.ReadyForBindings += this.ReadyForBindings;
m_Listener.BindingsReleased += this.BindingsReleased;
IsReadyForBindings = false;
#if !UNITY_EDITOR && UNITY_ANDROID
m_Listener.NewTouchEvent += (id, phase, x, y) =>
{
CoherentUI.InputManager.ProcessTouchEvent(id, phase,
x + this.XPos, y + this.YPos);
};
#endif
m_Camera = GetComponent<Camera>();
m_System.UISystemDestroying += OnDestroy;
m_System.SystemReady += OnSystemReady;
m_System.AddView(this);
}
private void RegisterMethodsForBinding()
{
List<CoherentMethodBindingInfo> methods = CoherentMethodHelper.GetCoherentMethodsInGameObject(this.gameObject);
m_CoherentMethods.AddRange(methods);
}
private void ReadyForBindings(int frame, string url, bool isMain)
{
if (isMain)
{
foreach (var item in m_CoherentMethods)
{
if (item.IsEvent)
{
View.RegisterForEvent(item.ScriptEventName, item.BoundFunction);
}
else
{
View.BindCall(item.ScriptEventName, item.BoundFunction);
}
}
if (m_InterceptAllEvents)
{
View.RegisterForEvent("all", (System.Action<string, Value[]>)this.InterceptEvent);
}
IsReadyForBindings = true;
}
}
void BindingsReleased (int frameId, string path, bool isMainFrame)
{
if (isMainFrame)
{
IsReadyForBindings = false;
}
}
private void InterceptEvent(string name, Value[] arguments)
{
SendMessage(name, arguments, SendMessageOptions.DontRequireReceiver);
}
private void SendCreateView()
{
if(Page == null || Page == "") {
throw new System.ApplicationException("The Page of a view must not be null or empty.");
}
var viewInfo = new ViewInfo();
viewInfo.Width = this.m_Width;
viewInfo.Height = this.m_Height;
viewInfo.IsTransparent = this.m_IsTransparent;
#if COHERENT_UI_PRO_UNITY3D && (UNITY_EDITOR || COHERENT_UNITY_STANDALONE)
viewInfo.IsOnDemand = this.m_IsOnDemand;
viewInfo.ControlTimeOnDemand = this.m_ControlTimeOnDemand;
viewInfo.TargetFrameRate = (int)this.m_TargetFramerate;
#endif
viewInfo.SupportClickThrough = this.m_SupportClickThrough;
viewInfo.ForceSoftwareRendering = this.m_ForceSoftwareRendering;
#if UNITY_EDITOR || COHERENT_UNITY_STANDALONE
viewInfo.ClickThroughAlphaThreshold = this.m_ClickThroughAlphaThreshold;
viewInfo.UsesSharedMemory = !m_System.DeviceSupportsSharedTextures || this.m_ForceSoftwareRendering;
#elif UNITY_IPHONE || UNITY_ANDROID
viewInfo.X = this.m_XPos;
viewInfo.Y = this.m_YPos;
viewInfo.ShowImmediately = this.enabled;
viewInfo.InitialInputState = (ViewInputState)this.m_ViewInputState;
viewInfo.ScaleToFit = m_ScaleToFit;
viewInfo.EnableWebGLSupport = m_EnableWebGLSupport;
viewInfo.IsSurfaceView = IsSurfaceView;
viewInfo.ResizeOnRotation = UseCameraDimensions;
#endif
#if UNITY_EDITOR || COHERENT_UNITY_STANDALONE
var initialScript = InitialScript;
#if COHERENT_SIMULATE_MOBILE_IN_EDITOR || COHERENT_SIMULATE_MOBILE_IN_PLAYER
initialScript = string.Format(
"var __couiMobileEmulator = {{ inputState: {0} }};",
(int)this.m_ViewInputState) +
@"var touchListener = function(phase) {
return function(event) {
if (phase == 1 && event.which == 0)
{
// Ignore mousemove events with no button pressed.
// This is something that cannot happen on mobile.
return;
}
if (__couiMobileEmulator.inputState == 0)
{
// Input state: Take all (all events go to the UI only)
return;
}
else if (__couiMobileEmulator.inputState == 1)
{
// Input state: Take none
event.preventDefault();
engine.call('__couiTouchEvent', event.which, phase,
event.x, event.y);
}
else
{
var isConsumed = engine && engine.checkClickThrough &&
engine.checkClickThrough(event.x, event.y);
if (phase != 0 || isConsumed == 'N') {
engine.call('__couiTouchEvent', event.which, phase,
event.x, event.y);
}
}
};
};
document.addEventListener('DOMContentLoaded', function() {
document.addEventListener('mousedown', touchListener(0));
document.addEventListener('mouseup', touchListener(3));
document.addEventListener('mousemove', touchListener(1));
var newdiv = document.createElement('div');
newdiv.setAttribute('id', '__CoherentBackground');
newdiv.setAttribute('class', 'coui-noinput');
newdiv.setAttribute('style',
'background-color: rgba(0,0,0,0); width: 100%;' +
'height: 100%; position: absolute; z-index: -1000000;');
document.body.insertBefore(newdiv, document.body.firstChild);
});
" +
(string.IsNullOrEmpty(initialScript) ? "" : initialScript);
#endif
if (initialScript == null)
{
m_System.UISystem.CreateView(viewInfo, Page, m_Listener);
}
else
{
m_System.UISystem.CreateView(viewInfo, Page, m_Listener,
initialScript);
}
#else
m_System.UISystem.CreateView(viewInfo, Page, m_Listener);
#endif
#if UNITY_EDITOR || COHERENT_UNITY_STANDALONE
CoherentUIViewRenderer.WakeRenderer();
#endif
}
private void OnSystemReady()
{
if (this.enabled)
{
SendCreateView();
}
else
{
m_QueueCreateView = true;
}
}
void Update () {
if (m_QueueCreateView && this.enabled)
{
SendCreateView();
m_QueueCreateView = false;
}
var view = View;
if(view != null)
{
#if COHERENT_UI_PRO_UNITY3D && (UNITY_EDITOR || COHERENT_UNITY_STANDALONE)
if(IsOnDemand)
{
if(ControlTimeOnDemand)
{
float arbitraryTime = 0.0f;
if(CalculateArbitraryTime != null)
{
arbitraryTime = CalculateArbitraryTime();
}
else
{
arbitraryTime = CoherentUISystem.Instance.StartTime + Time.time;
}
view.RequestFrame(arbitraryTime);
}
else
{
view.RequestFrame();
}
}
#endif
if(m_UseCameraDimensions)
{
int width = 0;
int height = 0;
if(GetCamDimensions(ref width, ref height))
{
if(width != m_Width || height != m_Height)
{
Resize(width, height);
}
}
}
}
}
void OnDisable()
{
#if (UNITY_IPHONE || UNITY_ANDROID) && !UNITY_EDITOR
SetShow(false);
#else
if(m_Listener != null && m_Listener.ViewRenderer != null)
{
m_Listener.ViewRenderer.IsActive = false;
}
#endif
}
void OnEnable()
{
#if (UNITY_IPHONE || UNITY_ANDROID) && !UNITY_EDITOR
SetShow(true);
#else
if(m_Listener != null && m_Listener.ViewRenderer != null)
{
m_Listener.ViewRenderer.IsActive = true;
}
#endif
}
void OnDestroy()
{
if(m_Listener != null)
{
m_Listener.Destroy();
m_Listener.Dispose();
m_Listener = null;
}
m_System.RemoveView(this);
if (OnViewDestroyed != null)
{
OnViewDestroyed();
}
}
/// <summary>
/// Destroy this view. Destroys the Coherent UI view and removes the CoherentUIView
/// component from its game object. Any usage of the view after this method is
/// undefined behaviour.
/// </summary>
public void DestroyView()
{
OnDestroy();
UnityEngine.Object.Destroy(this);
}
/// <summary>
/// Handler for ViewDestroyed event.
/// </summary>
public delegate void ViewDestroyedHandler();
/// <summary>
/// Occurs when the view has been destroyed and the CoherentUIView component
/// is going to be removed from the game object.
/// </summary>
public event ViewDestroyedHandler OnViewDestroyed;
/// <summary>
/// Resize the view to the specified width and height.
/// </summary>
/// <param name='width'>
/// New width for the view.
/// </param>
/// <param name='height'>
/// New height for the view.
/// </param>
public void Resize(int width, int height)
{
m_Width = width;
m_Height = height;
var view = View;
if(view != null)
{
view.Resize((uint)m_Width, (uint)m_Height);
if(m_Listener.RTTexture != null)
{
m_Listener.ResizeTexture(m_Width, m_Height);
}
}
}
#if (UNITY_IPHONE || UNITY_ANDROID) && !UNITY_EDITOR
/// <summary>
/// Move the overlay view to the specified x and y position.
/// </summary>
/// <param name='x'>
/// New X position of the view.
/// </param>
/// <param name='y'>
/// New Y position of the view.
/// </param>
public void Move(int x, int y)
{
m_XPos = x;
m_YPos = y;
var view = View;
if(view != null)
{
view.Move((uint)m_XPos, (uint)m_YPos);
}
}
/// <summary>
/// Show/hide the overlay view.
/// </summary>
/// <param name='show'>
/// Whether to show or to hide the view
/// </param>
public void SetShow(bool show)
{
var view = View;
if(view != null)
{
view.SetShow(show);
}
}
/// <summary>
/// Sets the input state of the overlay view.
/// </summary>
/// <param name='state'>
/// The new state of the input
/// </param>
public void SetInputState(CoherentViewInputState state)
{
m_ViewInputState = state;
var view = View;
if(view != null)
{
view.SetInputState((ViewInputState)m_ViewInputState);
}
}
#endif
/// <summary>
/// Gets the underlying Coherent.UI.View instance.
/// </summary>
/// <value>
/// The underlying Coherent.UI.View instance.
/// </value>
public View View
{
get {
if(m_Listener != null) {
return m_Listener.View;
}
else {
return null;
}
}
}
#if UNITY_EDITOR || COHERENT_UNITY_STANDALONE
/// <summary>
/// Request redraw of this view.
/// </summary>
public void Redraw()
{
var view = View;
if(view != null)
{
view.Redraw();
}
}
#endif
/// <summary>
/// Request reload of this view.
/// </summary>
/// <param name='ignoreCache'>
/// Ignore cache for the reload.
/// </param>
public void Reload(bool ignoreCache)
{
var view = View;
if(view != null)
{
view.Reload(ignoreCache);
}
}
/// <summary>
/// Returns the camera dimensions of the current view.
/// </summary>
public bool GetCamDimensions(ref int x, ref int y)
{
if (m_Camera != null)
{
x = (int)m_Camera.pixelWidth;
y = (int)m_Camera.pixelHeight;
return true;
}
else if(m_Listener.ViewRenderer != null)
{
GameObject rendererGO = m_Listener.ViewRenderer.gameObject;
if(rendererGO != null)
{
var camera = rendererGO.GetComponent<Camera>();
x = (int)camera.pixelWidth;
y = (int)camera.pixelHeight;
return true;
}
}
return false;
}
/// <summary>
/// Occurs when the underlying Coherent.UI.View is created
/// </summary>
public event UnityViewListener.CoherentUI_OnViewCreated OnViewCreated {
add {
m_Listener.ViewCreated += value;
}
remove {
m_Listener.ViewCreated -= value;
}
}
/// <summary>
/// Occurs when the view bindings should be registered.
/// </summary>
public event UnityViewListener.CoherentUI_OnReadyForBindings OnReadyForBindings {
add {
m_Listener.ReadyForBindings += value;
}
remove {
m_Listener.ReadyForBindings -= value;
}
}
/// <summary>
/// Gets the underlying UnityViewListener for this view.
/// </summary>
/// <value>
/// The listener.
/// </value>
public UnityViewListener Listener {
get { return m_Listener; }
}
#if UNITY_EDITOR || COHERENT_UNITY_STANDALONE
public float WidthToCamWidthRatio(float camWidth)
{
return m_Width / camWidth;
}
public float HeightToCamHeightRatio(float camHeight)
{
return m_Height / camHeight;
}
#endif
#if UNITY_EDITOR || COHERENT_UNITY_STANDALONE
/// <summary>
/// Handler for calculating the screen position of the IME candidate
/// list window.
/// </summary>
/// <param name='x'>
/// X coordinate of the current caret position in view space.
/// </param>
/// <param name='y'>
/// Y coordinate of the current caret position in view space.
/// </param>
/// <param name='width'>
/// The width of the text input control, on which the caret is positioned.
/// </param>
/// <param name='height'>
/// The height of the text input control, on which the caret is positioned.
/// </param>
/// <returns>
/// The position of the candaidate list window in screen space coordinates.
/// </returns>
public event IMEHandler.CalculateIMECandidateListPositionHandler
CalculateIMECandidateListPosition
{
add
{
var imeComponent = gameObject.GetComponent<IMEHandler>();
if(imeComponent != null)
{
imeComponent.CalculateIMECandidateListPosition += value;
}
}
remove
{
var imeComponent = gameObject.GetComponent<IMEHandler>();
if(imeComponent != null)
{
imeComponent.CalculateIMECandidateListPosition -= value;
}
}
}
#endif
public delegate float CalculateArbitraryTimeHandler();
public CalculateArbitraryTimeHandler CalculateArbitraryTime;
/// <summary>
/// whether this is a mobile surface view
/// </summary>
public virtual bool IsSurfaceView
{
get { return false; }
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.Numerics.Tests
{
public class multiplyTest
{
private static int s_samples = 10;
private static int s_seed = 100;
[Fact]
public static void RunMultiply_TwoLargeBigIntegers()
{
Random random = new Random(s_seed);
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Multiply Method - One Large BigInteger
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(random);
VerifyMultiplyString(Print(tempByteArray1) + "uMultiply");
}
// Multiply Method - Two Large BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(random);
tempByteArray2 = GetRandomByteArray(random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "bMultiply");
}
}
[Fact]
public static void RunMultiply_TwoLargeBigIntegers_Threshold()
{
// Again, with lower threshold
BigIntTools.Utils.RunWithFakeThreshold("SquareThreshold", 8, () =>
BigIntTools.Utils.RunWithFakeThreshold("MultiplyThreshold", 8, RunMultiply_TwoLargeBigIntegers)
);
// Again, with lower threshold
BigIntTools.Utils.RunWithFakeThreshold("SquareThreshold", 8, () =>
BigIntTools.Utils.RunWithFakeThreshold("MultiplyThreshold", 8, () =>
BigIntTools.Utils.RunWithFakeThreshold("AllocationThreshold", 8, RunMultiply_TwoLargeBigIntegers)
)
);
}
[Fact]
public static void RunMultiply_TwoSmallBigIntegers()
{
Random random = new Random(s_seed);
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Multiply Method - Two Small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(random, 2);
tempByteArray2 = GetRandomByteArray(random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "bMultiply");
}
}
[Fact]
public static void RunMultiply_OneLargeOneSmall()
{
Random random = new Random(s_seed);
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Multiply Method - One large and one small BigIntegers
for (int i = 0; i < s_samples; i++)
{
try
{
tempByteArray1 = GetRandomByteArray(random);
tempByteArray2 = GetRandomByteArray(random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "bMultiply");
tempByteArray1 = GetRandomByteArray(random, 2);
tempByteArray2 = GetRandomByteArray(random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "bMultiply");
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("Array1: " + Print(tempByteArray1));
Console.WriteLine("Array2: " + Print(tempByteArray2));
throw;
}
}
}
[Fact]
public static void RunMultiply_OneLargeOneZero()
{
Random random = new Random(s_seed);
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Multiply Method - One large BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(random);
tempByteArray2 = new byte[] { 0 };
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "bMultiply");
tempByteArray1 = new byte[] { 0 };
tempByteArray2 = GetRandomByteArray(random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "bMultiply");
}
}
[Fact]
public static void RunMultiply_OneSmallOneZero()
{
Random random = new Random(s_seed);
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Multiply Method - One small BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(random, 2);
tempByteArray2 = new byte[] { 0 };
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "bMultiply");
tempByteArray1 = new byte[] { 0 };
tempByteArray2 = GetRandomByteArray(random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "bMultiply");
}
}
[Fact]
public static void RunMultiply_AxiomXX1()
{
Random random = new Random(s_seed);
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: X*1 = X
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.One + " bMultiply", Int32.MaxValue.ToString());
VerifyIdentityString(Int64.MaxValue + " " + BigInteger.One + " bMultiply", Int64.MaxValue.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(random));
VerifyIdentityString(randBigInt + BigInteger.One + " bMultiply", randBigInt + "u+");
}
}
[Fact]
public static void RunMultiply_AxiomXX0()
{
Random random = new Random(s_seed);
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: X*0 = 0
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.Zero + " bMultiply", BigInteger.Zero.ToString());
VerifyIdentityString(Int64.MaxValue + " " + BigInteger.Zero + " bMultiply", BigInteger.Zero.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(random));
VerifyIdentityString(randBigInt + BigInteger.Zero + " bMultiply", BigInteger.Zero.ToString());
}
}
[Fact]
public static void RunMultiply_Commutat()
{
Random random = new Random(s_seed);
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: a*b = b*a
VerifyIdentityString(Int32.MaxValue + " " + Int64.MaxValue + " bMultiply", Int64.MaxValue + " " + Int32.MaxValue + " bMultiply");
for (int i = 0; i < s_samples; i++)
{
String randBigInt1 = Print(GetRandomByteArray(random));
String randBigInt2 = Print(GetRandomByteArray(random));
VerifyIdentityString(randBigInt1 + randBigInt2 + "bMultiply", randBigInt2 + randBigInt1 + "bMultiply");
}
}
[Fact]
public static void RunMultiply_Boundary()
{
Random random = new Random(s_seed);
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Check interesting cases for boundary conditions
// You'll either be shifting a 0 or 1 across the boundary
// 32 bit boundary n2=0
VerifyMultiplyString(Math.Pow(2, 32) + " 2 bMultiply");
// 32 bit boundary n1=0 n2=1
VerifyMultiplyString(Math.Pow(2, 33) + " 2 bMultiply");
}
private static void VerifyMultiplyString(string opstring)
{
StackCalc sc = new StackCalc(opstring);
while (sc.DoNextOperation())
{
Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString());
}
}
private static void VerifyIdentityString(string opstring1, string opstring2)
{
StackCalc sc1 = new StackCalc(opstring1);
while (sc1.DoNextOperation())
{
//Run the full calculation
sc1.DoNextOperation();
}
StackCalc sc2 = new StackCalc(opstring2);
while (sc2.DoNextOperation())
{
//Run the full calculation
sc2.DoNextOperation();
}
Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString());
}
private static byte[] GetRandomByteArray(Random random)
{
return GetRandomByteArray(random, random.Next(0, 100));
}
private static byte[] GetRandomByteArray(Random random, int size)
{
return MyBigIntImp.GetRandomByteArray(random, size);
}
private static String Print(byte[] bytes)
{
return MyBigIntImp.Print(bytes);
}
}
}
| |
//
// PlayingActivity.cs
//
// Author:
// John Moore <jcwmoore@gmail.com>
//
// Copyright (c) 2012 John Moore
//
// 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.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Views;
using Android.Widget;
using JohnMoore.AmpacheNet.Entities;
using JohnMoore.AmpacheNet.Logic;
namespace JohnMoore.AmpacheNet
{
public abstract class PlayingActivity : Activity, AmpacheService.IClient
{
protected AmpacheModel _model;
protected readonly Dictionary<string, Action> _uiActions = new Dictionary<string, Action>();
private AmpacheService.Connection _connection;
private Android.Graphics.Bitmap _currentAlbumArt;
protected abstract int MenuId { get; }
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
_connection = new AmpacheService.Connection(this);
StartService(new Intent(this.ApplicationContext, typeof(AmpacheService)));
}
protected override void OnResume()
{
base.OnResume();
if(_model == null)
{
BindService(new Intent(this.ApplicationContext, typeof(AmpacheService)), _connection, Bind.AutoCreate);
}
else
{
_model.PropertyChanged += Handle_modelPropertyChanged;
OnModelLoaded();
UpdateArt();
}
}
public void Connected (Athena.IoC.Container container)
{
_model = container.Resolve<AmpacheModel>();
if(!_uiActions.ContainsKey(AmpacheModel.ALBUM_ART_STREAM))
{
_uiActions.Add(AmpacheModel.ALBUM_ART_STREAM, UpdateArt);
RunOnUiThread(() => UpdateArt());
}
if(!_uiActions.ContainsKey(AmpacheModel.NEXT_REQUESTED))
{
_uiActions.Add(AmpacheModel.NEXT_REQUESTED, UpdateNextButton);
RunOnUiThread(() => UpdateNextButton());
}
if(!_uiActions.ContainsKey(AmpacheModel.PREVIOUS_REQUESTED))
{
_uiActions.Add(AmpacheModel.PREVIOUS_REQUESTED, UpdatePreviousButton);
RunOnUiThread(() => UpdatePreviousButton());
}
if(!_uiActions.ContainsKey(AmpacheModel.SHUFFELING))
{
_uiActions.Add(AmpacheModel.SHUFFELING, UpdateShuffleButton);
RunOnUiThread(() => UpdateShuffleButton());
}
if(!_uiActions.ContainsKey(AmpacheModel.PLAY_PAUSE_REQUESTED))
{
_uiActions.Add(AmpacheModel.PLAY_PAUSE_REQUESTED, UpdatePlayPauseButton);
RunOnUiThread(() => UpdatePlayPauseButton());
}
if(!_uiActions.ContainsKey(AmpacheModel.USER_MESSAGE))
{
_uiActions.Add(AmpacheModel.USER_MESSAGE, DisplayMessage);
}
_model.PropertyChanged += Handle_modelPropertyChanged;
_model.PropertyChanged += ModelDisposed;
ImageButton btn = FindViewById<ImageButton>(Resource.Id.imgPlayingNext);
if(btn != null)
{
btn.Click += HandleNextClick;
}
btn = FindViewById<ImageButton>(Resource.Id.imgPlayingPrevious);
if(btn != null)
{
btn.Click += HandlePreviousClick;
}
btn = FindViewById<ImageButton>(Resource.Id.imgPlayingPlayPause);
if(btn != null)
{
btn.Click += HandlePlayClick;
}
btn = FindViewById<ImageButton>(Resource.Id.imgPlayingShuffle);
if(btn != null)
{
btn.Click += HandleShuffleClick;
}
OnModelLoaded();
}
void Handle_modelPropertyChanged (object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if(_uiActions.ContainsKey(e.PropertyName))
{
RunOnUiThread(() => _uiActions[e.PropertyName].Invoke());
}
}
protected virtual void OnModelLoaded()
{
}
void DisplayMessage()
{
if(!string.IsNullOrEmpty(_model.UserMessage))
{
Toast.MakeText(this, _model.UserMessage, ToastLength.Long).Show();
_model.UserMessage = null;
}
}
void UpdateArt()
{
if(_currentAlbumArt != null)
{
_currentAlbumArt.Recycle();
_currentAlbumArt.Dispose();
}
if(_model.AlbumArtStream != null)
{
Console.WriteLine ("Change Art");
_currentAlbumArt = Android.Graphics.BitmapFactory.DecodeByteArray(_model.AlbumArtStream.ToArray(), 0, (int)_model.AlbumArtStream.Length);
FindViewById<ImageView>(Resource.Id.imgPlayingAlbumArt).SetImageBitmap(_currentAlbumArt);
}
}
void UpdateNextButton()
{
var view = FindViewById<ImageButton>(Resource.Id.imgPlayingNext);
if(view != null){
if(_model.NextRequested)
{
view.SetImageDrawable(Resources.GetDrawable(Resource.Drawable.ic_media_next_invert));
}
else
{
view.SetImageDrawable(Resources.GetDrawable(Resource.Drawable.ic_media_next));
}
}
}
void UpdatePreviousButton()
{
var view = FindViewById<ImageButton>(Resource.Id.imgPlayingPrevious);
if(view != null){
if(_model.PreviousRequested)
{
view.SetImageDrawable(Resources.GetDrawable(Resource.Drawable.ic_media_previous_invert));
}
else
{
view.SetImageDrawable(Resources.GetDrawable(Resource.Drawable.ic_media_previous));
}
}
}
void UpdatePlayPauseButton()
{
if(_model.IsPlaying)
{
FindViewById<ImageButton>(Resource.Id.imgPlayingPlayPause).SetImageDrawable(Resources.GetDrawable(Resource.Drawable.ic_media_pause));
}
else
{
FindViewById<ImageButton>(Resource.Id.imgPlayingPlayPause).SetImageDrawable(Resources.GetDrawable(Resource.Drawable.ic_media_play));
}
}
void UpdateShuffleButton()
{
var img = FindViewById<ImageButton>(Resource.Id.imgPlayingShuffle);
if(img != null){
if(_model.Shuffling)
{
img.SetImageDrawable(Resources.GetDrawable(Resource.Drawable.ic_menu_shuffle_invert));
}
else
{
img.SetImageDrawable(Resources.GetDrawable(Resource.Drawable.ic_menu_shuffle));
}
}
}
void HandleShuffleClick (object sender, EventArgs e)
{
Task.Factory.StartNew(() => _model.Shuffling = !_model.Shuffling);
}
void HandlePlayClick (object sender, EventArgs e)
{
Task.Factory.StartNew(() => _model.PlayPauseRequested = true);
}
void HandlePreviousClick (object sender, EventArgs e)
{
Task.Factory.StartNew(() => _model.PreviousRequested = true);
}
void HandleNextClick (object sender, EventArgs e)
{
Task.Factory.StartNew(() => _model.NextRequested = true);
}
void ModelDisposed(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if(e.PropertyName == AmpacheModel.IS_DISPOSED && _model.IsDisposed)
{
Finish();
}
}
public override bool OnCreateOptionsMenu (IMenu menu)
{
this.MenuInflater.Inflate(MenuId, menu);
return true;
}
public override bool OnOptionsItemSelected (IMenuItem item)
{
switch (item.ItemId)
{
case Resource.Id.configure:
StartActivity(typeof(ConfigurationActivity));
break;
case Resource.Id.fullscreen:
StartActivity(typeof(NowPlaying));
break;
case Resource.Id.albums:
StartActivity(typeof(AlbumLookupActivity));
break;
case Resource.Id.artists:
StartActivity(typeof(ArtistLookupActivity));
break;
case Resource.Id.playlists:
StartActivity(typeof(PlaylistLookupActivity));
break;
case Resource.Id.help:
var intent = new Intent(Intent.ActionView);
intent.SetData(Android.Net.Uri.Parse("https://github.com/jcwmoore/ampache-net/wiki/Android"));
StartActivity(intent);
break;
case Resource.Id.clearPlaylist:
Task.Factory.StartNew(() => _model.Playlist = new List<AmpacheSong>());
break;
case Resource.Id.search:
StartActivity(typeof(SongSearch));
break;
default:
// unknown
return false;
}
return true;
}
public override bool OnSearchRequested ()
{
StartActivity(typeof(SongSearch));
return true;
}
protected override void OnStop ()
{
base.OnStop ();
if(_model != null)
{
_model.PropertyChanged -= Handle_modelPropertyChanged;
}
}
protected override void OnDestroy ()
{
base.OnDestroy ();
Console.WriteLine ("Activity Destroyed");
ImageButton btn = FindViewById<ImageButton>(Resource.Id.imgPlayingNext);
if(btn != null)
{
btn.Click -= HandleNextClick;
}
btn = FindViewById<ImageButton>(Resource.Id.imgPlayingPrevious);
if(btn != null)
{
btn.Click -= HandlePreviousClick;
}
btn = FindViewById<ImageButton>(Resource.Id.imgPlayingPlayPause);
if(btn != null)
{
btn.Click -= HandlePlayClick;
}
btn = FindViewById<ImageButton>(Resource.Id.imgPlayingShuffle);
if(btn != null)
{
btn.Click -= HandleShuffleClick;
}
if (_currentAlbumArt != null)
{
_currentAlbumArt.Recycle ();
_currentAlbumArt.Dispose ();
_currentAlbumArt = null;
}
UnbindService(_connection);
_connection.Dispose();
_connection = null;
}
}
}
| |
using System;
using UnityEngine;
using UnityEngine.Rendering;
namespace UnityStandardAssets.CinematicEffects
{
[ExecuteInEditMode]
#if UNITY_5_4_OR_NEWER
[ImageEffectAllowedInSceneView]
#endif
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Image Effects/Cinematic/Screen Space Reflections")]
public class ScreenSpaceReflection : MonoBehaviour
{
public enum SSRResolution
{
High = 0,
Low = 2
}
public enum SSRReflectionBlendType
{
PhysicallyBased,
Additive
}
[Serializable]
public struct SSRSettings
{
[AttributeUsage(AttributeTargets.Field)]
public class LayoutAttribute : PropertyAttribute
{
}
[Layout]
public ReflectionSettings reflectionSettings;
[Layout]
public IntensitySettings intensitySettings;
[Layout]
public ScreenEdgeMask screenEdgeMask;
private static readonly SSRSettings s_Default = new SSRSettings
{
reflectionSettings = new ReflectionSettings
{
blendType = SSRReflectionBlendType.PhysicallyBased,
reflectionQuality = SSRResolution.High,
maxDistance = 100.0f,
iterationCount = 256,
stepSize = 3,
widthModifier = 0.5f,
reflectionBlur = 1.0f,
reflectBackfaces = true
},
intensitySettings = new IntensitySettings
{
reflectionMultiplier = 1.0f,
fadeDistance = 100.0f,
fresnelFade = 1.0f,
fresnelFadePower = 1.0f,
},
screenEdgeMask = new ScreenEdgeMask
{
intensity = 0.03f
}
};
public static SSRSettings defaultSettings
{
get
{
return s_Default;
}
}
}
[Serializable]
public struct IntensitySettings
{
[Tooltip("Nonphysical multiplier for the SSR reflections. 1.0 is physically based.")]
[Range(0.0f, 2.0f)]
public float reflectionMultiplier;
[Tooltip("How far away from the maxDistance to begin fading SSR.")]
[Range(0.0f, 1000.0f)]
public float fadeDistance;
[Tooltip("Amplify Fresnel fade out. Increase if floor reflections look good close to the surface and bad farther 'under' the floor.")]
[Range(0.0f, 1.0f)]
public float fresnelFade;
[Tooltip("Higher values correspond to a faster Fresnel fade as the reflection changes from the grazing angle.")]
[Range(0.1f, 10.0f)]
public float fresnelFadePower;
}
[Serializable]
public struct ReflectionSettings
{
// When enabled, we just add our reflections on top of the existing ones. This is physically incorrect, but several
// popular demos and games have taken this approach, and it does hide some artifacts.
[Tooltip("How the reflections are blended into the render.")]
public SSRReflectionBlendType blendType;
[Tooltip("Half resolution SSRR is much faster, but less accurate.")]
public SSRResolution reflectionQuality;
[Tooltip("Maximum reflection distance in world units.")]
[Range(0.1f, 300.0f)]
public float maxDistance;
/// REFLECTIONS
[Tooltip("Max raytracing length.")]
[Range(16, 1024)]
public int iterationCount;
[Tooltip("Log base 2 of ray tracing coarse step size. Higher traces farther, lower gives better quality silhouettes.")]
[Range(1, 16)]
public int stepSize;
[Tooltip("Typical thickness of columns, walls, furniture, and other objects that reflection rays might pass behind.")]
[Range(0.01f, 10.0f)]
public float widthModifier;
[Tooltip("Blurriness of reflections.")]
[Range(0.1f, 8.0f)]
public float reflectionBlur;
[Tooltip("Enable for a performance gain in scenes where most glossy objects are horizontal, like floors, water, and tables. Leave on for scenes with glossy vertical objects.")]
public bool reflectBackfaces;
}
[Serializable]
public struct ScreenEdgeMask
{
[Tooltip("Higher = fade out SSRR near the edge of the screen so that reflections don't pop under camera motion.")]
[Range(0.0f, 1.0f)]
public float intensity;
}
[SerializeField]
public SSRSettings settings = SSRSettings.defaultSettings;
///////////// Unexposed Variables //////////////////
[Tooltip("Enable to limit the effect a few bright pixels can have on rougher surfaces")]
private bool highlightSuppression = false;
[Tooltip("Enable to allow rays to pass behind objects. This can lead to more screen-space reflections, but the reflections are more likely to be wrong.")]
private bool traceBehindObjects = true;
[Tooltip("Enable to force more surfaces to use reflection probes if you see streaks on the sides of objects or bad reflections of their backs.")]
private bool treatBackfaceHitAsMiss = false;
[Tooltip("Drastically improves reflection reconstruction quality at the expense of some performance.")]
private bool bilateralUpsample = true;
///////////// Unexposed Variables //////////////////
[SerializeField]
private Shader m_Shader;
public Shader shader
{
get
{
if (m_Shader == null)
m_Shader = Shader.Find("Hidden/ScreenSpaceReflection");
return m_Shader;
}
}
private Material m_Material;
public Material material
{
get
{
if (m_Material == null)
m_Material = ImageEffectHelper.CheckShaderAndCreateMaterial(shader);
return m_Material;
}
}
private Camera m_Camera;
public Camera camera_
{
get
{
if (m_Camera == null)
m_Camera = GetComponent<Camera>();
return m_Camera;
}
}
private CommandBuffer m_CommandBuffer;
private static int kNormalAndRoughnessTexture;
private static int kHitPointTexture;
private static int[] kReflectionTextures;
private static int kFilteredReflections;
private static int kBlurTexture;
private static int kFinalReflectionTexture;
private static int kTempTexture;
private static int kRayStepSize;
private static int kAdditiveReflection;
private static int kBilateralUpsampling;
private static int kTreatBackfaceHitAsMiss;
private static int kAllowBackwardsRays;
private static int kTraceBehindObjects;
private static int kMaxSteps;
private static int kFullResolutionFiltering;
private static int kHalfResolution;
private static int kHighlightSuppression;
private static int kPixelsPerMeterAtOneMeter;
private static int kScreenEdgeFading;
private static int kReflectionBlur;
private static int kMaxRayTraceDistance;
private static int kFadeDistance;
private static int kLayerThickness;
private static int kSSRMultiplier;
private static int kFresnelFade;
private static int kFresnelFadePower;
private static int kReflectionBufferSize;
private static int kScreenSize;
private static int kInvScreenSize;
private static int kProjInfo;
private static int kCameraClipInfo;
private static int kProjectToPixelMatrix;
private static int kWorldToCameraMatrix;
private static int kCameraToWorldMatrix;
private static int kAxis;
private static int kCurrentMipLevel;
// Shader pass indices used by the effect
private enum PassIndex
{
RayTraceStep = 0,
CompositeFinal = 1,
Blur = 2,
CompositeSSR = 3,
MinMipGeneration = 4,
HitPointToReflections = 5,
BilateralKeyPack = 6,
BlitDepthAsCSZ = 7,
PoissonBlur = 8,
}
private void Awake()
{
kReflectionTextures = new int[5];
kNormalAndRoughnessTexture = Shader.PropertyToID("_NormalAndRoughnessTexture");
kHitPointTexture = Shader.PropertyToID("_HitPointTexture");
kReflectionTextures[0] = Shader.PropertyToID("_ReflectionTexture0");
kReflectionTextures[1] = Shader.PropertyToID("_ReflectionTexture1");
kReflectionTextures[2] = Shader.PropertyToID("_ReflectionTexture2");
kReflectionTextures[3] = Shader.PropertyToID("_ReflectionTexture3");
kReflectionTextures[4] = Shader.PropertyToID("_ReflectionTexture4");
kBlurTexture = Shader.PropertyToID("_BlurTexture");
kFilteredReflections = Shader.PropertyToID("_FilteredReflections");
kFinalReflectionTexture = Shader.PropertyToID("_FinalReflectionTexture");
kTempTexture = Shader.PropertyToID("_TempTexture");
kRayStepSize = Shader.PropertyToID("_RayStepSize");
kAdditiveReflection = Shader.PropertyToID("_AdditiveReflection");
kBilateralUpsampling = Shader.PropertyToID("_BilateralUpsampling");
kTreatBackfaceHitAsMiss = Shader.PropertyToID("_TreatBackfaceHitAsMiss");
kAllowBackwardsRays = Shader.PropertyToID("_AllowBackwardsRays");
kTraceBehindObjects = Shader.PropertyToID("_TraceBehindObjects");
kMaxSteps = Shader.PropertyToID("_MaxSteps");
kFullResolutionFiltering = Shader.PropertyToID("_FullResolutionFiltering");
kHalfResolution = Shader.PropertyToID("_HalfResolution");
kHighlightSuppression = Shader.PropertyToID("_HighlightSuppression");
kPixelsPerMeterAtOneMeter = Shader.PropertyToID("_PixelsPerMeterAtOneMeter");
kScreenEdgeFading = Shader.PropertyToID("_ScreenEdgeFading");
kReflectionBlur = Shader.PropertyToID("_ReflectionBlur");
kMaxRayTraceDistance = Shader.PropertyToID("_MaxRayTraceDistance");
kFadeDistance = Shader.PropertyToID("_FadeDistance");
kLayerThickness = Shader.PropertyToID("_LayerThickness");
kSSRMultiplier = Shader.PropertyToID("_SSRMultiplier");
kFresnelFade = Shader.PropertyToID("_FresnelFade");
kFresnelFadePower = Shader.PropertyToID("_FresnelFadePower");
kReflectionBufferSize = Shader.PropertyToID("_ReflectionBufferSize");
kScreenSize = Shader.PropertyToID("_ScreenSize");
kInvScreenSize = Shader.PropertyToID("_InvScreenSize");
kProjInfo = Shader.PropertyToID("_ProjInfo");
kCameraClipInfo = Shader.PropertyToID("_CameraClipInfo");
kProjectToPixelMatrix = Shader.PropertyToID("_ProjectToPixelMatrix");
kWorldToCameraMatrix = Shader.PropertyToID("_WorldToCameraMatrix");
kCameraToWorldMatrix = Shader.PropertyToID("_CameraToWorldMatrix");
kAxis = Shader.PropertyToID("_Axis");
kCurrentMipLevel = Shader.PropertyToID("_CurrentMipLevel");
}
private void OnEnable()
{
if (!ImageEffectHelper.IsSupported(shader, false, true, this))
{
enabled = false;
return;
}
camera_.depthTextureMode |= DepthTextureMode.Depth;
}
void OnDisable()
{
if (m_Material)
DestroyImmediate(m_Material);
m_Material = null;
if (camera_ != null)
{
if (m_CommandBuffer != null)
{
camera_.RemoveCommandBuffer(CameraEvent.AfterFinalPass, m_CommandBuffer);
}
m_CommandBuffer = null;
}
}
#if UNITY_EDITOR
void OnValidate()
{
if (camera_ != null)
{
if (m_CommandBuffer != null)
{
camera_.RemoveCommandBuffer(CameraEvent.AfterFinalPass, m_CommandBuffer);
}
m_CommandBuffer = null;
}
}
#endif
// [ImageEffectOpaque]
public void OnPreRender()
{
if (material == null)
{
return;
}
else if (Camera.current.actualRenderingPath != RenderingPath.DeferredShading)
{
return;
}
int downsampleAmount = (settings.reflectionSettings.reflectionQuality == SSRResolution.High) ? 1 : 2;
var rtW = camera_.pixelWidth / downsampleAmount;
var rtH = camera_.pixelHeight / downsampleAmount;
float sWidth = camera_.pixelWidth;
float sHeight = camera_.pixelHeight;
float sx = sWidth / 2.0f;
float sy = sHeight / 2.0f;
const int maxMip = 5;
RenderTextureFormat intermediateFormat = camera_.allowHDR ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32;
material.SetInt(kRayStepSize, settings.reflectionSettings.stepSize);
material.SetInt(kAdditiveReflection, settings.reflectionSettings.blendType == SSRReflectionBlendType.Additive ? 1 : 0);
material.SetInt(kBilateralUpsampling, bilateralUpsample ? 1 : 0);
material.SetInt(kTreatBackfaceHitAsMiss, treatBackfaceHitAsMiss ? 1 : 0);
material.SetInt(kAllowBackwardsRays, settings.reflectionSettings.reflectBackfaces ? 1 : 0);
material.SetInt(kTraceBehindObjects, traceBehindObjects ? 1 : 0);
material.SetInt(kMaxSteps, settings.reflectionSettings.iterationCount);
material.SetInt(kFullResolutionFiltering, 0);
material.SetInt(kHalfResolution, (settings.reflectionSettings.reflectionQuality != SSRResolution.High) ? 1 : 0);
material.SetInt(kHighlightSuppression, highlightSuppression ? 1 : 0);
/** The height in pixels of a 1m object if viewed from 1m away. */
float pixelsPerMeterAtOneMeter = sWidth / (-2.0f * (float)(Math.Tan(camera_.fieldOfView / 180.0 * Math.PI * 0.5)));
material.SetFloat(kPixelsPerMeterAtOneMeter, pixelsPerMeterAtOneMeter);
material.SetFloat(kScreenEdgeFading, settings.screenEdgeMask.intensity);
material.SetFloat(kReflectionBlur, settings.reflectionSettings.reflectionBlur);
material.SetFloat(kMaxRayTraceDistance, settings.reflectionSettings.maxDistance);
material.SetFloat(kFadeDistance, settings.intensitySettings.fadeDistance);
material.SetFloat(kLayerThickness, settings.reflectionSettings.widthModifier);
material.SetFloat(kSSRMultiplier, settings.intensitySettings.reflectionMultiplier);
material.SetFloat(kFresnelFade, settings.intensitySettings.fresnelFade);
material.SetFloat(kFresnelFadePower, settings.intensitySettings.fresnelFadePower);
Matrix4x4 P = camera_.projectionMatrix;
Vector4 projInfo = new Vector4
((-2.0f / (sWidth * P[0])),
(-2.0f / (sHeight * P[5])),
((1.0f - P[2]) / P[0]),
((1.0f + P[6]) / P[5]));
Vector3 cameraClipInfo = (float.IsPositiveInfinity(camera_.farClipPlane)) ?
new Vector3(camera_.nearClipPlane, -1.0f, 1.0f) :
new Vector3(camera_.nearClipPlane * camera_.farClipPlane, camera_.nearClipPlane - camera_.farClipPlane, camera_.farClipPlane);
material.SetVector(kReflectionBufferSize, new Vector2(rtW, rtH));
material.SetVector(kScreenSize, new Vector2(sWidth, sHeight));
material.SetVector(kInvScreenSize, new Vector2((float)(1.0f / sWidth), (float)(1.0f / sHeight)));
material.SetVector(kProjInfo, projInfo); // used for unprojection
material.SetVector(kCameraClipInfo, cameraClipInfo);
Matrix4x4 warpToScreenSpaceMatrix = new Matrix4x4();
warpToScreenSpaceMatrix.SetRow(0, new Vector4(sx, 0.0f, 0.0f, sx));
warpToScreenSpaceMatrix.SetRow(1, new Vector4(0.0f, sy, 0.0f, sy));
warpToScreenSpaceMatrix.SetRow(2, new Vector4(0.0f, 0.0f, 1.0f, 0.0f));
warpToScreenSpaceMatrix.SetRow(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
Matrix4x4 projectToPixelMatrix = warpToScreenSpaceMatrix * P;
material.SetMatrix(kProjectToPixelMatrix, projectToPixelMatrix);
material.SetMatrix(kWorldToCameraMatrix, camera_.worldToCameraMatrix);
material.SetMatrix(kCameraToWorldMatrix, camera_.worldToCameraMatrix.inverse);
if (m_CommandBuffer == null)
{
m_CommandBuffer = new CommandBuffer();
m_CommandBuffer.name = "Screen Space Reflections";
// RGB: Normals, A: Roughness.
// Has the nice benefit of allowing us to control the filtering mode as well.
m_CommandBuffer.GetTemporaryRT(kNormalAndRoughnessTexture, -1, -1, 0, FilterMode.Point, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
m_CommandBuffer.GetTemporaryRT(kHitPointTexture, rtW, rtH, 0, FilterMode.Bilinear, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
for (int i = 0; i < maxMip; ++i)
{
// We explicitly interpolate during bilateral upsampling.
m_CommandBuffer.GetTemporaryRT(kReflectionTextures[i], rtW >> i, rtH >> i, 0, FilterMode.Bilinear, intermediateFormat);
}
m_CommandBuffer.GetTemporaryRT(kFilteredReflections, rtW, rtH, 0, bilateralUpsample ? FilterMode.Point : FilterMode.Bilinear, intermediateFormat);
m_CommandBuffer.GetTemporaryRT(kFinalReflectionTexture, rtW, rtH, 0, FilterMode.Point, intermediateFormat);
m_CommandBuffer.Blit(BuiltinRenderTextureType.CameraTarget, kNormalAndRoughnessTexture, material, (int)PassIndex.BilateralKeyPack);
m_CommandBuffer.Blit(BuiltinRenderTextureType.CameraTarget, kHitPointTexture, material, (int)PassIndex.RayTraceStep);
m_CommandBuffer.Blit(BuiltinRenderTextureType.CameraTarget, kFilteredReflections, material, (int)PassIndex.HitPointToReflections);
m_CommandBuffer.Blit(kFilteredReflections, kReflectionTextures[0], material, (int)PassIndex.PoissonBlur);
for (int i = 1; i < maxMip; ++i)
{
int inputTex = kReflectionTextures[i - 1];
int lowMip = i;
m_CommandBuffer.GetTemporaryRT(kBlurTexture, rtW >> lowMip, rtH >> lowMip, 0, FilterMode.Bilinear, intermediateFormat);
m_CommandBuffer.SetGlobalVector(kAxis, new Vector4(1.0f, 0.0f, 0.0f, 0.0f));
m_CommandBuffer.SetGlobalFloat(kCurrentMipLevel, i - 1.0f);
m_CommandBuffer.Blit(inputTex, kBlurTexture, material, (int)PassIndex.Blur);
m_CommandBuffer.SetGlobalVector(kAxis, new Vector4(0.0f, 1.0f, 0.0f, 0.0f));
inputTex = kReflectionTextures[i];
m_CommandBuffer.Blit(kBlurTexture, inputTex, material, (int)PassIndex.Blur);
m_CommandBuffer.ReleaseTemporaryRT(kBlurTexture);
}
m_CommandBuffer.Blit(kReflectionTextures[0], kFinalReflectionTexture, material, (int)PassIndex.CompositeSSR);
m_CommandBuffer.GetTemporaryRT(kTempTexture, camera_.pixelWidth, camera_.pixelHeight, 0, FilterMode.Bilinear, intermediateFormat);
m_CommandBuffer.Blit(BuiltinRenderTextureType.CameraTarget, kTempTexture, material, (int)PassIndex.CompositeFinal);
m_CommandBuffer.Blit(kTempTexture, BuiltinRenderTextureType.CameraTarget);
m_CommandBuffer.ReleaseTemporaryRT(kTempTexture);
camera_.AddCommandBuffer(CameraEvent.AfterFinalPass, m_CommandBuffer);
}
}
}
}
| |
using System;
namespace CH.Combinations.Benchmark
{
internal class Program
{
private static int _seconds = 2;
private static void DoBenchmarkEnumerator<T>(Combinations<T> combs)
{
int count = 0;
DateTime start = DateTime.UtcNow;
TimeSpan elapsed;
do
{
foreach (T[] t in combs)
{
count++;
if (count % 10000 == 0)
{
elapsed = DateTime.UtcNow - start;
if (elapsed.Ticks >= _seconds * TimeSpan.TicksPerSecond)
{
break;
}
}
}
elapsed = DateTime.UtcNow - start;
} while (elapsed.Ticks < _seconds * TimeSpan.TicksPerSecond);
double eps = ((double)count) / (elapsed.Seconds * 1000 + elapsed.Milliseconds) * 1000.0;
Console.WriteLine("{0:#,0} e in {1:0.000}s = {2:#,0} e/s", count, elapsed.Seconds + elapsed.Milliseconds / 1000.0, (int)eps);
}
private static void DoBenchmarkEnumerator(int n, int r, int percentChanceDuplicate)
{
int[] data = new int[n];
Random rand = new Random();
for (int i = 0; i < data.Length; i++)
{
if (rand.Next(100) < percentChanceDuplicate && i > 0)
{
data[i] = data[i - 1];
}
else
{
data[i] = i;
}
}
Combinations<int> combs = new Combinations<int>(data, r);
DoBenchmarkEnumerator(combs);
}
private static void Shuffle<T>(T[] data)
{
int n = data.Length;
Random r = new Random();
while (n > 1)
{
int idx = r.Next(n--);
T temp = data[n];
data[n] = data[idx];
data[idx] = temp;
}
}
private enum DatasetBenchmarkType
{
Sequential, Random
}
private static void DoBenchmarkDataset(int n, DatasetBenchmarkType type)
{
int[] data = new int[n];
for (int i = 0; i < data.Length; i++)
{
data[i] = i;
}
if (type == DatasetBenchmarkType.Random)
{
Shuffle(data);
}
int count = 0;
DateTime start = DateTime.UtcNow;
TimeSpan elapsed;
do
{
new ElementSet<int>(data);
count++;
elapsed = DateTime.UtcNow - start;
} while (elapsed.Ticks < _seconds * TimeSpan.TicksPerSecond);
double dsps = ((double)count) / (elapsed.Seconds * 1000 + elapsed.Milliseconds) * 1000.0;
Console.WriteLine("{0:#,0} ds in {1:0.000}s = {2:#,0} ds/s = {3:#,0} e/s", count, elapsed.Seconds + elapsed.Milliseconds / 1000.0, (int)dsps, (int)(dsps * n));
}
private static void Main(string[] args)
{
if (args.Length == 1)
{
_seconds = int.Parse(args[0]);
}
Console.WriteLine("Integer enumerator benchmarks (distinct):");
Console.Write("10C5 integers:\t\t");
DoBenchmarkEnumerator(10, 5, 0);
Console.Write("10C7 integers:\t\t");
DoBenchmarkEnumerator(10, 7, 0);
Console.Write("10C3 integers:\t\t");
DoBenchmarkEnumerator(10, 3, 0);
Console.Write("100C50 integers:\t");
DoBenchmarkEnumerator(100, 50, 0);
Console.Write("100C70 integers:\t");
DoBenchmarkEnumerator(100, 70, 0);
Console.Write("100C30 integers:\t");
DoBenchmarkEnumerator(100, 30, 0);
Console.Write("1000C500 integers:\t");
DoBenchmarkEnumerator(1000, 500, 0);
Console.Write("1000C700 integers:\t");
DoBenchmarkEnumerator(1000, 700, 0);
Console.Write("1000C300 integers:\t");
DoBenchmarkEnumerator(1000, 300, 0);
Console.WriteLine();
Console.WriteLine("Integer enumerator benchmarks (10% duplicates):");
Console.Write("10C5 integers:\t\t");
DoBenchmarkEnumerator(10, 5, 10);
Console.Write("10C7 integers:\t\t");
DoBenchmarkEnumerator(10, 7, 10);
Console.Write("10C3 integers:\t\t");
DoBenchmarkEnumerator(10, 3, 10);
Console.Write("100C50 integers:\t");
DoBenchmarkEnumerator(100, 50, 10);
Console.Write("100C70 integers:\t");
DoBenchmarkEnumerator(100, 70, 10);
Console.Write("100C30 integers:\t");
DoBenchmarkEnumerator(100, 30, 10);
Console.Write("1000C500 integers:\t");
DoBenchmarkEnumerator(1000, 500, 10);
Console.Write("1000C700 integers:\t");
DoBenchmarkEnumerator(1000, 700, 10);
Console.Write("1000C300 integers:\t");
DoBenchmarkEnumerator(1000, 300, 10);
Console.WriteLine();
Console.WriteLine("Integer enumerator benchmarks (25% duplicates):");
Console.Write("10C5 integers:\t\t");
DoBenchmarkEnumerator(10, 5, 25);
Console.Write("10C7 integers:\t\t");
DoBenchmarkEnumerator(10, 7, 25);
Console.Write("10C3 integers:\t\t");
DoBenchmarkEnumerator(10, 3, 25);
Console.Write("100C50 integers:\t");
DoBenchmarkEnumerator(100, 50, 25);
Console.Write("100C70 integers:\t");
DoBenchmarkEnumerator(100, 70, 25);
Console.Write("100C30 integers:\t");
DoBenchmarkEnumerator(100, 30, 25);
Console.Write("1000C500 integers:\t");
DoBenchmarkEnumerator(1000, 500, 25);
Console.Write("1000C700 integers:\t");
DoBenchmarkEnumerator(1000, 700, 25);
Console.Write("1000C300 integers:\t");
DoBenchmarkEnumerator(1000, 300, 25);
Console.WriteLine();
Console.WriteLine("Integer enumerator benchmarks (60% duplicates):");
Console.Write("10C5 integers:\t\t");
DoBenchmarkEnumerator(10, 5, 60);
Console.Write("10C7 integers:\t\t");
DoBenchmarkEnumerator(10, 7, 60);
Console.Write("10C3 integers:\t\t");
DoBenchmarkEnumerator(10, 3, 60);
Console.Write("100C50 integers:\t");
DoBenchmarkEnumerator(100, 50, 60);
Console.Write("100C70 integers:\t");
DoBenchmarkEnumerator(100, 70, 60);
Console.Write("100C30 integers:\t");
DoBenchmarkEnumerator(100, 30, 60);
Console.Write("1000C500 integers:\t");
DoBenchmarkEnumerator(1000, 500, 60);
Console.Write("1000C700 integers:\t");
DoBenchmarkEnumerator(1000, 700, 60);
Console.Write("1000C300 integers:\t");
DoBenchmarkEnumerator(1000, 300, 60);
Console.WriteLine();
Console.WriteLine("Integer dataset preparation benchmarks (sequential):");
Console.Write("10 integers:\t");
DoBenchmarkDataset(10, DatasetBenchmarkType.Sequential);
Console.Write("100 integers:\t");
DoBenchmarkDataset(100, DatasetBenchmarkType.Sequential);
Console.Write("1000 integers:\t");
DoBenchmarkDataset(1000, DatasetBenchmarkType.Sequential);
Console.Write("10000 integers:\t");
DoBenchmarkDataset(10000, DatasetBenchmarkType.Sequential);
Console.WriteLine();
Console.WriteLine("Integer dataset preparation benchmarks (random):");
Console.Write("10 integers:\t");
DoBenchmarkDataset(10, DatasetBenchmarkType.Random);
Console.Write("100 integers:\t");
DoBenchmarkDataset(100, DatasetBenchmarkType.Random);
Console.Write("1000 integers:\t");
DoBenchmarkDataset(1000, DatasetBenchmarkType.Random);
Console.Write("10000 integers:\t");
DoBenchmarkDataset(10000, DatasetBenchmarkType.Random);
Console.WriteLine("Press a key to exit:");
Console.ReadKey();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Orleans.Concurrency;
using Orleans.Runtime;
using Orleans.Serialization;
namespace Orleans.Streams
{
[Serializable]
[Immutable]
internal class StreamImpl<T> : IStreamIdentity, IAsyncStream<T>, IStreamControl, ISerializable, IOnDeserialized
{
private readonly StreamId streamId;
private readonly bool isRewindable;
[NonSerialized]
private IInternalStreamProvider provider;
[NonSerialized]
private volatile IInternalAsyncBatchObserver<T> producerInterface;
[NonSerialized]
private IInternalAsyncObservable<T> consumerInterface;
[NonSerialized]
private readonly object initLock; // need the lock since the same code runs in the provider on the client and in the silo.
[NonSerialized]
private IRuntimeClient runtimeClient;
internal StreamId StreamId { get { return streamId; } }
public bool IsRewindable { get { return isRewindable; } }
public Guid Guid { get { return streamId.Guid; } }
public string Namespace { get { return streamId.Namespace; } }
public string ProviderName { get { return streamId.ProviderName; } }
// IMPORTANT: This constructor needs to be public for Json deserialization to work.
public StreamImpl()
{
initLock = new object();
}
internal StreamImpl(StreamId streamId, IInternalStreamProvider provider, bool isRewindable, IRuntimeClient runtimeClient)
{
if (null == streamId)
throw new ArgumentNullException(nameof(streamId));
if (null == provider)
throw new ArgumentNullException(nameof(provider));
if (null == runtimeClient)
throw new ArgumentNullException(nameof(runtimeClient));
this.streamId = streamId;
this.provider = provider;
producerInterface = null;
consumerInterface = null;
initLock = new object();
this.isRewindable = isRewindable;
this.runtimeClient = runtimeClient;
}
public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncObserver<T> observer)
{
return GetConsumerInterface().SubscribeAsync(observer, null);
}
public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncObserver<T> observer, StreamSequenceToken token,
StreamFilterPredicate filterFunc = null,
object filterData = null)
{
return GetConsumerInterface().SubscribeAsync(observer, token, filterFunc, filterData);
}
public async Task Cleanup(bool cleanupProducers, bool cleanupConsumers)
{
// Cleanup producers
if (cleanupProducers && producerInterface != null)
{
await producerInterface.Cleanup();
producerInterface = null;
}
// Cleanup consumers
if (cleanupConsumers && consumerInterface != null)
{
await consumerInterface.Cleanup();
consumerInterface = null;
}
}
public Task OnNextAsync(T item, StreamSequenceToken token = null)
{
return GetProducerInterface().OnNextAsync(item, token);
}
public Task OnNextBatchAsync(IEnumerable<T> batch, StreamSequenceToken token = null)
{
return GetProducerInterface().OnNextBatchAsync(batch, token);
}
public Task OnCompletedAsync()
{
return GetProducerInterface().OnCompletedAsync();
}
public Task OnErrorAsync(Exception ex)
{
return GetProducerInterface().OnErrorAsync(ex);
}
internal Task<StreamSubscriptionHandle<T>> ResumeAsync(
StreamSubscriptionHandle<T> handle,
IAsyncObserver<T> observer,
StreamSequenceToken token)
{
return GetConsumerInterface().ResumeAsync(handle, observer, token);
}
public Task<IList<StreamSubscriptionHandle<T>>> GetAllSubscriptionHandles()
{
return GetConsumerInterface().GetAllSubscriptions();
}
internal Task UnsubscribeAsync(StreamSubscriptionHandle<T> handle)
{
return GetConsumerInterface().UnsubscribeAsync(handle);
}
internal IAsyncBatchObserver<T> GetProducerInterface()
{
if (producerInterface != null) return producerInterface;
lock (initLock)
{
if (producerInterface != null)
return producerInterface;
if (provider == null)
provider = GetStreamProvider();
producerInterface = provider.GetProducerInterface<T>(this);
}
return producerInterface;
}
internal IInternalAsyncObservable<T> GetConsumerInterface()
{
if (consumerInterface == null)
{
lock (initLock)
{
if (consumerInterface == null)
{
if (provider == null)
provider = GetStreamProvider();
consumerInterface = provider.GetConsumerInterface<T>(this);
}
}
}
return consumerInterface;
}
private IInternalStreamProvider GetStreamProvider()
{
return this.runtimeClient.ServiceProvider.GetRequiredServiceByName<IStreamProvider>(streamId.ProviderName) as IInternalStreamProvider;
}
#region IComparable<IAsyncStream<T>> Members
public int CompareTo(IAsyncStream<T> other)
{
var o = other as StreamImpl<T>;
return o == null ? 1 : streamId.CompareTo(o.streamId);
}
#endregion
#region IEquatable<IAsyncStream<T>> Members
public virtual bool Equals(IAsyncStream<T> other)
{
var o = other as StreamImpl<T>;
return o != null && streamId.Equals(o.streamId);
}
#endregion
public override bool Equals(object obj)
{
var o = obj as StreamImpl<T>;
return o != null && streamId.Equals(o.streamId);
}
public override int GetHashCode()
{
return streamId.GetHashCode();
}
public override string ToString()
{
return streamId.ToString();
}
#region ISerializable Members
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// Use the AddValue method to specify serialized values.
info.AddValue("StreamId", streamId, typeof(StreamId));
info.AddValue("IsRewindable", isRewindable, typeof(bool));
}
// The special constructor is used to deserialize values.
protected StreamImpl(SerializationInfo info, StreamingContext context)
{
// Reset the property value using the GetValue method.
streamId = (StreamId)info.GetValue("StreamId", typeof(StreamId));
isRewindable = info.GetBoolean("IsRewindable");
initLock = new object();
var serializerContext = context.Context as ISerializerContext;
((IOnDeserialized)this).OnDeserialized(serializerContext);
}
void IOnDeserialized.OnDeserialized(ISerializerContext context)
{
this.runtimeClient = context?.AdditionalContext as IRuntimeClient;
}
#endregion
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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.Globalization;
using System.Text;
using System.Web;
using ASC.Blogs.Core;
using ASC.Blogs.Core.Domain;
using ASC.Blogs.Core.Security;
using ASC.Core;
using ASC.Core.Users;
using ASC.Web.Community.Modules.Blogs.Core.Resources;
using ASC.Web.Community.Product;
using ASC.Web.Core.Utility.Skins;
using ASC.Web.Studio.Controls.Common;
using ASC.Web.Studio.Utility;
namespace ASC.Web.Community.Blogs
{
public partial class Default : BasePage
{
public long blogsCount { get; set; }
public int BlogsPageSize
{
get { return ViewState["PageSize"] != null ? Convert.ToInt32(ViewState["PageSize"]) : 20; }
set { ViewState["PageSize"] = value; }
}
#region Properties
private int SelectedPage
{
get
{
int result;
Int32.TryParse(Request.QueryString["page"], out result);
if (result <= 0)
result = 1;
return result;
}
}
public string GroupID
{
get { return Request.QueryString["groupID"]; }
}
public string UserID
{
get { return Request.QueryString["userID"]; }
}
public string TagName
{
get { return Request.QueryString["tagName"]; }
}
public string Search
{
get { return Request.QueryString["search"]; }
}
public List<Tuple<Post, int>> PostsAndCommentsCount { get; set; }
#endregion
#region Methods
protected override void PageLoad()
{
PostsAndCommentsCount = new List<Tuple<Post, int>>();
BlogsPageSize = string.IsNullOrEmpty(Request["size"]) ? 20 : Convert.ToInt32(Request["size"]);
Guid? userId = null;
if (!String.IsNullOrEmpty(UserID))
{
userId = Guid.NewGuid();
try
{
userId = new Guid(UserID);
}
catch
{
}
}
var postsQuery = new PostsQuery();
if (userId.HasValue)
{
postsQuery.SetUser(userId.Value);
}
else if (!String.IsNullOrEmpty(TagName))
{
postsQuery.SetTag(TagName);
}
else if (!String.IsNullOrEmpty(Search))
{
postsQuery.SetSearch(Search);
}
if (!IsPostBack)
{
var engine = GetEngine();
FillPosts(postsQuery, engine);
}
Title = HeaderStringHelper.GetPageTitle(BlogsResource.AddonName);
var jsResource = new StringBuilder();
jsResource.Append(String.Format("ASC.Community.BlogsJSResource = {{}};ASC.Community.BlogsJSResource.ReadMoreLink = \"{0}\";", BlogsResource.ReadMoreLink));
jsResource.Append("jq('#tableForNavigation select').val(" + BlogsPageSize + ").change(function(evt) {changeBlogsCountOfRows(this.value);}).tlCombobox();");
Page.RegisterInlineScript(jsResource.ToString(), true);
}
protected string QueryString(string excludeParamList)
{
var queryString = "&" + Request.QueryString.ToString();
foreach (var excludeParamName in excludeParamList.Split(','))
{
var startPos = queryString.IndexOf("&" + excludeParamName + "=");
if (startPos != -1)
{
var endPos = queryString.IndexOf("&", startPos + 1);
if (endPos == -1)
{
queryString = queryString.Remove(startPos, queryString.Length - startPos);
}
else
{
queryString = queryString.Remove(startPos, endPos - startPos);
}
}
}
return queryString.Trim('&');
}
private void FillPosts(PostsQuery query, BlogsEngine engine)
{
query
.SetOffset((SelectedPage - 1) * BlogsPageSize)
.SetCount(BlogsPageSize);
SetTotalPostsCount(engine.GetPostsCount(query));
var posts = engine.SelectPosts(query);
FillSelectedPage(posts, engine);
}
private void FillSelectedPage(List<Post> posts, BlogsEngine engine)
{
var currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
if (posts == null || posts.Count == 0)
{
var emptyScreenControl = new EmptyScreenControl
{
ImgSrc = WebImageSupplier.GetAbsoluteWebPath("blog_icon.png", ASC.Blogs.Core.Constants.ModuleId),
Header = BlogsResource.EmptyScreenBlogCaption,
Describe = currentUser.IsVisitor() ? BlogsResource.EmptyScreenBlogTextVisitor : BlogsResource.EmptyScreenBlogText
};
if (CommunitySecurity.CheckPermissions(new PersonalBlogSecObject(currentUser), ASC.Blogs.Core.Constants.Action_AddPost)
&& string.IsNullOrEmpty(UserID) && string.IsNullOrEmpty(Search))
{
emptyScreenControl.ButtonHTML = String.Format("<a class='link underline blue plus' href='AddBlog.aspx'>{0}</a>", BlogsResource.EmptyScreenBlogLink);
}
placeContent.Controls.Add(emptyScreenControl);
return;
}
PostsAndCommentsCount = engine.GetPostsCommentsCount(posts);
}
#endregion
private void SetTotalPostsCount(int count)
{
var pageNavigator = new PageNavigator
{
PageUrl = string.Format(
CultureInfo.CurrentCulture,
"{0}?{1}",
VirtualPathUtility.ToAbsolute("~/Products/Community/Modules/Blogs/"),
QueryString("page")
//BlogsPageSize
),
//"./" + "?" + QueryString("page"),
CurrentPageNumber = SelectedPage,
EntryCountOnPage = BlogsPageSize,
VisiblePageCount = 5,
ParamName = "page",
EntryCount = count
};
blogsCount = count;
pageNavigatorHolder.Controls.Add(pageNavigator);
}
}
}
| |
// 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 AddSubtractSingle()
{
var test = new SimpleBinaryOpTest__AddSubtractSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddSubtractSingle
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Single);
private const int Op2ElementCount = VectorSize / sizeof(Single);
private const int RetElementCount = VectorSize / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector256<Single> _clsVar1;
private static Vector256<Single> _clsVar2;
private Vector256<Single> _fld1;
private Vector256<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable;
static SimpleBinaryOpTest__AddSubtractSingle()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__AddSubtractSingle()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], VectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx.AddSubtract(
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx.AddSubtract(
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx.AddSubtract(
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx).GetMethod(nameof(Avx.AddSubtract), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx).GetMethod(nameof(Avx.AddSubtract), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx).GetMethod(nameof(Avx.AddSubtract), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx.AddSubtract(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr);
var result = Avx.AddSubtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr));
var result = Avx.AddSubtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr));
var result = Avx.AddSubtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AddSubtractSingle();
var result = Avx.AddSubtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx.AddSubtract(_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(Vector256<Single> left, Vector256<Single> right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, 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 = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
if (BitConverter.SingleToInt32Bits(left[0] - right[0]) != BitConverter.SingleToInt32Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (((i % 2 != 0) && (BitConverter.SingleToInt32Bits(left[i] + right[i]) != BitConverter.SingleToInt32Bits(result[i]))) || ((i % 2 == 0) && (BitConverter.SingleToInt32Bits(left[i] - right[i]) != BitConverter.SingleToInt32Bits(result[i]))))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.AddSubtract)}<Single>(Vector256<Single>, Vector256<Single>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using VsChromium.Core.Linq;
using VsChromium.Core.Logging;
namespace VsChromium.Core.Collections {
public static class ArrayUtilities {
private const int SmallArrayThreshold = 200;
public class EmptyList<T> {
public static IList<T> Instance = new List<T>().ToReadOnlyCollection();
}
public static ArrayDiffsResult<T> BuildArrayDiffs<T>(IList<T> leftList, IList<T> rightList) {
return BuildArrayDiffs(leftList, rightList, null);
}
public static ArrayDiffsResult<T> BuildArrayDiffs<T>(
IList<T> leftList,
IList<T> rightList,
IEqualityComparer<T> comparer) {
comparer = comparer ?? EqualityComparer<T>.Default;
var result = ProcessSpecialCases(leftList, rightList, comparer);
if (result != null) {
return result.Value;
}
bool smallList = leftList.Count + rightList.Count <= SmallArrayThreshold;
var result2 = smallList
? BuildArrayDiffsForSmallArrays(leftList, rightList, comparer)
: BuildArrayDiffsForLargeArrays(leftList, rightList, comparer);
// Quick check assumption about identity is verified: both list should not
// contain duplicate elements.
Invariants.Assert(
result2.LeftOnlyItems.Count +
result2.RightOnlyItems.Count +
result2.CommonItems.Count * 2 ==
leftList.Count + rightList.Count);
return result2;
}
private static class EmptyResult<T> {
public static ArrayDiffsResult<T> Instance = new ArrayDiffsResult<T>(
EmptyList<T>.Instance,
EmptyList<T>.Instance,
EmptyList<LeftRightItemPair<T>>.Instance);
}
private static ArrayDiffsResult<T>? ProcessSpecialCases<T>(IList<T> leftList, IList<T> rightList, IEqualityComparer<T> comparer) {
if (leftList.Count == 0 && rightList.Count == 0) {
return EmptyResult<T>.Instance;
}
if (leftList.Count == 0) {
return new ArrayDiffsResult<T>(
EmptyList<T>.Instance,
rightList,
EmptyList<LeftRightItemPair<T>>.Instance);
}
if (rightList.Count == 0) {
return new ArrayDiffsResult<T>(
leftList,
EmptyList<T>.Instance,
EmptyList<LeftRightItemPair<T>>.Instance);
}
if (ListAreEqual(leftList, rightList, comparer)) {
var common = new LeftRightItemPair<T>[rightList.Count];
for (var i = 0; i < common.Length; i++) {
common[i] = new LeftRightItemPair<T>(leftList[i], rightList[i]);
}
return new ArrayDiffsResult<T>(EmptyList<T>.Instance, EmptyList<T>.Instance, common);
}
return null;
}
private static bool ListAreEqual<T>(IList<T> leftList, IList<T> rightList, IEqualityComparer<T> comparer) {
if (leftList.Count != rightList.Count)
return false;
for (var i = 0; i < leftList.Count; i++) {
if (!comparer.Equals(leftList[i], rightList[i]))
return false;
}
return true;
}
public static ArrayDiffsResult<T> BuildArrayDiffsForSmallArrays<T>(
IList<T> leftList,
IList<T> rightList) {
return BuildArrayDiffsForSmallArrays(leftList, rightList, null);
}
public static ArrayDiffsResult<T> BuildArrayDiffsForSmallArrays<T>(
IList<T> leftList,
IList<T> rightList,
IEqualityComparer<T> comparer) {
comparer = comparer ?? EqualityComparer<T>.Default;
var result = new ArrayDiffsResult<T>(
new List<T>(),
new List<T>(),
new List<LeftRightItemPair<T>>()
);
// Append left items, either unique or common with right items
foreach (var left in leftList) {
var index = ListIndexOf(rightList, left, comparer);
if (index >= 0) {
result.CommonItems.Add(new LeftRightItemPair<T>(left, rightList[index]));
} else {
result.LeftOnlyItems.Add(left);
}
}
// Append right items (unique ones only)
foreach (var right in rightList) {
var index = ListIndexOf(leftList, right, comparer);
if (index < 0) {
result.RightOnlyItems.Add(right);
}
}
return result;
}
public static ArrayDiffsResult<T> BuildArrayDiffsForLargeArrays<T>(
IList<T> leftList,
IList<T> rightList) {
return BuildArrayDiffsForLargeArrays(leftList, rightList, null);
}
public static ArrayDiffsResult<T> BuildArrayDiffsForLargeArrays<T>(
IList<T> leftList,
IList<T> rightList,
IEqualityComparer<T> comparer) {
comparer = comparer ?? EqualityComparer<T>.Default;
var result = new ArrayDiffsResult<T>(
new List<T>(),
new List<T>(),
new List<LeftRightItemPair<T>>()
);
// Build both map from item to item index.
var leftMap = new Dictionary<T, int>(leftList.Count, comparer);
leftList.ForAll((index, x) => leftMap.Add(x, index));
var rightMap = new Dictionary<T, int>(leftList.Count, comparer);
rightList.ForAll((index, x) => rightMap.Add(x, index));
// Append left items, either unique or common with right items
foreach (var left in leftList) {
var rightIndex = MapIndexOf(rightMap, left);
if (rightIndex >= 0) {
result.CommonItems.Add(new LeftRightItemPair<T>(left, rightList[rightIndex]));
} else {
result.LeftOnlyItems.Add(left);
}
}
// Append right items (unique ones only)
foreach (var right in rightList) {
var leftIndex = MapIndexOf(leftMap, right);
if (leftIndex < 0) {
result.RightOnlyItems.Add(right);
}
}
return result;
}
/// <summary>
/// Returns index of <paramref name="item"/> in <paramref name="items"/>
/// collection, using <paramref name="comparer"/> equality comparer. Returns
/// -1 if <paramref name="item"/> is not present.
/// </summary>
private static int ListIndexOf<T>(IList<T> items, T item, IEqualityComparer<T> comparer) {
for (var i = 0; i < items.Count; i++) {
if (comparer.Equals(items[i], item))
return i;
}
return -1;
}
private static int MapIndexOf<T>(IDictionary<T, int> items, T item) {
int result;
if (!items.TryGetValue(item, out result))
return -1;
Invariants.Assert(result >= 0);
return result;
}
public static void RemoveDuplicates<T>(IList<T> sortedList, Func<T, T, bool> comparer) {
if (sortedList.Count <= 1)
return;
var previousItem = sortedList[0];
for (var i = 1; i < sortedList.Count; ) {
var item = sortedList[i];
if (comparer(previousItem, item)) {
sortedList.RemoveAt(i);
continue;
}
previousItem = item;
i++;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Buffers;
using System.Diagnostics;
using System.Text;
using System.Text.Utf8;
namespace System.Text.Formatting {
// This whole API is very speculative, i.e. I am not sure I am happy with the design
// This API is trying to do composite formatting without boxing (or any other allocations).
// And because not all types in the platfrom implement IBufferFormattable (in particular built-in primitives don't),
// it needs to play some tricks with generic type parameters. But as you can see at the end of AppendUntyped, I am not sure how to tick the type system
// not never box.
public static class CompositeFormattingExtensions
{
public static void Format<TFormatter, T0>(this TFormatter formatter, string compositeFormat, T0 arg0) where TFormatter : ITextOutput
{
var reader = new CompositeFormatReader(compositeFormat);
while (true)
{
var segment = reader.Next();
if (segment == null) return;
if (segment.Value.Count == 0) // insertion point
{
if (segment.Value.Index == 0) formatter.AppendUntyped(arg0, segment.Value.Format);
else throw new Exception("invalid insertion point");
}
else // literal
{
formatter.Append(compositeFormat, segment.Value.Index, segment.Value.Count);
}
}
}
public static void Format<TFormatter, T0, T1>(this TFormatter formatter, string compositeFormat, T0 arg0, T1 arg1) where TFormatter : ITextOutput
{
var reader = new CompositeFormatReader(compositeFormat);
while (true)
{
var segment = reader.Next();
if (segment == null) return;
if (segment.Value.Count == 0) // insertion point
{
if (segment.Value.Index == 0) formatter.AppendUntyped(arg0, segment.Value.Format);
else if (segment.Value.Index == 1) formatter.AppendUntyped(arg1, segment.Value.Format);
else throw new Exception("invalid insertion point");
}
else // literal
{
formatter.Append(compositeFormat, segment.Value.Index, segment.Value.Count);
}
}
}
public static void Format<TFormatter, T0, T1, T2>(this TFormatter formatter, string compositeFormat, T0 arg0, T1 arg1, T2 arg2) where TFormatter : ITextOutput
{
var reader = new CompositeFormatReader(compositeFormat);
while (true)
{
var segment = reader.Next();
if (segment == null) return;
if (segment.Value.Count == 0) // insertion point
{
if (segment.Value.Index == 0) formatter.AppendUntyped(arg0, segment.Value.Format);
else if (segment.Value.Index == 1) formatter.AppendUntyped(arg1, segment.Value.Format);
else if (segment.Value.Index == 2) formatter.AppendUntyped(arg2, segment.Value.Format);
else throw new Exception("invalid insertion point");
}
else // literal
{
formatter.Append(compositeFormat, segment.Value.Index, segment.Value.Count);
}
}
}
public static void Format<TFormatter, T0, T1, T2, T3>(this TFormatter formatter, string compositeFormat, T0 arg0, T1 arg1, T2 arg2, T3 arg3) where TFormatter : ITextOutput
{
var reader = new CompositeFormatReader(compositeFormat);
while (true)
{
var segment = reader.Next();
if (segment == null) return;
if (segment.Value.Count == 0) // insertion point
{
if (segment.Value.Index == 0) formatter.AppendUntyped(arg0, segment.Value.Format);
else if (segment.Value.Index == 1) formatter.AppendUntyped(arg1, segment.Value.Format);
else if (segment.Value.Index == 2) formatter.AppendUntyped(arg2, segment.Value.Format);
else if (segment.Value.Index == 3) formatter.AppendUntyped(arg3, segment.Value.Format);
else throw new Exception("invalid insertion point");
}
else // literal
{
formatter.Append(compositeFormat, segment.Value.Index, segment.Value.Count);
}
}
}
public static void Format<TFormatter, T0, T1, T2, T3, T4>(this TFormatter formatter, string compositeFormat, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4) where TFormatter : ITextOutput
{
var reader = new CompositeFormatReader(compositeFormat);
while (true)
{
var segment = reader.Next();
if (segment == null) return;
if (segment.Value.Count == 0) // insertion point
{
if (segment.Value.Index == 0) formatter.AppendUntyped(arg0, segment.Value.Format);
else if (segment.Value.Index == 1) formatter.AppendUntyped(arg1, segment.Value.Format);
else if (segment.Value.Index == 2) formatter.AppendUntyped(arg2, segment.Value.Format);
else if (segment.Value.Index == 3) formatter.AppendUntyped(arg3, segment.Value.Format);
else if (segment.Value.Index == 4) formatter.AppendUntyped(arg4, segment.Value.Format);
else throw new Exception("invalid insertion point");
}
else // literal
{
formatter.Append(compositeFormat, segment.Value.Index, segment.Value.Count);
}
}
}
// TODO: this should be removed and an ability to append substrings should be added
static void Append<TFormatter>(this TFormatter formatter, string whole, int index, int count) where TFormatter : ITextOutput
{
var buffer = formatter.Buffer;
var maxBytes = count << 4; // this is the worst case, i.e. 4 bytes per char
while(buffer.Length < maxBytes)
{
formatter.Enlarge(maxBytes);
buffer = formatter.Buffer;
}
// this should be optimized using fixed pointer to substring, but I will wait with this till we design proper substring
var characters = whole.Slice(index, count);
int bytesWritten;
int charactersConsumed;
if (!formatter.Encoding.TextEncoder.TryEncode(characters, buffer, out charactersConsumed, out bytesWritten))
{
Debug.Assert(false, "this should never happen"); // because I pre-resized the buffer to 4 bytes per char at the top of this method.
}
formatter.Advance(bytesWritten);
}
static void AppendUntyped<TFormatter, T>(this TFormatter formatter, T value, TextFormat format) where TFormatter : ITextOutput
{
#region Built in types
var i32 = value as int?;
if (i32 != null)
{
formatter.Append(i32.Value, format);
return;
}
var i64 = value as long?;
if (i64 != null)
{
formatter.Append(i64.Value, format);
return;
}
var i16 = value as short?;
if (i16 != null)
{
formatter.Append(i16.Value, format);
return;
}
var b = value as byte?;
if (b != null)
{
formatter.Append(b.Value, format);
return;
}
var c = value as char?;
if (c != null)
{
formatter.Append(c.Value);
return;
}
var u32 = value as uint?;
if (u32 != null)
{
formatter.Append(u32.Value, format);
return;
}
var u64 = value as ulong?;
if (u64 != null)
{
formatter.Append(u64.Value, format);
return;
}
var u16 = value as ushort?;
if (u16 != null)
{
formatter.Append(u16.Value, format);
return;
}
var sb = value as sbyte?;
if (sb != null)
{
formatter.Append(sb.Value, format);
return;
}
var str = value as string;
if (str != null)
{
formatter.Append(str);
return;
}
var utf8 = value as Utf8String?;
if (utf8 != null) {
formatter.Append(utf8.Value);
return;
}
var dt = value as DateTime?;
if (dt != null)
{
formatter.Append(dt.Value, format);
return;
}
var dto = value as DateTimeOffset?;
if (dto != null) {
formatter.Append(dto.Value, format);
return;
}
var ts = value as TimeSpan?;
if (ts != null)
{
formatter.Append(ts.Value, format);
return;
}
var guid = value as Guid?;
if (guid != null) {
formatter.Append(guid.Value, format);
return;
}
#endregion
if (value is IBufferFormattable)
{
formatter.Append((IBufferFormattable)value, format); // this is boxing. not sure how to avoid it.
return;
}
throw new NotSupportedException("value is not formattable.");
}
// this is just a state machine walking the composite format and instructing CompositeFormattingExtensions.Format overloads on what to do.
// this whole type is not just a hacky prototype.
// I will clean it up later if I decide that I like this whole composite format model.
struct CompositeFormatReader
{
string _compositeFormatString;
int _currentIndex;
int _spanStart;
State _state;
public CompositeFormatReader(string format)
{
_compositeFormatString = format;
_currentIndex = 0;
_spanStart = 0;
_state = State.New;
}
public CompositeSegment? Next()
{
while (_currentIndex < _compositeFormatString.Length)
{
char c = _compositeFormatString[_currentIndex];
if (c == '{')
{
if (_state == State.Literal)
{
_state = State.New;
return CompositeSegment.Literal(_spanStart, _currentIndex);
}
if ((_currentIndex + 1 < _compositeFormatString.Length) && (_compositeFormatString[_currentIndex + 1] == c))
{
_state = State.Literal;
_currentIndex++;
_spanStart = _currentIndex;
}
else
{
_currentIndex++;
return ParseInsertionPoint();
}
}
else if (c == '}')
{
if ((_currentIndex + 1 < _compositeFormatString.Length) && (_compositeFormatString[_currentIndex + 1] == c))
{
if (_state == State.Literal)
{
_state = State.New;
return CompositeSegment.Literal(_spanStart, _currentIndex);
}
_state = State.Literal;
_currentIndex++;
_spanStart = _currentIndex;
}
else
{
throw new Exception("missing start bracket");
}
}
else
{
if (_state != State.Literal)
{
_state = State.Literal;
_spanStart = _currentIndex;
}
}
_currentIndex++;
}
if (_state == State.Literal)
{
_state = State.New;
return CompositeSegment.Literal(_spanStart, _currentIndex);
}
return null;
}
// this should be replaced with InvariantFormatter.Parse
static bool TryParse(string compositeFormat, int start, int count, out uint value, out int consumed)
{
consumed = 0;
value = 0;
for (int i = start; i < start + count; i++)
{
var digit = (byte)(compositeFormat[i] - '0');
if (digit >= 0 && digit <= 9)
{
value *= 10;
value += digit;
consumed++;
}
else
{
if (i == start) return false;
else return true;
}
}
return true;
}
CompositeSegment ParseInsertionPoint()
{
uint arg;
int consumed;
char? formatSpecifier = null;
if (!TryParse(_compositeFormatString, _currentIndex, 5, out arg, out consumed))
{
throw new Exception("invalid insertion point");
}
_currentIndex += consumed;
if (_currentIndex >= _compositeFormatString.Length)
{
throw new Exception("missing end bracket");
}
if(_compositeFormatString[_currentIndex] == ':')
{
_currentIndex++;
formatSpecifier = _compositeFormatString[_currentIndex];
_currentIndex++;
}
if (_compositeFormatString[_currentIndex] != '}')
{
throw new Exception("missing end bracket");
}
_currentIndex++;
var parsedFormat = formatSpecifier.HasValue ? TextFormat.Parse(formatSpecifier.Value): default(TextFormat);
return CompositeSegment.InsertionPoint(arg, parsedFormat);
}
public enum State : byte
{
New,
Literal,
InsertionPoint
}
public struct CompositeSegment
{
public TextFormat Format { get; private set; }
public int Index { get; private set; }
public int Count { get; private set; }
public static CompositeSegment InsertionPoint(uint argIndex, TextFormat format)
{
return new CompositeSegment() { Index = (int)argIndex, Format = format };
}
public static CompositeSegment Literal(int startIndex, int endIndex)
{
return new CompositeSegment() { Index = startIndex, Count = endIndex - startIndex };
}
}
}
}
}
| |
/*
* 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 NUnit.Framework;
using OpenSim.Tests.Common;
using System.Collections.Generic;
namespace OpenSim.Region.ScriptEngine.Shared.Tests
{
[TestFixture]
public class LSL_TypesTestLSLFloat : OpenSimTestCase
{
// Used for testing equality of two floats.
private double _lowPrecisionTolerance = 0.000001;
private Dictionary<int, double> m_intDoubleSet;
private Dictionary<double, double> m_doubleDoubleSet;
private Dictionary<double, int> m_doubleIntSet;
private Dictionary<double, int> m_doubleUintSet;
private Dictionary<string, double> m_stringDoubleSet;
private Dictionary<double, string> m_doubleStringSet;
private List<int> m_intList;
private List<double> m_doubleList;
/// <summary>
/// Sets up dictionaries and arrays used in the tests.
/// </summary>
[TestFixtureSetUp]
public void SetUpDataSets()
{
m_intDoubleSet = new Dictionary<int, double>();
m_intDoubleSet.Add(2, 2.0);
m_intDoubleSet.Add(-2, -2.0);
m_intDoubleSet.Add(0, 0.0);
m_intDoubleSet.Add(1, 1.0);
m_intDoubleSet.Add(-1, -1.0);
m_intDoubleSet.Add(999999999, 999999999.0);
m_intDoubleSet.Add(-99999999, -99999999.0);
m_doubleDoubleSet = new Dictionary<double, double>();
m_doubleDoubleSet.Add(2.0, 2.0);
m_doubleDoubleSet.Add(-2.0, -2.0);
m_doubleDoubleSet.Add(0.0, 0.0);
m_doubleDoubleSet.Add(1.0, 1.0);
m_doubleDoubleSet.Add(-1.0, -1.0);
m_doubleDoubleSet.Add(999999999.0, 999999999.0);
m_doubleDoubleSet.Add(-99999999.0, -99999999.0);
m_doubleDoubleSet.Add(0.5, 0.5);
m_doubleDoubleSet.Add(0.0005, 0.0005);
m_doubleDoubleSet.Add(0.6805, 0.6805);
m_doubleDoubleSet.Add(-0.5, -0.5);
m_doubleDoubleSet.Add(-0.0005, -0.0005);
m_doubleDoubleSet.Add(-0.6805, -0.6805);
m_doubleDoubleSet.Add(548.5, 548.5);
m_doubleDoubleSet.Add(2.0005, 2.0005);
m_doubleDoubleSet.Add(349485435.6805, 349485435.6805);
m_doubleDoubleSet.Add(-548.5, -548.5);
m_doubleDoubleSet.Add(-2.0005, -2.0005);
m_doubleDoubleSet.Add(-349485435.6805, -349485435.6805);
m_doubleIntSet = new Dictionary<double, int>();
m_doubleIntSet.Add(2.0, 2);
m_doubleIntSet.Add(-2.0, -2);
m_doubleIntSet.Add(0.0, 0);
m_doubleIntSet.Add(1.0, 1);
m_doubleIntSet.Add(-1.0, -1);
m_doubleIntSet.Add(999999999.0, 999999999);
m_doubleIntSet.Add(-99999999.0, -99999999);
m_doubleIntSet.Add(0.5, 0);
m_doubleIntSet.Add(0.0005, 0);
m_doubleIntSet.Add(0.6805, 0);
m_doubleIntSet.Add(-0.5, 0);
m_doubleIntSet.Add(-0.0005, 0);
m_doubleIntSet.Add(-0.6805, 0);
m_doubleIntSet.Add(548.5, 548);
m_doubleIntSet.Add(2.0005, 2);
m_doubleIntSet.Add(349485435.6805, 349485435);
m_doubleIntSet.Add(-548.5, -548);
m_doubleIntSet.Add(-2.0005, -2);
m_doubleIntSet.Add(-349485435.6805, -349485435);
m_doubleUintSet = new Dictionary<double, int>();
m_doubleUintSet.Add(2.0, 2);
m_doubleUintSet.Add(-2.0, 2);
m_doubleUintSet.Add(0.0, 0);
m_doubleUintSet.Add(1.0, 1);
m_doubleUintSet.Add(-1.0, 1);
m_doubleUintSet.Add(999999999.0, 999999999);
m_doubleUintSet.Add(-99999999.0, 99999999);
m_doubleUintSet.Add(0.5, 0);
m_doubleUintSet.Add(0.0005, 0);
m_doubleUintSet.Add(0.6805, 0);
m_doubleUintSet.Add(-0.5, 0);
m_doubleUintSet.Add(-0.0005, 0);
m_doubleUintSet.Add(-0.6805, 0);
m_doubleUintSet.Add(548.5, 548);
m_doubleUintSet.Add(2.0005, 2);
m_doubleUintSet.Add(349485435.6805, 349485435);
m_doubleUintSet.Add(-548.5, 548);
m_doubleUintSet.Add(-2.0005, 2);
m_doubleUintSet.Add(-349485435.6805, 349485435);
m_stringDoubleSet = new Dictionary<string, double>();
m_stringDoubleSet.Add("2", 2.0);
m_stringDoubleSet.Add("-2", -2.0);
m_stringDoubleSet.Add("1", 1.0);
m_stringDoubleSet.Add("-1", -1.0);
m_stringDoubleSet.Add("0", 0.0);
m_stringDoubleSet.Add("999999999.0", 999999999.0);
m_stringDoubleSet.Add("-99999999.0", -99999999.0);
m_stringDoubleSet.Add("0.5", 0.5);
m_stringDoubleSet.Add("0.0005", 0.0005);
m_stringDoubleSet.Add("0.6805", 0.6805);
m_stringDoubleSet.Add("-0.5", -0.5);
m_stringDoubleSet.Add("-0.0005", -0.0005);
m_stringDoubleSet.Add("-0.6805", -0.6805);
m_stringDoubleSet.Add("548.5", 548.5);
m_stringDoubleSet.Add("2.0005", 2.0005);
m_stringDoubleSet.Add("349485435.6805", 349485435.6805);
m_stringDoubleSet.Add("-548.5", -548.5);
m_stringDoubleSet.Add("-2.0005", -2.0005);
m_stringDoubleSet.Add("-349485435.6805", -349485435.6805);
// some oddball combinations and exponents
m_stringDoubleSet.Add("", 0.0);
m_stringDoubleSet.Add("1.0E+5", 100000.0);
m_stringDoubleSet.Add("-1.0E+5", -100000.0);
m_stringDoubleSet.Add("-1E+5", -100000.0);
m_stringDoubleSet.Add("-1.E+5", -100000.0);
m_stringDoubleSet.Add("-1.E+5.0", -100000.0);
m_stringDoubleSet.Add("1ef", 1.0);
m_stringDoubleSet.Add("e10", 0.0);
m_stringDoubleSet.Add("1.e0.0", 1.0);
m_doubleStringSet = new Dictionary<double, string>();
m_doubleStringSet.Add(2.0, "2.000000");
m_doubleStringSet.Add(-2.0, "-2.000000");
m_doubleStringSet.Add(1.0, "1.000000");
m_doubleStringSet.Add(-1.0, "-1.000000");
m_doubleStringSet.Add(0.0, "0.000000");
m_doubleStringSet.Add(999999999.0, "999999999.000000");
m_doubleStringSet.Add(-99999999.0, "-99999999.000000");
m_doubleStringSet.Add(0.5, "0.500000");
m_doubleStringSet.Add(0.0005, "0.000500");
m_doubleStringSet.Add(0.6805, "0.680500");
m_doubleStringSet.Add(-0.5, "-0.500000");
m_doubleStringSet.Add(-0.0005, "-0.000500");
m_doubleStringSet.Add(-0.6805, "-0.680500");
m_doubleStringSet.Add(548.5, "548.500000");
m_doubleStringSet.Add(2.0005, "2.000500");
m_doubleStringSet.Add(349485435.6805, "349485435.680500");
m_doubleStringSet.Add(-548.5, "-548.500000");
m_doubleStringSet.Add(-2.0005, "-2.000500");
m_doubleStringSet.Add(-349485435.6805, "-349485435.680500");
m_doubleList = new List<double>();
m_doubleList.Add(2.0);
m_doubleList.Add(-2.0);
m_doubleList.Add(1.0);
m_doubleList.Add(-1.0);
m_doubleList.Add(999999999.0);
m_doubleList.Add(-99999999.0);
m_doubleList.Add(0.5);
m_doubleList.Add(0.0005);
m_doubleList.Add(0.6805);
m_doubleList.Add(-0.5);
m_doubleList.Add(-0.0005);
m_doubleList.Add(-0.6805);
m_doubleList.Add(548.5);
m_doubleList.Add(2.0005);
m_doubleList.Add(349485435.6805);
m_doubleList.Add(-548.5);
m_doubleList.Add(-2.0005);
m_doubleList.Add(-349485435.6805);
m_intList = new List<int>();
m_intList.Add(2);
m_intList.Add(-2);
m_intList.Add(0);
m_intList.Add(1);
m_intList.Add(-1);
m_intList.Add(999999999);
m_intList.Add(-99999999);
}
/// <summary>
/// Tests constructing a LSLFloat from an integer.
/// </summary>
[Test]
public void TestConstructFromInt()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
foreach (KeyValuePair<int, double> number in m_intDoubleSet)
{
testFloat = new LSL_Types.LSLFloat(number.Key);
Assert.That(testFloat.value, new DoubleToleranceConstraint(number.Value, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests constructing a LSLFloat from a double.
/// </summary>
[Test]
public void TestConstructFromDouble()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
foreach (KeyValuePair<double, double> number in m_doubleDoubleSet)
{
testFloat = new LSL_Types.LSLFloat(number.Key);
Assert.That(testFloat.value, new DoubleToleranceConstraint(number.Value, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests LSLFloat is correctly cast explicitly to integer.
/// </summary>
[Test]
public void TestExplicitCastLSLFloatToInt()
{
TestHelpers.InMethod();
int testNumber;
foreach (KeyValuePair<double, int> number in m_doubleIntSet)
{
testNumber = (int)new LSL_Types.LSLFloat(number.Key);
Assert.AreEqual(number.Value, testNumber, "Converting double " + number.Key + ", expecting int " + number.Value);
}
}
/// <summary>
/// Tests LSLFloat is correctly cast explicitly to unsigned integer.
/// </summary>
[Test]
public void TestExplicitCastLSLFloatToUint()
{
TestHelpers.InMethod();
uint testNumber;
foreach (KeyValuePair<double, int> number in m_doubleUintSet)
{
testNumber = (uint)new LSL_Types.LSLFloat(number.Key);
Assert.AreEqual(number.Value, testNumber, "Converting double " + number.Key + ", expecting uint " + number.Value);
}
}
/// <summary>
/// Tests LSLFloat is correctly cast implicitly to Boolean if non-zero.
/// </summary>
[Test]
public void TestImplicitCastLSLFloatToBooleanTrue()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
bool testBool;
foreach (double number in m_doubleList)
{
testFloat = new LSL_Types.LSLFloat(number);
testBool = testFloat;
Assert.IsTrue(testBool);
}
}
/// <summary>
/// Tests LSLFloat is correctly cast implicitly to Boolean if zero.
/// </summary>
[Test]
public void TestImplicitCastLSLFloatToBooleanFalse()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat = new LSL_Types.LSLFloat(0.0);
bool testBool = testFloat;
Assert.IsFalse(testBool);
}
/// <summary>
/// Tests integer is correctly cast implicitly to LSLFloat.
/// </summary>
[Test]
public void TestImplicitCastIntToLSLFloat()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
foreach (int number in m_intList)
{
testFloat = number;
Assert.That(testFloat.value, new DoubleToleranceConstraint(number, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests LSLInteger is correctly cast implicitly to LSLFloat.
/// </summary>
[Test]
public void TestImplicitCastLSLIntegerToLSLFloat()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
foreach (int number in m_intList)
{
testFloat = new LSL_Types.LSLInteger(number);
Assert.That(testFloat.value, new DoubleToleranceConstraint(number, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests LSLInteger is correctly cast explicitly to LSLFloat.
/// </summary>
[Test]
public void TestExplicitCastLSLIntegerToLSLFloat()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
foreach (int number in m_intList)
{
testFloat = (LSL_Types.LSLFloat)new LSL_Types.LSLInteger(number);
Assert.That(testFloat.value, new DoubleToleranceConstraint(number, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests string is correctly cast explicitly to LSLFloat.
/// </summary>
[Test]
public void TestExplicitCastStringToLSLFloat()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
foreach (KeyValuePair<string, double> number in m_stringDoubleSet)
{
testFloat = (LSL_Types.LSLFloat)number.Key;
Assert.That(testFloat.value, new DoubleToleranceConstraint(number.Value, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests LSLString is correctly cast implicitly to LSLFloat.
/// </summary>
[Test]
public void TestExplicitCastLSLStringToLSLFloat()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
foreach (KeyValuePair<string, double> number in m_stringDoubleSet)
{
testFloat = (LSL_Types.LSLFloat)new LSL_Types.LSLString(number.Key);
Assert.That(testFloat.value, new DoubleToleranceConstraint(number.Value, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests double is correctly cast implicitly to LSLFloat.
/// </summary>
[Test]
public void TestImplicitCastDoubleToLSLFloat()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
foreach (double number in m_doubleList)
{
testFloat = number;
Assert.That(testFloat.value, new DoubleToleranceConstraint(number, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests LSLFloat is correctly cast implicitly to double.
/// </summary>
[Test]
public void TestImplicitCastLSLFloatToDouble()
{
TestHelpers.InMethod();
double testNumber;
LSL_Types.LSLFloat testFloat;
foreach (double number in m_doubleList)
{
testFloat = new LSL_Types.LSLFloat(number);
testNumber = testFloat;
Assert.That(testNumber, new DoubleToleranceConstraint(number, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests LSLFloat is correctly cast explicitly to float
/// </summary>
[Test]
public void TestExplicitCastLSLFloatToFloat()
{
TestHelpers.InMethod();
float testFloat;
float numberAsFloat;
LSL_Types.LSLFloat testLSLFloat;
foreach (double number in m_doubleList)
{
testLSLFloat = new LSL_Types.LSLFloat(number);
numberAsFloat = (float)number;
testFloat = (float)testLSLFloat;
Assert.That((double)testFloat, new DoubleToleranceConstraint((double)numberAsFloat, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests the equality (==) operator.
/// </summary>
[Test]
public void TestEqualsOperator()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloatA, testFloatB;
foreach (double number in m_doubleList)
{
testFloatA = new LSL_Types.LSLFloat(number);
testFloatB = new LSL_Types.LSLFloat(number);
Assert.IsTrue(testFloatA == testFloatB);
testFloatB = new LSL_Types.LSLFloat(number + 1.0);
Assert.IsFalse(testFloatA == testFloatB);
}
}
/// <summary>
/// Tests the inequality (!=) operator.
/// </summary>
[Test]
public void TestNotEqualOperator()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloatA, testFloatB;
foreach (double number in m_doubleList)
{
testFloatA = new LSL_Types.LSLFloat(number);
testFloatB = new LSL_Types.LSLFloat(number + 1.0);
Assert.IsTrue(testFloatA != testFloatB);
testFloatB = new LSL_Types.LSLFloat(number);
Assert.IsFalse(testFloatA != testFloatB);
}
}
/// <summary>
/// Tests the increment operator.
/// </summary>
[Test]
public void TestIncrementOperator()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
double testNumber;
foreach (double number in m_doubleList)
{
testFloat = new LSL_Types.LSLFloat(number);
testNumber = testFloat++;
Assert.That(testNumber, new DoubleToleranceConstraint(number, _lowPrecisionTolerance));
testNumber = testFloat;
Assert.That(testNumber, new DoubleToleranceConstraint(number + 1.0, _lowPrecisionTolerance));
testNumber = ++testFloat;
Assert.That(testNumber, new DoubleToleranceConstraint(number + 2.0, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests the decrement operator.
/// </summary>
[Test]
public void TestDecrementOperator()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
double testNumber;
foreach (double number in m_doubleList)
{
testFloat = new LSL_Types.LSLFloat(number);
testNumber = testFloat--;
Assert.That(testNumber, new DoubleToleranceConstraint(number, _lowPrecisionTolerance));
testNumber = testFloat;
Assert.That(testNumber, new DoubleToleranceConstraint(number - 1.0, _lowPrecisionTolerance));
testNumber = --testFloat;
Assert.That(testNumber, new DoubleToleranceConstraint(number - 2.0, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests LSLFloat.ToString().
/// </summary>
[Test]
public void TestToString()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
foreach (KeyValuePair<double, string> number in m_doubleStringSet)
{
testFloat = new LSL_Types.LSLFloat(number.Key);
Assert.AreEqual(number.Value, testFloat.ToString());
}
}
/// <summary>
/// Tests addition of two LSLFloats.
/// </summary>
[Test]
public void TestAddTwoLSLFloats()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testResult;
foreach (KeyValuePair<double, double> number in m_doubleDoubleSet)
{
testResult = new LSL_Types.LSLFloat(number.Key) + new LSL_Types.LSLFloat(number.Value);
Assert.That(testResult.value, new DoubleToleranceConstraint(number.Key + number.Value, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests subtraction of two LSLFloats.
/// </summary>
[Test]
public void TestSubtractTwoLSLFloats()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testResult;
foreach (KeyValuePair<double, double> number in m_doubleDoubleSet)
{
testResult = new LSL_Types.LSLFloat(number.Key) - new LSL_Types.LSLFloat(number.Value);
Assert.That(testResult.value, new DoubleToleranceConstraint(number.Key - number.Value, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests multiplication of two LSLFloats.
/// </summary>
[Test]
public void TestMultiplyTwoLSLFloats()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testResult;
foreach (KeyValuePair<double, double> number in m_doubleDoubleSet)
{
testResult = new LSL_Types.LSLFloat(number.Key) * new LSL_Types.LSLFloat(number.Value);
Assert.That(testResult.value, new DoubleToleranceConstraint(number.Key * number.Value, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests division of two LSLFloats.
/// </summary>
[Test]
public void TestDivideTwoLSLFloats()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testResult;
foreach (KeyValuePair<double, double> number in m_doubleDoubleSet)
{
if (number.Value != 0.0) // Let's avoid divide by zero.
{
testResult = new LSL_Types.LSLFloat(number.Key) / new LSL_Types.LSLFloat(number.Value);
Assert.That(testResult.value, new DoubleToleranceConstraint(number.Key / number.Value, _lowPrecisionTolerance));
}
}
}
/// <summary>
/// Tests boolean correctly cast implicitly to LSLFloat.
/// </summary>
[Test]
public void TestImplicitCastBooleanToLSLFloat()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
testFloat = (1 == 0);
Assert.That(testFloat.value, new DoubleToleranceConstraint(0.0, _lowPrecisionTolerance));
testFloat = (1 == 1);
Assert.That(testFloat.value, new DoubleToleranceConstraint(1.0, _lowPrecisionTolerance));
testFloat = false;
Assert.That(testFloat.value, new DoubleToleranceConstraint(0.0, _lowPrecisionTolerance));
testFloat = true;
Assert.That(testFloat.value, new DoubleToleranceConstraint(1.0, _lowPrecisionTolerance));
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using NetSpell.SpellChecker;
using NetSpell.SpellChecker.Dictionary;
using NetSpell.SpellChecker.Dictionary.Affix;
using NetSpell.SpellChecker.Dictionary.Phonetic;
namespace NetSpell.DictionaryBuild
{
/// <summary>
/// Summary description for DictionaryForm.
/// </summary>
public class DictionaryForm : System.Windows.Forms.Form
{
private bool _Changed = false;
private string _FileName = "untitled";
// the following is used to split a line by white space
private Regex _spaceRegx = new Regex(@"[^\s]+", RegexOptions.Compiled);
private ArrayList _Words = new ArrayList();
private System.Windows.Forms.Button btnLookup;
private System.ComponentModel.IContainer components;
private System.Windows.Forms.TabControl DictionaryTab;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.ImageList imageList1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.ListBox listAffixWords;
private System.Windows.Forms.MainMenu mainMenu;
private System.Windows.Forms.MenuItem menuAffix;
private System.Windows.Forms.MenuItem menuDictionary;
private System.Windows.Forms.MenuItem menuGenerate;
private System.Windows.Forms.MenuItem menuItem3;
private System.Windows.Forms.MenuItem menuItem5;
private System.Windows.Forms.MenuItem menuPhonetic;
private System.Windows.Forms.MenuItem menuWords;
private System.Windows.Forms.NumericUpDown numUpDownWord;
private System.Windows.Forms.OpenFileDialog openAffixDialog;
private System.Windows.Forms.OpenFileDialog openDictionaryDialog;
private System.Windows.Forms.OpenFileDialog openPhoneticDialog;
private System.Windows.Forms.OpenFileDialog openWordsDialog;
private System.Windows.Forms.SaveFileDialog saveDictionaryDialog;
private System.Windows.Forms.TabPage tabCopyright;
private System.Windows.Forms.TabPage tabNearMiss;
private System.Windows.Forms.TabPage tabPhonetic;
private System.Windows.Forms.TabPage tabPrefix;
private System.Windows.Forms.TabPage tabSuffix;
private System.Windows.Forms.TabPage tabWords;
private System.Windows.Forms.TextBox txtAffixKeys;
private System.Windows.Forms.TextBox txtCurrentWord;
private System.Windows.Forms.TextBox txtPhoneticCode;
private System.Windows.Forms.TextBox txtWord;
private System.Windows.Forms.TextBox txtWordCount;
internal System.Windows.Forms.TextBox txtCopyright;
internal System.Windows.Forms.TextBox txtPhonetic;
internal System.Windows.Forms.TextBox txtPrefix;
internal System.Windows.Forms.TextBox txtReplace;
internal System.Windows.Forms.TextBox txtSuffix;
internal System.Windows.Forms.TextBox txtTry;
public DictionaryForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
private void btnLookup_Click(object sender, System.EventArgs e)
{
// if saved and words > 0
if (_Words.Count == 0)
{
MessageBox.Show(this, "Dictionary contains no words!", "No Words", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (this.Changed)
{
if (MessageBox.Show(this, "Dictionary should be saved before phonetic cache is added. \r\n \r\n Save Dictonary Now?",
"Save Dictonary", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
this.SaveDictionary();
}
else
{
return;
}
}
this.Cursor = Cursors.WaitCursor;
WordDictionary dict = new WordDictionary();
dict.DictionaryFile = this.FileName;
dict.Initialize();
string[] parts = _Words[(int)numUpDownWord.Value].ToString().Split('/');
Word word = new Word();
word.Text = parts[0];
if (parts.Length > 1) word.AffixKeys = parts[1];
if (parts.Length > 2) word.PhoneticCode = parts[2];
ArrayList words = dict.ExpandWord(word);
this.listAffixWords.Items.Clear();
foreach (string tempWord in words)
{
this.listAffixWords.Items.Add(tempWord);
}
this.Cursor = Cursors.Default;
}
private void DictionaryForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (_Changed)
{
DialogResult result = MessageBox.Show(this,
string.Format("Save changes to {0}?", Path.GetFileName(this.FileName)),
"Save Dictionary", MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question);
switch (result)
{
case DialogResult.Yes :
this.SaveDictionary();
break;
case DialogResult.Cancel :
e.Cancel = true;
break;
}
}
}
private void form_TextChanged(object sender, System.EventArgs e)
{
this.Changed = true;
}
private void menuAffix_Click(object sender, System.EventArgs e)
{
this.LoadAffix();
}
private void menuGenerate_Click(object sender, System.EventArgs e)
{
this.GenerateCache();
}
private void menuPhonetic_Click(object sender, System.EventArgs e)
{
this.LoadPhonetic();
}
private void menuWords_Click(object sender, System.EventArgs e)
{
this.LoadWords();
}
private void numUpDownWord_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
this.UpdateCurrentWord();
}
private void numUpDownWord_ValueChanged(object sender, System.EventArgs e)
{
this.UpdateCurrentWord();
}
private void UpdateCurrentWord()
{
if ((int)numUpDownWord.Value < _Words.Count)
{
this.txtWordCount.Text = _Words.Count.ToString();
this.txtCurrentWord.Text = _Words[(int)numUpDownWord.Value].ToString();
this.listAffixWords.Items.Clear();
string[] parts = _Words[(int)numUpDownWord.Value].ToString().Split('/');
this.txtWord.Text = parts[0];
if (parts.Length > 1) this.txtAffixKeys.Text = parts[1];
if (parts.Length > 2) this.txtPhoneticCode.Text = parts[2];
}
}
public void GenerateCache()
{
// if saved and words > 0
if (_Words.Count == 0)
{
MessageBox.Show(this, "Dictionary contains no words!", "No Words", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (this.Changed)
{
if (MessageBox.Show(this, "Dictionary should be saved before phonetic cache is added. \r\n \r\n Save Dictonary Now?",
"Save Dictonary", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
this.SaveDictionary();
}
else
{
return;
}
}
this.Cursor = Cursors.WaitCursor;
// load dictionary
WordDictionary dict = new WordDictionary();
dict.DictionaryFile = this.FileName;
dict.Initialize();
this.Cursor = Cursors.Default;
if (dict.PhoneticRules.Count == 0)
{
MessageBox.Show(this, "Dictionary does not contain phonetic rules!", "No Phonetic Rules", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
MainForm main = (MainForm)this.MdiParent;
this.Cursor = Cursors.WaitCursor;
for (int i = 0; i < _Words.Count; i++)
{
if (i % 1000 == 0)
{
main.statusBar.Text = string.Format("Word {0} of {1}", i, _Words.Count);
Application.DoEvents();
}
string[] parts = _Words[i].ToString().Split('/');
// part 1 = base word
string tempWord = parts[0];
// part 2 = affix keys
string tempKeys = "";
if (parts.Length >= 2)
{
tempKeys = parts[1];
}
// part 3 = phonetic code
string tempCode = dict.PhoneticCode(tempWord);
if (tempCode.Length > 0)
{
_Words[i] = string.Format("{0}/{1}/{2}", tempWord, tempKeys, tempCode);
}
}
main.statusBar.Text = "";
this.Changed = true;
this.Cursor = Cursors.Default;
MessageBox.Show(this, "Cache created successfully", "Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
public void LoadAffix()
{
if (this.openAffixDialog.ShowDialog(this) == DialogResult.OK)
{
this.Cursor = Cursors.WaitCursor;
this.txtTry.Text = "";
this.txtReplace.Text = "";
this.txtPrefix.Text = "";
this.txtSuffix.Text = "";
// open dictionary file
FileStream fs = (FileStream)openAffixDialog.OpenFile();
StreamReader sr = new StreamReader(fs, Encoding.UTF7);
// read line by line
while (sr.Peek() >= 0)
{
string tempLine = sr.ReadLine().Trim();
if (tempLine.Length > 3)
{
switch (tempLine.Substring(0, 3))
{
case "TRY" :
this.txtTry.Text = tempLine.Substring(4);
break;
case "PFX" :
this.txtPrefix.AppendText(tempLine.Substring(4) + "\r\n");
break;
case "SFX" :
this.txtSuffix.AppendText(tempLine.Substring(4) + "\r\n");
break;
case "REP" :
if (!char.IsNumber(tempLine.Substring(4)[0]))
{
this.txtReplace.AppendText(tempLine.Substring(4) + "\r\n");
}
break;
}
}
}
// close reader
sr.Close();
// close stream
fs.Close();
}
this.Cursor = Cursors.Default;
}
public void LoadPhonetic()
{
if (this.openPhoneticDialog.ShowDialog(this) == DialogResult.OK)
{
this.Cursor = Cursors.WaitCursor;
// open dictionary file
FileStream fs = (FileStream)openPhoneticDialog.OpenFile();
StreamReader sr = new StreamReader(fs, Encoding.UTF7);
this.txtPhonetic.Text = "";
// read line by line
while (sr.Peek() >= 0)
{
string tempLine = sr.ReadLine().Trim();
if (!tempLine.StartsWith("#")
&& !tempLine.StartsWith("version")
&& !tempLine.StartsWith("followup")
&& !tempLine.StartsWith("collapse_result")
&& tempLine.Length > 0)
{
this.txtPhonetic.AppendText(tempLine + "\r\n");
}
}
// close reader
sr.Close();
// close stream
fs.Close();
}
this.Cursor = Cursors.Default;
}
public void LoadWords()
{
if (this.openWordsDialog.ShowDialog(this) == DialogResult.OK)
{
this.Cursor = Cursors.WaitCursor;
// open dictionary file
FileStream fs = (FileStream)openWordsDialog.OpenFile();
StreamReader sr = new StreamReader(fs, Encoding.UTF7);
_Words.Clear();
Hashtable tempWordList = new Hashtable();
// read line by line
while (sr.Peek() >= 0)
{
string tempLine = sr.ReadLine().Trim();
if (!char.IsNumber(tempLine[0]))
{
string[] parts = tempLine.Split('/');
string word = parts[0];
string affixKeys = "";
if(parts.Length > 1) affixKeys = parts[1];
// look for duplicate words
if(tempWordList.ContainsKey(word))
{
// merge affix keys on duplicate words
string[] tempParts = tempWordList[word].ToString().Split('/');
string oldKeys = "";
if(tempParts.Length > 1) oldKeys = tempParts[1];
foreach (char key in oldKeys)
{
// if the new affix keys do not contain old key, add old key to new keys
if(affixKeys.IndexOf(key) == -1)
{
affixKeys += key.ToString();
}
}
// only update if have keys
if(affixKeys.Length > 0)
{
tempWordList[word] = string.Format("{0}/{1}", word, affixKeys);
}
}
else
{
tempWordList.Add(word, tempLine);
}
}
}
// close reader
sr.Close();
// close stream
fs.Close();
_Words.AddRange(tempWordList.Values);
_Words.Sort();
this.numUpDownWord.Value = 0;
this.numUpDownWord.Maximum = _Words.Count;
this.UpdateCurrentWord();
this.Changed = true;
}
this.Cursor = Cursors.Default;
}
public bool OpenDictionary()
{
if (this.openDictionaryDialog.ShowDialog(this) == DialogResult.OK)
{
this.Cursor = Cursors.WaitCursor;
// open dictionary file
FileStream fs = (FileStream)openDictionaryDialog.OpenFile();
StreamReader sr = new StreamReader(fs, Encoding.UTF8);
string currentSection = "";
this.txtCopyright.Text = "";
this.txtTry.Text = "";
this.txtReplace.Text = "";
this.txtPrefix.Text = "";
this.txtSuffix.Text = "";
this.txtPhonetic.Text = "";
// read line by line
while (sr.Peek() >= 0)
{
string tempLine = sr.ReadLine().Trim();
if (tempLine.Length > 0)
{
switch (tempLine)
{
case "[Copyright]" :
case "[Try]" :
case "[Replace]" :
case "[Prefix]" :
case "[Suffix]" :
case "[Phonetic]" :
case "[Words]" :
currentSection = tempLine;
break;
default :
switch (currentSection)
{
case "[Copyright]" :
this.txtCopyright.AppendText(tempLine + "\r\n");
break;
case "[Try]" :
this.txtTry.AppendText(tempLine);
break;
case "[Replace]" :
this.txtReplace.AppendText(tempLine + "\r\n");
break;
case "[Prefix]" :
this.txtPrefix.AppendText(tempLine + "\r\n");
break;
case "[Suffix]" :
this.txtSuffix.AppendText(tempLine + "\r\n");
break;
case "[Phonetic]" :
this.txtPhonetic.AppendText(tempLine + "\r\n");
break;
case "[Words]" :
_Words.Add(tempLine);
break;
} // switch section
break;
} // switch temp line
}
} // while
// close reader
sr.Close();
// close stream
fs.Close();
this.txtWordCount.Text = _Words.Count.ToString();
if (_Words.Count > 0)
{
this.UpdateCurrentWord();
this.numUpDownWord.Maximum = _Words.Count - 1;
}
else
{
this.numUpDownWord.Maximum = 0;
}
this.FileName = this.openDictionaryDialog.FileName;
this.Cursor = Cursors.Default;
return true;
}
this.Cursor = Cursors.Default;
return false;
}
public void SaveDictionary()
{
if (!File.Exists(this.FileName))
{
if (this.saveDictionaryDialog.ShowDialog(this) == DialogResult.OK)
{
this.FileName = this.saveDictionaryDialog.FileName;
}
else
{
return;
}
}
this.Cursor = Cursors.WaitCursor;
// save dictionary file
FileStream fs = new FileStream(this.FileName, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
sw.NewLine = "\n"; // unix line ends
// copyright
sw.WriteLine("[Copyright]");
sw.WriteLine(this.txtCopyright.Text.Replace("\r\n", "\n")); // unix line ends
// try
sw.WriteLine("[Try]");
sw.WriteLine(this.txtTry.Text);
sw.WriteLine();
// replace
sw.WriteLine("[Replace]");
sw.WriteLine(this.txtReplace.Text.Replace("\r\n", "\n")); // unix line ends
// prefix
sw.WriteLine("[Prefix]");
sw.WriteLine(this.txtPrefix.Text.Replace("\r\n", "\n")); // unix line ends
// suffix
sw.WriteLine("[Suffix]");
sw.WriteLine(this.txtSuffix.Text.Replace("\r\n", "\n")); // unix line ends
// phonetic
sw.WriteLine("[Phonetic]");
sw.WriteLine(this.txtPhonetic.Text.Replace("\r\n", "\n")); // unix line ends
// words
sw.WriteLine("[Words]");
_Words.Sort();
foreach (string tempWord in _Words)
{
sw.WriteLine(tempWord);
}
sw.Close();
fs.Close();
this.Changed = false;
this.Cursor = Cursors.Default;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
internal bool Changed
{
get {return _Changed;}
set
{
_Changed = value;
if (_Changed)
{
this.Text = Path.GetFileName(this.FileName) + " *";
}
else
{
this.Text = Path.GetFileName(this.FileName);
}
}
}
internal string FileName
{
get
{
return _FileName;
}
set
{
_FileName = value;
this.Text = Path.GetFileName(this.FileName);
}
}
internal ArrayList Words
{
get {return _Words;}
set {_Words = value;}
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(DictionaryForm));
this.DictionaryTab = new System.Windows.Forms.TabControl();
this.tabCopyright = new System.Windows.Forms.TabPage();
this.txtCopyright = new System.Windows.Forms.TextBox();
this.tabNearMiss = new System.Windows.Forms.TabPage();
this.txtReplace = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.txtTry = new System.Windows.Forms.TextBox();
this.tabPrefix = new System.Windows.Forms.TabPage();
this.txtPrefix = new System.Windows.Forms.TextBox();
this.tabSuffix = new System.Windows.Forms.TabPage();
this.txtSuffix = new System.Windows.Forms.TextBox();
this.tabPhonetic = new System.Windows.Forms.TabPage();
this.txtPhonetic = new System.Windows.Forms.TextBox();
this.tabWords = new System.Windows.Forms.TabPage();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.btnLookup = new System.Windows.Forms.Button();
this.txtPhoneticCode = new System.Windows.Forms.TextBox();
this.label9 = new System.Windows.Forms.Label();
this.txtAffixKeys = new System.Windows.Forms.TextBox();
this.txtWord = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.listAffixWords = new System.Windows.Forms.ListBox();
this.label8 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.txtCurrentWord = new System.Windows.Forms.TextBox();
this.numUpDownWord = new System.Windows.Forms.NumericUpDown();
this.txtWordCount = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.mainMenu = new System.Windows.Forms.MainMenu();
this.menuDictionary = new System.Windows.Forms.MenuItem();
this.menuWords = new System.Windows.Forms.MenuItem();
this.menuAffix = new System.Windows.Forms.MenuItem();
this.menuItem3 = new System.Windows.Forms.MenuItem();
this.menuPhonetic = new System.Windows.Forms.MenuItem();
this.menuItem5 = new System.Windows.Forms.MenuItem();
this.menuGenerate = new System.Windows.Forms.MenuItem();
this.saveDictionaryDialog = new System.Windows.Forms.SaveFileDialog();
this.openDictionaryDialog = new System.Windows.Forms.OpenFileDialog();
this.openWordsDialog = new System.Windows.Forms.OpenFileDialog();
this.openAffixDialog = new System.Windows.Forms.OpenFileDialog();
this.openPhoneticDialog = new System.Windows.Forms.OpenFileDialog();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.DictionaryTab.SuspendLayout();
this.tabCopyright.SuspendLayout();
this.tabNearMiss.SuspendLayout();
this.tabPrefix.SuspendLayout();
this.tabSuffix.SuspendLayout();
this.tabPhonetic.SuspendLayout();
this.tabWords.SuspendLayout();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numUpDownWord)).BeginInit();
this.SuspendLayout();
//
// DictionaryTab
//
this.DictionaryTab.Controls.Add(this.tabCopyright);
this.DictionaryTab.Controls.Add(this.tabNearMiss);
this.DictionaryTab.Controls.Add(this.tabPrefix);
this.DictionaryTab.Controls.Add(this.tabSuffix);
this.DictionaryTab.Controls.Add(this.tabPhonetic);
this.DictionaryTab.Controls.Add(this.tabWords);
this.DictionaryTab.Dock = System.Windows.Forms.DockStyle.Fill;
this.DictionaryTab.Location = new System.Drawing.Point(0, 0);
this.DictionaryTab.Name = "DictionaryTab";
this.DictionaryTab.SelectedIndex = 0;
this.DictionaryTab.Size = new System.Drawing.Size(552, 478);
this.DictionaryTab.TabIndex = 0;
//
// tabCopyright
//
this.tabCopyright.Controls.Add(this.txtCopyright);
this.tabCopyright.Location = new System.Drawing.Point(4, 22);
this.tabCopyright.Name = "tabCopyright";
this.tabCopyright.Size = new System.Drawing.Size(544, 452);
this.tabCopyright.TabIndex = 0;
this.tabCopyright.Text = "Copyright Text";
//
// txtCopyright
//
this.txtCopyright.Dock = System.Windows.Forms.DockStyle.Fill;
this.txtCopyright.Font = new System.Drawing.Font("Lucida Console", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.txtCopyright.Location = new System.Drawing.Point(0, 0);
this.txtCopyright.Multiline = true;
this.txtCopyright.Name = "txtCopyright";
this.txtCopyright.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.txtCopyright.Size = new System.Drawing.Size(544, 452);
this.txtCopyright.TabIndex = 0;
this.txtCopyright.Text = "";
this.txtCopyright.WordWrap = false;
this.txtCopyright.TextChanged += new System.EventHandler(this.form_TextChanged);
//
// tabNearMiss
//
this.tabNearMiss.Controls.Add(this.txtReplace);
this.tabNearMiss.Controls.Add(this.label2);
this.tabNearMiss.Controls.Add(this.label1);
this.tabNearMiss.Controls.Add(this.txtTry);
this.tabNearMiss.Location = new System.Drawing.Point(4, 22);
this.tabNearMiss.Name = "tabNearMiss";
this.tabNearMiss.Size = new System.Drawing.Size(544, 452);
this.tabNearMiss.TabIndex = 1;
this.tabNearMiss.Text = "Near Miss Data";
//
// txtReplace
//
this.txtReplace.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtReplace.Font = new System.Drawing.Font("Lucida Console", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.txtReplace.Location = new System.Drawing.Point(16, 80);
this.txtReplace.Multiline = true;
this.txtReplace.Name = "txtReplace";
this.txtReplace.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.txtReplace.Size = new System.Drawing.Size(512, 360);
this.txtReplace.TabIndex = 4;
this.txtReplace.Text = "";
this.txtReplace.WordWrap = false;
this.txtReplace.TextChanged += new System.EventHandler(this.form_TextChanged);
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 64);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(392, 16);
this.label2.TabIndex = 3;
this.label2.Text = "&Replace Characters";
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(392, 16);
this.label1.TabIndex = 2;
this.label1.Text = "&Try Characters";
//
// txtTry
//
this.txtTry.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtTry.Font = new System.Drawing.Font("Lucida Console", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.txtTry.Location = new System.Drawing.Point(16, 32);
this.txtTry.Name = "txtTry";
this.txtTry.Size = new System.Drawing.Size(512, 20);
this.txtTry.TabIndex = 0;
this.txtTry.Text = "";
this.txtTry.TextChanged += new System.EventHandler(this.form_TextChanged);
//
// tabPrefix
//
this.tabPrefix.Controls.Add(this.txtPrefix);
this.tabPrefix.Location = new System.Drawing.Point(4, 22);
this.tabPrefix.Name = "tabPrefix";
this.tabPrefix.Size = new System.Drawing.Size(544, 452);
this.tabPrefix.TabIndex = 2;
this.tabPrefix.Text = "Prefix Rules";
//
// txtPrefix
//
this.txtPrefix.Dock = System.Windows.Forms.DockStyle.Fill;
this.txtPrefix.Font = new System.Drawing.Font("Lucida Console", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.txtPrefix.Location = new System.Drawing.Point(0, 0);
this.txtPrefix.Multiline = true;
this.txtPrefix.Name = "txtPrefix";
this.txtPrefix.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.txtPrefix.Size = new System.Drawing.Size(544, 452);
this.txtPrefix.TabIndex = 2;
this.txtPrefix.Text = "";
this.txtPrefix.WordWrap = false;
this.txtPrefix.TextChanged += new System.EventHandler(this.form_TextChanged);
//
// tabSuffix
//
this.tabSuffix.Controls.Add(this.txtSuffix);
this.tabSuffix.Location = new System.Drawing.Point(4, 22);
this.tabSuffix.Name = "tabSuffix";
this.tabSuffix.Size = new System.Drawing.Size(544, 452);
this.tabSuffix.TabIndex = 3;
this.tabSuffix.Text = "Suffix Rules";
//
// txtSuffix
//
this.txtSuffix.Dock = System.Windows.Forms.DockStyle.Fill;
this.txtSuffix.Font = new System.Drawing.Font("Lucida Console", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.txtSuffix.Location = new System.Drawing.Point(0, 0);
this.txtSuffix.Multiline = true;
this.txtSuffix.Name = "txtSuffix";
this.txtSuffix.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.txtSuffix.Size = new System.Drawing.Size(544, 452);
this.txtSuffix.TabIndex = 2;
this.txtSuffix.Text = "";
this.txtSuffix.WordWrap = false;
this.txtSuffix.TextChanged += new System.EventHandler(this.form_TextChanged);
//
// tabPhonetic
//
this.tabPhonetic.Controls.Add(this.txtPhonetic);
this.tabPhonetic.Location = new System.Drawing.Point(4, 22);
this.tabPhonetic.Name = "tabPhonetic";
this.tabPhonetic.Size = new System.Drawing.Size(544, 452);
this.tabPhonetic.TabIndex = 4;
this.tabPhonetic.Text = "Phonetic Rules";
//
// txtPhonetic
//
this.txtPhonetic.Dock = System.Windows.Forms.DockStyle.Fill;
this.txtPhonetic.Font = new System.Drawing.Font("Lucida Console", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.txtPhonetic.Location = new System.Drawing.Point(0, 0);
this.txtPhonetic.Multiline = true;
this.txtPhonetic.Name = "txtPhonetic";
this.txtPhonetic.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.txtPhonetic.Size = new System.Drawing.Size(544, 452);
this.txtPhonetic.TabIndex = 2;
this.txtPhonetic.Text = "";
this.txtPhonetic.WordWrap = false;
this.txtPhonetic.TextChanged += new System.EventHandler(this.form_TextChanged);
//
// tabWords
//
this.tabWords.Controls.Add(this.groupBox1);
this.tabWords.Controls.Add(this.txtWordCount);
this.tabWords.Controls.Add(this.label3);
this.tabWords.Location = new System.Drawing.Point(4, 22);
this.tabWords.Name = "tabWords";
this.tabWords.Size = new System.Drawing.Size(544, 452);
this.tabWords.TabIndex = 5;
this.tabWords.Text = "Word List";
//
// groupBox1
//
this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox1.Controls.Add(this.btnLookup);
this.groupBox1.Controls.Add(this.txtPhoneticCode);
this.groupBox1.Controls.Add(this.label9);
this.groupBox1.Controls.Add(this.txtAffixKeys);
this.groupBox1.Controls.Add(this.txtWord);
this.groupBox1.Controls.Add(this.label6);
this.groupBox1.Controls.Add(this.listAffixWords);
this.groupBox1.Controls.Add(this.label8);
this.groupBox1.Controls.Add(this.label7);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Controls.Add(this.txtCurrentWord);
this.groupBox1.Controls.Add(this.numUpDownWord);
this.groupBox1.Location = new System.Drawing.Point(16, 64);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(512, 376);
this.groupBox1.TabIndex = 14;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Current Word";
//
// btnLookup
//
this.btnLookup.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnLookup.Location = new System.Drawing.Point(416, 160);
this.btnLookup.Name = "btnLookup";
this.btnLookup.TabIndex = 24;
this.btnLookup.Text = "Lookup";
this.btnLookup.Click += new System.EventHandler(this.btnLookup_Click);
//
// txtPhoneticCode
//
this.txtPhoneticCode.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtPhoneticCode.Location = new System.Drawing.Point(144, 112);
this.txtPhoneticCode.Name = "txtPhoneticCode";
this.txtPhoneticCode.ReadOnly = true;
this.txtPhoneticCode.Size = new System.Drawing.Size(256, 20);
this.txtPhoneticCode.TabIndex = 23;
this.txtPhoneticCode.Text = "";
//
// label9
//
this.label9.Location = new System.Drawing.Point(56, 112);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(88, 23);
this.label9.TabIndex = 22;
this.label9.Text = "Phonetic Code:";
//
// txtAffixKeys
//
this.txtAffixKeys.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtAffixKeys.Location = new System.Drawing.Point(144, 88);
this.txtAffixKeys.Name = "txtAffixKeys";
this.txtAffixKeys.ReadOnly = true;
this.txtAffixKeys.Size = new System.Drawing.Size(256, 20);
this.txtAffixKeys.TabIndex = 21;
this.txtAffixKeys.Text = "";
//
// txtWord
//
this.txtWord.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtWord.Location = new System.Drawing.Point(144, 64);
this.txtWord.Name = "txtWord";
this.txtWord.ReadOnly = true;
this.txtWord.Size = new System.Drawing.Size(256, 20);
this.txtWord.TabIndex = 20;
this.txtWord.Text = "";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(16, 160);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(125, 16);
this.label6.TabIndex = 19;
this.label6.Text = "Words from Base Word:";
//
// listAffixWords
//
this.listAffixWords.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listAffixWords.Location = new System.Drawing.Point(144, 160);
this.listAffixWords.Name = "listAffixWords";
this.listAffixWords.Size = new System.Drawing.Size(256, 69);
this.listAffixWords.TabIndex = 18;
//
// label8
//
this.label8.Location = new System.Drawing.Point(80, 88);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(64, 16);
this.label8.TabIndex = 17;
this.label8.Text = "Affix Keys:";
//
// label7
//
this.label7.Location = new System.Drawing.Point(72, 64);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(64, 16);
this.label7.TabIndex = 16;
this.label7.Text = "Base Word:";
//
// label4
//
this.label4.Location = new System.Drawing.Point(16, 32);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(128, 17);
this.label4.TabIndex = 7;
this.label4.Text = "Current Word Raw Text:";
//
// txtCurrentWord
//
this.txtCurrentWord.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtCurrentWord.Location = new System.Drawing.Point(144, 32);
this.txtCurrentWord.Name = "txtCurrentWord";
this.txtCurrentWord.ReadOnly = true;
this.txtCurrentWord.Size = new System.Drawing.Size(256, 20);
this.txtCurrentWord.TabIndex = 6;
this.txtCurrentWord.Text = "";
//
// numUpDownWord
//
this.numUpDownWord.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.numUpDownWord.Location = new System.Drawing.Point(416, 32);
this.numUpDownWord.Name = "numUpDownWord";
this.numUpDownWord.Size = new System.Drawing.Size(72, 20);
this.numUpDownWord.TabIndex = 5;
this.numUpDownWord.KeyUp += new System.Windows.Forms.KeyEventHandler(this.numUpDownWord_KeyUp);
this.numUpDownWord.ValueChanged += new System.EventHandler(this.numUpDownWord_ValueChanged);
//
// txtWordCount
//
this.txtWordCount.Location = new System.Drawing.Point(152, 24);
this.txtWordCount.Name = "txtWordCount";
this.txtWordCount.ReadOnly = true;
this.txtWordCount.Size = new System.Drawing.Size(64, 20);
this.txtWordCount.TabIndex = 1;
this.txtWordCount.Text = "0";
//
// label3
//
this.label3.Location = new System.Drawing.Point(48, 24);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(96, 16);
this.label3.TabIndex = 0;
this.label3.Text = "Base Word Count:";
//
// mainMenu
//
this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuDictionary});
//
// menuDictionary
//
this.menuDictionary.Index = 0;
this.menuDictionary.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuWords,
this.menuAffix,
this.menuItem3,
this.menuPhonetic,
this.menuItem5,
this.menuGenerate});
this.menuDictionary.MergeOrder = 3;
this.menuDictionary.MergeType = System.Windows.Forms.MenuMerge.MergeItems;
this.menuDictionary.Text = "Dictionary";
//
// menuWords
//
this.menuWords.Index = 0;
this.menuWords.Text = "Add OpenOffice Word List";
this.menuWords.Click += new System.EventHandler(this.menuWords_Click);
//
// menuAffix
//
this.menuAffix.Index = 1;
this.menuAffix.Text = "Add OpenOffice Affix Data";
this.menuAffix.Click += new System.EventHandler(this.menuAffix_Click);
//
// menuItem3
//
this.menuItem3.Index = 2;
this.menuItem3.Text = "-";
//
// menuPhonetic
//
this.menuPhonetic.Index = 3;
this.menuPhonetic.Text = "Add Aspell Phonetic Rules";
this.menuPhonetic.Click += new System.EventHandler(this.menuPhonetic_Click);
//
// menuItem5
//
this.menuItem5.Index = 4;
this.menuItem5.Text = "-";
//
// menuGenerate
//
this.menuGenerate.Index = 5;
this.menuGenerate.Text = "Generate Phonetic Cache";
this.menuGenerate.Click += new System.EventHandler(this.menuGenerate_Click);
//
// saveDictionaryDialog
//
this.saveDictionaryDialog.DefaultExt = "dic";
this.saveDictionaryDialog.Filter = "Dictionary files (*.dic)|*.dic|Text files (*.txt)|*.txt|All files (*.*)|*.*";
//
// openDictionaryDialog
//
this.openDictionaryDialog.Filter = "Dictionary files (*.dic)|*.dic|Text files (*.txt)|*.txt|All files (*.*)|*.*";
//
// openWordsDialog
//
this.openWordsDialog.Filter = "Dictionary files (*.dic)|*.dic|Text files (*.txt)|*.txt|All files (*.*)|*.*";
//
// openAffixDialog
//
this.openAffixDialog.Filter = "Affix files (*.aff)|*.aff|Text files (*.txt)|*.txt|All files (*.*)|*.*";
//
// openPhoneticDialog
//
this.openPhoneticDialog.Filter = "Phonetic files (*.dat)|*.dat|Text files (*.txt)|*.txt|All files (*.*)|*.*";
//
// imageList1
//
this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
//
// DictionaryForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(552, 478);
this.Controls.Add(this.DictionaryTab);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Menu = this.mainMenu;
this.Name = "DictionaryForm";
this.Text = "untitled";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.Closing += new System.ComponentModel.CancelEventHandler(this.DictionaryForm_Closing);
this.DictionaryTab.ResumeLayout(false);
this.tabCopyright.ResumeLayout(false);
this.tabNearMiss.ResumeLayout(false);
this.tabPrefix.ResumeLayout(false);
this.tabSuffix.ResumeLayout(false);
this.tabPhonetic.ResumeLayout(false);
this.tabWords.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numUpDownWord)).EndInit();
this.ResumeLayout(false);
}
#endregion
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// ContentDocument Feed
///<para>SObject Name: ContentDocumentFeed</para>
///<para>Custom Object: False</para>
///</summary>
public class SfContentDocumentFeed : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "ContentDocumentFeed"; }
}
///<summary>
/// Feed Item ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Parent ID
/// <para>Name: ParentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "parentId")]
[Updateable(false), Createable(false)]
public string ParentId { get; set; }
///<summary>
/// ReferenceTo: ContentDocument
/// <para>RelationshipName: Parent</para>
///</summary>
[JsonProperty(PropertyName = "parent")]
[Updateable(false), Createable(false)]
public SfContentDocument Parent { get; set; }
///<summary>
/// Feed Item Type
/// <para>Name: Type</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "type")]
[Updateable(false), Createable(false)]
public string Type { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Comment Count
/// <para>Name: CommentCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "commentCount")]
[Updateable(false), Createable(false)]
public int? CommentCount { get; set; }
///<summary>
/// Like Count
/// <para>Name: LikeCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "likeCount")]
[Updateable(false), Createable(false)]
public int? LikeCount { get; set; }
///<summary>
/// Title
/// <para>Name: Title</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "title")]
[Updateable(false), Createable(false)]
public string Title { get; set; }
///<summary>
/// Body
/// <para>Name: Body</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "body")]
[Updateable(false), Createable(false)]
public string Body { get; set; }
///<summary>
/// Link Url
/// <para>Name: LinkUrl</para>
/// <para>SF Type: url</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "linkUrl")]
[Updateable(false), Createable(false)]
public string LinkUrl { get; set; }
///<summary>
/// Is Rich Text
/// <para>Name: IsRichText</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isRichText")]
[Updateable(false), Createable(false)]
public bool? IsRichText { get; set; }
///<summary>
/// Related Record ID
/// <para>Name: RelatedRecordId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "relatedRecordId")]
[Updateable(false), Createable(false)]
public string RelatedRecordId { get; set; }
///<summary>
/// InsertedBy ID
/// <para>Name: InsertedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "insertedById")]
[Updateable(false), Createable(false)]
public string InsertedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: InsertedBy</para>
///</summary>
[JsonProperty(PropertyName = "insertedBy")]
[Updateable(false), Createable(false)]
public SfUser InsertedBy { get; set; }
///<summary>
/// Best Comment ID
/// <para>Name: BestCommentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "bestCommentId")]
[Updateable(false), Createable(false)]
public string BestCommentId { get; set; }
///<summary>
/// ReferenceTo: FeedComment
/// <para>RelationshipName: BestComment</para>
///</summary>
[JsonProperty(PropertyName = "bestComment")]
[Updateable(false), Createable(false)]
public SfFeedComment BestComment { get; set; }
}
}
| |
//
// Copyright (c) 2014 .NET Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// Copyright (c) 2014 Couchbase, Inc. 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.
//using System;
using System.IO;
using Couchbase.Lite.Util;
using Sharpen;
namespace Couchbase.Lite.Util
{
/// <summary>
/// Utilities for encoding and decoding the Base64 representation of
/// binary data.
/// </summary>
/// <remarks>
/// Utilities for encoding and decoding the Base64 representation of
/// binary data. See RFCs <a
/// href="http://www.ietf.org/rfc/rfc2045.txt">2045</a> and <a
/// href="http://www.ietf.org/rfc/rfc3548.txt">3548</a>.
/// </remarks>
public class Base64
{
/// <summary>Default values for encoder/decoder flags.</summary>
/// <remarks>Default values for encoder/decoder flags.</remarks>
public const int Default = 0;
/// <summary>
/// Encoder flag bit to omit the padding '=' characters at the end
/// of the output (if any).
/// </summary>
/// <remarks>
/// Encoder flag bit to omit the padding '=' characters at the end
/// of the output (if any).
/// </remarks>
public const int NoPadding = 1;
/// <summary>
/// Encoder flag bit to omit all line terminators (i.e., the output
/// will be on one long line).
/// </summary>
/// <remarks>
/// Encoder flag bit to omit all line terminators (i.e., the output
/// will be on one long line).
/// </remarks>
public const int NoWrap = 2;
/// <summary>
/// Encoder flag bit to indicate lines should be terminated with a
/// CRLF pair instead of just an LF.
/// </summary>
/// <remarks>
/// Encoder flag bit to indicate lines should be terminated with a
/// CRLF pair instead of just an LF. Has no effect if
/// <code>NO_WRAP</code>
/// is specified as well.
/// </remarks>
public const int Crlf = 4;
/// <summary>
/// Encoder/decoder flag bit to indicate using the "URL and
/// filename safe" variant of Base64 (see RFC 3548 section 4) where
/// <code>-</code>
/// and
/// <code>_</code>
/// are used in place of
/// <code>+</code>
/// and
/// <code>/</code>
/// .
/// </summary>
public const int UrlSafe = 8;
/// <summary>
/// Flag to pass to
/// <see cref="Android.Util.Base64OutputStream">Android.Util.Base64OutputStream</see>
/// to indicate that it
/// should not close the output stream it is wrapping when it
/// itself is closed.
/// </summary>
public const int NoClose = 16;
internal abstract class Coder
{
public byte[] output;
public int op;
// --------------------------------------------------------
// shared code
// --------------------------------------------------------
/// <summary>Encode/decode another block of input data.</summary>
/// <remarks>
/// Encode/decode another block of input data. this.output is
/// provided by the caller, and must be big enough to hold all
/// the coded data. On exit, this.opwill be set to the length
/// of the coded data.
/// </remarks>
/// <param name="finish">
/// true if this is the final call to process for
/// this object. Will finalize the coder state and
/// include any final bytes in the output.
/// </param>
/// <returns>
/// true if the input so far is good; false if some
/// error has been detected in the input stream..
/// </returns>
public abstract bool Process(byte[] input, int offset, int len, bool finish);
/// <returns>
/// the maximum number of bytes a call to process()
/// could produce for the given number of input bytes. This may
/// be an overestimate.
/// </returns>
public abstract int MaxOutputSize(int len);
}
// --------------------------------------------------------
// decoding
// --------------------------------------------------------
/// <summary>
/// Decode the Base64-encoded data in input and return the data in
/// a new byte array.
/// </summary>
/// <remarks>
/// Decode the Base64-encoded data in input and return the data in
/// a new byte array.
/// <p>The padding '=' characters at the end are considered optional, but
/// if any are present, there must be the correct number of them.
/// </remarks>
/// <param name="str">
/// the input String to decode, which is converted to
/// bytes using the default charset
/// </param>
/// <param name="flags">
/// controls certain features of the decoded output.
/// Pass
/// <code>DEFAULT</code>
/// to decode standard Base64.
/// </param>
/// <exception cref="System.ArgumentException">
/// if the input contains
/// incorrect padding
/// </exception>
public static byte[] Decode(string str, int flags)
{
return Decode(Sharpen.Runtime.GetBytesForString(str), flags);
}
/// <summary>
/// Decode the Base64-encoded data in input and return the data in
/// a new byte array.
/// </summary>
/// <remarks>
/// Decode the Base64-encoded data in input and return the data in
/// a new byte array.
/// <p>The padding '=' characters at the end are considered optional, but
/// if any are present, there must be the correct number of them.
/// </remarks>
/// <param name="input">the input array to decode</param>
/// <param name="flags">
/// controls certain features of the decoded output.
/// Pass
/// <code>DEFAULT</code>
/// to decode standard Base64.
/// </param>
/// <exception cref="System.ArgumentException">
/// if the input contains
/// incorrect padding
/// </exception>
public static byte[] Decode(byte[] input, int flags)
{
return Decode(input, 0, input.Length, flags);
}
/// <summary>
/// Decode the Base64-encoded data in input and return the data in
/// a new byte array.
/// </summary>
/// <remarks>
/// Decode the Base64-encoded data in input and return the data in
/// a new byte array.
/// <p>The padding '=' characters at the end are considered optional, but
/// if any are present, there must be the correct number of them.
/// </remarks>
/// <param name="input">the data to decode</param>
/// <param name="offset">the position within the input array at which to start</param>
/// <param name="len">the number of bytes of input to decode</param>
/// <param name="flags">
/// controls certain features of the decoded output.
/// Pass
/// <code>DEFAULT</code>
/// to decode standard Base64.
/// </param>
/// <exception cref="System.ArgumentException">
/// if the input contains
/// incorrect padding
/// </exception>
public static byte[] Decode(byte[] input, int offset, int len, int flags)
{
// Allocate space for the most data the input could represent.
// (It could contain less if it contains whitespace, etc.)
Base64.Decoder decoder = new Base64.Decoder(flags, new byte[len * 3 / 4]);
if (!decoder.Process(input, offset, len, true))
{
throw new ArgumentException("bad base-64");
}
// Maybe we got lucky and allocated exactly enough output space.
if (decoder.op == decoder.output.Length)
{
return decoder.output;
}
// Need to shorten the array, so allocate a new one of the
// right size and copy.
byte[] temp = new byte[decoder.op];
System.Array.Copy(decoder.output, 0, temp, 0, decoder.op);
return temp;
}
internal class Decoder : Base64.Coder
{
/// <summary>
/// Lookup table for turning bytes into their position in the
/// Base64 alphabet.
/// </summary>
/// <remarks>
/// Lookup table for turning bytes into their position in the
/// Base64 alphabet.
/// </remarks>
private static readonly int Decode = new int[] { -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, -1, 0, 1, 2, 3,
4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25
, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39
, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1
, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
, -1, -1, -1, -1, -1 };
/// <summary>
/// Decode lookup table for the "web safe" variant (RFC 3548
/// sec.
/// </summary>
/// <remarks>
/// Decode lookup table for the "web safe" variant (RFC 3548
/// sec. 4) where - and _ replace + and /.
/// </remarks>
private static readonly int DecodeWebsafe = new int[] { -1, -1, -1, -1, -1, -1, -
1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -
1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -
1, -1, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, -1, 0, 1,
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, -1, -1, -1, -1, 63, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1 };
/// <summary>Non-data values in the DECODE arrays.</summary>
/// <remarks>Non-data values in the DECODE arrays.</remarks>
private const int Skip = -1;
private const int Equals = -2;
/// <summary>States 0-3 are reading through the next input tuple.</summary>
/// <remarks>
/// States 0-3 are reading through the next input tuple.
/// State 4 is having read one '=' and expecting exactly
/// one more.
/// State 5 is expecting no more data or padding characters
/// in the input.
/// State 6 is the error state; an error has been detected
/// in the input and no future input can "fix" it.
/// </remarks>
private int state;
private int value;
private readonly int[] alphabet;
public Decoder(int flags, byte[] output)
{
// state number (0 to 6)
this.output = output;
alphabet = ((flags & UrlSafe) == 0) ? Decode : DecodeWebsafe;
state = 0;
value = 0;
}
/// <returns>
/// an overestimate for the number of bytes
/// <code>len</code>
/// bytes could decode to.
/// </returns>
public override int MaxOutputSize(int len)
{
return len * 3 / 4 + 10;
}
/// <summary>Decode another block of input data.</summary>
/// <remarks>Decode another block of input data.</remarks>
/// <returns>
/// true if the state machine is still healthy. false if
/// bad base-64 data has been detected in the input stream.
/// </returns>
public override bool Process(byte[] input, int offset, int len, bool finish)
{
if (this.state == 6)
{
return false;
}
int p = offset;
len += offset;
// Using local variables makes the decoder about 12%
// faster than if we manipulate the member variables in
// the loop. (Even alphabet makes a measurable
// difference, which is somewhat surprising to me since
// the member variable is final.)
int state = this.state;
int value = this.value;
int op = 0;
byte[] output = this.output;
int[] alphabet = this.alphabet;
while (p < len)
{
// Try the fast path: we're starting a new tuple and the
// next four bytes of the input stream are all data
// bytes. This corresponds to going through states
// 0-1-2-3-0. We expect to use this method for most of
// the data.
//
// If any of the next four bytes of input are non-data
// (whitespace, etc.), value will end up negative. (All
// the non-data values in decode are small negative
// numbers, so shifting any of them up and or'ing them
// together will result in a value with its top bit set.)
//
// You can remove this whole block and the output should
// be the same, just slower.
if (state == 0)
{
while (p + 4 <= len && (value = ((alphabet[input[p] & unchecked((int)(0xff))] <<
18) | (alphabet[input[p + 1] & unchecked((int)(0xff))] << 12) | (alphabet[input[
p + 2] & unchecked((int)(0xff))] << 6) | (alphabet[input[p + 3] & unchecked((int
)(0xff))]))) >= 0)
{
output[op + 2] = unchecked((byte)value);
output[op + 1] = unchecked((byte)(value >> 8));
output[op] = unchecked((byte)(value >> 16));
op += 3;
p += 4;
}
if (p >= len)
{
break;
}
}
// The fast path isn't available -- either we've read a
// partial tuple, or the next four input bytes aren't all
// data, or whatever. Fall back to the slower state
// machine implementation.
int d = alphabet[input[p++] & unchecked((int)(0xff))];
switch (state)
{
case 0:
{
if (d >= 0)
{
value = d;
++state;
}
else
{
if (d != Skip)
{
this.state = 6;
return false;
}
}
break;
}
case 1:
{
if (d >= 0)
{
value = (value << 6) | d;
++state;
}
else
{
if (d != Skip)
{
this.state = 6;
return false;
}
}
break;
}
case 2:
{
if (d >= 0)
{
value = (value << 6) | d;
++state;
}
else
{
if (d == Equals)
{
// Emit the last (partial) output tuple;
// expect exactly one more padding character.
output[op++] = unchecked((byte)(value >> 4));
state = 4;
}
else
{
if (d != Skip)
{
this.state = 6;
return false;
}
}
}
break;
}
case 3:
{
if (d >= 0)
{
// Emit the output triple and return to state 0.
value = (value << 6) | d;
output[op + 2] = unchecked((byte)value);
output[op + 1] = unchecked((byte)(value >> 8));
output[op] = unchecked((byte)(value >> 16));
op += 3;
state = 0;
}
else
{
if (d == Equals)
{
// Emit the last (partial) output tuple;
// expect no further data or padding characters.
output[op + 1] = unchecked((byte)(value >> 2));
output[op] = unchecked((byte)(value >> 10));
op += 2;
state = 5;
}
else
{
if (d != Skip)
{
this.state = 6;
return false;
}
}
}
break;
}
case 4:
{
if (d == Equals)
{
++state;
}
else
{
if (d != Skip)
{
this.state = 6;
return false;
}
}
break;
}
case 5:
{
if (d != Skip)
{
this.state = 6;
return false;
}
break;
}
}
}
if (!finish)
{
// We're out of input, but a future call could provide
// more.
this.state = state;
this.value = value;
this.op = op;
return true;
}
switch (state)
{
case 0:
{
// Done reading input. Now figure out where we are left in
// the state machine and finish up.
// Output length is a multiple of three. Fine.
break;
}
case 1:
{
// Read one extra input byte, which isn't enough to
// make another output byte. Illegal.
this.state = 6;
return false;
}
case 2:
{
// Read two extra input bytes, enough to emit 1 more
// output byte. Fine.
output[op++] = unchecked((byte)(value >> 4));
break;
}
case 3:
{
// Read three extra input bytes, enough to emit 2 more
// output bytes. Fine.
output[op++] = unchecked((byte)(value >> 10));
output[op++] = unchecked((byte)(value >> 2));
break;
}
case 4:
{
// Read one padding '=' when we expected 2. Illegal.
this.state = 6;
return false;
}
case 5:
{
// Read all the padding '='s we expected and no more.
// Fine.
break;
}
}
this.state = state;
this.op = op;
return true;
}
}
// --------------------------------------------------------
// encoding
// --------------------------------------------------------
/// <summary>
/// Base64-encode the given data and return a newly allocated
/// String with the result.
/// </summary>
/// <remarks>
/// Base64-encode the given data and return a newly allocated
/// String with the result.
/// </remarks>
/// <param name="input">the data to encode</param>
/// <param name="flags">
/// controls certain features of the encoded output.
/// Passing
/// <code>DEFAULT</code>
/// results in output that
/// adheres to RFC 2045.
/// </param>
public static string EncodeToString(byte[] input, int flags)
{
try
{
return Sharpen.Runtime.GetStringForBytes(Encode(input, flags), "US-ASCII");
}
catch (UnsupportedEncodingException e)
{
// US-ASCII is guaranteed to be available.
throw new Exception(e);
}
}
/// <summary>
/// Base64-encode the given data and return a newly allocated
/// String with the result.
/// </summary>
/// <remarks>
/// Base64-encode the given data and return a newly allocated
/// String with the result.
/// </remarks>
/// <param name="input">the data to encode</param>
/// <param name="offset">
/// the position within the input array at which to
/// start
/// </param>
/// <param name="len">the number of bytes of input to encode</param>
/// <param name="flags">
/// controls certain features of the encoded output.
/// Passing
/// <code>DEFAULT</code>
/// results in output that
/// adheres to RFC 2045.
/// </param>
public static string EncodeToString(byte[] input, int offset, int len, int flags)
{
try
{
return Sharpen.Runtime.GetStringForBytes(Encode(input, offset, len, flags), "US-ASCII"
);
}
catch (UnsupportedEncodingException e)
{
// US-ASCII is guaranteed to be available.
throw new Exception(e);
}
}
/// <summary>
/// Base64-encode the given data and return a newly allocated
/// byte[] with the result.
/// </summary>
/// <remarks>
/// Base64-encode the given data and return a newly allocated
/// byte[] with the result.
/// </remarks>
/// <param name="input">the data to encode</param>
/// <param name="flags">
/// controls certain features of the encoded output.
/// Passing
/// <code>DEFAULT</code>
/// results in output that
/// adheres to RFC 2045.
/// </param>
public static byte[] Encode(byte[] input, int flags)
{
return Encode(input, 0, input.Length, flags);
}
/// <summary>
/// Base64-encode the given data and return a newly allocated
/// byte[] with the result.
/// </summary>
/// <remarks>
/// Base64-encode the given data and return a newly allocated
/// byte[] with the result.
/// </remarks>
/// <param name="input">the data to encode</param>
/// <param name="offset">
/// the position within the input array at which to
/// start
/// </param>
/// <param name="len">the number of bytes of input to encode</param>
/// <param name="flags">
/// controls certain features of the encoded output.
/// Passing
/// <code>DEFAULT</code>
/// results in output that
/// adheres to RFC 2045.
/// </param>
public static byte[] Encode(byte[] input, int offset, int len, int flags)
{
Base64.Encoder encoder = new Base64.Encoder(flags, null);
// Compute the exact length of the array we will produce.
int output_len = len / 3 * 4;
// Account for the tail of the data and the padding bytes, if any.
if (encoder.do_padding)
{
if (len % 3 > 0)
{
output_len += 4;
}
}
else
{
switch (len % 3)
{
case 0:
{
break;
}
case 1:
{
output_len += 2;
break;
}
case 2:
{
output_len += 3;
break;
}
}
}
// Account for the newlines, if any.
if (encoder.do_newline && len > 0)
{
output_len += (((len - 1) / (3 * Base64.Encoder.LineGroups)) + 1) * (encoder.do_cr
? 2 : 1);
}
encoder.output = new byte[output_len];
encoder.Process(input, offset, len, true);
System.Diagnostics.Debug.Assert(encoder.op == output_len);
return encoder.output;
}
internal class Encoder : Base64.Coder
{
/// <summary>Emit a new line every this many output tuples.</summary>
/// <remarks>
/// Emit a new line every this many output tuples. Corresponds to
/// a 76-character line length (the maximum allowable according to
/// <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>).
/// </remarks>
public const int LineGroups = 19;
/// <summary>
/// Lookup table for turning Base64 alphabet positions (6 bits)
/// into output bytes.
/// </summary>
/// <remarks>
/// Lookup table for turning Base64 alphabet positions (6 bits)
/// into output bytes.
/// </remarks>
private static readonly byte Encode = new byte[] { (byte)('A'), (byte)('B'), (byte
)('C'), (byte)('D'), (byte)('E'), (byte)('F'), (byte)('G'), (byte)('H'), (byte)(
'I'), (byte)('J'), (byte)('K'), (byte)('L'), (byte)('M'), (byte)('N'), (byte)('O'
), (byte)('P'), (byte)('Q'), (byte)('R'), (byte)('S'), (byte)('T'), (byte)('U'),
(byte)('V'), (byte)('W'), (byte)('X'), (byte)('Y'), (byte)('Z'), (byte)('a'), (byte
)('b'), (byte)('c'), (byte)('d'), (byte)('e'), (byte)('f'), (byte)('g'), (byte)(
'h'), (byte)('i'), (byte)('j'), (byte)('k'), (byte)('l'), (byte)('m'), (byte)('n'
), (byte)('o'), (byte)('p'), (byte)('q'), (byte)('r'), (byte)('s'), (byte)('t'),
(byte)('u'), (byte)('v'), (byte)('w'), (byte)('x'), (byte)('y'), (byte)('z'), (byte
)('0'), (byte)('1'), (byte)('2'), (byte)('3'), (byte)('4'), (byte)('5'), (byte)(
'6'), (byte)('7'), (byte)('8'), (byte)('9'), (byte)('+'), (byte)('/') };
/// <summary>
/// Lookup table for turning Base64 alphabet positions (6 bits)
/// into output bytes.
/// </summary>
/// <remarks>
/// Lookup table for turning Base64 alphabet positions (6 bits)
/// into output bytes.
/// </remarks>
private static readonly byte EncodeWebsafe = new byte[] { (byte)('A'), (byte)('B'
), (byte)('C'), (byte)('D'), (byte)('E'), (byte)('F'), (byte)('G'), (byte)('H'),
(byte)('I'), (byte)('J'), (byte)('K'), (byte)('L'), (byte)('M'), (byte)('N'), (byte
)('O'), (byte)('P'), (byte)('Q'), (byte)('R'), (byte)('S'), (byte)('T'), (byte)(
'U'), (byte)('V'), (byte)('W'), (byte)('X'), (byte)('Y'), (byte)('Z'), (byte)('a'
), (byte)('b'), (byte)('c'), (byte)('d'), (byte)('e'), (byte)('f'), (byte)('g'),
(byte)('h'), (byte)('i'), (byte)('j'), (byte)('k'), (byte)('l'), (byte)('m'), (byte
)('n'), (byte)('o'), (byte)('p'), (byte)('q'), (byte)('r'), (byte)('s'), (byte)(
't'), (byte)('u'), (byte)('v'), (byte)('w'), (byte)('x'), (byte)('y'), (byte)('z'
), (byte)('0'), (byte)('1'), (byte)('2'), (byte)('3'), (byte)('4'), (byte)('5'),
(byte)('6'), (byte)('7'), (byte)('8'), (byte)('9'), (byte)('-'), (byte)('_') };
private readonly byte[] tail;
internal int tailLen;
private int count;
public readonly bool do_padding;
public readonly bool do_newline;
public readonly bool do_cr;
private readonly byte[] alphabet;
public Encoder(int flags, byte[] output)
{
this.output = output;
do_padding = (flags & NoPadding) == 0;
do_newline = (flags & NoWrap) == 0;
do_cr = (flags & Crlf) != 0;
alphabet = ((flags & UrlSafe) == 0) ? Encode : EncodeWebsafe;
tail = new byte[2];
tailLen = 0;
count = do_newline ? LineGroups : -1;
}
/// <returns>
/// an overestimate for the number of bytes
/// <code>len</code>
/// bytes could encode to.
/// </returns>
public override int MaxOutputSize(int len)
{
return len * 8 / 5 + 10;
}
public override bool Process(byte[] input, int offset, int len, bool finish)
{
// Using local variables makes the encoder about 9% faster.
byte[] alphabet = this.alphabet;
byte[] output = this.output;
int op = 0;
int count = this.count;
int p = offset;
len += offset;
int v = -1;
switch (tailLen)
{
case 0:
{
// First we need to concatenate the tail of the previous call
// with any input bytes available now and see if we can empty
// the tail.
// There was no tail.
break;
}
case 1:
{
if (p + 2 <= len)
{
// A 1-byte tail with at least 2 bytes of
// input available now.
v = ((tail[0] & unchecked((int)(0xff))) << 16) | ((input[p++] & unchecked((int)(0xff
))) << 8) | (input[p++] & unchecked((int)(0xff)));
tailLen = 0;
}
break;
}
case 2:
{
if (p + 1 <= len)
{
// A 2-byte tail with at least 1 byte of input.
v = ((tail[0] & unchecked((int)(0xff))) << 16) | ((tail[1] & unchecked((int)(0xff
))) << 8) | (input[p++] & unchecked((int)(0xff)));
tailLen = 0;
}
break;
}
}
if (v != -1)
{
output[op++] = alphabet[(v >> 18) & unchecked((int)(0x3f))];
output[op++] = alphabet[(v >> 12) & unchecked((int)(0x3f))];
output[op++] = alphabet[(v >> 6) & unchecked((int)(0x3f))];
output[op++] = alphabet[v & unchecked((int)(0x3f))];
if (--count == 0)
{
if (do_cr)
{
output[op++] = (byte)('\r');
}
output[op++] = (byte)('\n');
count = LineGroups;
}
}
// At this point either there is no tail, or there are fewer
// than 3 bytes of input available.
// The main loop, turning 3 input bytes into 4 output bytes on
// each iteration.
while (p + 3 <= len)
{
v = ((input[p] & unchecked((int)(0xff))) << 16) | ((input[p + 1] & unchecked((int
)(0xff))) << 8) | (input[p + 2] & unchecked((int)(0xff)));
output[op] = alphabet[(v >> 18) & unchecked((int)(0x3f))];
output[op + 1] = alphabet[(v >> 12) & unchecked((int)(0x3f))];
output[op + 2] = alphabet[(v >> 6) & unchecked((int)(0x3f))];
output[op + 3] = alphabet[v & unchecked((int)(0x3f))];
p += 3;
op += 4;
if (--count == 0)
{
if (do_cr)
{
output[op++] = (byte)('\r');
}
output[op++] = (byte)('\n');
count = LineGroups;
}
}
if (finish)
{
// Finish up the tail of the input. Note that we need to
// consume any bytes in tail before any bytes
// remaining in input; there should be at most two bytes
// total.
if (p - tailLen == len - 1)
{
int t = 0;
v = ((tailLen > 0 ? tail[t++] : input[p++]) & unchecked((int)(0xff))) << 4;
tailLen -= t;
output[op++] = alphabet[(v >> 6) & unchecked((int)(0x3f))];
output[op++] = alphabet[v & unchecked((int)(0x3f))];
if (do_padding)
{
output[op++] = (byte)('=');
output[op++] = (byte)('=');
}
if (do_newline)
{
if (do_cr)
{
output[op++] = (byte)('\r');
}
output[op++] = (byte)('\n');
}
}
else
{
if (p - tailLen == len - 2)
{
int t = 0;
v = (((tailLen > 1 ? tail[t++] : input[p++]) & unchecked((int)(0xff))) << 10) | (
((tailLen > 0 ? tail[t++] : input[p++]) & unchecked((int)(0xff))) << 2);
tailLen -= t;
output[op++] = alphabet[(v >> 12) & unchecked((int)(0x3f))];
output[op++] = alphabet[(v >> 6) & unchecked((int)(0x3f))];
output[op++] = alphabet[v & unchecked((int)(0x3f))];
if (do_padding)
{
output[op++] = (byte)('=');
}
if (do_newline)
{
if (do_cr)
{
output[op++] = (byte)('\r');
}
output[op++] = (byte)('\n');
}
}
else
{
if (do_newline && op > 0 && count != LineGroups)
{
if (do_cr)
{
output[op++] = (byte)('\r');
}
output[op++] = (byte)('\n');
}
}
}
System.Diagnostics.Debug.Assert(tailLen == 0);
System.Diagnostics.Debug.Assert(p == len);
}
else
{
// Save the leftovers in tail to be consumed on the next
// call to encodeInternal.
if (p == len - 1)
{
tail[tailLen++] = input[p];
}
else
{
if (p == len - 2)
{
tail[tailLen++] = input[p];
tail[tailLen++] = input[p + 1];
}
}
}
this.op = op;
this.count = count;
return true;
}
}
private Base64()
{
}
// don't instantiate
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
namespace Microsoft.PythonTools.Project {
static class VirtualEnv {
private static readonly KeyValuePair<string, string>[] UnbufferedEnv = new[] {
new KeyValuePair<string, string>("PYTHONUNBUFFERED", "1")
};
/// <summary>
/// Installs virtualenv. If pip is not installed, the returned task will
/// succeed but error text will be passed to the redirector.
/// </summary>
public static Task<bool> Install(IServiceProvider provider, IPythonInterpreterFactory factory, Redirector output = null) {
bool elevate = provider.GetPythonToolsService().GeneralOptions.ElevatePip;
if (factory.Configuration.Version < new Version(2, 5)) {
if (output != null) {
output.WriteErrorLine("Python versions earlier than 2.5 are not supported by PTVS.");
}
throw new OperationCanceledException();
} else if (factory.Configuration.Version == new Version(2, 5)) {
return Pip.Install(provider, factory, "https://go.microsoft.com/fwlink/?LinkID=317970", elevate, output);
} else {
return Pip.Install(provider, factory, "https://go.microsoft.com/fwlink/?LinkID=317969", elevate, output);
}
}
private static async Task ContinueCreate(IServiceProvider provider, IPythonInterpreterFactory factory, string path, bool useVEnv, Redirector output) {
path = PathUtils.TrimEndSeparator(path);
var name = Path.GetFileName(path);
var dir = Path.GetDirectoryName(path);
if (output != null) {
output.WriteLine(Strings.VirtualEnvCreating.FormatUI(path));
if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForVirtualEnvCreate) {
output.ShowAndActivate();
} else {
output.Show();
}
}
// Ensure the target directory exists.
Directory.CreateDirectory(dir);
using (var proc = ProcessOutput.Run(
factory.Configuration.InterpreterPath,
new[] { "-m", useVEnv ? "venv" : "virtualenv", name },
dir,
UnbufferedEnv,
false,
output
)) {
var exitCode = await proc;
if (output != null) {
if (exitCode == 0) {
output.WriteLine(Strings.VirtualEnvCreationSucceeded.FormatUI(path));
} else {
output.WriteLine(Strings.VirtualEnvCreationFailedExitCode.FormatUI(path, exitCode));
}
if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForVirtualEnvCreate) {
output.ShowAndActivate();
} else {
output.Show();
}
}
if (exitCode != 0 || !Directory.Exists(path)) {
throw new InvalidOperationException(Strings.VirtualEnvCreationFailed.FormatUI(path));
}
}
}
/// <summary>
/// Creates a virtual environment. If virtualenv is not installed, the
/// task will succeed but error text will be passed to the redirector.
/// </summary>
public static Task Create(IServiceProvider provider, IPythonInterpreterFactory factory, string path, Redirector output = null) {
factory.ThrowIfNotRunnable();
return ContinueCreate(provider, factory, path, false, output);
}
/// <summary>
/// Creates a virtual environment using venv. If venv is not available,
/// the task will succeed but error text will be passed to the
/// redirector.
/// </summary>
public static Task CreateWithVEnv(IServiceProvider provider, IPythonInterpreterFactory factory, string path, Redirector output = null) {
factory.ThrowIfNotRunnable();
return ContinueCreate(provider, factory, path, true, output);
}
/// <summary>
/// Creates a virtual environment. If virtualenv or pip are not
/// installed then they are downloaded and installed automatically.
/// </summary>
public static async Task CreateAndInstallDependencies(
IServiceProvider provider,
IPythonInterpreterFactory factory,
string path,
Redirector output = null
) {
factory.ThrowIfNotRunnable("factory");
var modules = await factory.FindModulesAsync("pip", "virtualenv", "venv");
bool hasPip = modules.Contains("pip");
bool hasVirtualEnv = modules.Contains("virtualenv") || modules.Contains("venv");
if (!hasVirtualEnv) {
if (!hasPip) {
bool elevate = provider.GetPythonToolsService().GeneralOptions.ElevatePip;
await Pip.InstallPip(provider, factory, elevate, output);
}
if (!await Install(provider, factory, output)) {
throw new InvalidOperationException(Strings.VirtualEnvCreationFailed.FormatUI(path));
}
}
await ContinueCreate(provider, factory, path, false, output);
}
public static InterpreterConfiguration FindInterpreterConfiguration(
string id,
string prefixPath,
IInterpreterRegistryService service,
IPythonInterpreterFactory baseInterpreter = null
) {
var libPath = DerivedInterpreterFactory.FindLibPath(prefixPath);
if (baseInterpreter == null) {
baseInterpreter = DerivedInterpreterFactory.FindBaseInterpreterFromVirtualEnv(
prefixPath,
libPath,
service
);
if (baseInterpreter == null) {
return null;
}
}
// The interpreter name should be the same as the base interpreter.
string interpExe = Path.GetFileName(baseInterpreter.Configuration.InterpreterPath);
string winterpExe = Path.GetFileName(baseInterpreter.Configuration.WindowsInterpreterPath);
var scripts = new[] { "Scripts", "bin" };
interpExe = PathUtils.FindFile(prefixPath, interpExe, firstCheck: scripts);
winterpExe = PathUtils.FindFile(prefixPath, winterpExe, firstCheck: scripts);
string pathVar = baseInterpreter.Configuration.PathEnvironmentVariable;
string description = PathUtils.GetFileOrDirectoryName(prefixPath);
return new InterpreterConfiguration(
id ?? baseInterpreter.Configuration.Id,
description,
prefixPath,
interpExe,
winterpExe,
libPath,
pathVar,
baseInterpreter.Configuration.Architecture,
baseInterpreter.Configuration.Version,
InterpreterUIMode.CannotBeDefault | InterpreterUIMode.CannotBeConfigured | InterpreterUIMode.SupportsDatabase,
baseInterpreter != null ? string.Format("({0})", baseInterpreter.Configuration.FullDescription) : ""
);
}
// This helper function is not yet needed, but may be useful at some point.
//public static string FindLibPathFromInterpreter(string interpreterPath) {
// using (var output = ProcessOutput.RunHiddenAndCapture(interpreterPath, "-c", "import site; print(site.__file__)")) {
// output.Wait();
// return output.StandardOutputLines
// .Where(PathUtils.IsValidPath)
// .Select(line => Path.GetDirectoryName(line))
// .LastOrDefault(dir => Directory.Exists(dir));
// }
//}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Design;
using System.Windows.Forms.Design;
using System.ComponentModel;
namespace Oranikle.DesignBase.UI.Docking
{
#region DockPanelSkin classes
/// <summary>
/// The skin to use when displaying the DockPanel.
/// The skin allows custom gradient color schemes to be used when drawing the
/// DockStrips and Tabs.
/// </summary>
[TypeConverter(typeof(DockPanelSkinConverter))]
public class DockPanelSkin
{
private AutoHideStripSkin m_autoHideStripSkin;
private DockPaneStripSkin m_dockPaneStripSkin;
public DockPanelSkin()
{
m_autoHideStripSkin = new AutoHideStripSkin();
m_dockPaneStripSkin = new DockPaneStripSkin();
}
/// <summary>
/// The skin used to display the auto hide strips and tabs.
/// </summary>
public AutoHideStripSkin AutoHideStripSkin
{
get { return m_autoHideStripSkin; }
set { m_autoHideStripSkin = value; }
}
/// <summary>
/// The skin used to display the Document and ToolWindow style DockStrips and Tabs.
/// </summary>
public DockPaneStripSkin DockPaneStripSkin
{
get { return m_dockPaneStripSkin; }
set { m_dockPaneStripSkin = value; }
}
}
/// <summary>
/// The skin used to display the auto hide strip and tabs.
/// </summary>
[TypeConverter(typeof(AutoHideStripConverter))]
public class AutoHideStripSkin
{
private DockPanelGradient m_dockStripGradient;
private TabGradient m_TabGradient;
public AutoHideStripSkin()
{
m_dockStripGradient = new DockPanelGradient();
m_dockStripGradient.StartColor = SystemColors.ControlLight;
m_dockStripGradient.EndColor = SystemColors.ControlLight;
m_TabGradient = new TabGradient();
m_TabGradient.TextColor = SystemColors.ControlDarkDark;
}
/// <summary>
/// The gradient color skin for the DockStrips.
/// </summary>
public DockPanelGradient DockStripGradient
{
get { return m_dockStripGradient; }
set { m_dockStripGradient = value; }
}
/// <summary>
/// The gradient color skin for the Tabs.
/// </summary>
public TabGradient TabGradient
{
get { return m_TabGradient; }
set { m_TabGradient = value; }
}
}
/// <summary>
/// The skin used to display the document and tool strips and tabs.
/// </summary>
[TypeConverter(typeof(DockPaneStripConverter))]
public class DockPaneStripSkin
{
private DockPaneStripGradient m_DocumentGradient;
private DockPaneStripToolWindowGradient m_ToolWindowGradient;
public DockPaneStripSkin()
{
m_DocumentGradient = new DockPaneStripGradient();
m_DocumentGradient.DockStripGradient.StartColor = SystemColors.Control;
m_DocumentGradient.DockStripGradient.EndColor = SystemColors.Control;
m_DocumentGradient.ActiveTabGradient.StartColor = SystemColors.ControlLightLight;
m_DocumentGradient.ActiveTabGradient.EndColor = SystemColors.ControlLightLight;
m_DocumentGradient.InactiveTabGradient.StartColor = SystemColors.ControlLight;
m_DocumentGradient.InactiveTabGradient.EndColor = SystemColors.ControlLight;
m_ToolWindowGradient = new DockPaneStripToolWindowGradient();
m_ToolWindowGradient.DockStripGradient.StartColor = SystemColors.ControlLight;
m_ToolWindowGradient.DockStripGradient.EndColor = SystemColors.ControlLight;
m_ToolWindowGradient.ActiveTabGradient.StartColor = SystemColors.Control;
m_ToolWindowGradient.ActiveTabGradient.EndColor = SystemColors.Control;
m_ToolWindowGradient.InactiveTabGradient.StartColor = Color.Transparent;
m_ToolWindowGradient.InactiveTabGradient.EndColor = Color.Transparent;
m_ToolWindowGradient.InactiveTabGradient.TextColor = SystemColors.ControlDarkDark;
m_ToolWindowGradient.ActiveCaptionGradient.StartColor = SystemColors.GradientActiveCaption;
m_ToolWindowGradient.ActiveCaptionGradient.EndColor = SystemColors.ActiveCaption;
m_ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical;
m_ToolWindowGradient.ActiveCaptionGradient.TextColor = SystemColors.ActiveCaptionText;
m_ToolWindowGradient.InactiveCaptionGradient.StartColor = SystemColors.GradientInactiveCaption;
m_ToolWindowGradient.InactiveCaptionGradient.EndColor = SystemColors.GradientInactiveCaption;
m_ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical;
m_ToolWindowGradient.InactiveCaptionGradient.TextColor = SystemColors.ControlText;
}
/// <summary>
/// The skin used to display the Document style DockPane strip and tab.
/// </summary>
public DockPaneStripGradient DocumentGradient
{
get { return m_DocumentGradient; }
set { m_DocumentGradient = value; }
}
/// <summary>
/// The skin used to display the ToolWindow style DockPane strip and tab.
/// </summary>
public DockPaneStripToolWindowGradient ToolWindowGradient
{
get { return m_ToolWindowGradient; }
set { m_ToolWindowGradient = value; }
}
}
/// <summary>
/// The skin used to display the DockPane ToolWindow strip and tab.
/// </summary>
[TypeConverter(typeof(DockPaneStripGradientConverter))]
public class DockPaneStripToolWindowGradient : DockPaneStripGradient
{
private TabGradient m_activeCaptionGradient;
private TabGradient m_inactiveCaptionGradient;
public DockPaneStripToolWindowGradient()
{
m_activeCaptionGradient = new TabGradient();
m_inactiveCaptionGradient = new TabGradient();
}
/// <summary>
/// The skin used to display the active ToolWindow caption.
/// </summary>
public TabGradient ActiveCaptionGradient
{
get { return m_activeCaptionGradient; }
set { m_activeCaptionGradient = value; }
}
/// <summary>
/// The skin used to display the inactive ToolWindow caption.
/// </summary>
public TabGradient InactiveCaptionGradient
{
get { return m_inactiveCaptionGradient; }
set { m_inactiveCaptionGradient = value; }
}
}
/// <summary>
/// The skin used to display the DockPane strip and tab.
/// </summary>
[TypeConverter(typeof(DockPaneStripGradientConverter))]
public class DockPaneStripGradient
{
private DockPanelGradient m_dockStripGradient;
private TabGradient m_activeTabGradient;
private TabGradient m_inactiveTabGradient;
public DockPaneStripGradient()
{
m_dockStripGradient = new DockPanelGradient();
m_activeTabGradient = new TabGradient();
m_inactiveTabGradient = new TabGradient();
}
/// <summary>
/// The gradient color skin for the DockStrip.
/// </summary>
public DockPanelGradient DockStripGradient
{
get { return m_dockStripGradient; }
set { m_dockStripGradient = value; }
}
/// <summary>
/// The skin used to display the active DockPane tabs.
/// </summary>
public TabGradient ActiveTabGradient
{
get { return m_activeTabGradient; }
set { m_activeTabGradient = value; }
}
/// <summary>
/// The skin used to display the inactive DockPane tabs.
/// </summary>
public TabGradient InactiveTabGradient
{
get { return m_inactiveTabGradient; }
set { m_inactiveTabGradient = value; }
}
}
/// <summary>
/// The skin used to display the dock pane tab
/// </summary>
[TypeConverter(typeof(DockPaneTabGradientConverter))]
public class TabGradient : DockPanelGradient
{
private Color m_textColor;
public TabGradient()
{
m_textColor = SystemColors.ControlText;
}
/// <summary>
/// The text color.
/// </summary>
[DefaultValue(typeof(SystemColors), "ControlText")]
public Color TextColor
{
get { return m_textColor; }
set { m_textColor = value; }
}
}
/// <summary>
/// The gradient color skin.
/// </summary>
[TypeConverter(typeof(DockPanelGradientConverter))]
public class DockPanelGradient
{
private Color m_startColor;
private Color m_endColor;
private LinearGradientMode m_linearGradientMode;
public DockPanelGradient()
{
m_startColor = SystemColors.Control;
m_endColor = SystemColors.Control;
m_linearGradientMode = LinearGradientMode.Horizontal;
}
/// <summary>
/// The beginning gradient color.
/// </summary>
[DefaultValue(typeof(SystemColors), "Control")]
public Color StartColor
{
get { return m_startColor; }
set { m_startColor = value; }
}
/// <summary>
/// The ending gradient color.
/// </summary>
[DefaultValue(typeof(SystemColors), "Control")]
public Color EndColor
{
get { return m_endColor; }
set { m_endColor = value; }
}
/// <summary>
/// The gradient mode to display the colors.
/// </summary>
[DefaultValue(LinearGradientMode.Horizontal)]
public LinearGradientMode LinearGradientMode
{
get { return m_linearGradientMode; }
set { m_linearGradientMode = value; }
}
}
#endregion
#region Converters
public class DockPanelSkinConverter : ExpandableObjectConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(DockPanelSkin))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(String) && value is DockPanelSkin)
{
return "DockPanelSkin";
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
public class DockPanelGradientConverter : ExpandableObjectConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(DockPanelGradient))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(String) && value is DockPanelGradient)
{
return "DockPanelGradient";
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
public class AutoHideStripConverter : ExpandableObjectConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(AutoHideStripSkin))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(String) && value is AutoHideStripSkin)
{
return "AutoHideStripSkin";
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
public class DockPaneStripConverter : ExpandableObjectConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(DockPaneStripSkin))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(String) && value is DockPaneStripSkin)
{
return "DockPaneStripSkin";
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
public class DockPaneStripGradientConverter : ExpandableObjectConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(DockPaneStripGradient))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(String) && value is DockPaneStripGradient)
{
return "DockPaneStripGradient";
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
public class DockPaneTabGradientConverter : ExpandableObjectConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(TabGradient))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(String) && value is TabGradient)
{
return "DockPaneTabGradient";
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
#endregion
}
| |
/*
* 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 OpenMetaverse.StructuredData;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace OpenSim.Framework.Monitoring
{
/// <summary>
/// Measures of interest for this stat.
/// </summary>
[Flags]
public enum MeasuresOfInterest
{
None,
AverageChangeOverTime
}
/// <summary>
/// Stat type.
/// </summary>
/// <remarks>
/// A push stat is one which is continually updated and so it's value can simply by read.
/// A pull stat is one where reading the value triggers a collection method - the stat is not continually updated.
/// </remarks>
public enum StatType
{
Push,
Pull
}
/// <summary>
/// Verbosity of stat.
/// </summary>
/// <remarks>
/// Info will always be displayed.
/// </remarks>
public enum StatVerbosity
{
Debug,
Info
}
/// <summary>
/// Static class used to register/deregister/fetch statistics
/// </summary>
public static class StatsManager
{
// Subcommand used to list other stats.
public const string AllSubCommand = "all";
// Subcommand used to list other stats.
public const string ListSubCommand = "list";
/// <summary>
/// Registered stats categorized by category/container/shortname
/// </summary>
/// <remarks>
/// Do not add or remove directly from this dictionary.
/// </remarks>
public static SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Stat>>> RegisteredStats
= new SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Stat>>>();
// All subcommands
public static HashSet<string> SubCommands = new HashSet<string> { AllSubCommand, ListSubCommand };
// private static AssetStatsCollector assetStats;
// private static UserStatsCollector userStats;
// private static SimExtraStatsCollector simExtraStats = new SimExtraStatsCollector();
// public static AssetStatsCollector AssetStats { get { return assetStats; } }
// public static UserStatsCollector UserStats { get { return userStats; } }
public static SimExtraStatsCollector SimExtraStats { get; set; }
/// <summary>
/// Deregister a statistic
/// </summary>>
/// <param name='stat'></param>
/// <returns></returns>
public static bool DeregisterStat(Stat stat)
{
SortedDictionary<string, SortedDictionary<string, Stat>> category = null, newCategory;
SortedDictionary<string, Stat> container = null, newContainer;
lock (RegisteredStats)
{
if (!TryGetStatParents(stat, out category, out container))
return false;
newContainer = new SortedDictionary<string, Stat>(container);
newContainer.Remove(stat.ShortName);
newCategory = new SortedDictionary<string, SortedDictionary<string, Stat>>(category);
newCategory.Remove(stat.Container);
newCategory[stat.Container] = newContainer;
RegisteredStats[stat.Category] = newCategory;
return true;
}
}
public static List<string> GetAllStatsReports()
{
List<string> reports = new List<string>();
foreach (var category in RegisteredStats.Values)
reports.AddRange(GetCategoryStatsReports(category));
return reports;
}
// Creates an OSDMap of the format:
// { categoryName: {
// containerName: {
// statName: {
// "Name": name,
// "ShortName": shortName,
// ...
// },
// statName: {
// "Name": name,
// "ShortName": shortName,
// ...
// },
// ...
// },
// containerName: {
// ...
// },
// ...
// },
// categoryName: {
// ...
// },
// ...
// }
// The passed in parameters will filter the categories, containers and stats returned. If any of the
// parameters are either EmptyOrNull or the AllSubCommand value, all of that type will be returned.
// Case matters.
public static OSDMap GetStatsAsOSDMap(string pCategoryName, string pContainerName, string pStatName)
{
OSDMap map = new OSDMap();
foreach (string catName in RegisteredStats.Keys)
{
// Do this category if null spec, "all" subcommand or category name matches passed parameter.
// Skip category if none of the above.
if (!(String.IsNullOrEmpty(pCategoryName) || pCategoryName == AllSubCommand || pCategoryName == catName))
continue;
OSDMap contMap = new OSDMap();
foreach (string contName in RegisteredStats[catName].Keys)
{
if (!(string.IsNullOrEmpty(pContainerName) || pContainerName == AllSubCommand || pContainerName == contName))
continue;
OSDMap statMap = new OSDMap();
SortedDictionary<string, Stat> theStats = RegisteredStats[catName][contName];
foreach (string statName in theStats.Keys)
{
if (!(String.IsNullOrEmpty(pStatName) || pStatName == AllSubCommand || pStatName == statName))
continue;
statMap.Add(statName, theStats[statName].ToOSDMap());
}
contMap.Add(contName, statMap);
}
map.Add(catName, contMap);
}
return map;
}
/// <summary>
/// Get the same stat for each container in a given category.
/// </summary>
/// <returns>
/// The stats if there were any to fetch. Otherwise null.
/// </returns>
/// <param name='category'></param>
/// <param name='statShortName'></param>
public static List<Stat> GetStatsFromEachContainer(string category, string statShortName)
{
SortedDictionary<string, SortedDictionary<string, Stat>> categoryStats;
lock (RegisteredStats)
{
if (!RegisteredStats.TryGetValue(category, out categoryStats))
return null;
List<Stat> stats = null;
foreach (SortedDictionary<string, Stat> containerStats in categoryStats.Values)
{
if (containerStats.ContainsKey(statShortName))
{
if (stats == null)
stats = new List<Stat>();
stats.Add(containerStats[statShortName]);
}
}
return stats;
}
}
public static void HandleShowStatsCommand(string module, string[] cmd)
{
ICommandConsole con = MainConsole.Instance;
if (cmd.Length > 2)
{
foreach (string name in cmd.Skip(2))
{
string[] components = name.Split('.');
string categoryName = components[0];
string containerName = components.Length > 1 ? components[1] : null;
string statName = components.Length > 2 ? components[2] : null;
if (categoryName == AllSubCommand)
{
OutputAllStatsToConsole(con);
}
else if (categoryName == ListSubCommand)
{
con.Output("Statistic categories available are:");
foreach (string category in RegisteredStats.Keys)
con.OutputFormat(" {0}", category);
}
else
{
SortedDictionary<string, SortedDictionary<string, Stat>> category;
if (!RegisteredStats.TryGetValue(categoryName, out category))
{
con.OutputFormat("No such category as {0}", categoryName);
}
else
{
if (String.IsNullOrEmpty(containerName))
{
OutputCategoryStatsToConsole(con, category);
}
else
{
SortedDictionary<string, Stat> container;
if (category.TryGetValue(containerName, out container))
{
if (String.IsNullOrEmpty(statName))
{
OutputContainerStatsToConsole(con, container);
}
else
{
Stat stat;
if (container.TryGetValue(statName, out stat))
{
OutputStatToConsole(con, stat);
}
else
{
con.OutputFormat(
"No such stat {0} in {1}.{2}", statName, categoryName, containerName);
}
}
}
else
{
con.OutputFormat("No such container {0} in category {1}", containerName, categoryName);
}
}
}
}
}
}
else
{
// Legacy
if (SimExtraStats != null)
con.Output(SimExtraStats.Report());
else
OutputAllStatsToConsole(con);
}
}
public static Hashtable HandleStatsRequest(Hashtable request)
{
Hashtable responsedata = new Hashtable();
// string regpath = request["uri"].ToString();
int response_code = 200;
string contenttype = "text/json";
string pCategoryName = StatsManager.AllSubCommand;
string pContainerName = StatsManager.AllSubCommand;
string pStatName = StatsManager.AllSubCommand;
if (request.ContainsKey("cat")) pCategoryName = request["cat"].ToString();
if (request.ContainsKey("cont")) pContainerName = request["cat"].ToString();
if (request.ContainsKey("stat")) pStatName = request["cat"].ToString();
string strOut = StatsManager.GetStatsAsOSDMap(pCategoryName, pContainerName, pStatName).ToString();
// If requestor wants it as a callback function, build response as a function rather than just the JSON string.
if (request.ContainsKey("callback"))
{
strOut = request["callback"].ToString() + "(" + strOut + ");";
}
// m_log.DebugFormat("{0} StatFetch: uri={1}, cat={2}, cont={3}, stat={4}, resp={5}",
// LogHeader, regpath, pCategoryName, pContainerName, pStatName, strOut);
responsedata["int_response_code"] = response_code;
responsedata["content_type"] = contenttype;
responsedata["keepalive"] = false;
responsedata["str_response_string"] = strOut;
responsedata["access_control_allow_origin"] = "*";
return responsedata;
}
public static void RecordStats()
{
lock (RegisteredStats)
{
foreach (SortedDictionary<string, SortedDictionary<string, Stat>> category in RegisteredStats.Values)
{
foreach (SortedDictionary<string, Stat> container in category.Values)
{
foreach (Stat stat in container.Values)
{
if (stat.MeasuresOfInterest != MeasuresOfInterest.None)
stat.RecordValue();
}
}
}
}
}
public static void RegisterConsoleCommands(ICommandConsole console)
{
console.Commands.AddCommand(
"General",
false,
"stats show",
"stats show [list|all|(<category>[.<container>])+",
"Show statistical information for this server",
"If no final argument is specified then legacy statistics information is currently shown.\n"
+ "'list' argument will show statistic categories.\n"
+ "'all' will show all statistics.\n"
+ "A <category> name will show statistics from that category.\n"
+ "A <category>.<container> name will show statistics from that category in that container.\n"
+ "More than one name can be given separated by spaces.\n"
+ "THIS STATS FACILITY IS EXPERIMENTAL AND DOES NOT YET CONTAIN ALL STATS",
HandleShowStatsCommand);
console.Commands.AddCommand(
"General",
false,
"show stats",
"show stats [list|all|(<category>[.<container>])+",
"Alias for 'stats show' command",
HandleShowStatsCommand);
StatsLogger.RegisterConsoleCommands(console);
}
/// <summary>
/// Register a statistic.
/// </summary>
/// <param name='stat'></param>
/// <returns></returns>
public static bool RegisterStat(Stat stat)
{
SortedDictionary<string, SortedDictionary<string, Stat>> category = null, newCategory;
SortedDictionary<string, Stat> container = null, newContainer;
lock (RegisteredStats)
{
// Stat name is not unique across category/container/shortname key.
// XXX: For now just return false. This is to avoid problems in regression tests where all tests
// in a class are run in the same instance of the VM.
if (TryGetStatParents(stat, out category, out container))
return false;
// We take a copy-on-write approach here of replacing dictionaries when keys are added or removed.
// This means that we don't need to lock or copy them on iteration, which will be a much more
// common operation after startup.
if (container != null)
newContainer = new SortedDictionary<string, Stat>(container);
else
newContainer = new SortedDictionary<string, Stat>();
if (category != null)
newCategory = new SortedDictionary<string, SortedDictionary<string, Stat>>(category);
else
newCategory = new SortedDictionary<string, SortedDictionary<string, Stat>>();
newContainer[stat.ShortName] = stat;
newCategory[stat.Container] = newContainer;
RegisteredStats[stat.Category] = newCategory;
}
return true;
}
// /// <summary>
// /// Start collecting statistics related to assets.
// /// Should only be called once.
// /// </summary>
// public static AssetStatsCollector StartCollectingAssetStats()
// {
// assetStats = new AssetStatsCollector();
//
// return assetStats;
// }
//
// /// <summary>
// /// Start collecting statistics related to users.
// /// Should only be called once.
// /// </summary>
// public static UserStatsCollector StartCollectingUserStats()
// {
// userStats = new UserStatsCollector();
//
// return userStats;
// }
public static bool TryGetStat(string category, string container, string statShortName, out Stat stat)
{
stat = null;
SortedDictionary<string, SortedDictionary<string, Stat>> categoryStats;
lock (RegisteredStats)
{
if (!TryGetStatsForCategory(category, out categoryStats))
return false;
SortedDictionary<string, Stat> containerStats;
if (!categoryStats.TryGetValue(container, out containerStats))
return false;
return containerStats.TryGetValue(statShortName, out stat);
}
}
public static bool TryGetStatParents(
Stat stat,
out SortedDictionary<string, SortedDictionary<string, Stat>> category,
out SortedDictionary<string, Stat> container)
{
category = null;
container = null;
lock (RegisteredStats)
{
if (RegisteredStats.TryGetValue(stat.Category, out category))
{
if (category.TryGetValue(stat.Container, out container))
{
if (container.ContainsKey(stat.ShortName))
return true;
}
}
}
return false;
}
public static bool TryGetStatsForCategory(
string category, out SortedDictionary<string, SortedDictionary<string, Stat>> stats)
{
lock (RegisteredStats)
return RegisteredStats.TryGetValue(category, out stats);
}
private static List<string> GetCategoryStatsReports(
SortedDictionary<string, SortedDictionary<string, Stat>> category)
{
List<string> reports = new List<string>();
foreach (var container in category.Values)
reports.AddRange(GetContainerStatsReports(container));
return reports;
}
private static List<string> GetContainerStatsReports(SortedDictionary<string, Stat> container)
{
List<string> reports = new List<string>();
foreach (Stat stat in container.Values)
reports.Add(stat.ToConsoleString());
return reports;
}
private static void OutputAllStatsToConsole(ICommandConsole con)
{
foreach (string report in GetAllStatsReports())
con.Output(report);
}
private static void OutputCategoryStatsToConsole(
ICommandConsole con, SortedDictionary<string, SortedDictionary<string, Stat>> category)
{
foreach (string report in GetCategoryStatsReports(category))
con.Output(report);
}
private static void OutputContainerStatsToConsole(
ICommandConsole con, SortedDictionary<string, Stat> container)
{
foreach (string report in GetContainerStatsReports(container))
con.Output(report);
}
private static void OutputStatToConsole(ICommandConsole con, Stat stat)
{
con.Output(stat.ToConsoleString());
}
}
}
| |
// 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.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using Microsoft.Internal.Collections;
namespace System.ComponentModel.Composition.ReflectionModel
{
internal class ReflectionComposablePartDefinition : ComposablePartDefinition, ICompositionElement
{
private readonly IReflectionPartCreationInfo _creationInfo;
private volatile ImportDefinition[] _imports;
private volatile ExportDefinition[] _exports;
private volatile IDictionary<string, object> _metadata;
private volatile ConstructorInfo _constructor;
private readonly object _lock = new object();
public ReflectionComposablePartDefinition(IReflectionPartCreationInfo creationInfo)
{
if (creationInfo == null)
{
throw new ArgumentNullException(nameof(creationInfo));
}
_creationInfo = creationInfo;
}
public Type GetPartType()
{
return _creationInfo.GetPartType();
}
public Lazy<Type> GetLazyPartType()
{
return _creationInfo.GetLazyPartType();
}
public ConstructorInfo GetConstructor()
{
if (_constructor == null)
{
ConstructorInfo constructor = _creationInfo.GetConstructor();
lock (_lock)
{
if (_constructor == null)
{
_constructor = constructor;
}
}
}
return _constructor;
}
private ExportDefinition[] ExportDefinitionsInternal
{
get
{
if (_exports == null)
{
ExportDefinition[] exports = _creationInfo.GetExports().ToArray();
lock (_lock)
{
if (_exports == null)
{
_exports = exports;
}
}
}
return _exports;
}
}
public override IEnumerable<ExportDefinition> ExportDefinitions
{
get
{
return ExportDefinitionsInternal;
}
}
public override IEnumerable<ImportDefinition> ImportDefinitions
{
get
{
if (_imports == null)
{
ImportDefinition[] imports = _creationInfo.GetImports().ToArray();
lock (_lock)
{
if (_imports == null)
{
_imports = imports;
}
}
}
return _imports;
}
}
public override IDictionary<string, object> Metadata
{
get
{
if (_metadata == null)
{
IDictionary<string, object> metadata = _creationInfo.GetMetadata().AsReadOnly();
lock (_lock)
{
if (_metadata == null)
{
_metadata = metadata;
}
}
}
return _metadata;
}
}
internal bool IsDisposalRequired
{
get
{
return _creationInfo.IsDisposalRequired;
}
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
public override ComposablePart CreatePart()
{
if (IsDisposalRequired)
{
return new DisposableReflectionComposablePart(this);
}
else
{
return new ReflectionComposablePart(this);
}
}
internal override ComposablePartDefinition GetGenericPartDefinition()
{
GenericSpecializationPartCreationInfo genericCreationInfo = _creationInfo as GenericSpecializationPartCreationInfo;
if (genericCreationInfo != null)
{
return genericCreationInfo.OriginalPart;
}
return null;
}
internal override bool TryGetExports(ImportDefinition definition, out Tuple<ComposablePartDefinition, ExportDefinition> singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> multipleMatches)
{
if (this.IsGeneric())
{
singleMatch = null;
multipleMatches = null;
List<Tuple<ComposablePartDefinition, ExportDefinition>> exports = null;
var genericParameters = (definition.Metadata.Count > 0) ? definition.Metadata.GetValue<IEnumerable<object>>(CompositionConstants.GenericParametersMetadataName) : null;
// if and only if generic parameters have been supplied can we attempt to "close" the generic
if (genericParameters != null)
{
Type[] genericTypeParameters = null;
// we only understand types
if (TryGetGenericTypeParameters(genericParameters, out genericTypeParameters))
{
HashSet<ComposablePartDefinition> candidates = null;
ComposablePartDefinition candidatePart = null;
ComposablePartDefinition previousPart = null;
// go through all orders of generic parameters that part exports allows
foreach (Type[] candidateParameters in GetCandidateParameters(genericTypeParameters))
{
if (TryMakeGenericPartDefinition(candidateParameters, out candidatePart))
{
bool alreadyProcessed = false;
if (candidates == null)
{
if (previousPart != null)
{
if (candidatePart.Equals(previousPart))
{
alreadyProcessed = true;
}
else
{
candidates = new HashSet<ComposablePartDefinition>();
candidates.Add(previousPart);
candidates.Add(candidatePart);
}
}
else
{
previousPart = candidatePart;
}
}
else
{
if (candidates.Contains(candidatePart))
{
alreadyProcessed = true;
}
else
{
candidates.Add(candidatePart);
}
}
if (!alreadyProcessed)
{
Tuple<ComposablePartDefinition, ExportDefinition> candidateSingleMatch;
IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> candidateMultipleMatches;
if (candidatePart.TryGetExports(definition, out candidateSingleMatch, out candidateMultipleMatches))
{
exports = exports.FastAppendToListAllowNulls(candidateSingleMatch, candidateMultipleMatches);
}
}
}
}
}
}
if (exports != null)
{
multipleMatches = exports;
return true;
}
else
{
return false;
}
}
else
{
return TryGetNonGenericExports(definition, out singleMatch, out multipleMatches);
}
}
// Optimised for local as array case
private bool TryGetNonGenericExports(ImportDefinition definition, out Tuple<ComposablePartDefinition, ExportDefinition> singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> multipleMatches)
{
singleMatch = null;
multipleMatches = null;
List<Tuple<ComposablePartDefinition, ExportDefinition>> multipleExports = null;
Tuple<ComposablePartDefinition, ExportDefinition> singleExport = null;
bool matchesFound = false;
foreach (var export in ExportDefinitionsInternal)
{
if (definition.IsConstraintSatisfiedBy(export))
{
matchesFound = true;
if (singleExport == null)
{
singleExport = new Tuple<ComposablePartDefinition, ExportDefinition>(this, export);
}
else
{
if (multipleExports == null)
{
multipleExports = new List<Tuple<ComposablePartDefinition, ExportDefinition>>();
multipleExports.Add(singleExport);
}
multipleExports.Add(new Tuple<ComposablePartDefinition, ExportDefinition>(this, export));
}
}
}
if (!matchesFound)
{
return false;
}
if (multipleExports != null)
{
multipleMatches = multipleExports;
}
else
{
singleMatch = singleExport;
}
return true;
}
private IEnumerable<Type[]> GetCandidateParameters(Type[] genericParameters)
{
// we iterate over all exports and find only generic ones. Assuming the arity matches, we reorder the original parameters
foreach (ExportDefinition export in ExportDefinitionsInternal)
{
var genericParametersOrder = export.Metadata.GetValue<int[]>(CompositionConstants.GenericExportParametersOrderMetadataName);
if ((genericParametersOrder != null) && (genericParametersOrder.Length == genericParameters.Length))
{
yield return GenericServices.Reorder(genericParameters, genericParametersOrder);
}
}
}
private static bool TryGetGenericTypeParameters(IEnumerable<object> genericParameters, out Type[] genericTypeParameters)
{
genericTypeParameters = genericParameters as Type[];
if (genericTypeParameters == null)
{
object[] genericParametersAsArray = genericParameters.AsArray();
genericTypeParameters = new Type[genericParametersAsArray.Length];
for (int i = 0; i < genericParametersAsArray.Length; i++)
{
genericTypeParameters[i] = genericParametersAsArray[i] as Type;
if (genericTypeParameters[i] == null)
{
return false;
}
}
}
return true;
}
internal bool TryMakeGenericPartDefinition(Type[] genericTypeParameters, out ComposablePartDefinition genericPartDefinition)
{
genericPartDefinition = null;
if (!GenericSpecializationPartCreationInfo.CanSpecialize(Metadata, genericTypeParameters))
{
return false;
}
genericPartDefinition = new ReflectionComposablePartDefinition(new GenericSpecializationPartCreationInfo(_creationInfo, this, genericTypeParameters));
return true;
}
string ICompositionElement.DisplayName
{
get { return _creationInfo.DisplayName; }
}
ICompositionElement ICompositionElement.Origin
{
get { return _creationInfo.Origin; }
}
public override string ToString()
{
return _creationInfo.DisplayName;
}
public override bool Equals(object obj)
{
if (_creationInfo.IsIdentityComparison)
{
return object.ReferenceEquals(this, obj);
}
else
{
ReflectionComposablePartDefinition that = obj as ReflectionComposablePartDefinition;
if (that == null)
{
return false;
}
return _creationInfo.Equals(that._creationInfo);
}
}
public override int GetHashCode()
{
if (_creationInfo.IsIdentityComparison)
{
return base.GetHashCode();
}
else
{
return _creationInfo.GetHashCode();
}
}
}
}
| |
// 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.Runtime.InteropServices;
internal static partial class Interop
{
/// <summary>Common Unix errno error codes.</summary>
internal enum Error
{
// These values were defined in src/Native/System.Native/fxerrno.h
//
// They compare against values obtaied via Interop.Sys.GetLastError() not Marshal.GetLastWin32Error()
// which obtains the raw errno that varies between unixes. The strong typing as an enum is meant to
// prevent confusing the two. Casting to or from int is suspect. Use GetLastErrorInfo() if you need to
// correlate these to the underlying platform values or obtain the corresponding error message.
//
SUCCESS = 0,
E2BIG = 0x10001, // Argument list too long.
EACCES = 0x10002, // Permission denied.
EADDRINUSE = 0x10003, // Address in use.
EADDRNOTAVAIL = 0x10004, // Address not available.
EAFNOSUPPORT = 0x10005, // Address family not supported.
EAGAIN = 0x10006, // Resource unavailable, try again (same value as EWOULDBLOCK),
EALREADY = 0x10007, // Connection already in progress.
EBADF = 0x10008, // Bad file descriptor.
EBADMSG = 0x10009, // Bad message.
EBUSY = 0x1000A, // Device or resource busy.
ECANCELED = 0x1000B, // Operation canceled.
ECHILD = 0x1000C, // No child processes.
ECONNABORTED = 0x1000D, // Connection aborted.
ECONNREFUSED = 0x1000E, // Connection refused.
ECONNRESET = 0x1000F, // Connection reset.
EDEADLK = 0x10010, // Resource deadlock would occur.
EDESTADDRREQ = 0x10011, // Destination address required.
EDOM = 0x10012, // Mathematics argument out of domain of function.
EDQUOT = 0x10013, // Reserved.
EEXIST = 0x10014, // File exists.
EFAULT = 0x10015, // Bad address.
EFBIG = 0x10016, // File too large.
EHOSTUNREACH = 0x10017, // Host is unreachable.
EIDRM = 0x10018, // Identifier removed.
EILSEQ = 0x10019, // Illegal byte sequence.
EINPROGRESS = 0x1001A, // Operation in progress.
EINTR = 0x1001B, // Interrupted function.
EINVAL = 0x1001C, // Invalid argument.
EIO = 0x1001D, // I/O error.
EISCONN = 0x1001E, // Socket is connected.
EISDIR = 0x1001F, // Is a directory.
ELOOP = 0x10020, // Too many levels of symbolic links.
EMFILE = 0x10021, // File descriptor value too large.
EMLINK = 0x10022, // Too many links.
EMSGSIZE = 0x10023, // Message too large.
EMULTIHOP = 0x10024, // Reserved.
ENAMETOOLONG = 0x10025, // Filename too long.
ENETDOWN = 0x10026, // Network is down.
ENETRESET = 0x10027, // Connection aborted by network.
ENETUNREACH = 0x10028, // Network unreachable.
ENFILE = 0x10029, // Too many files open in system.
ENOBUFS = 0x1002A, // No buffer space available.
ENODEV = 0x1002C, // No such device.
ENOENT = 0x1002D, // No such file or directory.
ENOEXEC = 0x1002E, // Executable file format error.
ENOLCK = 0x1002F, // No locks available.
ENOLINK = 0x10030, // Reserved.
ENOMEM = 0x10031, // Not enough space.
ENOMSG = 0x10032, // No message of the desired type.
ENOPROTOOPT = 0x10033, // Protocol not available.
ENOSPC = 0x10034, // No space left on device.
ENOSYS = 0x10037, // Function not supported.
ENOTCONN = 0x10038, // The socket is not connected.
ENOTDIR = 0x10039, // Not a directory or a symbolic link to a directory.
ENOTEMPTY = 0x1003A, // Directory not empty.
ENOTRECOVERABLE = 0x1003B, // State not recoverable.
ENOTSOCK = 0x1003C, // Not a socket.
ENOTSUP = 0x1003D, // Not supported (same value as EOPNOTSUP).
ENOTTY = 0x1003E, // Inappropriate I/O control operation.
ENXIO = 0x1003F, // No such device or address.
EOVERFLOW = 0x10040, // Value too large to be stored in data type.
EOWNERDEAD = 0x10041, // Previous owner died.
EPERM = 0x10042, // Operation not permitted.
EPIPE = 0x10043, // Broken pipe.
EPROTO = 0x10044, // Protocol error.
EPROTONOSUPPORT = 0x10045, // Protocol not supported.
EPROTOTYPE = 0x10046, // Protocol wrong type for socket.
ERANGE = 0x10047, // Result too large.
EROFS = 0x10048, // Read-only file system.
ESPIPE = 0x10049, // Invalid seek.
ESRCH = 0x1004A, // No such process.
ESTALE = 0x1004B, // Reserved.
ETIMEDOUT = 0x1004D, // Connection timed out.
ETXTBSY = 0x1004E, // Text file busy.
EXDEV = 0x1004F, // Cross-device link.
// POSIX permits these to have the same value and we make them always equal so
// that CoreFX cannot introduce a dependency on distinguishing between them that
// would not work on all platforms.
EOPNOTSUPP = ENOTSUP, // Operation not supported on socket
EWOULDBLOCK = EAGAIN, // Operation would block
}
// Represents a platform-agnostic Error and underlying platform-specific errno
internal struct ErrorInfo
{
private Error _error;
private int _rawErrno;
internal ErrorInfo(int errno)
{
_error = Interop.Sys.ConvertErrorPlatformToPal(errno);
_rawErrno = errno;
}
internal ErrorInfo(Error error)
{
_error = error;
_rawErrno = -1;
}
internal Error Error
{
get { return _error; }
}
internal int RawErrno
{
get { return _rawErrno == -1 ? (_rawErrno = Interop.Sys.ConvertErrorPalToPlatform(_error)) : _rawErrno; }
}
internal string GetErrorMessage()
{
return Interop.Sys.StrError(RawErrno);
}
public override string ToString()
{
return string.Format(
"RawErrno: {0} Error: {1} GetErrorMessage: {2}", // No localization required; text is member names used for debugging purposes
RawErrno, Error, GetErrorMessage());
}
}
internal partial class Sys
{
internal static Error GetLastError()
{
return ConvertErrorPlatformToPal(Marshal.GetLastWin32Error());
}
internal static ErrorInfo GetLastErrorInfo()
{
return new ErrorInfo(Marshal.GetLastWin32Error());
}
internal static unsafe string StrError(int platformErrno)
{
int maxBufferLength = 1024; // should be long enough for most any UNIX error
byte* buffer = stackalloc byte[maxBufferLength];
byte* message = StrErrorR(platformErrno, buffer, maxBufferLength);
if (message == null)
{
// This means the buffer was not large enough, but still contains
// as much of the error message as possible and is guaranteed to
// be null-terminated. We're not currently resizing/retrying because
// maxBufferLength is large enough in practice, but we could do
// so here in the future if necessary.
message = buffer;
}
return Marshal.PtrToStringAnsi((IntPtr)message);
}
[DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ConvertErrorPlatformToPal")]
internal static extern Error ConvertErrorPlatformToPal(int platformErrno);
[DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ConvertErrorPalToPlatform")]
internal static extern int ConvertErrorPalToPlatform(Error error);
[DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_StrErrorR")]
private static unsafe extern byte* StrErrorR(int platformErrno, byte* buffer, int bufferSize);
}
}
// NOTE: extension method can't be nested inside Interop class.
internal static class InteropErrorExtensions
{
// Intended usage is e.g. Interop.Error.EFAIL.Info() for brevity
// vs. new Interop.ErrorInfo(Interop.Error.EFAIL) for synthesizing
// errors. Errors originated from the system should be obtained
// via GetLastErrorInfo(), not GetLastError().Info() as that will
// convert twice, which is not only inefficient but also lossy if
// we ever encounter a raw errno that no equivalent in the Error
// enum.
public static Interop.ErrorInfo Info(this Interop.Error error)
{
return new Interop.ErrorInfo(error);
}
}
| |
using System;
using System.Xml;
using System.Collections;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using GuruComponents.Netrix.ComInterop;
using GuruComponents.Netrix.WebEditing.Elements;
using GuruComponents.Netrix.Events;
using System.Collections.Generic;
#pragma warning disable 1591
namespace GuruComponents.Netrix.XmlDesigner.Edx
{
/// <summary>
/// Inline field definition.
/// </summary>
public class Field : Region
{
/// <summary>
/// Type of field
/// </summary>
public enum FieldType
{
/// <summary>
/// Complex element
/// </summary>
Rich,
/// <summary>
/// Simple flow element
/// </summary>
Flow
}
/// <summary>
/// Field type.
/// </summary>
public FieldType fieldType; // TODO: Enum
private string sHTMLSnapshot;
public bool bHonorIndexOnFocus;
public string editText;
public int cursorIndex;
/// <summary>
/// Constructor for field class.
/// </summary>
/// <param name="editor"></param>
/// <param name="p"></param>
/// <param name="sTemp"></param>
/// <param name="sPath"></param>
/// <param name="sOptions"></param>
/// <param name="index"></param>
public Field(IHtmlEditor editor, EdxNode p, string sTemp, string sPath, string sOptions, int index)
: base(editor, p, sTemp, sPath, sOptions, index)
{
if (sTemp.IndexOf(":") == 0)
{
throw new ArgumentException("Field template must be in format field:type. Provided name :" + sTemp);
}
// init our vars
this.fieldType = (Field.FieldType) Enum.Parse(typeof(Field.FieldType), sTemp.Substring(6), true);
if( this.fieldType != FieldType.Flow )
Util.Err("field must be type flow" );
this.sHTMLSnapshot = null;
this.bHonorIndexOnFocus = false;
// for doing our own editing
this.editText = null;
this.cursorIndex = -1;
}
# region Service Method
/// <summary>
/// Current text of the field.
/// </summary>
public string EditText
{
get
{
return editText;
}
}
/// <summary>
/// Creates XHTML for field.
/// </summary>
/// <param name="oFrag"></param>
/// <returns></returns>
public override XmlNode XHTML(XmlNode oFrag )
{
//if we already have HTML assoc'd, load it directly
if( this.hobj != null )
{
oFrag.InnerText = this.hobj.InnerText;
}
return oFrag;
}
/*
//
// _fieldAssociate
//
public void Associate(XmlControl h )
{
base.Associate( h );
// sanity check the tag we're being attached to to make sure it support content editable
// couldn't find a good way to do this so I'll just check a few that bit ME
switch( h.TagName.ToUpper() )
{
case "TR":
case "TD":
Util.Err("Error: you cannot attach a field:* template to a " + h.TagName + " tag at this time." );
return;
default:
break;
}
// set up for editing
h.tabIndex = 0;
XmlNode editnode = this.GetXmlNode();
string s = Util.GetXmlNodeValue( editnode );
h.InnerText = s;
this.editText = s;
this.root.WatchChanges( editnode, this );
// attach event handlers
h.OnFocus += new DocumentEventHandler(field_OnFocus);
h.OnBlur += new DocumentEventHandler(field_OnBlur );
h.OnClick += new DocumentEventHandler(field_OnClick );
h.OnKeyDown += new DocumentEventHandler(field_OnKeyDown );
h.OnKeyUp += new DocumentEventHandler(field_OnKeyUp );
h.OnKeyPress += new DocumentEventHandler(field_OnKeyPress );
}
//
// fieldOnFocus
//
// Note: has event context.
//
public void field_OnFocus(object sender, DocumentEventArgs evt)
{
EdxControl h = evt.SrcElement as EdxControl;
Field e = (Field) h.eobj;
e.root.focusField = e;
Interop.IHTMLElement2 body = (Interop.IHTMLElement2) Edx.Instance.Editor.GetBodyElement().GetBaseElement();
// see if we're supposed to go to spec'd position
if( e.bHonorIndexOnFocus )
e.bHonorIndexOnFocus = false;
else
e.cursorIndex = 0;
// make a text range pointing to current element's text
Interop.IHTMLTxtRange tr = ((Interop.IHtmlBodyElement)body).createTextRange();
tr.MoveToElementText( e.hobj.GetBaseElement() );
// see if we need to auto-select some placeholder text (kinda kludgey, I know)
if( e.editText.Length > 0
&& e.editText[0] == '['
&& e.editText[e.editText.Length-1] == ']'
)
{
if( e.root.aFieldSelection != null
&& e.root.aFieldSelection.Count == 1
&& ((Selection)e.root.aFieldSelection[0]).oField.Equals(e)
&& ((Selection)e.root.aFieldSelection[0]).bAll == true
)
{
// already selected
return;
}
e.cursorIndex = 0;
tr.Select();
System.Threading.Thread.Sleep(100);
Edx.Instance.eobj.RestoreFocus();
return;
}
// find cursor coors
tr.Move( "character", e.cursorIndex );
Interop.IHTMLRect rect = h.getClientRects()[0] as Interop.IHTMLRect;
e.root.FieldCursor( rect.right, rect.top, rect.bottom - rect.top );
}
/// <summary>
/// Looks at position of input index and adjusts cursor position accordingly.
/// </summary>
/// <param name="h"></param>
public void SetCursorPosition(XmlControl h )
{
string s = editText.Substring( 0, cursorIndex );
Interop.IHTMLElement2 body = (Interop.IHTMLElement2) Edx.Instance.Editor.GetBodyElement().GetBaseElement();
Interop.IHTMLTxtRange tr = ((Interop.IHtmlBodyElement) body).createTextRange();
tr.MoveToElementText( h );
tr.Collapse( true );
tr.MoveEnd( "character", cursorIndex );
Interop.IHTMLRectCollection r = body.GetClientRects() as Interop.IHTMLRectCollection; // tr
int rcnt = r.length;
Interop.IHTMLRect rect = r.item(rcnt - 1) as Interop.IHTMLRect;
// expand by one char to see if we're at end of a line
if( cursorIndex != editText.Length )
{
tr.Expand( "character" );
r = body.GetClientRects(); //tr
if( r.length != rcnt )
{
// grew a new rectangle, go to start of it
rect = r[r.length - 1];
root.FieldCursor( rect.left, rect.top, rect.bottom - rect.top );
return;
}
}
// stay with end of previous
root.FieldCursor( rect.right, rect.top, rect.bottom - rect.top );
}
//
// _fieldEnterRight
//
// Enters field at far right edge.
//
public void EnterRight()
{
cursorIndex = editText.Length;
bHonorIndexOnFocus = true;
hobj.focus();
}
//
// _fieldEnterLeft
//
// Enters field at far left edge.
//
public void EnterLeft()
{
cursorIndex = 0;
bHonorIndexOnFocus = true;
hobj.focus();
}
//
// _fieldProcessBackspaceKey
//
public void ProcessBackspaceKey()
{
if( cursorIndex > 0 )
{
string s = editText;
cursorIndex--;
s = s.Substring( 0, cursorIndex ) + s.Substring( cursorIndex + 1 );
//alert( "s: " + s );
hobj.InnerText = s;
editText = s;
SetCursorPosition( hobj );
return;
}
// find where we're going
EdxNode el = Util.TraverseLeft( this, true );
CursorSave oCursor;
if( el != null )
{
// save position as an XML node signature and an offset into same
int leftPosition = ((Field)el).editText.Length;
ArrayList leftSig = Util.GetSigFromNode( el.GetXmlNode());
int instance = ((Field)el).GetObservingInstance();
oCursor = new CursorSave( leftSig, leftPosition, instance );
}
// see if we scrub where we've been
if( editText.Length == 0 )
{
XmlManager xmlmgr = root.XmlManager;
xmlmgr.OpenTransaction( null );
XmlNode n = DeleteNode( GetTopContainer() );
xmlmgr.SetNotify( n );
xmlmgr.CloseTransaction();
root.AlertChange( n, null );
}
// go to new home
RestoreCursor( oCursor );
}
/// <summary>
/// Used to help freeze dry a cursor position.
/// </summary>
/// <remarks>
/// When multiple fields are observing the same XML node, this finds the instance # of the current field so that we
/// can return to the proper observing instance later. See restoreCursor() below for more.
/// </remarks>
/// <returns></returns>
public int GetObservingInstance()
{
int i = 0;
Root e = root;
bool bDir = false;
XmlNode editnode = GetXmlNode();
while( e != null )
{
EdxNode e = Util.TraverseRight( e, bDir );
if( e.Equals(this) )
return i;
if( e.GetXmlNode() == editnode )
i++;
bDir = true;
}
Util.Err("getObservingInstance: couldn't find self" );
return 0;
}
/// <summary>
/// Restores cursor position from freeze-dried snapshot.
/// </summary>
/// <param name="oCursor"></param>
public void RestoreCursor(CursorSave oCursor )
{
if( oCursor != CursorSave.Empty )
{
// re-hydrate sig to node
XmlNode nLeft = Util.GetNodeFromSig( oCursor.signature, root.oEditXml );
int inst = oCursor.instance;
// traverse all fields until we find one that owns this node
Root eCur = root;
bool bDir = false;
while( true )
{
eCur = Util.TraverseRight( eCur as EdxNode, bDir );
if( eCur == null )
break;
bDir = true;
if( eCur.GetXmlNode() == nLeft )
{
if( inst-- == 0 )
{
eCur.cursorIndex = oCursor.offset;
eCur.bHonorIndexOnFocus = true;
eCur.hobj.blur(); // force it to process as new focus
eCur.hobj.focus();
return;
}
}
}
}
// fell thru, not an error, just nowhere to go, clear cursor
root.FieldCursor();
}
//
// _fieldProcessDeleteKey
//
public void ProcessDeleteKey()
{
// check for selection
if( root.aFieldSelection != null )
{
root.FieldCursor();
// see if we can find a cursor spot to return to
CursorSave oCursor;
if( ((Selection) root.aFieldSelection[0]).bAll )
{
Field eLeft = Util.TraverseLeft( ((Selection)root.aFieldSelection[0]).oField ) as Field;
if( eLeft != null )
{
ArrayList leftSig = Util.GetSigFromNode( eLeft.GetXmlNode() );
int instance = ((Field)eLeft).GetObservingInstance();
oCursor = new CursorSave( leftSig, eLeft.editText.Length, instance );
}
}
else
{
Field e = ((Selection)root.aFieldSelection[0]).oField;
int instance = e.GetObservingInstance();
ArrayList leftSig = Util.GetSigFromNode( e.GetXmlNode() );
oCursor = new CursorSave( leftSig, e.start, instance );
}
root.DeleteTextSelection();
RestoreCursor( oCursor );
return;
}
if( editText.Length > cursorIndex )
{
string s = editText;
s = s.Substring( 0, cursorIndex ) + s.Substring( cursorIndex + 1 );
hobj.InnerText = s;
editText = s;
}
}
//
// _fieldReplaceSelection
//
public void ReplaceSelection(string sText )
{
root.FieldCursor();
// pop the new char into the first selected field
CursorSave oCursor;
Selection oSel = (Selection) root.aFieldSelection[0];
Field e = oSel.oField;
XmlControl h = e.hobj;
string s = e.editText;
e.editText = s.Substring( 0, oSel.start ) + sText + s.Substring( oSel.start );
h.InnerText = e.editText;
// modify the first selection to start after newly added char
oSel.start += sText.Length;
oSel.end += sText.Length;
oSel.bAll = false;
// grab this position
ArrayList leftSig = Util.GetSigFromNode( oSel.oField.GetXmlNode() );
int instance = oSel.oField.GetObservingInstance();
oCursor = new CursorSave( leftSig, oSel.start, instance );
root.DeleteTextSelection();
RestoreCursor( oCursor );
}
//
// fieldOnKeyDown
//
// Note: has event context.
//
public void field_OnKeyDown(object sender, DocumentEventArgs evt)
{
Keys keyCode = evt.KeyCode;
EdxControl h = evt.SrcElement as EdxControl;
Field e = h.eobj as Field;
if( keyCode == Keys.ShiftKey || keyCode == Keys.ControlKey || keyCode == Keys.Alt )
return;
switch( keyCode )
{
// case 16: // shift
// case 17: // ctrl
// case 18: // alt
// return;
case Keys.Right: // right arrow
if( e.root.aFieldSelection != null )
{
e.root.ClearFieldSelection();
window.document.selection.empty();
}
if( e.cursorIndex < e.editText.Length )
{
if( evt.ControlKey )
{
int w = e.editText.Substring( e.cursorIndex ).IndexOf(" "); //.search( /\s+/ );
if( w != -1 )
{
e.cursorIndex += w;
w = e.editText.Substring( e.cursorIndex ).IndexOf(" "); //.search( /\w/ );
if( w != -1 )
{
e.cursorIndex += w;
e.SetCursorPosition(h as EdxControl);
break;
}
}
e.cursorIndex = e.editText.Length;
}
else
e.cursorIndex++;
e.SetCursorPosition(h);
}
else
{
// look for adjacent field to hop to
Field er = Util.TraverseRight( e, true ) as Field;
if( er != null )
{
er.EnterLeft();
}
}
break;
case Keys.Left: // left arrow (37)
if( e.root.aFieldSelection != null )
{
e.root.ClearFieldSelection();
window.document.selection.empty();
}
if( e.cursorIndex > 0 )
{
if( evt.ControlKey )
{
int w = e.cursorIndex;
while( w > 0 && e.editText[ w-1 ] != ' ' )
w--;
if( w == e.cursorIndex )
{
while( w > 0 && e.editText[ w-1 ] == ' ' )
w--;
while( w > 0 && e.editText[ w-1 ] != ' ' )
w--;
}
e.cursorIndex = w;
}
else
e.cursorIndex--;
e.SetCursorPosition(h);
}
else
{
Field el = Util.TraverseLeft( e, true ) as Field;
if( el != null )
{
el.EnterRight();
}
}
break;
case Keys.Back: // backspace
break;
case Keys.Delete: // delete
e.ProcessDeleteKey();
break;
// case 67: // ctrl-C (copy)
// case 76: // ctrl-V (paste)
// case 78: // ctrl-X (cut)
// break;
default:
return;
}
// consume the event
evt.SetCancelBubble(true);
}
/// <summary>
/// fieldOnKeyPress
/// </summary>
/// <remarks>
/// Oddly even tho we are cancelling bubble, we still end up having this prop up to top level frame.
/// </remarks>
/// <param name="sender"></param>
/// <param name="evt"></param>
public void field_OnKeyPress(object sender, DocumentEventArgs evt)
{
Keys keyCode = evt.KeyCode;
EdxControl h = evt.SrcElement as EdxControl;
Field e = h.eobj as Field;
XmlManager xmlmgr = e.root.XmlManager;
switch( keyCode )
{
case Keys.C: // ctrl-C (copy)
case Keys.X: // ctrl-X (cut)
// look for a selection to move to clipboard
if( e.root.aFieldSelection != null )
{
e.root.CopyTextSelection();
if( keyCode == Keys.X )
{
e.ProcessDeleteKey();
}
}
break;
case Keys.Back: // ctrl-H (backspace)
// treat same as delete for simplicity's sake
if( e.root.aFieldSelection != null )
{
e.ProcessDeleteKey();
break;
}
// normal processing
e.ProcessBackspaceKey();
break;
//case 10:
case Keys.Enter:
// ignore this when there's a selection pending (no reason, just avoiding writing
// complicated code)
if( e.root.aFieldSelection != null )
break;
// do node splitting, auto-insertion handling here
switch( e.GetEnterAction() )
{
case "split":
e.SplitNode();
break;
case "new":
e.NewNode();
break;
default:
break;
}
break;
case Keys.V: // ctrl-V (paste)
// get data to paste
string sText = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();
if( sText == "" || sText == null )
break;
// see if we need to process a pending selection
if( e.root.aFieldSelection != null )
{
e.ReplaceSelection( sText );
return;
}
string s = e.editText;
e.editText = s.Substring( 0, e.cursorIndex ) + sText + s.Substring( e.cursorIndex );
h.InnerText = e.editText;
e.cursorIndex += sText.Length;
e.SetCursorPosition( evt.SrcElement as EdxControl );
break;
case Keys.Y: // ctrl-Y (redo)
if( xmlmgr.CanRedo() )
{
e.root.FieldCursor();
xmlmgr.Redo();
}
break;
case Keys.Z: // ctrl-Z (undo)
e.SaveNode();
if( xmlmgr.CanUndo() )
{
e.root.FieldCursor();
xmlmgr.Undo();
}
break;
default:
// see if we need to process a pending selection
if( e.root.aFieldSelection != null )
{
e.ReplaceSelection( keyCode.ToString() );
return;
}
string s = e.editText;
e.editText = String.Concat(s.Substring( 0, e.cursorIndex ), (char) keyCode, s.Substring( e.cursorIndex ));
h.InnerText = e.editText;
e.cursorIndex++;
e.SetCursorPosition( evt.SrcElement as EdxControl);
break;
}
// consume the event
evt.SetCancelBubble( true );
}
//
// fieldOnKeyUp
//
// Note: has HTML node 'this' context
//
public void field_OnKeyUp(object sender, DocumentEventArgs evt)
{
Keys keyCode = evt.KeyCode;
Field e = ((EdxControl) evt.SrcElement).eobj as Field;
switch( keyCode )
{
case Keys.Shift: //shift
case Keys.Control: // ctrl
case Keys.Alt: // alt
break;
default:
break;
}
// consume the event
evt.SetCancelBubble( true );
}
/// <summary>
/// Checks for change in the field and captures the value to XML if necessary.
/// </summary>
/// <param name="sender"></param>
/// <param name="evt"></param>
public void field_OnBlur(object sender, DocumentEventArgs evt)
{
Keys keyCode = evt.KeyCode;
Field e = ((EdxControl)evt.SrcElement).eobj as Field;
// save off value if changed
e.SaveNode();
// turn off cursor for this field
e.root.FieldCursor();
}
//
// fieldOnClick
//
public void field_OnClick(object sender, DocumentEventArgs evt)
{
Keys keyCode = evt.KeyCode;
Field e = ((EdxControl) evt.SrcElement).eobj as Field;
Interop.IHTMLTxtRange tr = window.document.selection.createRange();
Interop.IHTMLRect rect = tr.getClientRects()[0];
e.root.FieldCursor( rect.left, rect.top, rect.bottom - rect.top );
Interop.IHTMLTxtRange tr2 = window.document.body.createTextRange();
tr2.MoveToElementText( h );
tr2.SetEndPoint( "EndToStart", tr );
e.cursorIndex = tr2.GetText().Length;
}
/// <summary>
/// Saves off to XML if changed.
/// </summary>
public void SaveNode()
{
XmlNode editnode = GetXmlNode();
if( editnode != null )
{
if( Util.GetXmlNodeValue( editnode ) != hobj.InnerText )
{
XmlManager xmlmgr = root.XmlManager;
xmlmgr.OpenTransaction( editnode );
xmlmgr.Process( "updateNode", editnode, hobj.InnerText );
xmlmgr.CloseTransaction();
root.AlertChange( editnode, this );
}
}
}
//
// _fieldOnXmlNodeChange
//
public void OnXmlNodeChange( object sender )
{
// ignore updates from ourself
if( sender == this )
return;
XmlNode editnode = this.GetXmlNode();
if( editnode != null )
{
if( Util.GetXmlNodeValue( editnode ) != this.hobj.InnerText )
{
this.editText = Util.GetXmlNodeValue( editnode );
this.hobj.InnerText = this.editText;
this.cursorIndex = 0;
}
}
}
/// <summary>
/// Walks up tree looking for a defined enter action: split, new, or none Defaults to 'none' if no definition is found.
/// </summary>
/// <returns></returns>
public string GetEnterAction()
{
string action = "none";
Field cur = this;
while( cur != null )
{
if( cur.enterAction != undefined )
{
action = cur.enterAction;
break;
}
cur = cur.parent;
}
return action;
}
/// <summary>
/// Walks up tree looking for appropriate place to create a new template node.
/// </summary>
public void NewNode()
{
Util.Err("newNode not implemented yet" );
}
/// <summary>
/// Splits the current node and walks up tree splitting until it hits a barrier. Used to generate new paragraphs on enter and that sort of thing.
/// </summary>
public void SplitNode()
{
root.FieldCursor( -1 ); // turn off cursor
SaveNode(); // save off in case changed
// perform the split
XmlNode editnode = GetXmlNode();
XmlManager xmlmgr = root.XmlManager;
xmlmgr.OpenTransaction( null ); // don't know alert node yet
xmlmgr.Process( "splitText", editnode, cursorIndex );
XmlNode newNode = editnode.NextSibling;
// find the index of where we split
int i;
XmlNode par = editnode.ParentNode;
for(i = 0; i < par.ChildNodes.Count; i++ )
{
if( par.ChildNodes[i] == newNode )
break;
}
if( i == par.ChildNodes.Count )
{
Util.Err("splitNode couldn't find next sibling" );
return;
}
// walk up the tree splitting until we hit the container that says no
XmlNode topChild;
if( !parent.CanSplit() )
topChild = this;
else
topChild = parent.SplitNode( i, editnode );
// set undo/redo notify and close out
xmlmgr.SetNotify( topChild.parent.getXmlNode() );
xmlmgr.CloseTransaction();
// update parent container
var enew = topChild.parent.nodeHasSplit( topChild );
// establish focus in new node
EdxNode enew = Util.TraverseRight( enew, false );
enew.hobj.focus();
}
//
// _fieldCleanup
//
public new void Cleanup()
{
if( root.focusField == this )
root.focusField = null;
XmlNode editnode = GetXmlNode();
if( editnode != null )
{
root.UnwatchChanges( editnode, this );
}
root.DeassignID( id );
parent.RemoveChild( this );
}
*/
/// <summary>
/// Checks whether we can delete this field.
/// </summary>
/// <returns></returns>
public override bool CanDelete
{
get
{
// TODO: No such method in EdxNode
//if (!this.parent.permitChildDelete())
// return false;
return true;
}
}
/// <summary>
/// Deletes a leaf edit node.
/// </summary>
/// <remarks>Expects an already-eop XML manager transaction.</remarks>
public XmlNode DeleteNode(XmlNode nTopContainer)
{
XmlNode editnode = GetXmlNode();
XmlManager xmlmgr = root.XmlManager;
// delete the nodes and any newly empty parent(s)
XmlNode nTop = Util.DeleteXmlNode(editnode, nTopContainer, xmlmgr);
// coalesce if possible
if (nTop != nTopContainer)
{
Util.CoalesceXmlNodes(nTop, xmlmgr);
}
return nTop;
}
/// <summary>
/// Returns true if we can wrap ourselves (or selected portion thereof) in spec'd tag.
/// </summary>
/// <remarks>
/// Note: these next few routines are tricky cuz we're destroy the synchronization
/// between the edxnode tree and the XML node tree as we work. We need to only
/// assume we still have our original XML node but not much else.
/// </remarks>
/// <param name="sTag"></param>
/// <returns></returns>
public bool CanApplyTag(string sTag)
{
// get master container
EdxNode eTop = GetTopContainer();
if (eTop == null)
return false;
XmlNode oTopNode = eTop.GetXmlNode();
Dictionary<string, string> aMap = EdxDocument.GetEdxDocument.GetView().GetContainerMap(eTop.edxtemplate);
// trace out ancestry up to master container node
List<XmlNode> aAncestry = new List<XmlNode>();
XmlNode n = GetXmlNode();
while (n != oTopNode)
{
// if we hit the desired tag, we of course then can apply it (already applied)
if (n.Name.Equals(sTag))
return true;
aAncestry.Add(n);
n = n.ParentNode;
}
// now walk down looking for place to apply spec'd tag
for (int i = aAncestry.Count - 1; i >= 0; i--)
{
string sCurTag = ((XmlNode)aAncestry[i]).Name;
//Hashtable aChildMap = (Hashtable)aSubMap[sTag];
//if (aChildMap is Hashtable && aChildMap[sCurTag] != null)
// return true;
//aSubMap = aSubMap[sCurTag];
//if (!(aMap is Array))
// break;
}
// never hit match
return false;
}
/// <summary>
/// Inserts spec'd tag somewhere up above us.
/// </summary>
/// <remarks>
/// If bHigh is set, try to set it as high
/// as possible in the hierarchy if there are multiple choices. Else, try to set low.
/// As with comment further above, we are working only in the XML tree here-- the edxnode
/// is in an unknown state from possible previous processing. Caution!
/// </remarks>
/// <param name="sTag"></param>
/// <param name="oSel"></param>
/// <param name="bHigh"></param>
/// <param name="oTopNode"></param>
/// <param name="aMap"></param>
/// <returns>Returns highest affected node.</returns>
public XmlNode ApplyTag(string sTag, Selection oSel, bool bHigh, XmlNode oTopNode, Dictionary<string, string> aMap)
{
// trace out ancestry up to master container node
ArrayList aAncestry = new ArrayList();
XmlNode editnode = GetXmlNode();
XmlNode n = editnode;
while (n != oTopNode)
{
aAncestry.Add(n);
n = n.ParentNode;
}
Dictionary<string, string> aSubMap;
// now walk down looking for place to apply spec'd tag
int iApply = -1;
for (int i = aAncestry.Count - 1; i >= 0; i--)
{
string sCurTag = ((XmlNode)aAncestry[i]).Name;
//Dictionary<string, string> aChildMap = aMap[sTag];
//if (aChildMap != null && aChildMap[sCurTag] != null)
//{
// iApply = i;
// if (bHigh) // looking for highest possible?
// break; // done
//}
//aSubMap = aMap[sCurTag];
//if (aSubMap == null)
// break;
}
if (iApply == -1)
{
// must be some mistake, never hit a match
Util.Err("applyTag: never found insertion spot.");
return null;
}
// should already be an open XML transaction
XmlManager xmlmgr = root.XmlManager;
// see if we need to do a self-split first
if (!oSel.bAll)
{
if (oSel.end != editText.Length)
{
xmlmgr.Process("splitText", editnode, oSel.end);
}
if (oSel.start != 0)
{
xmlmgr.Process("splitText", editnode, oSel.start);
editnode = editnode.NextSibling;
}
}
// split up to selected ancestor as needed
XmlNode nHighest = ((XmlNode)aAncestry[iApply]).ParentNode;
XmlNode nPrev = editnode;
XmlNode nCur = editnode.ParentNode;
while (nCur != nHighest)
{
if (nCur.ChildNodes.Count != 1)
{
int iIndex = Util.ArrayIndex(nCur.ChildNodes, nPrev);
if (iIndex == -1)
{
Util.Err("applyTag: XML node found in parent");
return null;
}
if (iIndex != nCur.ChildNodes.Count - 1)
{
xmlmgr.Process("splitNode", nCur, iIndex + 1);
}
if (iIndex != 0)
{
xmlmgr.Process("splitNode", nCur, iIndex);
nCur = nCur.NextSibling;
}
}
nPrev = nCur;
nCur = nCur.ParentNode;
}
// insert the desired node immediately above the selected ancestor node
XmlDocument oDoc = nHighest.OwnerDocument;
string nsuri = nHighest.NamespaceURI;
XmlNode nNew = oDoc.CreateNode(XmlNodeType.Element, sTag, nsuri); // first para was 1 (Element ??)
int idx = Util.ArrayIndex(nHighest.ChildNodes, nPrev);
if (idx == -1)
{
Util.Err("applyTag: couldn't find XML node index to insert");
return null;
}
xmlmgr.Process("deleteNode", nHighest, idx);
xmlmgr.Process("insertNode", nHighest, nNew, idx);
xmlmgr.Process("insertNode", nNew, nPrev, 0);
// whew
return nHighest;
}
/// <summary>
/// Removes tag from up above. Same basic comments as applyTag above.
/// </summary>
/// <param name="sTag"></param>
/// <param name="oSel"></param>
/// <param name="oTopNode"></param>
/// <param name="aMap"></param>
/// <returns>Returns highest affected node.</returns>
public XmlNode RemoveTag(string sTag, Selection oSel, XmlNode oTopNode, Dictionary<string, string> aMap)
{
// trace out ancestry up to master container node
ArrayList aAncestry = new ArrayList();
XmlNode editnode = GetXmlNode();
XmlNode n = editnode;
while (n != oTopNode)
{
aAncestry[aAncestry.Count] = n;
n = n.ParentNode;
}
// now walk down looking for place to apply spec'd tag
int iApply = -1;
for (int i = aAncestry.Count - 1; i >= 0; i--)
{
if (((XmlNode)aAncestry[i]).Name == sTag)
{
iApply = i;
break;
}
}
if (iApply == -1)
{
// must be some mistake, never hit a match
Util.Err("removeTag: never found tag to remove: '" + sTag + "'");
return null;
}
// should already be an open XML transaction
XmlManager xmlmgr = root.XmlManager;
// see if we need to do a self-split first
if (!oSel.bAll)
{
if (oSel.end != editText.Length)
{
xmlmgr.Process("splitText", editnode, oSel.end);
}
if (oSel.start != 0)
{
xmlmgr.Process("splitText", editnode, oSel.start);
editnode = editnode.NextSibling;
}
}
// split up to selected ancestor as needed
XmlNode nHighest = ((XmlNode)aAncestry[iApply]).ParentNode;
XmlNode nPrev = editnode;
XmlNode nCur = editnode.ParentNode;
while (nCur != nHighest)
{
if (nCur.ChildNodes.Count != 1)
{
int iIndex = Util.ArrayIndex(nCur.ChildNodes, nPrev);
if (iIndex == -1)
{
Util.Err("removeTag: couldn't find XML node in parent");
return null;
}
if (iIndex != nCur.ChildNodes.Count - 1)
{
xmlmgr.Process("splitNode", nCur, iIndex + 1);
}
if (iIndex != 0)
{
xmlmgr.Process("splitNode", nCur, iIndex);
nCur = nCur.NextSibling;
}
}
nPrev = nCur;
nCur = nCur.ParentNode;
}
// remove the selected ancestor node
XmlNode nRemove = nPrev;
XmlNode nSave = nRemove.ChildNodes[0];
int idx = Util.ArrayIndex(nHighest.ChildNodes, nRemove);
if (idx == -1)
{
Util.Err("removeTag: node to remove not found in parent");
return null;
}
xmlmgr.Process("deleteNode", nHighest, idx);
xmlmgr.Process("insertNode", nHighest, nSave, idx);
// whew
return nHighest;
}
/// <summary>
/// Returns true if the spec'd tag is found anywhere up above the current field.
/// </summary>
/// <param name="sTag"></param>
/// <param name="oTopNode"></param>
public bool IsApplied(string sTag, XmlNode oTopNode)
{
// trace out ancestry up to master container node
XmlNode n = GetXmlNode();
while (!n.Equals(oTopNode))
{
// if we hit the desired tag, we of course then can apply it (already applied)
if (n.Name == sTag)
return true;
n = n.ParentNode;
}
// fell thru, not applied
return false;
}
/// <summary>
/// Looks to see if all or part of current field lies inside the supplied text range.
/// </summary>
/// <remarks>
/// If an intersection is found, returns a fieldSelection object defining the selection, else null.
/// </remarks>
public Selection GetSelection(Interop.IHTMLTxtRange tr)
{
int start, end;
Interop.IHTMLTxtRange dup;
Interop.IHTMLTxtRange ourtr = ((Interop.IHtmlBodyElement)editor.GetBodyElement().GetBaseElement()).createTextRange();
// TODO: Connect to native element
//ourtr.MoveToElementText(hobj);
if (tr.InRange(ourtr))
{
// we are equal to or completely contained in the main range
return new Selection(this, true, 0, editText.Length);
}
// see if main selection is completely inside us
if (ourtr.InRange(tr))
{
dup = ourtr.Duplicate();
dup.SetEndPoint("EndToStart", tr);
start = dup.GetText().Length;
dup = ourtr.Duplicate();
dup.SetEndPoint("StartToEnd", tr);
end = editText.Length - dup.GetText().Length;
if (start == end) // don't return empty
return Selection.Empty;
return new Selection(this, false, start, end);
}
// check for left endpoint within main range
dup = ourtr.Duplicate();
dup.Collapse(true);
if (tr.InRange(dup))
{
// left side is "in"
dup.SetEndPoint("EndToEnd", tr);
end = dup.GetText().Length;
if (end == 0) // don't return empty
return Selection.Empty;
return new Selection(this, false, 0, end);
}
// check for right endpoint within main range
dup = ourtr.Duplicate();
dup.Collapse(false);
if (tr.InRange(dup))
{
// right side is "in"
dup.SetEndPoint("StartToStart", tr);
start = editText.Length - dup.GetText().Length;
if (start == editText.Length) // don't return empty
return Selection.Empty;
return new Selection(this, false, start, editText.Length);
}
// no intersection
return Selection.Empty;
}
/// <summary>
/// Looks up node hierarchy for a non-splitting container.
/// </summary>
/// <returns></returns>
public EdxNode GetTopContainer()
{
// look upwards for non-splitting container
EdxNode par = this.parent;
while (par != null && par.CanSplit)
par = par.parent;
// if we didn't hit a container, we can't apply, done
if (par == null || !(par is Container))
return null;
return par;
}
# endregion
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Management.Automation.Language;
using Microsoft.Management.Infrastructure;
namespace System.Management.Automation.Runspaces
{
using System;
using System.Collections.ObjectModel;
using Debug = System.Management.Automation.Diagnostics;
/// <summary>
/// Define a parameter for <see cref="Command"/>
/// </summary>
public sealed class CommandParameter
{
#region Public constructors
/// <summary>
/// Create a named parameter with a null value.
/// </summary>
/// <param name="name">Parameter name.</param>
/// <exception cref="ArgumentNullException">
/// name is null.
/// </exception>
/// <exception cref="ArgumentException">
/// Name length is zero after trimming whitespace.
/// </exception>
public CommandParameter(string name)
: this(name, null)
{
if (name == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(name));
}
}
/// <summary>
/// Create a named parameter.
/// </summary>
/// <param name="name">Parameter name.</param>
/// <param name="value">Parameter value.</param>
/// <exception cref="ArgumentException">
/// Name is non null and name length is zero after trimming whitespace.
/// </exception>
public CommandParameter(string name, object value)
{
if (name != null)
{
if (string.IsNullOrWhiteSpace(name))
{
throw PSTraceSource.NewArgumentException(nameof(name));
}
Name = name;
}
else
{
Name = null;
}
Value = value;
}
#endregion Public constructors
#region Public properties
/// <summary>
/// Gets the parameter name.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the value of the parameter.
/// </summary>
public object Value { get; }
#endregion Public properties
/// <summary>
/// Gets whether the parameter was from splatting a Hashtable.
/// </summary>
private bool FromHashtableSplatting { get; set; }
#region Conversion from and to CommandParameterInternal
internal static CommandParameter FromCommandParameterInternal(CommandParameterInternal internalParameter)
{
if (internalParameter == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(internalParameter));
}
// we want the name to preserve 1) dashes, 2) colons, 3) followed-by-space information
string name = null;
if (internalParameter.ParameterNameSpecified)
{
name = internalParameter.ParameterText;
if (internalParameter.SpaceAfterParameter)
{
name += " ";
}
Diagnostics.Assert(name != null, "'name' variable should be initialized at this point");
Diagnostics.Assert(name[0].IsDash(), "first character in parameter name must be a dash");
Diagnostics.Assert(name.Trim().Length != 1, "Parameter name has to have some non-whitespace characters in it");
}
CommandParameter result = internalParameter.ParameterAndArgumentSpecified
? new CommandParameter(name, internalParameter.ArgumentValue)
: name != null
? new CommandParameter(name)
: new CommandParameter(name: null, internalParameter.ArgumentValue);
result.FromHashtableSplatting = internalParameter.FromHashtableSplatting;
return result;
}
internal static CommandParameterInternal ToCommandParameterInternal(CommandParameter publicParameter, bool forNativeCommand)
{
if (publicParameter == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(publicParameter));
}
string name = publicParameter.Name;
object value = publicParameter.Value;
Debug.Assert((name == null) || (name.Trim().Length != 0), "Parameter name has to null or have some non-whitespace characters in it");
if (name == null)
{
return CommandParameterInternal.CreateArgument(value);
}
string parameterText;
if (!name[0].IsDash())
{
parameterText = forNativeCommand ? name : "-" + name;
return CommandParameterInternal.CreateParameterWithArgument(
parameterAst: null,
parameterName: name,
parameterText: parameterText,
argumentAst: null,
value: value,
spaceAfterParameter: true);
}
// if first character of name is '-', then we try to fake the original token
// reconstructing dashes, colons and followed-by-space information
// find the last non-whitespace character
bool spaceAfterParameter = false;
int endPosition = name.Length;
while ((endPosition > 0) && char.IsWhiteSpace(name[endPosition - 1]))
{
spaceAfterParameter = true;
endPosition--;
}
Debug.Assert(endPosition > 0, "parameter name should have some non-whitespace characters in it");
// now make sure that parameterText doesn't have whitespace at the end,
parameterText = name.Substring(0, endPosition);
// parameterName should contain only the actual name of the parameter (no whitespace, colons, dashes)
bool hasColon = (name[endPosition - 1] == ':');
var parameterName = parameterText.Substring(1, parameterText.Length - (hasColon ? 2 : 1));
// At this point we have rebuilt the token. There are 3 strings that might be different:
// name = nameToken.Script = "-foo: " <- needed to fake FollowedBySpace=true (i.e. for "testecho.exe -a:b -c: d")
// tokenString = nameToken.TokenText = "-foo:" <- needed to preserve full token text (i.e. for write-output)
// nameToken.Data = "foo" <- needed to preserve name of parameter so parameter binding works
// Now we just need to use the token to build appropriate CommandParameterInternal object
// is this a name+value pair, or is it just a name (of a parameter)?
if (!hasColon && value == null)
{
// just a name
return CommandParameterInternal.CreateParameter(parameterName, parameterText);
}
// name+value pair
return CommandParameterInternal.CreateParameterWithArgument(
parameterAst: null,
parameterName,
parameterText,
argumentAst: null,
value,
spaceAfterParameter,
publicParameter.FromHashtableSplatting);
}
#endregion
#region Serialization / deserialization for remoting
/// <summary>
/// Creates a CommandParameter object from a PSObject property bag.
/// PSObject has to be in the format returned by ToPSObjectForRemoting method.
/// </summary>
/// <param name="parameterAsPSObject">PSObject to rehydrate.</param>
/// <returns>
/// CommandParameter rehydrated from a PSObject property bag
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown if the PSObject is null.
/// </exception>
/// <exception cref="System.Management.Automation.Remoting.PSRemotingDataStructureException">
/// Thrown when the PSObject is not in the expected format
/// </exception>
internal static CommandParameter FromPSObjectForRemoting(PSObject parameterAsPSObject)
{
if (parameterAsPSObject == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(parameterAsPSObject));
}
string name = RemotingDecoder.GetPropertyValue<string>(parameterAsPSObject, RemoteDataNameStrings.ParameterName);
object value = RemotingDecoder.GetPropertyValue<object>(parameterAsPSObject, RemoteDataNameStrings.ParameterValue);
return new CommandParameter(name, value);
}
/// <summary>
/// Returns this object as a PSObject property bag
/// that can be used in a remoting protocol data object.
/// </summary>
/// <returns>This object as a PSObject property bag.</returns>
internal PSObject ToPSObjectForRemoting()
{
PSObject parameterAsPSObject = RemotingEncoder.CreateEmptyPSObject();
parameterAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ParameterName, this.Name));
parameterAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ParameterValue, this.Value));
return parameterAsPSObject;
}
#endregion
}
/// <summary>
/// Defines a collection of parameters.
/// </summary>
public sealed class CommandParameterCollection : Collection<CommandParameter>
{
// TODO: this class needs a mechanism to lock further changes
/// <summary>
/// Create a new empty instance of this collection type.
/// </summary>
public CommandParameterCollection()
{
}
/// <summary>
/// Add a parameter with given name and default null value.
/// </summary>
/// <param name="name">Name of the parameter.</param>
/// <exception cref="ArgumentNullException">
/// name is null.
/// </exception>
/// <exception cref="ArgumentException">
/// Name length is zero after trimming whitespace.
/// </exception>
public void Add(string name)
{
Add(new CommandParameter(name));
}
/// <summary>
/// Add a parameter with given name and value.
/// </summary>
/// <param name="name">Name of the parameter.</param>
/// <param name="value">Value of the parameter.</param>
/// <exception cref="ArgumentNullException">
/// Both name and value are null. One of these must be non-null.
/// </exception>
/// <exception cref="ArgumentException">
/// Name is non null and name length is zero after trimming whitespace.
/// </exception>
public void Add(string name, object value)
{
Add(new CommandParameter(name, value));
}
}
}
| |
// Copyright (c) 2004-2010 Azavea, Inc.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Text;
using Azavea.Open.Common;
using Azavea.Open.DAO.SQL;
using Azavea.Open.DAO.Util;
using SqlTransaction=Azavea.Open.DAO.SQL.SqlTransaction;
namespace Azavea.Open.DAO.SQLServer
{
/// <summary>
/// This class represents the info necessary to connect to a SQL Server database.
/// TODO: Add support for SQL Server Spatial.
/// </summary>
public class SQLServerDescriptor : AbstractSqlConnectionDescriptor, ITransactionalConnectionDescriptor
{
/// <exclude/>
protected readonly string _connectionStr;
/// <exclude/>
protected readonly string _cleanConnStr;
/// <summary>
/// The server name. May not be null.
/// </summary>
public readonly string Server;
/// <summary>
/// The database name. May not be null.
/// </summary>
public readonly string Database;
/// <summary>
/// The user name, if necessary to log into the database. May be null.
/// </summary>
public readonly string User;
/// <summary>
/// The password for the User. May be null.
/// </summary>
public readonly string Password;
/// <summary>
/// This constructor reads all the appropriate values from a config file.
/// </summary>
/// <param name="config">Config to get params from.</param>
/// <param name="component">Section of the config XML to look in for db params.</param>
/// <param name="decryptionDelegate">Delegate to call to decrypt password fields.
/// May be null if passwords are in plain text.</param>
public SQLServerDescriptor(Config config, string component,
ConnectionInfoDecryptionDelegate decryptionDelegate)
: this(config.GetParameter(component, "Server", null),
config.GetParameter(component, "Database", null),
config.GetParameter(component, "User", null),
GetDecryptedConfigParameter(config, component, "Password", decryptionDelegate)) {}
/// <summary>
/// Constructor that lets you pass everything as parameters rather than requiring a config.
/// </summary>
/// <param name="server">Server name. May not be null.</param>
/// <param name="database">Database name on that server. May not be null.</param>
/// <param name="user">Database user name, may be null.</param>
/// <param name="password">Password for the user. May be null.</param>
public SQLServerDescriptor(string server, string database, string user, string password)
{
_connectionStr = MakeConnectionString(server, database, user, password);
_cleanConnStr = MakeConnectionString(server, database, user, null);
Server = server;
Database = database;
User = user;
Password = password;
}
public override IDaLayer CreateDataAccessLayer()
{
return new SQLServerDaLayer(this);
}
/// <summary>
/// Begins the transaction. Returns a NEW ConnectionDescriptor that you should
/// use for operations you wish to be part of the transaction.
///
/// NOTE: You MUST call Commit or Rollback on the returned ITransaction when you are done.
/// </summary>
/// <returns>The ConnectionDescriptor object to pass to calls that you wish to have
/// happen as part of this transaction.</returns>
public ITransaction BeginTransaction()
{
return new SqlTransaction(this);
}
/// <summary>
/// Assembles a connection string that can be used to get a database connection.
/// All the parameters are optional for the purposes of this method, although obviously
/// it would be possible to create a useless connection string if you leave out important
/// parameters.
/// </summary>
/// <param name="server">Server name that is hosting the database</param>
/// <param name="database">Database name on the server.</param>
/// <param name="user">User name to use when accessing the db.</param>
/// <param name="password">Password for above user.</param>
/// <returns>A connection string that can be used to create SqlConnections.</returns>
public static string MakeConnectionString(string server,
string database, string user, string password)
{
string connStr = "";
// Assemble the string. Only include parameters that have values.
if (StringHelper.IsNonBlank(server))
{
connStr += "server=" + server + ";";
}
if (StringHelper.IsNonBlank(user))
{
connStr += "uid=" + user + ";";
}
if (StringHelper.IsNonBlank(password))
{
connStr += "pwd=" + password + ";";
}
if (StringHelper.IsNonBlank(database))
{
connStr += "database=" + database + ";";
}
return connStr;
}
/// <exclude/>
public override string ToCleanString()
{
return _cleanConnStr;
}
/// <exclude/>
public override string ToCompleteString()
{
return _connectionStr;
}
/// <exclude/>
public override DbConnection CreateNewConnection()
{
return new SqlConnection(_connectionStr);
}
/// <exclude/>
public override void SetParametersOnCommand(IDbCommand cmd, IEnumerable parameters)
{
// TODO TODO TODO TODO
// This is almost a complete cut-n-paste from the SQLiteDescriptor.SetParametersOnCommand.
// The only difference is the class of the IDbParameter object instantiated.
// We need to refactor this into some sort of helper method, or even better,
// make it so we can construct the SQL with @params in the first place rather
// than always using ?'s even if the DB does not understand them.
IEnumerator enumer = parameters.GetEnumerator();
if (enumer.MoveNext())
{
// There's at least one, so split apart the sql.
string[] sqlPieces = cmd.CommandText.Split('?');
StringBuilder sb = DbCaches.StringBuilders.Get();
for (int x = 0; x < (sqlPieces.Length - 1); x++)
{
// First append the sql fragment.
sb.Append(sqlPieces[x]);
// The name of the param has to be prepended with a @ in the sql, but not
// on the parameter object.
sb.Append("@");
string paramName = DbCaches.ParamNames.Get(x);
sb.Append(paramName);
// Get the value to insert.
object param = enumer.Current ?? DBNull.Value;
// Construct and add the parameter object.
cmd.Parameters.Add(new SqlParameter(paramName, param));
// Move the enumerator to the next item, if there should be another one.
if ((x + 1) < (sqlPieces.Length - 1))
{
if (!enumer.MoveNext())
{
throw new ArgumentException("Command sql has " +
(sqlPieces.Length - 1) + " params, but you only passed " +
(x + 1) +
" parameters: " +
SqlUtilities.SqlParamsToString(cmd.CommandText, parameters) +
" You may get this if your sql string has a ? in it. In that case you" +
" can try parameterizing whatever string constant has the ? and passing" +
" the constant from your code. Not super elegant, but a whole lot easier than" +
" making this code understand quoted or escaped characters in the sql string.");
}
}
}
// Check that we don't have leftover parameters.
if (enumer.MoveNext())
{
throw new ArgumentException("Command sql has " +
(sqlPieces.Length - 1) + " params, but you passed more than that: " +
SqlUtilities.SqlParamsToString(cmd.CommandText, parameters));
}
// Append the last sql fragment.
sb.Append(sqlPieces[sqlPieces.Length - 1]);
cmd.CommandText = sb.ToString();
DbCaches.StringBuilders.Return(sb);
}
}
/// <exclude/>
public override DbDataAdapter CreateNewAdapter(IDbCommand cmd)
{
return new SqlDataAdapter((SqlCommand)cmd);
}
/// <exclude/>
public override bool UsePooling()
{
return true;
}
/// <exclude/>
public override SqlClauseWithValue MakeModulusClause(string fieldName)
{
StringBuilder sb = DbCaches.StringBuilders.Get();
SqlClauseWithValue retVal = DbCaches.Clauses.Get();
sb.Append("(");
sb.Append(fieldName);
sb.Append(" % ");
retVal.PartBeforeValue = sb.ToString();
retVal.PartAfterValue = ")";
DbCaches.StringBuilders.Return(sb);
return retVal;
}
/// <exclude/>
public override SqlClauseWithValue MakeBitwiseAndClause(string columnName)
{
StringBuilder sb = DbCaches.StringBuilders.Get();
SqlClauseWithValue retVal = DbCaches.Clauses.Get();
sb.Append(" (");
sb.Append(columnName);
sb.Append(" & ");
retVal.PartBeforeValue = sb.ToString();
retVal.PartAfterValue = ")";
DbCaches.StringBuilders.Return(sb);
return retVal;
}
/// <exclude/>
public override string TableAliasPrefix()
{
return "";
}
/// <exclude/>
public override string TableAliasSuffix()
{
return "";
}
/// <exclude/>
public override bool NeedToAliasColumns()
{
return true;
}
/// <exclude/>
public override bool NeedAsForColumnAliases()
{
return false;
}
/// <exclude/>
public override string ColumnAliasPrefix()
{
return "[";
}
/// <exclude/>
public override string ColumnAliasSuffix()
{
return "]";
}
}
}
| |
using System.Collections.Generic;
namespace NDCRaw
{
public class DCRawOptions
{
public string DCRawPath { get; set; }
public bool UseCameraWhiteBalance { get; set; }
public bool AverageWholeImageForWhiteBalance { get; set; }
public GrayBox AverageGrayBoxForWhiteBalance { get; set; }
public CustomWhiteBalance WhiteBalance { get; set; }
public bool? UseEmbeddedColorMatrix { get; set; }
public string DeadPixelFile { get; set; }
public string DarkFrameFile { get; set; }
public float? DarknessLevel { get; set; }
public float? SaturationLevel { get; set; }
public int? WaveletDenoisingThreshold { get; set; }
public HighlightMode? HighlightMode { get; set; }
public FlipImage? Flip { get; set; }
public Colorspace? Colorspace { get; set; }
public string OutputIccProfileFile { get; set; }
public string CameraIccProfileFile { get; set; }
public bool DocumentMode { get; set; }
public bool DocumentModeNoScaling { get; set; }
public bool DontAutomaticallyBrighten { get; set; }
public float? AdjustBrightness { get; set; }
public CustomGammaCurve GammaCurve { get; set; }
public InterpolationQuality? Quality { get; set; }
public bool HalfSizeColorImage { get; set; }
public bool InterpolateRggbAsFourColors { get; set; }
public int? AppliedMedianFilterNumberPasses { get; set; }
public bool Write16Bits { get; set; }
public Format Format { get; set; }
public DCRawOptions()
{
DCRawPath = "dcraw";
Format = Format.Ppm;
}
public string[] GetArguments(string rawFile)
{
var args = new List<string>();
if(UseCameraWhiteBalance)
{
args.Add("-w");
}
if(AverageWholeImageForWhiteBalance)
{
args.Add("-a");
}
if(AverageGrayBoxForWhiteBalance != null)
{
args.Add("-A");
args.Add($"{AverageGrayBoxForWhiteBalance.X}");
args.Add($"{AverageGrayBoxForWhiteBalance.Y}");
args.Add($"{AverageGrayBoxForWhiteBalance.Width}");
args.Add($"{AverageGrayBoxForWhiteBalance.Height}");
}
if(WhiteBalance != null)
{
args.Add("-r");
args.Add($"{WhiteBalance.R}");
args.Add($"{WhiteBalance.G1}");
args.Add($"{WhiteBalance.B}");
args.Add($"{WhiteBalance.G2}");
}
if(UseEmbeddedColorMatrix != null)
{
var arg = UseEmbeddedColorMatrix == true ? "+M" : "-M";
args.Add(arg);
}
if(!string.IsNullOrEmpty(DeadPixelFile))
{
args.Add("-P");
args.Add($"{DeadPixelFile}");
}
if(!string.IsNullOrEmpty(DarkFrameFile))
{
args.Add("-K");
args.Add($"{DarkFrameFile}");
}
if(DarknessLevel != null)
{
args.Add("-k");
args.Add($"{DarknessLevel}");
}
if(SaturationLevel != null)
{
args.Add("-S");
args.Add($"{SaturationLevel}");
}
if(WaveletDenoisingThreshold != null)
{
args.Add("-n");
args.Add($"{WaveletDenoisingThreshold}");
}
if(HighlightMode != null)
{
args.Add("-H");
args.Add($"{(int)HighlightMode}");
}
if(Flip != null)
{
args.Add("-t");
args.Add($"{(int)Flip}");
}
if(Colorspace != null)
{
args.Add("-o");
args.Add($"{(int)Colorspace}");
}
if(!string.IsNullOrEmpty(OutputIccProfileFile))
{
args.Add("-o");
args.Add($"{OutputIccProfileFile}");
}
if(!string.IsNullOrEmpty(CameraIccProfileFile))
{
args.Add("-p");
args.Add($"{CameraIccProfileFile}");
}
if(DocumentMode)
{
args.Add("-d");
}
if(DocumentModeNoScaling)
{
args.Add("-D");
}
if(DontAutomaticallyBrighten)
{
args.Add("-W");
}
if(AdjustBrightness != null)
{
args.Add("-b");
args.Add($"{AdjustBrightness}");
}
if(GammaCurve != null)
{
args.Add("-g");
args.Add($"{GammaCurve.Power}");
args.Add($"{GammaCurve.ToeSlope}");
}
if(Quality != null)
{
args.Add("-q");
args.Add($"{(int)Quality}");
}
if(HalfSizeColorImage)
{
args.Add("-h");
}
if(InterpolateRggbAsFourColors)
{
args.Add("-f");
}
if(AppliedMedianFilterNumberPasses != null)
{
args.Add("-m");
args.Add($"{AppliedMedianFilterNumberPasses}");
}
if(Write16Bits)
{
args.Add("-6");
}
if(Format == Format.Tiff)
{
args.Add("-T");
}
args.Add(rawFile);
return args.ToArray();
}
}
}
| |
using System;
using System.Runtime.CompilerServices;
namespace AddinX.Logging
{
/// <summary>
/// Manages logging.
/// </summary>
/// <remarks>
/// This is a facade for the different logging subsystems.
/// It offers a simplified interface that follows IOC patterns
/// and a simplified priority/level/severity abstraction.
/// </remarks>
public interface ILogger
{
/// <summary>
/// Determines if messages of priority "debug" will be logged.
/// </summary>
/// <value>True if "debug" messages will be logged.</value>
bool IsDebugEnabled { get; }
/// <summary>
/// Determines if messages of priority "error" will be logged.
/// </summary>
/// <value>True if "error" messages will be logged.</value>
bool IsErrorEnabled { get; }
/// <summary>
/// Determines if messages of priority "fatal" will be logged.
/// </summary>
/// <value>True if "fatal" messages will be logged.</value>
bool IsFatalEnabled { get; }
/// <summary>
/// Determines if messages of priority "info" will be logged.
/// </summary>
/// <value>True if "info" messages will be logged.</value>
bool IsInfoEnabled { get; }
/// <summary>
/// Determines if messages of priority "warn" will be logged.
/// </summary>
/// <value>True if "warn" messages will be logged.</value>
bool IsWarnEnabled { get; }
/// <summary>
/// Logs a debug message. The message will be constructed only if the <see cref="IsDebugEnabled" /> is true.
/// </summary>
/// <param name="message">The message to log</param>
void Debug(string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0);
/// <summary>
/// Logs a debug message with lazily constructed message. The message will be constructed only if the
/// <see cref="IsDebugEnabled" /> is true.
/// </summary>
/// <param name="messageFactory"></param>
void Debug(Func<string> messageFactory,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0);
/// <summary>
/// Logs a debug message. The message will be constructed only if the <see cref="IsDebugEnabled" /> is true.
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="message">The message to log</param>
void Debug(string message, Exception exception,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0);
/// <summary>
/// Logs a debug message. The message will be constructed only if the <see cref="IsDebugEnabled" /> is true.
/// </summary>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
void DebugFormat(string format, params object[] args);
/// <summary>
/// Logs an error message. The message will be constructed only if the <see cref="IsErrorEnabled" /> is true.
/// </summary>
/// <param name="message">The message to log</param>
void Error(string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0);
/// <summary>
/// Logs an error message with lazily constructed message. The message will be constructed only if the
/// <see cref="IsErrorEnabled" /> is true.
/// </summary>
/// <param name="messageFactory"></param>
void Error(Func<string> messageFactory,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0);
/// <summary>
/// Logs an error message. The message will be constructed only if the <see cref="IsErrorEnabled" /> is true.
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="message">The message to log</param>
void Error(string message, Exception exception,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0);
/// <summary>
/// Logs an error message. The message will be constructed only if the <see cref="IsErrorEnabled" /> is true.
/// </summary>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
void ErrorFormat(string format, params object[] args);
/// <summary>
/// Logs a fatal message. The message will be constructed only if the <see cref="IsFatalEnabled" /> is true.
/// </summary>
/// <param name="message">The message to log</param>
void Fatal(string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0);
/// <summary>
/// Logs a fatal message with lazily constructed message. The message will be constructed only if the
/// <see cref="IsFatalEnabled" /> is true.
/// </summary>
/// <param name="messageFactory"></param>
void Fatal(Func<string> messageFactory,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0);
/// <summary>
/// Logs a fatal message. The message will be constructed only if the <see cref="IsFatalEnabled" /> is true.
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="message">The message to log</param>
void Fatal(string message, Exception exception,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0);
/// <summary>
/// Logs a fatal message. The message will be constructed only if the <see cref="IsFatalEnabled" /> is true.
/// </summary>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
void FatalFormat(string format, params object[] args);
/// <summary>
/// Logs an info message. The message will be constructed only if the <see cref="IsInfoEnabled" /> is true.
/// </summary>
/// <param name="message">The message to log</param>
void Info(string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0);
/// <summary>
/// Logs a info message with lazily constructed message. The message will be constructed only if the
/// <see cref="IsInfoEnabled" /> is true.
/// </summary>
/// <param name="messageFactory"></param>
void Info(Func<string> messageFactory,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0);
/// <summary>
/// Logs an info message. The message will be constructed only if the <see cref="IsInfoEnabled" /> is true.
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="message">The message to log</param>
void Info(string message, Exception exception,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0);
/// <summary>
/// Logs an info message. The message will be constructed only if the <see cref="IsInfoEnabled" /> is true.
/// </summary>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
void InfoFormat(string format, params object[] args);
/// <summary>
/// Logs a warn message. The message will be constructed only if the <see cref="IsWarnEnabled" /> is true.
/// </summary>
/// <param name="message">The message to log</param>
void Warn(string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0);
/// <summary>
/// Logs a warn message with lazily constructed message. The message will be constructed only if the
/// <see cref="IsWarnEnabled" /> is true.
/// </summary>
/// <param name="messageFactory"></param>
void Warn(Func<string> messageFactory,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0);
/// <summary>
/// Logs a warn message. The message will be constructed only if the <see cref="IsWarnEnabled" /> is true.
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="message">The message to log</param>
void Warn(string message, Exception exception,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0);
/// <summary>
/// Logs a warn message. The message will be constructed only if the <see cref="IsWarnEnabled" /> is true.
/// </summary>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
void WarnFormat(string format, params object[] args);
}
}
| |
// ***********************************************************************
// Copyright (c) 2008-2015 Charlie Poole, Rob Prouse
//
// 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.Reflection;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Builders;
namespace NUnit.Framework
{
/// <summary>
/// Marks a method as a parameterized test suite and provides arguments for each test case.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited=false)]
public class TestCaseAttribute : NUnitAttribute, ITestBuilder, ITestCaseData, IImplyFixture
{
#region Constructors
/// <summary>
/// Construct a TestCaseAttribute with a list of arguments.
/// This constructor is not CLS-Compliant
/// </summary>
/// <param name="arguments"></param>
public TestCaseAttribute(params object[] arguments)
{
RunState = RunState.Runnable;
if (arguments == null)
Arguments = new object[] { null };
else
Arguments = arguments;
Properties = new PropertyBag();
}
/// <summary>
/// Construct a TestCaseAttribute with a single argument
/// </summary>
/// <param name="arg"></param>
public TestCaseAttribute(object arg)
{
RunState = RunState.Runnable;
Arguments = new object[] { arg };
Properties = new PropertyBag();
}
/// <summary>
/// Construct a TestCaseAttribute with a two arguments
/// </summary>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
public TestCaseAttribute(object arg1, object arg2)
{
RunState = RunState.Runnable;
Arguments = new object[] { arg1, arg2 };
Properties = new PropertyBag();
}
/// <summary>
/// Construct a TestCaseAttribute with a three arguments
/// </summary>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
/// <param name="arg3"></param>
public TestCaseAttribute(object arg1, object arg2, object arg3)
{
RunState = RunState.Runnable;
Arguments = new object[] { arg1, arg2, arg3 };
Properties = new PropertyBag();
}
#endregion
#region ITestData Members
/// <summary>
/// Gets or sets the name of the test.
/// </summary>
/// <value>The name of the test.</value>
public string TestName { get; set; }
/// <summary>
/// Gets or sets the RunState of this test case.
/// </summary>
public RunState RunState { get; private set; }
/// <summary>
/// Gets the list of arguments to a test case
/// </summary>
public object[] Arguments { get; }
/// <summary>
/// Gets the properties of the test case
/// </summary>
public IPropertyBag Properties { get; }
#endregion
#region ITestCaseData Members
/// <summary>
/// Gets or sets the expected result.
/// </summary>
/// <value>The result.</value>
public object ExpectedResult
{
get { return _expectedResult; }
set
{
_expectedResult = value;
HasExpectedResult = true;
}
}
private object _expectedResult;
/// <summary>
/// Returns true if the expected result has been set
/// </summary>
public bool HasExpectedResult { get; private set; }
#endregion
#region Other Properties
/// <summary>
/// Gets or sets the description.
/// </summary>
/// <value>The description.</value>
public string Description
{
get { return Properties.Get(PropertyNames.Description) as string; }
set { Properties.Set(PropertyNames.Description, value); }
}
/// <summary>
/// The author of this test
/// </summary>
public string Author
{
get { return Properties.Get(PropertyNames.Author) as string; }
set { Properties.Set(PropertyNames.Author, value); }
}
/// <summary>
/// The type that this test is testing
/// </summary>
public Type TestOf
{
get { return _testOf; }
set
{
_testOf = value;
Properties.Set(PropertyNames.TestOf, value.FullName);
}
}
private Type _testOf;
/// <summary>
/// Gets or sets the reason for ignoring the test
/// </summary>
public string Ignore
{
get { return IgnoreReason; }
set { IgnoreReason = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="NUnit.Framework.TestCaseAttribute"/> is explicit.
/// </summary>
/// <value>
/// <c>true</c> if explicit; otherwise, <c>false</c>.
/// </value>
public bool Explicit
{
get { return RunState == RunState.Explicit; }
set { RunState = value ? RunState.Explicit : RunState.Runnable; }
}
/// <summary>
/// Gets or sets the reason for not running the test.
/// </summary>
/// <value>The reason.</value>
public string Reason
{
get { return Properties.Get(PropertyNames.SkipReason) as string; }
set { Properties.Set(PropertyNames.SkipReason, value); }
}
/// <summary>
/// Gets or sets the ignore reason. When set to a non-null
/// non-empty value, the test is marked as ignored.
/// </summary>
/// <value>The ignore reason.</value>
public string IgnoreReason
{
get { return Reason; }
set
{
RunState = RunState.Ignored;
Reason = value;
}
}
#if PLATFORM_DETECTION
/// <summary>
/// Comma-delimited list of platforms to run the test for
/// </summary>
public string IncludePlatform { get; set; }
/// <summary>
/// Comma-delimited list of platforms to not run the test for
/// </summary>
public string ExcludePlatform { get; set; }
#endif
/// <summary>
/// Gets and sets the category for this test case.
/// May be a comma-separated list of categories.
/// </summary>
public string Category
{
get { return Properties.Get(PropertyNames.Category) as string; }
set
{
foreach (string cat in value.Split(new char[] { ',' }) )
Properties.Add(PropertyNames.Category, cat);
}
}
#endregion
#region Helper Methods
private TestCaseParameters GetParametersForTestCase(IMethodInfo method)
{
TestCaseParameters parms;
try
{
IParameterInfo[] parameters = method.GetParameters();
int argsNeeded = parameters.Length;
int argsProvided = Arguments.Length;
parms = new TestCaseParameters(this);
// Special handling for ExpectedResult (see if it needs to be converted into method return type)
object expectedResultInTargetType;
if (parms.HasExpectedResult
&& PerformSpecialConversion(parms.ExpectedResult, method.ReturnType.Type, out expectedResultInTargetType))
{
parms.ExpectedResult = expectedResultInTargetType;
}
// Special handling for params arguments
if (argsNeeded > 0 && argsProvided >= argsNeeded - 1)
{
IParameterInfo lastParameter = parameters[argsNeeded - 1];
Type lastParameterType = lastParameter.ParameterType;
Type elementType = lastParameterType.GetElementType();
if (lastParameterType.IsArray && lastParameter.IsDefined<ParamArrayAttribute>(false))
{
if (argsProvided == argsNeeded)
{
if (!lastParameterType.IsInstanceOfType(parms.Arguments[argsProvided - 1]))
{
Array array = Array.CreateInstance(elementType, 1);
array.SetValue(parms.Arguments[argsProvided - 1], 0);
parms.Arguments[argsProvided - 1] = array;
}
}
else
{
object[] newArglist = new object[argsNeeded];
for (int i = 0; i < argsNeeded && i < argsProvided; i++)
newArglist[i] = parms.Arguments[i];
int length = argsProvided - argsNeeded + 1;
Array array = Array.CreateInstance(elementType, length);
for (int i = 0; i < length; i++)
array.SetValue(parms.Arguments[argsNeeded + i - 1], i);
newArglist[argsNeeded - 1] = array;
parms.Arguments = newArglist;
argsProvided = argsNeeded;
}
}
}
//Special handling for optional parameters
if (parms.Arguments.Length < argsNeeded)
{
object[] newArgList = new object[parameters.Length];
Array.Copy(parms.Arguments, newArgList, parms.Arguments.Length);
//Fill with Type.Missing for remaining required parameters where optional
for (var i = parms.Arguments.Length; i < parameters.Length; i++)
{
if (parameters[i].IsOptional)
newArgList[i] = Type.Missing;
else
{
if (i < parms.Arguments.Length)
newArgList[i] = parms.Arguments[i];
else
throw new TargetParameterCountException(string.Format(
"Method requires {0} arguments but TestCaseAttribute only supplied {1}",
argsNeeded,
argsProvided));
}
}
parms.Arguments = newArgList;
}
//if (method.GetParameters().Length == 1 && method.GetParameters()[0].ParameterType == typeof(object[]))
// parms.Arguments = new object[]{parms.Arguments};
// Special handling when sole argument is an object[]
if (argsNeeded == 1 && method.GetParameters()[0].ParameterType == typeof(object[]))
{
if (argsProvided > 1 ||
argsProvided == 1 && parms.Arguments[0].GetType() != typeof(object[]))
{
parms.Arguments = new object[] { parms.Arguments };
}
}
if (argsProvided == argsNeeded)
PerformSpecialConversions(parms.Arguments, parameters);
}
catch (Exception ex)
{
parms = new TestCaseParameters(ex);
}
return parms;
}
/// <summary>
/// Performs several special conversions allowed by NUnit in order to
/// permit arguments with types that cannot be used in the constructor
/// of an Attribute such as TestCaseAttribute or to simplify their use.
/// </summary>
/// <param name="arglist">The arguments to be converted</param>
/// <param name="parameters">The ParameterInfo array for the method</param>
private static void PerformSpecialConversions(object[] arglist, IParameterInfo[] parameters)
{
for (int i = 0; i < arglist.Length; i++)
{
object arg = arglist[i];
Type targetType = parameters[i].ParameterType;
object argAsTargetType;
if (PerformSpecialConversion(arg, targetType, out argAsTargetType))
{
arglist[i] = argAsTargetType;
}
}
}
/// <summary>
/// Performs several special conversions allowed by NUnit in order to
/// permit arguments with types that cannot be used in the constructor
/// of an Attribute such as TestCaseAttribute or to simplify their use.
/// </summary>
/// <param name="arg">The argument to be converted</param>
/// <param name="targetType">The target <see cref="Type"/> in which the <paramref name="arg"/> should be converted</param>
/// <param name="argAsTargetType">If conversion was successfully applied, the <paramref name="arg"/> converted into <paramref name="targetType"/></param>
/// <returns>
/// <c>true</c> if <paramref name="arg"/> was converted and <paramref name="argAsTargetType"/> should be used;
/// <c>false</c> is no conversion was applied and <paramref name="argAsTargetType"/> should be ignored
/// </returns>
private static bool PerformSpecialConversion(object arg, Type targetType, out object argAsTargetType)
{
argAsTargetType = null;
if (arg == null)
return false;
if (targetType.IsInstanceOfType(arg))
return false;
if (arg.GetType().FullName == "System.DBNull")
{
argAsTargetType = null;
return true;
}
bool convert = false;
if (targetType == typeof(short) || targetType == typeof(byte) || targetType == typeof(sbyte) || targetType == typeof(long?) ||
targetType == typeof(short?) || targetType == typeof(byte?) || targetType == typeof(sbyte?) || targetType == typeof(double?))
{
convert = arg is int;
}
else if (targetType == typeof(decimal) || targetType == typeof(decimal?))
{
convert = arg is double || arg is string || arg is int;
}
else if (targetType == typeof(DateTime) || targetType == typeof(DateTime?))
{
convert = arg is string;
}
if (convert)
{
Type convertTo = targetType.GetTypeInfo().IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>) ?
targetType.GetGenericArguments()[0] : targetType;
argAsTargetType = Convert.ChangeType(arg, convertTo, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
// Convert.ChangeType doesn't work for TimeSpan from string
if ((targetType == typeof(TimeSpan) || targetType == typeof(TimeSpan?)) && arg is string)
{
argAsTargetType = TimeSpan.Parse((string)arg);
return true;
}
return false;
}
#endregion
#region ITestBuilder Members
/// <summary>
/// Builds a single test from the specified method and context.
/// </summary>
/// <param name="method">The MethodInfo for which tests are to be constructed.</param>
/// <param name="suite">The suite to which the tests will be added.</param>
public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test suite)
{
TestMethod test = new NUnitTestCaseBuilder().BuildTestMethod(method, suite, GetParametersForTestCase(method));
#if PLATFORM_DETECTION
if (test.RunState != RunState.NotRunnable &&
test.RunState != RunState.Ignored)
{
PlatformHelper platformHelper = new PlatformHelper();
if (!platformHelper.IsPlatformSupported(this))
{
test.RunState = RunState.Skipped;
test.Properties.Add(PropertyNames.SkipReason, platformHelper.Reason);
}
}
#endif
yield return test;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ResourceManager
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for ResourcesOperations.
/// </summary>
public static partial class ResourcesOperationsExtensions
{
/// <summary>
/// Move resources from one resource group to another. The resources being
/// moved should all be in the same resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='sourceResourceGroupName'>
/// Source resource group name.
/// </param>
/// <param name='parameters'>
/// move resources' parameters.
/// </param>
public static void MoveResources(this IResourcesOperations operations, string sourceResourceGroupName, ResourcesMoveInfo parameters)
{
Task.Factory.StartNew(s => ((IResourcesOperations)s).MoveResourcesAsync(sourceResourceGroupName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Move resources from one resource group to another. The resources being
/// moved should all be in the same resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='sourceResourceGroupName'>
/// Source resource group name.
/// </param>
/// <param name='parameters'>
/// move resources' parameters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task MoveResourcesAsync(this IResourcesOperations operations, string sourceResourceGroupName, ResourcesMoveInfo parameters, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.MoveResourcesWithHttpMessagesAsync(sourceResourceGroupName, parameters, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Move resources from one resource group to another. The resources being
/// moved should all be in the same resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='sourceResourceGroupName'>
/// Source resource group name.
/// </param>
/// <param name='parameters'>
/// move resources' parameters.
/// </param>
public static void BeginMoveResources(this IResourcesOperations operations, string sourceResourceGroupName, ResourcesMoveInfo parameters)
{
Task.Factory.StartNew(s => ((IResourcesOperations)s).BeginMoveResourcesAsync(sourceResourceGroupName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Move resources from one resource group to another. The resources being
/// moved should all be in the same resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='sourceResourceGroupName'>
/// Source resource group name.
/// </param>
/// <param name='parameters'>
/// move resources' parameters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginMoveResourcesAsync(this IResourcesOperations operations, string sourceResourceGroupName, ResourcesMoveInfo parameters, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginMoveResourcesWithHttpMessagesAsync(sourceResourceGroupName, parameters, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get all of the resources under a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<GenericResource> List(this IResourcesOperations operations, ODataQuery<GenericResourceFilter> odataQuery = default(ODataQuery<GenericResourceFilter>))
{
return Task.Factory.StartNew(s => ((IResourcesOperations)s).ListAsync(odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get all of the resources under a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<GenericResource>> ListAsync(this IResourcesOperations operations, ODataQuery<GenericResourceFilter> odataQuery = default(ODataQuery<GenericResourceFilter>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Checks whether resource exists.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Resource identity.
/// </param>
/// <param name='parentResourcePath'>
/// Resource identity.
/// </param>
/// <param name='resourceType'>
/// Resource identity.
/// </param>
/// <param name='resourceName'>
/// Resource identity.
/// </param>
/// <param name='apiVersion'>
/// Api version to use.
/// </param>
public static bool CheckExistence(this IResourcesOperations operations, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string apiVersion)
{
return Task.Factory.StartNew(s => ((IResourcesOperations)s).CheckExistenceAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Checks whether resource exists.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Resource identity.
/// </param>
/// <param name='parentResourcePath'>
/// Resource identity.
/// </param>
/// <param name='resourceType'>
/// Resource identity.
/// </param>
/// <param name='resourceName'>
/// Resource identity.
/// </param>
/// <param name='apiVersion'>
/// Api version to use.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<bool> CheckExistenceAsync(this IResourcesOperations operations, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string apiVersion, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CheckExistenceWithHttpMessagesAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Resource identity.
/// </param>
/// <param name='parentResourcePath'>
/// Resource identity.
/// </param>
/// <param name='resourceType'>
/// Resource identity.
/// </param>
/// <param name='resourceName'>
/// Resource identity.
/// </param>
/// <param name='apiVersion'>
/// Api version to use.
/// </param>
public static void Delete(this IResourcesOperations operations, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string apiVersion)
{
Task.Factory.StartNew(s => ((IResourcesOperations)s).DeleteAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Resource identity.
/// </param>
/// <param name='parentResourcePath'>
/// Resource identity.
/// </param>
/// <param name='resourceType'>
/// Resource identity.
/// </param>
/// <param name='resourceName'>
/// Resource identity.
/// </param>
/// <param name='apiVersion'>
/// Api version to use.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IResourcesOperations operations, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string apiVersion, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Create a resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Resource identity.
/// </param>
/// <param name='parentResourcePath'>
/// Resource identity.
/// </param>
/// <param name='resourceType'>
/// Resource identity.
/// </param>
/// <param name='resourceName'>
/// Resource identity.
/// </param>
/// <param name='apiVersion'>
/// Api version to use.
/// </param>
/// <param name='parameters'>
/// Create or update resource parameters.
/// </param>
public static GenericResource CreateOrUpdate(this IResourcesOperations operations, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string apiVersion, GenericResource parameters)
{
return Task.Factory.StartNew(s => ((IResourcesOperations)s).CreateOrUpdateAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Resource identity.
/// </param>
/// <param name='parentResourcePath'>
/// Resource identity.
/// </param>
/// <param name='resourceType'>
/// Resource identity.
/// </param>
/// <param name='resourceName'>
/// Resource identity.
/// </param>
/// <param name='apiVersion'>
/// Api version to use.
/// </param>
/// <param name='parameters'>
/// Create or update resource parameters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GenericResource> CreateOrUpdateAsync(this IResourcesOperations operations, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string apiVersion, GenericResource parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns a resource belonging to a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Resource identity.
/// </param>
/// <param name='parentResourcePath'>
/// Resource identity.
/// </param>
/// <param name='resourceType'>
/// Resource identity.
/// </param>
/// <param name='resourceName'>
/// Resource identity.
/// </param>
/// <param name='apiVersion'>
/// Api version to use.
/// </param>
public static GenericResource Get(this IResourcesOperations operations, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string apiVersion)
{
return Task.Factory.StartNew(s => ((IResourcesOperations)s).GetAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns a resource belonging to a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Resource identity.
/// </param>
/// <param name='parentResourcePath'>
/// Resource identity.
/// </param>
/// <param name='resourceType'>
/// Resource identity.
/// </param>
/// <param name='resourceName'>
/// Resource identity.
/// </param>
/// <param name='apiVersion'>
/// Api version to use.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GenericResource> GetAsync(this IResourcesOperations operations, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string apiVersion, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Checks whether resource exists.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceId'>
/// The fully qualified Id of the resource, including the resource name and
/// resource type. For example,
/// /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite
/// </param>
/// <param name='apiVersion'>
/// Api version to use.
/// </param>
public static bool CheckExistenceById(this IResourcesOperations operations, string resourceId, string apiVersion)
{
return Task.Factory.StartNew(s => ((IResourcesOperations)s).CheckExistenceByIdAsync(resourceId, apiVersion), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Checks whether resource exists.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceId'>
/// The fully qualified Id of the resource, including the resource name and
/// resource type. For example,
/// /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite
/// </param>
/// <param name='apiVersion'>
/// Api version to use.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<bool> CheckExistenceByIdAsync(this IResourcesOperations operations, string resourceId, string apiVersion, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CheckExistenceByIdWithHttpMessagesAsync(resourceId, apiVersion, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceId'>
/// The fully qualified Id of the resource, including the resource name and
/// resource type. For example,
/// /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite
/// </param>
/// <param name='apiVersion'>
/// Api version to use.
/// </param>
public static void DeleteById(this IResourcesOperations operations, string resourceId, string apiVersion)
{
Task.Factory.StartNew(s => ((IResourcesOperations)s).DeleteByIdAsync(resourceId, apiVersion), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceId'>
/// The fully qualified Id of the resource, including the resource name and
/// resource type. For example,
/// /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite
/// </param>
/// <param name='apiVersion'>
/// Api version to use.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteByIdAsync(this IResourcesOperations operations, string resourceId, string apiVersion, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteByIdWithHttpMessagesAsync(resourceId, apiVersion, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Create a resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceId'>
/// The fully qualified Id of the resource, including the resource name and
/// resource type. For example,
/// /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite
/// </param>
/// <param name='apiVersion'>
/// Api version to use.
/// </param>
/// <param name='parameters'>
/// Create or update resource parameters.
/// </param>
public static GenericResource CreateOrUpdateById(this IResourcesOperations operations, string resourceId, string apiVersion, GenericResource parameters)
{
return Task.Factory.StartNew(s => ((IResourcesOperations)s).CreateOrUpdateByIdAsync(resourceId, apiVersion, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceId'>
/// The fully qualified Id of the resource, including the resource name and
/// resource type. For example,
/// /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite
/// </param>
/// <param name='apiVersion'>
/// Api version to use.
/// </param>
/// <param name='parameters'>
/// Create or update resource parameters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GenericResource> CreateOrUpdateByIdAsync(this IResourcesOperations operations, string resourceId, string apiVersion, GenericResource parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateByIdWithHttpMessagesAsync(resourceId, apiVersion, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceId'>
/// The fully qualified Id of the resource, including the resource name and
/// resource type. For example,
/// /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite
/// </param>
/// <param name='apiVersion'>
/// Api version to use.
/// </param>
public static GenericResource GetById(this IResourcesOperations operations, string resourceId, string apiVersion)
{
return Task.Factory.StartNew(s => ((IResourcesOperations)s).GetByIdAsync(resourceId, apiVersion), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceId'>
/// The fully qualified Id of the resource, including the resource name and
/// resource type. For example,
/// /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite
/// </param>
/// <param name='apiVersion'>
/// Api version to use.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GenericResource> GetByIdAsync(this IResourcesOperations operations, string resourceId, string apiVersion, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetByIdWithHttpMessagesAsync(resourceId, apiVersion, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get all of the resources under a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<GenericResource> ListNext(this IResourcesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IResourcesOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get all of the resources under a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<GenericResource>> ListNextAsync(this IResourcesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Security;
using SFML.Window;
using Vector2f = SFML.Graphics.Vector2;
namespace SFML
{
namespace Graphics
{
////////////////////////////////////////////////////////////
/// <summary>
/// Base class for textured shapes with outline
/// </summary>
////////////////////////////////////////////////////////////
public abstract class Shape : Transformable, Drawable
{
////////////////////////////////////////////////////////////
/// <summary>
/// Source texture of the shape
/// </summary>
////////////////////////////////////////////////////////////
public Texture Texture
{
get { return myTexture; }
set { myTexture = value; sfShape_setTexture(CPointer, value != null ? value.CPointer : IntPtr.Zero, false); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Sub-rectangle of the texture that the shape will display
/// </summary>
////////////////////////////////////////////////////////////
public IntRect TextureRect
{
get { return sfShape_getTextureRect(CPointer); }
set { sfShape_setTextureRect(CPointer, value); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Fill color of the shape
/// </summary>
////////////////////////////////////////////////////////////
public Color FillColor
{
get { return sfShape_getFillColor(CPointer); }
set { sfShape_setFillColor(CPointer, value); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Outline color of the shape
/// </summary>
////////////////////////////////////////////////////////////
public Color OutlineColor
{
get { return sfShape_getOutlineColor(CPointer); }
set { sfShape_setOutlineColor(CPointer, value); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Thickness of the shape's outline
/// </summary>
////////////////////////////////////////////////////////////
public float OutlineThickness
{
get { return sfShape_getOutlineThickness(CPointer); }
set { sfShape_setOutlineThickness(CPointer, value); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Get the total number of points of the shape
/// </summary>
/// <returns>The total point count</returns>
////////////////////////////////////////////////////////////
public abstract uint GetPointCount();
////////////////////////////////////////////////////////////
/// <summary>
/// Get a point of the shape.
///
/// The result is undefined if index is out of the valid range.
/// </summary>
/// <param name="index">Index of the point to get, in range [0 .. PointCount - 1]</param>
/// <returns>Index-th point of the shape</returns>
////////////////////////////////////////////////////////////
public abstract Vector2f GetPoint(uint index);
////////////////////////////////////////////////////////////
/// <summary>
/// Get the local bounding rectangle of the entity.
///
/// The returned rectangle is in local coordinates, which means
/// that it ignores the transformations (translation, rotation,
/// scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// entity in the entity's coordinate system.
/// </summary>
/// <returns>Local bounding rectangle of the entity</returns>
////////////////////////////////////////////////////////////
public FloatRect GetLocalBounds()
{
return sfShape_getLocalBounds(CPointer);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Get the global bounding rectangle of the entity.
///
/// The returned rectangle is in global coordinates, which means
/// that it takes in account the transformations (translation,
/// rotation, scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// sprite in the global 2D world's coordinate system.
/// </summary>
/// <returns>Global bounding rectangle of the entity</returns>
////////////////////////////////////////////////////////////
public FloatRect GetGlobalBounds()
{
// we don't use the native getGlobalBounds function,
// because we override the object's transform
return Transform.TransformRect(GetLocalBounds());
}
////////////////////////////////////////////////////////////
/// <summmary>
/// Draw the object to a render target
///
/// This is a pure virtual function that has to be implemented
/// by the derived class to define how the drawable should be
/// drawn.
/// </summmary>
/// <param name="target">Render target to draw to</param>
/// <param name="states">Current render states</param>
////////////////////////////////////////////////////////////
public void Draw(RenderTarget target, RenderStates states)
{
//states.Transform *= Transform; // NetGore custom line
RenderStates.MarshalData marshaledStates = states.Marshal(Transform); // NetGore custom line
if (target is RenderWindow)
{
sfRenderWindow_drawShape(((RenderWindow)target).CPointer, CPointer, ref marshaledStates);
}
else if (target is RenderTexture)
{
sfRenderTexture_drawShape(((RenderTexture)target).CPointer, CPointer, ref marshaledStates);
}
ShapeHelper.AMDShapeRenderFix(target);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Default constructor
/// </summary>
////////////////////////////////////////////////////////////
protected Shape() :
base(IntPtr.Zero)
{
myGetPointCountCallback = new GetPointCountCallbackType(InternalGetPointCount);
myGetPointCallback = new GetPointCallbackType(InternalGetPoint);
SetThis(sfShape_create(myGetPointCountCallback, myGetPointCallback, IntPtr.Zero));
}
////////////////////////////////////////////////////////////
/// <summary>
/// Construct the shape from another shape
/// </summary>
/// <param name="copy">Shape to copy</param>
////////////////////////////////////////////////////////////
public Shape(Shape copy) :
base(IntPtr.Zero)
{
myGetPointCountCallback = new GetPointCountCallbackType(InternalGetPointCount);
myGetPointCallback = new GetPointCallbackType(InternalGetPoint);
SetThis(sfShape_create(myGetPointCountCallback, myGetPointCallback, IntPtr.Zero));
Origin = copy.Origin;
Position = copy.Position;
Rotation = copy.Rotation;
Scale = copy.Scale;
Texture = copy.Texture;
TextureRect = copy.TextureRect;
FillColor = copy.FillColor;
OutlineColor = copy.OutlineColor;
OutlineThickness = copy.OutlineThickness;
}
////////////////////////////////////////////////////////////
/// <summary>
/// Recompute the internal geometry of the shape.
///
/// This function must be called by the derived class everytime
/// the shape's points change (ie. the result of either
/// PointCount or GetPoint is different).
/// </summary>
////////////////////////////////////////////////////////////
protected void Update()
{
sfShape_update(CPointer);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Handle the destruction of the object
/// </summary>
/// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param>
////////////////////////////////////////////////////////////
protected override void Destroy(bool disposing)
{
sfShape_destroy(CPointer);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Callback passed to the C API
/// </summary>
////////////////////////////////////////////////////////////
private uint InternalGetPointCount(IntPtr userData)
{
return GetPointCount();
}
////////////////////////////////////////////////////////////
/// <summary>
/// Callback passed to the C API
/// </summary>
////////////////////////////////////////////////////////////
private Vector2f InternalGetPoint(uint index, IntPtr userData)
{
return GetPoint(index);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate uint GetPointCountCallbackType(IntPtr UserData);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate Vector2f GetPointCallbackType(uint index, IntPtr UserData);
private GetPointCountCallbackType myGetPointCountCallback;
private GetPointCallbackType myGetPointCallback;
private Texture myTexture = null;
#region Imports
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfShape_create(GetPointCountCallbackType getPointCount, GetPointCallbackType getPoint, IntPtr userData);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfShape_copy(IntPtr Shape);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShape_destroy(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShape_setTexture(IntPtr CPointer, IntPtr Texture, bool AdjustToNewSize);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShape_setTextureRect(IntPtr CPointer, IntRect Rect);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntRect sfShape_getTextureRect(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShape_setFillColor(IntPtr CPointer, Color Color);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern Color sfShape_getFillColor(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShape_setOutlineColor(IntPtr CPointer, Color Color);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern Color sfShape_getOutlineColor(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShape_setOutlineThickness(IntPtr CPointer, float Thickness);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern float sfShape_getOutlineThickness(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern FloatRect sfShape_getLocalBounds(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShape_update(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderWindow_drawShape(IntPtr CPointer, IntPtr Shape, ref RenderStates.MarshalData states);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderTexture_drawShape(IntPtr CPointer, IntPtr Shape, ref RenderStates.MarshalData states);
#endregion
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
public static class tk2dGuiUtility
{
public static bool HasActivePositionHandle { get { return activePositionHandleId != 0; } }
public static Vector2 ActiveHandlePosition { get { return activePositionHandlePosition; } }
static int activePositionHandleId = 0;
static Vector2 activePositionHandlePosition = Vector2.zero;
public static void SetPositionHandleValue(int id, Vector2 val)
{
if (id == activePositionHandleId)
activePositionHandlePosition = val;
}
public static Vector2 PositionHandle(int id, Vector2 position, float size, Color inactiveColor, Color activeColor)
{
KeyCode discardKeyCode = KeyCode.None;
return PositionHandle(id, position, size, inactiveColor, activeColor, out discardKeyCode);
}
public static Vector2 PositionHandle(int id, Vector2 position, float size, Color inactiveColor, Color activeColor, out KeyCode keyCode)
{
Rect rect = new Rect(position.x - size, position.y - size, size * 2, size * 2);
int controlID = GUIUtility.GetControlID(id, FocusType.Passive);
keyCode = KeyCode.None;
switch (Event.current.GetTypeForControl(controlID))
{
case EventType.MouseDown:
{
if (rect.Contains(Event.current.mousePosition))
{
activePositionHandleId = id;
GUIUtility.hotControl = controlID;
Event.current.Use();
}
break;
}
case EventType.MouseDrag:
{
if (GUIUtility.hotControl == controlID)
{
position = Event.current.mousePosition;
Event.current.Use();
}
break;
}
case EventType.MouseUp:
{
if (GUIUtility.hotControl == controlID)
{
activePositionHandleId = 0;
GUIUtility.hotControl = 0;
Event.current.Use();
}
break;
}
case EventType.KeyDown:
{
if (rect.Contains(Event.current.mousePosition))
{
keyCode = Event.current.keyCode;
if (GUIUtility.hotControl == controlID)
{
activePositionHandleId = 0;
GUIUtility.hotControl = 0;
Event.current.Use();
}
}
break;
}
case EventType.Repaint:
{
Color oc = Handles.color;
Handles.color = (GUIUtility.hotControl == controlID)?activeColor:inactiveColor;
Vector3[] pts = new Vector3[] {
new Vector3(rect.xMin, rect.yMin, 0.0f),
new Vector3(rect.xMax, rect.yMin, 0.0f),
new Vector3(rect.xMax, rect.yMax, 0.0f),
new Vector3(rect.xMin, rect.yMax, 0.0f),
};
Handles.DrawSolidRectangleWithOutline(pts, oc, oc);
Handles.color = oc;
break;
}
}
return position;
}
public enum WarningLevel
{
Info,
Warning,
Error
}
/// <summary>
/// Display a warning box in the current GUI layout.
/// This is expanded to fit the current GUILayout rect.
/// </summary>
public static void InfoBox(string message, WarningLevel warningLevel)
{
MessageType messageType = MessageType.None;
switch (warningLevel)
{
case WarningLevel.Info: messageType = MessageType.Info; break;
case WarningLevel.Warning: messageType = MessageType.Warning; break;
case WarningLevel.Error: messageType = MessageType.Error; break;
}
EditorGUILayout.HelpBox(message, messageType);
}
/// <summary>
/// Displays a warning box in the current GUI layout, with buttons.
/// Returns the index of button pressed, or -1 otherwise.
/// </summary>
public static int InfoBoxWithButtons(string message, WarningLevel warningLevel, params string[] buttons)
{
Color oldBackgroundColor = GUI.backgroundColor;
switch (warningLevel)
{
case WarningLevel.Info: GUI.backgroundColor = new Color32(154, 176, 203, 255); break;
case WarningLevel.Warning: GUI.backgroundColor = new Color32(255, 255, 0, 255); break;
case WarningLevel.Error: GUI.backgroundColor = new Color32(255, 0, 0, 255); break;
}
GUILayout.BeginVertical("textarea");
GUI.backgroundColor = oldBackgroundColor;
GUIStyle labelStyle = new GUIStyle("label");
labelStyle.wordWrap = true;
GUILayout.Label(message, labelStyle, GUILayout.ExpandWidth(true));
int buttonPressed = -1;
if (buttons != null)
{
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
for (int i = 0; i < buttons.Length; ++i)
{
if (GUILayout.Button(buttons[i], EditorStyles.miniButton))
buttonPressed = i;
}
GUILayout.EndHorizontal();
}
GUILayout.EndVertical();
return buttonPressed;
}
public enum DragDirection
{
Horizontal,
}
// Size is the offset into the rect to draw the DragableHandle
const float resizeBarHotSpotSize = 2.0f;
public static float DragableHandle(int id, Rect windowRect, float offset, DragDirection direction)
{
int controlID = GUIUtility.GetControlID(id, FocusType.Passive);
Vector2 positionFilter = Vector2.zero;
Rect controlRect = windowRect;
switch (direction)
{
case DragDirection.Horizontal:
controlRect = new Rect(controlRect.x + offset - resizeBarHotSpotSize,
controlRect.y,
resizeBarHotSpotSize * 2 + 1.0f,
controlRect.height);
positionFilter.x = 1.0f;
break;
}
EditorGUIUtility.AddCursorRect(controlRect, MouseCursor.ResizeHorizontal);
if (GUIUtility.hotControl == 0)
{
if (Event.current.type == EventType.MouseDown && controlRect.Contains(Event.current.mousePosition))
{
GUIUtility.hotControl = controlID;
Event.current.Use();
}
}
else if (GUIUtility.hotControl == controlID)
{
if (Event.current.type == EventType.MouseDrag)
{
Vector2 mousePosition = Event.current.mousePosition;
Vector2 handleOffset = new Vector2((mousePosition.x - windowRect.x) * positionFilter.x,
(mousePosition.y - windowRect.y) * positionFilter.y);
offset = handleOffset.x + handleOffset.y;
HandleUtility.Repaint();
}
else if (Event.current.type == EventType.MouseUp)
{
GUIUtility.hotControl = 0;
}
}
// Debug draw
// GUI.Box(controlRect, "");
return offset;
}
private static bool backupGuiChangedValue = false;
public static void BeginChangeCheck()
{
backupGuiChangedValue = GUI.changed;
GUI.changed = false;
}
public static bool EndChangeCheck()
{
bool hasChanged = GUI.changed;
GUI.changed |= backupGuiChangedValue;
return hasChanged;
}
public static string PlatformPopup(tk2dSystem system, string label, string platform)
{
if (system == null)
return label;
int selectedIndex = -1;
string[] platformNames = new string[system.assetPlatforms.Length];
for (int i = 0; i < system.assetPlatforms.Length; ++i)
{
platformNames[i] = system.assetPlatforms[i].name;
if (platformNames[i] == platform) selectedIndex = i;
}
selectedIndex = EditorGUILayout.Popup(label, selectedIndex, platformNames);
if (selectedIndex == -1) return "";
else return platformNames[selectedIndex];
}
public static string SaveFileInProject(string title, string directory, string filename, string ext)
{
string path = EditorUtility.SaveFilePanel(title, directory, filename, ext);
if (path.Length == 0) // cancelled
return "";
string cwd = System.IO.Directory.GetCurrentDirectory().Replace("\\","/") + "/assets/";
if (path.ToLower().IndexOf(cwd.ToLower()) != 0)
{
path = "";
EditorUtility.DisplayDialog(title, "Assets must be saved inside the Assets folder", "Ok");
}
else
{
path = path.Substring(cwd.Length - "/assets".Length);
}
return path;
}
}
| |
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 BdRestServer.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 InsertInt32129()
{
var test = new InsertScalarTest__InsertInt32129();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario();
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();
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();
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 InsertScalarTest__InsertInt32129
{
private struct TestStruct
{
public Vector128<Int32> _fld;
public Int32 _scalarFldData;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
testStruct._scalarFldData = (int)2;
return testStruct;
}
public void RunStructFldScenario(InsertScalarTest__InsertInt32129 testClass)
{
var result = Sse41.Insert(_fld, _scalarFldData, 129);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, _scalarFldData, 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[] _data = new Int32[Op1ElementCount];
private static Int32 _scalarClsData = (int)2;
private static Vector128<Int32> _clsVar;
private Vector128<Int32> _fld;
private Int32 _scalarFldData = (int)2;
private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable;
static InsertScalarTest__InsertInt32129()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public InsertScalarTest__InsertInt32129()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
var result = Sse41.Insert(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr),
(int)2,
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, (int)2, _dataTable.outArrayPtr);
}
public unsafe void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
Int32 localData = (int)2;
Int32* ptr = &localData;
var result = Sse41.Insert(
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)),
*ptr,
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr);
}
public unsafe void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
Int32 localData = (int)2;
Int32* ptr = &localData;
var result = Sse41.Insert(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)),
*ptr,
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Int32>), typeof(Int32), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr),
(int)2,
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, (int)2, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Int32>), typeof(Int32), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)),
(int)2,
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, (int)2, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Int32>), typeof(Int32), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)),
(int)2,
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, (int)2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.Insert(
_clsVar,
_scalarClsData,
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _scalarClsData,_dataTable.outArrayPtr);
}
public void RunLclVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario));
Int32 localData = (int)2;
var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr);
var result = Sse41.Insert(firstOp, localData, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, localData, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
Int32 localData = (int)2;
var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse41.Insert(firstOp, localData, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, localData, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
Int32 localData = (int)2;
var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse41.Insert(firstOp, localData, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, localData, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new InsertScalarTest__InsertInt32129();
var result = Sse41.Insert(test._fld, test._scalarFldData, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, test._scalarFldData, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.Insert(_fld, _scalarFldData, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _scalarFldData, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.Insert(test._fld, test._scalarFldData, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, test._scalarFldData, _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();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> firstOp, Int32 scalarData, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, scalarData, outArray, method);
}
private void ValidateResult(void* firstOp, Int32 scalarData, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (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(inArray, scalarData, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32 scalarData, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if ((i == 1 ? result[i] != scalarData : result[i] != firstOp[i]))
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<Int32>(Vector128<Int32><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using MonoTouch.ObjCRuntime;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.CoreLocation;
using MonoTouch.CoreBluetooth;
namespace EstimoteSDK {
[BaseType (typeof (NSObject))]
public partial interface ESTBeaconUpdateInfo {
[Export ("currentFirmwareVersion", ArgumentSemantic.Retain)]
string CurrentFirmwareVersion { get; set; }
[Export ("supportedHardware", ArgumentSemantic.Retain)]
NSArray SupportedHardware { get; set; }
}
/// <summary>
/// ESTBeaconDelegate defines beacon connection delegate mathods.
/// Connection is asynchronous operation so you need to be prepared that
/// eg. beaconDidDisconnectWith: method can be invoked without previous action.
/// </summary>
[Model, BaseType (typeof (NSObject))]
public partial interface ESTBeaconDelegate {
/// <summary>
/// Delegate method that indicates error in beacon connection.
/// </summary>
/// <param name="beacon">Reference to the Beacon.</param>
/// <param name="error">Error Reason.</param>
[Export ("beaconConnectionDidFail:withError:")]
void BeaconConnectionDidFail(ESTBeacon beacon, NSError error);
/// <summary>
/// Delegate method that indicates success in beacon connection.
/// </summary>
/// <param name="beacon">Reference to the Beacon.</param>
[Export ("beaconConnectionDidSucceeded:")]
void beaconConnectionDidSucceeded(ESTBeacon beacon);
/// <summary>
/// Delegate method that beacon did disconnect with device.
/// </summary>
/// <param name="beacon">Beacon.</param>
/// <param name="error">Error.</param>
[Export ("beaconDidDisconnect:withError:")]
void beaconDidDisconnect(ESTBeacon beacon, NSError error);
}
/// <summary>
/// Delegate declarations for blocks (C# lambdas
/// </summary>
public delegate void ESTStringCompletionBlock();
public delegate void ESTUnsignedShortCompletionBlock();
public delegate void ESTPowerCompletionBlock();
public delegate void ESTFirmwareUpdateCompletionBlock();
public delegate void ESTCompletionBlock();
/// <summary>
/// The ESTBeacon class represents a beacon that was encountered during region monitoring.
/// You do not create instances of this class directly.
/// The ESTBeaconManager object reports encountered beacons to its associated delegate object.
/// You can use the information in a beacon object to identify which beacon was encountered.
/// ESTBeacon class contains basic Apple CLBeacon object reference as well as some additional functionality.
/// It allows to connect with Estimote beacon to read / write its characteristics.
/// </summary>
[BaseType (typeof (NSObject))]
public partial interface ESTBeacon {
[Export ("firmwareState")]
ESTBeaconFirmwareState FirmwareState { get; set; }
[Export ("delegate", ArgumentSemantic.Assign)]
ESTBeaconDelegate Delegate { get; set; }
/// <summary>
/// Hardware MAC Address of the Beacon
/// </summary>
/// <value>The mac address.</value>
[Export ("macAddress", ArgumentSemantic.Retain)]
string MacAddress { get; set; }
/// <summary>
/// Proximity identifier associated with the beacon.
/// </summary>
/// <value>The proximity UUI.</value>
[Export ("proximityUUID", ArgumentSemantic.Retain)]
NSUuid ProximityUUID { get; set; }
/// <summary>
/// Most significant value associated with the region.
/// If a major value wasn't specified, this will be nil.
/// </summary>
/// <value>The major.</value>
[Export ("major", ArgumentSemantic.Retain)]
NSNumber Major { get; set; }
/// <summary>
/// Least significant value associated with the region.
/// If a minor value wasn't specified, this will be nil.
/// </summary>
/// <value>The minor.</value>
[Export ("minor", ArgumentSemantic.Retain)]
NSNumber Minor { get; set; }
/// <summary>
/// Received signal strength in decibels of the specified beacon.
/// This value is an average of the RSSI samples collected since this beacon was last reported.
/// </summary>
/// <value>The rssi.</value>
[Export ("rssi")]
int ReceivedSignalStrength { get; set; }
/// <summary>
/// Distance between phone and beacon calculated based on rssi and measured power.
/// </summary>
/// <value>The distance.</value>
[Export ("distance", ArgumentSemantic.Retain)]
NSNumber Distance { get; set; }
/// <summary>
/// The value in this property gives a general sense of the relative distance to the beacon.
/// Use it to quickly identify beacons that are nearer to the user rather than farther away.
/// </summary>
/// <value>The proximity.</value>
[Export ("proximity")]
CLProximity Proximity { get; set; }
/// <summary>
/// Received Signal Strength in dB (rssi) value measured from 1m.
/// This value is used for device calibration.
/// </summary>
/// <value>The measured power.</value>
[Export ("measuredPower", ArgumentSemantic.Retain)]
NSNumber MeasuredPower { get; set; }
/// <summary>
/// Reference of the device peripheral object.
/// </summary>
/// <value>The peripheral.</value>
[Export ("peripheral", ArgumentSemantic.Retain)]
CBPeripheral Peripheral { get; set; }
/// <summary>
/// Flag indicating connection status.
/// </summary>
/// <value><c>true</c> if this instance is connected; otherwise, <c>false</c>.</value>
[Export ("isConnected")]
bool IsConnected { get; }
/// <summary>
/// Power of signal in dBm.
/// Value available after connection with the beacon.
/// It takes one of the values represented by ESTBeaconPower .
/// </summary>
/// <value>The power.</value>
[Export ("power", ArgumentSemantic.Retain)]
NSNumber Power { get; set; }
/// <summary>
/// Advertising interval of the beacon. Value change from 50ms to 2000ms.
/// Value available after connection with the beacon
/// </summary>
/// <value>The adv interval.</value>
[Export ("advInterval", ArgumentSemantic.Retain)]
NSNumber AdvInterval { get; set; }
/// <summary>
/// Battery strength in %. Battery level change from 100% - 0%.
/// Value available after connection with the beacon
/// </summary>
/// <value>The battery level.</value>
[Export ("batteryLevel", ArgumentSemantic.Retain)]
NSNumber BatteryLevel { get; set; }
/// <summary>
/// Version of device hardware. Value available after connection with the beacon
/// </summary>
/// <value>The hardware version.</value>
[Export ("hardwareVersion", ArgumentSemantic.Retain)]
string HardwareVersion { get; set; }
/// <summary>
/// Version of device firmware. Value available after connection with the beacon
/// </summary>
/// <value>The firmware version.</value>
[Export ("firmwareVersion", ArgumentSemantic.Retain)]
string FirmwareVersion { get; set; }
/// <summary>
/// Firmware update availability status.
/// Value available after connection with the beacon and firmware version check.
/// </summary>
/// <value>The firmware update info.</value>
[Export ("firmwareUpdateInfo")]
ESTBeaconFirmwareUpdate FirmwareUpdateInfo { get; }
/// <summary>
/// Connect to particular beacon using bluetooth.
/// Connection is required to change values like
/// Major, Minor, Power and Advertising interval.
/// </summary>
[Export ("connectToBeacon")]
void ConnectToBeacon ();
/// <summary>
/// Disconnect device with particular beacon
/// </summary>
[Export ("disconnectBeacon")]
void DisconnectBeacon ();
/// <summary>
/// Read Proximity UUID of connected beacon (Previous connection required)
/// </summary>
/// <param name="completion">Callback function</param>
[Export ("readBeaconProximityUUIDWithCompletion:")]
void ReadBeaconProximityUUIDWithCompletion (ESTStringCompletionBlock completion);
/// <summary>
/// Read major of connected beacon (Previous connection required)
/// </summary>
/// <param name="completion">Callback function</param>
[Export ("readBeaconMajorWithCompletion:")]
void ReadBeaconMajorWithCompletion (ESTUnsignedShortCompletionBlock completion);
/// <summary>
/// Read minor of connected beacon (Previous connection required)
/// </summary>
/// <param name="completion">Callback function.</param>
[Export ("readBeaconMinorWithCompletion:")]
void ReadBeaconMinorWithCompletion (ESTUnsignedShortCompletionBlock completion);
/// <summary>
/// Read advertising interval of connected beacon (Previous connection required)
/// </summary>
/// <param name="completion">Callback function.</param>
[Export ("readBeaconAdvIntervalWithCompletion:")]
void ReadBeaconAdvIntervalWithCompletion (ESTUnsignedShortCompletionBlock completion);
/// <summary>
/// Read power of connected beacon (Previous connection required)
/// </summary>
/// <param name="completion">Callback function.</param>
[Export ("readBeaconPowerWithCompletion:")]
void ReadBeaconPowerWithCompletion (ESTPowerCompletionBlock completion);
/// <summary>
/// Read battery level of connected beacon (Previous connection required)
/// </summary>
/// <param name="completion">Callback function</param>
[Export ("readBeaconBatteryWithCompletion:")]
void ReadBeaconBatteryWithCompletion (ESTUnsignedShortCompletionBlock completion);
/// <summary>
/// Read firmware version of connected beacon (Previous connection required)
/// </summary>
/// <param name="completion">Callback function.</param>
[Export ("readBeaconFirmwareVersionWithCompletion:")]
void ReadBeaconFirmwareVersionWithCompletion (ESTStringCompletionBlock completion);
/// <summary>
/// Read hardware version of connected beacon (Previous connection required).
/// </summary>
/// <param name="completion">Callback function.</param>
[Export ("readBeaconHardwareVersionWithCompletion:")]
void ReadBeaconHardwareVersionWithCompletion (ESTStringCompletionBlock completion);
/// <summary>
/// Writes Proximity UUID param to bluetooth connected beacon.
/// Please remember that If you change the UUID to your very own value anyone can read it,
/// copy it and spoof your beacons. So if you are working on a mission critical application
/// where security is an issue - be sure to implement it on your end.
/// We are also working on a secure mode for our beacons and it will be included in one of the next firmware updates.
/// </summary>
/// <param name="pUUID">P UUI.</param>
/// <param name="completion">Completion.</param>
[Export ("writeBeaconProximityUUID:withCompletion:")]
void WriteBeaconProximityUUID (string pUUID, ESTStringCompletionBlock completion);
/// <summary>
/// Writes major param to bluetooth connected beacon.
/// </summary>
/// <param name="major">Major.</param>
/// <param name="completion">Completion.</param>
[Export ("writeBeaconMajor:withCompletion:")]
void WriteBeaconMajor (ushort major, ESTUnsignedShortCompletionBlock completion);
/// <summary>
/// Writes minor param to bluetooth connected beacon.
/// </summary>
/// <param name="minor">Minor.</param>
/// <param name="completion">Callback function.</param>
[Export ("writeBeaconMinor:withCompletion:")]
void WriteBeaconMinor (ushort minor, ESTUnsignedShortCompletionBlock completion);
/// <summary>
/// Writes advertising interval (in milisec) of connected beacon.
/// </summary>
/// <param name="interval">Interval.</param>
/// <param name="completion">Callback function.</param>
[Export ("writeBeaconAdvInterval:withCompletion:")]
void WriteBeaconAdvInterval (ushort interval, ESTUnsignedShortCompletionBlock completion);
/// <summary>
/// Writes power of bluetooth connected beacon.
/// </summary>
/// <param name="power">Power.</param>
/// <param name="completion">Callback function.</param>
[Export ("writeBeaconPower:withCompletion:")]
void WriteBeaconPower (ESTBeaconPower power, ESTPowerCompletionBlock completion);
/// <summary>
/// Verifies if new firmware version is available for download
/// without any additional action. Internet connection
/// is required to pass this process.
/// </summary>
/// <param name="completion">Callback function.</param>
[Export ("checkFirmwareUpdateWithCompletion:")]
void CheckFirmwareUpdateWithCompletion (ESTFirmwareUpdateCompletionBlock completion);
/// <summary>
/// Verifies if new firmware version is available for download
/// and updates firmware of connected beacon. Internet connection
/// is required to pass this process.
/// </summary>
/// <param name="progress">Progress.</param>
/// <param name="completion">Completion.</param>
[Export ("updateBeaconFirmwareWithProgress:andCompletion:")]
void UpdateBeaconFirmwareWithProgress (ESTStringCompletionBlock progress, ESTCompletionBlock completion);
}
[Model, BaseType (typeof (NSObject))]
public partial interface ESTBeaconManagerDelegate {
[Export ("beaconManager:didRangeBeacons:inRegion:")]
void DidRangeBeacons (ESTBeaconManager manager, NSArray beacons, ESTBeaconRegion region);
[Export ("beaconManager:rangingBeaconsDidFailForRegion:withError:")]
void RangingBeaconsDidFailForRegion (ESTBeaconManager manager, ESTBeaconRegion region, NSError error);
[Export ("beaconManager:monitoringDidFailForRegion:withError:")]
void MonitoringDidFailForRegion (ESTBeaconManager manager, ESTBeaconRegion region, NSError error);
[Export ("beaconManager:didEnterRegion:")]
void DidEnterRegion (ESTBeaconManager manager, ESTBeaconRegion region);
[Export ("beaconManager:didExitRegion:")]
void DidExitRegion (ESTBeaconManager manager, ESTBeaconRegion region);
[Export ("beaconManager:didDetermineState:forRegion:")]
void DidDetermineState (ESTBeaconManager manager, CLRegionState state, ESTBeaconRegion region);
[Export ("beaconManagerDidStartAdvertising:error:")]
void Error (ESTBeaconManager manager, NSError error);
[Export ("beaconManager:didDiscoverBeacons:inRegion:")]
void DidDiscoverBeacons (ESTBeaconManager manager, NSArray beacons, ESTBeaconRegion region);
[Export ("beaconManager:didFailDiscoveryInRegion:")]
void DidFailDiscoveryInRegion (ESTBeaconManager manager, ESTBeaconRegion region);
}
[BaseType (typeof (CLLocationManagerDelegate))]
public partial interface ESTBeaconManager {
[Export ("delegate", ArgumentSemantic.Assign)]
ESTBeaconManagerDelegate Delegate { get; set; }
[Export ("avoidUnknownStateBeacons")]
bool AvoidUnknownStateBeacons { get; set; }
[Export ("virtualBeaconRegion", ArgumentSemantic.Retain)]
ESTBeaconRegion VirtualBeaconRegion { get; set; }
[Export ("startRangingBeaconsInRegion:")]
void StartRangingBeaconsInRegion (ESTBeaconRegion region);
[Export ("startMonitoringForRegion:")]
void StartMonitoringForRegion (ESTBeaconRegion region);
[Export ("stopRangingBeaconsInRegion:")]
void StopRangingBeaconsInRegion (ESTBeaconRegion region);
[Export ("stopMonitoringForRegion:")]
void StopMonitoringForRegion (ESTBeaconRegion region);
[Export ("requestStateForRegion:")]
void RequestStateForRegion (ESTBeaconRegion region);
[Export ("startAdvertisingWithProximityUUID:major:minor:identifier:")]
void StartAdvertisingWithProximityUUID (NSUuid proximityUUID, NSNumber major, NSNumber minor, string identifier);
//void StartAdvertisingWithProximityUUID (NSUuid proximityUUID, CLBeaconMajorValue major, CLBeaconMinorValue minor, string identifier);
[Export ("stopAdvertising")]
void StopAdvertising ();
[Export ("startEstimoteBeaconsDiscoveryForRegion:")]
void StartEstimoteBeaconsDiscoveryForRegion (ESTBeaconRegion region);
[Export ("stopEstimoteBeaconDiscovery")]
void StopEstimoteBeaconDiscovery ();
}
[BaseType (typeof (CLBeaconRegion))]
public partial interface ESTBeaconRegion{
[Export("initWithProximityUUID:identifier:")]
IntPtr Constructor(NSUuid proximityUUID, NSString identifier);
[Export("initWithProximityUUID:major:identifier:")]
IntPtr Constructor(NSUuid proximityUUID, NSNumber major, NSString identifier);
[Export("initWithProximityUUID:major:minor:identifier:")]
IntPtr Constructor(NSUuid proximityUUID, NSNumber major, NSNumber minor, NSString identifier);
}
}
| |
/*
| Version 10.1.84
| Copyright 2013 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
using System;
using System.Diagnostics;
using System.Collections.Generic;
using ESRI.ArcLogistics.DomainObjects;
using ESRI.ArcLogistics.Routing.Json;
namespace ESRI.ArcLogistics.Routing
{
/// <summary>
/// UnassignOrdersParams class.
/// </summary>
internal class UnassignOrdersParams
{
internal UnassignOrdersParams(ICollection<Order> ordersToUnassign)
{
_ordersToUnassign = ordersToUnassign;
}
public ICollection<Order> OrdersToUnassign
{
get { return _ordersToUnassign; }
}
private ICollection<Order> _ordersToUnassign;
}
/// <summary>
/// UnassignOrdersOperation class.
/// </summary>
internal class UnassignOrdersOperation : VrpOperation
{
#region constructors
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
public UnassignOrdersOperation(SolverContext context,
Schedule schedule,
UnassignOrdersParams inputParams,
SolveOptions options)
: base(context, schedule, options)
{
Debug.Assert(inputParams != null);
_inputParams = inputParams;
}
public UnassignOrdersOperation(SolverContext context,
Schedule schedule,
UnassignOrdersParams inputParams,
SolveOptions options,
SolveRequestData reqData,
List<Violation> violations)
: base(context, schedule, options)
{
Debug.Assert(inputParams != null);
Debug.Assert(reqData != null);
Debug.Assert(violations != null);
_inputParams = inputParams;
_reqData = reqData;
_violations = violations;
}
#endregion constructors
#region public overrides
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
public override SolveOperationType OperationType
{
get { return SolveOperationType.UnassignOrders; }
}
public override Object InputParams
{
get { return _inputParams; }
}
public override bool CanGetResultWithoutSolve
{
get
{
SolveRequestData reqData = this.RequestData;
return (reqData.Routes.Count > 0 &&
reqData.Orders.Count == 0);
}
}
public override SolveResult CreateResultWithoutSolve()
{
SolveRequestData reqData = this.RequestData;
foreach (Route route in reqData.Routes)
SolverContext.Project.Schedules.ClearRouteResults(route);
return new SolveResult(null, null, false);
}
#endregion public overrides
#region protected overrides
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
protected override SolveRequestData RequestData
{
get
{
if (_reqData == null)
_reqData = _BuildRequestData();
return _reqData;
}
}
protected override SolveRequestOptions RequestOptions
{
get
{
SolveRequestOptions opt = base.RequestOptions;
opt.ConvertUnassignedOrders = false;
return opt;
}
}
protected override VrpOperation CreateOperation(SolveRequestData reqData,
List<Violation> violations)
{
return new UnassignOrdersOperation(base.SolverContext, base.Schedule,
_inputParams,
base.Options,
reqData,
violations);
}
protected override List<Violation> GetViolations(VrpResult vrpResult)
{
List<Violation> violations = base.GetViolations(vrpResult);
if (_violations != null)
violations.AddRange(_violations);
return violations;
}
#endregion protected overrides
#region private methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
private SolveRequestData _BuildRequestData()
{
// get unlocked assigned orders for schedule
List<Order> unlockedAssignedOrders = _GetUnlockedAssignedOrders();
// select unlocked assigned orders from OrdersToUnassign
List<Order> unlockedOrdersToUnassign = new List<Order>();
foreach (Order order in _inputParams.OrdersToUnassign)
{
if (unlockedAssignedOrders.Contains(order))
unlockedOrdersToUnassign.Add(order);
}
// get affected routes:
// routes planned on schedule's day where each route has at
// least one order from UnlockedOrdersToUnassign assigned to it
List<Route> affectedRoutes = _GetAffectedRoutes(
Schedule.Routes,
unlockedOrdersToUnassign);
// get orders to convert:
// orders assigned to affected routes except those from
// UnlockedOrdersToUnassign
List<Order> ordersToConvert = _GetOrdersToConvert(
affectedRoutes,
unlockedOrdersToUnassign);
// get barriers planned on schedule's date
ICollection<Barrier> barriers = SolverContext.Project.Barriers.Search(
(DateTime)Schedule.PlannedDate);
SolveRequestData reqData = new SolveRequestData();
reqData.Routes = affectedRoutes;
reqData.Orders = ordersToConvert;
reqData.Barriers = barriers;
return reqData;
}
private List<Order> _GetUnlockedAssignedOrders()
{
List<Order> orders = new List<Order>();
foreach (Route route in Schedule.Routes)
{
if (!route.IsLocked)
{
foreach (Stop stop in route.Stops)
{
if (stop.StopType == StopType.Order &&
!stop.IsLocked)
{
orders.Add(stop.AssociatedObject as Order);
}
}
}
}
return orders;
}
private List<Route> _GetAffectedRoutes(
ICollection<Route> dayRoutes,
ICollection<Order> unlockedOrders)
{
List<Route> routes = new List<Route>();
foreach (Route route in dayRoutes)
{
foreach (Stop stop in route.Stops)
{
if (stop.StopType == StopType.Order)
{
Order order = stop.AssociatedObject as Order;
if (unlockedOrders.Contains(order))
{
routes.Add(route);
break;
}
}
}
}
return routes;
}
private List<Order> _GetOrdersToConvert(
ICollection<Route> affectedRoutes,
ICollection<Order> unlockedOrders)
{
List<Order> orders = new List<Order>();
foreach (Route route in affectedRoutes)
{
foreach (Stop stop in route.Stops)
{
if (stop.StopType == StopType.Order)
{
Order order = stop.AssociatedObject as Order;
if (!unlockedOrders.Contains(order))
orders.Add(order); // TODO: (?) check duplicates
}
}
}
return orders;
}
#endregion private methods
#region private fields
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
private UnassignOrdersParams _inputParams;
private SolveRequestData _reqData;
private List<Violation> _violations;
#endregion private fields
}
}
| |
// File generated from our OpenAPI spec
namespace Stripe
{
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Stripe.Infrastructure;
/// <summary>
/// <c>Refund</c> objects allow you to refund a charge that has previously been created but
/// not yet refunded. Funds will be refunded to the credit or debit card that was originally
/// charged.
///
/// Related guide: <a href="https://stripe.com/docs/refunds">Refunds</a>.
/// </summary>
public class Refund : StripeEntity<Refund>, IHasId, IHasMetadata, IHasObject, IBalanceTransactionSource
{
/// <summary>
/// Unique identifier for the object.
/// </summary>
[JsonProperty("id")]
public string Id { get; set; }
/// <summary>
/// String representing the object's type. Objects of the same type share the same value.
/// </summary>
[JsonProperty("object")]
public string Object { get; set; }
/// <summary>
/// Amount, in %s.
/// </summary>
[JsonProperty("amount")]
public long Amount { get; set; }
#region Expandable BalanceTransaction
/// <summary>
/// (ID of the BalanceTransaction)
/// Balance transaction that describes the impact on your account balance.
/// </summary>
[JsonIgnore]
public string BalanceTransactionId
{
get => this.InternalBalanceTransaction?.Id;
set => this.InternalBalanceTransaction = SetExpandableFieldId(value, this.InternalBalanceTransaction);
}
/// <summary>
/// (Expanded)
/// Balance transaction that describes the impact on your account balance.
///
/// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>.
/// </summary>
[JsonIgnore]
public BalanceTransaction BalanceTransaction
{
get => this.InternalBalanceTransaction?.ExpandedObject;
set => this.InternalBalanceTransaction = SetExpandableFieldObject(value, this.InternalBalanceTransaction);
}
[JsonProperty("balance_transaction")]
[JsonConverter(typeof(ExpandableFieldConverter<BalanceTransaction>))]
internal ExpandableField<BalanceTransaction> InternalBalanceTransaction { get; set; }
#endregion
#region Expandable Charge
/// <summary>
/// (ID of the Charge)
/// ID of the charge that was refunded.
/// </summary>
[JsonIgnore]
public string ChargeId
{
get => this.InternalCharge?.Id;
set => this.InternalCharge = SetExpandableFieldId(value, this.InternalCharge);
}
/// <summary>
/// (Expanded)
/// ID of the charge that was refunded.
///
/// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>.
/// </summary>
[JsonIgnore]
public Charge Charge
{
get => this.InternalCharge?.ExpandedObject;
set => this.InternalCharge = SetExpandableFieldObject(value, this.InternalCharge);
}
[JsonProperty("charge")]
[JsonConverter(typeof(ExpandableFieldConverter<Charge>))]
internal ExpandableField<Charge> InternalCharge { get; set; }
#endregion
/// <summary>
/// Time at which the object was created. Measured in seconds since the Unix epoch.
/// </summary>
[JsonProperty("created")]
[JsonConverter(typeof(UnixDateTimeConverter))]
public DateTime Created { get; set; } = Stripe.Infrastructure.DateTimeUtils.UnixEpoch;
/// <summary>
/// Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency
/// code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported
/// currency</a>.
/// </summary>
[JsonProperty("currency")]
public string Currency { get; set; }
/// <summary>
/// An arbitrary string attached to the object. Often useful for displaying to users.
/// (Available on non-card refunds only).
/// </summary>
[JsonProperty("description")]
public string Description { get; set; }
#region Expandable FailureBalanceTransaction
/// <summary>
/// (ID of the BalanceTransaction)
/// If the refund failed, this balance transaction describes the adjustment made on your
/// account balance that reverses the initial balance transaction.
/// </summary>
[JsonIgnore]
public string FailureBalanceTransactionId
{
get => this.InternalFailureBalanceTransaction?.Id;
set => this.InternalFailureBalanceTransaction = SetExpandableFieldId(value, this.InternalFailureBalanceTransaction);
}
/// <summary>
/// (Expanded)
/// If the refund failed, this balance transaction describes the adjustment made on your
/// account balance that reverses the initial balance transaction.
///
/// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>.
/// </summary>
[JsonIgnore]
public BalanceTransaction FailureBalanceTransaction
{
get => this.InternalFailureBalanceTransaction?.ExpandedObject;
set => this.InternalFailureBalanceTransaction = SetExpandableFieldObject(value, this.InternalFailureBalanceTransaction);
}
[JsonProperty("failure_balance_transaction")]
[JsonConverter(typeof(ExpandableFieldConverter<BalanceTransaction>))]
internal ExpandableField<BalanceTransaction> InternalFailureBalanceTransaction { get; set; }
#endregion
/// <summary>
/// If the refund failed, the reason for refund failure if known. Possible values are
/// <c>lost_or_stolen_card</c>, <c>expired_or_canceled_card</c>, or <c>unknown</c>.
/// </summary>
[JsonProperty("failure_reason")]
public string FailureReason { get; set; }
/// <summary>
/// Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can
/// attach to an object. This can be useful for storing additional information about the
/// object in a structured format.
/// </summary>
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
[JsonProperty("next_action")]
public RefundNextAction NextAction { get; set; }
#region Expandable PaymentIntent
/// <summary>
/// (ID of the PaymentIntent)
/// ID of the PaymentIntent that was refunded.
/// </summary>
[JsonIgnore]
public string PaymentIntentId
{
get => this.InternalPaymentIntent?.Id;
set => this.InternalPaymentIntent = SetExpandableFieldId(value, this.InternalPaymentIntent);
}
/// <summary>
/// (Expanded)
/// ID of the PaymentIntent that was refunded.
///
/// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>.
/// </summary>
[JsonIgnore]
public PaymentIntent PaymentIntent
{
get => this.InternalPaymentIntent?.ExpandedObject;
set => this.InternalPaymentIntent = SetExpandableFieldObject(value, this.InternalPaymentIntent);
}
[JsonProperty("payment_intent")]
[JsonConverter(typeof(ExpandableFieldConverter<PaymentIntent>))]
internal ExpandableField<PaymentIntent> InternalPaymentIntent { get; set; }
#endregion
/// <summary>
/// Reason for the refund, either user-provided (<c>duplicate</c>, <c>fraudulent</c>, or
/// <c>requested_by_customer</c>) or generated by Stripe internally
/// (<c>expired_uncaptured_charge</c>).
/// One of: <c>duplicate</c>, <c>expired_uncaptured_charge</c>, <c>fraudulent</c>, or
/// <c>requested_by_customer</c>.
/// </summary>
[JsonProperty("reason")]
public string Reason { get; set; }
/// <summary>
/// This is the transaction number that appears on email receipts sent for this refund.
/// </summary>
[JsonProperty("receipt_number")]
public string ReceiptNumber { get; set; }
#region Expandable SourceTransferReversal
/// <summary>
/// (ID of the TransferReversal)
/// The transfer reversal that is associated with the refund. Only present if the charge
/// came from another Stripe account. See the Connect documentation for details.
/// </summary>
[JsonIgnore]
public string SourceTransferReversalId
{
get => this.InternalSourceTransferReversal?.Id;
set => this.InternalSourceTransferReversal = SetExpandableFieldId(value, this.InternalSourceTransferReversal);
}
/// <summary>
/// (Expanded)
/// The transfer reversal that is associated with the refund. Only present if the charge
/// came from another Stripe account. See the Connect documentation for details.
///
/// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>.
/// </summary>
[JsonIgnore]
public TransferReversal SourceTransferReversal
{
get => this.InternalSourceTransferReversal?.ExpandedObject;
set => this.InternalSourceTransferReversal = SetExpandableFieldObject(value, this.InternalSourceTransferReversal);
}
[JsonProperty("source_transfer_reversal")]
[JsonConverter(typeof(ExpandableFieldConverter<TransferReversal>))]
internal ExpandableField<TransferReversal> InternalSourceTransferReversal { get; set; }
#endregion
/// <summary>
/// Status of the refund. For credit card refunds, this can be <c>pending</c>,
/// <c>succeeded</c>, or <c>failed</c>. For other types of refunds, it can be
/// <c>pending</c>, <c>succeeded</c>, <c>failed</c>, or <c>canceled</c>. Refer to our <a
/// href="https://stripe.com/docs/refunds#failed-refunds">refunds</a> documentation for more
/// details.
/// </summary>
[JsonProperty("status")]
public string Status { get; set; }
#region Expandable TransferReversal
/// <summary>
/// (ID of the TransferReversal)
/// If the accompanying transfer was reversed, the transfer reversal object. Only applicable
/// if the charge was created using the destination parameter.
/// </summary>
[JsonIgnore]
public string TransferReversalId
{
get => this.InternalTransferReversal?.Id;
set => this.InternalTransferReversal = SetExpandableFieldId(value, this.InternalTransferReversal);
}
/// <summary>
/// (Expanded)
/// If the accompanying transfer was reversed, the transfer reversal object. Only applicable
/// if the charge was created using the destination parameter.
///
/// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>.
/// </summary>
[JsonIgnore]
public TransferReversal TransferReversal
{
get => this.InternalTransferReversal?.ExpandedObject;
set => this.InternalTransferReversal = SetExpandableFieldObject(value, this.InternalTransferReversal);
}
[JsonProperty("transfer_reversal")]
[JsonConverter(typeof(ExpandableFieldConverter<TransferReversal>))]
internal ExpandableField<TransferReversal> InternalTransferReversal { get; set; }
#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.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.Win32.SafeHandles;
namespace System
{
/// <summary>Provides access to and processing of a terminfo database.</summary>
internal static class TermInfo
{
internal enum WellKnownNumbers
{
Columns = 0,
Lines = 2,
MaxColors = 13,
}
internal enum WellKnownStrings
{
Bell = 1,
Clear = 5,
CursorAddress = 10,
CursorLeft = 14,
CursorPositionReport = 294,
OrigPairs = 297,
OrigColors = 298,
SetAnsiForeground = 359,
SetAnsiBackground = 360,
CursorInvisible = 13,
CursorVisible = 16,
FromStatusLine = 47,
ToStatusLine = 135,
KeyBackspace = 55,
KeyClear = 57,
KeyDelete = 59,
KeyDown = 61,
KeyF1 = 66,
KeyF10 = 67,
KeyF2 = 68,
KeyF3 = 69,
KeyF4 = 70,
KeyF5 = 71,
KeyF6 = 72,
KeyF7 = 73,
KeyF8 = 74,
KeyF9 = 75,
KeyHome = 76,
KeyInsert = 77,
KeyLeft = 79,
KeyPageDown = 81,
KeyPageUp = 82,
KeyRight = 83,
KeyScrollForward = 84,
KeyScrollReverse = 85,
KeyUp = 87,
KeypadXmit = 89,
KeyBackTab = 148,
KeyBegin = 158,
KeyEnd = 164,
KeyEnter = 165,
KeyHelp = 168,
KeyPrint = 176,
KeySBegin = 186,
KeySDelete = 191,
KeySelect = 193,
KeySHelp = 198,
KeySHome = 199,
KeySLeft = 201,
KeySPrint = 207,
KeySRight = 210,
KeyF11 = 216,
KeyF12 = 217,
KeyF13 = 218,
KeyF14 = 219,
KeyF15 = 220,
KeyF16 = 221,
KeyF17 = 222,
KeyF18 = 223,
KeyF19 = 224,
KeyF20 = 225,
KeyF21 = 226,
KeyF22 = 227,
KeyF23 = 228,
KeyF24 = 229,
}
/// <summary>Provides a terminfo database.</summary>
internal sealed class Database
{
/// <summary>The name of the terminfo file.</summary>
private readonly string _term;
/// <summary>Raw data of the database instance.</summary>
private readonly byte[] _data;
/// <summary>The number of bytes in the names section of the database.</summary>
private readonly int _nameSectionNumBytes;
/// <summary>The number of bytes in the Booleans section of the database.</summary>
private readonly int _boolSectionNumBytes;
/// <summary>The number of integers in the numbers section of the database.</summary>
private readonly int _numberSectionNumInts;
/// <summary>The number of offsets in the strings section of the database.</summary>
private readonly int _stringSectionNumOffsets;
/// <summary>The number of bytes in the strings table of the database.</summary>
private readonly int _stringTableNumBytes;
/// <summary>Whether or not to read the number section as 32-bit integers.</summary>
private readonly bool _readAs32Bit;
/// <summary>The size of the integers on the number section.</summary>
private readonly int _sizeOfInt;
/// <summary>Extended / user-defined entries in the terminfo database.</summary>
private readonly Dictionary<string, string> _extendedStrings;
/// <summary>Initializes the database instance.</summary>
/// <param name="term">The name of the terminal.</param>
/// <param name="data">The data from the terminfo file.</param>
private Database(string term, byte[] data)
{
_term = term;
_data = data;
const int MagicLegacyNumber = 0x11A; // magic number octal 0432 for legacy ncurses terminfo
const int Magic32BitNumber = 0x21E; // magic number octal 01036 for new ncruses terminfo
short magic = ReadInt16(data, 0);
_readAs32Bit =
magic == MagicLegacyNumber ? false :
magic == Magic32BitNumber ? true :
throw new InvalidOperationException(SR.Format(SR.IO_TermInfoInvalidMagicNumber, string.Concat("O" + Convert.ToString(magic, 8)))); // magic number was not recognized. Printing the magic number in octal.
_sizeOfInt = (_readAs32Bit) ? 4 : 2;
_nameSectionNumBytes = ReadInt16(data, 2);
_boolSectionNumBytes = ReadInt16(data, 4);
_numberSectionNumInts = ReadInt16(data, 6);
_stringSectionNumOffsets = ReadInt16(data, 8);
_stringTableNumBytes = ReadInt16(data, 10);
if (_nameSectionNumBytes < 0 ||
_boolSectionNumBytes < 0 ||
_numberSectionNumInts < 0 ||
_stringSectionNumOffsets < 0 ||
_stringTableNumBytes < 0)
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
// In addition to the main section of bools, numbers, and strings, there is also
// an "extended" section. This section contains additional entries that don't
// have well-known indices, and are instead named mappings. As such, we parse
// all of this data now rather than on each request, as the mapping is fairly complicated.
// This function relies on the data stored above, so it's the last thing we run.
// (Note that the extended section also includes other Booleans and numbers, but we don't
// have any need for those now, so we don't parse them.)
int extendedBeginning = RoundUpToEven(StringsTableOffset + _stringTableNumBytes);
_extendedStrings = ParseExtendedStrings(data, extendedBeginning, _readAs32Bit) ?? new Dictionary<string, string>();
}
/// <summary>The name of the associated terminfo, if any.</summary>
public string Term { get { return _term; } }
/// <summary>Read the database for the current terminal as specified by the "TERM" environment variable.</summary>
/// <returns>The database, or null if it could not be found.</returns>
internal static Database ReadActiveDatabase()
{
string term = Environment.GetEnvironmentVariable("TERM");
return !string.IsNullOrEmpty(term) ? ReadDatabase(term) : null;
}
/// <summary>
/// The default locations in which to search for terminfo databases.
/// This is the ordering of well-known locations used by ncurses.
/// </summary>
private static readonly string[] _terminfoLocations = new string[] {
"/etc/terminfo",
"/lib/terminfo",
"/usr/share/terminfo",
"/usr/share/misc/terminfo"
};
/// <summary>Read the database for the specified terminal.</summary>
/// <param name="term">The identifier for the terminal.</param>
/// <returns>The database, or null if it could not be found.</returns>
private static Database ReadDatabase(string term)
{
// This follows the same search order as prescribed by ncurses.
Database db;
// First try a location specified in the TERMINFO environment variable.
string terminfo = Environment.GetEnvironmentVariable("TERMINFO");
if (!string.IsNullOrWhiteSpace(terminfo) && (db = ReadDatabase(term, terminfo)) != null)
{
return db;
}
// Then try in the user's home directory.
string home = PersistedFiles.GetHomeDirectory();
if (!string.IsNullOrWhiteSpace(home) && (db = ReadDatabase(term, home + "/.terminfo")) != null)
{
return db;
}
// Then try a set of well-known locations.
foreach (string terminfoLocation in _terminfoLocations)
{
if ((db = ReadDatabase(term, terminfoLocation)) != null)
{
return db;
}
}
// Couldn't find one
return null;
}
/// <summary>Attempt to open as readonly the specified file path.</summary>
/// <param name="filePath">The path to the file to open.</param>
/// <param name="fd">If successful, the opened file descriptor; otherwise, -1.</param>
/// <returns>true if the file was successfully opened; otherwise, false.</returns>
private static bool TryOpen(string filePath, out SafeFileHandle fd)
{
fd = Interop.Sys.Open(filePath, Interop.Sys.OpenFlags.O_RDONLY | Interop.Sys.OpenFlags.O_CLOEXEC, 0);
if (fd.IsInvalid)
{
// Don't throw in this case, as we'll be polling multiple locations looking for the file.
fd = null;
return false;
}
return true;
}
/// <summary>Read the database for the specified terminal from the specified directory.</summary>
/// <param name="term">The identifier for the terminal.</param>
/// <param name="directoryPath">The path to the directory containing terminfo database files.</param>
/// <returns>The database, or null if it could not be found.</returns>
private static Database ReadDatabase(string term, string directoryPath)
{
if (string.IsNullOrEmpty(term) || string.IsNullOrEmpty(directoryPath))
{
return null;
}
SafeFileHandle fd;
if (!TryOpen(directoryPath + "/" + term[0].ToString() + "/" + term, out fd) && // /directory/termFirstLetter/term (Linux)
!TryOpen(directoryPath + "/" + ((int)term[0]).ToString("X") + "/" + term, out fd)) // /directory/termFirstLetterAsHex/term (Mac)
{
return null;
}
using (fd)
{
// Read in all of the terminfo data
long termInfoLength = Interop.CheckIo(Interop.Sys.LSeek(fd, 0, Interop.Sys.SeekWhence.SEEK_END)); // jump to the end to get the file length
Interop.CheckIo(Interop.Sys.LSeek(fd, 0, Interop.Sys.SeekWhence.SEEK_SET)); // reset back to beginning
const int MaxTermInfoLength = 4096; // according to the term and tic man pages, 4096 is the terminfo file size max
const int HeaderLength = 12;
if (termInfoLength <= HeaderLength || termInfoLength > MaxTermInfoLength)
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
int fileLen = (int)termInfoLength;
byte[] data = new byte[fileLen];
if (ConsolePal.Read(fd, data, 0, fileLen) != fileLen)
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
// Create the database from the data
return new Database(term, data);
}
}
/// <summary>The offset into data where the names section begins.</summary>
private const int NamesOffset = 12; // comes right after the header, which is always 12 bytes
/// <summary>The offset into data where the Booleans section begins.</summary>
private int BooleansOffset { get { return NamesOffset + _nameSectionNumBytes; } } // after the names section
/// <summary>The offset into data where the numbers section begins.</summary>
private int NumbersOffset { get { return RoundUpToEven(BooleansOffset + _boolSectionNumBytes); } } // after the Booleans section, at an even position
/// <summary>
/// The offset into data where the string offsets section begins. We index into this section
/// to find the location within the strings table where a string value exists.
/// </summary>
private int StringOffsetsOffset { get { return NumbersOffset + (_numberSectionNumInts * _sizeOfInt); } }
/// <summary>The offset into data where the string table exists.</summary>
private int StringsTableOffset { get { return StringOffsetsOffset + (_stringSectionNumOffsets * 2); } }
/// <summary>Gets a string from the strings section by the string's well-known index.</summary>
/// <param name="stringTableIndex">The index of the string to find.</param>
/// <returns>The string if it's in the database; otherwise, null.</returns>
public string GetString(WellKnownStrings stringTableIndex)
{
int index = (int)stringTableIndex;
Debug.Assert(index >= 0);
if (index >= _stringSectionNumOffsets)
{
// Some terminfo files may not contain enough entries to actually
// have the requested one.
return null;
}
int tableIndex = ReadInt16(_data, StringOffsetsOffset + (index * 2));
if (tableIndex == -1)
{
// Some terminfo files may have enough entries, but may not actually
// have it filled in for this particular string.
return null;
}
return ReadString(_data, StringsTableOffset + tableIndex);
}
/// <summary>Gets a string from the extended strings section.</summary>
/// <param name="name">The name of the string as contained in the extended names section.</param>
/// <returns>The string if it's in the database; otherwise, null.</returns>
public string GetExtendedString(string name)
{
Debug.Assert(name != null);
string value;
return _extendedStrings.TryGetValue(name, out value) ?
value :
null;
}
/// <summary>Gets a number from the numbers section by the number's well-known index.</summary>
/// <param name="numberIndex">The index of the string to find.</param>
/// <returns>The number if it's in the database; otherwise, -1.</returns>
public int GetNumber(WellKnownNumbers numberIndex)
{
int index = (int)numberIndex;
Debug.Assert(index >= 0);
if (index >= _numberSectionNumInts)
{
// Some terminfo files may not contain enough entries to actually
// have the requested one.
return -1;
}
return ReadInt(_data, NumbersOffset + (index * _sizeOfInt), _readAs32Bit);
}
/// <summary>Parses the extended string information from the terminfo data.</summary>
/// <returns>
/// A dictionary of the name to value mapping. As this section of the terminfo isn't as well
/// defined as the earlier portions, and may not even exist, the parsing is more lenient about
/// errors, returning an empty collection rather than throwing.
/// </returns>
private static Dictionary<string, string> ParseExtendedStrings(byte[] data, int extendedBeginning, bool readAs32Bit)
{
const int ExtendedHeaderSize = 10;
int sizeOfIntValuesInBytes = (readAs32Bit) ? 4 : 2;
if (extendedBeginning + ExtendedHeaderSize >= data.Length)
{
// Exit out as there's no extended information.
return null;
}
// Read in extended counts, and exit out if we got any incorrect info
int extendedBoolCount = ReadInt16(data, extendedBeginning);
int extendedNumberCount = ReadInt16(data, extendedBeginning + (2 * 1));
int extendedStringCount = ReadInt16(data, extendedBeginning + (2 * 2));
int extendedStringNumOffsets = ReadInt16(data, extendedBeginning + (2 * 3));
int extendedStringTableByteSize = ReadInt16(data, extendedBeginning + (2 * 4));
if (extendedBoolCount < 0 ||
extendedNumberCount < 0 ||
extendedStringCount < 0 ||
extendedStringNumOffsets < 0 ||
extendedStringTableByteSize < 0)
{
// The extended header contained invalid data. Bail.
return null;
}
// Skip over the extended bools. We don't need them now and can add this in later
// if needed. Also skip over extended numbers, for the same reason.
// Get the location where the extended string offsets begin. These point into
// the extended string table.
int extendedOffsetsStart =
extendedBeginning + // go past the normal data
ExtendedHeaderSize + // and past the extended header
RoundUpToEven(extendedBoolCount) + // and past all of the extended Booleans
(extendedNumberCount * sizeOfIntValuesInBytes); // and past all of the extended numbers
// Get the location where the extended string table begins. This area contains
// null-terminated strings.
int extendedStringTableStart =
extendedOffsetsStart +
(extendedStringCount * 2) + // and past all of the string offsets
((extendedBoolCount + extendedNumberCount + extendedStringCount) * 2); // and past all of the name offsets
// Get the location where the extended string table ends. We shouldn't read past this.
int extendedStringTableEnd =
extendedStringTableStart +
extendedStringTableByteSize;
if (extendedStringTableEnd > data.Length)
{
// We don't have enough data to parse everything. Bail.
return null;
}
// Now we need to parse all of the extended string values. These aren't necessarily
// "in order", meaning the offsets aren't guaranteed to be increasing. Instead, we parse
// the offsets in order, pulling out each string it references and storing them into our
// results list in the order of the offsets.
var values = new List<string>(extendedStringCount);
int lastEnd = 0;
for (int i = 0; i < extendedStringCount; i++)
{
int offset = extendedStringTableStart + ReadInt16(data, extendedOffsetsStart + (i * 2));
if (offset < 0 || offset >= data.Length)
{
// If the offset is invalid, bail.
return null;
}
// Add the string
int end = FindNullTerminator(data, offset);
values.Add(Encoding.ASCII.GetString(data, offset, end - offset));
// Keep track of where the last string ends. The name strings will come after that.
lastEnd = Math.Max(end, lastEnd);
}
// Now parse all of the names.
var names = new List<string>(extendedBoolCount + extendedNumberCount + extendedStringCount);
for (int pos = lastEnd + 1; pos < extendedStringTableEnd; pos++)
{
int end = FindNullTerminator(data, pos);
names.Add(Encoding.ASCII.GetString(data, pos, end - pos));
pos = end;
}
// The names are in order for the Booleans, then the numbers, and then the strings.
// Skip over the bools and numbers, and associate the names with the values.
var extendedStrings = new Dictionary<string, string>(extendedStringCount);
for (int iName = extendedBoolCount + extendedNumberCount, iValue = 0;
iName < names.Count && iValue < values.Count;
iName++, iValue++)
{
extendedStrings.Add(names[iName], values[iValue]);
}
return extendedStrings;
}
private static int RoundUpToEven(int i) { return i % 2 == 1 ? i + 1 : i; }
/// <summary>Read a 16-bit or 32-bit value from the buffer starting at the specified position.</summary>
/// <param name="buffer">The buffer from which to read.</param>
/// <param name="pos">The position at which to read.</param>
/// <param name="readAs32Bit">Whether or not to read value as 32-bit. Will read as 16-bit if set to false.</param>
/// <returns>The value read.</returns>
private static int ReadInt(byte[] buffer, int pos, bool readAs32Bit) =>
readAs32Bit ? ReadInt32(buffer, pos) : ReadInt16(buffer, pos);
/// <summary>Read a 16-bit value from the buffer starting at the specified position.</summary>
/// <param name="buffer">The buffer from which to read.</param>
/// <param name="pos">The position at which to read.</param>
/// <returns>The 16-bit value read.</returns>
private static short ReadInt16(byte[] buffer, int pos)
{
return unchecked((short)
((((int)buffer[pos + 1]) << 8) |
((int)buffer[pos] & 0xff)));
}
/// <summary>Read a 32-bit value from the buffer starting at the specified position.</summary>
/// <param name="buffer">The buffer from which to read.</param>
/// <param name="pos">The position at which to read.</param>
/// <returns>The 32-bit value read.</returns>
private static int ReadInt32(byte[] buffer, int pos)
{
return (int)((buffer[pos] & 0xff) |
buffer[pos + 1] << 8 |
buffer[pos + 2] << 16 |
buffer[pos + 3] << 24);
}
/// <summary>Reads a string from the buffer starting at the specified position.</summary>
/// <param name="buffer">The buffer from which to read.</param>
/// <param name="pos">The position at which to read.</param>
/// <returns>The string read from the specified position.</returns>
private static string ReadString(byte[] buffer, int pos)
{
int end = FindNullTerminator(buffer, pos);
return Encoding.ASCII.GetString(buffer, pos, end - pos);
}
/// <summary>Finds the null-terminator for a string that begins at the specified position.</summary>
private static int FindNullTerminator(byte[] buffer, int pos)
{
int termPos = pos;
while (termPos < buffer.Length && buffer[termPos] != '\0') termPos++;
return termPos;
}
}
/// <summary>Provides support for evaluating parameterized terminfo database format strings.</summary>
internal static class ParameterizedStrings
{
/// <summary>A cached stack to use to avoid allocating a new stack object for every evaluation.</summary>
[ThreadStatic]
private static Stack<FormatParam> t_cachedStack;
/// <summary>A cached array of arguments to use to avoid allocating a new array object for every evaluation.</summary>
[ThreadStatic]
private static FormatParam[] t_cachedOneElementArgsArray;
/// <summary>A cached array of arguments to use to avoid allocating a new array object for every evaluation.</summary>
[ThreadStatic]
private static FormatParam[] t_cachedTwoElementArgsArray;
/// <summary>Evaluates a terminfo formatting string, using the supplied argument.</summary>
/// <param name="format">The format string.</param>
/// <param name="arg">The argument to the format string.</param>
/// <returns>The formatted string.</returns>
public static string Evaluate(string format, FormatParam arg)
{
FormatParam[] args = t_cachedOneElementArgsArray;
if (args == null)
{
t_cachedOneElementArgsArray = args = new FormatParam[1];
}
args[0] = arg;
return Evaluate(format, args);
}
/// <summary>Evaluates a terminfo formatting string, using the supplied arguments.</summary>
/// <param name="format">The format string.</param>
/// <param name="arg1">The first argument to the format string.</param>
/// <param name="arg2">The second argument to the format string.</param>
/// <returns>The formatted string.</returns>
public static string Evaluate(string format, FormatParam arg1, FormatParam arg2)
{
FormatParam[] args = t_cachedTwoElementArgsArray;
if (args == null)
{
t_cachedTwoElementArgsArray = args = new FormatParam[2];
}
args[0] = arg1;
args[1] = arg2;
return Evaluate(format, args);
}
/// <summary>Evaluates a terminfo formatting string, using the supplied arguments.</summary>
/// <param name="format">The format string.</param>
/// <param name="args">The arguments to the format string.</param>
/// <returns>The formatted string.</returns>
public static string Evaluate(string format, params FormatParam[] args)
{
if (format == null)
{
throw new ArgumentNullException(nameof(format));
}
if (args == null)
{
throw new ArgumentNullException(nameof(args));
}
// Initialize the stack to use for processing.
Stack<FormatParam> stack = t_cachedStack;
if (stack == null)
{
t_cachedStack = stack = new Stack<FormatParam>();
}
else
{
stack.Clear();
}
// "dynamic" and "static" variables are much less often used (the "dynamic" and "static"
// terminology appears to just refer to two different collections rather than to any semantic
// meaning). As such, we'll only initialize them if we really need them.
FormatParam[] dynamicVars = null, staticVars = null;
int pos = 0;
return EvaluateInternal(format, ref pos, args, stack, ref dynamicVars, ref staticVars);
// EvaluateInternal may throw IndexOutOfRangeException and InvalidOperationException
// if the format string is malformed or if it's inconsistent with the parameters provided.
}
/// <summary>Evaluates a terminfo formatting string, using the supplied arguments and processing data structures.</summary>
/// <param name="format">The format string.</param>
/// <param name="pos">The position in <paramref name="format"/> to start processing.</param>
/// <param name="args">The arguments to the format string.</param>
/// <param name="stack">The stack to use as the format string is evaluated.</param>
/// <param name="dynamicVars">A lazily-initialized collection of variables.</param>
/// <param name="staticVars">A lazily-initialized collection of variables.</param>
/// <returns>
/// The formatted string; this may be empty if the evaluation didn't yield any output.
/// The evaluation stack will have a 1 at the top if all processing was completed at invoked level
/// of recursion, and a 0 at the top if we're still inside of a conditional that requires more processing.
/// </returns>
private static string EvaluateInternal(
string format, ref int pos, FormatParam[] args, Stack<FormatParam> stack,
ref FormatParam[] dynamicVars, ref FormatParam[] staticVars)
{
// Create a StringBuilder to store the output of this processing. We use the format's length as an
// approximation of an upper-bound for how large the output will be, though with parameter processing,
// this is just an estimate, sometimes way over, sometimes under.
StringBuilder output = StringBuilderCache.Acquire(format.Length);
// Format strings support conditionals, including the equivalent of "if ... then ..." and
// "if ... then ... else ...", as well as "if ... then ... else ... then ..."
// and so on, where an else clause can not only be evaluated for string output but also
// as a conditional used to determine whether to evaluate a subsequent then clause.
// We use recursion to process these subsequent parts, and we track whether we're processing
// at the same level of the initial if clause (or whether we're nested).
bool sawIfConditional = false;
// Process each character in the format string, starting from the position passed in.
for (; pos < format.Length; pos++)
{
// '%' is the escape character for a special sequence to be evaluated.
// Anything else just gets pushed to output.
if (format[pos] != '%')
{
output.Append(format[pos]);
continue;
}
// We have a special parameter sequence to process. Now we need
// to look at what comes after the '%'.
++pos;
switch (format[pos])
{
// Output appending operations
case '%': // Output the escaped '%'
output.Append('%');
break;
case 'c': // Pop the stack and output it as a char
output.Append((char)stack.Pop().Int32);
break;
case 's': // Pop the stack and output it as a string
output.Append(stack.Pop().String);
break;
case 'd': // Pop the stack and output it as an integer
output.Append(stack.Pop().Int32);
break;
case 'o':
case 'X':
case 'x':
case ':':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
// printf strings of the format "%[[:]flags][width[.precision]][doxXs]" are allowed
// (with a ':' used in front of flags to help differentiate from binary operations, as flags can
// include '-' and '+'). While above we've special-cased common usage (e.g. %d, %s),
// for more complicated expressions we delegate to printf.
int printfEnd = pos;
for (; printfEnd < format.Length; printfEnd++) // find the end of the printf format string
{
char ec = format[printfEnd];
if (ec == 'd' || ec == 'o' || ec == 'x' || ec == 'X' || ec == 's')
{
break;
}
}
if (printfEnd >= format.Length)
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
string printfFormat = format.Substring(pos - 1, printfEnd - pos + 2); // extract the format string
if (printfFormat.Length > 1 && printfFormat[1] == ':')
{
printfFormat = printfFormat.Remove(1, 1);
}
output.Append(FormatPrintF(printfFormat, stack.Pop().Object)); // do the printf formatting and append its output
break;
// Stack pushing operations
case 'p': // Push the specified parameter (1-based) onto the stack
pos++;
Debug.Assert(format[pos] >= '0' && format[pos] <= '9');
stack.Push(args[format[pos] - '1']);
break;
case 'l': // Pop a string and push its length
stack.Push(stack.Pop().String.Length);
break;
case '{': // Push integer literal, enclosed between braces
pos++;
int intLit = 0;
while (format[pos] != '}')
{
Debug.Assert(format[pos] >= '0' && format[pos] <= '9');
intLit = (intLit * 10) + (format[pos] - '0');
pos++;
}
stack.Push(intLit);
break;
case '\'': // Push literal character, enclosed between single quotes
stack.Push((int)format[pos + 1]);
Debug.Assert(format[pos + 2] == '\'');
pos += 2;
break;
// Storing and retrieving "static" and "dynamic" variables
case 'P': // Pop a value and store it into either static or dynamic variables based on whether the a-z variable is capitalized
pos++;
int setIndex;
FormatParam[] targetVars = GetDynamicOrStaticVariables(format[pos], ref dynamicVars, ref staticVars, out setIndex);
targetVars[setIndex] = stack.Pop();
break;
case 'g': // Push a static or dynamic variable; which is based on whether the a-z variable is capitalized
pos++;
int getIndex;
FormatParam[] sourceVars = GetDynamicOrStaticVariables(format[pos], ref dynamicVars, ref staticVars, out getIndex);
stack.Push(sourceVars[getIndex]);
break;
// Binary operations
case '+':
case '-':
case '*':
case '/':
case 'm':
case '^': // arithmetic
case '&':
case '|': // bitwise
case '=':
case '>':
case '<': // comparison
case 'A':
case 'O': // logical
int second = stack.Pop().Int32; // it's a stack... the second value was pushed last
int first = stack.Pop().Int32;
char c = format[pos];
stack.Push(
c == '+' ? (first + second) :
c == '-' ? (first - second) :
c == '*' ? (first * second) :
c == '/' ? (first / second) :
c == 'm' ? (first % second) :
c == '^' ? (first ^ second) :
c == '&' ? (first & second) :
c == '|' ? (first | second) :
c == '=' ? AsInt(first == second) :
c == '>' ? AsInt(first > second) :
c == '<' ? AsInt(first < second) :
c == 'A' ? AsInt(AsBool(first) && AsBool(second)) :
c == 'O' ? AsInt(AsBool(first) || AsBool(second)) :
0); // not possible; we just validated above
break;
// Unary operations
case '!':
case '~':
int value = stack.Pop().Int32;
stack.Push(
format[pos] == '!' ? AsInt(!AsBool(value)) :
~value);
break;
// Some terminfo files appear to have a fairly liberal interpretation of %i. The spec states that %i increments the first two arguments,
// but some uses occur when there's only a single argument. To make sure we accommodate these files, we increment the values
// of up to (but not requiring) two arguments.
case 'i':
if (args.Length > 0)
{
args[0] = 1 + args[0].Int32;
if (args.Length > 1)
args[1] = 1 + args[1].Int32;
}
break;
// Conditional of the form %? if-part %t then-part %e else-part %;
// The "%e else-part" is optional.
case '?':
sawIfConditional = true;
break;
case 't':
// We hit the end of the if-part and are about to start the then-part.
// The if-part left its result on the stack; pop and evaluate.
bool conditionalResult = AsBool(stack.Pop().Int32);
// Regardless of whether it's true, run the then-part to get past it.
// If the conditional was true, output the then results.
pos++;
string thenResult = EvaluateInternal(format, ref pos, args, stack, ref dynamicVars, ref staticVars);
if (conditionalResult)
{
output.Append(thenResult);
}
Debug.Assert(format[pos] == 'e' || format[pos] == ';');
// We're past the then; the top of the stack should now be a Boolean
// indicating whether this conditional has more to be processed (an else clause).
if (!AsBool(stack.Pop().Int32))
{
// Process the else clause, and if the conditional was false, output the else results.
pos++;
string elseResult = EvaluateInternal(format, ref pos, args, stack, ref dynamicVars, ref staticVars);
if (!conditionalResult)
{
output.Append(elseResult);
}
// Now we should be done (any subsequent elseif logic will have been handled in the recursive call).
if (!AsBool(stack.Pop().Int32))
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
}
// If we're in a nested processing, return to our parent.
if (!sawIfConditional)
{
stack.Push(1);
return StringBuilderCache.GetStringAndRelease(output);
}
// Otherwise, we're done processing the conditional in its entirety.
sawIfConditional = false;
break;
case 'e':
case ';':
// Let our caller know why we're exiting, whether due to the end of the conditional or an else branch.
stack.Push(AsInt(format[pos] == ';'));
return StringBuilderCache.GetStringAndRelease(output);
// Anything else is an error
default:
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
}
stack.Push(1);
return StringBuilderCache.GetStringAndRelease(output);
}
/// <summary>Converts an Int32 to a Boolean, with 0 meaning false and all non-zero values meaning true.</summary>
/// <param name="i">The integer value to convert.</param>
/// <returns>true if the integer was non-zero; otherwise, false.</returns>
private static bool AsBool(int i) { return i != 0; }
/// <summary>Converts a Boolean to an Int32, with true meaning 1 and false meaning 0.</summary>
/// <param name="b">The Boolean value to convert.</param>
/// <returns>1 if the Boolean is true; otherwise, 0.</returns>
private static int AsInt(bool b) { return b ? 1 : 0; }
/// <summary>Formats an argument into a printf-style format string.</summary>
/// <param name="format">The printf-style format string.</param>
/// <param name="arg">The argument to format. This must be an Int32 or a String.</param>
/// <returns>The formatted string.</returns>
private static unsafe string FormatPrintF(string format, object arg)
{
Debug.Assert(arg is string || arg is int);
// Determine how much space is needed to store the formatted string.
string stringArg = arg as string;
int neededLength = stringArg != null ?
Interop.Sys.SNPrintF(null, 0, format, stringArg) :
Interop.Sys.SNPrintF(null, 0, format, (int)arg);
if (neededLength == 0)
{
return string.Empty;
}
if (neededLength < 0)
{
throw new InvalidOperationException(SR.InvalidOperation_PrintF);
}
// Allocate the needed space, format into it, and return the data as a string.
byte[] bytes = new byte[neededLength + 1]; // extra byte for the null terminator
fixed (byte* ptr = &bytes[0])
{
int length = stringArg != null ?
Interop.Sys.SNPrintF(ptr, bytes.Length, format, stringArg) :
Interop.Sys.SNPrintF(ptr, bytes.Length, format, (int)arg);
if (length != neededLength)
{
throw new InvalidOperationException(SR.InvalidOperation_PrintF);
}
}
return Encoding.ASCII.GetString(bytes, 0, neededLength);
}
/// <summary>Gets the lazily-initialized dynamic or static variables collection, based on the supplied variable name.</summary>
/// <param name="c">The name of the variable.</param>
/// <param name="dynamicVars">The lazily-initialized dynamic variables collection.</param>
/// <param name="staticVars">The lazily-initialized static variables collection.</param>
/// <param name="index">The index to use to index into the variables.</param>
/// <returns>The variables collection.</returns>
private static FormatParam[] GetDynamicOrStaticVariables(
char c, ref FormatParam[] dynamicVars, ref FormatParam[] staticVars, out int index)
{
if (c >= 'A' && c <= 'Z')
{
index = c - 'A';
return staticVars ?? (staticVars = new FormatParam[26]); // one slot for each letter of alphabet
}
else if (c >= 'a' && c <= 'z')
{
index = c - 'a';
return dynamicVars ?? (dynamicVars = new FormatParam[26]); // one slot for each letter of alphabet
}
else throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}
/// <summary>
/// Represents a parameter to a terminfo formatting string.
/// It is a discriminated union of either an integer or a string,
/// with characters represented as integers.
/// </summary>
public readonly struct FormatParam
{
/// <summary>The integer stored in the parameter.</summary>
private readonly int _int32;
/// <summary>The string stored in the parameter.</summary>
private readonly string _string; // null means an Int32 is stored
/// <summary>Initializes the parameter with an integer value.</summary>
/// <param name="value">The value to be stored in the parameter.</param>
public FormatParam(int value) : this(value, null) { }
/// <summary>Initializes the parameter with a string value.</summary>
/// <param name="value">The value to be stored in the parameter.</param>
public FormatParam(string value) : this(0, value ?? string.Empty) { }
/// <summary>Initializes the parameter.</summary>
/// <param name="intValue">The integer value.</param>
/// <param name="stringValue">The string value.</param>
private FormatParam(int intValue, string stringValue)
{
_int32 = intValue;
_string = stringValue;
}
/// <summary>Implicit converts an integer into a parameter.</summary>
public static implicit operator FormatParam(int value)
{
return new FormatParam(value);
}
/// <summary>Implicit converts a string into a parameter.</summary>
public static implicit operator FormatParam(string value)
{
return new FormatParam(value);
}
/// <summary>Gets the integer value of the parameter. If a string was stored, 0 is returned.</summary>
public int Int32 { get { return _int32; } }
/// <summary>Gets the string value of the parameter. If an Int32 or a null String were stored, an empty string is returned.</summary>
public string String { get { return _string ?? string.Empty; } }
/// <summary>Gets the string or the integer value as an object.</summary>
public object Object { get { return _string ?? (object)_int32; } }
}
}
}
}
| |
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony
{
public class Loader : global::haxe.lang.HxObject
{
public Loader(global::haxe.lang.EmptyObject empty)
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
}
}
#line default
}
public Loader(global::haxe.lang.Null<int> intensivity, global::haxe.lang.Null<int> beginWait)
{
unchecked
{
#line 51 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
global::pony.Loader.__hx_ctor_pony_Loader(this, intensivity, beginWait);
}
#line default
}
public static void __hx_ctor_pony_Loader(global::pony.Loader __temp_me97, global::haxe.lang.Null<int> intensivity, global::haxe.lang.Null<int> beginWait)
{
unchecked
{
#line 49 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
__temp_me97.loaded = false;
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
__temp_me97.complites = 0;
#line 44 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
__temp_me97.total = 0;
#line 43 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
__temp_me97.totalActions = 0;
#line 51 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
int __temp_beginWait96 = ( (global::haxe.lang.Runtime.eq((beginWait).toDynamic(), (default(global::haxe.lang.Null<int>)).toDynamic())) ? (((int) (0) )) : (beginWait.@value) );
#line 51 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
int __temp_intensivity95 = ( (global::haxe.lang.Runtime.eq((intensivity).toDynamic(), (default(global::haxe.lang.Null<int>)).toDynamic())) ? (((int) (10) )) : (intensivity.@value) );
__temp_me97.intensivity = __temp_intensivity95;
__temp_me97.beginWait = __temp_beginWait96;
__temp_me97.actions = new global::List<object>();
__temp_me97.progress = new global::pony.events.Signal(((object) (__temp_me97) ));
__temp_me97.complite = new global::pony.events.Signal(((object) (__temp_me97) ));
{
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
int priority = 0;
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object listener = default(object);
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object f = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (__temp_me97) ), global::haxe.lang.Runtime.toString("end"), ((int) (5047259) ))) ), 0);
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
listener = global::pony.events._Listener.Listener_Impl_._fromFunction(f, false);
}
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object __temp_stmt453 = default(object);
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object f1 = global::haxe.lang.Runtime.getField(listener, "f", 102, true);
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object this1 = default(object);
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object __temp_getvar193 = f1;
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
double __temp_ret194 = ((double) (global::haxe.lang.Runtime.getField_f(__temp_getvar193, "used", 1303220797, true)) );
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object __temp_expr454 = ((object) (global::haxe.lang.Runtime.setField(__temp_getvar193, "used", 1303220797, ( __temp_ret194 + 1.0 ))) );
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
double __temp_expr455 = __temp_ret194;
}
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
bool __temp_odecl451 = ((bool) (global::haxe.lang.Runtime.getField(listener, "event", 1975830554, true)) );
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
bool __temp_odecl452 = ((bool) (global::haxe.lang.Runtime.getField(listener, "ignoreReturn", 98429794, true)) );
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this1 = new global::haxe.lang.DynamicObject(new global::Array<int>(new int[]{102, 98429794, 373703110, 1247723251, 1975830554}), new global::Array<object>(new object[]{f1, __temp_odecl452, true, default(global::pony.events.Event), __temp_odecl451}), new global::Array<int>(new int[]{1248019663, 1303220797}), new global::Array<double>(new double[]{((double) (1) ), ((double) (0) )}));
}
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
__temp_stmt453 = this1;
}
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
__temp_me97.complite.@add(((object) (__temp_stmt453) ), new global::haxe.lang.Null<int>(priority, true));
}
}
#line default
}
public static new object __hx_createEmpty()
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return new global::pony.Loader(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static new object __hx_create(global::Array arr)
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return new global::pony.Loader(global::haxe.lang.Null<object>.ofDynamic<int>(arr[0]), global::haxe.lang.Null<object>.ofDynamic<int>(arr[1]));
}
#line default
}
public int intensivity;
public int beginWait;
public global::List<object> actions;
public int totalActions;
public int total;
public int complites;
public global::pony.events.Signal progress;
public global::pony.events.Signal complite;
public bool loaded;
public virtual void init(global::haxe.lang.Null<bool> fastLoad)
{
unchecked
{
#line 62 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
bool __temp_fastLoad94 = ( (global::haxe.lang.Runtime.eq((fastLoad).toDynamic(), (default(global::haxe.lang.Null<bool>)).toDynamic())) ? (((bool) (false) )) : (fastLoad.@value) );
#line 62 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
if ( ! (__temp_fastLoad94) )
{
if (( this.beginWait == 0 ))
{
int priority = 0;
#line 64 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object listener = default(object);
#line 64 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object __temp_stmt435 = default(object);
#line 64 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
#line 64 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object l = default(object);
#line 64 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
#line 64 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object f = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("update"), ((int) (117802505) ))) ), 0);
#line 64 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
l = global::pony.events._Listener.Listener_Impl_._fromFunction(f, false);
}
#line 64 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
__temp_stmt435 = l;
}
#line 64 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
listener = ((object) (__temp_stmt435) );
#line 64 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
global::pony.events.Signal this1 = global::pony.DeltaTime.update;
#line 64 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this1.@add(((object) (listener) ), new global::haxe.lang.Null<int>(priority, true));
#line 64 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object __temp_expr436 = this1.target;
}
else
{
#line 66 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
int priority1 = 0;
#line 66 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object listener1 = default(object);
#line 66 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object __temp_stmt433 = default(object);
#line 66 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
#line 66 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object l1 = default(object);
#line 66 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
#line 66 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object f1 = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("wait"), ((int) (1324505717) ))) ), 0);
#line 66 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
l1 = global::pony.events._Listener.Listener_Impl_._fromFunction(f1, false);
}
#line 66 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
__temp_stmt433 = l1;
}
#line 66 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
listener1 = ((object) (__temp_stmt433) );
#line 66 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
global::pony.events.Signal this2 = global::pony.DeltaTime.update;
#line 66 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this2.@add(((object) (listener1) ), new global::haxe.lang.Null<int>(priority1, true));
#line 66 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object __temp_expr434 = this2.target;
}
}
else
{
#line 68 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
global::pony.events.Signal _this = this.complite;
#line 68 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
_this.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<object>(new object[]{})) ), ((object) (_this.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) )));
#line 68 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
global::pony.events.Signal __temp_expr432 = _this;
}
}
#line default
}
public virtual void fast()
{
unchecked
{
#line 130 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
global::pony.events.Signal _this = this.complite;
#line 130 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
_this.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<object>(new object[]{})) ), ((object) (_this.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) )));
#line 130 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
global::pony.events.Signal __temp_expr437 = _this;
}
#line default
}
public virtual void wait()
{
unchecked
{
#line 76 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
if (( this.beginWait-- <= 0 ))
{
{
#line 77 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object listener = default(object);
#line 77 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object __temp_stmt438 = default(object);
#line 77 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
#line 77 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object l = default(object);
#line 77 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
#line 77 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object f = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("wait"), ((int) (1324505717) ))) ), 0);
#line 77 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
l = global::pony.events._Listener.Listener_Impl_._fromFunction(f, false);
}
#line 77 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
__temp_stmt438 = l;
}
#line 77 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
listener = ((object) (__temp_stmt438) );
#line 77 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
global::pony.events.Signal this1 = global::pony.DeltaTime.update;
#line 77 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this1.@remove(((object) (listener) ));
#line 77 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object __temp_expr439 = this1.target;
}
{
#line 78 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
int priority = 0;
#line 78 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object listener1 = default(object);
#line 78 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object __temp_stmt440 = default(object);
#line 78 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
#line 78 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object l1 = default(object);
#line 78 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
#line 78 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object f1 = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("update"), ((int) (117802505) ))) ), 0);
#line 78 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
l1 = global::pony.events._Listener.Listener_Impl_._fromFunction(f1, false);
}
#line 78 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
__temp_stmt440 = l1;
}
#line 78 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
listener1 = ((object) (__temp_stmt440) );
#line 78 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
global::pony.events.Signal this2 = global::pony.DeltaTime.update;
#line 78 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this2.@add(((object) (listener1) ), new global::haxe.lang.Null<int>(priority, true));
#line 78 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object __temp_expr441 = this2.target;
}
}
}
#line default
}
public void begin()
{
unchecked
{
#line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
int priority = 0;
#line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object listener = default(object);
#line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object __temp_stmt442 = default(object);
#line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
#line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object l = default(object);
#line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
#line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object f = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("update"), ((int) (117802505) ))) ), 0);
#line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
l = global::pony.events._Listener.Listener_Impl_._fromFunction(f, false);
}
#line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
__temp_stmt442 = l;
}
#line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
listener = ((object) (__temp_stmt442) );
#line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
global::pony.events.Signal this1 = global::pony.DeltaTime.update;
#line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this1.@add(((object) (listener) ), new global::haxe.lang.Null<int>(priority, true));
#line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object __temp_expr443 = this1.target;
}
#line default
}
public virtual void update()
{
unchecked
{
#line 87 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
#line 87 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
int _g1 = 0;
#line 87 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
int _g = this.intensivity;
#line 87 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
while (( _g1 < _g ))
{
#line 87 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
int _ = _g1++;
#line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
if (( this.actions.length > 0 ))
{
#line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
((global::haxe.lang.Function) (this.actions.pop().@value) ).__hx_invoke0_o();
}
else
{
break;
}
}
}
#line 96 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
if (( this.totalActions == 0 ))
{
#line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
global::pony.events.Signal _this = this.progress;
#line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
_this.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<object>(new object[]{( ((double) (this.complites) ) / this.total )})) ), ((object) (_this.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) )));
#line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
global::pony.events.Signal __temp_expr446 = _this;
}
else
{
#line 98 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
if (( this.total == 0 ))
{
#line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
global::pony.events.Signal _this1 = this.progress;
#line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
_this1.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<object>(new object[]{( 1 - ( ((double) (this.actions.length) ) / this.totalActions ) )})) ), ((object) (_this1.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) )));
#line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
global::pony.events.Signal __temp_expr445 = _this1;
}
else
{
#line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
global::pony.events.Signal _this2 = this.progress;
#line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
_this2.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<object>(new object[]{( (( ( 1 - ( ((double) (this.actions.length) ) / this.totalActions ) ) + ( ((double) (this.complites) ) / this.total ) )) / 2 )})) ), ((object) (_this2.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) )));
#line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
global::pony.events.Signal __temp_expr444 = _this2;
}
}
#line 102 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
if (( ( this.actions.length == 0 ) && ( this.complites == this.total ) ))
{
#line 130 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
global::pony.events.Signal _this3 = this.complite;
#line 130 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
_this3.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<object>(new object[]{})) ), ((object) (_this3.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) )));
#line 130 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
global::pony.events.Signal __temp_expr447 = _this3;
}
}
#line default
}
public double listPercent()
{
unchecked
{
#line 106 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return ( 1 - ( ((double) (this.actions.length) ) / this.totalActions ) );
}
#line default
}
public double counterPercent()
{
unchecked
{
#line 107 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return ( ((double) (this.complites) ) / this.total );
}
#line default
}
public virtual void end()
{
unchecked
{
#line 110 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
#line 110 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object listener = default(object);
#line 110 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object __temp_stmt448 = default(object);
#line 110 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
#line 110 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object l = default(object);
#line 110 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
#line 110 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object f = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("update"), ((int) (117802505) ))) ), 0);
#line 110 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
l = global::pony.events._Listener.Listener_Impl_._fromFunction(f, false);
}
#line 110 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
__temp_stmt448 = l;
}
#line 110 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
listener = ((object) (__temp_stmt448) );
#line 110 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
global::pony.events.Signal this1 = global::pony.DeltaTime.update;
#line 110 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this1.@remove(((object) (listener) ));
#line 110 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
object __temp_expr449 = this1.target;
}
this.loaded = true;
}
#line default
}
public virtual void addAction(global::haxe.lang.Function f)
{
unchecked
{
#line 115 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.totalActions++;
this.actions.push(f);
}
#line default
}
public void fastEnd()
{
unchecked
{
#line 130 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
global::pony.events.Signal _this = this.complite;
#line 130 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
_this.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<object>(new object[]{})) ), ((object) (_this.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) )));
#line 130 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
global::pony.events.Signal __temp_expr450 = _this;
}
#line default
}
public override double __hx_setField_f(string field, int hash, double @value, bool handleProperties)
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
switch (hash)
{
case 1373469718:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.complites = ((int) (@value) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return @value;
}
case 338842564:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.total = ((int) (@value) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return @value;
}
case 271358105:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.totalActions = ((int) (@value) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return @value;
}
case 399259966:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.beginWait = ((int) (@value) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return @value;
}
case 1042925606:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.intensivity = ((int) (@value) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return @value;
}
default:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return base.__hx_setField_f(field, hash, @value, handleProperties);
}
}
}
#line default
}
public override object __hx_setField(string field, int hash, object @value, bool handleProperties)
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
switch (hash)
{
case 1483687941:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.loaded = ((bool) (@value) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return @value;
}
case 2144012733:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.complite = ((global::pony.events.Signal) (@value) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return @value;
}
case 103479213:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.progress = ((global::pony.events.Signal) (@value) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return @value;
}
case 1373469718:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.complites = ((int) (global::haxe.lang.Runtime.toInt(@value)) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return @value;
}
case 338842564:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.total = ((int) (global::haxe.lang.Runtime.toInt(@value)) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return @value;
}
case 271358105:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.totalActions = ((int) (global::haxe.lang.Runtime.toInt(@value)) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return @value;
}
case 1731068925:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.actions = ((global::List<object>) (global::List<object>.__hx_cast<object>(((global::List) (@value) ))) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return @value;
}
case 399259966:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.beginWait = ((int) (global::haxe.lang.Runtime.toInt(@value)) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return @value;
}
case 1042925606:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.intensivity = ((int) (global::haxe.lang.Runtime.toInt(@value)) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return @value;
}
default:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return base.__hx_setField(field, hash, @value, handleProperties);
}
}
}
#line default
}
public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties)
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
switch (hash)
{
case 1579254431:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("fastEnd"), ((int) (1579254431) ))) );
}
case 1315598519:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("addAction"), ((int) (1315598519) ))) );
}
case 5047259:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("end"), ((int) (5047259) ))) );
}
case 221002537:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("counterPercent"), ((int) (221002537) ))) );
}
case 802823687:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("listPercent"), ((int) (802823687) ))) );
}
case 117802505:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("update"), ((int) (117802505) ))) );
}
case 810936873:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("begin"), ((int) (810936873) ))) );
}
case 1324505717:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("wait"), ((int) (1324505717) ))) );
}
case 1135985308:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("fast"), ((int) (1135985308) ))) );
}
case 1169898256:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("init"), ((int) (1169898256) ))) );
}
case 1483687941:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return this.loaded;
}
case 2144012733:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return this.complite;
}
case 103479213:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return this.progress;
}
case 1373469718:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return this.complites;
}
case 338842564:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return this.total;
}
case 271358105:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return this.totalActions;
}
case 1731068925:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return this.actions;
}
case 399259966:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return this.beginWait;
}
case 1042925606:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return this.intensivity;
}
default:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties);
}
}
}
#line default
}
public override double __hx_getField_f(string field, int hash, bool throwErrors, bool handleProperties)
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
switch (hash)
{
case 1373469718:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return ((double) (this.complites) );
}
case 338842564:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return ((double) (this.total) );
}
case 271358105:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return ((double) (this.totalActions) );
}
case 399259966:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return ((double) (this.beginWait) );
}
case 1042925606:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return ((double) (this.intensivity) );
}
default:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return base.__hx_getField_f(field, hash, throwErrors, handleProperties);
}
}
}
#line default
}
public override object __hx_invokeField(string field, int hash, global::Array dynargs)
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
switch (hash)
{
case 1579254431:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.fastEnd();
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
break;
}
case 1315598519:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.addAction(((global::haxe.lang.Function) (dynargs[0]) ));
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
break;
}
case 5047259:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.end();
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
break;
}
case 221002537:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return this.counterPercent();
}
case 802823687:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return this.listPercent();
}
case 117802505:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.update();
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
break;
}
case 810936873:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.begin();
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
break;
}
case 1324505717:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.wait();
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
break;
}
case 1135985308:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.fast();
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
break;
}
case 1169898256:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
this.init(global::haxe.lang.Null<object>.ofDynamic<bool>(dynargs[0]));
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
break;
}
default:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return base.__hx_invokeField(field, hash, dynargs);
}
}
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
return default(object);
}
#line default
}
public override void __hx_getFields(global::Array<object> baseArr)
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
baseArr.push("loaded");
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
baseArr.push("complite");
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
baseArr.push("progress");
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
baseArr.push("complites");
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
baseArr.push("total");
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
baseArr.push("totalActions");
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
baseArr.push("actions");
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
baseArr.push("beginWait");
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
baseArr.push("intensivity");
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Loader.hx"
base.__hx_getFields(baseArr);
}
}
#line default
}
}
}
| |
using System.Linq;
using System.Threading.Tasks;
using OmniSharp.Models.Rename;
using OmniSharp.Roslyn.CSharp.Services.Refactoring;
using TestUtility;
using Xunit;
using Xunit.Abstractions;
namespace OmniSharp.Roslyn.CSharp.Tests
{
public class RenameFacts : AbstractSingleRequestHandlerTestFixture<RenameService>
{
public RenameFacts(ITestOutputHelper output, SharedOmniSharpHostFixture sharedOmniSharpHostFixture)
: base(output, sharedOmniSharpHostFixture)
{
}
protected override string EndpointName => OmniSharpEndpoints.Rename;
[Fact]
public async Task Rename_UpdatesWorkspaceAndDocumentText()
{
const string code = @"
using System;
namespace OmniSharp.Models
{
public class CodeFormat$$Response
{
public string Buffer { get; set; }
}
}";
const string expectedCode = @"
using System;
namespace OmniSharp.Models
{
public class foo
{
public string Buffer { get; set; }
}
}";
var testFile = new TestFile("test.cs", code);
using (var host = CreateOmniSharpHost(testFile))
{
var result = await PerformRename(host, testFile, "foo", applyTextChanges: true);
var solution = host.Workspace.CurrentSolution;
var documentId = solution.GetDocumentIdsWithFilePath(testFile.FileName).First();
var document = solution.GetDocument(documentId);
var sourceText = await document.GetTextAsync();
var change = result.Changes.Single();
// compare workspace change with response
Assert.Equal(change.Buffer, sourceText.ToString());
// check that response refers to correct modified file
Assert.Equal(change.FileName, testFile.FileName);
// check response for change
Assert.Equal(expectedCode, change.Buffer);
}
}
[Fact]
public async Task Rename_DoesNotUpdatesWorkspace()
{
const string fileContent = @"
using System;
namespace OmniSharp.Models
{
public class CodeFormat$$Response
{
public string Buffer { get; set; }
}
}";
var testFile = new TestFile("test.cs", fileContent);
using (var host = CreateOmniSharpHost(testFile))
{
var result = await PerformRename(host, testFile, "foo", applyTextChanges: false);
var solution = host.Workspace.CurrentSolution;
var documentId = solution.GetDocumentIdsWithFilePath(testFile.FileName).First();
var document = solution.GetDocument(documentId);
var sourceText = await document.GetTextAsync();
// check that the workspace has not been updated
Assert.Equal(testFile.Content.Code, sourceText.ToString());
}
}
[Fact]
public async Task Rename_UpdatesMultipleDocumentsIfNecessary()
{
const string code1 = "public class F$$oo {}";
const string code2 = @"
public class Bar {
public Foo Property {get; set;}
}";
const string expectedCode = @"
public class Bar {
public xxx Property {get; set;}
}";
var testFiles = new[]
{
new TestFile("test1.cs", code1),
new TestFile("test2.cs", code2)
};
using (var host = CreateOmniSharpHost(testFiles))
{
var result = await PerformRename(host, testFiles, "xxx");
var solution = host.Workspace.CurrentSolution;
var documentId1 = solution.GetDocumentIdsWithFilePath(testFiles[0].FileName).First();
var document1 = solution.GetDocument(documentId1);
var sourceText1 = await document1.GetTextAsync();
var documentId2 = solution.GetDocumentIdsWithFilePath(testFiles[1].FileName).First();
var document2 = solution.GetDocument(documentId2);
var sourceText2 = await document2.GetTextAsync();
var changes = result.Changes.ToArray();
//compare workspace change with response for file 1
Assert.Equal(sourceText1.ToString(), changes[0].Buffer);
//check that response refers to modified file 1
Assert.Equal(testFiles[0].FileName, changes[0].FileName);
//check response for change in file 1
Assert.Equal(@"public class xxx {}", changes[0].Buffer);
//compare workspace change with response for file 2
Assert.Equal(sourceText2.ToString(), changes[1].Buffer);
//check that response refers to modified file 2
Assert.Equal(testFiles[1].FileName, changes[1].FileName);
//check response for change in file 2
Assert.Equal(expectedCode, changes[1].Buffer);
}
}
[Fact]
public async Task Rename_UpdatesMultipleDocumentsIfNecessaryAndProducesTextChangesIfAsked()
{
const string code1 = "public class F$$oo {}";
const string code2 = @"
public class Bar {
public Foo Property {get; set;}
}";
var testFiles = new[]
{
new TestFile("test1.cs", code1),
new TestFile("test2.cs", code2)
};
var result = await PerformRename(testFiles, "xxx", wantsTextChanges: true);
var changes = result.Changes.ToArray();
Assert.Equal(2, changes.Length);
Assert.Single(changes[0].Changes);
Assert.Null(changes[0].Buffer);
Assert.Equal("xxx", changes[0].Changes.First().NewText);
Assert.Equal(0, changes[0].Changes.First().StartLine);
Assert.Equal(13, changes[0].Changes.First().StartColumn);
Assert.Equal(0, changes[0].Changes.First().EndLine);
Assert.Equal(16, changes[0].Changes.First().EndColumn);
Assert.Null(changes[1].Buffer);
Assert.Equal("xxx", changes[1].Changes.First().NewText);
Assert.Equal(2, changes[1].Changes.First().StartLine);
Assert.Equal(11, changes[1].Changes.First().StartColumn);
Assert.Equal(2, changes[1].Changes.First().EndLine);
Assert.Equal(14, changes[1].Changes.First().EndColumn);
}
[Fact]
public async Task Rename_DoesTheRightThingWhenDocumentIsNotFound()
{
const string fileContent = "class f$$oo{}";
var testFile = new TestFile("test.cs", fileContent);
// Note: We intentionally aren't including the TestFile in the host.
using (var host = CreateEmptyOmniSharpHost())
{
var result = await PerformRename(host, testFile, "xxx", updateBuffer: true);
var changes = result.Changes.ToArray();
Assert.Single(changes);
Assert.Equal(testFile.FileName, changes[0].FileName);
}
}
[Fact]
public async Task Rename_DoesNotExplodeWhenAttemptingToRenameALibrarySymbol()
{
const string fileContent = @"
using System;
public class Program
{
public static void Main()
{
Guid.New$$Guid();
}
}";
var testFile = new TestFile("test.cs", fileContent);
var result = await PerformRename(testFile, "foo");
Assert.Empty(result.Changes);
Assert.NotNull(result.ErrorMessage);
}
[Fact]
public async Task Rename_DoesNotDuplicateRenamesWithMultipleFrameworks()
{
const string fileContent = @"
using System;
public class Program
{
public void Main(bool aBool$$ean)
{
Console.Write(aBoolean);
}
}";
var testFile = new TestFile("test.cs", fileContent);
var result = await PerformRename(testFile, "foo", wantsTextChanges: true);
var changes = result.Changes.ToArray();
Assert.Single(changes);
Assert.Equal(testFile.FileName, changes[0].FileName);
Assert.Equal(2, changes[0].Changes.Count());
}
private Task<RenameResponse> PerformRename(
TestFile testFile, string renameTo,
bool wantsTextChanges = false,
bool applyTextChanges = true,
bool updateBuffer = false)
{
return PerformRename(new[] { testFile }, renameTo, wantsTextChanges, applyTextChanges, updateBuffer);
}
private async Task<RenameResponse> PerformRename(
TestFile[] testFiles, string renameTo,
bool wantsTextChanges = false,
bool applyTextChanges = true,
bool updateBuffer = false)
{
SharedOmniSharpTestHost.AddFilesToWorkspace(testFiles);
return await PerformRename(SharedOmniSharpTestHost, testFiles, renameTo, wantsTextChanges, applyTextChanges, updateBuffer);
}
private Task<RenameResponse> PerformRename(
OmniSharpTestHost host, TestFile testFile, string renameTo,
bool wantsTextChanges = false,
bool applyTextChanges = true,
bool updateBuffer = false)
{
return PerformRename(host, new[] { testFile }, renameTo, wantsTextChanges, applyTextChanges, updateBuffer);
}
private async Task<RenameResponse> PerformRename(
OmniSharpTestHost host, TestFile[] testFiles, string renameTo,
bool wantsTextChanges = false,
bool applyTextChanges = true,
bool updateBuffer = false)
{
var activeFile = testFiles.Single(tf => tf.Content.HasPosition);
var point = activeFile.Content.GetPointFromPosition();
var request = new RenameRequest
{
Line = point.Line,
Column = point.Offset,
RenameTo = renameTo,
FileName = activeFile.FileName,
Buffer = activeFile.Content.Code,
WantsTextChanges = wantsTextChanges,
ApplyTextChanges = applyTextChanges
};
var requestHandler = GetRequestHandler(host);
if (updateBuffer)
{
await host.Workspace.BufferManager.UpdateBufferAsync(request);
}
return await requestHandler.Handle(request);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2008-2014 Charlie Poole
//
// 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.Threading;
using NUnit.Engine.Internal;
namespace NUnit.Engine.Agents
{
/// <summary>
/// RemoteTestAgent represents a remote agent executing in another process
/// and communicating with NUnit by TCP. Although it is similar to a
/// TestServer, it does not publish a Uri at which clients may connect
/// to it. Rather, it reports back to the sponsoring TestAgency upon
/// startup so that the agency may in turn provide it to clients for use.
/// </summary>
public class RemoteTestAgent : TestAgent, ITestEngineRunner
{
static Logger log = InternalTrace.GetLogger(typeof(RemoteTestAgent));
#region Fields
private ITestEngineRunner _runner;
private TestPackage _package;
private ManualResetEvent stopSignal = new ManualResetEvent(false);
#endregion
#region Constructor
/// <summary>
/// Construct a RemoteTestAgent
/// </summary>
public RemoteTestAgent( Guid agentId, ITestAgency agency, ServiceContext services )
: base(agentId, agency, services)
{
}
#endregion
#region Properties
public int ProcessId
{
get { return System.Diagnostics.Process.GetCurrentProcess().Id; }
}
#endregion
#region Public Methods
public override ITestEngineRunner CreateRunner(TestPackage package)
{
_package = package;
return this;
}
public override bool Start()
{
log.Info("Agent starting");
try
{
this.Agency.Register( this );
log.Debug( "Registered with TestAgency" );
}
catch( Exception ex )
{
log.Error( "RemoteTestAgent: Failed to register with TestAgency", ex );
return false;
}
return true;
}
public override void Stop()
{
log.Info("Stopping");
// This causes an error in the client because the agent
// database is not thread-safe.
//if (agency != null)
// agency.ReportStatus(this.ProcessId, AgentStatus.Stopping);
stopSignal.Set();
}
public void WaitForStop()
{
stopSignal.WaitOne();
}
#endregion
#region ITestEngineRunner Members
/// <summary>
/// Explore a loaded TestPackage and return information about
/// the tests found.
/// </summary>
/// <param name="filter">Criteria used to filter the search results</param>
/// <returns>A TestEngineResult.</returns>
public TestEngineResult Explore(TestFilter filter)
{
if (_runner == null)
throw new InvalidOperationException("RemoteTestAgent: Explore called before Load");
return _runner.Explore(filter);
}
public TestEngineResult Load()
{
//System.Diagnostics.Debug.Assert(false, "Attach debugger if desired");
_runner = Services.GetService<ITestRunnerFactory>().MakeTestRunner(_package);
return _runner.Load();
}
public void Unload()
{
if (_runner != null)
_runner.Unload();
}
public TestEngineResult Reload()
{
if (_runner == null)
throw new InvalidOperationException("RemoteTestAgent: Reload called before Load");
return _runner.Reload();
}
/// <summary>
/// Count the test cases that would be run under
/// the specified filter.
/// </summary>
/// <param name="filter">A TestFilter</param>
/// <returns>The count of test cases</returns>
public int CountTestCases(TestFilter filter)
{
if (_runner == null)
throw new InvalidOperationException("RemoteTestAgent: CountTestCases called before Load");
return _runner.CountTestCases(filter);
}
/// <summary>
/// Run the tests in the loaded TestPackage and return a test result. The tests
/// are run synchronously and the listener interface is notified as it progresses.
/// </summary>
/// <param name="listener">An ITestEventHandler to receive events</param>
/// <param name="filter">A TestFilter used to select tests</param>
/// <returns>A TestEngineResult giving the result of the test execution</returns>
public TestEngineResult Run(ITestEventListener listener, TestFilter filter)
{
if (_runner == null)
throw new InvalidOperationException("RemoteTestAgent: Run called before Load");
return _runner.Run(listener, filter);
}
/// <summary>
/// Start a run of the tests in the loaded TestPackage. The tests are run
/// asynchronously and the listener interface is notified as it progresses.
/// </summary>
/// <param name="listener">An ITestEventHandler to receive events</param>
/// <param name="filter">A TestFilter used to select tests</param>
/// <returns>A <see cref="AsyncTestEngineResult"/> that will provide the result of the test execution</returns>
public AsyncTestEngineResult RunAsync(ITestEventListener listener, TestFilter filter)
{
if (_runner == null)
throw new InvalidOperationException("RemoteTestAgent: RunAsync called before Load");
return _runner.RunAsync(listener, filter);
}
/// <summary>
/// Start a run of the tests in the loaded TestPackage. The tests are run
/// asynchronously and the listener interface is notified as it progresses.
/// </summary>
/// <param name="listener">An ITestEventHandler to receive events</param>
/// <param name="filter">A TestFilter used to select tests</param>
public void StartRun(ITestEventListener listener, TestFilter filter)
{
RunAsync(listener, filter);
}
/// <summary>
/// Cancel the ongoing test run. If no test is running, the call is ignored.
/// </summary>
/// <param name="force">If true, cancel any ongoing test threads, otherwise wait for them to complete.</param>
public void StopRun(bool force)
{
if (_runner != null)
_runner.StopRun(force);
}
#endregion
}
}
| |
//
// System.Web.UI.WebControls/ParameterCollection.cs
//
// Author: Todd Berman <tberman@gentoo.org>
//
// (C) 2003 Todd Berman
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0
using System.Web.UI;
using System.Collections;
using System.Collections.Specialized;
namespace System.Web.UI.WebControls
{
public class ParameterCollection : StateManagedCollection
{
private static Type[] _knownTypes = new Type[] {
typeof (ControlParameter),
typeof (CookieParameter),
typeof (FormParameter),
typeof (Parameter),
typeof (QueryStringParameter),
typeof (SessionParameter) };
private EventHandler _parametersChanged;
public int Add (Parameter param)
{
return ((IList)this).Add (param);
}
public int Add (string name, string value)
{
return ((IList)this).Add (new Parameter (name, TypeCode.Object, value));
}
public int Add (string name, TypeCode type, string value)
{
return ((IList)this).Add (new Parameter (name, type, value));
}
protected override object CreateKnownType (int idx)
{
switch (idx) {
case 0:
return new ControlParameter ();
case 1:
return new CookieParameter ();
case 2:
return new FormParameter ();
case 3:
return new Parameter ();
case 4:
return new QueryStringParameter ();
case 5:
return new SessionParameter ();
}
throw new ArgumentOutOfRangeException ("index");
}
protected override Type[] GetKnownTypes ()
{
return _knownTypes;
}
public IOrderedDictionary GetValues (HttpContext context, Control control)
{
OrderedDictionary values = new OrderedDictionary ();
foreach (Parameter param in this)
{
string name = param.Name;
for (int i = 1; values.Contains (name); i++)
name = param.Name + i.ToString ();
values.Add (name, param.GetValue (context, control));
}
return values;
}
public void UpdateValues (HttpContext context, Control control)
{
foreach (Parameter param in this)
param.GetValue (context, control);
}
public void Insert (int idx, Parameter param)
{
((IList)this).Insert (idx, param);
}
protected override void OnClearComplete ()
{
base.OnClearComplete ();
OnParametersChanged (EventArgs.Empty);
}
protected override void OnInsert (int idx, object value)
{
base.OnInsert (idx, value);
((Parameter)value).SetOwnerCollection (this);
}
protected override void OnInsertComplete (int idx, object value)
{
base.OnInsertComplete (idx, value);
OnParametersChanged (EventArgs.Empty);
}
protected virtual void OnParametersChanged (EventArgs e)
{
if (_parametersChanged != null)
_parametersChanged(this, e);
}
protected override void OnValidate (object o)
{
base.OnValidate (o);
if ((o is Parameter) == false)
throw new ArgumentException ("o is not a Parameter");
}
public void Remove (Parameter param)
{
((IList)this).Remove (param);
}
public void RemoveAt (int idx)
{
((IList)this).RemoveAt (idx);
}
protected override void SetDirtyObject (object o)
{
Parameter param = (Parameter)o;
if (Contains (param))
param.SetDirty ();
}
internal void CallOnParameterChanged ()
{
OnParametersChanged (EventArgs.Empty);
}
private int IndexOfString (string name)
{
for (int i = 0; i < Count; i++)
{
if (((Parameter)((IList)this)[i]).Name == name)
return i;
}
return -1;
}
public Parameter this[int idx] {
get {
return (Parameter) ((IList)this)[idx];
}
set {
((IList)this)[idx] = value;
}
}
public Parameter this[string name] {
get {
int idx = IndexOfString (name);
if (idx == -1)
return null;
return ((Parameter) ((IList)this)[idx]);
}
set {
int idx = IndexOfString (name);
if (idx == -1) {
Add (value);
return;
}
((IList)this)[idx] = value;
}
}
public event EventHandler ParametersChanged {
add { _parametersChanged += value; }
remove { _parametersChanged -= value; }
}
public bool Contains (Parameter param)
{
return ((IList)this).Contains (param);
}
public void CopyTo (Parameter[] paramArray, int index)
{
((IList)this).CopyTo (paramArray, index);
}
public int IndexOf (Parameter param)
{
return ((IList)this).IndexOf (param);
}
protected override void OnRemoveComplete (int index, object value)
{
base.OnRemoveComplete (index, value);
OnParametersChanged (EventArgs.Empty);
}
}
}
#endif
| |
#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 NET_2_0
// pageType = BuildManager.GetCompiledType( rootedVPath ); // requires rooted virtual path!
//#else
// pageType = CreatePageInstance(pageUrl).GetType();
//#endif
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
{
//#if NET_2_0
// controlType = BuildManager.GetCompiledType( rootedVPath ); // requires rooted virtual path!
//#else
// controlType = (Type) miGetCompiledUserControlType.Invoke(null, new object[] { rootedVPath, null, ctx });
//#endif
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;
}
}
}
| |
using System;
using System.IO;
using BlackFox.Binary;
using BlackFox.U2F.Gnubby.Messages;
using JetBrains.Annotations;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.X509;
namespace BlackFox.U2F.Codec
{
/// <summary>Raw message formats, as per FIDO U2F: Raw Message Formats - Draft 4</summary>
public class RawMessageCodec
{
public const byte RegistrationReservedByteValue = 0x05;
public const byte RegistrationSignedReservedByteValue = 0x00;
public static byte[] EncodeKeyRegisterRequest([NotNull] KeyRegisterRequest keyRegisterRequest)
{
if (keyRegisterRequest == null)
{
throw new ArgumentNullException(nameof(keyRegisterRequest));
}
var appIdSha256 = keyRegisterRequest.ApplicationSha256;
var challengeSha256 = keyRegisterRequest.ChallengeSha256;
var result = new byte[appIdSha256.Length + challengeSha256.Length];
using (var writer = new EndianWriter(new MemoryStream(result), Endianness.BigEndian))
{
writer.Write(challengeSha256);
writer.Write(appIdSha256);
}
return result;
}
/// <exception cref="U2FException"/>
public static KeyRegisterRequest DecodeKeyRegisterRequest([NotNull] byte[] data)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
try
{
using (var inputStream = new EndianReader(new MemoryStream(data), Endianness.BigEndian))
{
var challengeSha256 = inputStream.ReadBytes(32);
var appIdSha256 = inputStream.ReadBytes(32);
if (inputStream.BaseStream.Position != inputStream.BaseStream.Length)
{
throw new U2FException("Message ends with unexpected data");
}
return new KeyRegisterRequest(appIdSha256, challengeSha256);
}
}
catch (IOException e)
{
throw new U2FException("Error when parsing raw RegistrationResponse", e);
}
}
/// <exception cref="U2FException"/>
public static byte[] EncodeKeyRegisterResponse([NotNull] KeyRegisterResponse keyRegisterResponse)
{
if (keyRegisterResponse == null)
{
throw new ArgumentNullException(nameof(keyRegisterResponse));
}
var userPublicKey = keyRegisterResponse.UserPublicKey;
var keyHandle = keyRegisterResponse.KeyHandle;
var attestationCertificate = keyRegisterResponse.AttestationCertificate;
var signature = keyRegisterResponse.Signature;
byte[] attestationCertificateBytes;
try
{
attestationCertificateBytes = attestationCertificate.GetEncoded();
}
catch (CertificateEncodingException e)
{
throw new U2FException("Error when encoding attestation certificate.", e);
}
if (keyHandle.Length > 255)
{
throw new U2FException("keyHandle length cannot be longer than 255 bytes!"
);
}
var result = new byte[1 + userPublicKey.Length + 1 + keyHandle.Length + attestationCertificateBytes
.Length + signature.Length];
using (var writer = new EndianWriter(new MemoryStream(result), Endianness.BigEndian))
{
writer.Write(RegistrationReservedByteValue);
writer.Write(userPublicKey);
writer.Write((byte)keyHandle.Length);
writer.Write(keyHandle);
writer.Write(attestationCertificateBytes);
writer.Write(signature);
}
return result;
}
/// <exception cref="U2FException"/>
public static KeyRegisterResponse DecodeKeyRegisterResponse(ArraySegment<byte> data)
{
try
{
using (var stream = data.AsStream())
using (var inputStream = new EndianReader(stream, Endianness.BigEndian))
{
var reservedByte = inputStream.ReadByte();
var userPublicKey = inputStream.ReadBytes(65);
var keyHandleSize = inputStream.ReadByte();
var keyHandle = inputStream.ReadBytes(keyHandleSize);
var parser = new X509CertificateParser();
var attestationCertificate = parser.ReadCertificate(inputStream.BaseStream);
var signatureSize = (int)(inputStream.BaseStream.Length - inputStream.BaseStream.Position);
var signature = inputStream.ReadBytes(signatureSize);
if (reservedByte != RegistrationReservedByteValue)
{
throw new U2FException(
$"Incorrect value of reserved byte. Expected: {RegistrationReservedByteValue}. Was: {reservedByte}");
}
return new KeyRegisterResponse(userPublicKey, keyHandle,
attestationCertificate, signature);
}
}
catch (IOException e)
{
throw new U2FException("Error when parsing raw RegistrationResponse", e);
}
catch (CertificateException e)
{
throw new U2FException("Error when parsing attestation certificate", e);
}
}
/// <exception cref="U2FException"/>
public static byte[] EncodeKeySignRequest([NotNull] KeySignRequest keySignRequest)
{
if (keySignRequest == null)
{
throw new ArgumentNullException(nameof(keySignRequest));
}
//var controlByte = authenticateRequest.Control;
var appIdSha256 = keySignRequest.ApplicationSha256;
var challengeSha256 = keySignRequest.ChallengeSha256;
var keyHandle = keySignRequest.KeyHandle;
if (keyHandle.Length > 255)
{
throw new U2FException("keyHandle length cannot be longer than 255 bytes!");
}
int size;
switch (keySignRequest.Version)
{
case U2FVersion.V1:
size = appIdSha256.Length + challengeSha256.Length + keyHandle.Length;
break;
case U2FVersion.V2:
size = appIdSha256.Length + challengeSha256.Length + keyHandle.Length + 1;
break;
default:
throw new ArgumentException("Unknown version: " + keySignRequest.Version, nameof(keySignRequest));
}
var result = new byte[size];
using (var writer = new EndianWriter(new MemoryStream(result), Endianness.BigEndian))
{
writer.Write(challengeSha256);
writer.Write(appIdSha256);
if (keySignRequest.Version == U2FVersion.V2)
{
writer.Write((byte)keyHandle.Length);
}
writer.Write(keyHandle);
}
return result;
}
/// <exception cref="U2FException"/>
public static KeySignRequest DecodeKeySignRequest([NotNull] byte[] data)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
try
{
using (var inputStream = new EndianReader(new MemoryStream(data), Endianness.BigEndian))
{
var challengeSha256 = inputStream.ReadBytes(32);
var appIdSha256 = inputStream.ReadBytes(32);
var keyHandleSize = inputStream.ReadByte();
var keyHandle = inputStream.ReadBytes(keyHandleSize);
if (inputStream.BaseStream.Position != inputStream.BaseStream.Length)
{
throw new U2FException("Message ends with unexpected data");
}
return new KeySignRequest(U2FVersion.V2, challengeSha256, appIdSha256, keyHandle);
}
}
catch (IOException e)
{
throw new U2FException("Error when parsing raw RegistrationResponse", e);
}
}
/// <exception cref="U2FException"/>
public static byte[] EncodeKeySignResponse([NotNull] KeySignResponse keySignResponse)
{
if (keySignResponse == null)
{
throw new ArgumentNullException(nameof(keySignResponse));
}
var userPresence = keySignResponse.UserPresence;
var counter = keySignResponse.Counter;
var signature = keySignResponse.Signature;
var result = new byte[1 + 4 + signature.Length];
using (var writer = new EndianWriter(new MemoryStream(result), Endianness.BigEndian))
{
writer.Write(userPresence);
writer.Write(counter);
writer.Write(signature);
}
return result;
}
/// <exception cref="U2FException"/>
public static KeySignResponse DecodeKeySignResponse(ArraySegment<byte> data)
{
try
{
using (var stream = data.AsStream())
{
using (var inputStream = new EndianReader(stream, Endianness.BigEndian))
{
var userPresence = inputStream.ReadByte();
var counter = inputStream.ReadInt32();
var signatureSize = (int)(inputStream.BaseStream.Length - inputStream.BaseStream.Position);
var signature = inputStream.ReadBytes(signatureSize);
return new KeySignResponse(userPresence, counter, signature);
}
}
}
catch (IOException e)
{
throw new U2FException("Error when parsing rawSignData", e);
}
}
public static byte[] EncodeKeyRegisterSignedBytes(byte[] applicationSha256, byte[] challengeSha256, byte[] keyHandle, byte[] userPublicKey)
{
var size = 1 + applicationSha256.Length + challengeSha256.Length + keyHandle.Length + userPublicKey.Length;
var signedData = new byte[size];
using (var writer = new EndianWriter(new MemoryStream(signedData), Endianness.BigEndian))
{
writer.Write(RegistrationSignedReservedByteValue);
writer.Write(applicationSha256);
writer.Write(challengeSha256);
writer.Write(keyHandle);
writer.Write(userPublicKey);
}
// RFU
return signedData;
}
public static byte[] EncodeKeySignSignedBytes(byte[] applicationSha256, byte userPresence, int counter, byte[] challengeSha256)
{
var size = applicationSha256.Length + 1 + 4 + challengeSha256.Length;
var signedData = new byte[size];
using (var writer = new EndianWriter(new MemoryStream(signedData), Endianness.BigEndian))
{
writer.Write(applicationSha256);
writer.Write(userPresence);
writer.Write(counter);
writer.Write(challengeSha256);
}
return signedData;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma warning disable 1634, 1691
using System.Threading;
using Dbg = System.Management.Automation;
namespace System.Management.Automation
{
/// <summary>
/// Defines a drive that exposes a provider path to the user.
/// </summary>
/// <remarks>
/// A cmdlet provider may want to derive from this class to provide their
/// own public members or to cache information related to the drive. For instance,
/// if a drive is a connection to a remote machine and making that connection
/// is expensive, then the provider may want keep a handle to the connection as
/// a member of their derived <see cref="PSDriveInfo"/> class and use it when
/// the provider is invoked.
/// </remarks>
public class PSDriveInfo : IComparable
{
/// <summary>
/// An instance of the PSTraceSource class used for trace output
/// using "SessionState" as the category.
/// This is the same category as the SessionState tracer class.
/// </summary>
[Dbg.TraceSourceAttribute(
"PSDriveInfo",
"The namespace navigation tracer")]
private static readonly Dbg.PSTraceSource s_tracer =
Dbg.PSTraceSource.GetTracer("PSDriveInfo",
"The namespace navigation tracer");
/// <summary>
/// Gets or sets the current working directory for the drive.
/// </summary>
public string CurrentLocation
{
get
{
return _currentWorkingDirectory;
}
set
{
_currentWorkingDirectory = value;
}
}
/// <summary>
/// The current working directory for the virtual drive
/// as a relative path from Root.
/// </summary>
private string _currentWorkingDirectory;
/// <summary>
/// Gets the name of the drive.
/// </summary>
public string Name
{
get
{
return _name;
}
}
/// <summary>
/// The name of the virtual drive.
/// </summary>
private string _name;
/// <summary>
/// Gets the name of the provider that root path
/// of the drive represents.
/// </summary>
public ProviderInfo Provider
{
get
{
return _provider;
}
}
/// <summary>
/// The provider information for the provider that implements
/// the functionality for the drive.
/// </summary>
private ProviderInfo _provider;
/// <summary>
/// Gets the root path of the drive.
/// </summary>
public string Root
{
get
{
return _root;
}
internal set
{
_root = value;
}
}
/// <summary>
/// Sets the root of the drive.
/// </summary>
/// <param name="path">
/// The root path to set for the drive.
/// </param>
/// <remarks>
/// This method can only be called during drive
/// creation. A NotSupportedException if this method
/// is called outside of drive creation.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="NotSupportedException">
/// If this method gets called any other time except
/// during drive creation.
/// </exception>
internal void SetRoot(string path)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(path));
}
if (!DriveBeingCreated)
{
NotSupportedException e =
PSTraceSource.NewNotSupportedException();
throw e;
}
_root = path;
}
/// <summary>
/// The root of the virtual drive.
/// </summary>
private string _root;
/// <summary>
/// Gets or sets the description for the drive.
/// </summary>
public string Description { get; set; }
/// <summary>
/// When supported by provider this specifies a maximum drive size.
/// </summary>
public long? MaximumSize { get; internal set; }
/// <summary>
/// Gets the credential to use with the drive.
/// </summary>
public PSCredential Credential { get; } = PSCredential.Empty;
/// <summary>
/// Determines if the root of the drive can
/// be modified during drive creation through
/// the SetRoot method.
/// </summary>
/// <value>
/// True if the drive is being created and the
/// root can be modified through the SetRoot method.
/// False otherwise.
/// </value>
internal bool DriveBeingCreated { get; set; }
/// <summary>
/// True if the drive was automounted by the system,
/// false otherwise.
/// </summary>
/// <value></value>
internal bool IsAutoMounted { get; set; }
/// <summary>
/// True if the drive was automounted by the system,
/// and then manually removed by the user.
/// </summary>
internal bool IsAutoMountedManuallyRemoved { get; set; }
/// <summary>
/// Gets or sets the Persist Switch parameter.
/// If this switch parameter is set then the created PSDrive
/// would be persisted across PowerShell sessions.
/// </summary>
internal bool Persist { get; } = false;
/// <summary>
/// Get or sets the value indicating if the created drive is a network drive.
/// </summary>
internal bool IsNetworkDrive { get; set; } = false;
/// <summary>
/// Gets or sets the UNC path of the drive. This property would be populated only
/// if the created PSDrive is targeting a network drive or else this property
/// would be null.
/// </summary>
public string DisplayRoot { get; internal set; } = null;
/// <summary>
/// Gets or sets if the drive-root relative paths on this drive are separated by a
/// colon or not.
///
/// This is true for all PSDrives on all platforms, except for filesystems on
/// non-Windows platforms.
///
/// This is not a path separator in the sense of separating paths in a single
/// string.
///
/// The biggest difference in filesystem handling between PS internally, and Unix
/// style systems is, that paths on Windows separate the drive letter from the
/// actual path by a colon. The second difference is, that a path that starts with
/// a \ or / on Windows is considered to be a relative path (drive-relative in
/// that case) where a similar path on a Unix style filesystem would be
/// root-relative, which is basically drive-relative for the filesystem, as there
/// is only one filesystem drive.
///
/// This property indicates, that a path can be checked for that drive-relativity
/// by checking for a colon. The main reason for this can be seen in all the
/// places that use this property, where PowerShell's code checks/splits/string
/// manipulates paths according to the colon character. This happens in many
/// places.
///
/// The idea here was to introduce a property that allows a code to query if a
/// PSDrive expects colon to be such a separator or not. I talked to Jim back then
/// about the problem, and this seemed to be a reasonable solution, given that
/// there is no other way to know for a PSDrive if paths can be qualified only in
/// a certain windows way on all platforms, or need special treatment on platforms
/// where colon does not exist as drive separator (regular filesystems on Unix
/// platforms are the only exception).
///
/// Globally this property can also be only true for one single PSDrive, because
/// if there is no drive separator, there is also no drive, and because there is
/// no drive there is no way to match against multiple such drives.
///
/// Additional data:
/// It seems that on single rooted filesystems, only the default
/// drive of "/" needs to set this VolumeSeparatedByColon to false
/// otherwise, creating new drives from the filesystem should actually
/// have this set to true as all the drives will have <string>: except
/// for "/"
/// </summary>
public bool VolumeSeparatedByColon { get; internal set; } = true;
#region ctor
/// <summary>
/// Constructs a new instance of the PSDriveInfo using another PSDriveInfo
/// as a template.
/// </summary>
/// <param name="driveInfo">
/// An existing PSDriveInfo object that should be copied to this instance.
/// </param>
/// <remarks>
/// A protected constructor that derived classes can call with an instance
/// of this class. This allows for easy creation of derived PSDriveInfo objects
/// which can be created in CmdletProvider's NewDrive method using the PSDriveInfo
/// that is passed in.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// If <paramref name="PSDriveInfo"/> is null.
/// </exception>
protected PSDriveInfo(PSDriveInfo driveInfo)
{
if (driveInfo == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(driveInfo));
}
_name = driveInfo.Name;
_provider = driveInfo.Provider;
Credential = driveInfo.Credential;
_currentWorkingDirectory = driveInfo.CurrentLocation;
Description = driveInfo.Description;
this.MaximumSize = driveInfo.MaximumSize;
DriveBeingCreated = driveInfo.DriveBeingCreated;
_hidden = driveInfo._hidden;
IsAutoMounted = driveInfo.IsAutoMounted;
_root = driveInfo._root;
Persist = driveInfo.Persist;
this.Trace();
}
/// <summary>
/// Constructs a drive that maps an MSH Path in
/// the shell to a Cmdlet Provider.
/// </summary>
/// <param name="name">
/// The name of the drive.
/// </param>
/// <param name="provider">
/// The name of the provider which implements the functionality
/// for the root path of the drive.
/// </param>
/// <param name="root">
/// The root path of the drive. For example, the root of a
/// drive in the file system can be c:\windows\system32
/// </param>
/// <param name="description">
/// The description for the drive.
/// </param>
/// <param name="credential">
/// The credentials under which all operations on the drive should occur.
/// If null, the current user credential is used.
/// </param>
/// <throws>
/// ArgumentNullException - if <paramref name="name"/>,
/// <paramref name="provider"/>, or <paramref name="root"/>
/// is null.
/// </throws>
public PSDriveInfo(
string name,
ProviderInfo provider,
string root,
string description,
PSCredential credential)
{
// Verify the parameters
if (name == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(name));
}
if (provider == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(provider));
}
if (root == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(root));
}
// Copy the parameters to the local members
_name = name;
_provider = provider;
_root = root;
Description = description;
if (credential != null)
{
Credential = credential;
}
// Set the current working directory to the empty
// string since it is relative to the root.
_currentWorkingDirectory = string.Empty;
Dbg.Diagnostics.Assert(
_currentWorkingDirectory != null,
"The currentWorkingDirectory cannot be null");
// Trace out the fields
this.Trace();
}
/// <summary>
/// Constructs a drive that maps an MSH Path in
/// the shell to a Cmdlet Provider.
/// </summary>
/// <param name="name">
/// The name of the drive.
/// </param>
/// <param name="provider">
/// The name of the provider which implements the functionality
/// for the root path of the drive.
/// </param>
/// <param name="root">
/// The root path of the drive. For example, the root of a
/// drive in the file system can be c:\windows\system32
/// </param>
/// <param name="description">
/// The description for the drive.
/// </param>
/// <param name="credential">
/// The credentials under which all operations on the drive should occur.
/// If null, the current user credential is used.
/// </param>
/// <param name="displayRoot">
/// The network path of the drive. This field would be populated only if PSDriveInfo
/// is targeting the network drive or else this filed is null for local drives.
/// </param>
/// <throws>
/// ArgumentNullException - if <paramref name="name"/>,
/// <paramref name="provider"/>, or <paramref name="root"/>
/// is null.
/// </throws>
public PSDriveInfo(
string name,
ProviderInfo provider,
string root,
string description,
PSCredential credential, string displayRoot)
: this(name, provider, root, description, credential)
{
DisplayRoot = displayRoot;
}
/// <summary>
/// Constructs a drive that maps an MSH Path in
/// the shell to a Cmdlet Provider.
/// </summary>
/// <param name="name">
/// The name of the drive.
/// </param>
/// <param name="provider">
/// The name of the provider which implements the functionality
/// for the root path of the drive.
/// </param>
/// <param name="root">
/// The root path of the drive. For example, the root of a
/// drive in the file system can be c:\windows\system32
/// </param>
/// <param name="description">
/// The description for the drive.
/// </param>
/// <param name="credential">
/// The credentials under which all operations on the drive should occur.
/// If null, the current user credential is used.
/// </param>
/// <param name="persist">
/// It indicates if the created PSDrive would be
/// persisted across PowerShell sessions.
/// </param>
/// <throws>
/// ArgumentNullException - if <paramref name="name"/>,
/// <paramref name="provider"/>, or <paramref name="root"/>
/// is null.
/// </throws>
public PSDriveInfo(
string name,
ProviderInfo provider,
string root,
string description,
PSCredential credential,
bool persist)
: this(name, provider, root, description, credential)
{
Persist = persist;
}
#endregion ctor
/// <summary>
/// Gets the name of the drive as a string.
/// </summary>
/// <returns>
/// Returns a String that is that name of the drive.
/// </returns>
public override string ToString()
{
return Name;
}
/// <summary>
/// Gets or sets the hidden property. The hidden property
/// determines if the drive should be hidden from the user.
/// </summary>
/// <value>
/// True if the drive should be hidden from the user, false
/// otherwise.
/// </value>
internal bool Hidden
{
get
{
return _hidden;
}
set
{
_hidden = value;
}
}
/// <summary>
/// Determines if the drive should be hidden from the user.
/// </summary>
private bool _hidden;
/// <summary>
/// Sets the name of the drive to a new name.
/// </summary>
/// <param name="newName">
/// The new name for the drive.
/// </param>
/// <remarks>
/// This must be internal so that we allow the renaming of drives
/// via the Core Command API but not through a reference to the
/// drive object. More goes in to renaming a drive than just modifying
/// the name in this class.
/// </remarks>
/// <exception cref="ArgumentException">
/// If <paramref name="newName"/> is null or empty.
/// </exception>
internal void SetName(string newName)
{
if (string.IsNullOrEmpty(newName))
{
throw PSTraceSource.NewArgumentException(nameof(newName));
}
_name = newName;
}
/// <summary>
/// Sets the provider of the drive to a new provider.
/// </summary>
/// <param name="newProvider">
/// The new provider for the drive.
/// </param>
/// <remarks>
/// This must be internal so that we allow the renaming of providers.
/// All drives must be associated with the new provider name and can
/// be changed using the Core Command API but not through a reference to the
/// drive object. More goes in to renaming a provider than just modifying
/// the provider in this class.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// If <paramref name="newProvider"/> is null.
/// </exception>
internal void SetProvider(ProviderInfo newProvider)
{
if (newProvider == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(newProvider));
}
_provider = newProvider;
}
/// <summary>
/// Traces the virtual drive.
/// </summary>
internal void Trace()
{
s_tracer.WriteLine(
"A drive was found:");
if (Name != null)
{
s_tracer.WriteLine(
"\tName: {0}",
Name);
}
if (Provider != null)
{
s_tracer.WriteLine(
"\tProvider: {0}",
Provider);
}
if (Root != null)
{
s_tracer.WriteLine(
"\tRoot: {0}",
Root);
}
if (CurrentLocation != null)
{
s_tracer.WriteLine(
"\tCWD: {0}",
CurrentLocation);
}
if (Description != null)
{
s_tracer.WriteLine(
"\tDescription: {0}",
Description);
}
}
/// <summary>
/// Compares this instance to the specified drive.
/// </summary>
/// <param name="drive">
/// A PSDriveInfo object to compare.
/// </param>
/// <returns>
/// A signed number indicating the relative values of this instance and object specified.
/// Return Value: Less than zero Meaning: This instance is less than object.
/// Return Value: Zero Meaning: This instance is equal to object.
/// Return Value: Greater than zero Meaning: This instance is greater than object or object is a null reference.
/// </returns>
public int CompareTo(PSDriveInfo drive)
{
#pragma warning disable 56506
if (drive == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(drive));
}
return string.Compare(Name, drive.Name, StringComparison.OrdinalIgnoreCase);
#pragma warning restore 56506
}
/// <summary>
/// Compares this instance to the specified object. The object must be a PSDriveInfo.
/// </summary>
/// <param name="obj">
/// An object to compare.
/// </param>
/// <returns>
/// A signed number indicating the relative values of this
/// instance and object specified.
/// </returns>
/// <exception cref="ArgumentException">
/// If <paramref name="obj"/> is not a PSDriveInfo instance.
/// </exception>
public int CompareTo(object obj)
{
PSDriveInfo drive = obj as PSDriveInfo;
if (drive == null)
{
ArgumentException e =
PSTraceSource.NewArgumentException(
nameof(obj),
SessionStateStrings.OnlyAbleToComparePSDriveInfo);
throw e;
}
return (CompareTo(drive));
}
/// <summary>
/// Compares this instance to the specified object.
/// </summary>
/// <param name="obj">
/// An object to compare.
/// </param>
/// <returns>
/// True if the drive names are equal, false otherwise.
/// </returns>
public override bool Equals(object obj)
{
if (obj is PSDriveInfo)
{
return CompareTo(obj) == 0;
}
else
{
return false;
}
}
/// <summary>
/// Compares this instance to the specified object.
/// </summary>
/// <param name="drive">
/// An object to compare.
/// </param>
/// <returns>
/// True if the drive names are equal, false otherwise.
/// </returns>
public bool Equals(PSDriveInfo drive)
{
return CompareTo(drive) == 0;
}
/// <summary>
/// Equality operator for the drive determines if the drives
/// are equal by having the same name.
/// </summary>
/// <param name="drive1">
/// The first object to compare to the second.
/// </param>
/// <param name="drive2">
/// The second object to compare to the first.
/// </param>
/// <returns>
/// True if the objects are PSDriveInfo objects and have the same name,
/// false otherwise.
/// </returns>
public static bool operator ==(PSDriveInfo drive1, PSDriveInfo drive2)
{
object drive1Object = drive1;
object drive2Object = drive2;
if ((drive1Object == null) == (drive2Object == null))
{
if (drive1Object != null)
{
return drive1.Equals(drive2);
}
return true;
}
else
{
return false;
}
}
/// <summary>
/// Inequality operator for the drive determines if the drives
/// are not equal by using the drive name.
/// </summary>
/// <param name="drive1">
/// The first object to compare to the second.
/// </param>
/// <param name="drive2">
/// The second object to compare to the first.
/// </param>
/// <returns>
/// True if the PSDriveInfo objects do not have the same name,
/// false otherwise.
/// </returns>
public static bool operator !=(PSDriveInfo drive1, PSDriveInfo drive2)
{
return !(drive1 == drive2);
}
/// <summary>
/// Compares the specified drives to determine if drive1 is less than
/// drive2.
/// </summary>
/// <param name="drive1">
/// The drive to determine if it is less than the other drive.
/// </param>
/// <param name="drive2">
/// The drive to compare drive1 against.
/// </param>
/// <returns>
/// True if the lexical comparison of drive1's name is less than drive2's name.
/// </returns>
public static bool operator <(PSDriveInfo drive1, PSDriveInfo drive2)
{
object drive1Object = drive1;
object drive2Object = drive2;
if (drive1Object == null)
{
return (drive2Object != null);
}
else
{
if (drive2Object == null)
{
// Since drive1 is not null and drive2 is, drive1 is greater than drive2
return false;
}
else
{
// Since drive1 and drive2 are not null use the CompareTo
return drive1.CompareTo(drive2) < 0;
}
}
}
/// <summary>
/// Compares the specified drives to determine if drive1 is greater than
/// drive2.
/// </summary>
/// <param name="drive1">
/// The drive to determine if it is greater than the other drive.
/// </param>
/// <param name="drive2">
/// The drive to compare drive1 against.
/// </param>
/// <returns>
/// True if the lexical comparison of drive1's name is greater than drive2's name.
/// </returns>
public static bool operator >(PSDriveInfo drive1, PSDriveInfo drive2)
{
object drive1Object = drive1;
object drive2Object = drive2;
if ((drive1Object == null))
{
// Since both drives are null, they are equal
// Since drive1 is null it is less than drive2 which is not null
return false;
}
else
{
if (drive2Object == null)
{
// Since drive1 is not null and drive2 is, drive1 is greater than drive2
return true;
}
else
{
// Since drive1 and drive2 are not null use the CompareTo
return drive1.CompareTo(drive2) > 0;
}
}
}
/// <summary>
/// Gets the hash code for this instance.
/// </summary>
/// <returns>The result of base.GetHashCode().</returns>
/// <!-- Override the base GetHashCode because the compiler complains
/// if you don't when you implement operator== and operator!= -->
public override int GetHashCode()
{
return base.GetHashCode();
}
private PSNoteProperty _noteProperty;
internal PSNoteProperty GetNotePropertyForProviderCmdlets(string name)
{
if (_noteProperty == null)
{
Interlocked.CompareExchange(ref _noteProperty,
new PSNoteProperty(name, this), null);
}
return _noteProperty;
}
}
}
| |
//-----------------------------------------------------------------------------
// Author : hiyohiyo
// Mail : hiyohiyo@crystalmark.info
// Web : http://openlibsys.org/
// License : The modified BSD license
//
// Copyright 2007-2009 OpenLibSys.org. All rights reserved.
//-----------------------------------------------------------------------------
// This is support library for WinRing0 1.3.x.
using System;
using System.Runtime.InteropServices;
namespace RoseHAService
{
public class Ols : IDisposable
{
const string dllNameX64 = "WinRing0x64.dll";
const string dllName = "WinRing0.dll";
// for this support library
public enum Status
{
NO_ERROR = 0,
DLL_NOT_FOUND = 1,
DLL_INCORRECT_VERSION = 2,
DLL_INITIALIZE_ERROR = 3,
}
// for WinRing0
public enum OlsDllStatus
{
OLS_DLL_NO_ERROR = 0,
OLS_DLL_UNSUPPORTED_PLATFORM = 1,
OLS_DLL_DRIVER_NOT_LOADED = 2,
OLS_DLL_DRIVER_NOT_FOUND = 3,
OLS_DLL_DRIVER_UNLOADED = 4,
OLS_DLL_DRIVER_NOT_LOADED_ON_NETWORK = 5,
OLS_DLL_UNKNOWN_ERROR = 9
}
// for WinRing0
public enum OlsDriverType
{
OLS_DRIVER_TYPE_UNKNOWN = 0,
OLS_DRIVER_TYPE_WIN_9X = 1,
OLS_DRIVER_TYPE_WIN_NT = 2,
OLS_DRIVER_TYPE_WIN_NT4 = 3, // Obsolete
OLS_DRIVER_TYPE_WIN_NT_X64 = 4,
OLS_DRIVER_TYPE_WIN_NT_IA64 = 5
}
// for WinRing0
public enum OlsErrorPci : uint
{
OLS_ERROR_PCI_BUS_NOT_EXIST = 0xE0000001,
OLS_ERROR_PCI_NO_DEVICE = 0xE0000002,
OLS_ERROR_PCI_WRITE_CONFIG = 0xE0000003,
OLS_ERROR_PCI_READ_CONFIG = 0xE0000004
}
// Bus Number, Device Number and Function Number to PCI Device Address
public uint PciBusDevFunc(uint bus, uint dev, uint func)
{
return ((bus&0xFF)<<8) | ((dev&0x1F)<<3) | (func&7);
}
// PCI Device Address to Bus Number
public uint PciGetBus(uint address)
{
return ((address>>8) & 0xFF);
}
// PCI Device Address to Device Number
public uint PciGetDev(uint address)
{
return ((address>>3) & 0x1F);
}
// PCI Device Address to Function Number
public uint PciGetFunc(uint address)
{
return (address&7);
}
[DllImport("kernel32")]
public extern static IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32", SetLastError = true)]
private static extern bool FreeLibrary(IntPtr hModule);
[DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = false)]
private static extern IntPtr GetProcAddress(IntPtr hModule, [MarshalAs(UnmanagedType.LPStr)] string lpProcName);
private IntPtr module = IntPtr.Zero;
private uint status = (uint)Status.NO_ERROR;
public Ols()
{
string fileName;
if (System.IntPtr.Size == 8)
{
fileName = dllNameX64;
}
else
{
fileName = dllName;
}
module = Ols.LoadLibrary(fileName);
if (module == IntPtr.Zero)
{
status = (uint)Status.DLL_NOT_FOUND;
}
else
{
GetDllStatus = (_GetDllStatus)GetDelegate("GetDllStatus", typeof(_GetDllStatus));
GetDllVersion = (_GetDllVersion)GetDelegate("GetDllVersion", typeof(_GetDllVersion));
GetDriverVersion = (_GetDriverVersion)GetDelegate("GetDriverVersion", typeof(_GetDriverVersion));
GetDriverType = (_GetDriverType)GetDelegate("GetDriverType", typeof(_GetDriverType));
InitializeOls = (_InitializeOls)GetDelegate("InitializeOls", typeof(_InitializeOls));
DeinitializeOls = (_DeinitializeOls)GetDelegate("DeinitializeOls", typeof(_DeinitializeOls));
IsCpuid = (_IsCpuid)GetDelegate("IsCpuid", typeof(_IsCpuid));
IsMsr = (_IsMsr)GetDelegate("IsMsr", typeof(_IsMsr));
IsTsc = (_IsTsc)GetDelegate("IsTsc", typeof(_IsTsc));
Hlt = (_Hlt)GetDelegate("Hlt", typeof(_Hlt));
HltTx = (_HltTx)GetDelegate("HltTx", typeof(_HltTx));
HltPx = (_HltPx)GetDelegate("HltPx", typeof(_HltPx));
Rdmsr = (_Rdmsr)GetDelegate("Rdmsr", typeof(_Rdmsr));
RdmsrTx = (_RdmsrTx)GetDelegate("RdmsrTx", typeof(_RdmsrTx));
RdmsrPx = (_RdmsrPx)GetDelegate("RdmsrPx", typeof(_RdmsrPx));
Wrmsr = (_Wrmsr)GetDelegate("Wrmsr", typeof(_Wrmsr));
WrmsrTx = (_WrmsrTx)GetDelegate("WrmsrTx", typeof(_WrmsrTx));
WrmsrPx = (_WrmsrPx)GetDelegate("WrmsrPx", typeof(_WrmsrPx));
Rdpmc = (_Rdpmc)GetDelegate("Rdpmc", typeof(_Rdpmc));
RdpmcTx = (_RdpmcTx)GetDelegate("RdpmcTx", typeof(_RdpmcTx));
RdpmcPx = (_RdpmcPx)GetDelegate("RdpmcPx", typeof(_RdpmcPx));
Cpuid = (_Cpuid)GetDelegate("Cpuid", typeof(_Cpuid));
CpuidTx = (_CpuidTx)GetDelegate("CpuidTx", typeof(_CpuidTx));
CpuidPx = (_CpuidPx)GetDelegate("CpuidPx", typeof(_CpuidPx));
Rdtsc = (_Rdtsc)GetDelegate("Rdtsc", typeof(_Rdtsc));
RdtscTx = (_RdtscTx)GetDelegate("RdtscTx", typeof(_RdtscTx));
RdtscPx = (_RdtscPx)GetDelegate("RdtscPx", typeof(_RdtscPx));
ReadIoPortByte = (_ReadIoPortByte)GetDelegate("ReadIoPortByte", typeof(_ReadIoPortByte));
ReadIoPortWord = (_ReadIoPortWord)GetDelegate("ReadIoPortWord", typeof(_ReadIoPortWord));
ReadIoPortDword = (_ReadIoPortDword)GetDelegate("ReadIoPortDword", typeof(_ReadIoPortDword));
ReadIoPortByteEx = (_ReadIoPortByteEx)GetDelegate("ReadIoPortByteEx", typeof(_ReadIoPortByteEx));
ReadIoPortWordEx = (_ReadIoPortWordEx)GetDelegate("ReadIoPortWordEx", typeof(_ReadIoPortWordEx));
ReadIoPortDwordEx = (_ReadIoPortDwordEx)GetDelegate("ReadIoPortDwordEx", typeof(_ReadIoPortDwordEx));
WriteIoPortByte = (_WriteIoPortByte)GetDelegate("WriteIoPortByte", typeof(_WriteIoPortByte));
WriteIoPortWord = (_WriteIoPortWord)GetDelegate("WriteIoPortWord", typeof(_WriteIoPortWord));
WriteIoPortDword = (_WriteIoPortDword)GetDelegate("WriteIoPortDword", typeof(_WriteIoPortDword));
WriteIoPortByteEx = (_WriteIoPortByteEx)GetDelegate("WriteIoPortByteEx", typeof(_WriteIoPortByteEx));
WriteIoPortWordEx = (_WriteIoPortWordEx)GetDelegate("WriteIoPortWordEx", typeof(_WriteIoPortWordEx));
WriteIoPortDwordEx = (_WriteIoPortDwordEx)GetDelegate("WriteIoPortDwordEx", typeof(_WriteIoPortDwordEx));
SetPciMaxBusIndex = (_SetPciMaxBusIndex)GetDelegate("SetPciMaxBusIndex", typeof(_SetPciMaxBusIndex));
ReadPciConfigByte = (_ReadPciConfigByte)GetDelegate("ReadPciConfigByte", typeof(_ReadPciConfigByte));
ReadPciConfigWord = (_ReadPciConfigWord)GetDelegate("ReadPciConfigWord", typeof(_ReadPciConfigWord));
ReadPciConfigDword = (_ReadPciConfigDword)GetDelegate("ReadPciConfigDword", typeof(_ReadPciConfigDword));
ReadPciConfigByteEx = (_ReadPciConfigByteEx)GetDelegate("ReadPciConfigByteEx", typeof(_ReadPciConfigByteEx));
ReadPciConfigWordEx = (_ReadPciConfigWordEx)GetDelegate("ReadPciConfigWordEx", typeof(_ReadPciConfigWordEx));
ReadPciConfigDwordEx = (_ReadPciConfigDwordEx)GetDelegate("ReadPciConfigDwordEx", typeof(_ReadPciConfigDwordEx));
WritePciConfigByte = (_WritePciConfigByte)GetDelegate("WritePciConfigByte", typeof(_WritePciConfigByte));
WritePciConfigWord = (_WritePciConfigWord)GetDelegate("WritePciConfigWord", typeof(_WritePciConfigWord));
WritePciConfigDword = (_WritePciConfigDword)GetDelegate("WritePciConfigDword", typeof(_WritePciConfigDword));
WritePciConfigByteEx = (_WritePciConfigByteEx)GetDelegate("WritePciConfigByteEx", typeof(_WritePciConfigByteEx));
WritePciConfigWordEx = (_WritePciConfigWordEx)GetDelegate("WritePciConfigWordEx", typeof(_WritePciConfigWordEx));
WritePciConfigDwordEx = (_WritePciConfigDwordEx)GetDelegate("WritePciConfigDwordEx", typeof(_WritePciConfigDwordEx));
FindPciDeviceById = (_FindPciDeviceById)GetDelegate("FindPciDeviceById", typeof(_FindPciDeviceById));
FindPciDeviceByClass = (_FindPciDeviceByClass)GetDelegate("FindPciDeviceByClass", typeof(_FindPciDeviceByClass));
#if _PHYSICAL_MEMORY_SUPPORT
ReadDmiMemory = (_ReadDmiMemory)GetDelegate("ReadDmiMemory", typeof(_ReadDmiMemory));
ReadPhysicalMemory = (_ReadPhysicalMemory)GetDelegate("ReadPhysicalMemory", typeof(_ReadPhysicalMemory));
WritePhysicalMemory = (_WritePhysicalMemory)GetDelegate("WritePhysicalMemory", typeof(_WritePhysicalMemory));
#endif
if (! (
GetDllStatus != null
&& GetDllVersion != null
&& GetDriverVersion != null
&& GetDriverType != null
&& InitializeOls != null
&& DeinitializeOls != null
&& IsCpuid != null
&& IsMsr != null
&& IsTsc != null
&& Hlt != null
&& HltTx != null
&& HltPx != null
&& Rdmsr != null
&& RdmsrTx != null
&& RdmsrPx != null
&& Wrmsr != null
&& WrmsrTx != null
&& WrmsrPx != null
&& Rdpmc != null
&& RdpmcTx != null
&& RdpmcPx != null
&& Cpuid != null
&& CpuidTx != null
&& CpuidPx != null
&& Rdtsc != null
&& RdtscTx != null
&& RdtscPx != null
&& ReadIoPortByte != null
&& ReadIoPortWord != null
&& ReadIoPortDword != null
&& ReadIoPortByteEx != null
&& ReadIoPortWordEx != null
&& ReadIoPortDwordEx != null
&& WriteIoPortByte != null
&& WriteIoPortWord != null
&& WriteIoPortDword != null
&& WriteIoPortByteEx != null
&& WriteIoPortWordEx != null
&& WriteIoPortDwordEx != null
&& SetPciMaxBusIndex != null
&& ReadPciConfigByte != null
&& ReadPciConfigWord != null
&& ReadPciConfigDword != null
&& ReadPciConfigByteEx != null
&& ReadPciConfigWordEx != null
&& ReadPciConfigDwordEx != null
&& WritePciConfigByte != null
&& WritePciConfigWord != null
&& WritePciConfigDword != null
&& WritePciConfigByteEx != null
&& WritePciConfigWordEx != null
&& WritePciConfigDwordEx != null
&& FindPciDeviceById != null
&& FindPciDeviceByClass != null
#if _PHYSICAL_MEMORY_SUPPORT
&& ReadDmiMemory != null
&& ReadPhysicalMemory != null
&& WritePhysicalMemory != null
#endif
))
{
status = (uint)Status.DLL_INCORRECT_VERSION;
}
if (InitializeOls() == 0)
{
status = (uint)Status.DLL_INITIALIZE_ERROR;
}
}
}
public uint GetStatus()
{
return status;
}
public void Dispose()
{
if (module != IntPtr.Zero)
{
DeinitializeOls();
Ols.FreeLibrary(module);
module = IntPtr.Zero;
}
}
public Delegate GetDelegate(string procName, Type delegateType)
{
IntPtr ptr = GetProcAddress(module, procName);
if (ptr != IntPtr.Zero)
{
Delegate d = Marshal.GetDelegateForFunctionPointer(ptr, delegateType);
return d;
}
int result = Marshal.GetHRForLastWin32Error();
throw Marshal.GetExceptionForHR(result);
}
//-----------------------------------------------------------------------------
// DLL Information
//-----------------------------------------------------------------------------
public delegate uint _GetDllStatus();
public delegate uint _GetDllVersion(ref byte major, ref byte minor, ref byte revision, ref byte release);
public delegate uint _GetDriverVersion(ref byte major, ref byte minor, ref byte revision, ref byte release);
public delegate uint _GetDriverType();
public delegate int _InitializeOls();
public delegate void _DeinitializeOls();
public _GetDllStatus GetDllStatus = null;
public _GetDriverType GetDriverType = null;
public _GetDllVersion GetDllVersion = null;
public _GetDriverVersion GetDriverVersion = null;
public _InitializeOls InitializeOls = null;
public _DeinitializeOls DeinitializeOls = null;
//-----------------------------------------------------------------------------
// CPU
//-----------------------------------------------------------------------------
public delegate int _IsCpuid();
public delegate int _IsMsr();
public delegate int _IsTsc();
public delegate int _Hlt();
public delegate int _HltTx(UIntPtr threadAffinityMask);
public delegate int _HltPx(UIntPtr processAffinityMask);
public delegate int _Rdmsr(uint index, ref uint eax, ref uint edx);
public delegate int _RdmsrTx(uint index, ref uint eax, ref uint edx, UIntPtr threadAffinityMask);
public delegate int _RdmsrPx(uint index, ref uint eax, ref uint edx, UIntPtr processAffinityMask);
public delegate int _Wrmsr(uint index, uint eax, uint edx);
public delegate int _WrmsrTx(uint index, uint eax, uint edx, UIntPtr threadAffinityMask);
public delegate int _WrmsrPx(uint index, uint eax, uint edx, UIntPtr processAffinityMask);
public delegate int _Rdpmc(uint index, ref uint eax, ref uint edx);
public delegate int _RdpmcTx(uint index, ref uint eax, ref uint edx, UIntPtr threadAffinityMask);
public delegate int _RdpmcPx(uint index, ref uint eax, ref uint edx, UIntPtr processAffinityMask);
public delegate int _Cpuid(uint index, ref uint eax, ref uint ebx, ref uint ecx, ref uint edx);
public delegate int _CpuidTx(uint index, ref uint eax, ref uint ebx, ref uint ecx, ref uint edx, UIntPtr threadAffinityMask);
public delegate int _CpuidPx(uint index, ref uint eax, ref uint ebx, ref uint ecx, ref uint edx, UIntPtr processAffinityMask);
public delegate int _Rdtsc(ref uint eax, ref uint edx);
public delegate int _RdtscTx(ref uint eax, ref uint edx, UIntPtr threadAffinityMask);
public delegate int _RdtscPx(ref uint eax, ref uint edx, UIntPtr processAffinityMask);
public _IsCpuid IsCpuid = null;
public _IsMsr IsMsr = null;
public _IsTsc IsTsc = null;
public _Hlt Hlt = null;
public _HltTx HltTx = null;
public _HltPx HltPx = null;
public _Rdmsr Rdmsr = null;
public _RdmsrTx RdmsrTx = null;
public _RdmsrPx RdmsrPx = null;
public _Wrmsr Wrmsr = null;
public _WrmsrTx WrmsrTx = null;
public _WrmsrPx WrmsrPx = null;
public _Rdpmc Rdpmc = null;
public _RdpmcTx RdpmcTx = null;
public _RdpmcPx RdpmcPx = null;
public _Cpuid Cpuid = null;
public _CpuidTx CpuidTx = null;
public _CpuidPx CpuidPx = null;
public _Rdtsc Rdtsc = null;
public _RdtscTx RdtscTx = null;
public _RdtscPx RdtscPx = null;
//-----------------------------------------------------------------------------
// I/O
//-----------------------------------------------------------------------------
public delegate byte _ReadIoPortByte(ushort port);
public delegate ushort _ReadIoPortWord(ushort port);
public delegate uint _ReadIoPortDword(ushort port);
public _ReadIoPortByte ReadIoPortByte;
public _ReadIoPortWord ReadIoPortWord;
public _ReadIoPortDword ReadIoPortDword;
public delegate int _ReadIoPortByteEx(ushort port, ref byte value);
public delegate int _ReadIoPortWordEx(ushort port, ref ushort value);
public delegate int _ReadIoPortDwordEx(ushort port, ref uint value);
public _ReadIoPortByteEx ReadIoPortByteEx;
public _ReadIoPortWordEx ReadIoPortWordEx;
public _ReadIoPortDwordEx ReadIoPortDwordEx;
public delegate void _WriteIoPortByte(ushort port, byte value);
public delegate void _WriteIoPortWord(ushort port, ushort value);
public delegate void _WriteIoPortDword(ushort port, uint value);
public _WriteIoPortByte WriteIoPortByte;
public _WriteIoPortWord WriteIoPortWord;
public _WriteIoPortDword WriteIoPortDword;
public delegate int _WriteIoPortByteEx(ushort port, byte value);
public delegate int _WriteIoPortWordEx(ushort port, ushort value);
public delegate int _WriteIoPortDwordEx(ushort port, uint value);
public _WriteIoPortByteEx WriteIoPortByteEx;
public _WriteIoPortWordEx WriteIoPortWordEx;
public _WriteIoPortDwordEx WriteIoPortDwordEx;
//-----------------------------------------------------------------------------
// PCI
//-----------------------------------------------------------------------------
public delegate void _SetPciMaxBusIndex(byte max);
public _SetPciMaxBusIndex SetPciMaxBusIndex;
public delegate byte _ReadPciConfigByte(uint pciAddress, byte regAddress);
public delegate ushort _ReadPciConfigWord(uint pciAddress, byte regAddress);
public delegate uint _ReadPciConfigDword(uint pciAddress, byte regAddress);
public _ReadPciConfigByte ReadPciConfigByte;
public _ReadPciConfigWord ReadPciConfigWord;
public _ReadPciConfigDword ReadPciConfigDword;
public delegate int _ReadPciConfigByteEx(uint pciAddress, uint regAddress, ref byte value);
public delegate int _ReadPciConfigWordEx(uint pciAddress, uint regAddress, ref ushort value);
public delegate int _ReadPciConfigDwordEx(uint pciAddress, uint regAddress, ref uint value);
public _ReadPciConfigByteEx ReadPciConfigByteEx;
public _ReadPciConfigWordEx ReadPciConfigWordEx;
public _ReadPciConfigDwordEx ReadPciConfigDwordEx;
public delegate void _WritePciConfigByte(uint pciAddress, byte regAddress, byte value);
public delegate void _WritePciConfigWord(uint pciAddress, byte regAddress, ushort value);
public delegate void _WritePciConfigDword(uint pciAddress, byte regAddress, uint value);
public _WritePciConfigByte WritePciConfigByte;
public _WritePciConfigWord WritePciConfigWord;
public _WritePciConfigDword WritePciConfigDword;
public delegate int _WritePciConfigByteEx(uint pciAddress, uint regAddress, byte value);
public delegate int _WritePciConfigWordEx(uint pciAddress, uint regAddress, ushort value);
public delegate int _WritePciConfigDwordEx(uint pciAddress, uint regAddress, uint value);
public _WritePciConfigByteEx WritePciConfigByteEx;
public _WritePciConfigWordEx WritePciConfigWordEx;
public _WritePciConfigDwordEx WritePciConfigDwordEx;
public delegate uint _FindPciDeviceById(ushort vendorId, ushort deviceId, byte index);
public delegate uint _FindPciDeviceByClass(byte baseClass, byte subClass, byte programIf, byte index);
public _FindPciDeviceById FindPciDeviceById;
public _FindPciDeviceByClass FindPciDeviceByClass;
//-----------------------------------------------------------------------------
// Physical Memory (unsafe)
//-----------------------------------------------------------------------------
#if _PHYSICAL_MEMORY_SUPPORT
public unsafe delegate uint _ReadDmiMemory(byte* buffer, uint count, uint unitSize);
public _ReadDmiMemory ReadDmiMemory;
public unsafe delegate uint _ReadPhysicalMemory(UIntPtr address, byte* buffer, uint count, uint unitSize);
public unsafe delegate uint _WritePhysicalMemory(UIntPtr address, byte* buffer, uint count, uint unitSize);
public _ReadPhysicalMemory ReadPhysicalMemory;
public _WritePhysicalMemory WritePhysicalMemory;
#endif
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Commencement.Core.Domain;
using Commencement.Tests.Core;
using Commencement.Tests.Core.Extensions;
using Commencement.Tests.Core.Helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using FluentNHibernate.Testing;
using UCDArch.Core.PersistanceSupport;
using UCDArch.Data.NHibernate;
using UCDArch.Testing.Extensions;
namespace Commencement.Tests.Repositories
{
/// <summary>
/// Entity Name: EmailQueue
/// LookupFieldName: Subject
/// </summary>
[TestClass]
public class EmailQueueRepositoryTests : AbstractRepositoryTests<EmailQueue, int, EmailQueueMap>
{
/// <summary>
/// Gets or sets the EmailQueue repository.
/// </summary>
/// <value>The EmailQueue repository.</value>
public IRepository<EmailQueue> EmailQueueRepository { get; set; }
public IRepositoryWithTypedId<Student, Guid> StudentRepository;
#region Init and Overrides
/// <summary>
/// Initializes a new instance of the <see cref="EmailQueueRepositoryTests"/> class.
/// </summary>
public EmailQueueRepositoryTests()
{
EmailQueueRepository = new Repository<EmailQueue>();
StudentRepository = new RepositoryWithTypedId<Student, Guid>();
}
/// <summary>
/// Gets the valid entity of type T
/// </summary>
/// <param name="counter">The counter.</param>
/// <returns>A valid entity of type T</returns>
protected override EmailQueue GetValid(int? counter)
{
var rtValue = CreateValidEntities.EmailQueue(counter);
rtValue.Student = StudentRepository.Queryable.First();
rtValue.Template = Repository.OfType<Template>().Queryable.First();
return rtValue;
}
/// <summary>
/// A Query which will return a single record
/// </summary>
/// <param name="numberAtEnd"></param>
/// <returns></returns>
protected override IQueryable<EmailQueue> GetQuery(int numberAtEnd)
{
return EmailQueueRepository.Queryable.Where(a => a.Subject.EndsWith(numberAtEnd.ToString()));
}
/// <summary>
/// A way to compare the entities that were read.
/// For example, this would have the assert.AreEqual("Comment" + counter, entity.Comment);
/// </summary>
/// <param name="entity"></param>
/// <param name="counter"></param>
protected override void FoundEntityComparison(EmailQueue entity, int counter)
{
Assert.AreEqual("Subject" + counter, entity.Subject);
}
/// <summary>
/// Updates , compares, restores.
/// </summary>
/// <param name="entity">The entity.</param>
/// <param name="action">The action.</param>
protected override void UpdateUtility(EmailQueue entity, ARTAction action)
{
const string updateValue = "Updated";
switch (action)
{
case ARTAction.Compare:
Assert.AreEqual(updateValue, entity.Subject);
break;
case ARTAction.Restore:
entity.Subject = RestoreValue;
break;
case ARTAction.Update:
RestoreValue = entity.Subject;
entity.Subject = updateValue;
break;
}
}
/// <summary>
/// Loads the data.
/// </summary>
protected override void LoadData()
{
Repository.OfType<Template>().DbContext.BeginTransaction();
LoadStudent(3);
LoadTemplateType(1);
LoadTermCode(1);
LoadCeremony(1);
LoadTemplate(3);
Repository.OfType<Template>().DbContext.BeginTransaction();
EmailQueueRepository.DbContext.BeginTransaction();
LoadRecords(5);
EmailQueueRepository.DbContext.CommitTransaction();
}
#endregion Init and Overrides
#region Student Tests
#region Invalid Tests
/// <summary>
/// Tests the Student with A value of null does not save.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ApplicationException))]
public void TestStudentWithAValueOfNullDoesNotSave()
{
EmailQueue emailQueue = null;
try
{
#region Arrange
emailQueue = GetValid(9);
emailQueue.Student = null;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception)
{
Assert.IsNotNull(emailQueue);
Assert.AreEqual(emailQueue.Student, null);
var results = emailQueue.ValidationResults().AsMessageList();
results.AssertErrorsAre("Student: may not be null");
Assert.IsTrue(emailQueue.IsTransient());
Assert.IsFalse(emailQueue.IsValid());
throw;
}
}
#endregion Invalid Tests
#region Valid Tests
[TestMethod]
public void TestEmailQueueWithAnExistingStudentSaves()
{
#region Arrange
var emailQueue = GetValid(9);
emailQueue.Student = StudentRepository.Queryable.Where(a => a.Id == SpecificGuid.GetGuid(2)).Single();
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.AreEqual("Pidm2", emailQueue.Student.Pidm);
Assert.IsFalse(emailQueue.IsTransient());
Assert.IsTrue(emailQueue.IsValid());
#endregion Assert
}
#endregion Valid Tests
#region Cascade Tests
[TestMethod]
public void TestDeleteEmailQueueDoesNotCascadeToStudent()
{
#region Arrange
var emailQueue = GetValid(9);
var student = StudentRepository.Queryable.Where(a => a.Id == SpecificGuid.GetGuid(2)).Single();
emailQueue.Student = student;
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
var saveId = emailQueue.Id;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.Remove(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
NHibernateSessionManager.Instance.GetSession().Evict(student);
Assert.IsNull(EmailQueueRepository.GetNullableById(saveId));
Assert.IsNotNull(StudentRepository.Queryable.Where(a => a.Id == SpecificGuid.GetGuid(2)).Single());
#endregion Assert
}
[TestMethod]
public void TestNewEmailQueueWithNewStudentDoesNotCascadeSave()
{
#region Arrange
var count = StudentRepository.Queryable.Count();
Assert.IsTrue(count > 0);
var emailQueue = GetValid(9);
emailQueue.Student = CreateValidEntities.Student(9);
var saveId = emailQueue.Student.Id;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
//var saveEmailQueueid = emailQueue.Id;
#endregion Act
#region Assert
Assert.IsFalse(emailQueue.IsTransient());
Assert.IsTrue(emailQueue.IsValid());
Assert.AreEqual(count, StudentRepository.Queryable.Count());
Assert.IsFalse(StudentRepository.Queryable.Where(a => a.Id == saveId).Any());
//NHibernateSessionManager.Instance.GetSession().Evict(emailQueue);
//emailQueue = EmailQueueRepository.GetById(saveEmailQueueid);
#endregion Assert
}
#endregion Cascade Tests
#endregion Student Tests
#region Created Tests
/// <summary>
/// Tests the Created with past date will save.
/// </summary>
[TestMethod]
public void TestCreatedWithPastDateWillSave()
{
#region Arrange
var compareDate = DateTime.Now.AddDays(-10);
EmailQueue record = GetValid(99);
record.Created = compareDate;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(record);
EmailQueueRepository.DbContext.CommitChanges();
#endregion Act
#region Assert
Assert.IsFalse(record.IsTransient());
Assert.IsTrue(record.IsValid());
Assert.AreEqual(compareDate, record.Created);
#endregion Assert
}
/// <summary>
/// Tests the Created with current date date will save.
/// </summary>
[TestMethod]
public void TestCreatedWithCurrentDateDateWillSave()
{
#region Arrange
var compareDate = DateTime.Now;
var record = GetValid(99);
record.Created = compareDate;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(record);
EmailQueueRepository.DbContext.CommitChanges();
#endregion Act
#region Assert
Assert.IsFalse(record.IsTransient());
Assert.IsTrue(record.IsValid());
Assert.AreEqual(compareDate, record.Created);
#endregion Assert
}
/// <summary>
/// Tests the Created with future date date will save.
/// </summary>
[TestMethod]
public void TestCreatedWithFutureDateDateWillSave()
{
#region Arrange
var compareDate = DateTime.Now.AddDays(15);
var record = GetValid(99);
record.Created = compareDate;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(record);
EmailQueueRepository.DbContext.CommitChanges();
#endregion Act
#region Assert
Assert.IsFalse(record.IsTransient());
Assert.IsTrue(record.IsValid());
Assert.AreEqual(compareDate, record.Created);
#endregion Assert
}
#endregion Created Tests
#region Pending Tests
/// <summary>
/// Tests the Pending is false saves.
/// </summary>
[TestMethod]
public void TestPendingIsFalseSaves()
{
#region Arrange
EmailQueue emailQueue = GetValid(9);
emailQueue.Pending = false;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(emailQueue.Pending);
Assert.IsFalse(emailQueue.IsTransient());
Assert.IsTrue(emailQueue.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the Pending is true saves.
/// </summary>
[TestMethod]
public void TestPendingIsTrueSaves()
{
#region Arrange
var emailQueue = GetValid(9);
emailQueue.Pending = true;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsTrue(emailQueue.Pending);
Assert.IsFalse(emailQueue.IsTransient());
Assert.IsTrue(emailQueue.IsValid());
#endregion Assert
}
#endregion Pending Tests
#region SentDateTime Tests
[TestMethod]
public void TestSentDateTimeWithNullValueWillSave()
{
#region Arrange
EmailQueue record = GetValid(99);
record.SentDateTime = null;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(record);
EmailQueueRepository.DbContext.CommitChanges();
#endregion Act
#region Assert
Assert.IsFalse(record.IsTransient());
Assert.IsTrue(record.IsValid());
Assert.IsNull(record.SentDateTime);
#endregion Assert
}
/// <summary>
/// Tests the SentDateTime with past date will save.
/// </summary>
[TestMethod]
public void TestSentDateTimeWithPastDateWillSave()
{
#region Arrange
var compareDate = DateTime.Now.AddDays(-10);
EmailQueue record = GetValid(99);
record.SentDateTime = compareDate;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(record);
EmailQueueRepository.DbContext.CommitChanges();
#endregion Act
#region Assert
Assert.IsFalse(record.IsTransient());
Assert.IsTrue(record.IsValid());
Assert.AreEqual(compareDate, record.SentDateTime);
#endregion Assert
}
/// <summary>
/// Tests the SentDateTime with current date date will save.
/// </summary>
[TestMethod]
public void TestSentDateTimeWithCurrentDateDateWillSave()
{
#region Arrange
var compareDate = DateTime.Now;
var record = GetValid(99);
record.SentDateTime = compareDate;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(record);
EmailQueueRepository.DbContext.CommitChanges();
#endregion Act
#region Assert
Assert.IsFalse(record.IsTransient());
Assert.IsTrue(record.IsValid());
Assert.AreEqual(compareDate, record.SentDateTime);
#endregion Assert
}
/// <summary>
/// Tests the SentDateTime with future date date will save.
/// </summary>
[TestMethod]
public void TestSentDateTimeWithFutureDateDateWillSave()
{
#region Arrange
var compareDate = DateTime.Now.AddDays(15);
var record = GetValid(99);
record.SentDateTime = compareDate;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(record);
EmailQueueRepository.DbContext.CommitChanges();
#endregion Act
#region Assert
Assert.IsFalse(record.IsTransient());
Assert.IsTrue(record.IsValid());
Assert.AreEqual(compareDate, record.SentDateTime);
#endregion Assert
}
#endregion SentDateTime Tests
#region Template Tests
#region Invalid Tests
/// <summary>
/// Tests the Template with A value of null does not save.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ApplicationException))]
public void TestTemplateWithAValueOfNullDoesNotSave()
{
EmailQueue emailQueue = null;
try
{
#region Arrange
emailQueue = GetValid(9);
emailQueue.Template = null;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception)
{
Assert.IsNotNull(emailQueue);
Assert.AreEqual(emailQueue.Template, null);
var results = emailQueue.ValidationResults().AsMessageList();
results.AssertErrorsAre("Template: may not be null");
Assert.IsTrue(emailQueue.IsTransient());
Assert.IsFalse(emailQueue.IsValid());
throw;
}
}
[TestMethod]
[ExpectedException(typeof(NHibernate.TransientObjectException))]
public void TestTemplateWithANewValueDoesNotSave()
{
EmailQueue emailQueue = null;
try
{
#region Arrange
emailQueue = GetValid(9);
emailQueue.Template = CreateValidEntities.Template(1);
emailQueue.Template.Ceremony = Repository.OfType<Ceremony>().Queryable.First();
emailQueue.Template.TemplateType = Repository.OfType<TemplateType>().Queryable.First();
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception ex)
{
Assert.IsNotNull(emailQueue);
Assert.IsNotNull(ex);
Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing. Type: Commencement.Core.Domain.Template, Entity: Commencement.Core.Domain.Template", ex.Message);
throw;
}
}
#endregion Invalid Tests
#region Valid Tests
[TestMethod]
public void TestEmailQueueWithAnExistingTemplateSaves()
{
#region Arrange
var emailQueue = GetValid(9);
emailQueue.Template = Repository.OfType<Template>().GetNullableById(2);
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.AreEqual("Subject2", emailQueue.Template.Subject);
Assert.IsFalse(emailQueue.IsTransient());
Assert.IsTrue(emailQueue.IsValid());
#endregion Assert
}
#endregion Valid Tests
#region Cascade Tests
[TestMethod]
public void TestDeleteEmailQueueDoesNotCascadeToTemplate()
{
#region Arrange
var emailQueue = GetValid(9);
var template = Repository.OfType<Template>().GetNullableById(2);
Assert.IsNotNull(template);
emailQueue.Template = template;
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
var saveId = emailQueue.Id;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.Remove(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
NHibernateSessionManager.Instance.GetSession().Evict(template);
Assert.IsNull(EmailQueueRepository.GetNullableById(saveId));
Assert.IsNotNull(Repository.OfType<Template>().GetNullableById(2));
#endregion Assert
}
#endregion Cascade Tests
#endregion Template Tests
#region Subject Tests
#region Invalid Tests
/// <summary>
/// Tests the Subject with null value does not save.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ApplicationException))]
public void TestSubjectWithNullValueDoesNotSave()
{
EmailQueue emailQueue = null;
try
{
#region Arrange
emailQueue = GetValid(9);
emailQueue.Subject = null;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception)
{
Assert.IsNotNull(emailQueue);
var results = emailQueue.ValidationResults().AsMessageList();
results.AssertErrorsAre("Subject: may not be null or empty");
Assert.IsTrue(emailQueue.IsTransient());
Assert.IsFalse(emailQueue.IsValid());
throw;
}
}
/// <summary>
/// Tests the Subject with empty string does not save.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ApplicationException))]
public void TestSubjectWithEmptyStringDoesNotSave()
{
EmailQueue emailQueue = null;
try
{
#region Arrange
emailQueue = GetValid(9);
emailQueue.Subject = string.Empty;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception)
{
Assert.IsNotNull(emailQueue);
var results = emailQueue.ValidationResults().AsMessageList();
results.AssertErrorsAre("Subject: may not be null or empty");
Assert.IsTrue(emailQueue.IsTransient());
Assert.IsFalse(emailQueue.IsValid());
throw;
}
}
/// <summary>
/// Tests the Subject with spaces only does not save.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ApplicationException))]
public void TestSubjectWithSpacesOnlyDoesNotSave()
{
EmailQueue emailQueue = null;
try
{
#region Arrange
emailQueue = GetValid(9);
emailQueue.Subject = " ";
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception)
{
Assert.IsNotNull(emailQueue);
var results = emailQueue.ValidationResults().AsMessageList();
results.AssertErrorsAre("Subject: may not be null or empty");
Assert.IsTrue(emailQueue.IsTransient());
Assert.IsFalse(emailQueue.IsValid());
throw;
}
}
/// <summary>
/// Tests the Subject with too long value does not save.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ApplicationException))]
public void TestSubjectWithTooLongValueDoesNotSave()
{
EmailQueue emailQueue = null;
try
{
#region Arrange
emailQueue = GetValid(9);
emailQueue.Subject = "x".RepeatTimes((100 + 1));
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception)
{
Assert.IsNotNull(emailQueue);
Assert.AreEqual(100 + 1, emailQueue.Subject.Length);
var results = emailQueue.ValidationResults().AsMessageList();
results.AssertErrorsAre("Subject: length must be between 0 and 100");
Assert.IsTrue(emailQueue.IsTransient());
Assert.IsFalse(emailQueue.IsValid());
throw;
}
}
#endregion Invalid Tests
#region Valid Tests
/// <summary>
/// Tests the Subject with one character saves.
/// </summary>
[TestMethod]
public void TestSubjectWithOneCharacterSaves()
{
#region Arrange
var emailQueue = GetValid(9);
emailQueue.Subject = "x";
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(emailQueue.IsTransient());
Assert.IsTrue(emailQueue.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the Subject with long value saves.
/// </summary>
[TestMethod]
public void TestSubjectWithLongValueSaves()
{
#region Arrange
var emailQueue = GetValid(9);
emailQueue.Subject = "x".RepeatTimes(100);
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.AreEqual(100, emailQueue.Subject.Length);
Assert.IsFalse(emailQueue.IsTransient());
Assert.IsTrue(emailQueue.IsValid());
#endregion Assert
}
#endregion Valid Tests
#endregion Subject Tests
#region Body Tests
#region Invalid Tests
/// <summary>
/// Tests the Body with null value does not save.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ApplicationException))]
public void TestBodyWithNullValueDoesNotSave()
{
EmailQueue emailQueue = null;
try
{
#region Arrange
emailQueue = GetValid(9);
emailQueue.Body = null;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception)
{
Assert.IsNotNull(emailQueue);
var results = emailQueue.ValidationResults().AsMessageList();
results.AssertErrorsAre("Body: may not be null or empty");
Assert.IsTrue(emailQueue.IsTransient());
Assert.IsFalse(emailQueue.IsValid());
throw;
}
}
/// <summary>
/// Tests the Body with empty string does not save.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ApplicationException))]
public void TestBodyWithEmptyStringDoesNotSave()
{
EmailQueue emailQueue = null;
try
{
#region Arrange
emailQueue = GetValid(9);
emailQueue.Body = string.Empty;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception)
{
Assert.IsNotNull(emailQueue);
var results = emailQueue.ValidationResults().AsMessageList();
results.AssertErrorsAre("Body: may not be null or empty");
Assert.IsTrue(emailQueue.IsTransient());
Assert.IsFalse(emailQueue.IsValid());
throw;
}
}
/// <summary>
/// Tests the Body with spaces only does not save.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ApplicationException))]
public void TestBodyWithSpacesOnlyDoesNotSave()
{
EmailQueue emailQueue = null;
try
{
#region Arrange
emailQueue = GetValid(9);
emailQueue.Body = " ";
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception)
{
Assert.IsNotNull(emailQueue);
var results = emailQueue.ValidationResults().AsMessageList();
results.AssertErrorsAre("Body: may not be null or empty");
Assert.IsTrue(emailQueue.IsTransient());
Assert.IsFalse(emailQueue.IsValid());
throw;
}
}
#endregion Invalid Tests
#region Valid Tests
/// <summary>
/// Tests the Body with one character saves.
/// </summary>
[TestMethod]
public void TestBodyWithOneCharacterSaves()
{
#region Arrange
var emailQueue = GetValid(9);
emailQueue.Body = "x";
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(emailQueue.IsTransient());
Assert.IsTrue(emailQueue.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the Body with long value saves.
/// </summary>
[TestMethod]
public void TestBodyWithLongValueSaves()
{
#region Arrange
var emailQueue = GetValid(9);
emailQueue.Body = "x".RepeatTimes(1000);
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.AreEqual(1000, emailQueue.Body.Length);
Assert.IsFalse(emailQueue.IsTransient());
Assert.IsTrue(emailQueue.IsValid());
#endregion Assert
}
#endregion Valid Tests
#endregion Body Tests
#region Immediate Tests
/// <summary>
/// Tests the Immediate is false saves.
/// </summary>
[TestMethod]
public void TestImmediateIsFalseSaves()
{
#region Arrange
EmailQueue emailQueue = GetValid(9);
emailQueue.Immediate = false;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(emailQueue.Immediate);
Assert.IsFalse(emailQueue.IsTransient());
Assert.IsTrue(emailQueue.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the Immediate is true saves.
/// </summary>
[TestMethod]
public void TestImmediateIsTrueSaves()
{
#region Arrange
var emailQueue = GetValid(9);
emailQueue.Immediate = true;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsTrue(emailQueue.Immediate);
Assert.IsFalse(emailQueue.IsTransient());
Assert.IsTrue(emailQueue.IsValid());
#endregion Assert
}
#endregion Immediate Tests
#region Registration Tests
#region Invalid Tests
[TestMethod]
[ExpectedException(typeof(NHibernate.TransientObjectException))]
public void TestRegistrationWithANewValueDoesNotSave()
{
EmailQueue emailQueue = null;
try
{
#region Arrange
Repository.OfType<State>().DbContext.BeginTransaction();
LoadState(1);
Repository.OfType<State>().DbContext.CommitTransaction();
emailQueue = GetValid(9);
emailQueue.Registration = CreateValidEntities.Registration(4);
emailQueue.Registration.State = Repository.OfType<State>().Queryable.First();
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception ex)
{
Assert.IsNotNull(emailQueue);
Assert.IsNotNull(ex);
Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing. Type: Commencement.Core.Domain.Registration, Entity: Commencement.Core.Domain.Registration", ex.Message);
throw;
}
}
#endregion Invalid Tests
#region Valid Tests
[TestMethod]
public void TestEmailQueueWithExistingRegistrationSaves()
{
#region Arrange
Repository.OfType<Registration>().DbContext.BeginTransaction();
LoadState(1);
LoadRegistrations(1);
Repository.OfType<Registration>().DbContext.CommitTransaction();
var emailQueue = GetValid(9);
emailQueue.Registration = Repository.OfType<Registration>().Queryable.First();
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.AreEqual("Address11", emailQueue.Registration.Address1);
Assert.IsFalse(emailQueue.IsTransient());
Assert.IsTrue(emailQueue.IsValid());
#endregion Assert
}
[TestMethod]
public void TestEmailQueueWithNullRegistrationSaves()
{
#region Arrange
var emailQueue = GetValid(9);
emailQueue.Registration = null;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsNull(emailQueue.Registration);
Assert.IsFalse(emailQueue.IsTransient());
Assert.IsTrue(emailQueue.IsValid());
#endregion Assert
}
#endregion Valid Tests
#region Cascade Tests
[TestMethod]
public void TestDeleteEmailQueueDoesNotCascadeToRegistration()
{
#region Arrange
Repository.OfType<Registration>().DbContext.BeginTransaction();
LoadState(1);
LoadRegistrations(3);
Repository.OfType<Registration>().DbContext.CommitTransaction();
var emailQueue = GetValid(9);
var registration = Repository.OfType<Registration>().GetNullableById(2);
Assert.IsNotNull(registration);
emailQueue.Registration = registration;
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
var saveId = emailQueue.Id;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.Remove(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
NHibernateSessionManager.Instance.GetSession().Evict(registration);
Assert.IsNull(EmailQueueRepository.GetNullableById(saveId));
Assert.IsNotNull(Repository.OfType<Registration>().GetNullableById(2));
#endregion Assert
}
#endregion Cascade Tests
#endregion Registration Tests
#region RegistrationParticipation Tests
#region Invalid Tests
[TestMethod]
[ExpectedException(typeof(NHibernate.TransientObjectException))]
public void TestRegistrationParticipationWithANewValueDoesNotSave()
{
EmailQueue emailQueue = null;
try
{
#region Arrange
emailQueue = GetValid(9);
emailQueue.RegistrationParticipation = CreateValidEntities.RegistrationParticipation(4);
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception ex)
{
Assert.IsNotNull(emailQueue);
Assert.IsNotNull(ex);
Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing. Type: Commencement.Core.Domain.RegistrationParticipation, Entity: Commencement.Core.Domain.RegistrationParticipation", ex.Message);
throw;
}
}
#endregion Invalid Tests
#region Valid Tests
[TestMethod]
public void TestEmailQueueWithANullRegistrationParticipationSaves()
{
#region Arrange
var emailQueue = GetValid(9);
emailQueue.RegistrationParticipation = null;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsNull(emailQueue.RegistrationParticipation);
Assert.IsFalse(emailQueue.IsTransient());
Assert.IsTrue(emailQueue.IsValid());
#endregion Assert
}
[TestMethod]
public void TestEmailQueueWithExistingRegistrationParticipationSaves()
{
#region Arrange
Repository.OfType<RegistrationParticipation>().DbContext.BeginTransaction();
LoadState(1);
LoadRegistrations(1);
//LoadTermCode(1);
LoadCeremony(1);
LoadMajorCode(1);
LoadRegistrationParticipations(3);
Repository.OfType<RegistrationParticipation>().DbContext.CommitTransaction();
var emailQueue = GetValid(9);
emailQueue.RegistrationParticipation = Repository.OfType<RegistrationParticipation>().Queryable.First();
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.AreEqual(1, emailQueue.RegistrationParticipation.Id);
Assert.IsFalse(emailQueue.IsTransient());
Assert.IsTrue(emailQueue.IsValid());
#endregion Assert
}
#endregion Valid Tests
#region Cascade Tests
[TestMethod]
public void TestDeleteEmailQueueDoesNotCascadeToRegistrationParticipation()
{
#region Arrange
Repository.OfType<RegistrationParticipation>().DbContext.BeginTransaction();
LoadCeremony(1);
LoadState(1);
LoadRegistrations(1);
LoadMajorCode(1);
LoadRegistrationParticipations(3);
Repository.OfType<RegistrationParticipation>().DbContext.CommitTransaction();
var emailQueue = GetValid(9);
var registrationParticipation = Repository.OfType<RegistrationParticipation>().GetNullableById(2);
Assert.IsNotNull(registrationParticipation);
emailQueue.RegistrationParticipation = registrationParticipation;
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
var saveId = emailQueue.Id;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.Remove(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
NHibernateSessionManager.Instance.GetSession().Evict(registrationParticipation);
Assert.IsNull(EmailQueueRepository.GetNullableById(saveId));
Assert.IsNotNull(Repository.OfType<RegistrationParticipation>().GetNullableById(2));
#endregion Assert
}
#endregion Cascade Tests
#endregion RegistrationParticipation Tests
#region RegistrationPetition Tests
#region Invalid Tests
[TestMethod]
[ExpectedException(typeof(NHibernate.TransientObjectException))]
public void TestRegistrationPetitionWithANewValueDoesNotSave()
{
EmailQueue emailQueue = null;
try
{
#region Arrange
Repository.OfType<RegistrationPetition>().DbContext.BeginTransaction();
LoadMajorCode(1);
LoadState(1);
LoadRegistrations(1);
Repository.OfType<RegistrationPetition>().DbContext.CommitTransaction();
emailQueue = GetValid(9);
emailQueue.RegistrationPetition = CreateValidEntities.RegistrationPetition(4);
emailQueue.RegistrationPetition.MajorCode = Repository.OfType<MajorCode>().Queryable.First();
emailQueue.RegistrationPetition.Registration = Repository.OfType<Registration>().Queryable.First();
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception ex)
{
Assert.IsNotNull(emailQueue);
Assert.IsNotNull(ex);
Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing. Type: Commencement.Core.Domain.RegistrationPetition, Entity: Commencement.Core.Domain.RegistrationPetition", ex.Message);
throw;
}
}
#endregion Invalid Tests
#region Valid Tests
[TestMethod]
public void TestEmailQueueWithANullRegistrationPetitionSaves()
{
#region Arrange
var emailQueue = GetValid(9);
emailQueue.RegistrationPetition = null;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsNull(emailQueue.RegistrationPetition);
Assert.IsFalse(emailQueue.IsTransient());
Assert.IsTrue(emailQueue.IsValid());
#endregion Assert
}
[TestMethod]
public void TestEmailQueueWithAnExistingRegistrationPetitionSaves()
{
#region Arrange
Repository.OfType<RegistrationPetition>().DbContext.BeginTransaction();
LoadMajorCode(1);
LoadState(1);
LoadRegistrations(1);
LoadRegistrationPetitions(3);
Repository.OfType<RegistrationPetition>().DbContext.CommitTransaction();
var emailQueue = GetValid(9);
emailQueue.RegistrationPetition = Repository.OfType<RegistrationPetition>().GetNullableById(2);
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.AreEqual("ExceptionReason2", Repository.OfType<RegistrationPetition>().GetNullableById(2).ExceptionReason);
Assert.IsFalse(emailQueue.IsTransient());
Assert.IsTrue(emailQueue.IsValid());
#endregion Assert
}
#endregion Valid Tests
#region Cascade Tests
[TestMethod]
public void TestDeleteEmailQueueDoesNotCascadeToRegistrationPetition()
{
#region Arrange
Repository.OfType<RegistrationPetition>().DbContext.BeginTransaction();
LoadMajorCode(1);
LoadState(1);
LoadRegistrations(1);
LoadRegistrationPetitions(3);
Repository.OfType<RegistrationPetition>().DbContext.CommitTransaction();
var emailQueue = GetValid(9);
var registrationPetition = Repository.OfType<RegistrationPetition>().GetNullableById(2);
Assert.IsNotNull(registrationPetition);
emailQueue.RegistrationPetition = registrationPetition;
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
var saveId = emailQueue.Id;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.Remove(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
NHibernateSessionManager.Instance.GetSession().Evict(registrationPetition);
Assert.IsNull(EmailQueueRepository.GetNullableById(saveId));
Assert.IsNotNull(Repository.OfType<RegistrationPetition>().GetNullableById(2));
#endregion Assert
}
#endregion Cascade Tests
#endregion RegistrationPetition Tests
#region ExtraTicketPetition Tests
#region Invalid Tests
[TestMethod]
[ExpectedException(typeof(NHibernate.TransientObjectException))]
public void TestExtraTicketPetitionWithANewValueDoesNotSave()
{
EmailQueue emailQueue = null;
try
{
#region Arrange
emailQueue = GetValid(9);
emailQueue.ExtraTicketPetition = CreateValidEntities.ExtraTicketPetition(4);
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception ex)
{
Assert.IsNotNull(emailQueue);
Assert.IsNotNull(ex);
Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing. Type: Commencement.Core.Domain.ExtraTicketPetition, Entity: Commencement.Core.Domain.ExtraTicketPetition", ex.Message);
throw;
}
}
#endregion Invalid Tests
#region Valid Tests
[TestMethod]
public void TestEmailQueueWithANullExtraTicketPetitionSaves()
{
#region Arrange
var emailQueue = GetValid(9);
emailQueue.ExtraTicketPetition = null;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsNull(emailQueue.ExtraTicketPetition);
Assert.IsFalse(emailQueue.IsTransient());
Assert.IsTrue(emailQueue.IsValid());
#endregion Assert
}
[TestMethod]
public void TestEmailQueueWithAnExistingExtraTicketPetitionSaves()
{
#region Arrange
Repository.OfType<ExtraTicketPetition>().DbContext.BeginTransaction();
LoadExtraTicketPetitions(3);
Repository.OfType<ExtraTicketPetition>().DbContext.CommitTransaction();
var emailQueue = GetValid(9);
emailQueue.ExtraTicketPetition = Repository.OfType<ExtraTicketPetition>().GetNullableById(2);
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.AreEqual("Reason2", emailQueue.ExtraTicketPetition.Reason);
Assert.IsFalse(emailQueue.IsTransient());
Assert.IsTrue(emailQueue.IsValid());
#endregion Assert
}
#endregion Valid Tests
#region Cascade Tests
[TestMethod]
public void TestDeleteEmailQueueDoesNotCascadeToExtraTicketPetition()
{
#region Arrange
Repository.OfType<ExtraTicketPetition>().DbContext.BeginTransaction();
LoadExtraTicketPetitions(3);
Repository.OfType<ExtraTicketPetition>().DbContext.CommitTransaction();
var emailQueue = GetValid(9);
var extraTicketPetition = Repository.OfType<ExtraTicketPetition>().GetNullableById(2);
Assert.IsNotNull(extraTicketPetition);
emailQueue.ExtraTicketPetition = extraTicketPetition;
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.EnsurePersistent(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
var saveId = emailQueue.Id;
#endregion Arrange
#region Act
EmailQueueRepository.DbContext.BeginTransaction();
EmailQueueRepository.Remove(emailQueue);
EmailQueueRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
NHibernateSessionManager.Instance.GetSession().Evict(extraTicketPetition);
Assert.IsNull(EmailQueueRepository.GetNullableById(saveId));
Assert.IsNotNull(Repository.OfType<ExtraTicketPetition>().GetNullableById(2));
#endregion Assert
}
#endregion Cascade Tests
#endregion ExtraTicketPetition Tests
#region Constructor Tests
[TestMethod]
public void TestConstructorWithNoParametersSetsExpectedValues()
{
#region Arrange
var record = new EmailQueue();
#endregion Arrange
#region Assert
Assert.AreEqual(DateTime.Now.Date, record.Created.Date);
Assert.IsTrue(record.Pending);
Assert.IsFalse(record.Immediate);
#endregion Assert
}
[TestMethod]
public void TestConstructorWithParametersSetsExpectedValues1()
{
#region Arrange
var record = new EmailQueue(CreateValidEntities.Student(7), CreateValidEntities.Template(8), "Sub", "Bod");
#endregion Arrange
#region Assert
Assert.AreEqual(DateTime.Now.Date, record.Created.Date);
Assert.IsTrue(record.Pending);
Assert.IsFalse(record.Immediate); // Default parameter
Assert.AreEqual("Pidm7", record.Student.Pidm);
Assert.AreEqual("Subject8", record.Template.Subject);
Assert.AreEqual("Sub", record.Subject);
Assert.AreEqual("Bod", record.Body);
#endregion Assert
}
[TestMethod]
public void TestConstructorWithParametersSetsExpectedValues2()
{
#region Arrange
var record = new EmailQueue(CreateValidEntities.Student(7), CreateValidEntities.Template(8), "Sub", "Bod", true);
#endregion Arrange
#region Assert
Assert.AreEqual(DateTime.Now.Date, record.Created.Date);
Assert.IsTrue(record.Pending);
Assert.IsTrue(record.Immediate); // Default parameter
Assert.AreEqual("Pidm7", record.Student.Pidm);
Assert.AreEqual("Subject8", record.Template.Subject);
Assert.AreEqual("Sub", record.Subject);
Assert.AreEqual("Bod", record.Body);
#endregion Assert
}
#endregion Constructor Tests
#region Fluent Mapping Tests
[TestMethod]
public void TestCanCorrectlyMapEmailQueue1()
{
#region Arrange
var id = EmailQueueRepository.Queryable.Max(x => x.Id) + 1;
var session = NHibernateSessionManager.Instance.GetSession();
var compareDate1 = DateTime.Now.Date.AddDays(1);
#endregion Arrange
#region Act/Assert
new PersistenceSpecification<EmailQueue>(session)
.CheckProperty(c => c.Id, id)
.CheckProperty(c => c.Created, compareDate1)
.CheckProperty(c => c.Pending, true)
.CheckProperty(c => c.SentDateTime, null)
.CheckProperty(c => c.Subject, "Subject")
.CheckProperty(c => c.Body, "Body")
.CheckProperty(c => c.Immediate, true)
//.CheckReference(c => c.Ceremony, ceremony)
.VerifyTheMappings();
#endregion Act/Assert
}
[TestMethod]
public void TestCanCorrectlyMapEmailQueue2()
{
#region Arrange
var id = EmailQueueRepository.Queryable.Max(x => x.Id) + 1;
var session = NHibernateSessionManager.Instance.GetSession();
var compareDate1 = DateTime.Now.Date.AddDays(1);
var compareDate2 = DateTime.Now.Date.AddDays(2);
#endregion Arrange
#region Act/Assert
new PersistenceSpecification<EmailQueue>(session)
.CheckProperty(c => c.Id, id)
.CheckProperty(c => c.Created, compareDate1)
.CheckProperty(c => c.Pending, false)
.CheckProperty(c => c.SentDateTime, compareDate2)
.CheckProperty(c => c.Subject, "Subject")
.CheckProperty(c => c.Body, "Body")
.CheckProperty(c => c.Immediate, false)
.VerifyTheMappings();
#endregion Act/Assert
}
[TestMethod]
public void TestCanCorrectlyMapEmailQueue3()
{
#region Arrange
var id = EmailQueueRepository.Queryable.Max(x => x.Id) + 1;
var session = NHibernateSessionManager.Instance.GetSession();
Repository.OfType<Registration>().DbContext.BeginTransaction();
LoadState(1);
LoadRegistrations(3);
LoadMajorCode(1);
LoadRegistrationParticipations(1);
LoadRegistrationPetitions(1);
LoadExtraTicketPetitions(1);
Repository.OfType<Registration>().DbContext.CommitTransaction();
var registration = Repository.OfType<Registration>().Queryable.First();
var student = Repository.OfType<Student>().Queryable.First();
var template = Repository.OfType<Template>().Queryable.First();
var registrationParticipation = Repository.OfType<RegistrationParticipation>().Queryable.First();
var registrationPetition = Repository.OfType<RegistrationPetition>().Queryable.First();
var extraTicketPetition = Repository.OfType<ExtraTicketPetition>().Queryable.First();
#endregion Arrange
#region Act/Assert
new PersistenceSpecification<EmailQueue>(session)
.CheckProperty(c => c.Id, id)
.CheckReference(c => c.Registration, registration)
.CheckReference(c => c.Student, student)
.CheckReference(c => c.Template, template)
.CheckReference(c => c.RegistrationParticipation, registrationParticipation)
.CheckReference(c => c.RegistrationPetition, registrationPetition)
.CheckReference(c => c.ExtraTicketPetition, extraTicketPetition)
.VerifyTheMappings();
#endregion Act/Assert
}
#endregion Fluent Mapping Tests
#region Reflection of Database.
/// <summary>
/// Tests all fields in the database have been tested.
/// If this fails and no other tests, it means that a field has been added which has not been tested above.
/// </summary>
[TestMethod]
public void TestAllFieldsInTheDatabaseHaveBeenTested()
{
#region Arrange
var expectedFields = new List<NameAndType>();
expectedFields.Add(new NameAndType("Body", "System.String", new List<string>
{
"[UCDArch.Core.NHibernateValidator.Extensions.RequiredAttribute()]"
}));
expectedFields.Add(new NameAndType("Created", "System.DateTime", new List<string>()));
expectedFields.Add(new NameAndType("ExtraTicketPetition", "Commencement.Core.Domain.ExtraTicketPetition", new List<string>()));
expectedFields.Add(new NameAndType("Id", "System.Int32", new List<string>
{
"[Newtonsoft.Json.JsonPropertyAttribute()]",
"[System.Xml.Serialization.XmlIgnoreAttribute()]"
}));
expectedFields.Add(new NameAndType("Immediate", "System.Boolean", new List<string>()));
expectedFields.Add(new NameAndType("Pending", "System.Boolean", new List<string>()));
expectedFields.Add(new NameAndType("Registration", "Commencement.Core.Domain.Registration", new List<string>()));
expectedFields.Add(new NameAndType("RegistrationParticipation", "Commencement.Core.Domain.RegistrationParticipation", new List<string>()));
expectedFields.Add(new NameAndType("RegistrationPetition", "Commencement.Core.Domain.RegistrationPetition", new List<string>()));
expectedFields.Add(new NameAndType("SentDateTime", "System.Nullable`1[System.DateTime]", new List<string>()));
expectedFields.Add(new NameAndType("Student", "Commencement.Core.Domain.Student", new List<string>
{
"[NHibernate.Validator.Constraints.NotNullAttribute()]"
}));
expectedFields.Add(new NameAndType("Subject", "System.String", new List<string>
{
"[NHibernate.Validator.Constraints.LengthAttribute((Int32)100)]",
"[UCDArch.Core.NHibernateValidator.Extensions.RequiredAttribute()]"
}));
expectedFields.Add(new NameAndType("Template", "Commencement.Core.Domain.Template", new List<string>
{
"[NHibernate.Validator.Constraints.NotNullAttribute()]"
}));
#endregion Arrange
AttributeAndFieldValidation.ValidateFieldsAndAttributes(expectedFields, typeof(EmailQueue));
}
#endregion Reflection of Database.
}
}
| |
// 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: Provides a fast, AV free, cross-language way of
** accessing unmanaged memory in a random fashion.
**
**
===========================================================*/
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Internal.Runtime.CompilerServices;
namespace System.IO
{
/// Perf notes: ReadXXX, WriteXXX (for basic types) acquire and release the
/// SafeBuffer pointer rather than relying on generic Read(T) from SafeBuffer because
/// this gives better throughput; benchmarks showed about 12-15% better.
public class UnmanagedMemoryAccessor : IDisposable
{
private SafeBuffer _buffer;
private long _offset;
private long _capacity;
private FileAccess _access;
private bool _isOpen;
private bool _canRead;
private bool _canWrite;
protected UnmanagedMemoryAccessor()
{
_isOpen = false;
}
public UnmanagedMemoryAccessor(SafeBuffer buffer, long offset, long capacity)
{
Initialize(buffer, offset, capacity, FileAccess.Read);
}
public UnmanagedMemoryAccessor(SafeBuffer buffer, long offset, long capacity, FileAccess access)
{
Initialize(buffer, offset, capacity, access);
}
protected void Initialize(SafeBuffer buffer, long offset, long capacity, FileAccess access)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (capacity < 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.ByteLength < (ulong)(offset + capacity))
{
throw new ArgumentException(SR.Argument_OffsetAndCapacityOutOfBounds);
}
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
{
throw new ArgumentOutOfRangeException(nameof(access));
}
if (_isOpen)
{
throw new InvalidOperationException(SR.InvalidOperation_CalledTwice);
}
unsafe
{
byte* pointer = null;
try
{
buffer.AcquirePointer(ref pointer);
if (((byte*)((long)pointer + offset + capacity)) < pointer)
{
throw new ArgumentException(SR.Argument_UnmanagedMemAccessorWrapAround);
}
}
finally
{
if (pointer != null)
{
buffer.ReleasePointer();
}
}
}
_offset = offset;
_buffer = buffer;
_capacity = capacity;
_access = access;
_isOpen = true;
_canRead = (_access & FileAccess.Read) != 0;
_canWrite = (_access & FileAccess.Write) != 0;
}
public long Capacity => _capacity;
public bool CanRead => _isOpen && _canRead;
public bool CanWrite => _isOpen && _canWrite;
protected virtual void Dispose(bool disposing)
{
_isOpen = false;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected bool IsOpen => _isOpen;
// ************** Read Methods ****************/
public bool ReadBoolean(long position) => ReadByte(position) != 0;
public byte ReadByte(long position)
{
EnsureSafeToRead(position, sizeof(byte));
byte result;
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
result = *((byte*)(pointer + _offset + position));
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
return result;
}
public char ReadChar(long position) => unchecked((char)ReadInt16(position));
public short ReadInt16(long position)
{
EnsureSafeToRead(position, sizeof(short));
short result;
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
result = Unsafe.ReadUnaligned<short>(pointer + _offset + position);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
return result;
}
public int ReadInt32(long position)
{
EnsureSafeToRead(position, sizeof(int));
int result;
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
result = Unsafe.ReadUnaligned<int>(pointer + _offset + position);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
return result;
}
public long ReadInt64(long position)
{
EnsureSafeToRead(position, sizeof(long));
long result;
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
result = Unsafe.ReadUnaligned<long>(pointer + _offset + position);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
return result;
}
public decimal ReadDecimal(long position)
{
const int ScaleMask = 0x00FF0000;
const int SignMask = unchecked((int)0x80000000);
EnsureSafeToRead(position, sizeof(decimal));
int lo, mid, hi, flags;
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
lo = Unsafe.ReadUnaligned<int>(pointer);
mid = Unsafe.ReadUnaligned<int>(pointer + 4);
hi = Unsafe.ReadUnaligned<int>(pointer + 8);
flags = Unsafe.ReadUnaligned<int>(pointer + 12);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
// Check for invalid Decimal values
if (!((flags & ~(SignMask | ScaleMask)) == 0 && (flags & ScaleMask) <= (28 << 16)))
{
throw new ArgumentException(SR.Arg_BadDecimal); // Throw same Exception type as Decimal(int[]) ctor for compat
}
bool isNegative = (flags & SignMask) != 0;
byte scale = (byte)(flags >> 16);
return new decimal(lo, mid, hi, isNegative, scale);
}
public float ReadSingle(long position) => BitConverter.Int32BitsToSingle(ReadInt32(position));
public double ReadDouble(long position) => BitConverter.Int64BitsToDouble(ReadInt64(position));
[CLSCompliant(false)]
public sbyte ReadSByte(long position) => unchecked((sbyte)ReadByte(position));
[CLSCompliant(false)]
public ushort ReadUInt16(long position) => unchecked((ushort)ReadInt16(position));
[CLSCompliant(false)]
public uint ReadUInt32(long position) => unchecked((uint)ReadInt32(position));
[CLSCompliant(false)]
public ulong ReadUInt64(long position) => unchecked((ulong)ReadInt64(position));
// Reads a struct of type T from unmanaged memory, into the reference pointed to by ref value.
// Note: this method is not safe, since it overwrites the contents of a structure, it can be
// used to modify the private members of a struct.
// This method is most performant when used with medium to large sized structs
// (larger than 8 bytes -- though this is number is JIT and architecture dependent). As
// such, it is best to use the ReadXXX methods for small standard types such as ints, longs,
// bools, etc.
public void Read<T>(long position, out T structure) where T : struct
{
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (!_isOpen)
{
throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed);
}
if (!_canRead)
{
throw new NotSupportedException(SR.NotSupported_Reading);
}
uint sizeOfT = SafeBuffer.SizeOf<T>();
if (position > _capacity - sizeOfT)
{
if (position >= _capacity)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
else
{
throw new ArgumentException(SR.Format(SR.Argument_NotEnoughBytesToRead, typeof(T)), nameof(position));
}
}
structure = _buffer.Read<T>((ulong)(_offset + position));
}
// Reads 'count' structs of type T from unmanaged memory, into 'array' starting at 'offset'.
// Note: this method is not safe, since it overwrites the contents of structures, it can
// be used to modify the private members of a struct.
public int ReadArray<T>(long position, T[] array, int offset, int count) where T : struct
{
if (array == null)
{
throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (!_isOpen)
{
throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed);
}
if (!_canRead)
{
throw new NotSupportedException(SR.NotSupported_Reading);
}
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
uint sizeOfT = SafeBuffer.AlignedSizeOf<T>();
// only check position and ask for fewer Ts if count is too big
if (position >= _capacity)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
int n = count;
long spaceLeft = _capacity - position;
if (spaceLeft < 0)
{
n = 0;
}
else
{
ulong spaceNeeded = (ulong)(sizeOfT * count);
if ((ulong)spaceLeft < spaceNeeded)
{
n = (int)(spaceLeft / sizeOfT);
}
}
_buffer.ReadArray<T>((ulong)(_offset + position), array, offset, n);
return n;
}
// ************** Write Methods ****************/
public void Write(long position, bool value) => Write(position, (byte)(value ? 1 : 0));
public void Write(long position, byte value)
{
EnsureSafeToWrite(position, sizeof(byte));
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
*((byte*)(pointer + _offset + position)) = value;
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
public void Write(long position, char value) => Write(position, unchecked((short)value));
public void Write(long position, short value)
{
EnsureSafeToWrite(position, sizeof(short));
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
Unsafe.WriteUnaligned<short>(pointer + _offset + position, value);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
public void Write(long position, int value)
{
EnsureSafeToWrite(position, sizeof(int));
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
Unsafe.WriteUnaligned<int>(pointer + _offset + position, value);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
public void Write(long position, long value)
{
EnsureSafeToWrite(position, sizeof(long));
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
Unsafe.WriteUnaligned<long>(pointer + _offset + position, value);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
public void Write(long position, decimal value)
{
EnsureSafeToWrite(position, sizeof(decimal));
unsafe
{
int* valuePtr = (int*)(&value);
int flags = *valuePtr;
int hi = *(valuePtr + 1);
int lo = *(valuePtr + 2);
int mid = *(valuePtr + 3);
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
Unsafe.WriteUnaligned<int>(pointer, lo);
Unsafe.WriteUnaligned<int>(pointer + 4, mid);
Unsafe.WriteUnaligned<int>(pointer + 8, hi);
Unsafe.WriteUnaligned<int>(pointer + 12, flags);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
public void Write(long position, float value) => Write(position, BitConverter.SingleToInt32Bits(value));
public void Write(long position, double value) => Write(position, BitConverter.DoubleToInt64Bits(value));
[CLSCompliant(false)]
public void Write(long position, sbyte value) => Write(position, unchecked((byte)value));
[CLSCompliant(false)]
public void Write(long position, ushort value) => Write(position, unchecked((short)value));
[CLSCompliant(false)]
public void Write(long position, uint value) => Write(position, unchecked((int)value));
[CLSCompliant(false)]
public void Write(long position, ulong value) => Write(position, unchecked((long)value));
// Writes the struct pointed to by ref value into unmanaged memory. Note that this method
// is most performant when used with medium to large sized structs (larger than 8 bytes
// though this is number is JIT and architecture dependent). As such, it is best to use
// the WriteX methods for small standard types such as ints, longs, bools, etc.
public void Write<T>(long position, ref T structure) where T : struct
{
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (!_isOpen)
{
throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed);
}
if (!_canWrite)
{
throw new NotSupportedException(SR.NotSupported_Writing);
}
uint sizeOfT = SafeBuffer.SizeOf<T>();
if (position > _capacity - sizeOfT)
{
if (position >= _capacity)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
else
{
throw new ArgumentException(SR.Format(SR.Argument_NotEnoughBytesToWrite, typeof(T)), nameof(position));
}
}
_buffer.Write<T>((ulong)(_offset + position), structure);
}
// Writes 'count' structs of type T from 'array' (starting at 'offset') into unmanaged memory.
public void WriteArray<T>(long position, T[] array, int offset, int count) where T : struct
{
if (array == null)
{
throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (position >= Capacity)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
if (!_isOpen)
{
throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed);
}
if (!_canWrite)
{
throw new NotSupportedException(SR.NotSupported_Writing);
}
_buffer.WriteArray<T>((ulong)(_offset + position), array, offset, count);
}
private void EnsureSafeToRead(long position, int sizeOfType)
{
if (!_isOpen)
{
throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed);
}
if (!_canRead)
{
throw new NotSupportedException(SR.NotSupported_Reading);
}
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (position > _capacity - sizeOfType)
{
if (position >= _capacity)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
else
{
throw new ArgumentException(SR.Argument_NotEnoughBytesToRead, nameof(position));
}
}
}
private void EnsureSafeToWrite(long position, int sizeOfType)
{
if (!_isOpen)
{
throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed);
}
if (!_canWrite)
{
throw new NotSupportedException(SR.NotSupported_Writing);
}
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (position > _capacity - sizeOfType)
{
if (position >= _capacity)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
else
{
throw new ArgumentException(SR.Argument_NotEnoughBytesToWrite, nameof(position));
}
}
}
}
}
| |
// 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.TransformCollection.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
{
sealed public partial class TransformCollection : System.Windows.Media.Animation.Animatable, System.Collections.IList, System.Collections.ICollection, IList<Transform>, ICollection<Transform>, IEnumerable<Transform>, System.Collections.IEnumerable
{
#region Methods and constructors
public void Add(Transform value)
{
}
public void Clear()
{
}
public TransformCollection Clone()
{
return default(TransformCollection);
}
protected override void CloneCore(System.Windows.Freezable source)
{
}
public TransformCollection CloneCurrentValue()
{
return default(TransformCollection);
}
protected override void CloneCurrentValueCore(System.Windows.Freezable source)
{
}
public bool Contains(Transform value)
{
return default(bool);
}
public void CopyTo(Transform[] array, int index)
{
}
protected override System.Windows.Freezable CreateInstanceCore()
{
return default(System.Windows.Freezable);
}
protected override bool FreezeCore(bool isChecking)
{
return default(bool);
}
protected override void GetAsFrozenCore(System.Windows.Freezable source)
{
}
protected override void GetCurrentValueAsFrozenCore(System.Windows.Freezable source)
{
}
public TransformCollection.Enumerator GetEnumerator()
{
return default(TransformCollection.Enumerator);
}
public int IndexOf(Transform value)
{
return default(int);
}
public void Insert(int index, Transform value)
{
}
public bool Remove(Transform value)
{
return default(bool);
}
public void RemoveAt(int index)
{
}
IEnumerator<Transform> System.Collections.Generic.IEnumerable<System.Windows.Media.Transform>.GetEnumerator()
{
return default(IEnumerator<Transform>);
}
void System.Collections.ICollection.CopyTo(Array array, int index)
{
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return default(System.Collections.IEnumerator);
}
int System.Collections.IList.Add(Object value)
{
return default(int);
}
bool System.Collections.IList.Contains(Object value)
{
return default(bool);
}
int System.Collections.IList.IndexOf(Object value)
{
return default(int);
}
void System.Collections.IList.Insert(int index, Object value)
{
}
void System.Collections.IList.Remove(Object value)
{
}
public TransformCollection(int capacity)
{
}
public TransformCollection()
{
}
public TransformCollection(IEnumerable<Transform> collection)
{
}
#endregion
#region Properties and indexers
public int Count
{
get
{
return default(int);
}
}
public Transform this [int index]
{
get
{
return default(Transform);
}
set
{
}
}
bool System.Collections.Generic.ICollection<System.Windows.Media.Transform>.IsReadOnly
{
get
{
return default(bool);
}
}
bool System.Collections.ICollection.IsSynchronized
{
get
{
return default(bool);
}
}
Object System.Collections.ICollection.SyncRoot
{
get
{
return default(Object);
}
}
bool System.Collections.IList.IsFixedSize
{
get
{
return default(bool);
}
}
bool System.Collections.IList.IsReadOnly
{
get
{
return default(bool);
}
}
Object System.Collections.IList.this [int index]
{
get
{
return default(Object);
}
set
{
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace AppData.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Abp.Dependency;
namespace Helios.Authentication.TwoFactor.Google
{
/// <summary>
/// This code taken from https://github.com/BrandonPotter/GoogleAuthenticator
/// </summary>
public class GoogleTwoFactorAuthenticateService : ITransientDependency
{
public static DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public TimeSpan DefaultClockDriftTolerance { get; set; }
public bool UseManagedSha1Algorithm { get; set; }
public bool TryUnmanagedAlgorithmOnFailure { get; set; }
public GoogleTwoFactorAuthenticateService() : this(true, true) { }
public GoogleTwoFactorAuthenticateService(bool useManagedSha1, bool useUnmanagedOnFail)
{
DefaultClockDriftTolerance = TimeSpan.FromMinutes(5);
UseManagedSha1Algorithm = useManagedSha1;
TryUnmanagedAlgorithmOnFailure = useUnmanagedOnFail;
}
public GoogleAuthenticatorSetupCode GenerateSetupCode(string accountTitleNoSpaces, string accountSecretKey, int qrCodeWidth, int qrCodeHeight)
{
return GenerateSetupCode(null, accountTitleNoSpaces, accountSecretKey, qrCodeWidth, qrCodeHeight);
}
public GoogleAuthenticatorSetupCode GenerateSetupCode(string issuer, string accountTitleNoSpaces, string accountSecretKey, int qrCodeWidth, int qrCodeHeight)
{
return GenerateSetupCode(issuer, accountTitleNoSpaces, accountSecretKey, qrCodeWidth, qrCodeHeight, false);
}
public GoogleAuthenticatorSetupCode GenerateSetupCode(string issuer, string accountTitleNoSpaces, string accountSecretKey, int qrCodeWidth, int qrCodeHeight, bool useHttps)
{
accountTitleNoSpaces = accountTitleNoSpaces?.Replace(" ", "") ?? throw new NullReferenceException("Account Title is null");
var setupCode = new GoogleAuthenticatorSetupCode
{
Account = accountTitleNoSpaces,
AccountSecretKey = accountSecretKey
};
var encodedSecretKey = EncodeAccountSecretKey(accountSecretKey);
setupCode.ManualEntryKey = encodedSecretKey;
string provisionUrl = UrlEncode(string.IsNullOrEmpty(issuer) ?
$"otpauth://totp/{accountTitleNoSpaces}?secret={encodedSecretKey}" :
$"otpauth://totp/{accountTitleNoSpaces}?secret={encodedSecretKey}&issuer={UrlEncode(issuer)}");
var protocol = useHttps ? "https" : "http";
var url =
$"{protocol}://chart.googleapis.com/chart?cht=qr&chs={qrCodeWidth}x{qrCodeHeight}&chl={provisionUrl}";
setupCode.QrCodeSetupImageUrl = url;
return setupCode;
}
private string UrlEncode(string value)
{
var stringBuilder = new StringBuilder();
const string validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
foreach (var symbol in value)
{
if (validChars.IndexOf(symbol) != -1)
{
stringBuilder.Append(symbol);
}
else
{
stringBuilder.Append('%' + $"{(int)symbol:X2}");
}
}
return stringBuilder.ToString().Replace(" ", "%20");
}
private string EncodeAccountSecretKey(string accountSecretKey)
{
return Base32Encode(Encoding.UTF8.GetBytes(accountSecretKey));
}
private string Base32Encode(byte[] data)
{
var inByteSize = 8;
var outByteSize = 5;
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".ToCharArray();
int i = 0, index = 0;
var result = new StringBuilder((data.Length + 7) * inByteSize / outByteSize);
while (i < data.Length)
{
var currentByte = data[i] >= 0 ? data[i] : (data[i] + 256);
int digit;
if (index > inByteSize - outByteSize)
{
int nextByte;
if (i + 1 < data.Length)
nextByte = (data[i + 1] >= 0) ? data[i + 1] : (data[i + 1] + 256);
else
nextByte = 0;
digit = currentByte & (0xFF >> index);
index = (index + outByteSize) % inByteSize;
digit <<= index;
digit |= nextByte >> (inByteSize - index);
i++;
}
else
{
digit = (currentByte >> (inByteSize - (index + outByteSize))) & 0x1F;
index = (index + outByteSize) % inByteSize;
if (index == 0)
i++;
}
result.Append(alphabet[digit]);
}
return result.ToString();
}
public string GeneratePinAtInterval(string accountSecretKey, long counter, int digits = 6)
{
return GenerateHashedCode(accountSecretKey, counter, digits);
}
internal string GenerateHashedCode(string secret, long iterationNumber, int digits = 6)
{
var key = Encoding.UTF8.GetBytes(secret);
return GenerateHashedCode(key, iterationNumber, digits);
}
internal string GenerateHashedCode(byte[] key, long iterationNumber, int digits = 6)
{
var counter = BitConverter.GetBytes(iterationNumber);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(counter);
}
var hmac = GetHmacSha1Algorithm(key);
var hash = hmac.ComputeHash(counter);
var offset = hash[hash.Length - 1] & 0xf;
// Convert the 4 bytes into an integer, ignoring the sign.
var binary =
((hash[offset] & 0x7f) << 24)
| (hash[offset + 1] << 16)
| (hash[offset + 2] << 8)
| (hash[offset + 3]);
var password = binary % (int)Math.Pow(10, digits);
return password.ToString(new string('0', digits));
}
private long GetCurrentCounter()
{
return GetCurrentCounter(DateTime.UtcNow, Epoch, 30);
}
private long GetCurrentCounter(DateTime now, DateTime epoch, int timeStep)
{
return (long)(now - epoch).TotalSeconds / timeStep;
}
private HMACSHA1 GetHmacSha1Algorithm(byte[] key)
{
return new HMACSHA1(key);
}
public bool ValidateTwoFactorPin(string accountSecretKey, string twoFactorCodeFromClient)
{
return ValidateTwoFactorPin(accountSecretKey, twoFactorCodeFromClient, DefaultClockDriftTolerance);
}
public bool ValidateTwoFactorPin(string accountSecretKey, string twoFactorCodeFromClient, TimeSpan timeTolerance)
{
var codes = GetCurrentPins(accountSecretKey, timeTolerance);
return codes.Any(c => c == twoFactorCodeFromClient);
}
public string[] GetCurrentPins(string accountSecretKey, TimeSpan timeTolerance)
{
var codes = new List<string>();
var iterationCounter = GetCurrentCounter();
var iterationOffset = 0;
if (timeTolerance.TotalSeconds > 30)
{
iterationOffset = Convert.ToInt32(timeTolerance.TotalSeconds / 30.00);
}
var iterationStart = iterationCounter - iterationOffset;
var iterationEnd = iterationCounter + iterationOffset;
for (var counter = iterationStart; counter <= iterationEnd; counter++)
{
codes.Add(GeneratePinAtInterval(accountSecretKey, counter));
}
return codes.ToArray();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
/// <summary>
/// ToInt64(System.Double)
/// </summary>
public class ConvertToInt64_5
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
//
// TODO: Add your negative test cases here
//
// TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method ToInt64(0<double<0.5)");
try
{
double d;
do
d = TestLibrary.Generator.GetDouble(-55);
while (d >= 0.5);
long actual = Convert.ToInt64(d);
long expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("001.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method ToInt64(1>double>=0.5)");
try
{
double d;
do
d = TestLibrary.Generator.GetDouble(-55);
while (d < 0.5);
long actual = Convert.ToInt64(d);
long expected = 1;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("002.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method ToInt64(0)");
try
{
double d = 0d;
long actual = Convert.ToInt64(d);
long expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("003.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify method ToInt64(int64.max)");
try
{
long actual = Convert.ToInt64(Int64.MaxValue);
long expected = Int64.MaxValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("004.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest5: Verify method ToInt64(int64.min)");
try
{
long actual = Convert.ToInt64(Int64.MinValue);
long expected = Int64.MinValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("005.1", "Method ToInt32 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: OverflowException is thrown for value > Int64.MaxValue.");
try
{
double d = (double)Int64.MaxValue + 1;
long i = Convert.ToInt64(d);
TestLibrary.TestFramework.LogError("101.1", "OverflowException is thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: OverflowException is thrown for value < Int64.MinValue");
try
{
// with the length of the min value being around 17 digits and the double going out to 15 or 16 digits
// before rounding, then subtracting one simply isn't enough to force the value to be less than Int64.MaxValue.
// If it is possible that the last two or 3 digits can get dropped and rounding can occur on the thousands, then
// subtracting 10000 is safe bet to be lower
double d = (double)Int64.MinValue - 10000;
long i = Convert.ToInt64(d);
TestLibrary.TestFramework.LogError("102.1", "OverflowException is not thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ConvertToInt64_5 test = new ConvertToInt64_5();
TestLibrary.TestFramework.BeginTestCase("ConvertToInt64_5");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
using System;
using System.Net;
using System.Text;
using netmfawss3.Account;
using netmfawss3.Aws;
using netmfawss3.Utilities;
namespace netmfawss3.Client
{
public class AwsS3Client
{
#region fields
private readonly AwsS3Account _account;
private readonly Encoding _encoding = new UTF8Encoding();
private readonly string _currentRegion;
private readonly Regions _region;
private readonly string _hostUri;
private string _timestamp;
private string _dateTimeStamp;
#endregion
private string HttpVerb { get; set; }
public AwsS3Client(AwsS3Account account, Regions region = Regions.UsEast1)
{
_account = account;
_region = region;
switch (region)
{
case Regions.EuCentral1:
_currentRegion = "eu-central-1";
break;
case Regions.UsEast1:
_currentRegion = "us-east-1";
break;
case Regions.UsWest2:
_currentRegion = "us-west-2";
break;
case Regions.UsWest1:
_currentRegion = "us-west-1";
break;
case Regions.EuWest1:
_currentRegion = "eu-west-1";
break;
case Regions.ApSoutheast1:
_currentRegion = "ap-southeast-1";
break;
case Regions.ApSoutheast2:
_currentRegion = "ap-southeast-2";
break;
case Regions.ApNortheast1:
_currentRegion = "ap-northeast-1";
break;
case Regions.SaEast1:
_currentRegion = "sa-east-1";
break;
default:
_currentRegion = "us-east-1";
break;
}
if (_region != Regions.UsEast1)
{
_hostUri = "s3-" + _currentRegion + ".amazonaws.com";
}
else
{
_hostUri = "s3.amazonaws.com";
}
}
public bool PutBucket(string bucketName)
{
HttpVerb = "PUT";
_timestamp = DateTime.UtcNow.ToString("yyyyMMdd") + "T" +
DateTime.UtcNow.ToString("HHmmss") + "Z";
const string signedHeaders = "host;x-amz-content-sha256;x-amz-date";
byte[] regionXmlByte;
if (_region != Regions.UsEast1)
{
var regionXml = "<CreateBucketConfiguration xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" +
"<LocationConstraint>" + _currentRegion + "</LocationConstraint>" +
"</CreateBucketConfiguration>";
regionXmlByte = _encoding.GetBytes(regionXml);
}
else
{
regionXmlByte = _encoding.GetBytes("");
}
var hashed = SHA.computeSHA256(regionXmlByte);
var hex = ConvertToString(hashed, 0, hashed.Length);
var hexHash = hex.Replace("-", string.Empty).ToLower();
var canonicalHeaders = "host:" + bucketName + ".s3.amazonaws.com:443" + "\n" +
"x-amz-content-sha256:" + hexHash + "\n" +
"x-amz-date:" + _timestamp + "\n";
var canRequest = CreateCanonicalRequest(HttpVerb, "/", canonicalHeaders, signedHeaders, hexHash);
var authHeader = CreateAuthorizationHeader("us-east-1", signedHeaders, canRequest);
var request =
(HttpWebRequest) WebRequest.Create("https://" + bucketName + ".s3.amazonaws.com/");
request.Method = HttpVerb;
request.ContentLength = regionXmlByte.Length;
request.Headers.Add("x-amz-content-sha256", hexHash);
request.Headers.Add("x-amz-date", _timestamp);
request.Headers.Add("Authorization", authHeader);
using (var stream = request.GetRequestStream())
{
stream.Write(regionXmlByte, 0, regionXmlByte.Length);
}
using (var response = (HttpWebResponse) request.GetResponse())
{
return response.StatusCode == HttpStatusCode.OK;
}
}
public bool DeleteBucket(string bucketName)
{
HttpVerb = "DELETE";
_timestamp = DateTime.UtcNow.ToString("yyyyMMdd") + "T" +
DateTime.UtcNow.ToString("HHmmss") + "Z";
const string signedHeaders = "host;x-amz-date";
var hashed = SHA.computeSHA256(_encoding.GetBytes(""));
var hex = ConvertToString(hashed, 0, hashed.Length);
var hexHash = hex.Replace("-", string.Empty).ToLower();
var canonicalHeaders = "host:" + _hostUri + ":443" + "\n" +
"x-amz-date:" + _timestamp + "\n";
var canRequest = CreateCanonicalRequest(HttpVerb, "/" + bucketName, canonicalHeaders, signedHeaders, hexHash);
var authHeader = CreateAuthorizationHeader(_currentRegion, signedHeaders, canRequest);
var request =
(HttpWebRequest) WebRequest.Create("https://" + _hostUri + "/" + bucketName);
request.Method = HttpVerb;
request.Headers.Add("x-amz-content-sha256", hexHash);
request.Headers.Add("x-amz-date", _timestamp);
request.Headers.Add("Authorization", authHeader);
using (var response = (HttpWebResponse) request.GetResponse())
{
return response.StatusCode == HttpStatusCode.NoContent;
}
}
public bool PutObject(string bucketName, string objectName, byte[] objectByte)
{
HttpVerb = "PUT";
_timestamp = DateTime.UtcNow.ToString("yyyyMMdd") + "T" +
DateTime.UtcNow.ToString("HHmmss") + "Z";
var objectUri = bucketName + "/" + objectName;
const string signedHeaders = "host;x-amz-content-sha256;x-amz-date";
var hashed = SHA.computeSHA256(objectByte);
var hex = ConvertToString(hashed, 0, hashed.Length);
var hexHash = hex.Replace("-", string.Empty).ToLower();
var canonicalHeaders = "host:" + _hostUri + ":443" + "\n" +
"x-amz-content-sha256:" + hexHash + "\n" +
"x-amz-date:" + _timestamp + "\n";
var canRequest = CreateCanonicalRequest(HttpVerb, "/" + objectUri, canonicalHeaders, signedHeaders,
hexHash);
var authHeader = CreateAuthorizationHeader(_currentRegion, signedHeaders, canRequest);
var request =
(HttpWebRequest) WebRequest.Create("https://" + _hostUri + "/" + objectUri);
request.Method = HttpVerb;
request.ContentLength = objectByte.Length;
request.Headers.Add("x-amz-content-sha256", hexHash);
request.Headers.Add("x-amz-date", _timestamp);
request.Headers.Add("Authorization", authHeader);
using (var stream = request.GetRequestStream())
{
stream.Write(objectByte, 0, objectByte.Length);
}
using (var response = (HttpWebResponse) request.GetResponse())
{
return response.StatusCode == HttpStatusCode.OK;
}
}
public bool DeleteObject(string bucketName, string objectName)
{
HttpVerb = "DELETE";
_timestamp = DateTime.UtcNow.ToString("yyyyMMdd") + "T" +
DateTime.UtcNow.ToString("HHmmss") + "Z";
var objectUri = bucketName + "/" + objectName;
const string signedHeaders = "host;x-amz-date";
var hashed = SHA.computeSHA256(_encoding.GetBytes(""));
var hex = ConvertToString(hashed, 0, hashed.Length);
var hexHash = hex.Replace("-", string.Empty).ToLower();
var canonicalHeaders = "host:" + _hostUri + ":443" + "\n" +
"x-amz-date:" + _timestamp + "\n";
var canRequest = CreateCanonicalRequest(HttpVerb, "/" + objectUri, canonicalHeaders, signedHeaders,
hexHash);
var authHeader = CreateAuthorizationHeader(_currentRegion, signedHeaders, canRequest);
var request =
(HttpWebRequest) WebRequest.Create("https://" + _hostUri + "/" + objectUri);
request.Method = HttpVerb;
request.Headers.Add("x-amz-content-sha256", hexHash);
request.Headers.Add("x-amz-date", _timestamp);
request.Headers.Add("Authorization", authHeader);
using (var response = (HttpWebResponse) request.GetResponse())
{
return response.StatusCode == HttpStatusCode.NoContent;
}
}
private static string CreateCanonicalRequest(string httpMethod, string canonicalUri, string canonicalHeaders,
string signedHeaders, string hashedPayload = "\n")
{
var canRequest = httpMethod + "\n" +
canonicalUri + "\n" +
"\n" +
canonicalHeaders + "\n" +
signedHeaders + "\n" +
hashedPayload;
return canRequest;
}
private string CreateStringToSign(string region, string canonicalRequest)
{
var hashed = SHA.computeSHA256(_encoding.GetBytes(canonicalRequest));
var hex = ConvertToString(hashed, 0, hashed.Length);
var hexHash = hex.Replace("-", string.Empty).ToLower();
var stringToSign = "AWS4-HMAC-SHA256" + "\n" +
_timestamp + "\n" +
_dateTimeStamp + "/" + region + "/s3/aws4_request" + "\n" +
hexHash;
return stringToSign;
}
private string CreateSignature(string region, string canonicalRequest)
{
var dateKey = SHA.computeHMAC_SHA256(_encoding.GetBytes("AWS4" + _account.AwsSecretAccessKey),
_encoding.GetBytes(_dateTimeStamp));
var dateRegionKey = SHA.computeHMAC_SHA256((dateKey), _encoding.GetBytes(region));
var dateRegionServiceKey = SHA.computeHMAC_SHA256(dateRegionKey, _encoding.GetBytes("s3"));
var signingKey = SHA.computeHMAC_SHA256(dateRegionServiceKey, _encoding.GetBytes("aws4_request"));
var signedPolicyBytes = SHA.computeHMAC_SHA256(signingKey,
_encoding.GetBytes(CreateStringToSign(region, canonicalRequest)));
return ConvertToString(signedPolicyBytes, 0, signedPolicyBytes.Length).Replace("-", string.Empty).ToLower();
}
private string CreateAuthorizationHeader(string region, string signedHeaders, string canonicalRequest)
{
_dateTimeStamp = DateTime.UtcNow.ToString("yyyyMMdd");
return "AWS4-HMAC-SHA256 Credential=" + _account.AwsAccessKeyId + "/" + _dateTimeStamp +
"/" + region + "/s3/aws4_request" + ",SignedHeaders=" + signedHeaders + ",Signature=" +
CreateSignature(region, canonicalRequest);
}
private static string ConvertToString(byte[] value, int index, int length)
{
var c = new char[length * 3];
byte b;
for (int y = 0, x = 0; y < length; ++y, ++x)
{
b = (byte)(value[index + y] >> 4);
c[x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
b = (byte)(value[index + y] & 0xF);
c[++x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
c[++x] = '-';
}
return new string(c, 0, c.Length - 1);
}
}
}
| |
#if !NETFX_CORE && !IOS
//-----------------------------------------------------------------------
// <copyright file="ObjectAdapter.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>An ObjectAdapter is used to convert data in an object </summary>
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.ComponentModel;
using System.Reflection;
using Csla.Properties;
namespace Csla.Data
{
/// <summary>
/// An ObjectAdapter is used to convert data in an object
/// or collection into a DataTable.
/// </summary>
public class ObjectAdapter
{
/// <summary>
/// Fills the DataSet with data from an object or collection.
/// </summary>
/// <remarks>
/// The name of the DataTable being filled is will be the class name of
/// the object acting as the data source. The
/// DataTable will be inserted if it doesn't already exist in the DataSet.
/// </remarks>
/// <param name="ds">A reference to the DataSet to be filled.</param>
/// <param name="source">A reference to the object or collection acting as a data source.</param>
public void Fill(DataSet ds, object source)
{
string className = source.GetType().Name;
Fill(ds, className, source);
}
/// <summary>
/// Fills the DataSet with data from an object or collection.
/// </summary>
/// <remarks>
/// The name of the DataTable being filled is specified as a parameter. The
/// DataTable will be inserted if it doesn't already exist in the DataSet.
/// </remarks>
/// <param name="ds">A reference to the DataSet to be filled.</param>
/// <param name="tableName"></param>
/// <param name="source">A reference to the object or collection acting as a data source.</param>
public void Fill(DataSet ds, string tableName, object source)
{
DataTable dt;
bool exists;
dt = ds.Tables[tableName];
exists = (dt != null);
if (!exists)
dt = new DataTable(tableName);
Fill(dt, source);
if (!exists)
ds.Tables.Add(dt);
}
/// <summary>
/// Fills a DataTable with data values from an object or collection.
/// </summary>
/// <param name="dt">A reference to the DataTable to be filled.</param>
/// <param name="source">A reference to the object or collection acting as a data source.</param>
public void Fill(DataTable dt, object source)
{
if (source == null)
throw new ArgumentException(Resources.NothingNotValid);
// get the list of columns from the source
List<string> columns = GetColumns(source);
if (columns.Count < 1) return;
// create columns in DataTable if needed
foreach (string column in columns)
if (!dt.Columns.Contains(column))
dt.Columns.Add(column);
// get an IList and copy the data
CopyData(dt, GetIList(source), columns);
}
#region DataCopyIList
private IList GetIList(object source)
{
if (source is IListSource)
return ((IListSource)source).GetList();
else if (source is IList)
return source as IList;
else
{
// this is a regular object - create a list
ArrayList col = new ArrayList();
col.Add(source);
return col;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void CopyData(
DataTable dt, IList ds, List<string> columns)
{
// load the data into the DataTable
dt.BeginLoadData();
for (int index = 0; index < ds.Count; index++)
{
DataRow dr = dt.NewRow();
foreach (string column in columns)
{
try
{
dr[column] = GetField(ds[index], column);
}
catch (Exception ex)
{
dr[column] = ex.Message;
}
}
dt.Rows.Add(dr);
}
dt.EndLoadData();
}
#endregion
#region GetColumns
private List<string> GetColumns(object source)
{
List<string> result;
// first handle DataSet/DataTable
object innerSource;
IListSource iListSource = source as IListSource;
if (iListSource != null)
innerSource = iListSource.GetList();
else
innerSource = source;
DataView dataView = innerSource as DataView;
if (dataView != null)
result = ScanDataView(dataView);
else
{
// now handle lists/arrays/collections
IEnumerable iEnumerable = innerSource as IEnumerable;
if (iEnumerable != null)
{
Type childType = Utilities.GetChildItemType(
innerSource.GetType());
result = ScanObject(childType);
}
else
{
// the source is a regular object
result = ScanObject(innerSource.GetType());
}
}
return result;
}
private List<string> ScanDataView(DataView ds)
{
List<string> result = new List<string>();
for (int field = 0; field < ds.Table.Columns.Count; field++)
result.Add(ds.Table.Columns[field].ColumnName);
return result;
}
private List<string> ScanObject(Type sourceType)
{
List<string> result = new List<string>();
if (sourceType != null)
{
// retrieve a list of all public properties
PropertyInfo[] props = sourceType.GetProperties();
if (props.Length >= 0)
for (int column = 0; column < props.Length; column++)
if (props[column].CanRead)
result.Add(props[column].Name);
// retrieve a list of all public fields
FieldInfo[] fields = sourceType.GetFields();
if (fields.Length >= 0)
for (int column = 0; column < fields.Length; column++)
result.Add(fields[column].Name);
}
return result;
}
#endregion
#region GetField
private static string GetField(object obj, string fieldName)
{
string result;
DataRowView dataRowView = obj as DataRowView;
if (dataRowView != null)
{
// this is a DataRowView from a DataView
result = dataRowView[fieldName].ToString();
}
else if (obj is ValueType && obj.GetType().IsPrimitive)
{
// this is a primitive value type
result = obj.ToString();
}
else
{
string tmp = obj as string;
if (tmp != null)
{
// this is a simple string
result = (string)obj;
}
else
{
// this is an object or Structure
try
{
Type sourceType = obj.GetType();
// see if the field is a property
PropertyInfo prop = sourceType.GetProperty(fieldName);
if ((prop == null) || (!prop.CanRead))
{
// no readable property of that name exists -
// check for a field
FieldInfo field = sourceType.GetField(fieldName);
if (field == null)
{
// no field exists either, throw an exception
throw new DataException(
Resources.NoSuchValueExistsException +
" " + fieldName);
}
else
{
// got a field, return its value
result = field.GetValue(obj).ToString();
}
}
else
{
// found a property, return its value
result = prop.GetValue(obj, null).ToString();
}
}
catch (Exception ex)
{
throw new DataException(
Resources.ErrorReadingValueException +
" " + fieldName, ex);
}
}
}
return result;
}
#endregion
}
}
#endif
| |
// 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.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.Osu.Edit.Checks;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
using osu.Game.Tests.Beatmaps;
using osuTK;
namespace osu.Game.Rulesets.Osu.Tests.Editor.Checks
{
[TestFixture]
public class CheckOffscreenObjectsTest
{
private static readonly Vector2 playfield_centre = OsuPlayfield.BASE_SIZE * 0.5f;
private CheckOffscreenObjects check;
[SetUp]
public void Setup()
{
check = new CheckOffscreenObjects();
}
[Test]
public void TestCircleInCenter()
{
assertOk(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new HitCircle
{
StartTime = 3000,
Position = playfield_centre
}
}
});
}
[Test]
public void TestCircleNearEdge()
{
assertOk(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new HitCircle
{
StartTime = 3000,
Position = new Vector2(5, 5)
}
}
});
}
[Test]
public void TestCircleNearEdgeStackedOffscreen()
{
assertOffscreenCircle(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new HitCircle
{
StartTime = 3000,
Position = new Vector2(5, 5),
StackHeight = 5
}
}
});
}
[Test]
public void TestCircleOffscreen()
{
assertOffscreenCircle(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new HitCircle
{
StartTime = 3000,
Position = new Vector2(0, 0)
}
}
});
}
[Test]
public void TestSliderInCenter()
{
assertOk(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new Slider
{
StartTime = 3000,
Position = new Vector2(420, 240),
Path = new SliderPath(new[]
{
new PathControlPoint(new Vector2(0, 0), PathType.Linear),
new PathControlPoint(new Vector2(-100, 0))
}),
}
}
});
}
[Test]
public void TestSliderNearEdge()
{
assertOk(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new Slider
{
StartTime = 3000,
Position = playfield_centre,
Path = new SliderPath(new[]
{
new PathControlPoint(new Vector2(0, 0), PathType.Linear),
new PathControlPoint(new Vector2(0, -playfield_centre.Y + 5))
}),
}
}
});
}
[Test]
public void TestSliderNearEdgeStackedOffscreen()
{
assertOffscreenSlider(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new Slider
{
StartTime = 3000,
Position = playfield_centre,
Path = new SliderPath(new[]
{
new PathControlPoint(new Vector2(0, 0), PathType.Linear),
new PathControlPoint(new Vector2(0, -playfield_centre.Y + 5))
}),
StackHeight = 5
}
}
});
}
[Test]
public void TestSliderOffscreenStart()
{
assertOffscreenSlider(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new Slider
{
StartTime = 3000,
Position = new Vector2(0, 0),
Path = new SliderPath(new[]
{
new PathControlPoint(new Vector2(0, 0), PathType.Linear),
new PathControlPoint(playfield_centre)
}),
}
}
});
}
[Test]
public void TestSliderOffscreenEnd()
{
assertOffscreenSlider(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new Slider
{
StartTime = 3000,
Position = playfield_centre,
Path = new SliderPath(new[]
{
new PathControlPoint(new Vector2(0, 0), PathType.Linear),
new PathControlPoint(-playfield_centre)
}),
}
}
});
}
[Test]
public void TestSliderOffscreenPath()
{
assertOffscreenSlider(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new Slider
{
StartTime = 3000,
Position = playfield_centre,
Path = new SliderPath(new[]
{
// Circular arc shoots over the top of the screen.
new PathControlPoint(new Vector2(0, 0), PathType.PerfectCurve),
new PathControlPoint(new Vector2(-100, -200)),
new PathControlPoint(new Vector2(100, -200))
}),
}
}
});
}
private void assertOk(IBeatmap beatmap)
{
var context = new BeatmapVerifierContext(beatmap, new TestWorkingBeatmap(beatmap));
Assert.That(check.Run(context), Is.Empty);
}
private void assertOffscreenCircle(IBeatmap beatmap)
{
var context = new BeatmapVerifierContext(beatmap, new TestWorkingBeatmap(beatmap));
var issues = check.Run(context).ToList();
Assert.That(issues, Has.Count.EqualTo(1));
Assert.That(issues.Single().Template is CheckOffscreenObjects.IssueTemplateOffscreenCircle);
}
private void assertOffscreenSlider(IBeatmap beatmap)
{
var context = new BeatmapVerifierContext(beatmap, new TestWorkingBeatmap(beatmap));
var issues = check.Run(context).ToList();
Assert.That(issues, Has.Count.EqualTo(1));
Assert.That(issues.Single().Template is CheckOffscreenObjects.IssueTemplateOffscreenSlider);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using AutoRest.Core.ClientModel;
using AutoRest.Core.Logging;
using AutoRest.Core.Utilities;
using AutoRest.Swagger.Model;
using AutoRest.Swagger.Properties;
using ParameterLocation = AutoRest.Swagger.Model.ParameterLocation;
namespace AutoRest.Swagger
{
/// <summary>
/// The builder for building swagger operations into client model methods.
/// </summary>
public class OperationBuilder
{
private IList<string> _effectiveProduces;
private IList<string> _effectiveConsumes;
private SwaggerModeler _swaggerModeler;
private Operation _operation;
private const string APP_JSON_MIME = "application/json";
public OperationBuilder(Operation operation, SwaggerModeler swaggerModeler)
{
if (operation == null)
{
throw new ArgumentNullException("operation");
}
if (swaggerModeler == null)
{
throw new ArgumentNullException("swaggerModeler");
}
this._operation = operation;
this._swaggerModeler = swaggerModeler;
this._effectiveProduces = operation.Produces.Any() ? operation.Produces : swaggerModeler.ServiceDefinition.Produces;
this._effectiveConsumes = operation.Consumes.Any() ? operation.Consumes : swaggerModeler.ServiceDefinition.Consumes;
}
public Method BuildMethod(HttpMethod httpMethod, string url, string methodName, string methodGroup)
{
EnsureUniqueMethodName(methodName, methodGroup);
var method = new Method
{
HttpMethod = httpMethod,
Url = url,
Name = methodName,
SerializedName = _operation.OperationId
};
method.RequestContentType = _effectiveConsumes.FirstOrDefault() ?? APP_JSON_MIME;
string produce = _effectiveConsumes.FirstOrDefault(s => s.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrEmpty(produce))
{
method.RequestContentType = produce;
}
if (method.RequestContentType.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase) &&
method.RequestContentType.IndexOf("charset=", StringComparison.OrdinalIgnoreCase) == -1)
{
// Enable UTF-8 charset
method.RequestContentType += "; charset=utf-8";
}
method.Description = _operation.Description;
method.Summary = _operation.Summary;
method.ExternalDocsUrl = _operation.ExternalDocs?.Url;
// Service parameters
if (_operation.Parameters != null)
{
BuildMethodParameters(method);
}
// Build header object
var responseHeaders = new Dictionary<string, Header>();
foreach (var response in _operation.Responses.Values)
{
if (response.Headers != null)
{
response.Headers.ForEach(h => responseHeaders[h.Key] = h.Value);
}
}
var headerTypeName = string.Format(CultureInfo.InvariantCulture,
"{0}-{1}-Headers", methodGroup, methodName).Trim('-');
var headerType = new CompositeType
{
Name = headerTypeName,
SerializedName = headerTypeName,
Documentation = string.Format(CultureInfo.InvariantCulture, "Defines headers for {0} operation.", methodName)
};
responseHeaders.ForEach(h =>
{
var property = new Property
{
Name = h.Key,
SerializedName = h.Key,
Type = h.Value.GetBuilder(this._swaggerModeler).BuildServiceType(h.Key),
Documentation = h.Value.Description
};
headerType.Properties.Add(property);
});
if (!headerType.Properties.Any())
{
headerType = null;
}
// Response format
List<Stack<IType>> typesList = BuildResponses(method, headerType);
method.ReturnType = BuildMethodReturnType(typesList, headerType);
if (method.Responses.Count == 0)
{
method.ReturnType = method.DefaultResponse;
}
if (method.ReturnType.Headers != null)
{
_swaggerModeler.ServiceClient.HeaderTypes.Add(method.ReturnType.Headers as CompositeType);
}
// Copy extensions
_operation.Extensions.ForEach(extention => method.Extensions.Add(extention.Key, extention.Value));
return method;
}
private static IEnumerable<SwaggerParameter> DeduplicateParameters(IEnumerable<SwaggerParameter> parameters)
{
return parameters
.Select(s =>
{
// if parameter with the same name exists in Body and Path/Query then we need to give it a unique name
if (s.In == ParameterLocation.Body)
{
string newName = s.Name;
while (parameters.Any(t => t.In != ParameterLocation.Body &&
string.Equals(t.Name, newName,
StringComparison.OrdinalIgnoreCase)))
{
newName += "Body";
}
s.Name = newName;
}
// if parameter with same name exists in Query and Path, make Query one required
if (s.In == ParameterLocation.Query &&
parameters.Any(t => t.In == ParameterLocation.Path &&
string.Equals(t.Name, s.Name, StringComparison.OrdinalIgnoreCase)))
{
s.IsRequired = true;
}
return s;
});
}
private static void BuildMethodReturnTypeStack(IType type, List<Stack<IType>> types)
{
var typeStack = new Stack<IType>();
typeStack.Push(type);
types.Add(typeStack);
}
private void BuildMethodParameters(Method method)
{
foreach (var swaggerParameter in DeduplicateParameters(_operation.Parameters))
{
var parameter = ((ParameterBuilder)swaggerParameter.GetBuilder(_swaggerModeler)).Build();
method.Parameters.Add(parameter);
StringBuilder parameterName = new StringBuilder(parameter.Name);
parameterName = CollectionFormatBuilder.OnBuildMethodParameter(method, swaggerParameter,
parameterName);
if (swaggerParameter.In == ParameterLocation.Header)
{
method.RequestHeaders[swaggerParameter.Name] =
string.Format(CultureInfo.InvariantCulture, "{{{0}}}", parameterName);
}
}
}
private List<Stack<IType>> BuildResponses(Method method, CompositeType headerType)
{
string methodName = method.Name;
var typesList = new List<Stack<IType>>();
foreach (var response in _operation.Responses)
{
if (string.Equals(response.Key, "default", StringComparison.OrdinalIgnoreCase))
{
TryBuildDefaultResponse(methodName, response.Value, method, headerType);
}
else
{
if (
!(TryBuildResponse(methodName, response.Key.ToHttpStatusCode(), response.Value, method,
typesList, headerType) ||
TryBuildStreamResponse(response.Key.ToHttpStatusCode(), response.Value, method, typesList, headerType) ||
TryBuildEmptyResponse(methodName, response.Key.ToHttpStatusCode(), response.Value, method,
typesList, headerType)))
{
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture,
Resources.UnsupportedMimeTypeForResponseBody,
methodName,
response.Key));
}
}
}
return typesList;
}
private Response BuildMethodReturnType(List<Stack<IType>> types, IType headerType)
{
IType baseType = new PrimaryType(KnownPrimaryType.Object);
// Return null if no response is specified
if (types.Count == 0)
{
return new Response(null, headerType);
}
// Return first if only one return type
if (types.Count == 1)
{
return new Response(types.First().Pop(), headerType);
}
// BuildParameter up type inheritance tree
types.ForEach(typeStack =>
{
IType type = typeStack.Peek();
while (!Equals(type, baseType))
{
if (type is CompositeType && _swaggerModeler.ExtendedTypes.ContainsKey(type.Name))
{
type = _swaggerModeler.GeneratedTypes[_swaggerModeler.ExtendedTypes[type.Name]];
}
else
{
type = baseType;
}
typeStack.Push(type);
}
});
// Eliminate commonly shared base classes
while (!types.First().IsNullOrEmpty())
{
IType currentType = types.First().Peek();
foreach (var typeStack in types)
{
IType t = typeStack.Pop();
if (!Equals(t, currentType))
{
return new Response(baseType, headerType);
}
}
baseType = currentType;
}
return new Response(baseType, headerType);
}
private bool TryBuildStreamResponse(HttpStatusCode responseStatusCode, OperationResponse response,
Method method, List<Stack<IType>> types, IType headerType)
{
bool handled = false;
if (SwaggerOperationProducesNotEmpty())
{
if (response.Schema != null)
{
IType serviceType = response.Schema.GetBuilder(_swaggerModeler)
.BuildServiceType(response.Schema.Reference.StripDefinitionPath());
Debug.Assert(serviceType != null);
BuildMethodReturnTypeStack(serviceType, types);
var compositeType = serviceType as CompositeType;
if (compositeType != null)
{
VerifyFirstPropertyIsByteArray(compositeType);
}
method.Responses[responseStatusCode] = new Response(serviceType, headerType);
handled = true;
}
}
return handled;
}
private void VerifyFirstPropertyIsByteArray(CompositeType serviceType)
{
var referenceKey = serviceType.Name;
var responseType = _swaggerModeler.GeneratedTypes[referenceKey];
var property = responseType.Properties.FirstOrDefault(p => p.Type is PrimaryType && ((PrimaryType)p.Type).Type == KnownPrimaryType.ByteArray);
if (property == null)
{
throw new KeyNotFoundException(
"Please specify a field with type of System.Byte[] to deserialize the file contents to");
}
}
private bool TryBuildResponse(string methodName, HttpStatusCode responseStatusCode,
OperationResponse response, Method method, List<Stack<IType>> types, IType headerType)
{
bool handled = false;
IType serviceType;
if (SwaggerOperationProducesJson())
{
if (TryBuildResponseBody(methodName, response,
s => GenerateResponseObjectName(s, responseStatusCode), out serviceType))
{
method.Responses[responseStatusCode] = new Response(serviceType, headerType);
BuildMethodReturnTypeStack(serviceType, types);
handled = true;
}
}
return handled;
}
private bool TryBuildEmptyResponse(string methodName, HttpStatusCode responseStatusCode,
OperationResponse response, Method method, List<Stack<IType>> types, IType headerType)
{
bool handled = false;
if (response.Schema == null)
{
method.Responses[responseStatusCode] = new Response(null, headerType);
handled = true;
}
else
{
if (_operation.Produces.IsNullOrEmpty())
{
method.Responses[responseStatusCode] = new Response(new PrimaryType(KnownPrimaryType.Object), headerType);
BuildMethodReturnTypeStack(new PrimaryType(KnownPrimaryType.Object), types);
handled = true;
}
var unwrapedSchemaProperties =
_swaggerModeler.Resolver.Unwrap(response.Schema).Properties;
if (unwrapedSchemaProperties != null && unwrapedSchemaProperties.Any())
{
Logger.LogWarning(Resources.NoProduceOperationWithBody,
methodName);
}
}
return handled;
}
private void TryBuildDefaultResponse(string methodName, OperationResponse response, Method method, IType headerType)
{
IType errorModel = null;
if (SwaggerOperationProducesJson())
{
if (TryBuildResponseBody(methodName, response, s => GenerateErrorModelName(s), out errorModel))
{
method.DefaultResponse = new Response(errorModel, headerType);
}
}
}
private bool TryBuildResponseBody(string methodName, OperationResponse response,
Func<string, string> typeNamer, out IType responseType)
{
bool handled = false;
responseType = null;
if (SwaggerOperationProducesJson())
{
if (response.Schema != null)
{
string referenceKey;
if (response.Schema.Reference != null)
{
referenceKey = response.Schema.Reference.StripDefinitionPath();
response.Schema.Reference = referenceKey;
}
else
{
referenceKey = typeNamer(methodName);
}
responseType = response.Schema.GetBuilder(_swaggerModeler).BuildServiceType(referenceKey);
handled = true;
}
}
return handled;
}
private bool SwaggerOperationProducesJson()
{
return _effectiveProduces != null &&
_effectiveProduces.Any(s => s.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase));
}
private bool SwaggerOperationProducesNotEmpty()
{
return _effectiveProduces != null
&& _effectiveProduces.Any();
}
private void EnsureUniqueMethodName(string methodName, string methodGroup)
{
string serviceOperationPrefix = "";
if (methodGroup != null)
{
serviceOperationPrefix = methodGroup + "_";
}
if (_swaggerModeler.ServiceClient.Methods.Any(m => m.Group == methodGroup && m.Name == methodName))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
Resources.DuplicateOperationIdException,
serviceOperationPrefix + methodName));
}
}
private static string GenerateResponseObjectName(string methodName, HttpStatusCode responseStatusCode)
{
return string.Format(CultureInfo.InvariantCulture,
"{0}{1}Response", methodName, responseStatusCode);
}
private static string GenerateErrorModelName(string methodName)
{
return string.Format(CultureInfo.InvariantCulture,
"{0}ErrorModel", methodName);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices.ComTypes;
using Microsoft.Build.Tasks;
using Marshal = System.Runtime.InteropServices.Marshal;
using Xunit;
namespace Microsoft.Build.UnitTests
{
/// <summary>
/// All possible failure points in MockTypeLib/MockTypeInfo classes. When adding new functionality there,
/// add a new failure point here and add a corresponding call to faultInjector.FailurePointThrow in the method.
/// </summary>
public enum MockTypeLibrariesFailurePoints
{
// MockTypeLibrary.ITypeLib
ITypeLib_GetLibAttr = 1,
ITypeLib_ReleaseTLibAttr,
ITypeLib_GetTypeInfo,
ITypeLib_GetTypeInfoCount,
// MockTypeLibrary.ITypeLib2
ITypeLib2_GetCustData,
// MockTypeInfo.ITypeInfo
ITypeInfo_GetContainingTypeLib,
ITypeInfo_GetTypeAttr,
ITypeInfo_ReleaseTypeAttr,
ITypeInfo_GetRefTypeOfImplType,
ITypeInfo_GetRefTypeInfo,
ITypeInfo_GetVarDesc,
ITypeInfo_ReleaseVarDesc,
ITypeInfo_GetFuncDesc,
ITypeInfo_ReleaseFuncDesc,
ITypeInfo_GetDocumentation
}
/// <summary>
/// Mock class for the ITypeLib interface
/// </summary>
public class MockTypeLib : ITypeLib, ITypeLib2
{
private List<MockTypeInfo> _containedTypeInfos;
public List<MockTypeInfo> ContainedTypeInfos
{
get
{
return _containedTypeInfos;
}
}
private TYPELIBATTR _typeLibAttributes;
public TYPELIBATTR Attributes
{
get
{
return _typeLibAttributes;
}
}
private string _exportedFromComPlus;
public string ExportedFromComPlus
{
set
{
_exportedFromComPlus = value;
}
}
// helper class for unmanaged allocations and leak tracking
private MockUnmanagedMemoryHelper _memoryHelper;
// helper class for injecting failures into chosen method calls
private MockFaultInjectionHelper<MockTypeLibrariesFailurePoints> _faultInjector;
/// <summary>
/// Public constructor
/// </summary>
public MockTypeLib()
{
_containedTypeInfos = new List<MockTypeInfo>();
_typeLibAttributes.guid = Guid.NewGuid();
_exportedFromComPlus = null;
_memoryHelper = new MockUnmanagedMemoryHelper();
_faultInjector = new MockFaultInjectionHelper<MockTypeLibrariesFailurePoints>();
}
/// <summary>
/// Create a mock type library with a specific guid
/// </summary>
/// <param name="guid"></param>
public MockTypeLib(Guid guid)
: this()
{
_typeLibAttributes.guid = guid;
}
/// <summary>
/// Tells the type lib to inject a specific failure (exception) at the chosen failure point.
/// </summary>
/// <param name="failurePoint"></param>
/// <param name="exceptionToThrow"></param>
public void InjectFailure(MockTypeLibrariesFailurePoints failurePoint, Exception exceptionToThrow)
{
_faultInjector.InjectFailure(failurePoint, exceptionToThrow);
}
/// <summary>
/// Add a new type info to the type library
/// </summary>
/// <param name="typeInfo"></param>
public void AddTypeInfo(MockTypeInfo typeInfo)
{
_containedTypeInfos.Add(typeInfo);
typeInfo.ContainingTypeLib = this;
typeInfo.IndexInContainingTypeLib = _containedTypeInfos.Count - 1;
typeInfo.SetFaultInjector(_faultInjector);
}
/// <summary>
/// Helper method for verifying there are no memory leaks from unmanaged allocations
/// </summary>
public void AssertAllHandlesReleased()
{
_memoryHelper.AssertAllHandlesReleased();
foreach (MockTypeInfo typeInfo in _containedTypeInfos)
{
typeInfo.AssertAllHandlesReleased();
}
}
#region Implemented ITypeLib members
public void GetLibAttr(out IntPtr ppTLibAttr)
{
// Fail BEFORE allocating the handle to avoid leaks. If the real COM object fails in this method
// and doesn't return the handle or clean it up itself there's not much we can do to avoid the leak.
_faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeLib_GetLibAttr);
ppTLibAttr = _memoryHelper.AllocateHandle(Marshal.SizeOf<TYPELIBATTR>());
Marshal.StructureToPtr(this.Attributes, ppTLibAttr, false);
}
public void ReleaseTLibAttr(IntPtr pTLibAttr)
{
_memoryHelper.FreeHandle(pTLibAttr);
// Fail AFTER releasing the handle to avoid leaks. If the real COM object fails in this method
// there's really nothing we can do to avoid leaking stuff
_faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeLib_ReleaseTLibAttr);
}
public void GetTypeInfo(int index, out ITypeInfo ppTI)
{
_faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeLib_GetTypeInfo);
Assert.True(index >= 0 && index < _containedTypeInfos.Count);
ppTI = _containedTypeInfos[index];
}
public int GetTypeInfoCount()
{
_faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeLib_GetTypeInfoCount);
return _containedTypeInfos.Count;
}
#endregion
#region Stubbed ITypeLib members
public void FindName(string szNameBuf, int lHashVal, ITypeInfo[] ppTInfo, int[] rgMemId, ref short pcFound)
{
throw new Exception("The method or operation is not implemented.");
}
public void GetDocumentation(int index, out string strName, out string strDocString, out int dwHelpContext, out string strHelpFile)
{
throw new Exception("The method or operation is not implemented.");
}
public void GetTypeComp(out ITypeComp ppTComp)
{
throw new Exception("The method or operation is not implemented.");
}
public void GetTypeInfoOfGuid(ref Guid guid, out ITypeInfo ppTInfo)
{
throw new Exception("The method or operation is not implemented.");
}
public void GetTypeInfoType(int index, out TYPEKIND pTKind)
{
throw new Exception("The method or operation is not implemented.");
}
public bool IsName(string szNameBuf, int lHashVal)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region Implemented ITypeLib2 members
public void GetCustData(ref Guid guid, out object pVarVal)
{
_faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeLib2_GetCustData);
if (guid == NativeMethods.GUID_ExportedFromComPlus)
{
pVarVal = _exportedFromComPlus;
}
else
{
Assert.True(false, "unexpected guid in ITypeLib2.GetCustData");
pVarVal = null;
}
}
#endregion
#region Stubbed ITypeLib2 Members
public void GetAllCustData(IntPtr pCustData)
{
throw new Exception("The method or operation is not implemented.");
}
public void GetDocumentation2(int index, out string pbstrHelpString, out int pdwHelpStringContext, out string pbstrHelpStringDll)
{
throw new Exception("The method or operation is not implemented.");
}
public void GetLibStatistics(IntPtr pcUniqueNames, out int pcchUniqueNames)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
}
| |
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com)
// 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 Ayende Rahien nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using Castle.Windsor;
using NHibernate;
using NHibernate.Cfg;
using Environment=NHibernate.Cfg.Environment;
namespace Rhino.Commons.ForTesting
{
public enum DatabaseEngine
{
SQLite,
MsSqlCe,
MsSql2005,
MsSql2005Express
}
public enum PersistenceFramework
{
ActiveRecord,
NHibernate
}
/// <summary>
/// Encapsulates the construction, initialization and disposal of the
/// database and UnitOfWork context required for testing. Allows different
/// implementations of this context to be substituted at runtime
/// </summary>
public abstract class UnitOfWorkTestContext : IDisposable
{
private const string activeRecordTestContextType = "Rhino.Commons.ForTesting.ARUnitOfWorkTestContext, Rhino.Commons.ActiveRecord";
private static Type activeRecordType;
public static UnitOfWorkTestContext For(PersistenceFramework framwork,
string rhinoContainerConfig,
UnitOfWorkTestContextDbStrategy dbStrategy,
MappingInfo mappingInfo)
{
switch (framwork)
{
case PersistenceFramework.ActiveRecord:
return CreateActiveRecordImplementation(dbStrategy, mappingInfo, rhinoContainerConfig);
case PersistenceFramework.NHibernate:
return new NHibernateUnitOfWorkTestContext(dbStrategy, rhinoContainerConfig, mappingInfo);
default:
throw new ArgumentOutOfRangeException();
}
}
public static UnitOfWorkTestContext For(PersistenceFramework framwork,
IWindsorContainer container,
UnitOfWorkTestContextDbStrategy dbStrategy,
MappingInfo mappingInfo)
{
UnitOfWorkTestContext context = For(framwork, string.Empty, dbStrategy, mappingInfo);
context.rhinoContainer = container;
return context;
}
private static UnitOfWorkTestContext CreateActiveRecordImplementation(UnitOfWorkTestContextDbStrategy dbStrategy,
MappingInfo mappingInfo,
string rhinoContainerConfig)
{
if (activeRecordType == null)
activeRecordType = Type.GetType(activeRecordTestContextType);
if (activeRecordType == null)
{
throw new InvalidOperationException("Could not find Active Record context type. Did you forget to reference 'Rhino.Commons.ActiveRecord'?");
}
return
(UnitOfWorkTestContext)
Activator.CreateInstance(activeRecordType,
new object[] {dbStrategy, rhinoContainerConfig, mappingInfo});
}
private readonly string rhinoContainerConfigPath;
private readonly UnitOfWorkTestContextDbStrategy dbStrategy;
private readonly MappingInfo mappingInfo;
private IWindsorContainer rhinoContainer;
private int unitOfWorkNestingLevel = -1;
public UnitOfWorkTestContext(UnitOfWorkTestContextDbStrategy dbStrategy,
string rhinoContainerConfigPath,
MappingInfo assemblies)
{
this.rhinoContainerConfigPath = rhinoContainerConfigPath ?? string.Empty;
this.dbStrategy = dbStrategy;
mappingInfo = assemblies;
this.dbStrategy.TestContext = this;
}
protected MappingInfo MappingInfo
{
get { return mappingInfo; }
}
public abstract Configuration Configuration
{
get;
}
public string DatabaseName
{
get { return dbStrategy.DatabaseName; }
}
public DatabaseEngine DatabaseEngine
{
get { return dbStrategy.DatabaseEngine; }
}
protected UnitOfWorkTestContextDbStrategy DbStrategy
{
get { return dbStrategy; }
}
public abstract PersistenceFramework Framework { get; }
public IWindsorContainer RhinoContainer
{
get
{
if (string.IsNullOrEmpty(rhinoContainerConfigPath) && rhinoContainer==null)
return null;
return
rhinoContainer =
rhinoContainer ?? new RhinoContainer(rhinoContainerConfigPath);
}
}
public string RhinoContainerConfigPath
{
get { return rhinoContainerConfigPath; }
}
public abstract ISessionFactory SessionFactory { get; }
public int UnitOfWorkNestingLevel
{
get { return unitOfWorkNestingLevel; }
}
/// <summary>
/// Starts a <see cref="UnitOfWork" /> and creates the db schema.
/// </summary>
/// <example>Using <see cref="Commons.RhinoContainer" />, <see cref="IoC" />, and <see cref="UnitOfWork" /> in your tests.
/// <code lang="c#" escaped="true">
/// using MbUnit.Framework;
/// using Rhino.Commons;
/// using Rhino.Commons.ForTesting;
///
/// [TestFixture]
/// public class FooTest : DatabaseTestFixtureBase
/// {
/// [TestFixtureSetup]
/// public void TestFixtureSetup()
/// {
/// IntializeNHibernateAndIoC(PersistenceFramework.NHibernate, "RhinoContainer.boo", typeof(Foo).Assembly);
/// }
///
/// [Setup]
/// public void TestSetup()
/// {
/// /// Creates a top level UnitOfWork, remember to clean me up
/// CurrentContext.CreateUnitOfWork();
/// }
///
/// [TearDown]
/// public void TestTearDown()
/// {
/// /// Cleanup the top level UnitOfWork
/// CurrentContext.DisposeUnitOfWork();
/// }
///
/// [Test]
/// public void CanSaveFoo()
/// {
/// Foo f = new Foo();
/// Foo res = null;
/// f.Name = "Bar";
///
/// Assert.AreEqual(Guid.Empty, f.Id);
///
/// With.Transaction(delegate
/// {
/// IoC.Resolve<IRepository<Foo>>().Save(f);
/// });
///
/// Assert.AreNotEqual(Guid.Empty, f.Id);
///
/// using(UnitOfWork.Start())
/// res = IoC.Resolve<IRepository<Foo>>().Load(f.Id);
///
/// Assert.IsNotNull(res);
/// Assert.AreEqual("Bar", res.Name);
/// }
/// }
/// </code>
/// </example>
/// <seealso cref="Commons.RhinoContainer" />
/// <seealso cref="IoC" />
/// <seealso cref="UnitOfWork" />
public virtual void CreateUnitOfWork()
{
if (unitOfWorkNestingLevel == 0)
{
throw new InvalidOperationException(
"Cannot create a nested UnitOfWork with this method. Use CreateNestedUnitOfWork() instead");
}
UnitOfWork.Start();
SetupDatabase(UnitOfWork.CurrentSession);
unitOfWorkNestingLevel = 0;
}
public IUnitOfWork CreateNestedUnitOfWork()
{
if (unitOfWorkNestingLevel == -1)
{
throw new InvalidOperationException(
"Did you forgot to call CreateUnitOfWork()? UnitOfWorkTestContext did not create any previous unit of work.");
}
IUnitOfWork uow =
UnitOfWork.Start(UnitOfWork.CurrentSession.Connection, UnitOfWorkNestingOptions.CreateNewOrNestUnitOfWork);
unitOfWorkNestingLevel += 1;
return uow;
}
/// <summary>
/// Opens an NHibernate session and creates the db schema.
/// </summary>
/// <returns>The open NHibernate session.</returns>
public virtual ISession CreateSession()
{
ISession session = dbStrategy.CreateSession();
SetupDatabase(session);
return session;
}
public void DisposeSession(ISession sessionToClose)
{
//explicit disposing of connection is required (??) for in memory databases
IDbConnection con = sessionToClose.Connection;
sessionToClose.Dispose();
con.Dispose();
}
public virtual void DisposeUnitOfWork()
{
UnitOfWork.Current.Dispose();
unitOfWorkNestingLevel -= 1;
}
public abstract void InitializeContainerAndUowFactory();
/// <summary>
/// Creates the in db schema using the session.
/// </summary>
/// <param name="session">An open NHibernate session.</param>
public void SetupDatabase(ISession session)
{
dbStrategy.SetupDatabase(session);
}
public override string ToString()
{
return
string.Format("Framework: {0}; DatabaseEngine: {1}; DatabaseName: {2}; RhinoContainerPath: {3}",
Framework,
DatabaseEngine,
DatabaseName,
RhinoContainerConfigPath ?? "");
}
#region IDisposable Members
public void Dispose()
{
if (rhinoContainer != null) rhinoContainer.Dispose();
}
#endregion
private class NHibernateUnitOfWorkTestContext : UnitOfWorkTestContext
{
private Configuration configs;
private ISessionFactory sessionFactory;
public NHibernateUnitOfWorkTestContext(UnitOfWorkTestContextDbStrategy dbStrategy,
string rhinoContainerConfigPath,
MappingInfo assemblies)
: base(dbStrategy, rhinoContainerConfigPath, assemblies) {}
public override Configuration Configuration
{
get { return configs = configs ?? CreateConfigs(); }
}
public override PersistenceFramework Framework
{
get { return PersistenceFramework.NHibernate; }
}
public override ISessionFactory SessionFactory
{
get { return sessionFactory = sessionFactory ?? BuildSessionFactory(); }
}
private ISessionFactory BuildSessionFactory()
{
//TODO: This is hack for rev 1705. there should be a better way
if (Configuration.GetProperty(Environment.ProxyFactoryFactoryClass) == null)
Configuration.Properties[Environment.ProxyFactoryFactoryClass] = "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle";
ISessionFactory sessionFactory = Configuration.BuildSessionFactory();
foreach (INHibernateInitializationAware initializer in GetNHibernateInitializers())
initializer.Initialized(configs, sessionFactory);
return sessionFactory;
}
private Configuration CreateConfigs()
{
foreach (INHibernateInitializationAware initializer in GetNHibernateInitializers())
initializer.BeforeInitialization();
Configuration cfg = new Configuration();
cfg.Properties = DbStrategy.NHibernateProperties;
foreach (KeyValuePair<string, string> import in MappingInfo.QueryLanguageImports)
cfg.Imports[import.Key] = import.Value;
foreach (Assembly assembly in MappingInfo.MappingAssemblies)
cfg.AddAssembly(assembly);
foreach (INHibernateInitializationAware initializer in GetNHibernateInitializers())
initializer.Configured(cfg);
return cfg;
}
private IEnumerable<INHibernateInitializationAware> GetNHibernateInitializers()
{
INHibernateInitializationAware[] initializers = new INHibernateInitializationAware[]{};
if (MappingInfo.NHInitializationAware != null)
{
// locally configured initializer takes precendence over a container component
initializers = new INHibernateInitializationAware[] {MappingInfo.NHInitializationAware};
}
else if (IoC.IsInitialized && IoC.Container.Kernel.HasComponent(typeof(INHibernateInitializationAware)))
{
initializers = IoC.ResolveAll<INHibernateInitializationAware>();
}
if (initializers.Length == 0)
yield break;
foreach (INHibernateInitializationAware initializer in initializers)
yield return initializer;
}
public override void InitializeContainerAndUowFactory()
{
ResetRhinoContainer();
if (RhinoContainer != null)
{
IoC.Initialize(RhinoContainer);
NHibernateUnitOfWorkFactory hibernateUnitOfWorkFactory =
(NHibernateUnitOfWorkFactory)IoC.Resolve<IUnitOfWorkFactory>();
hibernateUnitOfWorkFactory.RegisterSessionFactory(SessionFactory);
}
}
protected void ResetRhinoContainer()
{
if (!string.IsNullOrEmpty(rhinoContainerConfigPath))
{
if (IoC.IsInitialized)
IoC.Reset();
rhinoContainer = null;
}
else
{
IoC.Reset(rhinoContainer);
}
}
}
}
}
| |
/*
Microsoft Automatic Graph Layout,MSAGL
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.
*/
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Windows.Forms;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Drawing;
using BBox = Microsoft.Msagl.Core.Geometry.Rectangle;
using Color = System.Drawing.Color;
using MouseButtons = System.Windows.Forms.MouseButtons;
using P2 = Microsoft.Msagl.Core.Geometry.Point;
namespace Microsoft.Msagl.GraphViewerGdi {
/// <summary>
/// this class serves as a drawing panel for GViewer
/// </summary>
internal class DrawingPanel : Control {
readonly Color rubberRectColor = Color.Black;
MouseButtons currentPressedButton;
GViewer gViewer;
System.Drawing.Point mouseDownPoint;
System.Drawing.Point mouseUpPoint;
P2 rubberLineEnd;
P2 rubberLineStart;
System.Drawing.Rectangle rubberRect;
const FrameStyle RubberRectStyle = FrameStyle.Dashed;
bool zoomWindow;
PlaneTransformation mouseDownTransform;
bool NeedToEraseRubber { get; set; }
internal GViewer GViewer {
private get { return gViewer; }
set { gViewer = value; }
}
DraggingMode MouseDraggingMode {
get {
if (gViewer.panButton.Pushed)
return DraggingMode.Pan;
if (gViewer.windowZoomButton.Pushed)
return DraggingMode.WindowZoom;
return DraggingMode.Default;
}
}
bool DrawingRubberEdge { get; set; }
P2 RubberLineEnd {
get { return rubberLineEnd; }
set {
if (DrawingRubberEdge)
Invalidate(CreateRectForRubberEdge());
rubberLineEnd = value;
}
}
EdgeGeometry CurrentRubberEdge { get; set; }
internal void SetDoubleBuffering() {
// the magic calls for invoking doublebuffering
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
}
protected override void OnPaint(PaintEventArgs e) {
if (gViewer != null && gViewer.Graph != null && gViewer.Graph.GeometryGraph != null) {
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
gViewer.ProcessOnPaint(e.Graphics, null);
}
if (CurrentRubberEdge != null)
using (GraphicsPath gp = Draw.CreateGraphicsPath(CurrentRubberEdge.Curve))
using (var pen = new Pen(Brushes.Black, (float) GViewer.LineThicknessForEditing))
e.Graphics.DrawPath(pen, gp);
if (DrawingRubberEdge)
e.Graphics.DrawLine(new Pen(Brushes.Black, (float) GViewer.LineThicknessForEditing),
(float) rubberLineStart.X, (float) rubberLineStart.Y, (float) RubberLineEnd.X,
(float) RubberLineEnd.Y);
base.OnPaint(e); // Filippo Polo 13/11/07; if I don't do this, onpaint events won't be invoked
gViewer.RaisePaintEvent(e);
}
protected override void OnMouseDown(MouseEventArgs e) {
base.OnMouseDown(e);
MsaglMouseEventArgs iArgs = CreateMouseEventArgs(e);
gViewer.RaiseMouseDownEvent(iArgs);
if (!iArgs.Handled) {
currentPressedButton = e.Button;
if (currentPressedButton == MouseButtons.Left)
if (ClientRectangle.Contains(PointToClient(MousePosition))) {
mouseDownPoint = new Point(e.X, e.Y);
if (MouseDraggingMode != DraggingMode.Pan)
zoomWindow = true;
else {
mouseDownTransform = gViewer.Transform.Clone();
}
}
}
}
void DrawXorFrame() {
ControlPaint.DrawReversibleFrame(rubberRect, rubberRectColor, RubberRectStyle);
NeedToEraseRubber = !NeedToEraseRubber;
}
protected override void OnMouseUp(MouseEventArgs args) {
base.OnMouseUp(args);
MsaglMouseEventArgs iArgs = CreateMouseEventArgs(args);
gViewer.RaiseMouseUpEvent(iArgs);
if (NeedToEraseRubber)
DrawXorFrame();
if (!iArgs.Handled) {
if (gViewer.OriginalGraph != null && MouseDraggingMode == DraggingMode.WindowZoom) {
var p = mouseDownPoint;
double f = Math.Max(Math.Abs(p.X - args.X), Math.Abs(p.Y - args.Y))/GViewer.Dpi;
if (f > gViewer.ZoomWindowThreshold && zoomWindow) {
mouseUpPoint = new Point(args.X, args.Y);
if (ClientRectangle.Contains(mouseUpPoint)) {
var r = GViewer.RectFromPoints(mouseDownPoint, mouseUpPoint);
r.Intersect(gViewer.DestRect);
if (GViewer.ModifierKeyWasPressed() == false) {
mouseDownPoint.X = r.Left;
mouseDownPoint.Y = r.Top;
mouseUpPoint.X = r.Right;
mouseUpPoint.Y = r.Bottom;
P2 p1 = gViewer.ScreenToSource(mouseDownPoint);
P2 p2 = gViewer.ScreenToSource(mouseUpPoint);
double sc = Math.Min((double) ClientRectangle.Width/r.Width,
ClientRectangle.Height/(double) r.Height);
P2 center = 0.5f*(p1 + p2);
gViewer.SetTransformOnScaleAndCenter(sc, center);
Invalidate();
}
}
}
}
}
zoomWindow = false;
}
/// <summary>
/// Set context menu strip
/// </summary>
/// <param name="contexMenuStrip"></param>
public void SetCms(ContextMenuStrip contexMenuStrip) {
MouseClick +=
delegate(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Right) {
var newE = new MouseEventArgs(
MouseButtons.None,
e.Clicks,
e.X,
e.Y,
e.Delta);
OnMouseMove(newE);
contexMenuStrip.Show(this, e.X, e.Y);
}
};
}
protected override void OnMouseMove(MouseEventArgs args) {
MsaglMouseEventArgs iArgs = CreateMouseEventArgs(args);
gViewer.RaiseMouseMoveEvent(iArgs);
gViewer.RaiseRegularMouseMove(args);
if (!iArgs.Handled) {
if (gViewer.Graph != null) {
SetCursor(args);
if (MouseDraggingMode == DraggingMode.Pan)
ProcessPan(args);
else if (zoomWindow) //the user is holding the left button
DrawZoomWindow(args);
else
HitIfBbNodeIsNotNull(args);
}
}
}
void HitIfBbNodeIsNotNull(MouseEventArgs args) {
if (gViewer.DGraph != null && gViewer.BbNode != null)
gViewer.Hit(args);
}
static MsaglMouseEventArgs CreateMouseEventArgs(MouseEventArgs args) {
return new ViewerMouseEventArgs(args);
}
void SetCursor(MouseEventArgs args) {
Cursor cur;
if (MouseDraggingMode == DraggingMode.Pan) {
cur = args.Button == MouseButtons.Left
? gViewer.panGrabCursor
: gViewer.panOpenCursor;
} else
cur = gViewer.originalCursor;
if (cur != null)
Cursor = cur;
}
void DrawZoomWindow(MouseEventArgs args) {
mouseUpPoint.X = args.X;
mouseUpPoint.Y = args.Y;
if (NeedToEraseRubber)
DrawXorFrame();
if (ClientRectangle.Contains(PointToClient(MousePosition))) {
rubberRect = GViewer.RectFromPoints(PointToScreen(mouseDownPoint), PointToScreen(mouseUpPoint));
DrawXorFrame();
}
}
void ProcessPan(MouseEventArgs args) {
if (ClientRectangle.Contains(args.X, args.Y)) {
if (args.Button == MouseButtons.Left) {
if (mouseDownTransform != null) {
gViewer.Transform[0, 2] = mouseDownTransform[0, 2] + args.X - mouseDownPoint.X;
gViewer.Transform[1, 2] = mouseDownTransform[1, 2] + args.Y - mouseDownPoint.Y;
}
gViewer.Invalidate();
} else
GViewer.Hit(args);
}
}
protected override void OnKeyUp(KeyEventArgs e) {
gViewer.OnKey(e);
base.OnKeyUp(e);
}
internal void DrawRubberLine(MsaglMouseEventArgs args) {
RubberLineEnd = gViewer.ScreenToSource(new Point(args.X, args.Y));
DrawRubberLineWithKnownEnd();
}
internal void DrawRubberLine(P2 point) {
RubberLineEnd = point;
DrawRubberLineWithKnownEnd();
}
void DrawRubberLineWithKnownEnd() {
DrawingRubberEdge = true;
Invalidate(CreateRectForRubberEdge());
}
Rectangle CreateRectForRubberEdge() {
var rect = new BBox(rubberLineStart, RubberLineEnd);
double w = gViewer.LineThicknessForEditing;
var del = new P2(-w, w);
rect.Add(rect.LeftTop + del);
rect.Add(rect.RightBottom - del);
return GViewer.CreateScreenRectFromTwoCornersInTheSource(rect.LeftTop, rect.RightBottom);
}
internal void StopDrawRubberLine() {
DrawingRubberEdge = false;
Invalidate(CreateRectForRubberEdge());
}
internal void MarkTheStartOfRubberLine(P2 point) {
rubberLineStart = point;
}
internal void DrawRubberEdge(EdgeGeometry edgeGeometry) {
BBox rectToInvalidate = edgeGeometry.BoundingBox;
if (CurrentRubberEdge != null) {
BBox b = CurrentRubberEdge.BoundingBox;
rectToInvalidate.Add(b);
}
CurrentRubberEdge = edgeGeometry;
GViewer.Invalidate(GViewer.CreateScreenRectFromTwoCornersInTheSource(rectToInvalidate.LeftTop,
rectToInvalidate.RightBottom));
}
internal void StopDrawingRubberEdge() {
if (CurrentRubberEdge != null)
GViewer.Invalidate(
GViewer.CreateScreenRectFromTwoCornersInTheSource(
CurrentRubberEdge.BoundingBox.LeftTop,
CurrentRubberEdge.BoundingBox.RightBottom));
CurrentRubberEdge = null;
}
}
}
| |
using System;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto.Generators
{
internal class DHParametersHelper
{
// The primes b/w 2 and ~2^10
/*
3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349
353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463
467 479 487 491 499 503 509 521 523 541
547 557 563 569 571 577 587 593 599 601
607 613 617 619 631 641 643 647 653 659
661 673 677 683 691 701 709 719 727 733
739 743 751 757 761 769 773 787 797 809
811 821 823 827 829 839 853 857 859 863
877 881 883 887 907 911 919 929 937 941
947 953 967 971 977 983 991 997
1009 1013 1019 1021 1031
*/
// Each list has a product < 2^31
private static readonly int[][] primeLists = new int[][]
{
new int[]{ 3, 5, 7, 11, 13, 17, 19, 23 },
new int[]{ 29, 31, 37, 41, 43 },
new int[]{ 47, 53, 59, 61, 67 },
new int[]{ 71, 73, 79, 83 },
new int[]{ 89, 97, 101, 103 },
new int[]{ 107, 109, 113, 127 },
new int[]{ 131, 137, 139, 149 },
new int[]{ 151, 157, 163, 167 },
new int[]{ 173, 179, 181, 191 },
new int[]{ 193, 197, 199, 211 },
new int[]{ 223, 227, 229 },
new int[]{ 233, 239, 241 },
new int[]{ 251, 257, 263 },
new int[]{ 269, 271, 277 },
new int[]{ 281, 283, 293 },
new int[]{ 307, 311, 313 },
new int[]{ 317, 331, 337 },
new int[]{ 347, 349, 353 },
new int[]{ 359, 367, 373 },
new int[]{ 379, 383, 389 },
new int[]{ 397, 401, 409 },
new int[]{ 419, 421, 431 },
new int[]{ 433, 439, 443 },
new int[]{ 449, 457, 461 },
new int[]{ 463, 467, 479 },
new int[]{ 487, 491, 499 },
new int[]{ 503, 509, 521 },
new int[]{ 523, 541, 547 },
new int[]{ 557, 563, 569 },
new int[]{ 571, 577, 587 },
new int[]{ 593, 599, 601 },
new int[]{ 607, 613, 617 },
new int[]{ 619, 631, 641 },
new int[]{ 643, 647, 653 },
new int[]{ 659, 661, 673 },
new int[]{ 677, 683, 691 },
new int[]{ 701, 709, 719 },
new int[]{ 727, 733, 739 },
new int[]{ 743, 751, 757 },
new int[]{ 761, 769, 773 },
new int[]{ 787, 797, 809 },
new int[]{ 811, 821, 823 },
new int[]{ 827, 829, 839 },
new int[]{ 853, 857, 859 },
new int[]{ 863, 877, 881 },
new int[]{ 883, 887, 907 },
new int[]{ 911, 919, 929 },
new int[]{ 937, 941, 947 },
new int[]{ 953, 967, 971 },
new int[]{ 977, 983, 991 },
new int[]{ 997, 1009, 1013 },
new int[]{ 1019, 1021, 1031 },
};
private static readonly BigInteger Six = BigInteger.ValueOf(6);
private static readonly int[] primeProducts;
private static readonly BigInteger[] PrimeProducts;
static DHParametersHelper()
{
primeProducts = new int[primeLists.Length];
PrimeProducts = new BigInteger[primeLists.Length];
for (int i = 0; i < primeLists.Length; ++i)
{
int[] primeList = primeLists[i];
int product = 1;
for (int j = 0; j < primeList.Length; ++j)
{
product *= primeList[j];
}
primeProducts[i] = product;
PrimeProducts[i] = BigInteger.ValueOf(product);
}
}
// Finds a pair of prime BigInteger's {p, q: p = 2q + 1}
internal static BigInteger[] GenerateSafePrimes(
int size,
int certainty,
SecureRandom random)
{
BigInteger p, q;
int qLength = size - 1;
if (size <= 32)
{
for (;;)
{
q = new BigInteger(qLength, 2, random);
p = q.ShiftLeft(1).Add(BigInteger.One);
if (p.IsProbablePrime(certainty)
&& (certainty <= 2 || q.IsProbablePrime(certainty)))
break;
}
}
else
{
// Note: Modified from Java version for speed
for (;;)
{
q = new BigInteger(qLength, 0, random);
retry:
for (int i = 0; i < primeLists.Length; ++i)
{
int test = q.Remainder(PrimeProducts[i]).IntValue;
if (i == 0)
{
int rem3 = test % 3;
if (rem3 != 2)
{
int diff = 2 * rem3 + 2;
q = q.Add(BigInteger.ValueOf(diff));
test = (test + diff) % primeProducts[i];
}
}
int[] primeList = primeLists[i];
for (int j = 0; j < primeList.Length; ++j)
{
int prime = primeList[j];
int qRem = test % prime;
if (qRem == 0 || qRem == (prime >> 1))
{
q = q.Add(Six);
goto retry;
}
}
}
if (q.BitLength != qLength)
continue;
if (!q.RabinMillerTest(2, random))
continue;
p = q.ShiftLeft(1).Add(BigInteger.One);
if (p.RabinMillerTest(certainty, random)
&& (certainty <= 2 || q.RabinMillerTest(certainty - 2, random)))
break;
}
}
return new BigInteger[] { p, q };
}
// Select a high order element of the multiplicative group Zp*
// p and q must be s.t. p = 2*q + 1, where p and q are prime
internal static BigInteger SelectGenerator(
BigInteger p,
BigInteger q,
SecureRandom random)
{
BigInteger pMinusTwo = p.Subtract(BigInteger.Two);
BigInteger g;
// Handbook of Applied Cryptography 4.86
do
{
g = BigIntegers.CreateRandomInRange(BigInteger.Two, pMinusTwo, random);
}
while (g.ModPow(BigInteger.Two, p).Equals(BigInteger.One)
|| g.ModPow(q, p).Equals(BigInteger.One));
/*
// RFC 2631 2.1.1 (and see Handbook of Applied Cryptography 4.81)
do
{
BigInteger h = CreateInRange(BigInteger.Two, pMinusTwo, random);
g = h.ModPow(BigInteger.Two, p);
}
while (g.Equals(BigInteger.One));
*/
return g;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Logging;
using System.Text;
using Orleans.Configuration;
namespace Orleans.Runtime.MembershipService
{
internal class MembershipOracleData
{
private readonly Dictionary<SiloAddress, MembershipEntry> localTable; // all silos not including current silo
private Dictionary<SiloAddress, SiloStatus> localTableCopy; // a cached copy of a local table, including current silo, for fast access
private Dictionary<SiloAddress, SiloStatus> localTableCopyOnlyActive; // a cached copy of a local table, for fast access, including only active nodes and current silo (if active)
private Dictionary<SiloAddress, string> localNamesTableCopy; // a cached copy of a map from SiloAddress to Silo Name, not including current silo, for fast access
private List<SiloAddress> localMultiClusterGatewaysCopy; // a cached copy of the silos that are designated gateways
private readonly List<ISiloStatusListener> statusListeners;
private readonly ILogger logger;
private IntValueStatistic clusterSizeStatistic;
private StringValueStatistic clusterStatistic;
internal readonly DateTime SiloStartTime;
internal readonly SiloAddress MyAddress;
internal readonly int MyProxyPort;
internal readonly string MyHostname;
internal SiloStatus CurrentStatus { get; private set; } // current status of this silo.
internal string SiloName { get; } // name of this silo.
private readonly bool multiClusterActive; // set by configuration if multicluster is active
private readonly int maxMultiClusterGateways; // set by configuration
private UpdateFaultCombo myFaultAndUpdateZones;
internal MembershipOracleData(ILocalSiloDetails siloDetails, ILogger log, MultiClusterOptions multiClusterOptions)
{
logger = log;
localTable = new Dictionary<SiloAddress, MembershipEntry>();
localTableCopy = new Dictionary<SiloAddress, SiloStatus>();
localTableCopyOnlyActive = new Dictionary<SiloAddress, SiloStatus>();
localNamesTableCopy = new Dictionary<SiloAddress, string>();
localMultiClusterGatewaysCopy = new List<SiloAddress>();
statusListeners = new List<ISiloStatusListener>();
SiloStartTime = DateTime.UtcNow;
MyAddress = siloDetails.SiloAddress;
MyHostname = siloDetails.DnsHostName;
MyProxyPort = siloDetails.GatewayAddress?.Endpoint?.Port ?? 0;
SiloName = siloDetails.Name;
this.multiClusterActive = multiClusterOptions.HasMultiClusterNetwork;
this.maxMultiClusterGateways = multiClusterOptions.MaxMultiClusterGateways;
CurrentStatus = SiloStatus.Created;
clusterSizeStatistic = IntValueStatistic.FindOrCreate(StatisticNames.MEMBERSHIP_ACTIVE_CLUSTER_SIZE, () => localTableCopyOnlyActive.Count);
clusterStatistic = StringValueStatistic.FindOrCreate(StatisticNames.MEMBERSHIP_ACTIVE_CLUSTER,
() =>
{
List<string> list = localTableCopyOnlyActive.Keys.Select(addr => addr.ToLongString()).ToList();
list.Sort();
return Utils.EnumerableToString(list);
});
}
// ONLY access localTableCopy and not the localTable, to prevent races, as this method may be called outside the turn.
internal SiloStatus GetApproximateSiloStatus(SiloAddress siloAddress)
{
var status = SiloStatus.None;
if (siloAddress.Equals(MyAddress))
{
status = CurrentStatus;
}
else
{
if (!localTableCopy.TryGetValue(siloAddress, out status))
{
if (CurrentStatus == SiloStatus.Active)
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Runtime_Error_100209, "-The given siloAddress {0} is not registered in this MembershipOracle.", siloAddress.ToLongString());
status = SiloStatus.None;
}
}
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("-GetApproximateSiloStatus returned {0} for silo: {1}", status, siloAddress.ToLongString());
return status;
}
// ONLY access localTableCopy or localTableCopyOnlyActive and not the localTable, to prevent races, as this method may be called outside the turn.
internal Dictionary<SiloAddress, SiloStatus> GetApproximateSiloStatuses(bool onlyActive = false)
{
Dictionary<SiloAddress, SiloStatus> dict = onlyActive ? localTableCopyOnlyActive : localTableCopy;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("-GetApproximateSiloStatuses returned {0} silos: {1}", dict.Count, Utils.DictionaryToString(dict));
return dict;
}
internal List<SiloAddress> GetApproximateMultiClusterGateways()
{
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("-GetApproximateMultiClusterGateways returned {0} silos: {1}", localMultiClusterGatewaysCopy.Count, string.Join(",", localMultiClusterGatewaysCopy));
return localMultiClusterGatewaysCopy;
}
internal bool TryGetSiloName(SiloAddress siloAddress, out string siloName)
{
if (siloAddress.Equals(MyAddress))
{
siloName = SiloName;
return true;
}
return localNamesTableCopy.TryGetValue(siloAddress, out siloName);
}
internal bool SubscribeToSiloStatusEvents(ISiloStatusListener observer)
{
lock (statusListeners)
{
if (statusListeners.Contains(observer))
return false;
statusListeners.Add(observer);
return true;
}
}
internal bool UnSubscribeFromSiloStatusEvents(ISiloStatusListener observer)
{
lock (statusListeners)
{
return statusListeners.Contains(observer) && statusListeners.Remove(observer);
}
}
internal void UpdateMyStatusLocal(SiloStatus status)
{
if (CurrentStatus == status) return;
// make copies
var tmpLocalTableCopy = GetSiloStatuses(st => true, true); // all the silos including me.
var tmpLocalTableCopyOnlyActive = GetSiloStatuses(st => st == SiloStatus.Active, true); // only active silos including me.
var tmpLocalTableNamesCopy = localTable.ToDictionary(pair => pair.Key, pair => pair.Value.SiloName); // all the silos excluding me.
CurrentStatus = status;
tmpLocalTableCopy[MyAddress] = status;
if (status == SiloStatus.Active)
{
tmpLocalTableCopyOnlyActive[MyAddress] = status;
}
else if (tmpLocalTableCopyOnlyActive.ContainsKey(MyAddress))
{
tmpLocalTableCopyOnlyActive.Remove(MyAddress);
}
localTableCopy = tmpLocalTableCopy;
localTableCopyOnlyActive = tmpLocalTableCopyOnlyActive;
localNamesTableCopy = tmpLocalTableNamesCopy;
if (this.multiClusterActive)
localMultiClusterGatewaysCopy = DetermineMultiClusterGateways();
NotifyLocalSubscribers(MyAddress, CurrentStatus);
}
private SiloStatus GetSiloStatus(SiloAddress siloAddress)
{
if (siloAddress.Equals(MyAddress))
return CurrentStatus;
MembershipEntry data;
return !localTable.TryGetValue(siloAddress, out data) ? SiloStatus.None : data.Status;
}
internal MembershipEntry GetSiloEntry(SiloAddress siloAddress)
{
return localTable[siloAddress];
}
internal Dictionary<SiloAddress, SiloStatus> GetSiloStatuses(Func<SiloStatus, bool> filter, bool includeMyself)
{
Dictionary<SiloAddress, SiloStatus> dict = localTable.Where(
pair => filter(pair.Value.Status)).ToDictionary(pair => pair.Key, pair => pair.Value.Status);
if (includeMyself && filter(CurrentStatus)) // add myself
dict.Add(MyAddress, CurrentStatus);
return dict;
}
internal MembershipEntry CreateNewMembershipEntry(SiloStatus myStatus)
{
return CreateNewMembershipEntry(SiloName, MyAddress, MyProxyPort, MyHostname, myStatus, SiloStartTime);
}
private static MembershipEntry CreateNewMembershipEntry(string siloName, SiloAddress myAddress, int proxyPort, string myHostname, SiloStatus myStatus, DateTime startTime)
{
var assy = Assembly.GetEntryAssembly() ?? typeof(MembershipOracleData).GetTypeInfo().Assembly;
var roleName = assy.GetName().Name;
var entry = new MembershipEntry
{
SiloAddress = myAddress,
HostName = myHostname,
SiloName = siloName,
Status = myStatus,
ProxyPort = proxyPort,
RoleName = roleName,
SuspectTimes = new List<Tuple<SiloAddress, DateTime>>(),
StartTime = startTime,
IAmAliveTime = DateTime.UtcNow
};
return entry;
}
internal void UpdateMyFaultAndUpdateZone(MembershipEntry entry)
{
this.myFaultAndUpdateZones = new UpdateFaultCombo(entry.UpdateZone, entry.FaultZone);
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug($"-Updated my FaultZone={entry.FaultZone} UpdateZone={entry.UpdateZone}");
if (this.multiClusterActive)
localMultiClusterGatewaysCopy = DetermineMultiClusterGateways();
}
internal bool TryUpdateStatusAndNotify(MembershipEntry entry)
{
if (!TryUpdateStatus(entry)) return false;
localTableCopy = GetSiloStatuses(status => true, true); // all the silos including me.
localTableCopyOnlyActive = GetSiloStatuses(status => status == SiloStatus.Active, true); // only active silos including me.
localNamesTableCopy = localTable.ToDictionary(pair => pair.Key, pair => pair.Value.SiloName); // all the silos excluding me.
if (this.multiClusterActive)
localMultiClusterGatewaysCopy = DetermineMultiClusterGateways();
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("-Updated my local view of {0} status. It is now {1}.", entry.SiloAddress.ToLongString(), GetSiloStatus(entry.SiloAddress));
NotifyLocalSubscribers(entry.SiloAddress, entry.Status);
return true;
}
// return true if the status changed
private bool TryUpdateStatus(MembershipEntry updatedSilo)
{
MembershipEntry currSiloData = null;
if (!localTable.TryGetValue(updatedSilo.SiloAddress, out currSiloData))
{
// an optimization - if I learn about dead silo and I never knew about him before, I don't care, can just ignore him.
if (updatedSilo.Status == SiloStatus.Dead) return false;
localTable.Add(updatedSilo.SiloAddress, updatedSilo);
return true;
}
if (currSiloData.Status == updatedSilo.Status) return false;
currSiloData.Update(updatedSilo);
return true;
}
private void NotifyLocalSubscribers(SiloAddress siloAddress, SiloStatus newStatus)
{
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("-NotifyLocalSubscribers about {0} status {1}", siloAddress.ToLongString(), newStatus);
List<ISiloStatusListener> copy;
lock (statusListeners)
{
copy = statusListeners.ToList();
}
foreach (ISiloStatusListener listener in copy)
{
try
{
listener.SiloStatusChangeNotification(siloAddress, newStatus);
}
catch (Exception exc)
{
logger.Error(ErrorCode.MembershipLocalSubscriberException,
String.Format("Local ISiloStatusListener {0} has thrown an exception when was notified about SiloStatusChangeNotification about silo {1} new status {2}",
listener.GetType().FullName, siloAddress.ToLongString(), newStatus), exc);
}
}
}
// deterministic function for designating the silos that should act as multi-cluster gateways
private List<SiloAddress> DetermineMultiClusterGateways()
{
// function should never be called if we are not in a multicluster
if (! this.multiClusterActive)
throw new OrleansException("internal error: should not call this function without multicluster network");
List<SiloAddress> result;
// take all the active silos if their count does not exceed the desired number of gateways
if (localTableCopyOnlyActive.Count <= this.maxMultiClusterGateways)
{
result = localTableCopyOnlyActive.Keys.ToList();
}
else
{
result = DeterministicBalancedChoice<SiloAddress, UpdateFaultCombo>(
localTableCopyOnlyActive.Keys,
this.maxMultiClusterGateways,
(SiloAddress a) => a.Equals(MyAddress) ? this.myFaultAndUpdateZones : new UpdateFaultCombo(localTable[a]),
logger);
}
if (logger.IsEnabled(LogLevel.Debug))
{
var gateways = string.Join(", ", result.Select(silo => silo.ToString()));
logger.Debug($"-DetermineMultiClusterGateways {gateways}");
}
return result;
}
// pick a specified number of elements from a set of candidates
// - in a balanced way (try to pick evenly from groups)
// - in a deterministic way (using sorting order on candidates and keys)
internal static List<T> DeterministicBalancedChoice<T, K>(IEnumerable<T> candidates, int count, Func<T, K> group, ILogger logger = null)
where T:IComparable where K:IComparable
{
// organize candidates by groups
var groups = new Dictionary<K, List<T>>();
var keys = new List<K>();
int numcandidates = 0;
foreach (var c in candidates)
{
var key = group(c);
List<T> list;
if (!groups.TryGetValue(key, out list))
{
groups[key] = list = new List<T>();
keys.Add(key);
}
list.Add(c);
numcandidates++;
}
if (numcandidates < count)
throw new ArgumentException("not enough candidates");
// sort the keys and the groups to guarantee deterministic result
keys.Sort();
foreach(var kvp in groups)
kvp.Value.Sort();
// for debugging, trace all the gateway candidates
if (logger != null && logger.IsEnabled(LogLevel.Trace))
{
var b = new StringBuilder();
foreach (var k in keys)
{
b.Append(k);
b.Append(':');
foreach (var s in groups[k])
{
b.Append(' ');
b.Append(s);
}
}
logger.Trace($"-DeterministicBalancedChoice candidates {b}");
}
// pick round-robin from groups
var result = new List<T>();
for (int i = 0; result.Count < count; i++)
{
var list = groups[keys[i % keys.Count]];
var col = i / keys.Count;
if (col < list.Count)
result.Add(list[col]);
}
return result;
}
internal struct UpdateFaultCombo : IComparable
{
public readonly int UpdateZone;
public readonly int FaultZone;
public UpdateFaultCombo(int updateZone, int faultZone)
{
UpdateZone = updateZone;
FaultZone = faultZone;
}
public UpdateFaultCombo(MembershipEntry e)
{
UpdateZone = e.UpdateZone;
FaultZone = e.FaultZone;
}
public int CompareTo(object x)
{
var other = (UpdateFaultCombo)x;
int comp = UpdateZone.CompareTo(other.UpdateZone);
if (comp != 0) return comp;
return FaultZone.CompareTo(other.FaultZone);
}
public override string ToString()
{
return $"({UpdateZone},{FaultZone})";
}
}
public override string ToString()
{
return string.Format("CurrentSiloStatus = {0}, {1} silos: {2}.",
CurrentStatus,
localTableCopy.Count,
Utils.EnumerableToString(localTableCopy, pair =>
String.Format("SiloAddress={0} Status={1}", pair.Key.ToLongString(), pair.Value)));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using MSAst = System.Linq.Expressions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Utils;
using Microsoft.Scripting.Interpreter;
using Microsoft.Scripting.Runtime;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
namespace IronPython.Compiler.Ast {
public class CallExpression : Expression, IInstructionProvider {
private readonly Expression _target;
private readonly Arg[] _args;
public CallExpression(Expression target, Arg[] args) {
_target = target;
_args = args;
}
public Expression Target {
get { return _target; }
}
public IList<Arg> Args {
get { return _args; }
}
public bool NeedsLocalsDictionary() {
if (!(_target is NameExpression nameExpr)) return false;
if (_args.Length == 0) {
if (nameExpr.Name == "locals") return true;
if (nameExpr.Name == "vars") return true;
if (nameExpr.Name == "dir") return true;
return false;
} else if (_args.Length == 1 && (nameExpr.Name == "dir" || nameExpr.Name == "vars")) {
if (_args[0].Name == "*" || _args[0].Name == "**") {
// could be splatting empty list or dict resulting in 0-param call which needs context
return true;
}
} else if (_args.Length == 2 && (nameExpr.Name == "dir" || nameExpr.Name == "vars")) {
if (_args[0].Name == "*" && _args[1].Name == "**") {
// could be splatting empty list and dict resulting in 0-param call which needs context
return true;
}
} else {
if (nameExpr.Name == "eval") return true;
if (nameExpr.Name == "execfile") return true;
}
return false;
}
public override MSAst.Expression Reduce() {
return UnicodeCall() ?? NormalCall(_target);
}
private MSAst.Expression NormalCall(MSAst.Expression target) {
MSAst.Expression[] values = new MSAst.Expression[_args.Length + 2];
Argument[] kinds = new Argument[_args.Length];
values[0] = Parent.LocalContext;
values[1] = target;
for (int i = 0; i < _args.Length; i++) {
kinds[i] = _args[i].GetArgumentInfo();
values[i + 2] = _args[i].Expression;
}
return Parent.Invoke(
new CallSignature(kinds),
values
);
}
private static MSAst.MethodCallExpression _GetUnicode = Expression.Call(AstMethods.GetUnicodeFunction);
private MSAst.Expression UnicodeCall() {
if (_target is NameExpression && ((NameExpression)_target).Name == "unicode") {
// NameExpressions are always typed to object
Debug.Assert(_target.Type == typeof(object));
var tmpVar = Expression.Variable(typeof(object));
return Expression.Block(
new[] { tmpVar },
Expression.Assign(tmpVar, _target),
Expression.Condition(
Expression.Call(
AstMethods.IsUnicode,
tmpVar
),
NormalCall(_GetUnicode),
NormalCall(tmpVar)
)
);
}
return null;
}
#region IInstructionProvider Members
void IInstructionProvider.AddInstructions(LightCompiler compiler) {
if (_target is NameExpression && ((NameExpression)_target).Name == "unicode") {
compiler.Compile(Reduce());
return;
}
for (int i = 0; i < _args.Length; i++) {
if (!_args[i].GetArgumentInfo().IsSimple) {
compiler.Compile(Reduce());
return;
}
}
switch (_args.Length) {
#region Generated Python Call Expression Instruction Switch
// *** BEGIN GENERATED CODE ***
// generated by function: gen_call_expression_instruction_switch from: generate_calls.py
case 0:
compiler.Compile(Parent.LocalContext);
compiler.Compile(_target);
compiler.Instructions.Emit(new Invoke0Instruction(Parent.PyContext));
return;
case 1:
compiler.Compile(Parent.LocalContext);
compiler.Compile(_target);
compiler.Compile(_args[0].Expression);
compiler.Instructions.Emit(new Invoke1Instruction(Parent.PyContext));
return;
case 2:
compiler.Compile(Parent.LocalContext);
compiler.Compile(_target);
compiler.Compile(_args[0].Expression);
compiler.Compile(_args[1].Expression);
compiler.Instructions.Emit(new Invoke2Instruction(Parent.PyContext));
return;
case 3:
compiler.Compile(Parent.LocalContext);
compiler.Compile(_target);
compiler.Compile(_args[0].Expression);
compiler.Compile(_args[1].Expression);
compiler.Compile(_args[2].Expression);
compiler.Instructions.Emit(new Invoke3Instruction(Parent.PyContext));
return;
case 4:
compiler.Compile(Parent.LocalContext);
compiler.Compile(_target);
compiler.Compile(_args[0].Expression);
compiler.Compile(_args[1].Expression);
compiler.Compile(_args[2].Expression);
compiler.Compile(_args[3].Expression);
compiler.Instructions.Emit(new Invoke4Instruction(Parent.PyContext));
return;
case 5:
compiler.Compile(Parent.LocalContext);
compiler.Compile(_target);
compiler.Compile(_args[0].Expression);
compiler.Compile(_args[1].Expression);
compiler.Compile(_args[2].Expression);
compiler.Compile(_args[3].Expression);
compiler.Compile(_args[4].Expression);
compiler.Instructions.Emit(new Invoke5Instruction(Parent.PyContext));
return;
case 6:
compiler.Compile(Parent.LocalContext);
compiler.Compile(_target);
compiler.Compile(_args[0].Expression);
compiler.Compile(_args[1].Expression);
compiler.Compile(_args[2].Expression);
compiler.Compile(_args[3].Expression);
compiler.Compile(_args[4].Expression);
compiler.Compile(_args[5].Expression);
compiler.Instructions.Emit(new Invoke6Instruction(Parent.PyContext));
return;
// *** END GENERATED CODE ***
#endregion
}
compiler.Compile(Reduce());
}
#endregion
abstract class InvokeInstruction : Instruction {
public override int ProducedStack {
get {
return 1;
}
}
public override string InstructionName {
get {
return "Python Invoke" + (ConsumedStack - 1);
}
}
}
#region Generated Python Call Expression Instructions
// *** BEGIN GENERATED CODE ***
// generated by function: gen_call_expression_instructions from: generate_calls.py
class Invoke0Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object>> _site;
public Invoke0Instruction(PythonContext context) {
_site = context.CallSite0;
}
public override int ConsumedStack {
get {
return 2;
}
}
public override int Run(InterpretedFrame frame) {
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target));
return +1;
}
}
class Invoke1Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object, object>> _site;
public Invoke1Instruction(PythonContext context) {
_site = context.CallSite1;
}
public override int ConsumedStack {
get {
return 3;
}
}
public override int Run(InterpretedFrame frame) {
var arg0 = frame.Pop();
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0));
return +1;
}
}
class Invoke2Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object>> _site;
public Invoke2Instruction(PythonContext context) {
_site = context.CallSite2;
}
public override int ConsumedStack {
get {
return 4;
}
}
public override int Run(InterpretedFrame frame) {
var arg1 = frame.Pop();
var arg0 = frame.Pop();
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1));
return +1;
}
}
class Invoke3Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object, object>> _site;
public Invoke3Instruction(PythonContext context) {
_site = context.CallSite3;
}
public override int ConsumedStack {
get {
return 5;
}
}
public override int Run(InterpretedFrame frame) {
var arg2 = frame.Pop();
var arg1 = frame.Pop();
var arg0 = frame.Pop();
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1, arg2));
return +1;
}
}
class Invoke4Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object, object, object>> _site;
public Invoke4Instruction(PythonContext context) {
_site = context.CallSite4;
}
public override int ConsumedStack {
get {
return 6;
}
}
public override int Run(InterpretedFrame frame) {
var arg3 = frame.Pop();
var arg2 = frame.Pop();
var arg1 = frame.Pop();
var arg0 = frame.Pop();
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1, arg2, arg3));
return +1;
}
}
class Invoke5Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object, object, object, object>> _site;
public Invoke5Instruction(PythonContext context) {
_site = context.CallSite5;
}
public override int ConsumedStack {
get {
return 7;
}
}
public override int Run(InterpretedFrame frame) {
var arg4 = frame.Pop();
var arg3 = frame.Pop();
var arg2 = frame.Pop();
var arg1 = frame.Pop();
var arg0 = frame.Pop();
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1, arg2, arg3, arg4));
return +1;
}
}
class Invoke6Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object, object, object, object, object>> _site;
public Invoke6Instruction(PythonContext context) {
_site = context.CallSite6;
}
public override int ConsumedStack {
get {
return 8;
}
}
public override int Run(InterpretedFrame frame) {
var arg5 = frame.Pop();
var arg4 = frame.Pop();
var arg3 = frame.Pop();
var arg2 = frame.Pop();
var arg1 = frame.Pop();
var arg0 = frame.Pop();
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1, arg2, arg3, arg4, arg5));
return +1;
}
}
// *** END GENERATED CODE ***
#endregion
public override string NodeName => "function call";
public override void Walk(PythonWalker walker) {
if (walker.Walk(this)) {
if (_target != null) {
_target.Walk(walker);
}
if (_args != null) {
foreach (Arg arg in _args) {
arg.Walk(walker);
}
}
}
walker.PostWalk(this);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RestSharp;
using RestSharp.Extensions;
using RestSharp.Validation;
namespace Twilio
{
public partial class TwilioRestClient
{
/// <summary>
/// Retrieve the details for a specific Message instance.
/// Makes a GET request to an Message Instance resource.
/// </summary>
/// <param name="messageSid">The Sid of the message to retrieve</param>
public virtual Message GetMessage(string messageSid)
{
var request = new RestRequest();
request.Resource = "Accounts/{AccountSid}/Messages/{MessageSid}.json";
request.AddUrlSegment("MessageSid", messageSid);
return Execute<Message>(request);
}
/// <summary>
/// Deletes the single Message resource specified by messageSid.
/// </summary>
/// <param name="messageSid">The Sid of the message to delete</param>
public virtual DeleteStatus DeleteMessage(string messageSid)
{
var request = new RestRequest(Method.DELETE);
request.Resource = "Accounts/{AccountSid}/Messages/{MessageSid}.json";
request.AddUrlSegment("MessageSid", messageSid);
var response = Execute(request);
return response.StatusCode == System.Net.HttpStatusCode.NoContent ? DeleteStatus.Success : DeleteStatus.Failed;
}
public virtual Message RedactMessage(string messageSid)
{
var request = new RestRequest(Method.POST);
request.Resource = "Accounts/{AccountSid}/Messages/{MessageSid}.json";
request.AddUrlSegment("MessageSid", messageSid);
request.AddParameter("Body", "");
return Execute<Message>(request);
}
/// <summary>
/// Returns a list of Messages.
/// The list includes paging information.
/// Makes a GET request to the Message List resource.
/// </summary>
public virtual MessageResult ListMessages()
{
return ListMessages(new MessageListRequest());
}
/// <summary>
/// Returns a list of Messages.
/// The list includes paging information.
/// Makes a GET request to the Message List resource.
/// </summary>
/// <param name="To"></param>
public virtual MessageResult ListMessages(string To)
{
return ListMessages(new MessageListRequest() { To = To } );
}
/// <summary>
/// Returns a filtered list of Messages. The list includes paging information.
/// Makes a GET request to the Messages List resource.
/// </summary>
/// <param name="options">The list filters for the request</param>
public virtual MessageResult ListMessages(MessageListRequest options)
{
var request = new RestRequest();
request.Resource = "Accounts/{AccountSid}/Messages.json";
AddMessageListOptions(options, request);
return Execute<MessageResult>(request);
}
/// <summary>
/// Send a new Message to the specified recipients.
/// Makes a POST request to the Messages List resource.
/// </summary>
/// <param name="from">The phone number to send the message from. Must be a Twilio-provided or ported local (not toll-free) number. Validated outgoing caller IDs cannot be used.</param>
/// <param name="to">The phone number to send the message to.</param>
/// <param name="body">The message to send. Must be 160 characters or less.</param>
public virtual Message SendMessage(string from, string to, string body)
{
return SendMessage(from, to, body, new string[0], string.Empty);
}
/// <summary>
/// Send a new Message to the specified recipients.
/// Makes a POST request to the Messages List resource.
/// </summary>
/// <param name="from">The phone number to send the message from. Must be a Twilio-provided or ported local (not toll-free) number. Validated outgoing caller IDs cannot be used.</param>
/// <param name="to">The phone number to send the message to.</param>
/// <param name="body">The message to send. Must be 160 characters or less.</param>
/// <param name="statusCallback">A URL that Twilio will POST to when your message is processed. Twilio will POST the MessageSid as well as MessageStatus=sent or MessageStatus=failed</param>
public virtual Message SendMessage(string from, string to, string body, string statusCallback)
{
return SendMessage(from, to, body, new string[0], statusCallback);
}
/// <summary>
/// Send a new Message to the specified recipients.
/// Makes a POST request to the Messages List resource.
/// </summary>
/// <param name="from">The phone number to send the message from. Must be a Twilio-provided or ported local (not toll-free) number. Validated outgoing caller IDs cannot be used.</param>
/// <param name="to">The phone number to send the message to.</param>
/// <param name="mediaUrls">An array of URLs where each member of the array points to a media file to be sent with the message. You can include a maximum of 10 media URLs</param>
public virtual Message SendMessage(string from, string to, string[] mediaUrls)
{
return SendMessage(from, to, String.Empty, mediaUrls, string.Empty);
}
/// <summary>
/// Send a new Message to the specified recipients.
/// Makes a POST request to the Messages List resource.
/// </summary>
/// <param name="from">The phone number to send the message from. Must be a Twilio-provided or ported local (not toll-free) number. Validated outgoing caller IDs cannot be used.</param>
/// <param name="to">The phone number to send the message to.</param>
/// <param name="body">The message to send. Must be 160 characters or less.</param>
/// <param name="mediaUrls">An array of URLs where each member of the array points to a media file to be sent with the message. You can include a maximum of 10 media URLs</param>
public virtual Message SendMessage(string from, string to, string body, string[] mediaUrls)
{
return SendMessage(from, to, body, mediaUrls, string.Empty);
}
/// <summary>
/// Send a new Message to the specified recipients
/// Makes a POST request to the Messages List resource.
/// </summary>
/// <param name="from">The phone number to send the message from. Must be a Twilio-provided or ported local (not toll-free) number. Validated outgoing caller IDs cannot be used.</param>
/// <param name="to">The phone number to send the message to. If using the Sandbox, this number must be a validated outgoing caller ID</param>
/// <param name="body">The message to send. Must be 160 characters or less.</param>
/// <param name="mediaUrls">An array of URLs where each member of the array points to a media file to be sent with the message. You can include a maximum of 10 media URLs</param>
/// <param name="statusCallback">A URL that Twilio will POST to when your message is processed. Twilio will POST the MessageSid as well as MessageStatus=sent or MessageStatus=failed</param>
public virtual Message SendMessage(string from, string to, string body, string[] mediaUrls, string statusCallback)
{
return SendMessage(from, to, body, mediaUrls, statusCallback, string.Empty);
}
/// <summary>
/// Send a new Message to the specified recipients
/// Makes a POST request to the Messages List resource.
/// </summary>
/// <param name="from">The phone number to send the message from. Must be a Twilio-provided or ported local (not toll-free) number. Validated outgoing caller IDs cannot be used.</param>
/// <param name="to">The phone number to send the message to. If using the Sandbox, this number must be a validated outgoing caller ID</param>
/// <param name="body">The message to send. Must be 160 characters or less.</param>
/// <param name="mediaUrls">An array of URLs where each member of the array points to a media file to be sent with the message. You can include a maximum of 10 media URLs</param>
/// <param name="statusCallback">A URL that Twilio will POST to when your message is processed. Twilio will POST the MessageSid as well as MessageStatus=sent or MessageStatus=failed</param>
/// <param name="applicationSid"></param>
public virtual Message SendMessage(string from, string to, string body, string[] mediaUrls, string statusCallback, string applicationSid)
{
return SendMessage(from, to, body, mediaUrls, statusCallback, applicationSid, false);
}
/// <summary>
/// Send a new Message to the specified recipients
/// Makes a POST request to the Messages List resource.
/// </summary>
/// <param name="from">The phone number to send the message from. Must be a Twilio-provided or ported local (not toll-free) number. Validated outgoing caller IDs cannot be used.</param>
/// <param name="to">The phone number to send the message to. If using the Sandbox, this number must be a validated outgoing caller ID</param>
/// <param name="body">The message to send. Must be 160 characters or less.</param>
/// <param name="mediaUrls">An array of URLs where each member of the array points to a media file to be sent with the message. You can include a maximum of 10 media URLs</param>
/// <param name="statusCallback">A URL that Twilio will POST to when your message is processed. Twilio will POST the MessageSid as well as MessageStatus=sent or MessageStatus=failed</param>
/// <param name="applicationSid"></param>
/// <param name="mmsOnly">Doesn't fallback to SMS if set to true</param>
public virtual Message SendMessage(string from, string to, string body, string[] mediaUrls, string statusCallback, string applicationSid, bool? mmsOnly)
{
Require.Argument("from", from);
Require.Argument("to", to);
var request = new RestRequest(Method.POST);
request.Resource = "Accounts/{AccountSid}/Messages.json";
request.AddParameter("From", from);
request.AddParameter("To", to);
if (body.HasValue()) request.AddParameter("Body", body);
for (int i = 0; i < mediaUrls.Length; i++)
{
request.AddParameter("MediaUrl", mediaUrls[i]);
}
if (statusCallback.HasValue()) request.AddParameter("StatusCallback", statusCallback);
if (applicationSid.HasValue()) request.AddParameter("ApplicationSid", applicationSid);
if (mmsOnly.HasValue) request.AddParameter("MmsOnly", mmsOnly.Value);
return Execute<Message>(request);
}
/// <summary>
/// Send a new Message to the specified recipients.
/// Makes a POST request to the Messages List resource.
/// </summary>
/// <param name="messagingServiceSid">The MessagingServiceSid to send the message from.</param>
/// <param name="to">The phone number to send the message to.</param>
/// <param name="body">The message to send. Must be 160 characters or less.</param>
/// <param name="statusCallback">A URL that Twilio will POST to when your message is processed. Twilio will POST the MessageSid as well as MessageStatus=sent or MessageStatus=failed</param>
public virtual Message SendMessageWithService(string messagingServiceSid, string to, string body)
{
return SendMessageWithService(messagingServiceSid, to, body, new string[0], string.Empty);
}
/// <summary>
/// Send a new Message to the specified recipients.
/// Makes a POST request to the Messages List resource.
/// </summary>
/// <param name="messagingServiceSid">The MessagingServiceSid to send the message from.</param>
/// <param name="to">The phone number to send the message to.</param>
/// <param name="body">The message to send. Must be 160 characters or less.</param>
/// <param name="statusCallback">A URL that Twilio will POST to when your message is processed. Twilio will POST the MessageSid as well as MessageStatus=sent or MessageStatus=failed</param>
public virtual Message SendMessageWithService(string messagingServiceSid, string to, string body, string statusCallback)
{
return SendMessageWithService(messagingServiceSid, to, body, new string[0], statusCallback);
}
/// <summary>
/// Send a new Message to the specified recipients.
/// Makes a POST request to the Messages List resource.
/// </summary>
/// <param name="messagingServiceSid">The MessagingServiceSid to send the message from.</param>
/// <param name="to">The phone number to send the message to.</param>
/// <param name="mediaUrls">An array of URLs where each member of the array points to a media file to be sent with the message. You can include a maximum of 10 media URLs</param>
public virtual Message SendMessageWithService(string messagingServiceSid, string to, string[] mediaUrls)
{
return SendMessageWithService(messagingServiceSid, to, String.Empty, mediaUrls, string.Empty);
}
/// <summary>
/// Send a new Message to the specified recipients.
/// Makes a POST request to the Messages List resource.
/// </summary>
/// <param name="messagingServiceSid">The MessagingServiceSid to send the message from.</param>
/// <param name="to">The phone number to send the message to.</param>
/// <param name="body">The message to send. Must be 160 characters or less.</param>
/// <param name="mediaUrls">An array of URLs where each member of the array points to a media file to be sent with the message. You can include a maximum of 10 media URLs</param>
public virtual Message SendMessageWithService(string messagingServiceSid, string to, string body, string[] mediaUrls)
{
return SendMessageWithService(messagingServiceSid, to, body, mediaUrls, string.Empty);
}
/// <summary>
/// Send a new Message to the specified recipients
/// Makes a POST request to the Messages List resource.
/// </summary>
/// <param name="messagingServiceSid">The MessagingServiceSid to send the message from.</param>
/// <param name="to">The phone number to send the message to. If using the Sandbox, this number must be a validated outgoing caller ID</param>
/// <param name="body">The message to send. Must be 160 characters or less.</param>
/// <param name="mediaUrls">An array of URLs where each member of the array points to a media file to be sent with the message. You can include a maximum of 10 media URLs</param>
/// <param name="statusCallback">A URL that Twilio will POST to when your message is processed. Twilio will POST the MessageSid as well as MessageStatus=sent or MessageStatus=failed</param>
public virtual Message SendMessageWithService(string messagingServiceSid, string to, string body, string[] mediaUrls, string statusCallback)
{
return SendMessageWithService(messagingServiceSid, to, body, mediaUrls, statusCallback, string.Empty);
}
/// <summary>
/// Send a new Message to the specified recipients
/// Makes a POST request to the Messages List resource.
/// </summary>
/// <param name="messagingServiceSid">The MessagingServiceSid to send the message from.</param>
/// <param name="to">The phone number to send the message to. If using the Sandbox, this number must be a validated outgoing caller ID</param>
/// <param name="body">The message to send. Must be 160 characters or less.</param>
/// <param name="mediaUrls">An array of URLs where each member of the array points to a media file to be sent with the message. You can include a maximum of 10 media URLs</param>
/// <param name="statusCallback">A URL that Twilio will POST to when your message is processed. Twilio will POST the MessageSid as well as MessageStatus=sent or MessageStatus=failed</param>
/// <param name="applicationSid"></param>
public virtual Message SendMessageWithService(string messagingServiceSid, string to, string body, string[] mediaUrls, string statusCallback, string applicationSid)
{
return SendMessageWithService(messagingServiceSid, to, body, mediaUrls, statusCallback, applicationSid, false);
}
/// <summary>
/// Send a new Message to the specified recipients
/// Makes a POST request to the Messages List resource.
/// </summary>
/// <param name="messagingServiceSid">The MessagingServiceSid to send the message from.</param>
/// <param name="to">The phone number to send the message to. If using the Sandbox, this number must be a validated outgoing caller ID</param>
/// <param name="body">The message to send. Must be 160 characters or less.</param>
/// <param name="mediaUrls">An array of URLs where each member of the array points to a media file to be sent with the message. You can include a maximum of 10 media URLs</param>
/// <param name="statusCallback">A URL that Twilio will POST to when your message is processed. Twilio will POST the MessageSid as well as MessageStatus=sent or MessageStatus=failed</param>
/// <param name="applicationSid"></param>
/// <param name="mmsOnly">Doesn't fallback to SMS if set to true</param>
public virtual Message SendMessageWithService(string messagingServiceSid, string to, string body, string[] mediaUrls, string statusCallback, string applicationSid, bool? mmsOnly)
{
Require.Argument("messagingServiceSid", messagingServiceSid);
Require.Argument("to", to);
var request = new RestRequest(Method.POST);
request.Resource = "Accounts/{AccountSid}/Messages.json";
request.AddParameter("MessagingServiceSid", messagingServiceSid);
request.AddParameter("To", to);
if (body.HasValue()) request.AddParameter("Body", body);
for (int i = 0; i < mediaUrls.Length; i++)
{
request.AddParameter("MediaUrl", mediaUrls[i]);
}
if (statusCallback.HasValue()) request.AddParameter("StatusCallback", statusCallback);
if (applicationSid.HasValue()) request.AddParameter("ApplicationSid", applicationSid);
if (mmsOnly.HasValue) request.AddParameter("MmsOnly", mmsOnly.Value);
return Execute<Message>(request);
}
}
}
| |
// The MIT License (MIT)
//
// CoreTweet - A .NET Twitter Library supporting Twitter API 1.1
// Copyright (c) 2013-2015 CoreTweet Development Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using CoreTweet.Core;
using Newtonsoft.Json;
namespace CoreTweet
{
/// <summary>
/// <para>Represents a place, which are specific, named locations with corresponding geo coordinates.</para>
/// <para>They can be attached to Tweets by specifying a place_id when tweeting.</para>
/// <para>Tweets associated with places are not necessarily issued from that location but could also potentially be about that location.</para>
/// <para>Places can be searched for.</para>
/// <para>Tweets can also be found by place_id.</para>
/// </summary>
public class Place : CoreBase
{
/// <summary>
/// <para>Gets or sets a hash of variant information about the place.</para>
/// <para>See also: https://dev.twitter.com/docs/about-geo-place-attributes</para>
/// </summary>
[JsonProperty("attributes")]
public GeoAttributes Attributes { get; set; }
/// <summary>
/// Gets or sets a bounding box of coordinates which encloses this place.
/// </summary>
[JsonProperty("bounding_box")]
public BoundingBox BoundingBox { get; set; }
/// <summary>
/// Gets or sets the name of the country containing this place.
/// </summary>
[JsonProperty("country")]
public string Country { get; set; }
/// <summary>
/// Gets or sets the shortened country code representing the country containing this place.
/// </summary>
[JsonProperty("country_code")]
public string CountryCode { get; set; }
/// <summary>
/// Gets or sets the full human-readable representation of the name of the place.
/// </summary>
[JsonProperty("full_name")]
public string FullName { get; set; }
/// <summary>
/// <para>Gets or sets the ID representing this place.</para>
/// <para>Note that this is represented as a string, not an integer.</para>
/// <para>In trends/available or trends/closest, ID is a Yahoo! Where On Earth ID.</para>
/// </summary>
[JsonProperty("id")]
public string Id { get; set; }
/// <summary>
/// Gets or sets the short human-readable representation of the name of the place.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the type of location represented by this place.
/// </summary>
[JsonProperty("place_type")]
public string PlaceType { get; set; }
/// <summary>
/// Gets or sets the URL representing the location of additional place metadata for this place.
/// </summary>
[JsonProperty("url")]
[JsonConverter(typeof(UriConverter))]
public Uri Url { get; set; }
/// <summary>
/// Gets or sets the array of Places contained within this Place.
/// </summary>
[JsonProperty("contained_within")]
public Place[] ContainedWithin { get; set; }
/// <summary>
/// Returns the ID of this instance.
/// </summary>
/// <returns>The ID of this instance.</returns>
public override string ToString()
{
return this.Id;
}
}
/// <summary>
/// <para>Represents a place with rate limit.</para>
/// <para>Places are specific, named locations with corresponding geo coordinates.</para>
/// <para>They can be attached to Tweets by specifying a place_id when tweeting.</para>
/// <para>Tweets associated with places are not necessarily issued from that location but could also potentially be about that location.</para>
/// <para>Places can be searched for.</para>
/// <para>Tweets can also be found by place_id.</para>
/// </summary>
public class PlaceResponse : Place, ITwitterResponse
{
/// <summary>
/// Gets or sets the rate limit of the response.
/// </summary>
public RateLimit RateLimit { get; set; }
/// <summary>
/// Gets or sets the JSON of the response.
/// </summary>
public string Json { get; set; }
}
/// <summary>
/// <para>Represents a bounding box.</para>
/// <para>This class can be converted to a JSON with <see cref="Newtonsoft.Json.JsonConvert.SerializeObject(object)"/>.</para>
/// </summary>
[JsonObject]
public class BoundingBox : CoreBase, IEnumerable<Coordinates>
{
/// <summary>
/// <para>Gets or sets a series of longitude and latitude points, defining a box which will contain the Place entity this bounding box is related to.</para>
/// <para>Each point is an array in the form of [longitude, latitude].</para>
/// <para>Points are grouped into an array per bounding box.</para>
/// <para>Bounding box arrays are wrapped in one additional array to be compatible with the polygon notation.</para>
/// </summary>
[JsonProperty("coordinates")]
public double[][][] Coordinates { get; set; }
IEnumerable<Coordinates> GetCoordinates()
{
return Coordinates[0].Select(x => new Coordinates(x[0], x[1]));
}
/// <summary>
/// <para>Gets or sets the type of data encoded in the coordinates property.</para>
/// <para>This will be "Polygon" for bounding boxes.</para>
/// </summary>
[JsonProperty("type")]
public string Type { get; set; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetCoordinates().ToArray().GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An IEnumerator object that can be used to iterate through the collection.</returns>
public IEnumerator<Coordinates> GetEnumerator()
{
return GetCoordinates().GetEnumerator();
}
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <returns>The element at the specified index.</returns>
public Coordinates this[int index]
{
get
{
return GetCoordinates().ToArray()[index];
}
set
{
Coordinates[0][index][0] = value.Longtitude;
Coordinates[0][index][1] = value.Latitude;
}
}
}
/// <summary>
/// Represents the places near the given coordinates which are similar in name.
/// </summary>
[JsonObject]
public class GeoResult : CoreBase, IEnumerable<Place>, ITwitterResponse
{
/// <summary>
/// Gets or set the names of the places.
/// </summary>
[JsonProperty("places")]
public Place[] Places { get; set; }
/// <summary>
/// Gets or sets the token needed to be able to create a new place.
/// </summary>
[JsonProperty("token")]
public string Token { get; set; }
/// <summary>
/// Gets or sets the rate limit of the response.
/// </summary>
public RateLimit RateLimit { get; set; }
/// <summary>
/// Gets or sets the JSON of the response.
/// </summary>
public string Json { get; set; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return Places.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An IEnumerator object that can be used to iterate through the collection.</returns>
public IEnumerator<Place> GetEnumerator()
{
return (Places as IEnumerable<Place>).GetEnumerator();
}
}
/// <summary>
/// Represents a trending topics for a specific WOEID.
/// </summary>
[JsonObject]
public class TrendsResult : CoreBase, IEnumerable<Trend>
{
/// <summary>
/// Gets or sets the UTC datetime that the trends are valid as of.
/// </summary>
[JsonProperty("as_of")]
[JsonConverter(typeof(DateTimeOffsetConverter))]
public DateTimeOffset AsOf { get; set; }
/// <summary>
/// Gets or sets the UTC datetime that this result was created at.
/// </summary>
[JsonProperty("created_at")]
[JsonConverter(typeof(DateTimeOffsetConverter))]
public DateTimeOffset CreatedAt { get; set; }
/// <summary>
/// Gets or sets the Locations of trending topics.
/// </summary>
[JsonProperty("locations")]
public Location[] Locations { get; set; }
/// <summary>
/// Gets or sets the queried trends.
/// </summary>
[JsonProperty("trends")]
public Trend[] Trends { get; set; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return Trends.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An IEnumerator object that can be used to iterate through the collection.</returns>
public IEnumerator<Trend> GetEnumerator()
{
return (Trends as IEnumerable<Trend>).GetEnumerator();
}
}
/// <summary>
/// Represents the metadata about places.
/// </summary>
public class GeoAttributes : CoreBase
{
/// <summary>
/// Gets or sets the address of street.
/// </summary>
[JsonProperty("street_address")]
public string StreetAddress { get; set; }
/// <summary>
/// Gets or sets the city the place is in.
/// </summary>
[JsonProperty("locality")]
public string Locality { get; set; }
/// <summary>
/// Gets or sets the administrative region the place is in.
/// </summary>
[JsonProperty("region")]
public string Region { get; set; }
/// <summary>
/// Gets or sets the country code.
/// </summary>
[JsonProperty("iso3")]
public string Iso3CountryCode { get; set; }
/// <summary>
/// Gets or sets the preferred local format for the place.
/// </summary>
[JsonProperty("postal_code")]
public string PostalCode { get; set; }
/// <summary>
/// Gets or sets the preferred local format for the place, include long distance code.
/// </summary>
[JsonProperty("phone")]
public string Phone { get; set; }
}
/// <summary>
/// Represents a location.
/// </summary>
public class Location : CoreBase
{
/// <summary>
/// Gets or sets the name of the location.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the WOEID of the location.
/// </summary>
[JsonProperty("woeid")]
public string WoeId { get; set; }
/// <summary>
/// Returns the ID of this instance.
/// </summary>
/// <returns>The ID of this instance.</returns>
public override string ToString()
{
return this.WoeId;
}
}
/// <summary>
/// Represents the trend.
/// </summary>
public class Trend : CoreBase
{
/// <summary>
/// Gets or sets the name of this trend.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the URL to search this trend.
/// </summary>
[JsonProperty("url")]
[JsonConverter(typeof(UriConverter))]
public Uri Url { get; set; }
/// <summary>
/// Gets or sets the query string for search.
/// </summary>
[JsonProperty("query")]
public string Query { get; set; }
}
/// <summary>
/// Represents a location.
/// </summary>
public class TrendLocation : Location
{
/// <summary>
/// Gets or sets the country name of the location.
/// </summary>
[JsonProperty("country")]
public string Country { get; set; }
/// <summary>
/// Gets or sets the country code of the location.
/// </summary>
[JsonProperty("countryCode")]
public string CountryCode { get; set; }
/// <summary>
/// Gets or sets the WOEID of the parent location.
/// </summary>
[JsonProperty("parentid")]
public long ParentId { get; set; }
/// <summary>
/// Gets or sets the WOEID type of the location.
/// </summary>
[JsonProperty("placeType")]
public PlaceType PlaceType { get; set; }
/// <summary>
/// Gets or sets the URL of Yahoo! GeoPlanet API.
/// </summary>
[JsonProperty("url")]
[JsonConverter(typeof(UriConverter))]
public Uri Url { get; set; }
}
/// <summary>
/// Represents a WOEID type of a location.
/// </summary>
public class PlaceType : CoreBase
{
/// <summary>
/// Gets or sets the WOEID of the location.
/// </summary>
[JsonProperty("code")]
public int Code { get; set; }
/// <summary>
/// Gets or sets the WOEID name of the location.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
}
}
| |
namespace Nancy
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using Nancy.Configuration;
using Nancy.ModelBinding;
using Nancy.Responses.Negotiation;
using Nancy.Routing;
using Nancy.Session;
using Nancy.Validation;
using Nancy.ViewEngines;
/// <summary>
/// Basic class containing the functionality for defining routes and actions in Nancy.
/// </summary>
public abstract class NancyModule : INancyModule, IHideObjectMembers
{
private readonly List<Route> routes;
/// <summary>
/// Initializes a new instance of the <see cref="NancyModule"/> class.
/// </summary>
protected NancyModule()
: this(String.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="NancyModule"/> class.
/// </summary>
/// <param name="modulePath">A <see cref="string"/> containing the root relative path that all paths in the module will be a subset of.</param>
protected NancyModule(string modulePath)
{
this.After = new AfterPipeline();
this.Before = new BeforePipeline();
this.OnError = new ErrorPipeline();
this.ModulePath = modulePath;
this.routes = new List<Route>();
}
/// <summary>
/// Non-model specific data for rendering in the response
/// </summary>
public dynamic ViewBag
{
get
{
return this.Context == null ? null : this.Context.ViewBag;
}
}
public dynamic Text
{
get { return this.Context.Text; }
}
/// <summary>
/// Gets <see cref="RouteBuilder"/> for declaring actions for DELETE requests.
/// </summary>
/// <value>A <see cref="RouteBuilder"/> instance.</value>
public RouteBuilder Delete
{
get { return new RouteBuilder("DELETE", this); }
}
/// <summary>
/// Gets <see cref="RouteBuilder"/> for declaring actions for GET requests.
/// </summary>
/// <value>A <see cref="RouteBuilder"/> instance.</value>
public RouteBuilder Get
{
get { return new RouteBuilder("GET", this); }
}
/// <summary>
/// Gets <see cref="RouteBuilder"/> for declaring actions for HEAD requests.
/// </summary>
/// <value>A <see cref="RouteBuilder"/> instance.</value>
public RouteBuilder Head
{
get { return new RouteBuilder("HEAD", this); }
}
/// <summary>
/// Gets <see cref="RouteBuilder"/> for declaring actions for OPTIONS requests.
/// </summary>
/// <value>A <see cref="RouteBuilder"/> instance.</value>
public RouteBuilder Options
{
get { return new RouteBuilder("OPTIONS", this); }
}
/// <summary>
/// Gets <see cref="RouteBuilder"/> for declaring actions for PATCH requests.
/// </summary>
/// <value>A <see cref="RouteBuilder"/> instance.</value>
public RouteBuilder Patch
{
get { return new RouteBuilder("PATCH", this); }
}
/// <summary>
/// Gets <see cref="RouteBuilder"/> for declaring actions for POST requests.
/// </summary>
/// <value>A <see cref="RouteBuilder"/> instance.</value>
public RouteBuilder Post
{
get { return new RouteBuilder("POST", this); }
}
/// <summary>
/// Gets <see cref="RouteBuilder"/> for declaring actions for PUT requests.
/// </summary>
/// <value>A <see cref="RouteBuilder"/> instance.</value>
public RouteBuilder Put
{
get { return new RouteBuilder("PUT", this); }
}
/// <summary>
/// Get the root path of the routes in the current module.
/// </summary>
/// <value>
/// A <see cref="T:System.String" /> containing the root path of the module or <see langword="null" />
/// if no root path should be used.</value><remarks>All routes will be relative to this root path.
/// </remarks>
public string ModulePath { get; protected set; }
/// <summary>
/// Gets all declared routes by the module.
/// </summary>
/// <value>A <see cref="IEnumerable{T}"/> instance, containing all <see cref="Route"/> instances declared by the module.</value>
/// <remarks>This is automatically set by Nancy at runtime.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual IEnumerable<Route> Routes
{
get { return this.routes.AsReadOnly(); }
}
/// <summary>
/// Gets the current session.
/// </summary>
public ISession Session
{
get { return this.Request.Session; }
}
/// <summary>
/// Renders a view from inside a route handler.
/// </summary>
/// <value>A <see cref="ViewRenderer"/> instance that is used to determine which view that should be rendered.</value>
public ViewRenderer View
{
get { return new ViewRenderer(this); }
}
/// <summary>
/// Used to negotiate the content returned based on Accepts header.
/// </summary>
/// <value>A <see cref="Negotiator"/> instance that is used to negotiate the content returned.</value>
public Negotiator Negotiate
{
get { return new Negotiator(this.Context); }
}
/// <summary>
/// Gets or sets the validator locator.
/// </summary>
/// <remarks>This is automatically set by Nancy at runtime.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public IModelValidatorLocator ValidatorLocator { get; set; }
/// <summary>
/// Gets or sets an <see cref="Request"/> instance that represents the current request.
/// </summary>
/// <value>An <see cref="Request"/> instance.</value>
public virtual Request Request
{
get { return this.Context.Request; }
set { this.Context.Request = value; }
}
/// <summary>
/// The extension point for accessing the view engines in Nancy.
/// </summary><value>An <see cref="IViewFactory" /> instance.</value>
/// <remarks>This is automatically set by Nancy at runtime.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public IViewFactory ViewFactory { get; set; }
/// <summary><para>
/// The post-request hook
/// </para><para>
/// The post-request hook is called after the response is created by the route execution.
/// It can be used to rewrite the response or add/remove items from the context.
/// </para>
/// <remarks>This is automatically set by Nancy at runtime.</remarks>
/// </summary>
public AfterPipeline After { get; set; }
/// <summary>
/// <para>
/// The pre-request hook
/// </para>
/// <para>
/// The PreRequest hook is called prior to executing a route. If any item in the
/// pre-request pipeline returns a response then the route is not executed and the
/// response is returned.
/// </para>
/// <remarks>This is automatically set by Nancy at runtime.</remarks>
/// </summary>
public BeforePipeline Before { get; set; }
/// <summary>
/// <para>
/// The error hook
/// </para>
/// <para>
/// The error hook is called if an exception is thrown at any time during executing
/// the PreRequest hook, a route and the PostRequest hook. It can be used to set
/// the response and/or finish any ongoing tasks (close database session, etc).
/// </para>
/// <remarks>This is automatically set by Nancy at runtime.</remarks>
/// </summary>
public ErrorPipeline OnError { get; set; }
/// <summary>
/// Gets or sets the current Nancy context
/// </summary>
/// <value>A <see cref="NancyContext" /> instance.</value>
/// <remarks>This is automatically set by Nancy at runtime.</remarks>
public NancyContext Context { get; set; }
/// <summary>
/// An extension point for adding support for formatting response contents.
/// </summary><value>This property will always return <see langword="null" /> because it acts as an extension point.</value><remarks>Extension methods to this property should always return <see cref="P:Nancy.NancyModuleBase.Response" /> or one of the types that can implicitly be types into a <see cref="P:Nancy.NancyModuleBase.Response" />.</remarks>
public IResponseFormatter Response { get; set; }
/// <summary>
/// Gets or sets the model binder locator
/// </summary>
/// <remarks>This is automatically set by Nancy at runtime.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public IModelBinderLocator ModelBinderLocator { get; set; }
/// <summary>
/// Gets or sets the model validation result
/// </summary>
/// <remarks>This is automatically set by Nancy at runtime when you run validation.</remarks>
public virtual ModelValidationResult ModelValidationResult
{
get { return this.Context == null ? null : this.Context.ModelValidationResult; }
set
{
if (this.Context != null)
{
this.Context.ModelValidationResult = value;
}
}
}
/// <summary>
/// Helper class for configuring a route handler in a module.
/// </summary>
public class RouteBuilder : IHideObjectMembers
{
private readonly string method;
private readonly NancyModule parentModule;
/// <summary>
/// Initializes a new instance of the <see cref="RouteBuilder"/> class.
/// </summary>
/// <param name="method">The HTTP request method that the route should be available for.</param>
/// <param name="parentModule">The <see cref="INancyModule"/> that the route is being configured for.</param>
public RouteBuilder(string method, NancyModule parentModule)
{
this.method = method;
this.parentModule = parentModule;
}
/// <summary>
/// Defines a Nancy route for the specified <paramref name="path"/>.
/// </summary>
/// <value>A delegate that is used to invoke the route.</value>
public Func<dynamic, dynamic> this[string path]
{
set { this.AddRoute(string.Empty, path, null, value); }
}
/// <summary>
/// Defines a Nancy route for the specified <paramref name="path"/> and <paramref name="condition"/>.
/// </summary>
/// <value>A delegate that is used to invoke the route.</value>
public Func<dynamic, dynamic> this[string path, Func<NancyContext, bool> condition]
{
set { this.AddRoute(string.Empty, path, condition, value); }
}
/// <summary>
/// Defines an async route for the specified <paramref name="path"/>
/// </summary>
public Func<dynamic, CancellationToken, Task<dynamic>> this[string path, bool runAsync]
{
set { this.AddRoute(string.Empty, path, null, value); }
}
/// <summary>
/// Defines an async route for the specified <paramref name="path"/> and <paramref name="condition"/>.
/// </summary>
public Func<dynamic, CancellationToken, Task<dynamic>> this[string path, Func<NancyContext, bool> condition, bool runAsync]
{
set { this.AddRoute(string.Empty, path, condition, value); }
}
/// <summary>
/// Defines a Nancy route for the specified <paramref name="path"/> and <paramref name="name"/>
/// </summary>
/// <value>A delegate that is used to invoke the route.</value>
public Func<dynamic, dynamic> this[string name, string path]
{
set { this.AddRoute(name, path, null, value); }
}
/// <summary>
/// Defines a Nancy route for the specified <paramref name="path"/>, <paramref name="condition"/> and <paramref name="name"/>
/// </summary>
/// <value>A delegate that is used to invoke the route.</value>
public Func<dynamic, dynamic> this[string name, string path, Func<NancyContext, bool> condition]
{
set { this.AddRoute(name, path, condition, value); }
}
/// <summary>
/// Defines an async route for the specified <paramref name="path"/> and <paramref name="name"/>
/// </summary>
public Func<dynamic, CancellationToken, Task<dynamic>> this[string name, string path, bool runAsync]
{
set { this.AddRoute(name, path, null, value); }
}
/// <summary>
/// Defines an async route for the specified <paramref name="path"/>, <paramref name="condition"/> and <paramref name="name"/>
/// </summary>
public Func<dynamic, CancellationToken, Task<dynamic>> this[string name, string path, Func<NancyContext, bool> condition, bool runAsync]
{
set { this.AddRoute(name, path, condition, value); }
}
protected void AddRoute(string name, string path, Func<NancyContext, bool> condition, Func<dynamic, dynamic> value)
{
var fullPath = GetFullPath(path);
this.parentModule.routes.Add(Route.FromSync(name, this.method, fullPath, condition, value));
}
protected void AddRoute(string name, string path, Func<NancyContext, bool> condition, Func<dynamic, CancellationToken, Task<dynamic>> value)
{
var fullPath = GetFullPath(path);
this.parentModule.routes.Add(new Route(name, this.method, fullPath, condition, value));
}
private string GetFullPath(string path)
{
var relativePath = (path ?? string.Empty).Trim('/');
var parentPath = (this.parentModule.ModulePath ?? string.Empty).Trim('/');
if (string.IsNullOrEmpty(parentPath))
{
return string.Concat("/", relativePath);
}
if (string.IsNullOrEmpty(relativePath))
{
return string.Concat("/", parentPath);
}
return string.Concat("/", parentPath, "/", relativePath);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
namespace Codentia.Common.Membership
{
/// <summary>
/// Contact class
/// </summary>
public class Contact : IContactDetails
{
private int _emailAddressId;
private string _emailAddressText;
private bool _isConfirmed;
private int _emailAddressOrder;
private Guid _confirmGuid;
private Address[] _addresses;
/// <summary>
/// Initializes a new instance of the <see cref="Contact"/> class.
/// </summary>
/// <param name="emailAddressText">The email address text.</param>
public Contact(string emailAddressText)
: this(Guid.Empty, emailAddressText)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Contact"/> class.
/// </summary>
/// <param name="txnId">The TXN id.</param>
/// <param name="emailAddressText">The email address text.</param>
public Contact(Guid txnId, string emailAddressText)
{
_emailAddressText = emailAddressText;
PopulateByEmailAddress(txnId);
}
/// <summary>
/// Initializes a new instance of the <see cref="Contact"/> class.
/// </summary>
/// <param name="cookie">The cookie.</param>
public Contact(Guid cookie)
{
PopulateViaCookie(cookie);
}
/// <summary>
/// Initializes a new instance of the <see cref="Contact"/> class.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="contactCookieName">Name of the contact cookie.</param>
public Contact(HttpContext context, string contactCookieName)
{
Guid emailAddressGuid = Guid.Empty;
if (context.User.Identity.IsAuthenticated)
{
_emailAddressText = context.User.Identity.Name;
PopulateByEmailAddress(Guid.Empty);
}
else
{
HttpCookie emailAddressCookie = context.Request.Cookies[contactCookieName];
if (emailAddressCookie != null)
{
if (!string.IsNullOrEmpty(emailAddressCookie.Value))
{
emailAddressGuid = new Guid(emailAddressCookie.Value);
}
}
if (emailAddressGuid == Guid.Empty)
{
throw new ArgumentException("A valid emailaddress cannot be found, empty or missing Guid");
}
PopulateViaCookie(emailAddressGuid);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="Contact"/> class.
/// </summary>
/// <param name="emailAddressId">The email address id.</param>
internal Contact(int emailAddressId)
: this(Guid.Empty, emailAddressId)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Contact"/> class.
/// </summary>
/// <param name="txnId">The TXN id.</param>
/// <param name="emailAddressId">The email address id.</param>
internal Contact(Guid txnId, int emailAddressId)
{
DataTable dt = ContactData.GetEmailAddressData(txnId, emailAddressId);
PopulateByDataRow(dt.Rows[0]);
}
/// <summary>
/// Initializes a new instance of the <see cref="Contact"/> class.
/// </summary>
/// <param name="txnId">The TXN id.</param>
/// <param name="emailAddressData">The email address data.</param>
internal Contact(Guid txnId, DataRow emailAddressData)
{
this.PopulateByDataRow(emailAddressData);
}
/// <summary>
/// Gets a value indicating whether this instance is confirmed.
/// </summary>
/// <value>
/// <c>true</c> if this instance is confirmed; otherwise, <c>false</c>.
/// </value>
public bool IsConfirmed
{
get
{
return _isConfirmed;
}
}
/// <summary>
/// Gets the email address order.
/// </summary>
public int EmailAddressOrder
{
get
{
return _emailAddressOrder;
}
}
/// <summary>
/// Gets the confirm GUID.
/// </summary>
public Guid ConfirmGuid
{
get
{
return _confirmGuid;
}
}
/// <summary>
/// Gets the addresses.
/// </summary>
/// <value>The addresses.</value>
public Address[] Addresses
{
get
{
if (_addresses == null)
{
_addresses = GetAddressesForContact();
}
return _addresses;
}
}
/// <summary>
/// Gets the email address.
/// </summary>
/// <value>The email address.</value>
public string EmailAddress
{
get
{
return _emailAddressText;
}
}
/// <summary>
/// Gets the email address id.
/// </summary>
internal int EmailAddressId
{
get
{
return _emailAddressId;
}
}
/// <summary>
/// Constructor (By Cookie) - get data
/// </summary>
/// <param name="emailAddress">The email address.</param>
/// <returns>Contact object</returns>
public static Contact CreateContact(string emailAddress)
{
return CreateContact(Guid.Empty, emailAddress);
}
/// <summary>
/// Constructor (By Cookie) - get data
/// </summary>
/// <param name="txnId">transaction Id</param>
/// <param name="emailAddress">The email address.</param>
/// <returns>Contact object</returns>
public static Contact CreateContact(Guid txnId, string emailAddress)
{
if (!ContactData.EmailAddressExists(txnId, emailAddress))
{
int emailAddressId = ContactData.CreateEmailAddress(txnId, emailAddress);
return new Contact(txnId, emailAddressId);
}
else
{
return new Contact(txnId, emailAddress);
}
}
/// <summary>
/// Confirms the email address.
/// </summary>
/// <param name="emailAddress">The email address.</param>
/// <param name="confirmGuid">The confirm GUID.</param>
/// <returns>Is Confirmed</returns>
public static bool ConfirmEmailAddress(string emailAddress, Guid confirmGuid)
{
return ContactData.Confirm(emailAddress, confirmGuid);
}
/// <summary>
/// Gets the system user for email address.
/// </summary>
/// <returns>SystemUser object</returns>
public SystemUser GetSystemUserForEmailAddress()
{
int systemUserId = ContactData.GetSystemUserIdForEmailAddress(_emailAddressId);
if (systemUserId > 0)
{
return new SystemUser(Convert.ToInt32(systemUserId));
}
else
{
return null;
}
}
private void PopulateViaCookie(Guid cookie)
{
DataTable dt = ContactData.GetEmailAddressData(cookie);
if (dt.Rows.Count == 0)
{
throw new ArgumentException(string.Format("A valid emailaddress cannot be found, emailAddressGuid={0}", cookie));
}
PopulateByDataRow(dt.Rows[0]);
}
private void PopulateByEmailAddress(Guid txnId)
{
DataTable dt = ContactData.GetEmailAddressData(txnId, _emailAddressText);
PopulateByDataRow(dt.Rows[0]);
}
private void PopulateByDataRow(DataRow dr)
{
_emailAddressId = Convert.ToInt32(dr["EmailAddressId"]);
_emailAddressText = Convert.ToString(dr["EmailAddress"]);
_emailAddressOrder = 0;
if (dr["EmailAddressOrder"] != DBNull.Value)
{
_emailAddressOrder = Convert.ToInt32(dr["EmailAddressOrder"]);
}
_isConfirmed = Convert.ToBoolean(dr["IsConfirmed"]);
_confirmGuid = new Guid(Convert.ToString(dr["ConfirmGuid"]));
}
private Address[] GetAddressesForContact()
{
DataTable dt = ContactData.GetAddressesForEmailAddress(_emailAddressId);
List<Address> list = new List<Address>();
for (int i = 0; i < dt.Rows.Count; i++)
{
list.Add(new Address(dt.Rows[i]));
}
return list.ToArray();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Delta.UI;
using Delta.Input;
using Delta.Audio;
using Delta.Graphics;
using Delta.Graphics.Effects;
using Delta.Collision;
#if WINDOWS
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using Delta.Editor;
#endif
namespace Delta
{
/// <summary>
/// Static game class wrapper for Delta games.
/// </summary>
public class G : Game
{
internal const bool LETTERBOX = false;
internal const float ASPECT_RATIO_SD = 800f / 600f;
internal const float ASPECT_RATIO_HD = 1920f / 1080f;
internal const Microsoft.Xna.Framework.Input.Keys EDITOR_KEY = Microsoft.Xna.Framework.Input.Keys.F12;
#if WINDOWS
internal static bool _refreshPropertyGrid = false;
internal static float _refreshPropertyGridTimer = 0;
#endif
internal static ResourceContentManager _embedded = null;
internal static GraphicsDeviceManager _graphicsDeviceManager = null;
internal static bool _lateInitialized = false;
internal static Game _instance = null;
internal static DeltaGameTime _time = new DeltaGameTime();
public new static ContentManager Content { get; private set; }
public static InputManager Input { get; private set; }
public static AudioManager Audio { get; private set; }
public static World World { get; private set; }
public static UIManager UI { get; private set; }
public static PostEffects CurrentPostEffects { get; set; }
public new static GraphicsDevice GraphicsDevice { get { return _instance.GraphicsDevice; } }
public new static bool IsMouseVisible { get { return _instance.IsMouseVisible; } set { _instance.IsMouseVisible = value; } }
public static bool IsVSyncEnabled { get { return _graphicsDeviceManager.SynchronizeWithVerticalRetrace; } }
public static SpriteBatch SpriteBatch { get; private set; }
public static PrimitiveBatch PrimitiveBatch { get; private set; }
public static CollisionWorld Collision { get; private set; }
public static Texture2D PixelTexture { get; private set; }
public static SpriteFont Font { get; private set; }
public static Random Random { get; private set; }
public static Rectangle ScreenArea { get; private set; }
public static Vector2 ScreenCenter { get; private set; }
public static DeltaEffect DeltaEffect { get; private set; }
public static SimpleEffect SimpleEffect { get; private set; }
#if WINDOWS
public static Process Process { get; set; }
public static Form GameForm { get; set; }
public static EditorForm EditorForm { get; set; }
#endif
public G(int screenWidth, int screenHeight)
: this(screenWidth, screenHeight, true, "Content")
{
}
public G(int screenWidth, int screenHeight, bool vSync, string contentDirectory)
: base()
{
_instance = this;
Content = base.Content;
Content.RootDirectory = contentDirectory;
IsFixedTimeStep = true;
_graphicsDeviceManager = new GraphicsDeviceManager(this);
_graphicsDeviceManager.PreferredBackBufferWidth = screenWidth;
_graphicsDeviceManager.PreferredBackBufferHeight = screenHeight;
_graphicsDeviceManager.DeviceReset += OnDeviceReset;
_graphicsDeviceManager.PreparingDeviceSettings += OnPreparingDeviceSettings;
_graphicsDeviceManager.SynchronizeWithVerticalRetrace = vSync;
_embedded = new ResourceContentManager(Services, EmbeddedContent.ResourceManager);
#if DEBUG
base.IsMouseVisible = true;
Window.AllowUserResizing = true;
#endif
World = new World();
UI = new UIManager();
Random = new Random();
Input = new InputManager();
Audio = new AudioManager(@"Content\Audio\audio.xgs", @"Content\Audio\Sound Bank.xsb", @"Content\Audio\Wave Bank.xwb", @"Content\Audio\StreamingBank.xwb");
Collision = new CollisionWorld(new SeperatingAxisNarrowphase(), new UniformGridBroadphase());
ScreenArea = new Rectangle(0, 0, screenWidth, screenHeight);
ScreenCenter = ScreenArea.Center.ToVector2();
#if WINDOWS
Process = Process.GetCurrentProcess();
GameForm = (Form)Control.FromHandle(Window.Handle);
EditorForm = new EditorForm();
EditorForm.Icon = GameForm.Icon;
#endif
}
protected override void LoadContent()
{
base.LoadContent();
SpriteBatch = new SpriteBatch(GraphicsDevice);
PrimitiveBatch = new PrimitiveBatch(GraphicsDevice);
PixelTexture = new Texture2D(GraphicsDevice, 1, 1);
PixelTexture.SetData<Color>(new Color[] { Color.White });
Font = _embedded.Load<SpriteFont>("TinyFont");
DeltaEffect = new DeltaEffect(_embedded.Load<Effect>("DeltaEffect"));
SimpleEffect = new SimpleEffect(_embedded.Load<Effect>("SimpleEffect"));
World.InternalLoadContent();
UI.InternalLoadContent();
}
protected virtual void LateInitialize()
{
GC.Collect();
ResetElapsedTime();
}
protected override void Update(GameTime gameTime)
{
base.Update(gameTime);
_time.ElapsedSeconds = (float)gameTime.ElapsedGameTime.TotalSeconds;
_time.TotalSeconds += _time.ElapsedSeconds;
Input.Update(_time);
Audio.Update(_time);
if (!_lateInitialized)
{
_lateInitialized = true;
LateInitialize();
}
//if (_lateInitialized) // only update after the game has late initialized, otherwise entities will lateinitialize first.
//{
World.InternalUpdate(_time);
UI.InternalUpdate(_time);
//}
Collision.Simulate(_time.ElapsedSeconds); // simulate after the world update! otherwise simulating a previous frame's worldstate.
#if WINDOWS
if (G.Input.Keyboard.IsPressed(EDITOR_KEY))
{
if (!EditorForm.Visible)
{
EditorForm.Show();
EditorForm.Focus();
}
else
{
EditorForm.Hide();
}
}
if (_refreshPropertyGrid)
{
if (_refreshPropertyGridTimer <= 0)
{
G.EditorForm.grdProperty.Refresh();
_refreshPropertyGridTimer = 0;
_refreshPropertyGrid = false;
}
else
_refreshPropertyGridTimer -= _time.ElapsedSeconds;
}
#endif
}
protected override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
World.InternalDraw(World.Time, G.SpriteBatch);
UI.InternalDraw(_time, G.SpriteBatch);
}
public static void ToggleFullScreen()
{
_graphicsDeviceManager.ToggleFullScreen();
}
void OnDeviceReset(object sender, EventArgs e)
{
var pp = GraphicsDevice.PresentationParameters;
int width = pp.BackBufferWidth;
int height = pp.BackBufferHeight;
// scale height to maintain widescreen aspect ratio
if (width / height == (int)ASPECT_RATIO_SD && LETTERBOX)
{
height = (int)((float)width * (1f / ASPECT_RATIO_HD));
GraphicsDevice.Viewport = new Viewport(0, (pp.BackBufferHeight - height) / 2, width, height);
}
// xna will try to maintain the backbuffer resolution, however the monitor may not support it.
// xna will then pick the next best resolution. eg. 1920x1080 fullscreened becomes 1600x900.
// therefore the original resolution is not maintained and ScreenArea needs to update accordingly.
Vector2 increaseFactor = new Vector2((float)width / (float)ScreenArea.Width, (float)height / (float)ScreenArea.Height);
ScreenArea = new Rectangle(0, 0, width, height);
ScreenCenter = ScreenArea.Center.ToVector2();
// re-align the camera's offset
World.Camera.Offset = World.Camera.Offset * increaseFactor;
}
void OnPreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs e)
{
var pp = e.GraphicsDeviceInformation.PresentationParameters;
if (pp.IsFullScreen)
{
// testing: manually set the resolution; needs a supported check.
//pp.BackBufferWidth = 1920;
//pp.BackBufferHeight = 1080;
}
}
}
}
| |
#if NETFX_CORE
using MarkerMetro.Unity.WinLegacy.Security.Cryptography;
using System.Threading.Tasks;
using System.Globalization;
#endif
using Facebook;
using System;
using System.Collections.Generic;
using MarkerMetro.Unity.WinIntegration;
#if NETFX_CORE
using Windows.Storage;
using MarkerMetro.Unity.WinIntegration.Storage;
#endif
namespace MarkerMetro.Unity.WinIntegration.Facebook
{
public class MissingPlatformException : Exception
{
public MissingPlatformException()
: base("Platform components have not been set")
{
}
}
public static class FB
{
#if NETFX_CORE
private static FacebookClient _client;
private static IWebInterface _web;
private static HideUnityDelegate _onHideUnity;
private static string _redirectUrl = "http://www.facebook.com/connect/login_success.html";
private const string TOKEN_KEY = "ATK";
private const string EXPIRY_DATE = "EXP";
private const string EXPIRY_DATE_BIN = "EXPB";
private const string FBID_KEY = "FBID";
private const string FBNAME_KEY = "FBNAME";
#endif
public static string UserId { get; private set; }
public static string UserName { get; set; }
public static bool IsLoggedIn { get { return !string.IsNullOrEmpty(AccessToken); } }
public static string AppId { get; private set; }
public static string AccessToken { get; private set; }
public static DateTime Expires { get; private set; }
// check whether facebook is initialized
public static bool IsInitialized
{
get
{
#if NETFX_CORE
return _client != null;
#else
throw new PlatformNotSupportedException("");
#endif
}
}
public static void Logout()
{
#if NETFX_CORE
if (_web == null) throw new MissingPlatformException();
if (_web.IsActive || !IsLoggedIn) return;
var uri = _client.GetLogoutUrl(new
{
access_token = AccessToken,
next = _redirectUrl,
display = "popup"
});
_web.ClearCookies();
InvalidateData();
_web.Navigate(uri, false, (url, state) =>
{
_web.Finish();
},
(url, error, state) => _web.Finish());
#else
throw new PlatformNotSupportedException("");
#endif
}
public static void Login(string permissions, FacebookDelegate callback)
{
#if NETFX_CORE
if (_web == null) throw new MissingPlatformException();
if (_web.IsActive || IsLoggedIn)
{
// Already in use
if (callback != null)
{
callback(new FBResult() { Error = "Already in use" });
}
return;
}
var uri = _client.GetLoginUrl(new
{
redirect_uri = _redirectUrl,
scope = permissions,
display = "popup",
response_type = "token"
});
_web.ClearCookies();
_web.Navigate(uri, true, onError: LoginNavigationError, state: callback, startedCallback: LoginNavigationStarted);
if (_onHideUnity != null)
{
_onHideUnity(true);
}
#else
throw new PlatformNotSupportedException("");
#endif
}
#if NETFX_CORE
private static void LoginNavigationError(Uri url, int error, object state)
{
//Debug.LogError("Nav error: " + error);
if (state is FacebookDelegate)
((FacebookDelegate)state)(new FBResult() { Error = error.ToString() });
_web.Finish();
if (_onHideUnity != null)
_onHideUnity(false);
}
private static void LoginNavigationStarted(Uri url, object state)
{
FacebookOAuthResult result;
// Check if we're waiting for user input or if login is complete
if (_client.TryParseOAuthCallbackUrl(url, out result))
{
// Login complete
if (result.IsSuccess)
{
AccessToken = result.AccessToken;
Expires = result.Expires;
_client.AccessToken = AccessToken;
Settings.Set(TOKEN_KEY, EncryptionProvider.Encrypt(AccessToken, AppId));
Settings.Set(EXPIRY_DATE_BIN, Expires.ToBinary());
}
_web.Finish();
if (_onHideUnity != null)
{
_onHideUnity(false);
}
API("/me?fields=id,name", HttpMethod.GET, fbResult =>
{
if (IsLoggedIn)
{
UserId = fbResult.Json["id"] as string;
UserName = fbResult.Json["name"] as string;
Settings.Set(FBID_KEY, UserId);
Settings.Set(FBNAME_KEY, UserName);
}
if (state is FacebookDelegate)
{
JsonObject jResult = new JsonObject();
jResult.Add(new KeyValuePair<string, object>("authToken", AccessToken));
jResult.Add(new KeyValuePair<string, object>("authTokenExpiry", Expires.ToString()));
((FacebookDelegate)state)(new FBResult()
{
Json = jResult,
Text = jResult.ToString()
});
}
});
}
}
#endif
public static void Init(
InitDelegate onInitComplete,
string appId,
HideUnityDelegate onHideUnity, string redirectUrl = null)
{
#if NETFX_CORE
if (_client != null)
{
if (onInitComplete != null)
onInitComplete();
return;
}
if (_web == null) throw new MissingPlatformException();
if (string.IsNullOrEmpty(appId)) throw new ArgumentException("Invalid Facebook App ID");
if (!string.IsNullOrEmpty(redirectUrl))
_redirectUrl = redirectUrl;
_client = new FacebookClient();
_client.GetCompleted += HandleGetCompleted;
AppId = _client.AppId = appId;
_onHideUnity = onHideUnity;
if (Settings.HasKey(TOKEN_KEY))
{
AccessToken = EncryptionProvider.Decrypt(Settings.GetString(TOKEN_KEY), AppId);
if (Settings.HasKey(EXPIRY_DATE))
{
string expDate = EncryptionProvider.Decrypt(Settings.GetString(EXPIRY_DATE), AppId);
Expires = DateTime.Parse(expDate, CultureInfo.InvariantCulture);
}
else
{
long expDate = Settings.GetLong(EXPIRY_DATE_BIN);
Expires = DateTime.FromBinary(expDate);
}
_client.AccessToken = AccessToken;
UserId = Settings.GetString(FBID_KEY);
UserName = Settings.GetString(FBNAME_KEY);
// verifies if the token has expired:
if (DateTime.Compare(DateTime.UtcNow, Expires) > 0)
InvalidateData();
//var task = TestAccessToken();
//task.Wait();
}
if (onInitComplete != null)
onInitComplete();
#else
throw new PlatformNotSupportedException("");
#endif
}
public static void ChangeRedirect(string redirectUrl)
{
#if NETFX_CORE
if (!string.IsNullOrEmpty(redirectUrl) && !_web.IsActive)
_redirectUrl = redirectUrl;
#endif
}
#if NETFX_CORE
/// <summary>
/// Test if the access token is still valid by making a simple API call
/// </summary>
/// <returns>The async task</returns>
private static async Task TestAccessToken()
{
try
{
await _client.GetTaskAsync("/me?fields=id,name");
}
catch (FacebookApiException)
{
// If any exception then auto login has been an issue. Set everything to null so the game
// thinks the user is logged out and they can restart the login procedure
InvalidateData();
}
}
private static void InvalidateData()
{
AccessToken = null;
Expires = default(DateTime);
UserId = null;
UserName = null;
_client.AccessToken = null;
Settings.DeleteKey(TOKEN_KEY);
Settings.DeleteKey(FBID_KEY);
Settings.DeleteKey(FBNAME_KEY);
Settings.DeleteKey(EXPIRY_DATE);
Settings.DeleteKey(EXPIRY_DATE_BIN);
}
private static void HandleGetCompleted(object sender, FacebookApiEventArgs e)
{
var callback = e.UserState as FacebookDelegate;
if (callback != null)
{
var result = new FBResult();
if (e.Cancelled)
result.Error = "Cancelled";
else if (e.Error != null)
result.Error = e.Error.Message;
else
{
var obj = e.GetResultData();
result.Text = obj.ToString();
result.Json = obj as JsonObject;
}
Dispatcher.InvokeOnAppThread(() => { callback(result); });
}
}
#endif
public static void API(
string endpoint,
HttpMethod method,
FacebookDelegate callback,
object parameters = null)
{
#if NETFX_CORE
if (_web == null) throw new MissingPlatformException();
if (!IsLoggedIn)
{
// Already in use
if (callback != null)
callback(new FBResult() { Error = "Not logged in" });
return;
}
Task.Run(async () =>
{
FBResult fbResult = null;
try
{
object apiCall;
if (method == HttpMethod.GET)
{
apiCall = await _client.GetTaskAsync(endpoint, parameters);
}
else if (method == HttpMethod.POST)
{
apiCall = await _client.PostTaskAsync(endpoint, parameters);
}
else
{
apiCall = await _client.DeleteTaskAsync(endpoint);
}
if (apiCall != null)
{
fbResult = new FBResult();
fbResult.Text = apiCall.ToString();
fbResult.Json = apiCall as JsonObject;
}
}
catch (Exception ex)
{
fbResult = new FBResult();
fbResult.Error = ex.Message;
}
if (callback != null)
{
Dispatcher.InvokeOnAppThread(() => { callback(fbResult); });
}
});
#else
throw new PlatformNotSupportedException("");
#endif
}
public static void SetPlatformInterface(IWebInterface web)
{
#if NETFX_CORE
_web = web;
#else
throw new PlatformNotSupportedException("");
#endif
}
/// <summary>
/// Show Request Dialog.
/// to, title, data, filters, excludeIds and maxRecipients are not currently supported at this time.
/// </summary>
public static void AppRequest(
string message,
string[] to = null,
string filters = "",
string[] excludeIds = null,
int? maxRecipients = null,
string data = "",
string title = "",
FacebookDelegate callback = null
)
{
#if NETFX_CORE
///
/// @note: [vaughan.sanders 15.8.14] We are overriding the Unity FB.AppRequest here to send a more
/// general web style request as WP8 does not support the actual request functionality.
/// Currently we ignore all but the message and callback params
///
if (_web == null) throw new MissingPlatformException();
if (_web.IsActive || !IsLoggedIn)
{
// Already in use
if (callback != null)
callback(new FBResult() { Error = "Already in use / Not Logged In" });
return;
}
if (_onHideUnity != null)
_onHideUnity(true);
Uri uri = new Uri("https://www.facebook.com/dialog/apprequests?app_id=" + AppId +
"&message=" + message + "&display=popup&redirect_uri=" + _redirectUrl, UriKind.RelativeOrAbsolute);
_web.Navigate(uri, true, finishedCallback: (url, state) =>
{
if (url.ToString().StartsWith(_redirectUrl))
{
// parsing query string to get request id and facebook ids of the people the request has been sent to
// or error code and error messages
FBResult fbResult = new FBResult();
fbResult.Json = new JsonObject();
string[] queries = url.Query.Split('&');
if (queries.Length > 0)
{
string request = string.Empty;
List<string> toList = new List<string>();
foreach (string query in queries)
{
string[] keyValue = query.Split('=');
if (keyValue.Length == 2)
{
if (keyValue[0].Contains("request"))
request = keyValue[1];
else if (keyValue[0].Contains("to"))
toList.Add(keyValue[1]);
else if (keyValue[0].Contains("error_code"))
fbResult.Error = keyValue[1];
else if (keyValue[0].Contains("error_message"))
fbResult.Text = keyValue[1].Replace('+', ' ');
}
}
if (!string.IsNullOrWhiteSpace(request))
{
fbResult.Json.Add(new KeyValuePair<string, object>("request", request));
fbResult.Json.Add(new KeyValuePair<string, object>("to", toList));
}
}
// If there's no error, assign the success text
if (string.IsNullOrWhiteSpace(fbResult.Text))
fbResult.Text = "Success";
_web.Finish();
if (_onHideUnity != null)
_onHideUnity(false);
if (callback != null)
callback(fbResult);
}
}, onError: LoginNavigationError, state: callback);
// throw not supported exception when user passed in parameters not supported currently
if (!string.IsNullOrWhiteSpace(filters) || excludeIds != null || maxRecipients != null || to != null || !string.IsNullOrWhiteSpace(data) || !string.IsNullOrWhiteSpace(title))
throw new NotSupportedException("to, title, data, filters, excludeIds and maxRecipients are not currently supported at this time.");
#else
throw new PlatformNotSupportedException("");
#endif
}
/// <summary>
/// Show the Feed Dialog.
/// mediaSource, actionName, actionLink, reference and properties are not currently supported at this time.
/// </summary>
public static void Feed(
string toId = "",
string link = "",
string linkName = "",
string linkCaption = "",
string linkDescription = "",
string picture = "",
string mediaSource = "",
string actionName = "",
string actionLink = "",
string reference = "",
Dictionary<string, string[]> properties = null,
FacebookDelegate callback = null)
{
#if NETFX_CORE
if (_web == null) throw new MissingPlatformException();
if (_web.IsActive || !IsLoggedIn)
{
// Already in use
if (callback != null)
callback(new FBResult() { Error = "Already in use / Not Logged In" });
return;
}
if (_onHideUnity != null)
_onHideUnity(true);
Uri uri = new Uri("https://www.facebook.com/dialog/feed?app_id=" + AppId + "&to=" + toId +
"&link=" + link + "&name=" + linkName + "&caption=" + linkCaption + "&description=" + linkDescription + "&picture=" + picture + "&display=popup&redirect_uri=" + _redirectUrl, UriKind.RelativeOrAbsolute);
_web.Navigate(uri, true, finishedCallback: (url, state) =>
{
if (url.ToString().StartsWith(_redirectUrl))
{
// parsing query string to get request id and facebook ids of the people the request has been sent to
// or error code and error messages
FBResult fbResult = new FBResult();
fbResult.Json = new JsonObject();
string[] queries = url.Query.Split('&');
if (queries.Length > 0)
{
string postId = string.Empty;
List<string> toList = new List<string>();
foreach (string query in queries)
{
string[] keyValue = query.Split('=');
if (keyValue.Length == 2)
{
if (keyValue[0].Contains("post_id"))
postId = keyValue[1];
else if (keyValue[0].Contains("error_code"))
fbResult.Error = keyValue[1];
else if (keyValue[0].Contains("error_msg"))
fbResult.Text = keyValue[1].Replace('+', ' ');
}
}
if (!string.IsNullOrWhiteSpace(postId))
{
fbResult.Json.Add(new KeyValuePair<string, object>("post_id", postId));
}
}
// If there's no error, assign the success text
if (string.IsNullOrWhiteSpace(fbResult.Text))
fbResult.Text = "Success";
_web.Finish();
if (_onHideUnity != null)
_onHideUnity(false);
if (callback != null)
callback(fbResult);
}
}, onError: LoginNavigationError, state: callback);
// throw not supported exception when user passed in parameters not supported currently
if (!string.IsNullOrWhiteSpace(mediaSource) || !string.IsNullOrWhiteSpace(actionName) || !string.IsNullOrWhiteSpace(actionLink) ||
!string.IsNullOrWhiteSpace(reference) || properties != null)
throw new NotSupportedException("mediaSource, actionName, actionLink, reference and properties are not currently supported at this time.");
#else
throw new PlatformNotSupportedException("");
#endif
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using Orleans.TestingHost;
using TestExtensions;
using UnitTests.GrainInterfaces;
using UnitTests.TestHelper;
using Xunit;
using Xunit.Abstractions;
using System.Linq;
using Orleans.Internal;
using Orleans.Hosting;
using Orleans.Configuration;
using Microsoft.Extensions.Configuration;
namespace UnitTests.ActivationsLifeCycleTests
{
[TestCategory("ActivationCollector")]
public class DeactivateOnIdleTests : OrleansTestingBase, IDisposable
{
private readonly ITestOutputHelper output;
private TestCluster testCluster;
public DeactivateOnIdleTests(ITestOutputHelper output)
{
this.output = output;
}
private void Initialize(TestClusterBuilder builder = null)
{
if (builder == null)
{
builder = new TestClusterBuilder(1);
}
testCluster = builder.Build();
testCluster.Deploy();
}
public void Dispose()
{
testCluster?.StopAllSilos();
testCluster = null;
}
[Fact, TestCategory("Functional")]
public async Task DeactivateOnIdleTestInside_Basic()
{
Initialize();
var a = this.testCluster.GrainFactory.GetGrain<ICollectionTestGrain>(1);
var b = this.testCluster.GrainFactory.GetGrain<ICollectionTestGrain>(2);
await a.SetOther(b);
await a.GetOtherAge(); // prime a's routing cache
await b.DeactivateSelf();
Thread.Sleep(5000);
var age = a.GetOtherAge().WaitForResultWithThrow(TimeSpan.FromMilliseconds(2000));
Assert.True(age.TotalMilliseconds < 2000, "Should be newly activated grain");
}
[Fact, TestCategory("SlowBVT"), TestCategory("Functional")]
public async Task DeactivateOnIdleTest_Stress_1()
{
Initialize();
var a = this.testCluster.GrainFactory.GetGrain<ICollectionTestGrain>(1);
await a.GetAge();
await a.DeactivateSelf();
for (int i = 0; i < 30; i++)
{
await a.GetAge();
}
}
[Fact, TestCategory("Functional")]
public async Task DeactivateOnIdleTest_Stress_2_NonReentrant()
{
Initialize();
var a = this.testCluster.GrainFactory.GetGrain<ICollectionTestGrain>(1, "UnitTests.Grains.CollectionTestGrain");
await a.IncrCounter();
Task t1 = Task.Run(async () =>
{
List<Task> tasks = new List<Task>();
for (int i = 0; i < 100; i++)
{
tasks.Add(a.IncrCounter());
}
await Task.WhenAll(tasks);
});
await Task.Delay(1);
Task t2 = a.DeactivateSelf();
await Task.WhenAll(t1, t2);
}
[Fact, TestCategory("Functional")]
public async Task DeactivateOnIdleTest_Stress_3_Reentrant()
{
Initialize();
var a = this.testCluster.GrainFactory.GetGrain<ICollectionTestGrain>(1, "UnitTests.Grains.ReentrantCollectionTestGrain");
await a.IncrCounter();
Task t1 = Task.Run(async () =>
{
List<Task> tasks = new List<Task>();
for (int i = 0; i < 100; i++)
{
tasks.Add(a.IncrCounter());
}
await Task.WhenAll(tasks);
});
await Task.Delay(TimeSpan.FromMilliseconds(1));
Task t2 = a.DeactivateSelf();
await Task.WhenAll(t1, t2);
}
[Fact, TestCategory("Functional")]
public async Task DeactivateOnIdleTest_Stress_4_Timer()
{
Initialize();
var a = this.testCluster.GrainFactory.GetGrain<ICollectionTestGrain>(1, "UnitTests.Grains.ReentrantCollectionTestGrain");
for (int i = 0; i < 10; i++)
{
await a.StartTimer(TimeSpan.FromMilliseconds(5), TimeSpan.FromMilliseconds(100));
}
await a.DeactivateSelf();
await a.IncrCounter();
}
[Fact, TestCategory("Functional")]
public async Task DeactivateOnIdleTest_Stress_5()
{
Initialize();
var a = this.testCluster.GrainFactory.GetGrain<ICollectionTestGrain>(1);
await a.IncrCounter();
Task t1 = Task.Run(async () =>
{
List<Task> tasks = new List<Task>();
for (int i = 0; i < 100; i++)
{
tasks.Add(a.IncrCounter());
}
await Task.WhenAll(tasks);
});
Task t2 = Task.Run(async () =>
{
List<Task> tasks = new List<Task>();
for (int i = 0; i < 1; i++)
{
await Task.Delay(1);
tasks.Add(a.DeactivateSelf());
}
await Task.WhenAll(tasks);
});
await Task.WhenAll(t1, t2);
}
[Fact, TestCategory("Stress")]
public async Task DeactivateOnIdleTest_Stress_11()
{
Initialize();
var a = this.testCluster.GrainFactory.GetGrain<ICollectionTestGrain>(1);
List<Task> tasks = new List<Task>();
for (int i = 0; i < 100; i++)
{
tasks.Add(a.IncrCounter());
}
await Task.WhenAll(tasks);
}
[Fact, TestCategory("Functional")]
public async Task DeactivateOnIdle_NonExistentActivation_1()
{
await DeactivateOnIdle_NonExistentActivation_Runner(0);
}
[Fact, TestCategory("Functional")]
public async Task DeactivateOnIdle_NonExistentActivation_2()
{
await DeactivateOnIdle_NonExistentActivation_Runner(1);
}
public class ClientConfigurator : IClientBuilderConfigurator
{
public void Configure(IConfiguration configuration, IClientBuilder clientBuilder)
{
clientBuilder.Configure<StaticGatewayListProviderOptions>(options => { options.Gateways = options.Gateways.Take(1).ToList(); });
}
}
public class SiloConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
var cfg = hostBuilder.GetConfiguration();
var maxForwardCount = int.Parse(cfg["MaxForwardCount"]);
hostBuilder.Configure<SiloMessagingOptions>(options => options.MaxForwardCount = maxForwardCount);
}
}
private async Task DeactivateOnIdle_NonExistentActivation_Runner(int forwardCount)
{
var builder = new TestClusterBuilder(2);
builder.AddClientBuilderConfigurator<ClientConfigurator>();
builder.AddSiloBuilderConfigurator<SiloConfigurator>();
builder.Properties["MaxForwardCount"] = forwardCount.ToString();
Initialize(builder);
ICollectionTestGrain grain = await PickGrainInNonPrimary();
output.WriteLine("About to make a 1st GetAge() call.");
TimeSpan age = await grain.GetAge();
output.WriteLine(age.ToString());
await grain.DeactivateSelf();
await Task.Delay(3000);
// ReSharper disable once PossibleNullReferenceException
var thrownException = await Record.ExceptionAsync(() => grain.GetAge());
if (forwardCount != 0)
{
Assert.Null(thrownException);
output.WriteLine("\nThe 1st call after DeactivateSelf has NOT thrown any exception as expected, since forwardCount is {0}.\n", forwardCount);
}
else
{
Assert.NotNull(thrownException);
Assert.IsType<OrleansMessageRejectionException>(thrownException);
Assert.Contains("Non-existent activation", thrownException.Message);
output.WriteLine("\nThe 1st call after DeactivateSelf has thrown Non-existent activation exception as expected, since forwardCount is {0}.\n", forwardCount);
// Try sending agan now and see it was fixed.
await grain.GetAge();
}
}
private async Task<ICollectionTestGrain> PickGrainInNonPrimary()
{
for (int i = 0; i < 500; i++)
{
if (i % 30 == 29) await Task.Delay(1000); // give some extra time to stabilize if it can't find a suitable grain
// Create grain such that:
// Its directory owner is not the Gateway silo. This way Gateway will use its directory cache.
// Its activation is located on the non Gateway silo as well.
ICollectionTestGrain grain = this.testCluster.GrainFactory.GetGrain<ICollectionTestGrain>(i);
GrainId grainId = ((GrainReference)await grain.GetGrainReference()).GrainId;
SiloAddress primaryForGrain = (await TestUtils.GetDetailedGrainReport(this.testCluster.InternalGrainFactory, grainId, this.testCluster.Primary)).PrimaryForGrain;
if (primaryForGrain.Equals(this.testCluster.Primary.SiloAddress))
{
continue;
}
string siloHostingActivation = await grain.GetRuntimeInstanceId();
if (this.testCluster.Primary.SiloAddress.ToLongString().Equals(siloHostingActivation))
{
continue;
}
this.output.WriteLine("\nCreated grain with key {0} whose primary directory owner is silo {1} and which was activated on silo {2}\n", i, primaryForGrain.ToLongString(), siloHostingActivation);
return grain;
}
Assert.True(testCluster.GetActiveSilos().Count() > 1, "This logic requires at least 1 non-primary active silo");
Assert.True(false, "Could not find a grain that activates on a non-primary silo, and has the partition be also managed by a non-primary silo");
return null;
}
[Fact, TestCategory("Functional")]
public async Task MissingActivation_WithoutDirectoryLazyDeregistration_MultiSilo()
{
var directoryLazyDeregistrationDelay = TimeSpan.FromMilliseconds(-1);
var builder = new TestClusterBuilder(2);
builder.AddSiloBuilderConfigurator<NoForwardingSiloConfigurator>();
Initialize(builder);
for (int i = 0; i < 10; i++)
{
await MissingActivation_Runner(i, directoryLazyDeregistrationDelay);
}
}
public class NoForwardingSiloConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
// Disable retries in this case, to make test more predictable.
hostBuilder.Configure<SiloMessagingOptions>(options => options.MaxForwardCount = 0);
}
}
[Fact, TestCategory("Functional")]
public async Task MissingActivation_WithDirectoryLazyDeregistration_SingleSilo()
{
var lazyDeregistrationDelay = TimeSpan.FromMilliseconds(5000);
var builder = new TestClusterBuilder(1);
builder.AddSiloBuilderConfigurator<NoForwardingSiloConfigurator>();
builder.AddSiloBuilderConfigurator<LazyDeregistrationDelaySiloConfigurator>();
Initialize(builder);
for (int i = 0; i < 10; i++)
{
await MissingActivation_Runner(i, lazyDeregistrationDelay);
}
}
public class LazyDeregistrationDelaySiloConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder.Configure<GrainDirectoryOptions>(options => options.LazyDeregistrationDelay = TimeSpan.FromMilliseconds(5000));
}
}
[Fact(Skip = "Needs investigation"), TestCategory("Functional")]
public async Task MissingActivation_WithoutDirectoryLazyDeregistration_MultiSilo_SecondaryFirst()
{
var lazyDeregistrationDelay = TimeSpan.FromMilliseconds(-1);
var builder = new TestClusterBuilder(2);
builder.Properties["MaxForwardCount"] = "0";
builder.AddClientBuilderConfigurator<ClientConfigurator>();
builder.AddSiloBuilderConfigurator<SiloConfigurator>();
Initialize(builder);
await MissingActivation_Runner(1, lazyDeregistrationDelay, true);
}
private async Task MissingActivation_Runner(
int grainId,
TimeSpan lazyDeregistrationDelay,
bool forceCreationInSecondary = false)
{
output.WriteLine("\n\n\n SMissingActivation_Runner.\n\n\n");
var realGrainId = grainId;
ITestGrain grain;
var isMultipleSilosPresent = testCluster.SecondarySilos != null && testCluster.SecondarySilos.Count > 0;
if (!isMultipleSilosPresent && forceCreationInSecondary)
{
throw new InvalidOperationException(
"If 'forceCreationInSecondary' is true multiple silos must be present, check the test!");
}
var grainSiloAddress = String.Empty;
var primarySiloAddress = testCluster.Primary.SiloAddress.ToString();
var secondarySiloAddress = isMultipleSilosPresent
? testCluster.SecondarySilos[0].SiloAddress.ToString()
: String.Empty;
//
// We only doing this for multiple silos.
//
if (isMultipleSilosPresent && forceCreationInSecondary)
{
//
// Make sure that we proceeding with a grain which is created in the secondary silo for first!
//
while (true)
{
this.output.WriteLine($"GetGrain: {realGrainId}");
grain = this.testCluster.GrainFactory.GetGrain<ITestGrain>(realGrainId);
grainSiloAddress = await grain.GetRuntimeInstanceId();
if (grainSiloAddress != secondarySiloAddress)
{
this.output.WriteLine($"GetGrain: {realGrainId} Primary, skipping.");
realGrainId++;
}
else
{
this.output.WriteLine($"GetGrain: {realGrainId} Secondary, proceeding.");
break;
}
}
}
else
{
grain = this.testCluster.GrainFactory.GetGrain<ITestGrain>(realGrainId);
}
await grain.SetLabel("hello_" + grainId);
var grainReference = ((GrainReference)await grain.GetGrainReference()).GrainId;
// Call again to make sure the grain is in all silo caches
for (int i = 0; i < 10; i++)
{
var label = await grain.GetLabel();
}
// Now we know that there's an activation; try both silos and deactivate it incorrectly
int primaryActivation =
await
this.testCluster.Client.GetTestHooks(testCluster.Primary)
.UnregisterGrainForTesting(grainReference);
int secondaryActivation = 0;
if (isMultipleSilosPresent)
{
secondaryActivation =
await
this.testCluster.Client.GetTestHooks(testCluster.SecondarySilos[0])
.UnregisterGrainForTesting(grainReference);
}
Assert.Equal(1, primaryActivation + secondaryActivation);
// If we try again, we shouldn't find any
primaryActivation =
await
this.testCluster.Client.GetTestHooks(testCluster.Primary)
.UnregisterGrainForTesting(grainReference);
secondaryActivation = 0;
if (isMultipleSilosPresent)
{
secondaryActivation =
await
this.testCluster.Client.GetTestHooks(testCluster.SecondarySilos[0])
.UnregisterGrainForTesting(grainReference);
}
Assert.Equal(0, primaryActivation + secondaryActivation);
if (lazyDeregistrationDelay > TimeSpan.Zero)
{
// Wait a bit
TimeSpan pause = lazyDeregistrationDelay.Multiply(2);
output.WriteLine($"Pausing for {0} because we are using lazy deregistration", pause);
await Task.Delay(pause);
}
// Now send a message again; it should fail);
var firstEx = await Assert.ThrowsAsync<OrleansMessageRejectionException>(() => grain.GetLabel());
Assert.Contains("Non-existent activation", firstEx.Message);
output.WriteLine("Got 1st Non-existent activation Exception, as expected.");
// Try again; it should succeed or fail, based on doLazyDeregistration
if (lazyDeregistrationDelay > TimeSpan.Zero || forceCreationInSecondary)
{
var newLabel = "";
newLabel = await grain.GetLabel();
// Since a new instance returned, we've to check that the label is no more prefixed with "hello_"
Assert.Equal(grainId.ToString(), newLabel);
output.WriteLine($"After 2nd call. newLabel = '{newLabel}'");
if (forceCreationInSecondary)
{
grainSiloAddress = await grain.GetRuntimeInstanceId();
output.WriteLine(
grainSiloAddress == primarySiloAddress ? "Recreated in Primary" : "Recreated in Secondary");
output.WriteLine(
grainSiloAddress == primarySiloAddress ? "Recreated in Primary" : "Recreated in Secondary");
}
}
else
{
var secondEx = await Assert.ThrowsAsync<OrleansMessageRejectionException>(() => grain.GetLabel());
output.WriteLine("Got 2nd exception - " + secondEx.GetBaseException().Message);
Assert.True(
secondEx.Message.Contains("duplicate activation")
|| secondEx.Message.Contains("Non-existent activation")
|| secondEx.Message.Contains("Forwarding failed"),
"2nd exception message: " + secondEx);
output.WriteLine("Got 2nd exception, as expected.");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ThinMvvm.Data;
using ThinMvvm.Data.Infrastructure;
using ThinMvvm.Logging;
using ThinMvvm.Tests.TestInfrastructure;
using Xunit;
namespace ThinMvvm.Tests.Logging
{
public sealed class DataLoggerExtensionsTests
{
private sealed class TestLogger : ILogger
{
public List<Tuple<string, Exception>> Errors { get; } = new List<Tuple<string, Exception>>();
public void LogNavigation( string viewModelId, bool isArriving )
{
throw new NotSupportedException();
}
public void LogEvent( string viewModelId, string eventId, string label )
{
throw new NotSupportedException();
}
public void LogError( string name, Exception exception )
{
Errors.Add( Tuple.Create( name, exception ) );
}
}
private sealed class MyDataSource : DataSource<int>
{
public Exception FetchError { get; set; }
public Exception CacheError { get; set; }
public Exception TransformError { get; set; }
public MyDataSource()
{
EnableCache( "X", new InMemoryDataStore(), () =>
{
if( CacheError != null )
{
throw CacheError;
}
return CacheMetadata.Default;
} );
}
protected override Task<int> FetchAsync( CancellationToken cancellationToken )
{
if( FetchError != null )
{
return TaskEx.FromException<int>( FetchError );
}
return Task.FromResult( 0 );
}
protected override Task<int> TransformAsync( int value )
{
if( TransformError != null )
{
throw TransformError;
}
return Task.FromResult( value );
}
}
[Fact]
public void CannotRegisterSourceWithNullLogger()
{
Assert.Throws<ArgumentNullException>(
() => DataLoggerExtensions.Register( null, new MyDataSource() )
);
}
[Fact]
public void CannotRegisterNullSource()
{
Assert.Throws<ArgumentNullException>(
() => DataLoggerExtensions.Register( new TestLogger(), (IDataSource) null )
);
}
[Fact]
public async Task NothingLoggedOnSourceSuccess()
{
var source = new MyDataSource();
var logger = new TestLogger();
logger.Register( source );
await source.RefreshAsync();
Assert.Equal( 0, logger.Errors.Count );
}
[Fact]
public async Task SourceFetchErrorIsLogged()
{
var ex = (Exception) new MyException();
var source = new MyDataSource { FetchError = ex };
var logger = new TestLogger();
logger.Register( source );
await source.RefreshAsync();
Assert.Equal( new[] { Tuple.Create( "Data source fetch error", ex ) }, logger.Errors );
}
[Fact]
public async Task SourceCacheErrorIsLogged()
{
var ex = (Exception) new MyException();
var source = new MyDataSource { CacheError = ex };
var logger = new TestLogger();
logger.Register( source );
await source.RefreshAsync();
Assert.Equal( new[] { Tuple.Create( "Data source cache error", ex ) }, logger.Errors );
}
[Fact]
public async Task SourceTransformErrorIsLogged()
{
var ex = (Exception) new MyException();
var source = new MyDataSource { TransformError = ex };
var logger = new TestLogger();
logger.Register( source );
await source.RefreshAsync();
Assert.Equal( new[] { Tuple.Create( "Data source processing error", ex ) }, logger.Errors );
}
[Fact]
public async Task MultipleSourceErrorsAreLogged()
{
var fetchEx = (Exception) new MyException();
var cacheEx = (Exception) new MyException();
var source = new MyDataSource { FetchError = fetchEx, CacheError = cacheEx };
var logger = new TestLogger();
logger.Register( source );
await source.RefreshAsync();
Assert.Equal( new[]
{
Tuple.Create( "Data source fetch error", fetchEx ),
Tuple.Create( "Data source cache error", cacheEx )
}, logger.Errors );
}
private sealed class MyForm : Form<int>
{
public Exception InitialError { get; set; }
public Exception SubmitError { get; set; }
protected override Task<int> LoadInitialInputAsync()
{
if( InitialError != null )
{
throw InitialError;
}
return Task.FromResult( 0 );
}
protected override Task SubmitAsync( int input )
{
if( SubmitError != null )
{
throw SubmitError;
}
return TaskEx.CompletedTask;
}
}
[Fact]
public void CannotRegisterFormWithNullLogger()
{
Assert.Throws<ArgumentNullException>(
() => DataLoggerExtensions.Register( null, new MyForm() )
);
}
[Fact]
public void CannotRegisterNullForm()
{
Assert.Throws<ArgumentNullException>(
() => DataLoggerExtensions.Register( new TestLogger(), (IForm) null )
);
}
[Fact]
public async Task NothingLoggedOnFormSuccess()
{
var form = new MyForm();
var logger = new TestLogger();
logger.Register( form );
await form.InitializeAsync();
await form.SubmitAsync();
Assert.Equal( 0, logger.Errors.Count );
}
[Fact]
public async Task FormInitialErrorIsLogged()
{
var ex = (Exception) new MyException();
var form = new MyForm() { InitialError = ex };
var logger = new TestLogger();
logger.Register( form );
await form.InitializeAsync();
Assert.Equal( new[] { Tuple.Create( "Form initialization error", ex ) }, logger.Errors );
}
[Fact]
public async Task FormSubmitErrorIsLogged()
{
var ex = (Exception) new MyException();
var form = new MyForm() { SubmitError = ex };
var logger = new TestLogger();
logger.Register( form );
await form.InitializeAsync();
await form.SubmitAsync();
Assert.Equal( new[] { Tuple.Create( "Form submission error", ex ) }, logger.Errors );
}
}
}
| |
#region Copyright (c) 2003, newtelligence AG. All rights reserved.
/*
// Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com)
// Original BlogX Source Code: Copyright (c) 2003, Chris Anderson (http://simplegeek.com)
// 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.
// (3) Neither the name of the newtelligence AG 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.
// -------------------------------------------------------------------------
//
// Original BlogX source code (c) 2003 by Chris Anderson (http://simplegeek.com)
//
// newtelligence is a registered trademark of newtelligence Aktiengesellschaft.
//
// For portions of this software, the some additional copyright notices may apply
// which can either be found in the license.txt file included in the source distribution
// or following this notice.
//
*/
#endregion
using CookComputing.XmlRpc;
namespace newtelligence.DasBlog.Web.Services.Blogger
{
/// <summary>
///
/// </summary>
public struct Category
{
/// <summary>
///
/// </summary>
public string categoryid;
/// <summary>
///
/// </summary>
public string title;
/// <summary>
///
/// </summary>
public string description;
/// <summary>
///
/// </summary>
public string htmlUrl;
/// <summary>
///
/// </summary>
public string rssUrl;
}
/// <summary>
///
/// </summary>
public struct Post
{
/// <summary>
///
/// </summary>
public System.DateTime dateCreated;
/// <summary>
///
/// </summary>
[XmlRpcMember(
Description="Depending on server may be either string or integer. "
+ "Use Convert.ToInt32(userid) to treat as integer or "
+ "Convert.ToString(userid) to treat as string")]
public object userid;
/// <summary>
///
/// </summary>
public string postid;
/// <summary>
///
/// </summary>
public string content;
}
/// <summary>
///
/// </summary>
public struct UserInfo
{
/// <summary>
///
/// </summary>
public string url;
/// <summary>
///
/// </summary>
public string email;
/// <summary>
///
/// </summary>
public string nickname;
/// <summary>
///
/// </summary>
public string lastname;
/// <summary>
///
/// </summary>
public string firstname;
}
/// <summary>
///
/// </summary>
public struct BlogInfo
{
/// <summary>
///
/// </summary>
public string blogid;
/// <summary>
///
/// </summary>
public string url;
/// <summary>
///
/// </summary>
public string blogName;
}
/// <summary>
///
/// </summary>
public interface IBlogger
{
/// <summary>
///
/// </summary>
/// <param name="appKey"></param>
/// <param name="postid"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="publish"></param>
/// <returns></returns>
[XmlRpcMethod("blogger.deletePost",
Description="Deletes a post.")]
[return: XmlRpcReturnValue(Description="Always returns true.")]
bool blogger_deletePost(
string appKey,
string postid,
string username,
string password,
[XmlRpcParameter(
Description="Where applicable, this specifies whether the blog "
+ "should be republished after the post has been deleted.")]
bool publish);
/// <summary>
///
/// </summary>
/// <param name="appKey"></param>
/// <param name="postid"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="content"></param>
/// <param name="publish"></param>
/// <returns></returns>
[XmlRpcMethod("blogger.editPost",
Description="Edits a given post. Optionally, will publish the "
+ "blog after making the edit.")]
[return: XmlRpcReturnValue(Description="Always returns true.")]
bool blogger_editPost(
string appKey,
string postid,
string username,
string password,
string content,
bool publish);
/// <summary>
///
/// </summary>
/// <param name="blogid"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
[XmlRpcMethod("blogger.getCategories",
Description="Returns a list of the categories that you can use "
+ "to log against a post.")]
Category[] blogger_getCategories(
string blogid,
string username,
string password);
/// <summary>
///
/// </summary>
/// <param name="appKey"></param>
/// <param name="postid"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
[XmlRpcMethod("blogger.getPost",
Description="Returns a single post.")]
Post blogger_getPost(
string appKey,
string postid,
string username,
string password);
/// <summary>
///
/// </summary>
/// <param name="appKey"></param>
/// <param name="blogid"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="numberOfPosts"></param>
/// <returns></returns>
[XmlRpcMethod("blogger.getRecentPosts",
Description="Returns a list of the most recent posts in the system.")]
Post[] blogger_getRecentPosts(
string appKey,
string blogid,
string username,
string password,
int numberOfPosts);
/// <summary>
///
/// </summary>
/// <param name="appKey"></param>
/// <param name="blogid"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="templateType"></param>
/// <returns></returns>
[XmlRpcMethod("blogger.getTemplate",
Description="Returns the main or archive index template of "
+ "a given blog.")]
string blogger_getTemplate(
string appKey,
string blogid,
string username,
string password,
string templateType);
/// <summary>
///
/// </summary>
/// <param name="appKey"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
[XmlRpcMethod("blogger.getUserInfo",
Description="Authenticates a user and returns basic user info "
+ "(name, email, userid, etc.).")]
UserInfo blogger_getUserInfo(
string appKey,
string username,
string password);
/// <summary>
///
/// </summary>
/// <param name="appKey"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
[XmlRpcMethod("blogger.getUsersBlogs",
Description="Returns information on all the blogs a given user "
+ "is a member.")]
BlogInfo[] blogger_getUsersBlogs(
string appKey,
string username,
string password);
/// <summary>
///
/// </summary>
/// <param name="appKey"></param>
/// <param name="blogid"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="content"></param>
/// <param name="publish"></param>
/// <returns></returns>
[XmlRpcMethod("blogger.newPost",
Description="Makes a new post to a designated blog. Optionally, "
+ "will publish the blog after making the post.")]
[return: XmlRpcReturnValue(Description="Id of new post")]
string blogger_newPost(
string appKey,
string blogid,
string username,
string password,
string content,
bool publish);
/// <summary>
///
/// </summary>
/// <param name="appKey"></param>
/// <param name="blogid"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="template"></param>
/// <param name="templateType"></param>
/// <returns></returns>
[XmlRpcMethod("blogger.setTemplate",
Description="Edits the main or archive index template of a given blog.")]
bool blogger_setTemplate(
string appKey,
string blogid,
string username,
string password,
string template,
string templateType);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Memory;
using Apache.Ignite.Core.Impl.Unmanaged;
using Apache.Ignite.Core.Interop;
using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader;
using BinaryWriter = Apache.Ignite.Core.Impl.Binary.BinaryWriter;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// Base class for interop targets.
/// </summary>
[SuppressMessage("ReSharper", "LocalVariableHidesMember")]
internal class PlatformTarget : IPlatformTarget
{
/** */
protected const int False = 0;
/** */
protected const int True = 1;
/** */
protected const int Error = -1;
/** */
public const int OpNone = -2;
/** */
private static readonly Dictionary<Type, FutureType> IgniteFutureTypeMap
= new Dictionary<Type, FutureType>
{
{typeof(bool), FutureType.Bool},
{typeof(byte), FutureType.Byte},
{typeof(char), FutureType.Char},
{typeof(double), FutureType.Double},
{typeof(float), FutureType.Float},
{typeof(int), FutureType.Int},
{typeof(long), FutureType.Long},
{typeof(short), FutureType.Short}
};
/** Unmanaged target. */
private readonly IUnmanagedTarget _target;
/** Marshaller. */
private readonly Marshaller _marsh;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="marsh">Marshaller.</param>
public PlatformTarget(IUnmanagedTarget target, Marshaller marsh)
{
Debug.Assert(target != null);
Debug.Assert(marsh != null);
_target = target;
_marsh = marsh;
}
/// <summary>
/// Unmanaged target.
/// </summary>
internal IUnmanagedTarget Target
{
get { return _target; }
}
/// <summary>
/// Marshaller.
/// </summary>
internal Marshaller Marshaller
{
get { return _marsh; }
}
#region Static Helpers
/// <summary>
/// Write collection.
/// </summary>
/// <param name="writer">Writer.</param>
/// <param name="vals">Values.</param>
/// <returns>The same writer for chaining.</returns>
protected static BinaryWriter WriteCollection<T>(BinaryWriter writer, ICollection<T> vals)
{
return WriteCollection<T, T>(writer, vals, null);
}
/// <summary>
/// Write nullable collection.
/// </summary>
/// <param name="writer">Writer.</param>
/// <param name="vals">Values.</param>
/// <returns>The same writer for chaining.</returns>
protected static BinaryWriter WriteNullableCollection<T>(BinaryWriter writer, ICollection<T> vals)
{
return WriteNullable(writer, vals, WriteCollection);
}
/// <summary>
/// Write collection.
/// </summary>
/// <param name="writer">Writer.</param>
/// <param name="vals">Values.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The same writer for chaining.</returns>
protected static BinaryWriter WriteCollection<T1, T2>(BinaryWriter writer,
ICollection<T1> vals, Func<T1, T2> selector)
{
writer.WriteInt(vals.Count);
if (selector == null)
{
foreach (var val in vals)
writer.Write(val);
}
else
{
foreach (var val in vals)
writer.Write(selector(val));
}
return writer;
}
/// <summary>
/// Write enumerable.
/// </summary>
/// <param name="writer">Writer.</param>
/// <param name="vals">Values.</param>
/// <returns>The same writer for chaining.</returns>
protected static BinaryWriter WriteEnumerable<T>(BinaryWriter writer, IEnumerable<T> vals)
{
return WriteEnumerable<T, T>(writer, vals, null);
}
/// <summary>
/// Write enumerable.
/// </summary>
/// <param name="writer">Writer.</param>
/// <param name="vals">Values.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The same writer for chaining.</returns>
protected static BinaryWriter WriteEnumerable<T1, T2>(BinaryWriter writer,
IEnumerable<T1> vals, Func<T1, T2> selector)
{
var col = vals as ICollection<T1>;
if (col != null)
return WriteCollection(writer, col, selector);
var stream = writer.Stream;
var pos = stream.Position;
stream.Seek(4, SeekOrigin.Current);
var size = 0;
if (selector == null)
{
foreach (var val in vals)
{
writer.Write(val);
size++;
}
}
else
{
foreach (var val in vals)
{
writer.Write(selector(val));
size++;
}
}
stream.WriteInt(pos, size);
return writer;
}
/// <summary>
/// Write dictionary.
/// </summary>
/// <param name="writer">Writer.</param>
/// <param name="vals">Values.</param>
protected static void WriteDictionary<T1, T2>(BinaryWriter writer, IEnumerable<KeyValuePair<T1, T2>> vals)
{
var pos = writer.Stream.Position;
writer.WriteInt(0); // Reserve count.
int cnt = 0;
foreach (var pair in vals)
{
writer.Write(pair.Key);
writer.Write(pair.Value);
cnt++;
}
writer.Stream.WriteInt(pos, cnt);
}
/// <summary>
/// Write a nullable item.
/// </summary>
/// <param name="writer">Writer.</param>
/// <param name="item">Item.</param>
/// <param name="writeItem">Write action to perform on item when it is not null.</param>
/// <returns>The same writer for chaining.</returns>
private static BinaryWriter WriteNullable<T>(BinaryWriter writer, T item,
Func<BinaryWriter, T, BinaryWriter> writeItem) where T : class
{
if (item == null)
{
writer.WriteBoolean(false);
return writer;
}
writer.WriteBoolean(true);
return writeItem(writer, item);
}
#endregion
#region OUT operations
/// <summary>
/// Perform out operation.
/// </summary>
/// <param name="type">Operation type.</param>
/// <param name="action">Action to be performed on the stream.</param>
/// <returns></returns>
protected long DoOutOp(int type, Action<IBinaryStream> action)
{
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
action(stream);
return UU.TargetInStreamOutLong(_target, type, stream.SynchronizeOutput());
}
}
/// <summary>
/// Perform out operation.
/// </summary>
/// <param name="type">Operation type.</param>
/// <param name="action">Action to be performed on the stream.</param>
/// <returns></returns>
protected long DoOutOp(int type, Action<BinaryWriter> action)
{
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
var writer = _marsh.StartMarshal(stream);
action(writer);
FinishMarshal(writer);
return UU.TargetInStreamOutLong(_target, type, stream.SynchronizeOutput());
}
}
/// <summary>
/// Perform out operation.
/// </summary>
/// <param name="type">Operation type.</param>
/// <param name="action">Action to be performed on the stream.</param>
/// <returns></returns>
protected IUnmanagedTarget DoOutOpObject(int type, Action<BinaryWriter> action)
{
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
var writer = _marsh.StartMarshal(stream);
action(writer);
FinishMarshal(writer);
return UU.TargetInStreamOutObject(_target, type, stream.SynchronizeOutput());
}
}
/// <summary>
/// Perform out operation.
/// </summary>
/// <param name="type">Operation type.</param>
/// <returns>Resulting object.</returns>
protected IUnmanagedTarget DoOutOpObject(int type)
{
return UU.TargetOutObject(_target, type);
}
/// <summary>
/// Perform simple output operation accepting single argument.
/// </summary>
/// <param name="type">Operation type.</param>
/// <param name="val1">Value.</param>
/// <returns>Result.</returns>
protected long DoOutOp<T1>(int type, T1 val1)
{
return DoOutOp(type, writer =>
{
writer.Write(val1);
});
}
/// <summary>
/// Perform simple output operation accepting two arguments.
/// </summary>
/// <param name="type">Operation type.</param>
/// <param name="val1">Value 1.</param>
/// <param name="val2">Value 2.</param>
/// <returns>Result.</returns>
protected long DoOutOp<T1, T2>(int type, T1 val1, T2 val2)
{
return DoOutOp(type, writer =>
{
writer.Write(val1);
writer.Write(val2);
});
}
/// <summary>
/// Perform simple output operation accepting three arguments.
/// </summary>
/// <param name="type">Operation type.</param>
/// <param name="val1">Value 1.</param>
/// <param name="val2">Value 2.</param>
/// <param name="val3">Value 3.</param>
/// <returns>Result.</returns>
protected long DoOutOp<T1, T2, T3>(int type, T1 val1, T2 val2, T3 val3)
{
return DoOutOp(type, writer =>
{
writer.Write(val1);
writer.Write(val2);
writer.Write(val3);
});
}
#endregion
#region IN operations
/// <summary>
/// Perform in operation.
/// </summary>
/// <param name="type">Type.</param>
/// <param name="action">Action.</param>
protected void DoInOp(int type, Action<IBinaryStream> action)
{
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
UU.TargetOutStream(_target, type, stream.MemoryPointer);
stream.SynchronizeInput();
action(stream);
}
}
/// <summary>
/// Perform in operation.
/// </summary>
/// <param name="type">Type.</param>
/// <param name="action">Action.</param>
/// <returns>Result.</returns>
protected T DoInOp<T>(int type, Func<IBinaryStream, T> action)
{
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
UU.TargetOutStream(_target, type, stream.MemoryPointer);
stream.SynchronizeInput();
return action(stream);
}
}
/// <summary>
/// Perform simple in operation returning immediate result.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Result.</returns>
protected T DoInOp<T>(int type)
{
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
UU.TargetOutStream(_target, type, stream.MemoryPointer);
stream.SynchronizeInput();
return Unmarshal<T>(stream);
}
}
#endregion
#region OUT-IN operations
/// <summary>
/// Perform out-in operation.
/// </summary>
/// <param name="type">Operation type.</param>
/// <param name="outAction">Out action.</param>
/// <param name="inAction">In action.</param>
protected void DoOutInOp(int type, Action<BinaryWriter> outAction, Action<IBinaryStream> inAction)
{
using (PlatformMemoryStream outStream = IgniteManager.Memory.Allocate().GetStream())
{
using (PlatformMemoryStream inStream = IgniteManager.Memory.Allocate().GetStream())
{
BinaryWriter writer = _marsh.StartMarshal(outStream);
outAction(writer);
FinishMarshal(writer);
UU.TargetInStreamOutStream(_target, type, outStream.SynchronizeOutput(), inStream.MemoryPointer);
inStream.SynchronizeInput();
inAction(inStream);
}
}
}
/// <summary>
/// Perform out-in operation.
/// </summary>
/// <param name="type">Operation type.</param>
/// <param name="outAction">Out action.</param>
/// <param name="inAction">In action.</param>
/// <returns>Result.</returns>
protected TR DoOutInOp<TR>(int type, Action<BinaryWriter> outAction, Func<IBinaryStream, TR> inAction)
{
using (PlatformMemoryStream outStream = IgniteManager.Memory.Allocate().GetStream())
{
using (PlatformMemoryStream inStream = IgniteManager.Memory.Allocate().GetStream())
{
BinaryWriter writer = _marsh.StartMarshal(outStream);
outAction(writer);
FinishMarshal(writer);
UU.TargetInStreamOutStream(_target, type, outStream.SynchronizeOutput(), inStream.MemoryPointer);
inStream.SynchronizeInput();
return inAction(inStream);
}
}
}
/// <summary>
/// Perform out-in operation with a single stream.
/// </summary>
/// <typeparam name="TR">The type of the r.</typeparam>
/// <param name="type">Operation type.</param>
/// <param name="outAction">Out action.</param>
/// <param name="inAction">In action.</param>
/// <param name="inErrorAction">The action to read an error.</param>
/// <returns>
/// Result.
/// </returns>
protected TR DoOutInOpX<TR>(int type, Action<BinaryWriter> outAction, Func<IBinaryStream, long, TR> inAction,
Func<IBinaryStream, Exception> inErrorAction)
{
Debug.Assert(inErrorAction != null);
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
var writer = _marsh.StartMarshal(stream);
outAction(writer);
FinishMarshal(writer);
var res = UU.TargetInStreamOutLong(_target, type, stream.SynchronizeOutput());
if (res != Error && inAction == null)
return default(TR); // quick path for void operations
stream.SynchronizeInput();
stream.Seek(0, SeekOrigin.Begin);
if (res != Error)
return inAction != null ? inAction(stream, res) : default(TR);
throw inErrorAction(stream);
}
}
/// <summary>
/// Perform out-in operation with a single stream.
/// </summary>
/// <param name="type">Operation type.</param>
/// <param name="outAction">Out action.</param>
/// <param name="inErrorAction">The action to read an error.</param>
/// <returns>
/// Result.
/// </returns>
protected bool DoOutInOpX(int type, Action<BinaryWriter> outAction,
Func<IBinaryStream, Exception> inErrorAction)
{
Debug.Assert(inErrorAction != null);
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
var writer = _marsh.StartMarshal(stream);
outAction(writer);
FinishMarshal(writer);
var res = UU.TargetInStreamOutLong(_target, type, stream.SynchronizeOutput());
if (res != Error)
return res == True;
stream.SynchronizeInput();
stream.Seek(0, SeekOrigin.Begin);
throw inErrorAction(stream);
}
}
/// <summary>
/// Perform out-in operation.
/// </summary>
/// <param name="type">Operation type.</param>
/// <param name="outAction">Out action.</param>
/// <param name="inAction">In action.</param>
/// <param name="arg">Argument.</param>
/// <returns>Result.</returns>
protected unsafe TR DoOutInOp<TR>(int type, Action<BinaryWriter> outAction,
Func<IBinaryStream, IUnmanagedTarget, TR> inAction, void* arg)
{
PlatformMemoryStream outStream = null;
long outPtr = 0;
PlatformMemoryStream inStream = null;
long inPtr = 0;
try
{
if (outAction != null)
{
outStream = IgniteManager.Memory.Allocate().GetStream();
var writer = _marsh.StartMarshal(outStream);
outAction(writer);
FinishMarshal(writer);
outPtr = outStream.SynchronizeOutput();
}
if (inAction != null)
{
inStream = IgniteManager.Memory.Allocate().GetStream();
inPtr = inStream.MemoryPointer;
}
var res = UU.TargetInObjectStreamOutObjectStream(_target, type, arg, outPtr, inPtr);
if (inAction == null)
return default(TR);
inStream.SynchronizeInput();
return inAction(inStream, res);
}
finally
{
try
{
if (inStream != null)
inStream.Dispose();
}
finally
{
if (outStream != null)
outStream.Dispose();
}
}
}
/// <summary>
/// Perform out-in operation.
/// </summary>
/// <param name="type">Operation type.</param>
/// <param name="outAction">Out action.</param>
/// <returns>Result.</returns>
protected TR DoOutInOp<TR>(int type, Action<BinaryWriter> outAction)
{
using (PlatformMemoryStream outStream = IgniteManager.Memory.Allocate().GetStream())
{
using (PlatformMemoryStream inStream = IgniteManager.Memory.Allocate().GetStream())
{
BinaryWriter writer = _marsh.StartMarshal(outStream);
outAction(writer);
FinishMarshal(writer);
UU.TargetInStreamOutStream(_target, type, outStream.SynchronizeOutput(), inStream.MemoryPointer);
inStream.SynchronizeInput();
return Unmarshal<TR>(inStream);
}
}
}
/// <summary>
/// Perform simple out-in operation accepting single argument.
/// </summary>
/// <param name="type">Operation type.</param>
/// <param name="val">Value.</param>
/// <returns>Result.</returns>
protected TR DoOutInOp<T1, TR>(int type, T1 val)
{
using (PlatformMemoryStream outStream = IgniteManager.Memory.Allocate().GetStream())
{
using (PlatformMemoryStream inStream = IgniteManager.Memory.Allocate().GetStream())
{
BinaryWriter writer = _marsh.StartMarshal(outStream);
writer.WriteObject(val);
FinishMarshal(writer);
UU.TargetInStreamOutStream(_target, type, outStream.SynchronizeOutput(), inStream.MemoryPointer);
inStream.SynchronizeInput();
return Unmarshal<TR>(inStream);
}
}
}
/// <summary>
/// Perform simple out-in operation accepting two arguments.
/// </summary>
/// <param name="type">Operation type.</param>
/// <param name="val1">Value.</param>
/// <param name="val2">Value.</param>
/// <returns>Result.</returns>
protected TR DoOutInOp<T1, T2, TR>(int type, T1 val1, T2 val2)
{
using (PlatformMemoryStream outStream = IgniteManager.Memory.Allocate().GetStream())
{
using (PlatformMemoryStream inStream = IgniteManager.Memory.Allocate().GetStream())
{
BinaryWriter writer = _marsh.StartMarshal(outStream);
writer.WriteObject(val1);
writer.WriteObject(val2);
FinishMarshal(writer);
UU.TargetInStreamOutStream(_target, type, outStream.SynchronizeOutput(), inStream.MemoryPointer);
inStream.SynchronizeInput();
return Unmarshal<TR>(inStream);
}
}
}
/// <summary>
/// Perform simple out-in operation accepting two arguments.
/// </summary>
/// <param name="type">Operation type.</param>
/// <param name="val">Value.</param>
/// <returns>Result.</returns>
protected long DoOutInOp(int type, long val = 0)
{
return UU.TargetInLongOutLong(_target, type, val);
}
#endregion
#region Async operations
/// <summary>
/// Performs async operation.
/// </summary>
/// <param name="type">The type code.</param>
/// <param name="writeAction">The write action.</param>
/// <returns>Task for async operation</returns>
protected Task DoOutOpAsync(int type, Action<BinaryWriter> writeAction = null)
{
return DoOutOpAsync<object>(type, writeAction);
}
/// <summary>
/// Performs async operation.
/// </summary>
/// <typeparam name="T">Type of the result.</typeparam>
/// <param name="type">The type code.</param>
/// <param name="writeAction">The write action.</param>
/// <param name="keepBinary">Keep binary flag, only applicable to object futures. False by default.</param>
/// <param name="convertFunc">The function to read future result from stream.</param>
/// <returns>Task for async operation</returns>
protected Task<T> DoOutOpAsync<T>(int type, Action<BinaryWriter> writeAction = null, bool keepBinary = false,
Func<BinaryReader, T> convertFunc = null)
{
return GetFuture((futId, futType) => DoOutOp(type, w =>
{
if (writeAction != null)
writeAction(w);
w.WriteLong(futId);
w.WriteInt(futType);
}), keepBinary, convertFunc).Task;
}
/// <summary>
/// Performs async operation.
/// </summary>
/// <typeparam name="T">Type of the result.</typeparam>
/// <param name="type">The type code.</param>
/// <param name="writeAction">The write action.</param>
/// <returns>Future for async operation</returns>
protected Future<T> DoOutOpObjectAsync<T>(int type, Action<IBinaryRawWriter> writeAction)
{
return GetFuture<T>((futId, futType) => DoOutOpObject(type, w =>
{
writeAction(w);
w.WriteLong(futId);
w.WriteInt(futType);
}));
}
/// <summary>
/// Performs async operation.
/// </summary>
/// <typeparam name="TR">Type of the result.</typeparam>
/// <typeparam name="T1">The type of the first arg.</typeparam>
/// <param name="type">The type code.</param>
/// <param name="val1">First arg.</param>
/// <returns>
/// Task for async operation
/// </returns>
protected Task<TR> DoOutOpAsync<T1, TR>(int type, T1 val1)
{
return GetFuture<TR>((futId, futType) => DoOutOp(type, w =>
{
w.WriteObject(val1);
w.WriteLong(futId);
w.WriteInt(futType);
})).Task;
}
/// <summary>
/// Performs async operation.
/// </summary>
/// <typeparam name="TR">Type of the result.</typeparam>
/// <typeparam name="T1">The type of the first arg.</typeparam>
/// <typeparam name="T2">The type of the second arg.</typeparam>
/// <param name="type">The type code.</param>
/// <param name="val1">First arg.</param>
/// <param name="val2">Second arg.</param>
/// <returns>
/// Task for async operation
/// </returns>
protected Task<TR> DoOutOpAsync<T1, T2, TR>(int type, T1 val1, T2 val2)
{
return GetFuture<TR>((futId, futType) => DoOutOp(type, w =>
{
w.WriteObject(val1);
w.WriteObject(val2);
w.WriteLong(futId);
w.WriteInt(futType);
})).Task;
}
#endregion
#region Miscelanneous
/// <summary>
/// Finish marshaling.
/// </summary>
/// <param name="writer">Writer.</param>
internal void FinishMarshal(BinaryWriter writer)
{
_marsh.FinishMarshal(writer);
}
/// <summary>
/// Unmarshal object using the given stream.
/// </summary>
/// <param name="stream">Stream.</param>
/// <returns>Unmarshalled object.</returns>
protected virtual T Unmarshal<T>(IBinaryStream stream)
{
return _marsh.Unmarshal<T>(stream);
}
/// <summary>
/// Creates a future and starts listening.
/// </summary>
/// <typeparam name="T">Future result type</typeparam>
/// <param name="listenAction">The listen action.</param>
/// <param name="keepBinary">Keep binary flag, only applicable to object futures. False by default.</param>
/// <param name="convertFunc">The function to read future result from stream.</param>
/// <returns>Created future.</returns>
private Future<T> GetFuture<T>(Func<long, int, IUnmanagedTarget> listenAction, bool keepBinary = false,
Func<BinaryReader, T> convertFunc = null)
{
var futType = FutureType.Object;
var type = typeof(T);
if (type.IsPrimitive)
IgniteFutureTypeMap.TryGetValue(type, out futType);
var fut = convertFunc == null && futType != FutureType.Object
? new Future<T>()
: new Future<T>(new FutureConverter<T>(_marsh, keepBinary, convertFunc));
var futHnd = _marsh.Ignite.HandleRegistry.Allocate(fut);
IUnmanagedTarget futTarget;
try
{
futTarget = listenAction(futHnd, (int)futType);
}
catch (Exception)
{
_marsh.Ignite.HandleRegistry.Release(futHnd);
throw;
}
fut.SetTarget(new Listenable(futTarget, _marsh));
return fut;
}
/// <summary>
/// Creates a future and starts listening.
/// </summary>
/// <typeparam name="T">Future result type</typeparam>
/// <param name="listenAction">The listen action.</param>
/// <param name="keepBinary">Keep binary flag, only applicable to object futures. False by default.</param>
/// <param name="convertFunc">The function to read future result from stream.</param>
/// <returns>Created future.</returns>
protected Future<T> GetFuture<T>(Action<long, int> listenAction, bool keepBinary = false,
Func<BinaryReader, T> convertFunc = null)
{
var futType = FutureType.Object;
var type = typeof(T);
if (type.IsPrimitive)
IgniteFutureTypeMap.TryGetValue(type, out futType);
var fut = convertFunc == null && futType != FutureType.Object
? new Future<T>()
: new Future<T>(new FutureConverter<T>(_marsh, keepBinary, convertFunc));
var futHnd = _marsh.Ignite.HandleRegistry.Allocate(fut);
try
{
listenAction(futHnd, (int)futType);
}
catch (Exception)
{
_marsh.Ignite.HandleRegistry.Release(futHnd);
throw;
}
return fut;
}
#endregion
#region IPlatformTarget
/** <inheritdoc /> */
public long InLongOutLong(int type, long val)
{
return DoOutInOp(type, val);
}
/** <inheritdoc /> */
public long InStreamOutLong(int type, Action<IBinaryRawWriter> writeAction)
{
return DoOutOp(type, writer => writeAction(writer));
}
/** <inheritdoc /> */
public T InStreamOutStream<T>(int type, Action<IBinaryRawWriter> writeAction,
Func<IBinaryRawReader, T> readAction)
{
return DoOutInOp(type, writeAction, stream => readAction(Marshaller.StartUnmarshal(stream)));
}
/** <inheritdoc /> */
public IPlatformTarget InStreamOutObject(int type, Action<IBinaryRawWriter> writeAction)
{
return GetPlatformTarget(DoOutOpObject(type, writeAction));
}
/** <inheritdoc /> */
public unsafe T InObjectStreamOutObjectStream<T>(int type, IPlatformTarget arg, Action<IBinaryRawWriter> writeAction,
Func<IBinaryRawReader, IPlatformTarget, T> readAction)
{
return DoOutInOp(type, writeAction, (stream, obj) => readAction(Marshaller.StartUnmarshal(stream),
GetPlatformTarget(obj)), GetTargetPtr(arg));
}
/** <inheritdoc /> */
public T OutStream<T>(int type, Func<IBinaryRawReader, T> readAction)
{
return DoInOp(type, stream => readAction(Marshaller.StartUnmarshal(stream)));
}
/** <inheritdoc /> */
public IPlatformTarget OutObject(int type)
{
return GetPlatformTarget(DoOutOpObject(type));
}
/** <inheritdoc /> */
public Task<T> DoOutOpAsync<T>(int type, Action<IBinaryRawWriter> writeAction = null,
Func<IBinaryRawReader, T> readAction = null)
{
var convertFunc = readAction != null
? r => readAction(r)
: (Func<BinaryReader, T>) null;
return GetFuture((futId, futType) =>
{
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
stream.WriteLong(futId);
stream.WriteInt(futType);
if (writeAction != null)
{
var writer = _marsh.StartMarshal(stream);
writeAction(writer);
FinishMarshal(writer);
}
UU.TargetInStreamAsync(_target, type, stream.SynchronizeOutput());
}
}, false, convertFunc).Task;
}
/// <summary>
/// Gets the platform target.
/// </summary>
private IPlatformTarget GetPlatformTarget(IUnmanagedTarget target)
{
return target == null ? null : new PlatformTarget(target, Marshaller);
}
/// <summary>
/// Gets the target pointer.
/// </summary>
private static unsafe void* GetTargetPtr(IPlatformTarget target)
{
return target == null ? null : ((PlatformTarget) target).Target.Target;
}
#endregion
}
/// <summary>
/// PlatformTarget with IDisposable pattern.
/// </summary>
internal abstract class PlatformDisposableTarget : PlatformTarget, IDisposable
{
/** Disposed flag. */
private volatile bool _disposed;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="marsh">Marshaller.</param>
protected PlatformDisposableTarget(IUnmanagedTarget target, Marshaller marsh) : base(target, marsh)
{
// No-op.
}
/** <inheritdoc /> */
public void Dispose()
{
lock (this)
{
if (_disposed)
return;
Dispose(true);
GC.SuppressFinalize(this);
_disposed = true;
}
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing">
/// <c>true</c> when called from Dispose; <c>false</c> when called from finalizer.
/// </param>
protected virtual void Dispose(bool disposing)
{
Target.Dispose();
}
/// <summary>
/// Throws <see cref="ObjectDisposedException"/> if this instance has been disposed.
/// </summary>
protected void ThrowIfDisposed()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name, "Object has been disposed.");
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters;
using Newtonsoft.Json4.Converters;
using Newtonsoft.Json4.Serialization;
using Newtonsoft.Json4.Utilities;
using System.Runtime.Serialization;
using ErrorEventArgs=Newtonsoft.Json4.Serialization.ErrorEventArgs;
namespace Newtonsoft.Json4
{
/// <summary>
/// Serializes and deserializes objects into and from the JSON format.
/// The <see cref="JsonSerializer"/> enables you to control how objects are encoded into JSON.
/// </summary>
public class JsonSerializer
{
#region Properties
private TypeNameHandling _typeNameHandling;
private FormatterAssemblyStyle _typeNameAssemblyFormat;
private PreserveReferencesHandling _preserveReferencesHandling;
private ReferenceLoopHandling _referenceLoopHandling;
private MissingMemberHandling _missingMemberHandling;
private ObjectCreationHandling _objectCreationHandling;
private NullValueHandling _nullValueHandling;
private DefaultValueHandling _defaultValueHandling;
private ConstructorHandling _constructorHandling;
private JsonConverterCollection _converters;
private IContractResolver _contractResolver;
private IReferenceResolver _referenceResolver;
private SerializationBinder _binder;
private StreamingContext _context;
/// <summary>
/// Occurs when the <see cref="JsonSerializer"/> errors during serialization and deserialization.
/// </summary>
public virtual event EventHandler<ErrorEventArgs> Error;
/// <summary>
/// Gets or sets the <see cref="IReferenceResolver"/> used by the serializer when resolving references.
/// </summary>
public virtual IReferenceResolver ReferenceResolver
{
get
{
if (_referenceResolver == null)
_referenceResolver = new DefaultReferenceResolver();
return _referenceResolver;
}
set
{
if (value == null)
throw new ArgumentNullException("value", "Reference resolver cannot be null.");
_referenceResolver = value;
}
}
/// <summary>
/// Gets or sets the <see cref="SerializationBinder"/> used by the serializer when resolving type names.
/// </summary>
public virtual SerializationBinder Binder
{
get
{
return _binder;
}
set
{
if (value == null)
throw new ArgumentNullException("value", "Serialization binder cannot be null.");
_binder = value;
}
}
/// <summary>
/// Gets or sets how type name writing and reading is handled by the serializer.
/// </summary>
public virtual TypeNameHandling TypeNameHandling
{
get { return _typeNameHandling; }
set
{
if (value < TypeNameHandling.None || value > TypeNameHandling.Auto)
throw new ArgumentOutOfRangeException("value");
_typeNameHandling = value;
}
}
/// <summary>
/// Gets or sets how a type name assembly is written and resolved by the serializer.
/// </summary>
/// <value>The type name assembly format.</value>
public virtual FormatterAssemblyStyle TypeNameAssemblyFormat
{
get { return _typeNameAssemblyFormat; }
set
{
if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full)
throw new ArgumentOutOfRangeException("value");
_typeNameAssemblyFormat = value;
}
}
/// <summary>
/// Gets or sets how object references are preserved by the serializer.
/// </summary>
public virtual PreserveReferencesHandling PreserveReferencesHandling
{
get { return _preserveReferencesHandling; }
set
{
if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All)
throw new ArgumentOutOfRangeException("value");
_preserveReferencesHandling = value;
}
}
/// <summary>
/// Get or set how reference loops (e.g. a class referencing itself) is handled.
/// </summary>
public virtual ReferenceLoopHandling ReferenceLoopHandling
{
get { return _referenceLoopHandling; }
set
{
if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize)
throw new ArgumentOutOfRangeException("value");
_referenceLoopHandling = value;
}
}
/// <summary>
/// Get or set how missing members (e.g. JSON contains a property that isn't a member on the object) are handled during deserialization.
/// </summary>
public virtual MissingMemberHandling MissingMemberHandling
{
get { return _missingMemberHandling; }
set
{
if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error)
throw new ArgumentOutOfRangeException("value");
_missingMemberHandling = value;
}
}
/// <summary>
/// Get or set how null values are handled during serialization and deserialization.
/// </summary>
public virtual NullValueHandling NullValueHandling
{
get { return _nullValueHandling; }
set
{
if (value < NullValueHandling.Include || value > NullValueHandling.Ignore)
throw new ArgumentOutOfRangeException("value");
_nullValueHandling = value;
}
}
/// <summary>
/// Get or set how null default are handled during serialization and deserialization.
/// </summary>
public virtual DefaultValueHandling DefaultValueHandling
{
get { return _defaultValueHandling; }
set
{
if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate)
throw new ArgumentOutOfRangeException("value");
_defaultValueHandling = value;
}
}
/// <summary>
/// Gets or sets how objects are created during deserialization.
/// </summary>
/// <value>The object creation handling.</value>
public virtual ObjectCreationHandling ObjectCreationHandling
{
get { return _objectCreationHandling; }
set
{
if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace)
throw new ArgumentOutOfRangeException("value");
_objectCreationHandling = value;
}
}
/// <summary>
/// Gets or sets how constructors are used during deserialization.
/// </summary>
/// <value>The constructor handling.</value>
public virtual ConstructorHandling ConstructorHandling
{
get { return _constructorHandling; }
set
{
if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor)
throw new ArgumentOutOfRangeException("value");
_constructorHandling = value;
}
}
/// <summary>
/// Gets a collection <see cref="JsonConverter"/> that will be used during serialization.
/// </summary>
/// <value>Collection <see cref="JsonConverter"/> that will be used during serialization.</value>
public virtual JsonConverterCollection Converters
{
get
{
if (_converters == null)
_converters = new JsonConverterCollection();
return _converters;
}
}
/// <summary>
/// Gets or sets the contract resolver used by the serializer when
/// serializing .NET objects to JSON and vice versa.
/// </summary>
public virtual IContractResolver ContractResolver
{
get
{
if (_contractResolver == null)
_contractResolver = DefaultContractResolver.Instance;
return _contractResolver;
}
set { _contractResolver = value; }
}
/// <summary>
/// Gets or sets the <see cref="StreamingContext"/> used by the serializer when invoking serialization callback methods.
/// </summary>
/// <value>The context.</value>
public virtual StreamingContext Context
{
get { return _context; }
set { _context = value; }
}
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializer"/> class.
/// </summary>
public JsonSerializer()
{
_referenceLoopHandling = JsonSerializerSettings.DefaultReferenceLoopHandling;
_missingMemberHandling = JsonSerializerSettings.DefaultMissingMemberHandling;
_nullValueHandling = JsonSerializerSettings.DefaultNullValueHandling;
_defaultValueHandling = JsonSerializerSettings.DefaultDefaultValueHandling;
_objectCreationHandling = JsonSerializerSettings.DefaultObjectCreationHandling;
_preserveReferencesHandling = JsonSerializerSettings.DefaultPreserveReferencesHandling;
_constructorHandling = JsonSerializerSettings.DefaultConstructorHandling;
_typeNameHandling = JsonSerializerSettings.DefaultTypeNameHandling;
_context = JsonSerializerSettings.DefaultContext;
_binder = DefaultSerializationBinder.Instance;
}
/// <summary>
/// Creates a new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="settings">The settings to be applied to the <see cref="JsonSerializer"/>.</param>
/// <returns>A new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>.</returns>
public static JsonSerializer Create(JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = new JsonSerializer();
if (settings != null)
{
if (!CollectionUtils.IsNullOrEmpty(settings.Converters))
jsonSerializer.Converters.AddRange(settings.Converters);
jsonSerializer.TypeNameHandling = settings.TypeNameHandling;
jsonSerializer.TypeNameAssemblyFormat = settings.TypeNameAssemblyFormat;
jsonSerializer.PreserveReferencesHandling = settings.PreserveReferencesHandling;
jsonSerializer.ReferenceLoopHandling = settings.ReferenceLoopHandling;
jsonSerializer.MissingMemberHandling = settings.MissingMemberHandling;
jsonSerializer.ObjectCreationHandling = settings.ObjectCreationHandling;
jsonSerializer.NullValueHandling = settings.NullValueHandling;
jsonSerializer.DefaultValueHandling = settings.DefaultValueHandling;
jsonSerializer.ConstructorHandling = settings.ConstructorHandling;
jsonSerializer.Context = settings.Context;
if (settings.Error != null)
jsonSerializer.Error += settings.Error;
if (settings.ContractResolver != null)
jsonSerializer.ContractResolver = settings.ContractResolver;
if (settings.ReferenceResolver != null)
jsonSerializer.ReferenceResolver = settings.ReferenceResolver;
if (settings.Binder != null)
jsonSerializer.Binder = settings.Binder;
}
return jsonSerializer;
}
/// <summary>
/// Populates the JSON values onto the target object.
/// </summary>
/// <param name="reader">The <see cref="TextReader"/> that contains the JSON structure to reader values from.</param>
/// <param name="target">The target object to populate values onto.</param>
public void Populate(TextReader reader, object target)
{
Populate(new JsonTextReader(reader), target);
}
/// <summary>
/// Populates the JSON values onto the target object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to reader values from.</param>
/// <param name="target">The target object to populate values onto.</param>
public void Populate(JsonReader reader, object target)
{
PopulateInternal(reader, target);
}
internal virtual void PopulateInternal(JsonReader reader, object target)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
ValidationUtils.ArgumentNotNull(target, "target");
JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this);
serializerReader.Populate(reader, target);
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to deserialize.</param>
/// <returns>The <see cref="Object"/> being deserialized.</returns>
public object Deserialize(JsonReader reader)
{
return Deserialize(reader, null);
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="StringReader"/>
/// into an instance of the specified type.
/// </summary>
/// <param name="reader">The <see cref="TextReader"/> containing the object.</param>
/// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns>
public object Deserialize(TextReader reader, Type objectType)
{
return Deserialize(new JsonTextReader(reader), objectType);
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>
/// into an instance of the specified type.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> containing the object.</param>
/// <typeparam name="T">The type of the object to deserialize.</typeparam>
/// <returns>The instance of <typeparamref name="T"/> being deserialized.</returns>
public T Deserialize<T>(JsonReader reader)
{
return (T)Deserialize(reader, typeof(T));
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>
/// into an instance of the specified type.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> containing the object.</param>
/// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns>
public object Deserialize(JsonReader reader, Type objectType)
{
return DeserializeInternal(reader, objectType);
}
internal virtual object DeserializeInternal(JsonReader reader, Type objectType)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this);
return serializerReader.Deserialize(reader, objectType);
}
/// <summary>
/// Serializes the specified <see cref="Object"/> and writes the Json structure
/// to a <c>Stream</c> using the specified <see cref="TextWriter"/>.
/// </summary>
/// <param name="textWriter">The <see cref="TextWriter"/> used to write the Json structure.</param>
/// <param name="value">The <see cref="Object"/> to serialize.</param>
public void Serialize(TextWriter textWriter, object value)
{
Serialize(new JsonTextWriter(textWriter), value);
}
/// <summary>
/// Serializes the specified <see cref="Object"/> and writes the Json structure
/// to a <c>Stream</c> using the specified <see cref="JsonWriter"/>.
/// </summary>
/// <param name="jsonWriter">The <see cref="JsonWriter"/> used to write the Json structure.</param>
/// <param name="value">The <see cref="Object"/> to serialize.</param>
public void Serialize(JsonWriter jsonWriter, object value)
{
SerializeInternal(jsonWriter, value);
}
internal virtual void SerializeInternal(JsonWriter jsonWriter, object value)
{
ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter");
JsonSerializerInternalWriter serializerWriter = new JsonSerializerInternalWriter(this);
serializerWriter.Serialize(jsonWriter, value);
}
internal JsonConverter GetMatchingConverter(Type type)
{
return GetMatchingConverter(_converters, type);
}
internal static JsonConverter GetMatchingConverter(IList<JsonConverter> converters, Type objectType)
{
#if DEBUG
ValidationUtils.ArgumentNotNull(objectType, "objectType");
#endif
if (converters != null)
{
for (int i = 0; i < converters.Count; i++)
{
JsonConverter converter = converters[i];
if (converter.CanConvert(objectType))
return converter;
}
}
return null;
}
internal void OnError(ErrorEventArgs e)
{
EventHandler<ErrorEventArgs> error = Error;
if (error != null)
error(this, e);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using DeOps.Simulator;
using DeOps.Services;
using DeOps.Implementation.Protocol;
using DeOps.Implementation.Protocol.Net;
// network size = bucket size * 2 ^ (bucket count - 1)
namespace DeOps.Implementation.Dht
{
public class DhtRouting
{
int BucketLimit = 63;
public int ContactsPerBucket = 16;
// super-classes
public OpCore Core;
public DhtNetwork Network;
public ulong LocalRoutingID;
public List<DhtBucket> BucketList = new List<DhtBucket>();
public Dictionary<ulong, DhtContact> ContactMap = new Dictionary<ulong, DhtContact>();
int NetworkTimeout = 15; // seconds
int AttemptTimeout = 5; // seconds
public bool DhtResponsive;
public DateTime NextSelfSearch = new DateTime(0);
public DhtBound NearXor = new DhtBound(ulong.MaxValue, 8);
public DhtBound NearHigh = new DhtBound(ulong.MaxValue, 4);
public DhtBound NearLow = new DhtBound(0, 4);
public DhtRouting(DhtNetwork network)
{
Core = network.Core;
Network = network;
if (Core.Sim != null)
ContactsPerBucket = 8;
LocalRoutingID = Network.Local.UserID ^ Network.Local.ClientID;
BucketList.Add( new DhtBucket(this, 0, true) );
}
public void SecondTimer()
{
// if not connected, cache is frozen until re-connected
// ideally for disconnects around 10 mins, most of cache will still be valid upon reconnect
if (!Network.Responsive)
return;
// hourly self search, even if dht not enabled so we can find closer proxies for example
if (Core.TimeNow > NextSelfSearch)
{
// if behind nat this is how we ensure we are at closest proxy
// slightly off to avoid proxy host from returning with a found
Network.Searches.Start(LocalRoutingID + 1, "Self", Core.DhtServiceID, 0, null, null);
NextSelfSearch = Core.TimeNow.AddHours(1);
}
// refresh highest lowest bucket
if (DhtEnabled)
foreach (DhtBucket bucket in BucketList)
{
// if a node has a lot of dupes logged on there will be 20 empty buckets all the way down
// to where clientIDs start getting split up, don't research on those
// if bucket not low, then it will not refresh, but once low state is triggered
// a re-search is almost always immediately done to bring it back up
if (bucket.ContactList.Count != 0 &&
bucket.ContactList.Count < ContactsPerBucket / 2 &&
Core.Firewall == FirewallType.Open &&
Core.TimeNow > bucket.NextRefresh)
{
// search on random id in bucket
Network.Searches.Start(bucket.GetRandomBucketID(), "Low Bucket", Core.DhtServiceID, 0, null, null);
bucket.NextRefresh = Core.TimeNow.AddMinutes(15);
break;
}
}
/*
est network size = bucket size * 2^(number of buckets - 1)
est cache contacts = bucket size * number of buckets
ex: net of 2M = 2^21 = 2^4 * 2^(18-1)
contacts = 16 * 18 = 288, 1 refresh per sec = ~5 mins for full cache validation
*/
// if dhtEnabled - continually ping hosts - get oldest and ping it, remove timed out
// if not (proxied) - passively collect hosts from server - time out non-refreshed
// if not connected - don't remove hosts from routing
// get youngest (freshest) and oldest contact
DhtContact oldest = null;
DhtContact youngest = null;
List<DhtContact> timedOut = new List<DhtContact>();
int passiveTimeout = ContactMap.Count + 3 * AttemptTimeout; // the timeout upper bound is the routing table size + attempt wait * 3
foreach (DhtContact contact in ContactMap.Values)
{
if (youngest == null || contact.LastSeen > youngest.LastSeen)
youngest = contact;
if (DhtEnabled)
{
if (Core.TimeNow > contact.NextTry && (oldest == null || contact.LastSeen < oldest.LastSeen))
if (contact.Attempts < 2)
oldest = contact;
else
timedOut.Add(contact); // move than two tries, time out
}
else if(Core.TimeNow > contact.LastSeen.AddSeconds(passiveTimeout))
timedOut.Add(contact);
}
foreach (DhtContact contact in timedOut)
RemoveContact(contact);
// stagger cache pings, so once every second
// find oldest can attempt, send ping, remove expired
if (oldest != null && Core.TimeNow > oldest.NextTry)
{
Network.Send_Ping(oldest);
oldest.Attempts++;
// allow 10 (2*AttemptTimeout) unique nodes to be tried before disconnect
// (others should be pinging us as well if connected)
oldest.NextTry = Core.TimeNow.AddSeconds(AttemptTimeout);
}
// know if disconnected within 15 secs for any network size
// find youngest, if more than 15 secs old, we are disconnected
// in this time 15 unique contacts should have been pinged
SetResponsive(youngest != null && youngest.LastSeen.AddSeconds(NetworkTimeout) > Core.TimeNow);
}
private void SetResponsive(bool responsive)
{
if (DhtResponsive == responsive)
return;
// reset attempts when re-entering responsive mode
if (responsive)
foreach (DhtContact contact in ContactMap.Values)
{
contact.Attempts = 0;
contact.NextTry = Core.TimeNow;
}
DhtResponsive = responsive;
}
private void RemoveContact(DhtContact target)
{
// alert app of new bounds? yes need to activate caching to new nodes in bounds as network shrinks
bool refreshBuckets = false;
bool refreshXor = false;
bool refreshHigh = false;
bool refreshLow = false;
if (ContactMap.ContainsKey(target.RoutingID))
ContactMap.Remove(target.RoutingID);
foreach (DhtBucket check in BucketList)
if (check.ContactList.Contains(target))
{
refreshBuckets = check.ContactList.Remove(target) ? true : refreshBuckets;
break;
}
refreshXor = NearXor.Contacts.Remove(target) ? true : refreshXor;
refreshHigh = NearHigh.Contacts.Remove(target) ? true : refreshHigh;
refreshLow = NearLow.Contacts.Remove(target) ? true : refreshLow;
if (refreshBuckets)
CheckMerge();
// refesh lists that have been modified by getting next closest contacts
List<DhtContact> replicate = new List<DhtContact>();
if (refreshXor)
{
NearXor.Contacts = Find(LocalRoutingID, NearXor.Max);
// set bound to furthest contact in range
if (NearXor.Contacts.Count == NearXor.Max)
{
DhtContact furthest = NearXor.Contacts[NearXor.Max - 1];
NearXor.SetBounds(LocalRoutingID ^ furthest.RoutingID,
Network.Local.UserID ^ furthest.UserID);
// ensure node being replicated to hasnt already been replicated to through another list
if (!NearHigh.Contacts.Contains(furthest) &&
!NearLow.Contacts.Contains(furthest) &&
!replicate.Contains(furthest))
replicate.Add(furthest);
}
else
NearXor.SetBounds(ulong.MaxValue, ulong.MaxValue);
}
// node removed from closest, so there isnt anything in buckets closer than lower bound
// so find node next closest to lower bound
if (refreshLow)
{
DhtContact closest = null;
ulong bound = NearLow.Contacts.Count > 0 ? NearLow.Contacts[0].RoutingID : LocalRoutingID;
foreach (DhtBucket x in BucketList)
foreach (DhtContact contact in x.ContactList)
if (closest == null ||
(closest.RoutingID < contact.RoutingID && contact.RoutingID < bound))
{
closest = contact;
}
if (closest != null && !NearLow.Contacts.Contains(closest))
{
NearLow.Contacts.Insert(0, closest);
if (!NearXor.Contacts.Contains(closest) &&
!NearHigh.Contacts.Contains(closest) &&
!replicate.Contains(closest))
replicate.Add(closest);
}
if (NearLow.Contacts.Count < NearLow.Max)
NearLow.SetBounds(0, 0);
else
NearLow.SetBounds(NearLow.Contacts[0].RoutingID, NearLow.Contacts[0].UserID);
}
// high - get next highest
if (refreshHigh)
{
DhtContact closest = null;
ulong bound = NearHigh.Contacts.Count > 0 ? NearHigh.Contacts[NearHigh.Contacts.Count - 1].RoutingID : LocalRoutingID;
foreach (DhtBucket x in BucketList)
foreach (DhtContact contact in x.ContactList)
if (closest == null ||
(bound < contact.RoutingID && contact.RoutingID < closest.RoutingID))
{
closest = contact;
}
if (closest != null && !NearHigh.Contacts.Contains(closest))
{
NearHigh.Contacts.Insert(NearHigh.Contacts.Count, closest);
if (!NearXor.Contacts.Contains(closest) &&
!NearLow.Contacts.Contains(closest) &&
!replicate.Contains(closest))
replicate.Add(closest);
}
if (NearHigh.Contacts.Count < NearHigh.Max)
NearHigh.SetBounds(ulong.MaxValue, ulong.MaxValue);
else
NearHigh.SetBounds(NearHigh.Contacts[NearHigh.Contacts.Count - 1].RoutingID,
NearHigh.Contacts[NearHigh.Contacts.Count - 1].UserID);
}
foreach (DhtContact contact in replicate)
Network.Store.Replicate(contact);
}
private bool RemoveFromBuckets(DhtContact removed)
{
foreach (DhtBucket bucket in BucketList)
foreach (DhtContact contact in bucket.ContactList)
if (contact == removed)
{
bucket.ContactList.Remove(contact);
return true;
}
NearXor.Contacts.Remove(removed);
return false;
}
private bool InBucket(DhtContact find)
{
foreach (DhtBucket bucket in BucketList)
foreach (DhtContact contact in bucket.ContactList)
if (contact == find)
return true;
return false;
}
public bool InCacheArea(ulong user)
{
// modify lower bits so user on xor/high/low routing ID specific client boundary wont be rejected
if (user == Network.Local.UserID)
return true;
// xor is primary
if ((Network.Local.UserID ^ user) <= NearXor.UserBound)
return true;
// high/low is backup, a continuous cache, to keep data from being lost by grouped nodes in xor
// boundaries are xor'd with client id these need to be modified to work with an user id
//ex a node on one side of the network, and 8 nodes on the other side
// the single node is not deemed one of the 8 closests so his data is not cached by anyone
if (NearLow.UserBound <= user && user <= Network.Local.UserID)
return true;
if (Network.Local.UserID <= user && user <= NearHigh.UserBound)
return true;
return false;
}
public IEnumerable<DhtContact> GetCacheArea()
{
Dictionary<ulong, DhtContact> map = new Dictionary<ulong,DhtContact>();
// can replace these with delegate
foreach (DhtContact contact in NearXor.Contacts)
if (!map.ContainsKey(contact.RoutingID))
map.Add(contact.RoutingID, contact);
foreach (DhtContact contact in NearLow.Contacts)
if (!map.ContainsKey(contact.RoutingID))
map.Add(contact.RoutingID, contact);
foreach (DhtContact contact in NearHigh.Contacts)
if (!map.ContainsKey(contact.RoutingID))
map.Add(contact.RoutingID, contact);
return map.Values;
}
public bool DhtEnabled
{
get
{
// dht enable if node is open, or psuedo-open as signaled by using global proxies
return Core.Firewall == FirewallType.Open || Network.UseLookupProxies;
}
}
public void TryAdd(G2ReceivedPacket packet, DhtSource source)
{
TryAdd(packet, source, false);
}
public void TryAdd(G2ReceivedPacket packet, DhtSource source, bool pong)
{
// packet has IP and tunnel info
// source has operational info
// if firewall flag not set add to routing
if (source.Firewall == FirewallType.Open)
Add(new DhtContact(source, packet.Source.IP), pong);
// if tunneled source doesnt have op reachable IP, must go over global
else if (packet.Tunneled)
Add(new DhtContact(source, packet.Source.IP, packet.Source.TunnelClient, packet.Source.TunnelServer), pong);
}
public void Add(DhtContact newContact)
{
Add(newContact, false);
}
public void Add(DhtContact newContact, bool pong)
{
if (Core.User != null && Core.User.Settings.OpAccess == AccessType.Secret)
Debug.Assert(newContact.TunnelClient == null);
if(newContact.UserID == 0)
{
Network.UpdateLog("Routing", "Zero add attempt");
return;
}
if (newContact.UserID == Network.Local.UserID && newContact.ClientID == Network.Local.ClientID)
{
// happens because nodes will include ourselves in returnes to search requests
//Network.UpdateLog("Routing", "Self add attempt");
return;
}
if (newContact.ClientID == 0)
return;
// test to check if non open hosts being added to routing table through simulation
if (Core.Sim != null && newContact.TunnelClient == null)
{
IPEndPoint address = new IPEndPoint(newContact.IP, newContact.UdpPort);
if (Core.Sim.Internet.UdpEndPoints.ContainsKey(address))
{
DhtNetwork checkNet = Core.Sim.Internet.UdpEndPoints[address];
if (checkNet.Local.UserID != newContact.UserID ||
checkNet.Local.ClientID != newContact.ClientID ||
checkNet.TcpControl.ListenPort != newContact.TcpPort ||
checkNet.Core.Sim.RealFirewall != FirewallType.Open)
throw new Exception("Routing add mismatch");
}
}
// if dht enabled routing entries are set alive by pong
// many things call add, like the location service, but don't want to falsely report being responsive
// so only trigger dht responsive when a direct pong comes in
if (!DhtEnabled || pong)
{
newContact.LastSeen = Core.TimeNow;
if (ContactMap.ContainsKey(newContact.RoutingID))
ContactMap[newContact.RoutingID].Alive(Core.TimeNow);
SetResponsive(true);
}
Network.Cache.AddContact(newContact);
if (ContactMap.ContainsKey(newContact.RoutingID))
{
if (!Network.IsLookup)
{
DhtContact dupe = ContactMap[newContact.RoutingID];
// tunnel may change from pong / location update etc.. reflect in routing
// once host is open and in routing, prevent it from being maliciously set back to tunneled
if (dupe.TunnelServer != null)
{
dupe.TunnelServer = newContact.TunnelServer;
dupe.TunnelClient = newContact.TunnelClient;
}
}
// dont handle dupes
return;
}
// add to searches
foreach (DhtSearch search in Network.Searches.Active)
search.Add(newContact);
AddtoBucket(newContact);
bool replicate = false;
// check/set xor bound, cant combine below because both need to run
if (CheckXor(newContact))
replicate = true;
// check if should be added to high/low
if (CheckHighLow(newContact))
replicate = true;
if (replicate)
Network.Store.Replicate(newContact);
Core.RunInGuiThread(Network.UpdateBandwidthGraph);
}
private void AddtoBucket(DhtContact newContact)
{
// add to buckets
int depth = 0;
int pos = 1;
List<DhtContact> moveContacts = null;
lock (BucketList)
foreach (DhtBucket bucket in BucketList)
{
// if not the last bucket
if (!bucket.Last)
// if this is not the contacts place on tree
if (Utilities.GetBit(LocalRoutingID, depth) == Utilities.GetBit(newContact.RoutingID, depth))
{
depth++;
pos++;
continue;
}
// if cant add contact
if (!bucket.Add(newContact))
{
if (BucketList.Count > BucketLimit)
return;
// split bucket if last and try add again
if (bucket.Last)
{
// save contacts from bucket and reset
moveContacts = bucket.ContactList;
bucket.ContactList = new List<DhtContact>();
// create new bucket
bucket.Last = false;
BucketList.Add(new DhtBucket(this, bucket.Depth + 1, true));
// reaching here means dhtbucket::add was never called successfully, it gets recalled after the move
//Network.Store.RoutingUpdate(BucketList.Count);
break;
}
// else contact dropped
}
break;
}
// split should not recurse anymore than once
if (moveContacts != null)
{
foreach (DhtContact contact in moveContacts)
AddtoBucket(contact);
AddtoBucket(newContact);
}
}
private bool CheckXor(DhtContact check)
{
if ((LocalRoutingID ^ check.RoutingID) <= NearXor.RoutingBound)
{
NearXor.Contacts = Find(LocalRoutingID, NearXor.Max);
// set bound to furthest contact in range
if (NearXor.Contacts.Count == NearXor.Max)
NearXor.SetBounds( LocalRoutingID ^ NearXor.Contacts[NearXor.Max - 1].RoutingID,
Network.Local.UserID ^ NearXor.Contacts[NearXor.Max - 1].UserID);
return true;
}
return false;
}
private bool CheckHighLow(DhtContact check)
{
// dont store self in high/low, buckets do that
// we keep high/low nodes (not xor'd distance) because xor is absolute and
// will cause a cluster of nodes to cache each other and ignore a node further away
// then they are to each other, to ensure that far off node's stuff exists on network
// we also set bounds high/low based on ID so node will always have someone to cache for it
// nodes in high/low and xor ranges should mostly overlap
// if another client of same user added, in bounds, replicate to it
if (NearLow.RoutingBound < check.RoutingID && check.RoutingID < LocalRoutingID)
{
// sorted lowest to ourself
int i = 0;
for ( ; i < NearLow.Contacts.Count; i++)
if (check.RoutingID < NearLow.Contacts[i].RoutingID)
break;
NearLow.Contacts.Insert(i, check);
ContactMap[check.RoutingID] = check;
if (NearLow.Contacts.Count > NearLow.Max)
{
DhtContact remove = NearLow.Contacts[0];
NearLow.Contacts.Remove(remove);
if (!InBucket(remove))
ContactMap.Remove(remove.RoutingID);
NearLow.SetBounds( NearLow.Contacts[0].RoutingID, NearLow.Contacts[0].UserID);
}
return true;
}
if (LocalRoutingID < check.RoutingID && check.RoutingID < NearHigh.RoutingBound)
{
// sorted ourself to highest
int i = 0;
for (; i < NearHigh.Contacts.Count; i++)
if (check.RoutingID < NearHigh.Contacts[i].RoutingID)
break;
NearHigh.Contacts.Insert(i, check);
ContactMap[check.RoutingID] = check;
if (NearHigh.Contacts.Count > NearHigh.Max)
{
DhtContact remove = NearHigh.Contacts[NearHigh.Contacts.Count - 1];
NearHigh.Contacts.Remove(remove);
if ( !InBucket(remove) )
ContactMap.Remove(remove.RoutingID);
NearHigh.SetBounds( NearHigh.Contacts[NearHigh.Contacts.Count - 1].RoutingID,
NearHigh.Contacts[NearHigh.Contacts.Count - 1].UserID);
}
return true;
}
return false;
}
public void CheckMerge()
{
if(BucketList.Count <= 1)
return;
lock(BucketList)
{
DhtBucket lastBucket = (DhtBucket) BucketList[BucketList.Count - 1];
DhtBucket nexttoLast = (DhtBucket) BucketList[BucketList.Count - 2];
// see if buckets can be merged
if (nexttoLast.ContactList.Count + lastBucket.ContactList.Count < ContactsPerBucket)
{
nexttoLast.Last = true;
BucketList.Remove(lastBucket);
foreach (DhtContact contact in lastBucket.ContactList)
nexttoLast.Add(contact);
}
}
}
public List<DhtContact> Find(UInt64 targetID, int resultMax)
{
// refactor for speed
SortedList<ulong, DhtContact> closest = new SortedList<ulong, DhtContact>();
foreach (DhtContact contact in ContactMap.Values)
{
closest.Add(contact.RoutingID ^ targetID, contact);
if (closest.Count > resultMax)
closest.RemoveAt(closest.Count - 1);
}
List<DhtContact> results = new List<DhtContact>();
foreach (DhtContact contact in closest.Values)
results.Add(contact);
return results;
}
public int GetBucketIndex(ulong remoteRouting)
{
int index = 0;
for (int x = 0; x < 64; x++)
if (Utilities.GetBit(remoteRouting, x) != Utilities.GetBit(LocalRoutingID, x))
break;
else
index++;
return index;
}
}
public class DhtBound
{
public ulong RoutingBound;
public ulong UserBound;
public List<DhtContact> Contacts = new List<DhtContact>();
public int Max;
public DhtBound(ulong bound, int max)
{
RoutingBound = bound;
UserBound = bound;
Max = max;
}
public void SetBounds(ulong routing, ulong user)
{
RoutingBound = routing;
UserBound = user;
}
}
}
| |
using System;
using NBitcoin.BouncyCastle.Crypto.Utilities;
using NBitcoin.BouncyCastle.Utilities;
namespace NBitcoin.BouncyCastle.Crypto.Digests
{
/**
* SHA-224 as described in RFC 3874
* <pre>
* block word digest
* SHA-1 512 32 160
* SHA-224 512 32 224
* SHA-256 512 32 256
* SHA-384 1024 64 384
* SHA-512 1024 64 512
* </pre>
*/
internal class Sha224Digest
: GeneralDigest
{
private const int DigestLength = 28;
private uint H1, H2, H3, H4, H5, H6, H7, H8;
private uint[] X = new uint[64];
private int xOff;
/**
* Standard constructor
*/
public Sha224Digest()
{
Reset();
}
/**
* Copy constructor. This will copy the state of the provided
* message digest.
*/
public Sha224Digest(
Sha224Digest t)
: base(t)
{
CopyIn(t);
}
private void CopyIn(Sha224Digest t)
{
base.CopyIn(t);
this.H1 = t.H1;
this.H2 = t.H2;
this.H3 = t.H3;
this.H4 = t.H4;
this.H5 = t.H5;
this.H6 = t.H6;
this.H7 = t.H7;
this.H8 = t.H8;
Array.Copy(t.X, 0, this.X, 0, t.X.Length);
this.xOff = t.xOff;
}
public override string AlgorithmName
{
get
{
return "SHA-224";
}
}
public override int GetDigestSize()
{
return DigestLength;
}
internal override void ProcessWord(
byte[] input,
int inOff)
{
this.X[this.xOff] = Pack.BE_To_UInt32(input, inOff);
if(++this.xOff == 16)
{
ProcessBlock();
}
}
internal override void ProcessLength(
long bitLength)
{
if(this.xOff > 14)
{
ProcessBlock();
}
this.X[14] = (uint)((ulong)bitLength >> 32);
this.X[15] = (uint)((ulong)bitLength);
}
public override int DoFinal(
byte[] output,
int outOff)
{
Finish();
Pack.UInt32_To_BE(this.H1, output, outOff);
Pack.UInt32_To_BE(this.H2, output, outOff + 4);
Pack.UInt32_To_BE(this.H3, output, outOff + 8);
Pack.UInt32_To_BE(this.H4, output, outOff + 12);
Pack.UInt32_To_BE(this.H5, output, outOff + 16);
Pack.UInt32_To_BE(this.H6, output, outOff + 20);
Pack.UInt32_To_BE(this.H7, output, outOff + 24);
Reset();
return DigestLength;
}
/**
* reset the chaining variables
*/
public override void Reset()
{
base.Reset();
/* SHA-224 initial hash value
*/
this.H1 = 0xc1059ed8;
this.H2 = 0x367cd507;
this.H3 = 0x3070dd17;
this.H4 = 0xf70e5939;
this.H5 = 0xffc00b31;
this.H6 = 0x68581511;
this.H7 = 0x64f98fa7;
this.H8 = 0xbefa4fa4;
this.xOff = 0;
Array.Clear(this.X, 0, this.X.Length);
}
internal override void ProcessBlock()
{
//
// expand 16 word block into 64 word blocks.
//
for(int ti = 16; ti <= 63; ti++)
{
this.X[ti] = Theta1(this.X[ti - 2]) + this.X[ti - 7] + Theta0(this.X[ti - 15]) + this.X[ti - 16];
}
//
// set up working variables.
//
uint a = this.H1;
uint b = this.H2;
uint c = this.H3;
uint d = this.H4;
uint e = this.H5;
uint f = this.H6;
uint g = this.H7;
uint h = this.H8;
int t = 0;
for(int i = 0; i < 8; i++)
{
// t = 8 * i
h += Sum1(e) + Ch(e, f, g) + K[t] + this.X[t];
d += h;
h += Sum0(a) + Maj(a, b, c);
++t;
// t = 8 * i + 1
g += Sum1(d) + Ch(d, e, f) + K[t] + this.X[t];
c += g;
g += Sum0(h) + Maj(h, a, b);
++t;
// t = 8 * i + 2
f += Sum1(c) + Ch(c, d, e) + K[t] + this.X[t];
b += f;
f += Sum0(g) + Maj(g, h, a);
++t;
// t = 8 * i + 3
e += Sum1(b) + Ch(b, c, d) + K[t] + this.X[t];
a += e;
e += Sum0(f) + Maj(f, g, h);
++t;
// t = 8 * i + 4
d += Sum1(a) + Ch(a, b, c) + K[t] + this.X[t];
h += d;
d += Sum0(e) + Maj(e, f, g);
++t;
// t = 8 * i + 5
c += Sum1(h) + Ch(h, a, b) + K[t] + this.X[t];
g += c;
c += Sum0(d) + Maj(d, e, f);
++t;
// t = 8 * i + 6
b += Sum1(g) + Ch(g, h, a) + K[t] + this.X[t];
f += b;
b += Sum0(c) + Maj(c, d, e);
++t;
// t = 8 * i + 7
a += Sum1(f) + Ch(f, g, h) + K[t] + this.X[t];
e += a;
a += Sum0(b) + Maj(b, c, d);
++t;
}
this.H1 += a;
this.H2 += b;
this.H3 += c;
this.H4 += d;
this.H5 += e;
this.H6 += f;
this.H7 += g;
this.H8 += h;
//
// reset the offset and clean out the word buffer.
//
this.xOff = 0;
Array.Clear(this.X, 0, 16);
}
/* SHA-224 functions */
private static uint Ch(uint x, uint y, uint z)
{
return (x & y) ^ (~x & z);
}
private static uint Maj(uint x, uint y, uint z)
{
return (x & y) ^ (x & z) ^ (y & z);
}
private static uint Sum0(uint x)
{
return ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10));
}
private static uint Sum1(uint x)
{
return ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7));
}
private static uint Theta0(uint x)
{
return ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3);
}
private static uint Theta1(uint x)
{
return ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10);
}
/* SHA-224 Constants
* (represent the first 32 bits of the fractional parts of the
* cube roots of the first sixty-four prime numbers)
*/
internal static readonly uint[] K = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
public override IMemoable Copy()
{
return new Sha224Digest(this);
}
public override void Reset(IMemoable other)
{
var d = (Sha224Digest)other;
CopyIn(d);
}
}
}
| |
// 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.ComponentModel.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
using CodeFixGroupKey = Tuple<DiagnosticData, CodeActionPriority>;
[Export(typeof(ISuggestedActionsSourceProvider))]
[VisualStudio.Utilities.ContentType(ContentTypeNames.RoslynContentType)]
[VisualStudio.Utilities.Name("Roslyn Code Fix")]
[VisualStudio.Utilities.Order]
internal class SuggestedActionsSourceProvider : ISuggestedActionsSourceProvider
{
private static readonly Guid s_CSharpSourceGuid = new Guid("b967fea8-e2c3-4984-87d4-71a38f49e16a");
private static readonly Guid s_visualBasicSourceGuid = new Guid("4de30e93-3e0c-40c2-a4ba-1124da4539f6");
private const int InvalidSolutionVersion = -1;
private readonly ICodeRefactoringService _codeRefactoringService;
private readonly IDiagnosticAnalyzerService _diagnosticService;
private readonly ICodeFixService _codeFixService;
private readonly ICodeActionEditHandlerService _editHandler;
private readonly IAsynchronousOperationListener _listener;
private readonly IWaitIndicator _waitIndicator;
[ImportingConstructor]
public SuggestedActionsSourceProvider(
ICodeRefactoringService codeRefactoringService,
IDiagnosticAnalyzerService diagnosticService,
ICodeFixService codeFixService,
ICodeActionEditHandlerService editHandler,
IWaitIndicator waitIndicator,
[ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners)
{
_codeRefactoringService = codeRefactoringService;
_diagnosticService = diagnosticService;
_codeFixService = codeFixService;
_editHandler = editHandler;
_waitIndicator = waitIndicator;
_listener = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.LightBulb);
}
public ISuggestedActionsSource CreateSuggestedActionsSource(ITextView textView, ITextBuffer textBuffer)
{
Contract.ThrowIfNull(textView);
Contract.ThrowIfNull(textBuffer);
return new Source(this, textView, textBuffer);
}
private class Source : ForegroundThreadAffinitizedObject, ISuggestedActionsSource
{
// state that will be only reset when source is disposed.
private SuggestedActionsSourceProvider _owner;
private ITextView _textView;
private ITextBuffer _subjectBuffer;
private WorkspaceRegistration _registration;
// mutable state
private Workspace _workspace;
private int _lastSolutionVersionReported;
public Source(SuggestedActionsSourceProvider owner, ITextView textView, ITextBuffer textBuffer)
{
_owner = owner;
_textView = textView;
_textView.Closed += OnTextViewClosed;
_subjectBuffer = textBuffer;
_registration = Workspace.GetWorkspaceRegistration(textBuffer.AsTextContainer());
_lastSolutionVersionReported = InvalidSolutionVersion;
var updateSource = (IDiagnosticUpdateSource)_owner._diagnosticService;
updateSource.DiagnosticsUpdated += OnDiagnosticsUpdated;
if (_registration.Workspace != null)
{
_workspace = _registration.Workspace;
_workspace.DocumentActiveContextChanged += OnActiveContextChanged;
}
_registration.WorkspaceChanged += OnWorkspaceChanged;
}
public event EventHandler<EventArgs> SuggestedActionsChanged;
public bool TryGetTelemetryId(out Guid telemetryId)
{
telemetryId = default(Guid);
var workspace = _workspace;
if (workspace == null || _subjectBuffer == null)
{
return false;
}
var documentId = workspace.GetDocumentIdInCurrentContext(_subjectBuffer.AsTextContainer());
if (documentId == null)
{
return false;
}
var project = workspace.CurrentSolution.GetProject(documentId.ProjectId);
if (project == null)
{
return false;
}
switch (project.Language)
{
case LanguageNames.CSharp:
telemetryId = s_CSharpSourceGuid;
return true;
case LanguageNames.VisualBasic:
telemetryId = s_visualBasicSourceGuid;
return true;
default:
return false;
}
}
public IEnumerable<SuggestedActionSet> GetSuggestedActions(ISuggestedActionCategorySet requestedActionCategories, SnapshotSpan range, CancellationToken cancellationToken)
{
AssertIsForeground();
using (Logger.LogBlock(FunctionId.SuggestedActions_GetSuggestedActions, cancellationToken))
{
var documentAndSnapshot = GetMatchingDocumentAndSnapshotAsync(range.Snapshot, cancellationToken).WaitAndGetResult(cancellationToken);
if (!documentAndSnapshot.HasValue)
{
// this is here to fail test and see why it is failed.
Trace.WriteLine("given range is not current");
return null;
}
var document = documentAndSnapshot.Value.Item1;
var workspace = document.Project.Solution.Workspace;
var supportsFeatureService = workspace.Services.GetService<IDocumentSupportsFeatureService>();
var fixes = GetCodeFixes(supportsFeatureService, requestedActionCategories, workspace, document, range, cancellationToken);
var refactorings = GetRefactorings(supportsFeatureService, requestedActionCategories, workspace, document, range, cancellationToken);
var result = fixes == null ? refactorings : refactorings == null
? fixes : fixes.Concat(refactorings);
if (result == null)
{
return null;
}
var allActionSets = result.ToList();
allActionSets = InlineActionSetsIfDesirable(allActionSets);
return allActionSets;
}
}
private List<SuggestedActionSet> InlineActionSetsIfDesirable(List<SuggestedActionSet> allActionSets)
{
// If we only have a single set of items, and that set only has three max suggestion
// offered. Then we can consider inlining any nested actions into the top level list.
// (but we only do this if the parent of the nested actions isn't invokable itself).
if (allActionSets.Sum(a => a.Actions.Count()) > 3)
{
return allActionSets;
}
return allActionSets.Select(InlineActions).ToList();
}
private bool IsInlineable(ISuggestedAction action)
{
var suggestedAction = action as SuggestedAction;
return suggestedAction != null &&
!suggestedAction.CodeAction.IsInvokable &&
suggestedAction.CodeAction.HasCodeActions;
}
private SuggestedActionSet InlineActions(SuggestedActionSet actionSet)
{
if (!actionSet.Actions.Any(IsInlineable))
{
return actionSet;
}
var newActions = new List<ISuggestedAction>();
foreach (var action in actionSet.Actions)
{
if (IsInlineable(action))
{
// Looks like something we can inline.
var childActionSets = ((SuggestedAction)action).GetActionSets();
if (childActionSets.Length != 1)
{
return actionSet;
}
newActions.AddRange(childActionSets[0].Actions);
continue;
}
newActions.Add(action);
}
return new SuggestedActionSet(newActions, actionSet.Title, actionSet.Priority, actionSet.ApplicableToSpan);
}
private IEnumerable<SuggestedActionSet> GetCodeFixes(
IDocumentSupportsFeatureService supportsFeatureService,
ISuggestedActionCategorySet requestedActionCategories,
Workspace workspace,
Document document,
SnapshotSpan range,
CancellationToken cancellationToken)
{
this.AssertIsForeground();
if (_owner._codeFixService != null &&
supportsFeatureService.SupportsCodeFixes(document) &&
requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.CodeFix))
{
// We only include suppressions if lightbulb is asking for everything.
// If the light bulb is only asking for code fixes, then we don't include suppressions.
var includeSuppressionFixes = requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Any);
var fixes = Task.Run(
async () =>
{
var stream = await _owner._codeFixService.GetFixesAsync(
document, range.Span.ToTextSpan(), includeSuppressionFixes, cancellationToken).ConfigureAwait(false);
return stream.ToList();
},
cancellationToken).WaitAndGetResult(cancellationToken);
var filteredFixes = FilterOnUIThread(fixes, workspace);
return OrganizeFixes(workspace, filteredFixes, hasSuppressionFixes: includeSuppressionFixes);
}
return null;
}
private List<CodeFixCollection> FilterOnUIThread(List<CodeFixCollection> collections, Workspace workspace)
{
this.AssertIsForeground();
return collections.Select(c => FilterOnUIThread(c, workspace)).WhereNotNull().ToList();
}
private CodeFixCollection FilterOnUIThread(
CodeFixCollection collection,
Workspace workspace)
{
this.AssertIsForeground();
var applicableFixes = collection.Fixes.Where(f => IsApplicable(f.Action, workspace)).ToList();
return applicableFixes.Count == 0
? null
: applicableFixes.Count == collection.Fixes.Length
? collection
: new CodeFixCollection(collection.Provider, collection.TextSpan, applicableFixes,
collection.FixAllState,
collection.SupportedScopes, collection.FirstDiagnostic);
}
private bool IsApplicable(CodeAction action, Workspace workspace)
{
if (!action.PerformFinalApplicabilityCheck)
{
// If we don't even need to perform the final applicability check,
// then the code actoin is applicable.
return true;
}
// Otherwise, defer to the action to make the decision.
this.AssertIsForeground();
return action.IsApplicable(workspace);
}
private List<CodeRefactoring> FilterOnUIThread(List<CodeRefactoring> refactorings, Workspace workspace)
{
return refactorings.Select(r => FilterOnUIThread(r, workspace)).WhereNotNull().ToList();
}
private CodeRefactoring FilterOnUIThread(CodeRefactoring refactoring, Workspace workspace)
{
var actions = refactoring.Actions.Where(a => IsApplicable(a, workspace)).ToList();
return actions.Count == 0
? null
: actions.Count == refactoring.Actions.Count
? refactoring
: new CodeRefactoring(refactoring.Provider, actions);
}
/// <summary>
/// Arrange fixes into groups based on the issue (diagnostic being fixed) and prioritize these groups.
/// </summary>
private IEnumerable<SuggestedActionSet> OrganizeFixes(Workspace workspace, IEnumerable<CodeFixCollection> fixCollections, bool hasSuppressionFixes)
{
var map = ImmutableDictionary.CreateBuilder<CodeFixGroupKey, IList<SuggestedAction>>();
var order = ArrayBuilder<CodeFixGroupKey>.GetInstance();
// First group fixes by diagnostic and priority.
GroupFixes(workspace, fixCollections, map, order, hasSuppressionFixes);
// Then prioritize between the groups.
return PrioritizeFixGroups(map.ToImmutable(), order.ToImmutableAndFree());
}
/// <summary>
/// Groups fixes by the diagnostic being addressed by each fix.
/// </summary>
private void GroupFixes(
Workspace workspace,
IEnumerable<CodeFixCollection> fixCollections,
IDictionary<CodeFixGroupKey, IList<SuggestedAction>> map,
ArrayBuilder<CodeFixGroupKey> order,
bool hasSuppressionFixes)
{
foreach (var fixCollection in fixCollections)
{
var fixes = fixCollection.Fixes;
var fixCount = fixes.Length;
Func<CodeAction, SuggestedActionSet> getFixAllSuggestedActionSet =
codeAction => CodeFixSuggestedAction.GetFixAllSuggestedActionSet(
codeAction, fixCount, fixCollection.FixAllState,
fixCollection.SupportedScopes, fixCollection.FirstDiagnostic,
workspace, _subjectBuffer, _owner._editHandler,
_owner._waitIndicator, _owner._listener);
foreach (var fix in fixes)
{
// Suppression fixes are handled below.
if (!(fix.Action is SuppressionCodeAction))
{
SuggestedAction suggestedAction;
if (fix.Action.HasCodeActions)
{
var nestedActions = new List<SuggestedAction>();
foreach (var nestedAction in fix.Action.GetCodeActions())
{
nestedActions.Add(new CodeFixSuggestedAction(workspace, _subjectBuffer,
_owner._editHandler, _owner._waitIndicator, fix,
nestedAction, fixCollection.Provider, getFixAllSuggestedActionSet(nestedAction), _owner._listener));
}
var diag = fix.PrimaryDiagnostic;
var set = new SuggestedActionSet(nestedActions, SuggestedActionSetPriority.Medium, diag.Location.SourceSpan.ToSpan());
suggestedAction = new SuggestedAction(workspace, _subjectBuffer,
_owner._editHandler, _owner._waitIndicator, fix.Action,
fixCollection.Provider, _owner._listener, new[] { set });
}
else
{
suggestedAction = new CodeFixSuggestedAction(
workspace, _subjectBuffer, _owner._editHandler, _owner._waitIndicator, fix,
fix.Action, fixCollection.Provider, getFixAllSuggestedActionSet(fix.Action), _owner._listener);
}
AddFix(fix, suggestedAction, map, order);
}
}
if (hasSuppressionFixes)
{
// Add suppression fixes to the end of a given SuggestedActionSet so that they always show up last in a group.
foreach (var fix in fixes)
{
if (fix.Action is SuppressionCodeAction)
{
SuggestedAction suggestedAction;
if (fix.Action.HasCodeActions)
{
suggestedAction = new SuppressionSuggestedAction(
workspace, _subjectBuffer, _owner._editHandler, _owner._waitIndicator,
fix, fixCollection.Provider, getFixAllSuggestedActionSet, _owner._listener);
}
else
{
suggestedAction = new CodeFixSuggestedAction(
workspace, _subjectBuffer, _owner._editHandler, _owner._waitIndicator, fix,
fix.Action, fixCollection.Provider, getFixAllSuggestedActionSet(fix.Action), _owner._listener);
}
AddFix(fix, suggestedAction, map, order);
}
}
}
}
}
private static void AddFix(
CodeFix fix, SuggestedAction suggestedAction,
IDictionary<CodeFixGroupKey, IList<SuggestedAction>> map,
ArrayBuilder<CodeFixGroupKey> order)
{
var diag = fix.GetPrimaryDiagnosticData();
var groupKey = new CodeFixGroupKey(diag, fix.Action.Priority);
if (!map.ContainsKey(groupKey))
{
order.Add(groupKey);
map[groupKey] = ImmutableArray.CreateBuilder<SuggestedAction>();
}
map[groupKey].Add(suggestedAction);
}
/// <summary>
/// Return prioritized set of fix groups such that fix group for suppression always show up at the bottom of the list.
/// </summary>
/// <remarks>
/// Fix groups are returned in priority order determined based on <see cref="ExtensionOrderAttribute"/>.
/// Priority for all <see cref="SuggestedActionSet"/>s containing fixes is set to <see cref="SuggestedActionSetPriority.Medium"/> by default.
/// The only exception is the case where a <see cref="SuggestedActionSet"/> only contains suppression fixes -
/// the priority of such <see cref="SuggestedActionSet"/>s is set to <see cref="SuggestedActionSetPriority.None"/> so that suppression fixes
/// always show up last after all other fixes (and refactorings) for the selected line of code.
/// </remarks>
private static IEnumerable<SuggestedActionSet> PrioritizeFixGroups(IDictionary<CodeFixGroupKey, IList<SuggestedAction>> map, IList<CodeFixGroupKey> order)
{
var sets = ArrayBuilder<SuggestedActionSet>.GetInstance();
foreach (var diag in order)
{
var actions = map[diag];
foreach (var group in actions.GroupBy(a => a.Priority))
{
var priority = GetSuggestedActionSetPriority(group.Key);
// diagnostic from things like build shouldn't reach here since we don't support LB for those diagnostics
Contract.Requires(diag.Item1.HasTextSpan);
sets.Add(new SuggestedActionSet(group, priority, diag.Item1.TextSpan.ToSpan()));
}
}
return sets.ToImmutableAndFree();
}
private static SuggestedActionSetPriority GetSuggestedActionSetPriority(CodeActionPriority key)
{
switch (key)
{
case CodeActionPriority.None: return SuggestedActionSetPriority.None;
case CodeActionPriority.Low: return SuggestedActionSetPriority.Low;
case CodeActionPriority.Medium: return SuggestedActionSetPriority.Medium;
case CodeActionPriority.High: return SuggestedActionSetPriority.High;
default:
throw new InvalidOperationException();
}
}
private IEnumerable<SuggestedActionSet> GetRefactorings(
IDocumentSupportsFeatureService supportsFeatureService,
ISuggestedActionCategorySet requestedActionCategories,
Workspace workspace,
Document document,
SnapshotSpan range,
CancellationToken cancellationToken)
{
this.AssertIsForeground();
if (workspace.Options.GetOption(EditorComponentOnOffOptions.CodeRefactorings) &&
_owner._codeRefactoringService != null &&
supportsFeatureService.SupportsRefactorings(document) &&
requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Refactoring))
{
// Get the selection while on the UI thread.
var selection = TryGetCodeRefactoringSelection(_subjectBuffer, _textView, range);
if (!selection.HasValue)
{
// this is here to fail test and see why it is failed.
Trace.WriteLine("given range is not current");
return null;
}
var refactorings = Task.Run(
async () =>
{
var stream = await _owner._codeRefactoringService.GetRefactoringsAsync(
document, selection.Value, cancellationToken).ConfigureAwait(false);
return stream.ToList();
},
cancellationToken).WaitAndGetResult(cancellationToken);
var filteredRefactorings = FilterOnUIThread(refactorings, workspace);
return filteredRefactorings.Select(r => OrganizeRefactorings(workspace, r));
}
return null;
}
/// <summary>
/// Arrange refactorings into groups.
/// </summary>
/// <remarks>
/// Refactorings are returned in priority order determined based on <see cref="ExtensionOrderAttribute"/>.
/// Priority for all <see cref="SuggestedActionSet"/>s containing refactorings is set to <see cref="SuggestedActionSetPriority.Low"/>
/// and should show up after fixes but before suppression fixes in the light bulb menu.
/// </remarks>
private SuggestedActionSet OrganizeRefactorings(Workspace workspace, CodeRefactoring refactoring)
{
var refactoringSuggestedActions = ArrayBuilder<SuggestedAction>.GetInstance();
foreach (var a in refactoring.Actions)
{
refactoringSuggestedActions.Add(new CodeRefactoringSuggestedAction(
workspace, _subjectBuffer, _owner._editHandler, _owner._waitIndicator,
a, refactoring.Provider, _owner._listener));
}
return new SuggestedActionSet(
refactoringSuggestedActions.ToImmutableAndFree(), SuggestedActionSetPriority.Low);
}
public async Task<bool> HasSuggestedActionsAsync(ISuggestedActionCategorySet requestedActionCategories, SnapshotSpan range, CancellationToken cancellationToken)
{
// Explicitly hold onto below fields in locals and use these locals throughout this code path to avoid crashes
// if these fields happen to be cleared by Dispose() below. This is required since this code path involves
// code that can run asynchronously from background thread.
var view = _textView;
var buffer = _subjectBuffer;
var provider = _owner;
if (view == null || buffer == null || provider == null)
{
return false;
}
using (var asyncToken = provider._listener.BeginAsyncOperation("HasSuggestedActionsAsync"))
{
var documentAndSnapshot = await GetMatchingDocumentAndSnapshotAsync(range.Snapshot, cancellationToken).ConfigureAwait(false);
if (!documentAndSnapshot.HasValue)
{
// this is here to fail test and see why it is failed.
Trace.WriteLine("given range is not current");
return false;
}
var document = documentAndSnapshot.Value.Item1;
var workspace = document.Project.Solution.Workspace;
var supportsFeatureService = workspace.Services.GetService<IDocumentSupportsFeatureService>();
return
await HasFixesAsync(
supportsFeatureService, requestedActionCategories, provider, document, range,
cancellationToken).ConfigureAwait(false) ||
await HasRefactoringsAsync(
supportsFeatureService, requestedActionCategories, provider, document, buffer, view, range,
cancellationToken).ConfigureAwait(false);
}
}
private async Task<bool> HasFixesAsync(
IDocumentSupportsFeatureService supportsFeatureService,
ISuggestedActionCategorySet requestedActionCategories,
SuggestedActionsSourceProvider provider,
Document document, SnapshotSpan range,
CancellationToken cancellationToken)
{
if (provider._codeFixService != null && supportsFeatureService.SupportsCodeFixes(document) &&
requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.CodeFix))
{
// We only consider suppressions if lightbulb is asking for everything.
// If the light bulb is only asking for code fixes, then we don't consider suppressions.
var considerSuppressionFixes = requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Any);
var result = await Task.Run(
() => provider._codeFixService.GetFirstDiagnosticWithFixAsync(
document, range.Span.ToTextSpan(), considerSuppressionFixes, cancellationToken),
cancellationToken).ConfigureAwait(false);
if (result.HasFix)
{
Logger.Log(FunctionId.SuggestedActions_HasSuggestedActionsAsync);
return true;
}
if (result.PartialResult)
{
// reset solution version number so that we can raise suggested action changed event
Volatile.Write(ref _lastSolutionVersionReported, InvalidSolutionVersion);
return false;
}
}
return false;
}
private async Task<bool> HasRefactoringsAsync(
IDocumentSupportsFeatureService supportsFeatureService,
ISuggestedActionCategorySet requestedActionCategories,
SuggestedActionsSourceProvider provider,
Document document,
ITextBuffer buffer,
ITextView view,
SnapshotSpan range,
CancellationToken cancellationToken)
{
if (document.Project.Solution.Options.GetOption(EditorComponentOnOffOptions.CodeRefactorings) &&
provider._codeRefactoringService != null &&
supportsFeatureService.SupportsRefactorings(document) &&
requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Refactoring))
{
TextSpan? selection = null;
if (IsForeground())
{
// This operation needs to happen on UI thread because it needs to access textView.Selection.
selection = TryGetCodeRefactoringSelection(buffer, view, range);
}
else
{
await InvokeBelowInputPriority(() =>
{
// This operation needs to happen on UI thread because it needs to access textView.Selection.
selection = TryGetCodeRefactoringSelection(buffer, view, range);
}).ConfigureAwait(false);
}
if (!selection.HasValue)
{
// this is here to fail test and see why it is failed.
Trace.WriteLine("given range is not current");
return false;
}
return await Task.Run(
() => provider._codeRefactoringService.HasRefactoringsAsync(
document, selection.Value, cancellationToken),
cancellationToken).ConfigureAwait(false);
}
return false;
}
private static TextSpan? TryGetCodeRefactoringSelection(ITextBuffer buffer, ITextView view, SnapshotSpan range)
{
var selectedSpans = view.Selection.SelectedSpans
.SelectMany(ss => view.BufferGraph.MapDownToBuffer(ss, SpanTrackingMode.EdgeExclusive, buffer))
.Where(ss => !view.IsReadOnlyOnSurfaceBuffer(ss))
.ToList();
// We only support refactorings when there is a single selection in the document.
if (selectedSpans.Count != 1)
{
return null;
}
var translatedSpan = selectedSpans[0].TranslateTo(range.Snapshot, SpanTrackingMode.EdgeInclusive);
// We only support refactorings when selected span intersects with the span that the light bulb is asking for.
if (!translatedSpan.IntersectsWith(range))
{
return null;
}
return translatedSpan.Span.ToTextSpan();
}
private static async Task<ValueTuple<Document, ITextSnapshot>?> GetMatchingDocumentAndSnapshotAsync(ITextSnapshot givenSnapshot, CancellationToken cancellationToken)
{
var buffer = givenSnapshot.TextBuffer;
if (buffer == null)
{
return null;
}
var workspace = buffer.GetWorkspace();
if (workspace == null)
{
return null;
}
var documentId = workspace.GetDocumentIdInCurrentContext(buffer.AsTextContainer());
if (documentId == null)
{
return null;
}
var document = workspace.CurrentSolution.GetDocument(documentId);
if (document == null)
{
return null;
}
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
var snapshot = sourceText.FindCorrespondingEditorTextSnapshot();
if (snapshot == null || snapshot.Version.ReiteratedVersionNumber != givenSnapshot.Version.ReiteratedVersionNumber)
{
return null;
}
return ValueTuple.Create(document, snapshot);
}
private void OnTextViewClosed(object sender, EventArgs e)
{
Dispose();
}
private void OnWorkspaceChanged(object sender, EventArgs e)
{
// REVIEW: this event should give both old and new workspace as argument so that
// one doesn't need to hold onto workspace in field.
// remove existing event registration
if (_workspace != null)
{
_workspace.DocumentActiveContextChanged -= OnActiveContextChanged;
}
// REVIEW: why one need to get new workspace from registration? why not just pass in the new workspace?
// add new event registration
_workspace = _registration.Workspace;
if (_workspace != null)
{
_workspace.DocumentActiveContextChanged += OnActiveContextChanged;
}
}
private void OnActiveContextChanged(object sender, DocumentActiveContextChangedEventArgs e)
{
// REVIEW: it would be nice for changed event to pass in both old and new document.
OnSuggestedActionsChanged(e.Solution.Workspace, e.NewActiveContextDocumentId, e.Solution.WorkspaceVersion);
}
private void OnDiagnosticsUpdated(object sender, DiagnosticsUpdatedArgs e)
{
// document removed case. no reason to raise event
if (e.Solution == null)
{
return;
}
OnSuggestedActionsChanged(e.Workspace, e.DocumentId, e.Solution.WorkspaceVersion);
}
private void OnSuggestedActionsChanged(Workspace currentWorkspace, DocumentId currentDocumentId, int solutionVersion, DiagnosticsUpdatedArgs args = null)
{
// Explicitly hold onto the _subjectBuffer field in a local and use this local in this function to avoid crashes
// if this field happens to be cleared by Dispose() below. This is required since this code path involves code
// that can run on background thread.
var buffer = _subjectBuffer;
if (buffer == null)
{
return;
}
var workspace = buffer.GetWorkspace();
// workspace is not ready, nothing to do.
if (workspace == null || workspace != currentWorkspace)
{
return;
}
if (currentDocumentId != workspace.GetDocumentIdInCurrentContext(buffer.AsTextContainer()) ||
solutionVersion == Volatile.Read(ref _lastSolutionVersionReported))
{
return;
}
this.SuggestedActionsChanged?.Invoke(this, EventArgs.Empty);
Volatile.Write(ref _lastSolutionVersionReported, solutionVersion);
}
public void Dispose()
{
if (_owner != null)
{
var updateSource = (IDiagnosticUpdateSource)_owner._diagnosticService;
updateSource.DiagnosticsUpdated -= OnDiagnosticsUpdated;
_owner = null;
}
if (_workspace != null)
{
_workspace.DocumentActiveContextChanged -= OnActiveContextChanged;
_workspace = null;
}
if (_registration != null)
{
_registration.WorkspaceChanged -= OnWorkspaceChanged;
_registration = null;
}
if (_textView != null)
{
_textView.Closed -= OnTextViewClosed;
_textView = null;
}
if (_subjectBuffer != null)
{
_subjectBuffer = null;
}
}
}
}
}
| |
namespace Microsoft.Zelig.Debugger.ArmProcessor
{
partial class BreakpointsView
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose( bool disposing )
{
if(disposing && (components != null))
{
components.Dispose();
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager( typeof( BreakpointsView ) );
this.panel_Breakpoints_Search = new System.Windows.Forms.Panel();
this.listBox_Breakpoint_SearchResults = new System.Windows.Forms.ListBox();
this.label_Breakpoint_Search = new System.Windows.Forms.Label();
this.textBox_Breakpoint_Search = new System.Windows.Forms.TextBox();
this.dataGridView_Breakpoints = new System.Windows.Forms.DataGridView();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.toolStripButton_DeleteBreakpoint = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripButton_DeleteAllBreakpoints = new System.Windows.Forms.ToolStripButton();
this.toolStripButton_ToggleAllBreakpoints = new System.Windows.Forms.ToolStripButton();
this.panel1 = new System.Windows.Forms.Panel();
this.dataGridViewImageColumn_Breakpoints_Status = new System.Windows.Forms.DataGridViewImageColumn();
this.dataGridViewTextBoxColumn_Breakpoints_Method = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn_Breakpoints_Condition = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn_Breakpoints_HitCount = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.panel_Breakpoints_Search.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView_Breakpoints)).BeginInit();
this.toolStrip1.SuspendLayout();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// panel_Breakpoints_Search
//
this.panel_Breakpoints_Search.Controls.Add( this.listBox_Breakpoint_SearchResults );
this.panel_Breakpoints_Search.Controls.Add( this.label_Breakpoint_Search );
this.panel_Breakpoints_Search.Controls.Add( this.textBox_Breakpoint_Search );
this.panel_Breakpoints_Search.Dock = System.Windows.Forms.DockStyle.Top;
this.panel_Breakpoints_Search.Location = new System.Drawing.Point( 0, 0 );
this.panel_Breakpoints_Search.Name = "panel_Breakpoints_Search";
this.panel_Breakpoints_Search.Size = new System.Drawing.Size( 572, 187 );
this.panel_Breakpoints_Search.TabIndex = 1;
//
// listBox_Breakpoint_SearchResults
//
this.listBox_Breakpoint_SearchResults.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listBox_Breakpoint_SearchResults.FormattingEnabled = true;
this.listBox_Breakpoint_SearchResults.HorizontalScrollbar = true;
this.listBox_Breakpoint_SearchResults.Location = new System.Drawing.Point( 7, 30 );
this.listBox_Breakpoint_SearchResults.Name = "listBox_Breakpoint_SearchResults";
this.listBox_Breakpoint_SearchResults.Size = new System.Drawing.Size( 560, 147 );
this.listBox_Breakpoint_SearchResults.TabIndex = 2;
this.listBox_Breakpoint_SearchResults.DoubleClick += new System.EventHandler( this.listBox_Breakpoint_SearchResults_DoubleClick );
this.listBox_Breakpoint_SearchResults.Click += new System.EventHandler( this.listBox_Breakpoint_SearchResults_Click );
//
// label_Breakpoint_Search
//
this.label_Breakpoint_Search.AutoSize = true;
this.label_Breakpoint_Search.Location = new System.Drawing.Point( 4, 7 );
this.label_Breakpoint_Search.Name = "label_Breakpoint_Search";
this.label_Breakpoint_Search.Size = new System.Drawing.Size( 44, 13 );
this.label_Breakpoint_Search.TabIndex = 1;
this.label_Breakpoint_Search.Text = "Search:";
//
// textBox_Breakpoint_Search
//
this.textBox_Breakpoint_Search.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBox_Breakpoint_Search.Location = new System.Drawing.Point( 54, 4 );
this.textBox_Breakpoint_Search.Name = "textBox_Breakpoint_Search";
this.textBox_Breakpoint_Search.Size = new System.Drawing.Size( 513, 20 );
this.textBox_Breakpoint_Search.TabIndex = 0;
this.textBox_Breakpoint_Search.TextChanged += new System.EventHandler( this.textBox_Breakpoint_Search_TextChanged );
//
// dataGridView_Breakpoints
//
this.dataGridView_Breakpoints.AllowUserToAddRows = false;
this.dataGridView_Breakpoints.AllowUserToDeleteRows = false;
this.dataGridView_Breakpoints.AllowUserToResizeRows = false;
this.dataGridView_Breakpoints.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dataGridView_Breakpoints.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView_Breakpoints.Columns.AddRange( new System.Windows.Forms.DataGridViewColumn[] {
this.dataGridViewImageColumn_Breakpoints_Status,
this.dataGridViewTextBoxColumn_Breakpoints_Method,
this.dataGridViewTextBoxColumn_Breakpoints_Condition,
this.dataGridViewTextBoxColumn_Breakpoints_HitCount} );
this.dataGridView_Breakpoints.Location = new System.Drawing.Point( 0, 28 );
this.dataGridView_Breakpoints.Name = "dataGridView_Breakpoints";
this.dataGridView_Breakpoints.ReadOnly = true;
this.dataGridView_Breakpoints.RowHeadersWidth = 24;
this.dataGridView_Breakpoints.Size = new System.Drawing.Size( 572, 254 );
this.dataGridView_Breakpoints.TabIndex = 2;
this.dataGridView_Breakpoints.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler( this.dataGridView_Breakpoints_CellContentClick );
this.dataGridView_Breakpoints.CellContentDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler( this.dataGridView_Breakpoints_CellContentDoubleClick );
this.dataGridView_Breakpoints.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler( this.dataGridView_Breakpoints_CellContentClick );
//
// toolStrip1
//
this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.toolStrip1.Items.AddRange( new System.Windows.Forms.ToolStripItem[] {
this.toolStripButton_DeleteBreakpoint,
this.toolStripSeparator1,
this.toolStripButton_DeleteAllBreakpoints,
this.toolStripButton_ToggleAllBreakpoints} );
this.toolStrip1.Location = new System.Drawing.Point( 0, 0 );
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size( 572, 25 );
this.toolStrip1.TabIndex = 3;
this.toolStrip1.Text = "toolStrip1";
//
// toolStripButton_DeleteBreakpoint
//
this.toolStripButton_DeleteBreakpoint.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButton_DeleteBreakpoint.Enabled = false;
this.toolStripButton_DeleteBreakpoint.Image = ((System.Drawing.Image)(resources.GetObject( "toolStripButton_DeleteBreakpoint.Image" )));
this.toolStripButton_DeleteBreakpoint.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton_DeleteBreakpoint.Name = "toolStripButton_DeleteBreakpoint";
this.toolStripButton_DeleteBreakpoint.Size = new System.Drawing.Size( 23, 22 );
this.toolStripButton_DeleteBreakpoint.ToolTipText = "Delete Breakpoint";
this.toolStripButton_DeleteBreakpoint.Click += new System.EventHandler( this.toolStripButton_DeleteBreakpoint_Click );
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size( 6, 25 );
//
// toolStripButton_DeleteAllBreakpoints
//
this.toolStripButton_DeleteAllBreakpoints.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButton_DeleteAllBreakpoints.Enabled = false;
this.toolStripButton_DeleteAllBreakpoints.Image = ((System.Drawing.Image)(resources.GetObject( "toolStripButton_DeleteAllBreakpoints.Image" )));
this.toolStripButton_DeleteAllBreakpoints.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton_DeleteAllBreakpoints.Name = "toolStripButton_DeleteAllBreakpoints";
this.toolStripButton_DeleteAllBreakpoints.Size = new System.Drawing.Size( 23, 22 );
this.toolStripButton_DeleteAllBreakpoints.ToolTipText = "Delete All Breakpoints";
this.toolStripButton_DeleteAllBreakpoints.Click += new System.EventHandler( this.toolStripButton_DeleteAllBreakpoints_Click );
//
// toolStripButton_ToggleAllBreakpoints
//
this.toolStripButton_ToggleAllBreakpoints.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButton_ToggleAllBreakpoints.Enabled = false;
this.toolStripButton_ToggleAllBreakpoints.Image = ((System.Drawing.Image)(resources.GetObject( "toolStripButton_ToggleAllBreakpoints.Image" )));
this.toolStripButton_ToggleAllBreakpoints.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton_ToggleAllBreakpoints.Name = "toolStripButton_ToggleAllBreakpoints";
this.toolStripButton_ToggleAllBreakpoints.Size = new System.Drawing.Size( 23, 22 );
this.toolStripButton_ToggleAllBreakpoints.ToolTipText = "Toggle All Breakpoints";
this.toolStripButton_ToggleAllBreakpoints.Click += new System.EventHandler( this.toolStripButton_ToggleAllBreakpoints_Click );
//
// panel1
//
this.panel1.Controls.Add( this.toolStrip1 );
this.panel1.Controls.Add( this.dataGridView_Breakpoints );
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point( 0, 187 );
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size( 572, 282 );
this.panel1.TabIndex = 4;
//
// dataGridViewImageColumn_Breakpoints_Status
//
this.dataGridViewImageColumn_Breakpoints_Status.HeaderText = "";
this.dataGridViewImageColumn_Breakpoints_Status.Name = "dataGridViewImageColumn_Breakpoints_Status";
this.dataGridViewImageColumn_Breakpoints_Status.ReadOnly = true;
this.dataGridViewImageColumn_Breakpoints_Status.Resizable = System.Windows.Forms.DataGridViewTriState.False;
this.dataGridViewImageColumn_Breakpoints_Status.Width = 20;
//
// dataGridViewTextBoxColumn_Breakpoints_Method
//
this.dataGridViewTextBoxColumn_Breakpoints_Method.HeaderText = "Method";
this.dataGridViewTextBoxColumn_Breakpoints_Method.Name = "dataGridViewTextBoxColumn_Breakpoints_Method";
this.dataGridViewTextBoxColumn_Breakpoints_Method.ReadOnly = true;
this.dataGridViewTextBoxColumn_Breakpoints_Method.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// dataGridViewTextBoxColumn_Breakpoints_Condition
//
this.dataGridViewTextBoxColumn_Breakpoints_Condition.HeaderText = "Condition";
this.dataGridViewTextBoxColumn_Breakpoints_Condition.Name = "dataGridViewTextBoxColumn_Breakpoints_Condition";
this.dataGridViewTextBoxColumn_Breakpoints_Condition.ReadOnly = true;
this.dataGridViewTextBoxColumn_Breakpoints_Condition.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// dataGridViewTextBoxColumn_Breakpoints_HitCount
//
this.dataGridViewTextBoxColumn_Breakpoints_HitCount.HeaderText = "Hit Count";
this.dataGridViewTextBoxColumn_Breakpoints_HitCount.Name = "dataGridViewTextBoxColumn_Breakpoints_HitCount";
this.dataGridViewTextBoxColumn_Breakpoints_HitCount.ReadOnly = true;
this.dataGridViewTextBoxColumn_Breakpoints_HitCount.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// BreakpointsView
//
this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F );
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add( this.panel1 );
this.Controls.Add( this.panel_Breakpoints_Search );
this.Name = "BreakpointsView";
this.Size = new System.Drawing.Size( 572, 469 );
this.panel_Breakpoints_Search.ResumeLayout( false );
this.panel_Breakpoints_Search.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView_Breakpoints)).EndInit();
this.toolStrip1.ResumeLayout( false );
this.toolStrip1.PerformLayout();
this.panel1.ResumeLayout( false );
this.panel1.PerformLayout();
this.ResumeLayout( false );
}
#endregion
private System.Windows.Forms.Panel panel_Breakpoints_Search;
private System.Windows.Forms.ListBox listBox_Breakpoint_SearchResults;
private System.Windows.Forms.Label label_Breakpoint_Search;
private System.Windows.Forms.TextBox textBox_Breakpoint_Search;
private System.Windows.Forms.DataGridView dataGridView_Breakpoints;
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripButton toolStripButton_DeleteBreakpoint;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripButton toolStripButton_DeleteAllBreakpoints;
private System.Windows.Forms.ToolStripButton toolStripButton_ToggleAllBreakpoints;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.DataGridViewImageColumn dataGridViewImageColumn_Breakpoints_Status;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn_Breakpoints_Method;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn_Breakpoints_Condition;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn_Breakpoints_HitCount;
}
}
| |
//
// Copyright (c) 2004-2016 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.
//
using JetBrains.Annotations;
#if !SILVERLIGHT
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.IO;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
// For issue #1351 - These are not available for Android or IOS
#if !__ANDROID__ && !__IOS__
using System.Configuration;
using System.Net.Configuration;
#endif
/// <summary>
/// Sends log messages by email using SMTP protocol.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/Mail-target">Documentation on NLog Wiki</seealso>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/Mail/Simple/NLog.config" />
/// <p>
/// This assumes just one target and a single rule. More configuration
/// options are described <a href="config.html">here</a>.
/// </p>
/// <p>
/// To set up the log target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/Mail/Simple/Example.cs" />
/// <p>
/// Mail target works best when used with BufferingWrapper target
/// which lets you send multiple log messages in single mail
/// </p>
/// <p>
/// To set up the buffered mail target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/Mail/Buffered/NLog.config" />
/// <p>
/// To set up the buffered mail target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/Mail/Buffered/Example.cs" />
/// </example>
[Target("Mail")]
public class MailTarget : TargetWithLayoutHeaderAndFooter
{
private const string RequiredPropertyIsEmptyFormat = "After the processing of the MailTarget's '{0}' property it appears to be empty. The email message will not be sent.";
private Layout _from;
/// <summary>
/// Initializes a new instance of the <see cref="MailTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "This one is safe.")]
public MailTarget()
{
this.Body = "${message}${newline}";
this.Subject = "Message from NLog on ${machinename}";
this.Encoding = Encoding.UTF8;
this.SmtpPort = 25;
this.SmtpAuthentication = SmtpAuthenticationMode.None;
this.Timeout = 10000;
}
#if !__ANDROID__ && !__IOS__
private SmtpSection _currentailSettings;
/// <summary>
/// Gets the mailSettings/smtp configuration from app.config in cases when we need those configuration.
/// E.g when UseSystemNetMailSettings is enabled and we need to read the From attribute from system.net/mailSettings/smtp
/// </summary>
/// <remarks>Internal for mocking</remarks>
internal SmtpSection SmtpSection
{
get
{
if (_currentailSettings == null)
{
try
{
_currentailSettings = System.Configuration.ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection;
}
catch (Exception ex)
{
InternalLogger.Warn(ex, "reading 'From' from .config failed.");
if (ex.MustBeRethrown())
{
throw;
}
_currentailSettings = new SmtpSection();
}
}
return _currentailSettings;
}
set { _currentailSettings = value; }
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="MailTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
/// <param name="name">Name of the target.</param>
public MailTarget(string name) : this()
{
this.Name = name;
}
/// <summary>
/// Gets or sets sender's email address (e.g. joe@domain.com).
/// </summary>
/// <docgen category='Message Options' order='10' />
public Layout From
{
get
{
#if !__ANDROID__ && !__IOS__
if (UseSystemNetMailSettings)
{
// In contrary to other settings, System.Net.Mail.SmtpClient doesn't read the 'From' attribute from the system.net/mailSettings/smtp section in the config file.
// Thus, when UseSystemNetMailSettings is enabled we have to read the configuration section of system.net/mailSettings/smtp to initialize the 'From' address.
// It will do so only if the 'From' attribute in system.net/mailSettings/smtp is not empty.
//only use from config when not set in current
if (_from == null)
{
var from = SmtpSection.From;
if (from == null) return null;
return from;
}
}
#endif
return _from;
}
set { _from = value; }
}
/// <summary>
/// Gets or sets recipients' email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com).
/// </summary>
/// <docgen category='Message Options' order='11' />
[RequiredParameter]
public Layout To { get; set; }
/// <summary>
/// Gets or sets CC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com).
/// </summary>
/// <docgen category='Message Options' order='12' />
public Layout CC { get; set; }
/// <summary>
/// Gets or sets BCC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com).
/// </summary>
/// <docgen category='Message Options' order='13' />
public Layout Bcc { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to add new lines between log entries.
/// </summary>
/// <value>A value of <c>true</c> if new lines should be added; otherwise, <c>false</c>.</value>
/// <docgen category='Layout Options' order='99' />
public bool AddNewLines { get; set; }
/// <summary>
/// Gets or sets the mail subject.
/// </summary>
/// <docgen category='Message Options' order='5' />
[DefaultValue("Message from NLog on ${machinename}")]
[RequiredParameter]
public Layout Subject { get; set; }
/// <summary>
/// Gets or sets mail message body (repeated for each log message send in one mail).
/// </summary>
/// <remarks>Alias for the <c>Layout</c> property.</remarks>
/// <docgen category='Message Options' order='6' />
[DefaultValue("${message}${newline}")]
public Layout Body
{
get { return this.Layout; }
set { this.Layout = value; }
}
/// <summary>
/// Gets or sets encoding to be used for sending e-mail.
/// </summary>
/// <docgen category='Layout Options' order='20' />
[DefaultValue("UTF8")]
public Encoding Encoding { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to send message as HTML instead of plain text.
/// </summary>
/// <docgen category='Layout Options' order='11' />
[DefaultValue(false)]
public bool Html { get; set; }
/// <summary>
/// Gets or sets SMTP Server to be used for sending.
/// </summary>
/// <docgen category='SMTP Options' order='10' />
public Layout SmtpServer { get; set; }
/// <summary>
/// Gets or sets SMTP Authentication mode.
/// </summary>
/// <docgen category='SMTP Options' order='11' />
[DefaultValue("None")]
public SmtpAuthenticationMode SmtpAuthentication { get; set; }
/// <summary>
/// Gets or sets the username used to connect to SMTP server (used when SmtpAuthentication is set to "basic").
/// </summary>
/// <docgen category='SMTP Options' order='12' />
public Layout SmtpUserName { get; set; }
/// <summary>
/// Gets or sets the password used to authenticate against SMTP server (used when SmtpAuthentication is set to "basic").
/// </summary>
/// <docgen category='SMTP Options' order='13' />
public Layout SmtpPassword { get; set; }
/// <summary>
/// Gets or sets a value indicating whether SSL (secure sockets layer) should be used when communicating with SMTP server.
/// </summary>
/// <docgen category='SMTP Options' order='14' />.
[DefaultValue(false)]
public bool EnableSsl { get; set; }
/// <summary>
/// Gets or sets the port number that SMTP Server is listening on.
/// </summary>
/// <docgen category='SMTP Options' order='15' />
[DefaultValue(25)]
public int SmtpPort { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the default Settings from System.Net.MailSettings should be used.
/// </summary>
/// <docgen category='SMTP Options' order='16' />
[DefaultValue(false)]
public bool UseSystemNetMailSettings { get; set; }
/// <summary>
/// Specifies how outgoing email messages will be handled.
/// </summary>
/// <docgen category='SMTP Options' order='18' />
[DefaultValue(SmtpDeliveryMethod.Network)]
public SmtpDeliveryMethod DeliveryMethod { get; set; }
/// <summary>
/// Gets or sets the folder where applications save mail messages to be processed by the local SMTP server.
/// </summary>
/// <docgen category='SMTP Options' order='17' />
[DefaultValue(null)]
public string PickupDirectoryLocation { get; set; }
/// <summary>
/// Gets or sets the priority used for sending mails.
/// </summary>
public Layout Priority { get; set; }
/// <summary>
/// Gets or sets a value indicating whether NewLine characters in the body should be replaced with <br/> tags.
/// </summary>
/// <remarks>Only happens when <see cref="Html"/> is set to true.</remarks>
[DefaultValue(false)]
public bool ReplaceNewlineWithBrTagInHtml { get; set; }
/// <summary>
/// Gets or sets a value indicating the SMTP client timeout.
/// </summary>
/// <remarks>Warning: zero is not infinit waiting</remarks>
[DefaultValue(10000)]
public int Timeout { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "This is a factory method.")]
internal virtual ISmtpClient CreateSmtpClient()
{
return new MySmtpClient();
}
/// <summary>
/// Renders the logging event message and adds it to the internal ArrayList of log messages.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(AsyncLogEventInfo logEvent)
{
this.Write(new[] { logEvent });
}
/// <summary>
/// Renders an array logging events.
/// </summary>
/// <param name="logEvents">Array of logging events.</param>
protected override void Write(AsyncLogEventInfo[] logEvents)
{
var buckets = logEvents.BucketSort(c => this.GetSmtpSettingsKey(c.LogEvent));
foreach (var bucket in buckets)
{
var eventInfos = bucket.Value;
this.ProcessSingleMailMessage(eventInfos);
}
}
/// <summary>
/// Initializes the target. Can be used by inheriting classes
/// to initialize logging.
/// </summary>
protected override void InitializeTarget()
{
CheckRequiredParameters();
base.InitializeTarget();
}
/// <summary>
/// Create mail and send with SMTP
/// </summary>
/// <param name="events">event printed in the body of the event</param>
private void ProcessSingleMailMessage([NotNull] IList<AsyncLogEventInfo> events)
{
try
{
if (events.Count == 0)
{
throw new NLogRuntimeException("We need at least one event.");
}
LogEventInfo firstEvent = events[0].LogEvent;
LogEventInfo lastEvent = events[events.Count - 1].LogEvent;
// unbuffered case, create a local buffer, append header, body and footer
var bodyBuffer = CreateBodyBuffer(events, firstEvent, lastEvent);
using (var msg = CreateMailMessage(lastEvent, bodyBuffer.ToString()))
{
using (ISmtpClient client = this.CreateSmtpClient())
{
if (!UseSystemNetMailSettings)
{
ConfigureMailClient(lastEvent, client);
}
InternalLogger.Debug("Sending mail to {0} using {1}:{2} (ssl={3})", msg.To, client.Host, client.Port, client.EnableSsl);
InternalLogger.Trace(" Subject: '{0}'", msg.Subject);
InternalLogger.Trace(" From: '{0}'", msg.From.ToString());
client.Send(msg);
foreach (var ev in events)
{
ev.Continuation(null);
}
}
}
}
catch (Exception exception)
{
//always log
InternalLogger.Error(exception, "Error sending mail.");
if (exception.MustBeRethrown())
{
throw;
}
foreach (var ev in events)
{
ev.Continuation(exception);
}
}
}
/// <summary>
/// Create buffer for body
/// </summary>
/// <param name="events">all events</param>
/// <param name="firstEvent">first event for header</param>
/// <param name="lastEvent">last event for footer</param>
/// <returns></returns>
private StringBuilder CreateBodyBuffer(IEnumerable<AsyncLogEventInfo> events, LogEventInfo firstEvent, LogEventInfo lastEvent)
{
var bodyBuffer = new StringBuilder();
if (this.Header != null)
{
bodyBuffer.Append(this.Header.Render(firstEvent));
if (this.AddNewLines)
{
bodyBuffer.Append("\n");
}
}
foreach (AsyncLogEventInfo eventInfo in events)
{
bodyBuffer.Append(this.Layout.Render(eventInfo.LogEvent));
if (this.AddNewLines)
{
bodyBuffer.Append("\n");
}
}
if (this.Footer != null)
{
bodyBuffer.Append(this.Footer.Render(lastEvent));
if (this.AddNewLines)
{
bodyBuffer.Append("\n");
}
}
return bodyBuffer;
}
/// <summary>
/// Set properties of <paramref name="client"/>
/// </summary>
/// <param name="lastEvent">last event for username/password</param>
/// <param name="client">client to set properties on</param>
/// <remarks>Configure not at <see cref="InitializeTarget"/>, as the properties could have layout renderers.</remarks>
internal void ConfigureMailClient(LogEventInfo lastEvent, ISmtpClient client)
{
CheckRequiredParameters();
if (this.SmtpServer == null && string.IsNullOrEmpty(this.PickupDirectoryLocation))
{
throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer/PickupDirectoryLocation"));
}
if (this.DeliveryMethod == SmtpDeliveryMethod.Network && this.SmtpServer == null)
{
throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer"));
}
if (this.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory && string.IsNullOrEmpty(this.PickupDirectoryLocation))
{
throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "PickupDirectoryLocation"));
}
if (this.SmtpServer != null && this.DeliveryMethod == SmtpDeliveryMethod.Network)
{
var renderedSmtpServer = this.SmtpServer.Render(lastEvent);
if (string.IsNullOrEmpty(renderedSmtpServer))
{
throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer"));
}
client.Host = renderedSmtpServer;
client.Port = this.SmtpPort;
client.EnableSsl = this.EnableSsl;
if (this.SmtpAuthentication == SmtpAuthenticationMode.Ntlm)
{
InternalLogger.Trace(" Using NTLM authentication.");
client.Credentials = CredentialCache.DefaultNetworkCredentials;
}
else if (this.SmtpAuthentication == SmtpAuthenticationMode.Basic)
{
string username = this.SmtpUserName.Render(lastEvent);
string password = this.SmtpPassword.Render(lastEvent);
InternalLogger.Trace(" Using basic authentication: Username='{0}' Password='{1}'", username, new string('*', password.Length));
client.Credentials = new NetworkCredential(username, password);
}
}
if (!string.IsNullOrEmpty(this.PickupDirectoryLocation) && this.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
{
client.PickupDirectoryLocation = ConvertDirectoryLocation(PickupDirectoryLocation);
}
// In case DeliveryMethod = PickupDirectoryFromIis we will not require Host nor PickupDirectoryLocation
client.DeliveryMethod = this.DeliveryMethod;
client.Timeout = this.Timeout;
}
/// <summary>
/// Handle <paramref name="pickupDirectoryLocation"/> if it is a virtual directory.
/// </summary>
/// <param name="pickupDirectoryLocation"></param>
/// <returns></returns>
internal static string ConvertDirectoryLocation(string pickupDirectoryLocation)
{
const string virtualPathPrefix = "~/";
if (!pickupDirectoryLocation.StartsWith(virtualPathPrefix))
{
return pickupDirectoryLocation;
}
// Support for Virtual Paths
var root = AppDomain.CurrentDomain.BaseDirectory;
var directory = pickupDirectoryLocation.Substring(virtualPathPrefix.Length).Replace('/', Path.DirectorySeparatorChar);
var pickupRoot = Path.Combine(root, directory);
return pickupRoot;
}
private void CheckRequiredParameters()
{
if (!this.UseSystemNetMailSettings && this.SmtpServer == null && this.DeliveryMethod == SmtpDeliveryMethod.Network)
{
throw new NLogConfigurationException("The MailTarget's '{0}' properties are not set - but needed because useSystemNetMailSettings=false and DeliveryMethod=Network. The email message will not be sent.", "SmtpServer");
}
if (!this.UseSystemNetMailSettings && string.IsNullOrEmpty(this.PickupDirectoryLocation) && this.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
{
throw new NLogConfigurationException("The MailTarget's '{0}' properties are not set - but needed because useSystemNetMailSettings=false and DeliveryMethod=SpecifiedPickupDirectory. The email message will not be sent.", "PickupDirectoryLocation");
}
if (this.From == null)
{
throw new NLogConfigurationException(RequiredPropertyIsEmptyFormat, "From");
}
}
/// <summary>
/// Create key for grouping. Needed for multiple events in one mailmessage
/// </summary>
/// <param name="logEvent">event for rendering layouts </param>
///<returns>string to group on</returns>
private string GetSmtpSettingsKey(LogEventInfo logEvent)
{
var sb = new StringBuilder();
AppendLayout(sb, logEvent, this.From);
AppendLayout(sb, logEvent, this.To);
AppendLayout(sb, logEvent, this.CC);
AppendLayout(sb, logEvent, this.Bcc);
AppendLayout(sb, logEvent, this.SmtpServer);
AppendLayout(sb, logEvent, this.SmtpPassword);
AppendLayout(sb, logEvent, this.SmtpUserName);
return sb.ToString();
}
/// <summary>
/// Append rendered layout to the stringbuilder
/// </summary>
/// <param name="sb">append to this</param>
/// <param name="logEvent">event for rendering <paramref name="layout"/></param>
/// <param name="layout">append if not <c>null</c></param>
private static void AppendLayout(StringBuilder sb, LogEventInfo logEvent, Layout layout)
{
sb.Append("|");
if (layout != null)
sb.Append(layout.Render(logEvent));
}
/// <summary>
/// Create the mailmessage with the addresses, properties and body.
/// </summary>
private MailMessage CreateMailMessage(LogEventInfo lastEvent, string body)
{
var msg = new MailMessage();
var renderedFrom = this.From == null ? null : this.From.Render(lastEvent);
if (string.IsNullOrEmpty(renderedFrom))
{
throw new NLogRuntimeException(RequiredPropertyIsEmptyFormat, "From");
}
msg.From = new MailAddress(renderedFrom);
var addedTo = AddAddresses(msg.To, this.To, lastEvent);
var addedCc = AddAddresses(msg.CC, this.CC, lastEvent);
var addedBcc = AddAddresses(msg.Bcc, this.Bcc, lastEvent);
if (!addedTo && !addedCc && !addedBcc)
{
throw new NLogRuntimeException(RequiredPropertyIsEmptyFormat, "To/Cc/Bcc");
}
msg.Subject = this.Subject == null ? string.Empty : this.Subject.Render(lastEvent).Trim();
msg.BodyEncoding = this.Encoding;
msg.IsBodyHtml = this.Html;
if (this.Priority != null)
{
var renderedPriority = this.Priority.Render(lastEvent);
try
{
msg.Priority = (MailPriority)Enum.Parse(typeof(MailPriority), renderedPriority, true);
}
catch
{
InternalLogger.Warn("Could not convert '{0}' to MailPriority, valid values are Low, Normal and High. Using normal priority as fallback.");
msg.Priority = MailPriority.Normal;
}
}
msg.Body = body;
if (msg.IsBodyHtml && ReplaceNewlineWithBrTagInHtml && msg.Body != null)
msg.Body = msg.Body.Replace(EnvironmentHelper.NewLine, "<br/>");
return msg;
}
/// <summary>
/// Render <paramref name="layout"/> and add the addresses to <paramref name="mailAddressCollection"/>
/// </summary>
/// <param name="mailAddressCollection">Addresses appended to this list</param>
/// <param name="layout">layout with addresses, ; separated</param>
/// <param name="logEvent">event for rendering the <paramref name="layout"/></param>
/// <returns>added a address?</returns>
private static bool AddAddresses(MailAddressCollection mailAddressCollection, Layout layout, LogEventInfo logEvent)
{
var added = false;
if (layout != null)
{
foreach (string mail in layout.Render(logEvent).Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
mailAddressCollection.Add(mail);
added = true;
}
}
return added;
}
}
}
#endif
| |
//
// property.cs: Property based handlers
//
// Authors: Miguel de Icaza (miguel@gnu.org)
// Martin Baulig (martin@ximian.com)
// Marek Safar (marek.safar@seznam.cz)
//
// Dual licensed under the terms of the MIT X11 or GNU GPL
//
// Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
// Copyright 2004-2008 Novell, Inc
// Copyright 2011 Xamarin Inc
//
using System;
using System.Collections.Generic;
using System.Text;
using Mono.CompilerServices.SymbolWriter;
#if NET_2_1
using XmlElement = System.Object;
#endif
#if STATIC
using IKVM.Reflection;
using IKVM.Reflection.Emit;
#else
using System.Reflection;
using System.Reflection.Emit;
#endif
namespace Mono.CSharp
{
// It is used as a base class for all property based members
// This includes properties, indexers, and events
public abstract class PropertyBasedMember : InterfaceMemberBase
{
public PropertyBasedMember (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name, Attributes attrs)
: base (parent, type, mod, allowed_mod, name, attrs)
{
}
protected void CheckReservedNameConflict (string prefix, MethodSpec accessor)
{
string name;
AParametersCollection parameters;
if (accessor != null) {
name = accessor.Name;
parameters = accessor.Parameters;
} else {
name = prefix + ShortName;
if (IsExplicitImpl)
name = MemberName.Left + "." + name;
if (this is Indexer) {
parameters = ((Indexer) this).ParameterInfo;
if (prefix[0] == 's') {
var data = new IParameterData[parameters.Count + 1];
Array.Copy (parameters.FixedParameters, data, data.Length - 1);
data[data.Length - 1] = new ParameterData ("value", Parameter.Modifier.NONE);
var types = new TypeSpec[data.Length];
Array.Copy (parameters.Types, types, data.Length - 1);
types[data.Length - 1] = member_type;
parameters = new ParametersImported (data, types, false);
}
} else {
if (prefix[0] == 's')
parameters = ParametersCompiled.CreateFullyResolved (new[] { member_type });
else
parameters = ParametersCompiled.EmptyReadOnlyParameters;
}
}
var conflict = MemberCache.FindMember (Parent.Definition,
new MemberFilter (name, 0, MemberKind.Method, parameters, null),
BindingRestriction.DeclaredOnly | BindingRestriction.NoAccessors);
if (conflict != null) {
Report.SymbolRelatedToPreviousError (conflict);
Report.Error (82, Location, "A member `{0}' is already reserved", conflict.GetSignatureForError ());
}
}
protected override bool VerifyClsCompliance ()
{
if (!base.VerifyClsCompliance ())
return false;
if (!MemberType.IsCLSCompliant ()) {
Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
GetSignatureForError ());
}
return true;
}
}
public class PropertySpec : MemberSpec, IInterfaceMemberSpec
{
PropertyInfo info;
TypeSpec memberType;
MethodSpec set, get;
public PropertySpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, PropertyInfo info, Modifiers modifiers)
: base (kind, declaringType, definition, modifiers)
{
this.info = info;
this.memberType = memberType;
}
#region Properties
public MethodSpec Get {
get {
return get;
}
set {
get = value;
get.IsAccessor = true;
}
}
public MethodSpec Set {
get {
return set;
}
set {
set = value;
set.IsAccessor = true;
}
}
public bool HasDifferentAccessibility {
get {
return HasGet && HasSet &&
(Get.Modifiers & Modifiers.AccessibilityMask) != (Set.Modifiers & Modifiers.AccessibilityMask);
}
}
public bool HasGet {
get {
return Get != null;
}
}
public bool HasSet {
get {
return Set != null;
}
}
public PropertyInfo MetaInfo {
get {
if ((state & StateFlags.PendingMetaInflate) != 0)
throw new NotSupportedException ();
return info;
}
}
public TypeSpec MemberType {
get {
return memberType;
}
}
#endregion
public override MemberSpec InflateMember (TypeParameterInflator inflator)
{
var ps = (PropertySpec) base.InflateMember (inflator);
ps.memberType = inflator.Inflate (memberType);
return ps;
}
public override List<TypeSpec> ResolveMissingDependencies ()
{
return memberType.ResolveMissingDependencies ();
}
}
//
// Properties and Indexers both generate PropertyBuilders, we use this to share
// their common bits.
//
abstract public class PropertyBase : PropertyBasedMember {
public class GetMethod : PropertyMethod
{
static readonly string[] attribute_targets = new string [] { "method", "return" };
internal const string Prefix = "get_";
public GetMethod (PropertyBase method, Modifiers modifiers, Attributes attrs, Location loc)
: base (method, Prefix, modifiers, attrs, loc)
{
}
public override MethodBuilder Define (TypeContainer parent)
{
base.Define (parent);
Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, null, ParameterInfo, ModFlags);
method_data = new MethodData (method, ModFlags, flags, this);
if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
return null;
Spec.SetMetaInfo (method_data.MethodBuilder);
return method_data.MethodBuilder;
}
public override TypeSpec ReturnType {
get {
return method.MemberType;
}
}
public override ParametersCompiled ParameterInfo {
get {
return ParametersCompiled.EmptyReadOnlyParameters;
}
}
public override string[] ValidAttributeTargets {
get {
return attribute_targets;
}
}
}
public class SetMethod : PropertyMethod {
static readonly string[] attribute_targets = new string[] { "method", "param", "return" };
internal const string Prefix = "set_";
protected ParametersCompiled parameters;
public SetMethod (PropertyBase method, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
: base (method, Prefix, modifiers, attrs, loc)
{
this.parameters = parameters;
}
protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
{
if (a.Target == AttributeTargets.Parameter) {
parameters[0].ApplyAttributeBuilder (a, ctor, cdata, pa);
return;
}
base.ApplyAttributeBuilder (a, ctor, cdata, pa);
}
public override ParametersCompiled ParameterInfo {
get {
return parameters;
}
}
public override MethodBuilder Define (TypeContainer parent)
{
parameters.Resolve (this);
base.Define (parent);
Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, null, ParameterInfo, ModFlags);
method_data = new MethodData (method, ModFlags, flags, this);
if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
return null;
Spec.SetMetaInfo (method_data.MethodBuilder);
return method_data.MethodBuilder;
}
public override TypeSpec ReturnType {
get {
return Parent.Compiler.BuiltinTypes.Void;
}
}
public override string[] ValidAttributeTargets {
get {
return attribute_targets;
}
}
}
static readonly string[] attribute_targets = new string[] { "property" };
public abstract class PropertyMethod : AbstractPropertyEventMethod
{
const Modifiers AllowedModifiers =
Modifiers.PUBLIC |
Modifiers.PROTECTED |
Modifiers.INTERNAL |
Modifiers.PRIVATE;
protected readonly PropertyBase method;
protected MethodAttributes flags;
public PropertyMethod (PropertyBase method, string prefix, Modifiers modifiers, Attributes attrs, Location loc)
: base (method, prefix, attrs, loc)
{
this.method = method;
this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, modifiers, 0, loc, Report);
this.ModFlags |= (method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE));
}
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
{
if (a.Type == pa.MethodImpl) {
method.is_external_implementation = a.IsInternalCall ();
}
base.ApplyAttributeBuilder (a, ctor, cdata, pa);
}
public override AttributeTargets AttributeTargets {
get {
return AttributeTargets.Method;
}
}
public override bool IsClsComplianceRequired ()
{
return method.IsClsComplianceRequired ();
}
public virtual MethodBuilder Define (TypeContainer parent)
{
var container = parent.PartialContainer;
//
// Check for custom access modifier
//
if ((ModFlags & Modifiers.AccessibilityMask) == 0) {
ModFlags |= method.ModFlags;
flags = method.flags;
} else {
if (container.Kind == MemberKind.Interface)
Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
GetSignatureForError ());
else if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
}
CheckModifiers (ModFlags);
ModFlags |= (method.ModFlags & (~Modifiers.AccessibilityMask));
ModFlags |= Modifiers.PROPERTY_CUSTOM;
flags = ModifiersExtensions.MethodAttr (ModFlags);
flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
}
CheckAbstractAndExtern (block != null);
CheckProtectedModifier ();
if (block != null) {
if (block.IsIterator)
Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
if (Compiler.Settings.WriteMetadataOnly)
block = null;
}
return null;
}
public bool HasCustomAccessModifier {
get {
return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
}
}
public PropertyBase Property {
get {
return method;
}
}
public override ObsoleteAttribute GetAttributeObsolete ()
{
return method.GetAttributeObsolete ();
}
public override string GetSignatureForError()
{
return method.GetSignatureForError () + "." + prefix.Substring (0, 3);
}
void CheckModifiers (Modifiers modflags)
{
if (!ModifiersExtensions.IsRestrictedModifier (modflags & Modifiers.AccessibilityMask, method.ModFlags & Modifiers.AccessibilityMask)) {
Report.Error (273, Location,
"The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
GetSignatureForError (), method.GetSignatureForError ());
}
}
}
PropertyMethod get, set, first;
PropertyBuilder PropertyBuilder;
public PropertyBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, Modifiers allowed_mod, MemberName name, Attributes attrs)
: base (parent, type, mod_flags, allowed_mod, name, attrs)
{
}
#region Properties
public override AttributeTargets AttributeTargets {
get {
return AttributeTargets.Property;
}
}
public PropertyMethod AccessorFirst {
get {
return first;
}
}
public PropertyMethod AccessorSecond {
get {
return first == get ? set : get;
}
}
public override Variance ExpectedMemberTypeVariance {
get {
return (get != null && set != null) ?
Variance.None : set == null ?
Variance.Covariant :
Variance.Contravariant;
}
}
public PropertyMethod Get {
get {
return get;
}
set {
get = value;
if (first == null)
first = value;
Parent.AddNameToContainer (get, get.MemberName.Basename);
}
}
public PropertyMethod Set {
get {
return set;
}
set {
set = value;
if (first == null)
first = value;
Parent.AddNameToContainer (set, set.MemberName.Basename);
}
}
public override string[] ValidAttributeTargets {
get {
return attribute_targets;
}
}
#endregion
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
{
if (a.HasSecurityAttribute) {
a.Error_InvalidSecurityParent ();
return;
}
if (a.Type == pa.Dynamic) {
a.Error_MisusedDynamicAttribute ();
return;
}
PropertyBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
}
void CheckMissingAccessor (MemberKind kind, ParametersCompiled parameters, bool get)
{
if (IsExplicitImpl) {
MemberFilter filter;
if (kind == MemberKind.Indexer)
filter = new MemberFilter (MemberCache.IndexerNameAlias, 0, kind, parameters, null);
else
filter = new MemberFilter (MemberName.Name, 0, kind, null, null);
var implementing = MemberCache.FindMember (InterfaceType, filter, BindingRestriction.DeclaredOnly) as PropertySpec;
if (implementing == null)
return;
var accessor = get ? implementing.Get : implementing.Set;
if (accessor != null) {
Report.SymbolRelatedToPreviousError (accessor);
Report.Error (551, Location, "Explicit interface implementation `{0}' is missing accessor `{1}'",
GetSignatureForError (), accessor.GetSignatureForError ());
}
}
}
protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
{
var ok = base.CheckOverrideAgainstBase (base_member);
//
// Check base property accessors conflict
//
var base_prop = (PropertySpec) base_member;
if (Get != null) {
if (!base_prop.HasGet) {
if (ok) {
Report.SymbolRelatedToPreviousError (base_prop);
Report.Error (545, Get.Location,
"`{0}': cannot override because `{1}' does not have an overridable get accessor",
Get.GetSignatureForError (), base_prop.GetSignatureForError ());
ok = false;
}
} else if (Get.HasCustomAccessModifier || base_prop.HasDifferentAccessibility) {
if (!CheckAccessModifiers (Get, base_prop.Get)) {
Error_CannotChangeAccessModifiers (Get, base_prop.Get);
ok = false;
}
}
}
if (Set != null) {
if (!base_prop.HasSet) {
if (ok) {
Report.SymbolRelatedToPreviousError (base_prop);
Report.Error (546, Set.Location,
"`{0}': cannot override because `{1}' does not have an overridable set accessor",
Set.GetSignatureForError (), base_prop.GetSignatureForError ());
ok = false;
}
} else if (Set.HasCustomAccessModifier || base_prop.HasDifferentAccessibility) {
if (!CheckAccessModifiers (Set, base_prop.Set)) {
Error_CannotChangeAccessModifiers (Set, base_prop.Set);
ok = false;
}
}
}
if ((Set == null || !Set.HasCustomAccessModifier) && (Get == null || !Get.HasCustomAccessModifier)) {
if (!CheckAccessModifiers (this, base_prop)) {
Error_CannotChangeAccessModifiers (this, base_prop);
ok = false;
}
}
return ok;
}
protected override void DoMemberTypeDependentChecks ()
{
base.DoMemberTypeDependentChecks ();
IsTypePermitted ();
if (MemberType.IsStatic)
Error_StaticReturnType ();
}
protected override void DoMemberTypeIndependentChecks ()
{
base.DoMemberTypeIndependentChecks ();
//
// Accessors modifiers check
//
if (AccessorSecond != null) {
if ((Get.ModFlags & Modifiers.AccessibilityMask) != 0 && (Set.ModFlags & Modifiers.AccessibilityMask) != 0) {
Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
GetSignatureForError ());
}
} else if ((ModFlags & Modifiers.OVERRIDE) == 0 &&
(Get == null && (Set.ModFlags & Modifiers.AccessibilityMask) != 0) ||
(Set == null && (Get.ModFlags & Modifiers.AccessibilityMask) != 0)) {
Report.Error (276, Location,
"`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
GetSignatureForError ());
}
}
protected bool DefineAccessors ()
{
first.Define (Parent);
if (AccessorSecond != null)
AccessorSecond.Define (Parent);
return true;
}
protected void DefineBuilders (MemberKind kind, ParametersCompiled parameters)
{
PropertyBuilder = Parent.TypeBuilder.DefineProperty (
GetFullName (MemberName), PropertyAttributes.None,
#if !BOOTSTRAP_BASIC // Requires trunk version mscorlib
IsStatic ? 0 : CallingConventions.HasThis,
#endif
MemberType.GetMetaInfo (), null, null,
parameters.GetMetaInfo (), null, null);
PropertySpec spec;
if (kind == MemberKind.Indexer)
spec = new IndexerSpec (Parent.Definition, this, MemberType, parameters, PropertyBuilder, ModFlags);
else
spec = new PropertySpec (kind, Parent.Definition, this, MemberType, PropertyBuilder, ModFlags);
if (Get != null) {
spec.Get = Get.Spec;
var method = Get.Spec.GetMetaInfo () as MethodBuilder;
if (method != null) {
PropertyBuilder.SetGetMethod (method);
Parent.MemberCache.AddMember (this, method.Name, Get.Spec);
}
} else {
CheckMissingAccessor (kind, parameters, true);
}
if (Set != null) {
spec.Set = Set.Spec;
var method = Set.Spec.GetMetaInfo () as MethodBuilder;
if (method != null) {
PropertyBuilder.SetSetMethod (method);
Parent.MemberCache.AddMember (this, method.Name, Set.Spec);
}
} else {
CheckMissingAccessor (kind, parameters, false);
}
Parent.MemberCache.AddMember (this, PropertyBuilder.Name, spec);
}
public override void Emit ()
{
CheckReservedNameConflict (GetMethod.Prefix, get == null ? null : get.Spec);
CheckReservedNameConflict (SetMethod.Prefix, set == null ? null : set.Spec);
if (OptAttributes != null)
OptAttributes.Emit ();
if (member_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder);
} else if (member_type.HasDynamicElement) {
Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder, member_type, Location);
}
ConstraintChecker.Check (this, member_type, type_expr.Location);
first.Emit (Parent);
if (AccessorSecond != null)
AccessorSecond.Emit (Parent);
base.Emit ();
}
public override bool IsUsed {
get {
if (IsExplicitImpl)
return true;
return Get.IsUsed | Set.IsUsed;
}
}
protected override void SetMemberName (MemberName new_name)
{
base.SetMemberName (new_name);
if (Get != null)
Get.UpdateName (this);
if (Set != null)
Set.UpdateName (this);
}
public override void WriteDebugSymbol (MonoSymbolFile file)
{
if (get != null)
get.WriteDebugSymbol (file);
if (set != null)
set.WriteDebugSymbol (file);
}
//
// Represents header string for documentation comment.
//
public override string DocCommentHeader {
get { return "P:"; }
}
}
public class Property : PropertyBase
{
public sealed class BackingField : Field
{
readonly Property property;
public BackingField (Property p)
: base (p.Parent, p.type_expr,
Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (p.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
new MemberName ("<" + p.GetFullName (p.MemberName) + ">k__BackingField", p.Location), null)
{
this.property = p;
}
public Property OriginalProperty {
get {
return property;
}
}
public override string GetSignatureForError ()
{
return property.GetSignatureForError ();
}
}
public Property (TypeDefinition parent, FullNamedExpression type, Modifiers mod,
MemberName name, Attributes attrs)
: base (parent, type, mod,
parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
AllowedModifiersClass,
name, attrs)
{
}
public override void Accept (StructuralVisitor visitor)
{
visitor.Visit (this);
}
void CreateAutomaticProperty ()
{
// Create backing field
Field field = new BackingField (this);
if (!field.Define ())
return;
Parent.PartialContainer.Members.Add (field);
FieldExpr fe = new FieldExpr (field, Location);
if ((field.ModFlags & Modifiers.STATIC) == 0)
fe.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
//
// Create get block but we careful with location to
// emit only single sequence point per accessor. This allow
// to set a breakpoint on it even with no user code
//
Get.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
Return r = new Return (fe, Get.Location);
Get.Block.AddStatement (r);
// Create set block
Set.Block = new ToplevelBlock (Compiler, Set.ParameterInfo, Location.Null);
Assign a = new SimpleAssign (fe, new SimpleName ("value", Location.Null), Location.Null);
Set.Block.AddStatement (new StatementExpression (a, Set.Location));
}
public override bool Define ()
{
if (!base.Define ())
return false;
flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
if (!IsInterface && (ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
AccessorSecond != null && Get.Block == null && Set.Block == null) {
if (Compiler.Settings.Version <= LanguageVersion.ISO_2)
Report.FeatureIsNotAvailable (Compiler, Location, "automatically implemented properties");
Get.ModFlags |= Modifiers.COMPILER_GENERATED;
Set.ModFlags |= Modifiers.COMPILER_GENERATED;
CreateAutomaticProperty ();
}
if (!DefineAccessors ())
return false;
if (AccessorSecond == null) {
PropertyMethod pm;
if (AccessorFirst is GetMethod)
pm = new SetMethod (this, 0, ParametersCompiled.EmptyReadOnlyParameters, null, Location);
else
pm = new GetMethod (this, 0, null, Location);
Parent.AddNameToContainer (pm, pm.MemberName.Basename);
}
if (!CheckBase ())
return false;
DefineBuilders (MemberKind.Property, ParametersCompiled.EmptyReadOnlyParameters);
return true;
}
public override void Emit ()
{
if ((AccessorFirst.ModFlags & (Modifiers.STATIC | Modifiers.COMPILER_GENERATED)) == Modifiers.COMPILER_GENERATED && Parent.PartialContainer.HasExplicitLayout) {
Report.Error (842, Location,
"Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
GetSignatureForError ());
}
base.Emit ();
}
}
/// <summary>
/// For case when event is declared like property (with add and remove accessors).
/// </summary>
public class EventProperty: Event {
public abstract class AEventPropertyAccessor : AEventAccessor
{
protected AEventPropertyAccessor (EventProperty method, string prefix, Attributes attrs, Location loc)
: base (method, prefix, attrs, loc)
{
}
public override MethodBuilder Define (TypeContainer ds)
{
CheckAbstractAndExtern (block != null);
return base.Define (ds);
}
public override string GetSignatureForError ()
{
return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
}
}
public sealed class AddDelegateMethod: AEventPropertyAccessor
{
public AddDelegateMethod (EventProperty method, Attributes attrs, Location loc)
: base (method, AddPrefix, attrs, loc)
{
}
}
public sealed class RemoveDelegateMethod: AEventPropertyAccessor
{
public RemoveDelegateMethod (EventProperty method, Attributes attrs, Location loc)
: base (method, RemovePrefix, attrs, loc)
{
}
}
static readonly string[] attribute_targets = new string [] { "event" };
public EventProperty (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
: base (parent, type, mod_flags, name, attrs)
{
}
public override void Accept (StructuralVisitor visitor)
{
visitor.Visit (this);
}
public override bool Define()
{
if (!base.Define ())
return false;
SetIsUsed ();
return true;
}
public override string[] ValidAttributeTargets {
get {
return attribute_targets;
}
}
}
/// <summary>
/// Event is declared like field.
/// </summary>
public class EventField : Event
{
abstract class EventFieldAccessor : AEventAccessor
{
protected EventFieldAccessor (EventField method, string prefix)
: base (method, prefix, null, method.Location)
{
}
protected abstract MethodSpec GetOperation (Location loc);
public override void Emit (TypeDefinition parent)
{
if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 && !Compiler.Settings.WriteMetadataOnly) {
block = new ToplevelBlock (Compiler, ParameterInfo, Location) {
IsCompilerGenerated = true
};
FabricateBodyStatement ();
}
base.Emit (parent);
}
void FabricateBodyStatement ()
{
//
// Delegate obj1 = backing_field
// do {
// Delegate obj2 = obj1;
// obj1 = Interlocked.CompareExchange (ref backing_field, Delegate.Combine|Remove(obj2, value), obj1);
// } while ((object)obj1 != (object)obj2)
//
var field_info = ((EventField) method).backing_field;
FieldExpr f_expr = new FieldExpr (field_info, Location);
if (!IsStatic)
f_expr.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
var obj1 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
var obj2 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
block.AddStatement (new StatementExpression (new SimpleAssign (new LocalVariableReference (obj1, Location), f_expr)));
var cond = new BooleanExpression (new Binary (Binary.Operator.Inequality,
new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj1, Location), Location),
new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj2, Location), Location)));
var body = new ExplicitBlock (block, Location, Location);
block.AddStatement (new Do (body, cond, Location, Location));
body.AddStatement (new StatementExpression (
new SimpleAssign (new LocalVariableReference (obj2, Location), new LocalVariableReference (obj1, Location))));
var args_oper = new Arguments (2);
args_oper.Add (new Argument (new LocalVariableReference (obj2, Location)));
args_oper.Add (new Argument (block.GetParameterReference (0, Location)));
var op_method = GetOperation (Location);
var args = new Arguments (3);
args.Add (new Argument (f_expr, Argument.AType.Ref));
args.Add (new Argument (new Cast (
new TypeExpression (field_info.MemberType, Location),
new Invocation (MethodGroupExpr.CreatePredefined (op_method, op_method.DeclaringType, Location), args_oper),
Location)));
args.Add (new Argument (new LocalVariableReference (obj1, Location)));
var cas = Module.PredefinedMembers.InterlockedCompareExchange_T.Resolve (Location);
if (cas == null)
return;
body.AddStatement (new StatementExpression (new SimpleAssign (
new LocalVariableReference (obj1, Location),
new Invocation (MethodGroupExpr.CreatePredefined (cas, cas.DeclaringType, Location), args))));
}
}
sealed class AddDelegateMethod: EventFieldAccessor
{
public AddDelegateMethod (EventField method):
base (method, AddPrefix)
{
}
protected override MethodSpec GetOperation (Location loc)
{
return Module.PredefinedMembers.DelegateCombine.Resolve (loc);
}
}
sealed class RemoveDelegateMethod: EventFieldAccessor
{
public RemoveDelegateMethod (EventField method):
base (method, RemovePrefix)
{
}
protected override MethodSpec GetOperation (Location loc)
{
return Module.PredefinedMembers.DelegateRemove.Resolve (loc);
}
}
static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
Expression initializer;
Field backing_field;
List<FieldDeclarator> declarators;
public EventField (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
: base (parent, type, mod_flags, name, attrs)
{
Add = new AddDelegateMethod (this);
Remove = new RemoveDelegateMethod (this);
}
#region Properties
public List<FieldDeclarator> Declarators {
get {
return this.declarators;
}
}
bool HasBackingField {
get {
return !IsInterface && (ModFlags & Modifiers.ABSTRACT) == 0;
}
}
public Expression Initializer {
get {
return initializer;
}
set {
initializer = value;
}
}
public override string[] ValidAttributeTargets {
get {
return HasBackingField ? attribute_targets : attribute_targets_interface;
}
}
#endregion
public override void Accept (StructuralVisitor visitor)
{
visitor.Visit (this);
}
public void AddDeclarator (FieldDeclarator declarator)
{
if (declarators == null)
declarators = new List<FieldDeclarator> (2);
declarators.Add (declarator);
Parent.AddNameToContainer (this, declarator.Name.Value);
}
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
{
if (a.Target == AttributeTargets.Field) {
backing_field.ApplyAttributeBuilder (a, ctor, cdata, pa);
return;
}
if (a.Target == AttributeTargets.Method) {
int errors = Report.Errors;
Add.ApplyAttributeBuilder (a, ctor, cdata, pa);
if (errors == Report.Errors)
Remove.ApplyAttributeBuilder (a, ctor, cdata, pa);
return;
}
base.ApplyAttributeBuilder (a, ctor, cdata, pa);
}
public override bool Define()
{
var mod_flags_src = ModFlags;
if (!base.Define ())
return false;
if (declarators != null) {
if ((mod_flags_src & Modifiers.DEFAULT_ACCESS_MODIFER) != 0)
mod_flags_src &= ~(Modifiers.AccessibilityMask | Modifiers.DEFAULT_ACCESS_MODIFER);
var t = new TypeExpression (MemberType, TypeExpression.Location);
foreach (var d in declarators) {
var ef = new EventField (Parent, t, mod_flags_src, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
if (d.Initializer != null)
ef.initializer = d.Initializer;
ef.Define ();
Parent.PartialContainer.Members.Add (ef);
}
}
if (!HasBackingField) {
SetIsUsed ();
return true;
}
if (Add.IsInterfaceImplementation)
SetIsUsed ();
backing_field = new Field (Parent,
new TypeExpression (MemberType, Location),
Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
MemberName, null);
Parent.PartialContainer.Members.Add (backing_field);
backing_field.Initializer = Initializer;
backing_field.ModFlags &= ~Modifiers.COMPILER_GENERATED;
// Call define because we passed fields definition
backing_field.Define ();
// Set backing field for event fields
spec.BackingField = backing_field.Spec;
return true;
}
}
public abstract class Event : PropertyBasedMember
{
public abstract class AEventAccessor : AbstractPropertyEventMethod
{
protected readonly Event method;
readonly ParametersCompiled parameters;
static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
public const string AddPrefix = "add_";
public const string RemovePrefix = "remove_";
protected AEventAccessor (Event method, string prefix, Attributes attrs, Location loc)
: base (method, prefix, attrs, loc)
{
this.method = method;
this.ModFlags = method.ModFlags;
this.parameters = ParametersCompiled.CreateImplicitParameter (method.TypeExpression, loc);
}
public bool IsInterfaceImplementation {
get { return method_data.implementing != null; }
}
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
{
if (a.Type == pa.MethodImpl) {
method.is_external_implementation = a.IsInternalCall ();
}
base.ApplyAttributeBuilder (a, ctor, cdata, pa);
}
protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
{
if (a.Target == AttributeTargets.Parameter) {
parameters[0].ApplyAttributeBuilder (a, ctor, cdata, pa);
return;
}
base.ApplyAttributeBuilder (a, ctor, cdata, pa);
}
public override AttributeTargets AttributeTargets {
get {
return AttributeTargets.Method;
}
}
public override bool IsClsComplianceRequired ()
{
return method.IsClsComplianceRequired ();
}
public virtual MethodBuilder Define (TypeContainer parent)
{
// Fill in already resolved event type to speed things up and
// avoid confusing duplicate errors
((Parameter) parameters.FixedParameters[0]).Type = method.member_type;
parameters.Types = new TypeSpec[] { method.member_type };
method_data = new MethodData (method, method.ModFlags,
method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
return null;
if (Compiler.Settings.WriteMetadataOnly)
block = null;
MethodBuilder mb = method_data.MethodBuilder;
Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, mb, ParameterInfo, method.ModFlags);
Spec.IsAccessor = true;
return mb;
}
public override TypeSpec ReturnType {
get {
return Parent.Compiler.BuiltinTypes.Void;
}
}
public override ObsoleteAttribute GetAttributeObsolete ()
{
return method.GetAttributeObsolete ();
}
public override string[] ValidAttributeTargets {
get {
return attribute_targets;
}
}
public override ParametersCompiled ParameterInfo {
get {
return parameters;
}
}
}
AEventAccessor add, remove;
EventBuilder EventBuilder;
protected EventSpec spec;
protected Event (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
: base (parent, type, mod_flags,
parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
AllowedModifiersClass,
name, attrs)
{
}
#region Properties
public override AttributeTargets AttributeTargets {
get {
return AttributeTargets.Event;
}
}
public AEventAccessor Add {
get {
return this.add;
}
set {
add = value;
Parent.AddNameToContainer (value, value.MemberName.Basename);
}
}
public override Variance ExpectedMemberTypeVariance {
get {
return Variance.Contravariant;
}
}
public AEventAccessor Remove {
get {
return this.remove;
}
set {
remove = value;
Parent.AddNameToContainer (value, value.MemberName.Basename);
}
}
#endregion
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
{
if ((a.HasSecurityAttribute)) {
a.Error_InvalidSecurityParent ();
return;
}
EventBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
}
protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
{
var ok = base.CheckOverrideAgainstBase (base_member);
if (!CheckAccessModifiers (this, base_member)) {
Error_CannotChangeAccessModifiers (this, base_member);
ok = false;
}
return ok;
}
public override bool Define ()
{
if (!base.Define ())
return false;
if (!MemberType.IsDelegate) {
Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
}
if (!CheckBase ())
return false;
//
// Now define the accessors
//
var AddBuilder = Add.Define (Parent);
if (AddBuilder == null)
return false;
var RemoveBuilder = remove.Define (Parent);
if (RemoveBuilder == null)
return false;
EventBuilder = Parent.TypeBuilder.DefineEvent (GetFullName (MemberName), EventAttributes.None, MemberType.GetMetaInfo ());
EventBuilder.SetAddOnMethod (AddBuilder);
EventBuilder.SetRemoveOnMethod (RemoveBuilder);
spec = new EventSpec (Parent.Definition, this, MemberType, ModFlags, Add.Spec, remove.Spec);
Parent.MemberCache.AddMember (this, GetFullName (MemberName), spec);
Parent.MemberCache.AddMember (this, AddBuilder.Name, Add.Spec);
Parent.MemberCache.AddMember (this, RemoveBuilder.Name, remove.Spec);
return true;
}
public override void Emit ()
{
CheckReservedNameConflict (null, add.Spec);
CheckReservedNameConflict (null, remove.Spec);
if (OptAttributes != null) {
OptAttributes.Emit ();
}
ConstraintChecker.Check (this, member_type, type_expr.Location);
Add.Emit (Parent);
Remove.Emit (Parent);
base.Emit ();
}
public override void WriteDebugSymbol (MonoSymbolFile file)
{
add.WriteDebugSymbol (file);
remove.WriteDebugSymbol (file);
}
//
// Represents header string for documentation comment.
//
public override string DocCommentHeader {
get { return "E:"; }
}
}
public class EventSpec : MemberSpec, IInterfaceMemberSpec
{
MethodSpec add, remove;
FieldSpec backing_field;
public EventSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec eventType, Modifiers modifiers, MethodSpec add, MethodSpec remove)
: base (MemberKind.Event, declaringType, definition, modifiers)
{
this.AccessorAdd = add;
this.AccessorRemove = remove;
this.MemberType = eventType;
}
#region Properties
public MethodSpec AccessorAdd {
get {
return add;
}
set {
add = value;
}
}
public MethodSpec AccessorRemove {
get {
return remove;
}
set {
remove = value;
}
}
public FieldSpec BackingField {
get {
return backing_field;
}
set {
backing_field = value;
}
}
public TypeSpec MemberType { get; private set; }
#endregion
public override MemberSpec InflateMember (TypeParameterInflator inflator)
{
var es = (EventSpec) base.InflateMember (inflator);
es.MemberType = inflator.Inflate (MemberType);
if (backing_field != null)
es.backing_field = (FieldSpec) backing_field.InflateMember (inflator);
return es;
}
public override List<TypeSpec> ResolveMissingDependencies ()
{
return MemberType.ResolveMissingDependencies ();
}
}
public class Indexer : PropertyBase, IParametersMember
{
public class GetIndexerMethod : GetMethod, IParametersMember
{
ParametersCompiled parameters;
public GetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
: base (property, modifiers, attrs, loc)
{
this.parameters = parameters;
}
public override MethodBuilder Define (TypeContainer parent)
{
// Disable reporting, parameters are resolved twice
Report.DisableReporting ();
try {
parameters.Resolve (this);
} finally {
Report.EnableReporting ();
}
return base.Define (parent);
}
public override ParametersCompiled ParameterInfo {
get {
return parameters;
}
}
#region IParametersMember Members
AParametersCollection IParametersMember.Parameters {
get {
return parameters;
}
}
TypeSpec IInterfaceMemberSpec.MemberType {
get {
return ReturnType;
}
}
#endregion
}
public class SetIndexerMethod : SetMethod, IParametersMember
{
public SetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
: base (property, modifiers, parameters, attrs, loc)
{
}
#region IParametersMember Members
AParametersCollection IParametersMember.Parameters {
get {
return parameters;
}
}
TypeSpec IInterfaceMemberSpec.MemberType {
get {
return ReturnType;
}
}
#endregion
}
const Modifiers AllowedModifiers =
Modifiers.NEW |
Modifiers.PUBLIC |
Modifiers.PROTECTED |
Modifiers.INTERNAL |
Modifiers.PRIVATE |
Modifiers.VIRTUAL |
Modifiers.SEALED |
Modifiers.OVERRIDE |
Modifiers.UNSAFE |
Modifiers.EXTERN |
Modifiers.ABSTRACT;
const Modifiers AllowedInterfaceModifiers =
Modifiers.NEW;
readonly ParametersCompiled parameters;
public Indexer (TypeDefinition parent, FullNamedExpression type, MemberName name, Modifiers mod, ParametersCompiled parameters, Attributes attrs)
: base (parent, type, mod,
parent.PartialContainer.Kind == MemberKind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
name, attrs)
{
this.parameters = parameters;
}
#region Properties
AParametersCollection IParametersMember.Parameters {
get {
return parameters;
}
}
public ParametersCompiled ParameterInfo {
get {
return parameters;
}
}
#endregion
public override void Accept (StructuralVisitor visitor)
{
visitor.Visit (this);
}
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
{
if (a.Type == pa.IndexerName) {
// Attribute was copied to container
return;
}
base.ApplyAttributeBuilder (a, ctor, cdata, pa);
}
protected override bool CheckForDuplications ()
{
return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
}
public override bool Define ()
{
if (!base.Define ())
return false;
if (!DefineParameters (parameters))
return false;
if (OptAttributes != null) {
Attribute indexer_attr = OptAttributes.Search (Module.PredefinedAttributes.IndexerName);
if (indexer_attr != null) {
var compiling = indexer_attr.Type.MemberDefinition as TypeContainer;
if (compiling != null)
compiling.Define ();
if (IsExplicitImpl) {
Report.Error (415, indexer_attr.Location,
"The `{0}' attribute is valid only on an indexer that is not an explicit interface member declaration",
indexer_attr.Type.GetSignatureForError ());
} else if ((ModFlags & Modifiers.OVERRIDE) != 0) {
Report.Error (609, indexer_attr.Location,
"Cannot set the `IndexerName' attribute on an indexer marked override");
} else {
string name = indexer_attr.GetIndexerAttributeValue ();
if (!string.IsNullOrEmpty (name)) {
SetMemberName (new MemberName (MemberName.Left, name, Location));
}
}
}
}
if (InterfaceType != null) {
string base_IndexerName = InterfaceType.MemberDefinition.GetAttributeDefaultMember ();
if (base_IndexerName != ShortName) {
SetMemberName (new MemberName (MemberName.Left, base_IndexerName, new TypeExpression (InterfaceType, Location), Location));
}
}
Parent.AddNameToContainer (this, MemberName.Basename);
flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
if (!DefineAccessors ())
return false;
if (!CheckBase ())
return false;
DefineBuilders (MemberKind.Indexer, parameters);
return true;
}
public override bool EnableOverloadChecks (MemberCore overload)
{
if (overload is Indexer) {
caching_flags |= Flags.MethodOverloadsExist;
return true;
}
return base.EnableOverloadChecks (overload);
}
public override void Emit ()
{
parameters.CheckConstraints (this);
base.Emit ();
}
public override string GetSignatureForError ()
{
StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
if (MemberName.ExplicitInterface != null) {
sb.Append (".");
sb.Append (MemberName.ExplicitInterface.GetSignatureForError ());
}
sb.Append (".this");
sb.Append (parameters.GetSignatureForError ("[", "]", parameters.Count));
return sb.ToString ();
}
public override string GetSignatureForDocumentation ()
{
return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
}
protected override bool VerifyClsCompliance ()
{
if (!base.VerifyClsCompliance ())
return false;
parameters.VerifyClsCompliance (this);
return true;
}
}
public class IndexerSpec : PropertySpec, IParametersMember
{
AParametersCollection parameters;
public IndexerSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, AParametersCollection parameters, PropertyInfo info, Modifiers modifiers)
: base (MemberKind.Indexer, declaringType, definition, memberType, info, modifiers)
{
this.parameters = parameters;
}
#region Properties
public AParametersCollection Parameters {
get {
return parameters;
}
}
#endregion
public override string GetSignatureForDocumentation ()
{
return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
}
public override string GetSignatureForError ()
{
return DeclaringType.GetSignatureForError () + ".this" + parameters.GetSignatureForError ("[", "]", parameters.Count);
}
public override MemberSpec InflateMember (TypeParameterInflator inflator)
{
var spec = (IndexerSpec) base.InflateMember (inflator);
spec.parameters = parameters.Inflate (inflator);
return spec;
}
public override List<TypeSpec> ResolveMissingDependencies ()
{
var missing = base.ResolveMissingDependencies ();
foreach (var pt in parameters.Types) {
var m = pt.GetMissingDependencies ();
if (m == null)
continue;
if (missing == null)
missing = new List<TypeSpec> ();
missing.AddRange (m);
}
return missing;
}
}
}
| |
/*
* Magix - A Web Application Framework for Humans
* Copyright 2010 - 2014 - thomas@magixilluminate.com
* Magix is licensed as MITx11, see enclosed License.txt File for Details.
*/
using System;
using System.IO;
using System.Collections.Generic;
using sys = System.Security.Cryptography.X509Certificates;
using sys2 = System.Security.Cryptography;
using MimeKit;
using MimeKit.Cryptography;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto;
using Magix.Core;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Prng;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Crypto.Parameters;
namespace Magix.cryptography
{
/*
* signs emails
*/
internal class CryptographyHelper
{
/*
* returns true if email address can sign email
*/
public static bool CanSign(string email)
{
try
{
MailboxAddress signer = new MailboxAddress("", email);
TextPart entity = new TextPart("text");
using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser))
{
MultipartSigned.Create(ctx, signer, DigestAlgorithm.Sha1, entity);
return true;
}
}
catch
{
return false;
}
}
/*
* returns true if email can be encrypted
*/
public static string CanEncrypt(Node emails)
{
if (emails.Count == 0)
return "there are no recipients";
try
{
List<MailboxAddress> list = new List<MailboxAddress>();
foreach (Node idx in emails)
list.Add(new MailboxAddress("", idx.Get<string>()));
TextPart entity = new TextPart("text");
using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser))
{
ApplicationPkcs7Mime.Encrypt(ctx, list, entity);
}
return null;
}
catch(Exception err)
{
return err.Message;
}
}
/*
* tries to sign a MimeEntity
*/
public static MimeEntity SignEntity(MimeEntity entity, MailboxAddress signer)
{
using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser))
{
return MultipartSigned.Create(ctx, signer, DigestAlgorithm.Sha1, entity);
}
}
/*
* tries to encrypt a MimeEntity
*/
public static MimeEntity EncryptEntity(MimeEntity entity, IEnumerable<MailboxAddress> list)
{
using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser))
{
return ApplicationPkcs7Mime.Encrypt(ctx, list, entity);
}
}
/*
* tries to sign and encrypt a MimeEntity
*/
public static MimeEntity SignAndEncryptEntity(MimeEntity entity, MailboxAddress signer, IEnumerable<MailboxAddress> list)
{
using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser))
{
return ApplicationPkcs7Mime.SignAndEncrypt(ctx, signer, DigestAlgorithm.Sha1, list, entity);
}
}
/*
* imports the given certificate file into certificate database
*/
public static void ImportCertificate(string certificateFile, string password)
{
Node getBase = new Node();
ActiveEvents.Instance.RaiseActiveEvent(
typeof(CryptographyHelper),
"magix.file.get-base-path",
getBase);
string basePath = getBase["path"].Get<string>();
using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser))
{
using (FileStream stream = File.OpenRead(basePath + certificateFile))
{
if (!string.IsNullOrEmpty(password))
ctx.Import(stream, password);
else
ctx.Import(stream);
}
}
}
/*
* creates a certificate and a private key and installs into windows registry
*/
public static void CreateCertificateKey(
string subjectName,
string issuerName,
string signatureAlgorithm,
int strength,
DateTime begin,
DateTime end,
string subjectCountryCode,
string subjectOrganization,
string subjectTitle,
string issuerCountryCode,
string issuerOrganization,
string issuerTitle,
string subjectCommonName,
string issuerCommonName)
{
// creating key pair
RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();
SecureRandom secureRandom = new SecureRandom(new CryptoApiRandomGenerator());
keyPairGenerator.Init(new KeyGenerationParameters(secureRandom, strength));
AsymmetricCipherKeyPair asCipherKeyPair = keyPairGenerator.GenerateKeyPair();
AsymmetricKeyParameter publicKey = asCipherKeyPair.Public;
RsaPrivateCrtKeyParameters privateKey = (RsaPrivateCrtKeyParameters)asCipherKeyPair.Private;
// initializing certificate generator
X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), secureRandom);
certificateGenerator.SetSerialNumber(serialNumber);
// setting subject name
string subjectNameString = "E=" + subjectName;
if (subjectCommonName != null)
subjectNameString += ", CN=" + subjectCommonName;
if (subjectCountryCode != null)
subjectNameString += ", C=" + subjectCountryCode;
if (subjectOrganization != null)
subjectNameString += ", O=" + subjectOrganization;
if (subjectTitle != null)
subjectNameString += ", T=" + subjectTitle;
certificateGenerator.SetSubjectDN(new X509Name(subjectNameString));
// setting issuer name
string issuerNameString = "E=" + issuerName;
if (issuerCommonName != null)
issuerNameString += ", CN=" + issuerCommonName;
if (issuerCountryCode != null)
issuerNameString += ", C=" + issuerCountryCode;
if (issuerOrganization != null)
issuerNameString += ", O=" + issuerOrganization;
if (issuerTitle != null)
issuerNameString += ", T=" + issuerTitle;
certificateGenerator.SetIssuerDN(new X509Name(issuerNameString));
// setting other properties of certificate
certificateGenerator.SetNotBefore(begin);
certificateGenerator.SetNotAfter(end);
certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
certificateGenerator.SetPublicKey(publicKey);
// setting key usage
KeyPurposeID[] usages = new KeyPurposeID[] { KeyPurposeID.IdKPEmailProtection };
certificateGenerator.AddExtension(
X509Extensions.ExtendedKeyUsage.Id,
false,
new ExtendedKeyUsage(usages));
// creating certificate and installing into certificate/key database
X509Certificate certificate = certificateGenerator.Generate(privateKey);
sys.X509Certificate2 windowsCertificate = new sys.X509Certificate2(DotNetUtilities.ToX509Certificate(certificate));
windowsCertificate.PrivateKey = ConvertToSystemKey(privateKey);
InstallIntoRegistry(windowsCertificate);
}
/*
* converts a bouncy castle private key to a windows private key
*/
private static sys2.AsymmetricAlgorithm ConvertToSystemKey(RsaPrivateCrtKeyParameters privateKey)
{
sys2.CspParameters cspPars = new sys2.CspParameters
{
KeyContainerName = Guid.NewGuid().ToString(),
KeyNumber = (int)sys2.KeyNumber.Exchange
};
sys2.RSACryptoServiceProvider rsaCryptoProvider = new sys2.RSACryptoServiceProvider(cspPars);
sys2.RSAParameters rsaParameters = new sys2.RSAParameters
{
Modulus = privateKey.Modulus.ToByteArrayUnsigned(),
P = privateKey.P.ToByteArrayUnsigned(),
Q = privateKey.Q.ToByteArrayUnsigned(),
DP = privateKey.DP.ToByteArrayUnsigned(),
DQ = privateKey.DQ.ToByteArrayUnsigned(),
InverseQ = privateKey.QInv.ToByteArrayUnsigned(),
D = privateKey.Exponent.ToByteArrayUnsigned(),
Exponent = privateKey.PublicExponent.ToByteArrayUnsigned()
};
rsaCryptoProvider.ImportParameters(rsaParameters);
return rsaCryptoProvider;
}
/*
* installs certificate and key into windows registry
*/
private static void InstallIntoRegistry(sys.X509Certificate2 windowsCertificate)
{
sys.X509Store store = new sys.X509Store();
store.Open(sys.OpenFlags.ReadWrite);
try
{
store.Add(windowsCertificate);
}
finally
{
store.Close();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.ApplicationParts;
using Orleans.CodeGeneration;
using Orleans.Configuration;
using Orleans.GrainDirectory;
using Orleans.Metadata;
using Orleans.Runtime.Placement;
using Orleans.Serialization;
using Orleans.Utilities;
namespace Orleans.Runtime
{
internal class GrainTypeManager
{
private Dictionary<SiloAddress, GrainInterfaceMap> grainInterfaceMapsBySilo;
private Dictionary<int, List<SiloAddress>> supportedSilosByTypeCode;
private readonly ILogger logger;
private readonly GrainInterfaceMap grainInterfaceMap;
private readonly Dictionary<string, GrainTypeData> grainTypes;
private readonly Dictionary<int, InvokerData> invokers;
private readonly SerializationManager serializationManager;
private readonly MultiClusterRegistrationStrategyManager multiClusterRegistrationStrategyManager;
private readonly PlacementStrategy defaultPlacementStrategy;
private Dictionary<int, Dictionary<ushort, List<SiloAddress>>> supportedSilosByInterface;
internal IReadOnlyDictionary<SiloAddress, GrainInterfaceMap> GrainInterfaceMapsBySilo => this.grainInterfaceMapsBySilo;
public IEnumerable<KeyValuePair<string, GrainTypeData>> GrainClassTypeData => this.grainTypes;
public GrainInterfaceMap ClusterGrainInterfaceMap { get; private set; }
public IGrainTypeResolver GrainTypeResolver { get; private set; }
public GrainTypeManager(
ILocalSiloDetails siloDetails,
IApplicationPartManager applicationPartManager,
PlacementStrategy defaultPlacementStrategy,
SerializationManager serializationManager,
MultiClusterRegistrationStrategyManager multiClusterRegistrationStrategyManager,
ILogger<GrainTypeManager> logger,
IOptions<GrainClassOptions> grainClassOptions)
{
var localTestMode = siloDetails.SiloAddress.Endpoint.Address.Equals(IPAddress.Loopback);
this.logger = logger;
this.defaultPlacementStrategy = defaultPlacementStrategy;
this.serializationManager = serializationManager;
this.multiClusterRegistrationStrategyManager = multiClusterRegistrationStrategyManager;
grainInterfaceMap = new GrainInterfaceMap(localTestMode, this.defaultPlacementStrategy);
ClusterGrainInterfaceMap = grainInterfaceMap;
GrainTypeResolver = grainInterfaceMap.GetGrainTypeResolver();
grainInterfaceMapsBySilo = new Dictionary<SiloAddress, GrainInterfaceMap>();
var grainClassFeature = applicationPartManager.CreateAndPopulateFeature<GrainClassFeature>();
this.grainTypes = CreateGrainTypeMap(grainClassFeature, grainClassOptions.Value);
var grainInterfaceFeature = applicationPartManager.CreateAndPopulateFeature<GrainInterfaceFeature>();
this.invokers = CreateInvokerMap(grainInterfaceFeature);
this.InitializeInterfaceMap();
}
public void Start()
{
LogGrainTypesFound(this.logger, this.grainTypes);
this.serializationManager.LogRegisteredTypes();
CrashUtils.GrainTypes = this.grainTypes.Keys.ToList();
}
public Dictionary<string, string> GetGrainInterfaceToClassMap()
{
return grainInterfaceMap.GetPrimaryImplementations();
}
internal bool TryGetPrimaryImplementation(string grainInterface, out string grainClass)
{
return grainInterfaceMap.TryGetPrimaryImplementation(grainInterface, out grainClass);
}
internal GrainTypeData this[string className]
{
get
{
string msg;
lock (this)
{
string grainType;
if (grainInterfaceMap.TryGetPrimaryImplementation(className, out grainType))
return grainTypes[grainType];
if (grainTypes.ContainsKey(className))
return grainTypes[className];
if (TypeUtils.IsGenericClass(className))
{
var templateName = TypeUtils.GetRawClassName(className);
if (grainInterfaceMap.TryGetPrimaryImplementation(templateName, out grainType))
templateName = grainType;
if (grainTypes.ContainsKey(templateName))
{
// Found the generic template class
try
{
// Instantiate the specific type from generic template
var genericGrainTypeData = (GenericGrainTypeData)grainTypes[templateName];
Type[] typeArgs = TypeUtils.GenericTypeArgsFromClassName(className);
var concreteTypeData = genericGrainTypeData.MakeGenericType(typeArgs);
// Add to lookup tables for next time
var grainClassName = concreteTypeData.GrainClass;
grainTypes.Add(grainClassName, concreteTypeData);
return concreteTypeData;
}
catch (Exception ex)
{
msg = "Cannot instantiate generic class " + className;
logger.Error(ErrorCode.Runtime_Error_100092, msg, ex);
throw new KeyNotFoundException(msg, ex);
}
}
}
}
msg = "Cannot find GrainTypeData for class " + className;
logger.Error(ErrorCode.Runtime_Error_100093, msg);
throw new TypeLoadException(msg);
}
}
internal void GetTypeInfo(int typeCode, out string grainClass, out PlacementStrategy placement, out MultiClusterRegistrationStrategy activationStrategy, string genericArguments = null)
{
if (!ClusterGrainInterfaceMap.TryGetTypeInfo(typeCode, out grainClass, out placement, out activationStrategy, genericArguments))
throw new OrleansException(string.Format("Unexpected: Cannot find an implementation class for grain interface {0}", typeCode));
}
internal void SetInterfaceMapsBySilo(Dictionary<SiloAddress, GrainInterfaceMap> value)
{
grainInterfaceMapsBySilo = value;
RebuildFullGrainInterfaceMap();
}
internal IReadOnlyList<SiloAddress> GetSupportedSilos(int typeCode)
{
return supportedSilosByTypeCode[typeCode];
}
internal IReadOnlyDictionary<ushort, IReadOnlyList<SiloAddress>> GetSupportedSilos(int typeCode, int ifaceId, IReadOnlyList<ushort> versions)
{
var result = new Dictionary<ushort, IReadOnlyList<SiloAddress>>();
foreach (var version in versions)
{
var silosWithTypeCode = supportedSilosByTypeCode[typeCode];
// We need to sort this so the list of silos returned will
// be the same accross all silos in the cluster
var silosWithCorrectVersion = supportedSilosByInterface[ifaceId][version]
.Intersect(silosWithTypeCode)
.OrderBy(addr => addr)
.ToList();
result[version] = silosWithCorrectVersion;
}
return result;
}
internal IReadOnlyList<ushort> GetAvailableVersions(int ifaceId)
{
return supportedSilosByInterface[ifaceId].Keys.ToList();
}
internal ushort GetLocalSupportedVersion(int ifaceId)
{
return grainInterfaceMap.GetInterfaceVersion(ifaceId);
}
private static Dictionary<int, InvokerData> CreateInvokerMap(GrainInterfaceFeature grainInterfaceFeature)
{
var result = new Dictionary<int, InvokerData>();
foreach (var grainInterfaceMetadata in grainInterfaceFeature.Interfaces)
{
int ifaceId = grainInterfaceMetadata.InterfaceId;
if (result.ContainsKey(ifaceId))
throw new InvalidOperationException($"Grain method invoker classes {result[ifaceId]} and {grainInterfaceMetadata.InvokerType.FullName} use the same interface id {ifaceId}");
result[ifaceId] = new InvokerData(grainInterfaceMetadata.InvokerType);
}
return result;
}
private void InitializeInterfaceMap()
{
foreach (GrainTypeData grainType in grainTypes.Values)
AddToGrainInterfaceToClassMap(grainType.Type, grainType.RemoteInterfaceTypes, grainType.IsStatelessWorker);
}
private void AddToGrainInterfaceToClassMap(Type grainClass, IEnumerable<Type> grainInterfaces, bool isUnordered)
{
var placement = GrainTypeData.GetPlacementStrategy(grainClass, this.defaultPlacementStrategy);
var registrationStrategy = this.multiClusterRegistrationStrategyManager.GetMultiClusterRegistrationStrategy(grainClass);
foreach (var iface in grainInterfaces)
{
var isPrimaryImplementor = IsPrimaryImplementor(grainClass, iface);
grainInterfaceMap.AddEntry(iface, grainClass, placement, registrationStrategy, isPrimaryImplementor);
}
if (isUnordered)
grainInterfaceMap.AddToUnorderedList(grainClass);
}
private static bool IsPrimaryImplementor(Type grainClass, Type iface)
{
// If the class name exactly matches the interface name, it is considered the primary (default)
// implementation of the interface, e.g. IFooGrain -> FooGrain
return (iface.Name.Substring(1) == grainClass.Name);
}
public bool TryGetData(string name, out GrainTypeData result)
{
return grainTypes.TryGetValue(name, out result);
}
internal GrainInterfaceMap GetTypeCodeMap()
{
// the map is immutable at this point
return grainInterfaceMap;
}
private void AddInvokerClass(int interfaceId, Type invoker)
{
lock (invokers)
{
if (!invokers.ContainsKey(interfaceId))
invokers.Add(interfaceId, new InvokerData(invoker));
}
}
/// <summary>
/// Returns a list of all graintypes in the system.
/// </summary>
/// <returns></returns>
internal string[] GetGrainTypeList()
{
return grainTypes.Keys.ToArray();
}
internal IGrainMethodInvoker GetInvoker(int interfaceId, string genericGrainType = null)
{
try
{
InvokerData invokerData;
if (invokers.TryGetValue(interfaceId, out invokerData))
return invokerData.GetInvoker(genericGrainType);
}
catch (Exception ex)
{
throw new OrleansException(String.Format("Error finding invoker for interface ID: {0} (0x{0, 8:X8}). {1}", interfaceId, ex), ex);
}
Type type;
var interfaceName = grainInterfaceMap.TryGetServiceInterface(interfaceId, out type) ?
type.FullName : "*unavailable*";
throw new OrleansException(String.Format("Cannot find an invoker for interface {0} (ID={1},0x{1, 8:X8}).",
interfaceName, interfaceId));
}
private void RebuildFullGrainInterfaceMap()
{
var newClusterGrainInterfaceMap = new GrainInterfaceMap(false, this.defaultPlacementStrategy);
var newSupportedSilosByTypeCode = new Dictionary<int, List<SiloAddress>>();
var newSupportedSilosByInterface = new Dictionary<int, Dictionary<ushort, List<SiloAddress>>>();
foreach (var kvp in grainInterfaceMapsBySilo)
{
newClusterGrainInterfaceMap.AddMap(kvp.Value);
foreach (var supportedInterface in kvp.Value.SupportedInterfaces)
{
var ifaceId = supportedInterface.InterfaceId;
var version = supportedInterface.InterfaceVersion;
var supportedSilosByVersion = newSupportedSilosByInterface.GetValueOrAddNew(ifaceId);
var supportedSilosForVersion = supportedSilosByVersion.GetValueOrAddNew(version);
supportedSilosForVersion.Add(kvp.Key);
}
foreach (var grainClassData in kvp.Value.SupportedGrainClassData)
{
var grainType = grainClassData.GrainTypeCode;
var supportedSilos = newSupportedSilosByTypeCode.GetValueOrAddNew(grainType);
supportedSilos.Add(kvp.Key);
}
}
foreach (var silos in newSupportedSilosByTypeCode.Values)
{
// We need to sort this so the list of silos returned will
// be the same accross all silos in the cluster
silos.Sort();
}
ClusterGrainInterfaceMap = newClusterGrainInterfaceMap;
GrainTypeResolver = ClusterGrainInterfaceMap.GetGrainTypeResolver();
supportedSilosByTypeCode = newSupportedSilosByTypeCode;
supportedSilosByInterface = newSupportedSilosByInterface;
}
private static Dictionary<string, GrainTypeData> CreateGrainTypeMap(GrainClassFeature grainClassFeature, GrainClassOptions grainClassOptions)
{
var result = new Dictionary<string, GrainTypeData>();
var excluded = grainClassOptions.ExcludedGrainTypes;
foreach (var grainClassMetadata in grainClassFeature.Classes)
{
var grainType = grainClassMetadata.ClassType;
var className = TypeUtils.GetFullName(grainType);
if (excluded != null && excluded.Contains(className)) continue;
var typeData = grainType.IsGenericTypeDefinition ?
new GenericGrainTypeData(grainType) :
new GrainTypeData(grainType);
result[className] = typeData;
}
return result;
}
internal static void LogGrainTypesFound(ILogger logger, IDictionary<string, GrainTypeData> grainTypeData)
{
var sb = new StringBuilder();
sb.AppendLine(String.Format("Loaded grain type summary for {0} types: ", grainTypeData.Count));
foreach (var grainType in grainTypeData.Values.OrderBy(gtd => gtd.Type.FullName))
{
// Skip system targets and Orleans grains
var assemblyName = grainType.Type.Assembly.FullName.Split(',')[0];
if (!typeof(ISystemTarget).IsAssignableFrom(grainType.Type))
{
int grainClassTypeCode = CodeGeneration.GrainInterfaceUtils.GetGrainClassTypeCode(grainType.Type);
sb.AppendFormat("Grain class {0}.{1} [{2} (0x{3})] from {4}.dll implementing interfaces: ",
grainType.Type.Namespace,
TypeUtils.GetTemplatedName(grainType.Type),
grainClassTypeCode,
grainClassTypeCode.ToString("X"),
assemblyName);
var first = true;
foreach (var iface in grainType.RemoteInterfaceTypes)
{
if (!first)
sb.Append(", ");
sb.Append(TypeUtils.GetTemplatedName(iface));
if (CodeGeneration.GrainInterfaceUtils.IsGrainType(iface))
{
int ifaceTypeCode = CodeGeneration.GrainInterfaceUtils.GetGrainInterfaceId(iface);
sb.AppendFormat(" [{0} (0x{1})]", ifaceTypeCode, ifaceTypeCode.ToString("X"));
}
first = false;
}
sb.AppendLine();
}
}
var report = sb.ToString();
logger.Info(ErrorCode.Loader_GrainTypeFullList, report);
}
private class InvokerData
{
private readonly Type baseInvokerType;
private readonly CachedReadConcurrentDictionary<string, IGrainMethodInvoker> cachedGenericInvokers;
private readonly bool isGeneric;
private IGrainMethodInvoker invoker;
public InvokerData(Type invokerType)
{
baseInvokerType = invokerType;
this.isGeneric = invokerType.IsGenericType;
if (this.isGeneric)
{
cachedGenericInvokers = new CachedReadConcurrentDictionary<string, IGrainMethodInvoker>();
}
}
public IGrainMethodInvoker GetInvoker(string genericGrainType = null)
{
// if the grain class is non-generic
if (!this.isGeneric)
{
return invoker ?? (invoker = (IGrainMethodInvoker)Activator.CreateInstance(baseInvokerType));
}
if (this.cachedGenericInvokers.TryGetValue(genericGrainType, out IGrainMethodInvoker result)) return result;
var typeArgs = TypeUtils.GenericTypeArgsFromArgsString(genericGrainType);
var concreteType = this.baseInvokerType.MakeGenericType(typeArgs);
var inv = (IGrainMethodInvoker)Activator.CreateInstance(concreteType);
this.cachedGenericInvokers.TryAdd(genericGrainType, inv);
return inv;
}
public override string ToString()
{
return $"InvokerType: {this.baseInvokerType}";
}
}
}
}
| |
// 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.IO;
using System.Collections.Generic;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Sys
{
private const int MountPointFormatBufferSizeInBytes = 32;
/// <summary>
/// Internal FileSystem names and magic numbers taken from man(2) statfs
/// </summary>
/// <remarks>
/// These value names MUST be kept in sync with those in GetDriveType below
/// </remarks>
internal enum UnixFileSystemTypes : long
{
adfs = 0xadf5,
affs = 0xADFF,
befs = 0x42465331,
bfs = 0x1BADFACE,
cifs = 0xFF534D42,
coda = 0x73757245,
coherent = 0x012FF7B7,
cramfs = 0x28cd3d45,
devfs = 0x1373,
efs = 0x00414A53,
ext = 0x137D,
ext2_old = 0xEF51,
ext2 = 0xEF53,
ext3 = 0xEF53,
ext4 = 0xEF53,
hfs = 0x4244,
hpfs = 0xF995E849,
hugetlbfs = 0x958458f6,
isofs = 0x9660,
jffs2 = 0x72b6,
jfs = 0x3153464a,
minix_old = 0x137F, /* orig. minix */
minix = 0x138F, /* 30 char minix */
minix2 = 0x2468, /* minix V2 */
minix2v2 = 0x2478, /* minix V2, 30 char names */
msdos = 0x4d44,
ncpfs = 0x564c,
nfs = 0x6969,
ntfs = 0x5346544e,
openprom = 0x9fa1,
proc = 0x9fa0,
qnx4 = 0x002f,
reiserfs = 0x52654973,
romfs = 0x7275,
smb = 0x517B,
sysv2 = 0x012FF7B6,
sysv4 = 0x012FF7B5,
tmpfs = 0x01021994,
udf = 0x15013346,
ufs = 0x00011954,
usbdevice = 0x9fa2,
vxfs = 0xa501FCF5,
xenix = 0x012FF7B4,
xfs = 0x58465342,
xiafs = 0x012FD16D,
}
[StructLayout(LayoutKind.Sequential)]
internal struct MountPointInformation
{
internal ulong AvailableFreeSpace;
internal ulong TotalFreeSpace;
internal ulong TotalSize;
}
[DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetSpaceInfoForMountPoint", SetLastError = true)]
internal static extern int GetSpaceInfoForMountPoint([MarshalAs(UnmanagedType.LPStr)]string name, out MountPointInformation mpi);
[DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetFormatInfoForMountPoint", SetLastError = true)]
private unsafe static extern int GetFormatInfoForMountPoint(
[MarshalAs(UnmanagedType.LPStr)]string name,
byte* formatNameBuffer,
int bufferLength,
long* formatType);
internal static int GetFormatInfoForMountPoint(string name, out string format)
{
DriveType temp;
return GetFormatInfoForMountPoint(name, out format, out temp);
}
internal static int GetFormatInfoForMountPoint(string name, out DriveType type)
{
string temp;
return GetFormatInfoForMountPoint(name, out temp, out type);
}
private static int GetFormatInfoForMountPoint(string name, out string format, out DriveType type)
{
unsafe
{
byte* formatBuffer = stackalloc byte[MountPointFormatBufferSizeInBytes]; // format names should be small
long numericFormat;
int result = GetFormatInfoForMountPoint(name, formatBuffer, MountPointFormatBufferSizeInBytes, &numericFormat);
if (result == 0)
{
// Check if we have a numeric answer or string
format = numericFormat != -1 ?
Enum.GetName(typeof(UnixFileSystemTypes), numericFormat) :
Marshal.PtrToStringAnsi((IntPtr)formatBuffer);
type = GetDriveType(format);
}
else
{
format = string.Empty;
type = DriveType.Unknown;
}
return result;
}
}
/// <summary>Categorizes a file system name into a drive type.</summary>
/// <param name="fileSystemName">The name to categorize.</param>
/// <returns>The recognized drive type.</returns>
private static DriveType GetDriveType(string fileSystemName)
{
// This list is based primarily on "man fs", "man mount", "mntent.h", "/proc/filesystems",
// and "wiki.debian.org/FileSystem". It can be extended over time as we
// find additional file systems that should be recognized as a particular drive type.
switch (fileSystemName)
{
case "iso":
case "isofs":
case "iso9660":
case "fuseiso":
case "fuseiso9660":
case "umview-mod-umfuseiso9660":
return DriveType.CDRom;
case "adfs":
case "affs":
case "befs":
case "bfs":
case "btrfs":
case "ecryptfs":
case "efs":
case "ext":
case "ext2":
case "ext2_old":
case "ext3":
case "ext4":
case "ext4dev":
case "fat":
case "fuseblk":
case "fuseext2":
case "fusefat":
case "hfs":
case "hfsplus":
case "hpfs":
case "jbd":
case "jbd2":
case "jfs":
case "jffs":
case "jffs2":
case "minix":
case "minix_old":
case "minix2":
case "minix2v2":
case "msdos":
case "ocfs2":
case "omfs":
case "openprom":
case "ntfs":
case "qnx4":
case "reiserfs":
case "squashfs":
case "swap":
case "sysv":
case "ubifs":
case "udf":
case "ufs":
case "umsdos":
case "umview-mod-umfuseext2":
case "xenix":
case "xfs":
case "xiafs":
case "xmount":
case "zfs-fuse":
return DriveType.Fixed;
case "9p":
case "autofs":
case "autofs4":
case "beaglefs":
case "cifs":
case "coda":
case "coherent":
case "curlftpfs":
case "davfs2":
case "dlm":
case "flickrfs":
case "fusedav":
case "fusesmb":
case "gfs2":
case "glusterfs-client":
case "gmailfs":
case "kafs":
case "ltspfs":
case "ncpfs":
case "nfs":
case "nfs4":
case "obexfs":
case "s3ql":
case "smb":
case "smbfs":
case "sshfs":
case "sysfs":
case "sysv2":
case "sysv4":
case "vxfs":
case "wikipediafs":
return DriveType.Network;
case "anon_inodefs":
case "aptfs":
case "avfs":
case "bdev":
case "binfmt_misc":
case "cgroup":
case "configfs":
case "cramfs":
case "cryptkeeper":
case "cpuset":
case "debugfs":
case "devfs":
case "devpts":
case "devtmpfs":
case "encfs":
case "fuse":
case "fuse.gvfsd-fuse":
case "fusectl":
case "hugetlbfs":
case "libpam-encfs":
case "ibpam-mount":
case "mtpfs":
case "mythtvfs":
case "mqueue":
case "pipefs":
case "plptools":
case "proc":
case "pstore":
case "pytagsfs":
case "ramfs":
case "rofs":
case "romfs":
case "rootfs":
case "securityfs":
case "sockfs":
case "tmpfs":
return DriveType.Ram;
case "gphotofs":
case "usbfs":
case "usbdevice":
case "vfat":
return DriveType.Removable;
case "aufs": // marking all unions as unknown
case "funionfs":
case "unionfs-fuse":
case "mhddfs":
default:
return DriveType.Unknown;
}
}
}
}
| |
// File generated from our OpenAPI spec
namespace Stripe
{
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Stripe.Infrastructure;
/// <summary>
/// A subscription schedule allows you to create and manage the lifecycle of a subscription
/// by predefining expected changes.
///
/// Related guide: <a
/// href="https://stripe.com/docs/billing/subscriptions/subscription-schedules">Subscription
/// Schedules</a>.
/// </summary>
public class SubscriptionSchedule : StripeEntity<SubscriptionSchedule>, IHasId, IHasMetadata, IHasObject
{
/// <summary>
/// Unique identifier for the object.
/// </summary>
[JsonProperty("id")]
public string Id { get; set; }
/// <summary>
/// String representing the object's type. Objects of the same type share the same value.
/// </summary>
[JsonProperty("object")]
public string Object { get; set; }
/// <summary>
/// Time at which the subscription schedule was canceled. Measured in seconds since the Unix
/// epoch.
/// </summary>
[JsonProperty("canceled_at")]
[JsonConverter(typeof(UnixDateTimeConverter))]
public DateTime? CanceledAt { get; set; }
/// <summary>
/// Time at which the subscription schedule was completed. Measured in seconds since the
/// Unix epoch.
/// </summary>
[JsonProperty("completed_at")]
[JsonConverter(typeof(UnixDateTimeConverter))]
public DateTime? CompletedAt { get; set; }
/// <summary>
/// Time at which the object was created. Measured in seconds since the Unix epoch.
/// </summary>
[JsonProperty("created")]
[JsonConverter(typeof(UnixDateTimeConverter))]
public DateTime Created { get; set; } = Stripe.Infrastructure.DateTimeUtils.UnixEpoch;
/// <summary>
/// Object representing the start and end dates for the current phase of the subscription
/// schedule, if it is <c>active</c>.
/// </summary>
[JsonProperty("current_phase")]
public SubscriptionScheduleCurrentPhase CurrentPhase { get; set; }
#region Expandable Customer
/// <summary>
/// (ID of the Customer)
/// ID of the customer who owns the subscription schedule.
/// </summary>
[JsonIgnore]
public string CustomerId
{
get => this.InternalCustomer?.Id;
set => this.InternalCustomer = SetExpandableFieldId(value, this.InternalCustomer);
}
/// <summary>
/// (Expanded)
/// ID of the customer who owns the subscription schedule.
///
/// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>.
/// </summary>
[JsonIgnore]
public Customer Customer
{
get => this.InternalCustomer?.ExpandedObject;
set => this.InternalCustomer = SetExpandableFieldObject(value, this.InternalCustomer);
}
[JsonProperty("customer")]
[JsonConverter(typeof(ExpandableFieldConverter<Customer>))]
internal ExpandableField<Customer> InternalCustomer { get; set; }
#endregion
[JsonProperty("default_settings")]
public SubscriptionScheduleDefaultSettings DefaultSettings { get; set; }
/// <summary>
/// Behavior of the subscription schedule and underlying subscription when it ends. Possible
/// values are <c>release</c> and <c>cancel</c>.
/// One of: <c>cancel</c>, <c>none</c>, <c>release</c>, or <c>renew</c>.
/// </summary>
[JsonProperty("end_behavior")]
public string EndBehavior { get; set; }
/// <summary>
/// Has the value <c>true</c> if the object exists in live mode or the value <c>false</c> if
/// the object exists in test mode.
/// </summary>
[JsonProperty("livemode")]
public bool Livemode { get; set; }
/// <summary>
/// Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can
/// attach to an object. This can be useful for storing additional information about the
/// object in a structured format.
/// </summary>
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
/// <summary>
/// Configuration for the subscription schedule's phases.
/// </summary>
[JsonProperty("phases")]
public List<SubscriptionSchedulePhase> Phases { get; set; }
/// <summary>
/// Time at which the subscription schedule was released. Measured in seconds since the Unix
/// epoch.
/// </summary>
[JsonProperty("released_at")]
[JsonConverter(typeof(UnixDateTimeConverter))]
public DateTime? ReleasedAt { get; set; }
/// <summary>
/// ID of the subscription once managed by the subscription schedule (if it is released).
/// </summary>
[JsonProperty("released_subscription")]
public string ReleasedSubscription { get; set; }
/// <summary>
/// The present status of the subscription schedule. Possible values are <c>not_started</c>,
/// <c>active</c>, <c>completed</c>, <c>released</c>, and <c>canceled</c>. You can read more
/// about the different states in our <a
/// href="https://stripe.com/docs/billing/subscriptions/subscription-schedules">behavior
/// guide</a>.
/// One of: <c>active</c>, <c>canceled</c>, <c>completed</c>, <c>not_started</c>, or
/// <c>released</c>.
/// </summary>
[JsonProperty("status")]
public string Status { get; set; }
#region Expandable Subscription
/// <summary>
/// (ID of the Subscription)
/// ID of the subscription managed by the subscription schedule.
/// </summary>
[JsonIgnore]
public string SubscriptionId
{
get => this.InternalSubscription?.Id;
set => this.InternalSubscription = SetExpandableFieldId(value, this.InternalSubscription);
}
/// <summary>
/// (Expanded)
/// ID of the subscription managed by the subscription schedule.
///
/// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>.
/// </summary>
[JsonIgnore]
public Subscription Subscription
{
get => this.InternalSubscription?.ExpandedObject;
set => this.InternalSubscription = SetExpandableFieldObject(value, this.InternalSubscription);
}
[JsonProperty("subscription")]
[JsonConverter(typeof(ExpandableFieldConverter<Subscription>))]
internal ExpandableField<Subscription> InternalSubscription { get; set; }
#endregion
#region Expandable TestClock
/// <summary>
/// (ID of the TestHelpers.TestClock)
/// ID of the test clock this subscription schedule belongs to.
/// </summary>
[JsonIgnore]
public string TestClockId
{
get => this.InternalTestClock?.Id;
set => this.InternalTestClock = SetExpandableFieldId(value, this.InternalTestClock);
}
/// <summary>
/// (Expanded)
/// ID of the test clock this subscription schedule belongs to.
///
/// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>.
/// </summary>
[JsonIgnore]
public TestHelpers.TestClock TestClock
{
get => this.InternalTestClock?.ExpandedObject;
set => this.InternalTestClock = SetExpandableFieldObject(value, this.InternalTestClock);
}
[JsonProperty("test_clock")]
[JsonConverter(typeof(ExpandableFieldConverter<TestHelpers.TestClock>))]
internal ExpandableField<TestHelpers.TestClock> InternalTestClock { get; set; }
#endregion
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Alerts.Alerts
File: AlertService.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Alerts
{
using System;
using System.IO;
using System.Linq;
using System.Speech.Synthesis;
using System.Windows.Media;
using Ecng.Collections;
using Ecng.Common;
using Ecng.ComponentModel;
using Ecng.Configuration;
using Ecng.Serialization;
using Ecng.Xaml;
using StockSharp.Community;
using StockSharp.Logging;
using StockSharp.Messages;
using StockSharp.Localization;
/// <summary>
/// Alert service.
/// </summary>
public class AlertService : Disposable, IAlertService
{
private readonly BlockingQueue<Tuple<AlertTypes, string, string, DateTimeOffset>> _alerts = new BlockingQueue<Tuple<AlertTypes, string, string, DateTimeOffset>>();
private readonly SynchronizedDictionary<Type, AlertSchema> _schemas = new SynchronizedDictionary<Type, AlertSchema>();
/// <summary>
/// Initializes a new instance of the <see cref="AlertService"/>.
/// </summary>
/// <param name="dumpDir">Temp files directory.</param>
public AlertService(string dumpDir)
{
if (dumpDir.IsEmpty())
throw new ArgumentNullException(nameof(dumpDir));
ThreadingHelper
.Thread(() =>
{
try
{
var player = new MediaPlayer();
var fileName = Path.Combine(dumpDir, "alert.mp3");
if (!File.Exists(fileName))
{
Directory.CreateDirectory(dumpDir);
Properties.Resources.Alert.Save(fileName);
}
player.Open(new Uri(fileName, UriKind.RelativeOrAbsolute));
var logManager = ConfigManager.GetService<LogManager>();
using (var speech = new SpeechSynthesizer())
using (var client = new NotificationClient())
using (player.MakeDisposable(p => p.Close()))
{
while (!IsDisposed)
{
Tuple<AlertTypes, string, string, DateTimeOffset> alert;
if (!_alerts.TryDequeue(out alert))
break;
try
{
switch (alert.Item1)
{
case AlertTypes.Sound:
player.Play();
break;
case AlertTypes.Speech:
speech.Speak(alert.Item2);
break;
case AlertTypes.Popup:
GuiDispatcher.GlobalDispatcher.AddAction(() => new AlertPopupWindow
{
Title = alert.Item2,
Message = alert.Item3,
Time = alert.Item4.UtcDateTime
}.Show());
break;
case AlertTypes.Sms:
client.SendSms(alert.Item2);
break;
case AlertTypes.Email:
client.SendEmail(alert.Item2, alert.Item3);
break;
case AlertTypes.Log:
logManager.Application.AddWarningLog(() => LocalizedStrings.Str3033Params
.Put(alert.Item4, alert.Item2, Environment.NewLine + alert.Item3));
break;
default:
throw new ArgumentOutOfRangeException();
}
}
catch (Exception ex)
{
ex.LogError();
}
}
}
}
catch (Exception ex)
{
ex.LogError();
}
})
.Name("Alert thread")
.Launch();
}
/// <summary>
/// Add alert at the output.
/// </summary>
/// <param name="type">Alert type.</param>
/// <param name="caption">Signal header.</param>
/// <param name="message">Alert text.</param>
/// <param name="time">Creation time.</param>
public void PushAlert(AlertTypes type, string caption, string message, DateTimeOffset time)
{
_alerts.Enqueue(Tuple.Create(type, caption, message, time));
}
/// <summary>
/// Register schema.
/// </summary>
/// <param name="schema">Schema.</param>
public void Register(AlertSchema schema)
{
if (schema == null)
throw new ArgumentNullException(nameof(schema));
_schemas[schema.MessageType] = schema;
}
/// <summary>
/// Remove previously registered by <see cref="Register"/> schema.
/// </summary>
/// <param name="schema">Schema.</param>
public void UnRegister(AlertSchema schema)
{
if (schema == null)
throw new ArgumentNullException(nameof(schema));
_schemas.Remove(schema.MessageType);
}
/// <summary>
/// Check message on alert conditions.
/// </summary>
/// <param name="message">Message.</param>
public void Process(Message message)
{
if (message == null)
throw new ArgumentNullException(nameof(message));
var schema = _schemas.TryGetValue(message.GetType());
var type = schema?.AlertType;
if (type == null)
return;
var canAlert = schema.Rules.All(rule =>
{
var value = rule.Property.GetValue(message, null);
switch (rule.Operator)
{
case ComparisonOperator.Equal:
return rule.Value.Equals(value);
case ComparisonOperator.NotEqual:
return !rule.Value.Equals(value);
case ComparisonOperator.Greater:
return OperatorRegistry.GetOperator(rule.Property.PropertyType).Compare(rule.Value, value) == 1;
case ComparisonOperator.GreaterOrEqual:
return OperatorRegistry.GetOperator(rule.Property.PropertyType).Compare(rule.Value, value) >= 0;
case ComparisonOperator.Less:
return OperatorRegistry.GetOperator(rule.Property.PropertyType).Compare(rule.Value, value) == -1;
case ComparisonOperator.LessOrEqual:
return OperatorRegistry.GetOperator(rule.Property.PropertyType).Compare(rule.Value, value) <= 0;
case ComparisonOperator.Any:
return true;
default:
throw new ArgumentOutOfRangeException();
}
});
if (canAlert)
PushAlert((AlertTypes)type, schema.Caption, schema.Message, message.LocalTime);
}
/// <summary>
/// Release resources.
/// </summary>
protected override void DisposeManaged()
{
_alerts.Close();
base.DisposeManaged();
}
}
}
| |
// 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.Xml;
using System.Xml.Linq;
using Microsoft.Test.ModuleCore;
using Xunit;
namespace CoreXml.Test.XLinq
{
public partial class XNodeReaderFunctionalTests : TestModule
{
public partial class XNodeReaderTests : XLinqTestCase
{
//[TestCase(Name = "ReadState", Desc = "ReadState")]
public partial class TCReadState : BridgeHelpers
{
//[Variation("XmlReader ReadState Initial", Priority = 0)]
public void ReadState1()
{
XDocument doc = new XDocument();
XmlReader r = doc.CreateReader();
if (r.ReadState != ReadState.Initial)
throw new TestFailedException("");
}
//[Variation("XmlReader ReadState Interactive", Priority = 0)]
public void ReadState2()
{
XDocument doc = XDocument.Parse("<a/>");
XmlReader r = doc.CreateReader();
while (r.Read())
{
if (r.ReadState != ReadState.Interactive)
throw new TestFailedException("");
else
return;
}
if (r.ReadState != ReadState.EndOfFile)
throw new TestFailedException("");
}
//[Variation("XmlReader ReadState EndOfFile", Priority = 0)]
public void ReadState3()
{
XDocument doc = new XDocument();
XmlReader r = doc.CreateReader();
while (r.Read()) { };
if (r.ReadState != ReadState.EndOfFile)
throw new TestFailedException("");
}
//[Variation("XmlReader ReadState Initial", Priority = 0)]
public void ReadState4()
{
XDocument doc = XDocument.Parse("<a/>");
XmlReader r = doc.CreateReader();
try
{
r.ReadContentAsInt();
}
catch (InvalidOperationException) { }
if (r.ReadState != ReadState.Initial)
throw new TestFailedException("");
}
//[Variation("XmlReader ReadState EndOfFile", Priority = 0)]
public void ReadState5()
{
XDocument doc = XDocument.Parse("<a/>");
XmlReader r = doc.CreateReader();
while (r.Read()) { };
try
{
r.ReadContentAsInt();
}
catch (InvalidOperationException) { }
if (r.ReadState != ReadState.EndOfFile)
throw new TestFailedException("");
}
}
//[TestCase(Name = "ReadInnerXml", Desc = "ReadInnerXml")]
public partial class TCReadInnerXml : BridgeHelpers
{
void VerifyNextNode(XmlReader DataReader, XmlNodeType nt, string name, string value)
{
while (DataReader.NodeType == XmlNodeType.Whitespace ||
DataReader.NodeType == XmlNodeType.SignificantWhitespace)
{
// skip all whitespace nodes
// if EOF is reached NodeType=None
DataReader.Read();
}
TestLog.Compare(VerifyNode(DataReader, nt, name, value), "VerifyNextNode");
}
//[Variation("ReadInnerXml on Empty Tag", Priority = 0)]
public void TestReadInnerXml1()
{
bool bPassed = false;
string strExpected = string.Empty;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "EMPTY1");
bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc);
BoolToLTMResult(bPassed);
}
//[Variation("ReadInnerXml on non Empty Tag", Priority = 0)]
public void TestReadInnerXml2()
{
bool bPassed = false;
string strExpected = string.Empty;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "EMPTY2");
bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc);
BoolToLTMResult(bPassed);
}
//[Variation("ReadInnerXml on non Empty Tag with text content", Priority = 0)]
public void TestReadInnerXml3()
{
bool bPassed = false;
string strExpected = "ABCDE";
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NONEMPTY1");
bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc);
BoolToLTMResult(bPassed);
}
//[Variation("ReadInnerXml with multiple Level of elements")]
public void TestReadInnerXml6()
{
bool bPassed = false;
string strExpected;
strExpected = "<ELEM1 /><ELEM2>xxx yyy</ELEM2><ELEM3 />";
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "SKIP3");
bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc);
VerifyNextNode(DataReader, XmlNodeType.Element, "AFTERSKIP3", string.Empty);
BoolToLTMResult(bPassed);
}
//[Variation("ReadInnerXml with multiple Level of elements, text and attributes", Priority = 0)]
public void TestReadInnerXml7()
{
bool bPassed = false;
string strExpected = "<e1 a1='a1value' a2='a2value'><e2 a1='a1value' a2='a2value'><e3 a1='a1value' a2='a2value'>leave</e3></e2></e1>";
strExpected = strExpected.Replace('\'', '"');
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "CONTENT");
bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc);
BoolToLTMResult(bPassed);
}
//[Variation("ReadInnerXml with entity references, EntityHandling = ExpandEntities")]
public void TestReadInnerXml8()
{
bool bPassed = false;
string strExpected = ST_EXPAND_ENTITIES2;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_ENTTEST_NAME);
bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc);
VerifyNextNode(DataReader, XmlNodeType.Element, "ENTITY2", string.Empty);
BoolToLTMResult(bPassed);
}
//[Variation("ReadInnerXml on attribute node", Priority = 0)]
public void TestReadInnerXml9()
{
bool bPassed = false;
string strExpected = "a1value";
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ATTRIBUTE2");
bPassed = DataReader.MoveToFirstAttribute();
bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc);
VerifyNextNode(DataReader, XmlNodeType.Attribute, "a1", strExpected);
BoolToLTMResult(bPassed);
}
//[Variation("ReadInnerXml on attribute node with entity reference in value", Priority = 0)]
public void TestReadInnerXml10()
{
bool bPassed = false;
string strExpected = ST_ENT1_ATT_EXPAND_CHAR_ENTITIES4;
string strExpectedAttValue = ST_ENT1_ATT_EXPAND_ENTITIES;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_ENTTEST_NAME);
bPassed = DataReader.MoveToFirstAttribute();
bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc);
VerifyNextNode(DataReader, XmlNodeType.Attribute, "att1", strExpectedAttValue);
BoolToLTMResult(bPassed);
}
//[Variation("ReadInnerXml on Text", Priority = 0)]
public void TestReadInnerXml11()
{
XmlNodeType nt;
string name;
string value;
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Text);
TestLog.Compare(DataReader.ReadInnerXml(), string.Empty, Variation.Desc);
// save status and compare with Read
nt = DataReader.NodeType;
name = DataReader.Name;
value = DataReader.Value;
DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Text);
DataReader.Read();
TestLog.Compare(VerifyNode(DataReader, nt, name, value), "vn");
}
//[Variation("ReadInnerXml on CDATA")]
public void TestReadInnerXml12()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.CDATA))
{
TestLog.Compare(DataReader.ReadInnerXml(), string.Empty, Variation.Desc);
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadInnerXml on ProcessingInstruction")]
public void TestReadInnerXml13()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.ProcessingInstruction))
{
TestLog.Compare(DataReader.ReadInnerXml(), string.Empty, Variation.Desc);
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadInnerXml on Comment")]
public void TestReadInnerXml14()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.Comment))
{
TestLog.Compare(DataReader.ReadInnerXml(), string.Empty, Variation.Desc);
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadInnerXml on EndElement")]
public void TestReadInnerXml16()
{
XmlReader DataReader = GetReader();
FindNodeType(DataReader, XmlNodeType.EndElement);
TestLog.Compare(DataReader.ReadInnerXml(), string.Empty, Variation.Desc);
}
//[Variation("ReadInnerXml on XmlDeclaration")]
public void TestReadInnerXml17()
{
XmlReader DataReader = GetReader();
TestLog.Compare(DataReader.ReadInnerXml(), string.Empty, Variation.Desc);
}
//[Variation("Current node after ReadInnerXml on element", Priority = 0)]
public void TestReadInnerXml18()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "SKIP2");
DataReader.ReadInnerXml();
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Element, "AFTERSKIP2", string.Empty), true, "VN");
}
//[Variation("Current node after ReadInnerXml on element")]
public void TestReadInnerXml19()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "MARKUP");
TestLog.Compare(DataReader.ReadInnerXml(), string.Empty, "RIX");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Text, string.Empty, "yyy"), true, "VN");
}
//[Variation("ReadInnerXml with entity references, EntityHandling = ExpandCharEntites")]
public void TestTextReadInnerXml2()
{
bool bPassed = false;
string strExpected = ST_EXPAND_ENTITIES2;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_ENTTEST_NAME);
bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc);
BoolToLTMResult(bPassed);
}
//[Variation("ReadInnerXml on EntityReference")]
public void TestTextReadInnerXml4()
{
XmlReader DataReader = GetReader();
TestLog.Compare(DataReader.ReadInnerXml(), string.Empty, Variation.Desc);
}
//[Variation("ReadInnerXml on EndEntity")]
public void TestTextReadInnerXml5()
{
XmlReader DataReader = GetReader();
TestLog.Compare(DataReader.ReadInnerXml(), string.Empty, Variation.Desc);
}
//[Variation("One large element")]
public void TestTextReadInnerXml18()
{
string strp = "a ";
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
string strxml = "<Name a=\"b\">" + strp + "</Name>";
XmlReader DataReader = GetReaderStr(strxml);
DataReader.Read();
TestLog.Compare(DataReader.ReadInnerXml(), strp, "rix");
}
}
//[TestCase(Name = "MoveToContent", Desc = "MoveToContent")]
public partial class TCMoveToContent : BridgeHelpers
{
public const string ST_TEST_NAME1 = "GOTOCONTENT";
public const string ST_TEST_NAME2 = "SKIPCONTENT";
public const string ST_TEST_NAME3 = "MIXCONTENT";
public const string ST_TEST_TEXT = "some text";
public const string ST_TEST_CDATA = "cdata info";
//[Variation("MoveToContent on Skip XmlDeclaration", Priority = 0)]
public void TestMoveToContent1()
{
XmlReader DataReader = GetReader();
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Element, Variation.Desc);
TestLog.Compare(DataReader.Name, "PLAY", Variation.Desc);
}
//[Variation("MoveToContent on Read through All valid Content Node(Element, Text, CDATA, and EndElement)", Priority = 0)]
public void TestMoveToContent2()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_NAME1);
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Element, Variation.Desc);
TestLog.Compare(DataReader.Name, ST_TEST_NAME1, "Element name");
DataReader.Read();
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Text, "Move to Text");
TestLog.Compare(DataReader.ReadContentAsString(), ST_TEST_TEXT + ST_TEST_CDATA, "Read String");
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.EndElement, "Move to EndElement");
TestLog.Compare(DataReader.Name, ST_TEST_NAME1, "EndElement value");
}
//[Variation("MoveToContent on Read through All invalid Content Node(PI, Comment and whitespace)", Priority = 0)]
public void TestMoveToContent3()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_NAME2);
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Element, Variation.Desc);
TestLog.Compare(DataReader.Name, ST_TEST_NAME2, "Element name");
DataReader.Read();
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Text, "Move to Text");
TestLog.Compare(DataReader.Name, "", "EndElement value");
}
//[Variation("MoveToContent on Read through Mix valid and Invalid Content Node")]
public void TestMoveToContent4()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_NAME3);
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Element, Variation.Desc);
TestLog.Compare(DataReader.Name, ST_TEST_NAME3, "Element name");
DataReader.Read();
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Text, "Move to Text");
DataReader.Read();
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Text, "Move to Text");
TestLog.Compare(DataReader.Value, ST_TEST_TEXT, "text value");
DataReader.Read();
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.CDATA, "Move to CDATA");
TestLog.Compare(DataReader.Name, "", "CDATA value");
DataReader.Read();
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.EndElement, "Move to EndElement");
TestLog.Compare(DataReader.Name, ST_TEST_NAME3, "EndElement value");
}
//[Variation("MoveToContent on Attribute", Priority = 0)]
public void TestMoveToContent5()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_NAME1);
PositionOnNodeType(DataReader, XmlNodeType.Attribute);
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Element, "Move to EndElement");
TestLog.Compare(DataReader.Name, ST_TEST_NAME2, "EndElement value");
}
}
//[TestCase(Name = "IsStartElement", Desc = "IsStartElement")]
public partial class TCIsStartElement : BridgeHelpers
{
private const string ST_TEST_ELEM = "DOCNAMESPACE";
private const string ST_TEST_EMPTY_ELEM = "NOSPACE";
private const string ST_TEST_ELEM_NS = "NAMESPACE1";
private const string ST_TEST_EMPTY_ELEM_NS = "EMPTY_NAMESPACE1";
//[Variation("IsStartElement on Regular Element, no namespace", Priority = 0)]
public void TestIsStartElement1()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM);
TestLog.Compare(DataReader.IsStartElement(), true, "IsStartElement()");
TestLog.Compare(DataReader.IsStartElement(ST_TEST_ELEM), true, "IsStartElement(n)");
TestLog.Compare(DataReader.IsStartElement(ST_TEST_ELEM, string.Empty), true, "IsStartElement(n,ns)");
}
//[Variation("IsStartElement on Empty Element, no namespace", Priority = 0)]
public void TestIsStartElement2()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM);
TestLog.Compare(DataReader.IsStartElement(), true, "IsStartElement()");
TestLog.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM), true, "IsStartElement(n)");
TestLog.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM, string.Empty), true, "IsStartElement(n,ns)");
}
//[Variation("IsStartElement on regular Element, with namespace", Priority = 0)]
public void TestIsStartElement3()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
TestLog.Compare(DataReader.IsStartElement(), true, "IsStartElement()");
TestLog.Compare(DataReader.IsStartElement("check", "1"), true, "IsStartElement(n,ns)");
TestLog.Compare(DataReader.IsStartElement("check", string.Empty), false, "IsStartElement(n)");
TestLog.Compare(DataReader.IsStartElement("check"), false, "IsStartElement2(n)");
TestLog.Compare(DataReader.IsStartElement("bar:check"), true, "IsStartElement(qname)");
TestLog.Compare(DataReader.IsStartElement("bar1:check"), false, "IsStartElement(invalid_qname)");
}
//[Variation("IsStartElement on Empty Tag, with default namespace", Priority = 0)]
public void TestIsStartElement4()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS);
TestLog.Compare(DataReader.IsStartElement(), true, "IsStartElement()");
TestLog.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM_NS, "14"), true, "IsStartElement(n,ns)");
TestLog.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM_NS, string.Empty), false, "IsStartElement(n)");
TestLog.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM_NS), true, "IsStartElement2(n)");
}
//[Variation("IsStartElement with Name=String.Empty")]
public void TestIsStartElement5()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM);
TestLog.Compare(DataReader.IsStartElement(string.Empty), false, Variation.Desc);
}
//[Variation("IsStartElement on Empty Element with Name and Namespace=String.Empty")]
public void TestIsStartElement6()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM);
TestLog.Compare(DataReader.IsStartElement(string.Empty, string.Empty), false, Variation.Desc);
}
//[Variation("IsStartElement on CDATA")]
public void TestIsStartElement7()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.CDATA);
TestLog.Compare(DataReader.IsStartElement(), false, Variation.Desc);
}
//[Variation("IsStartElement on EndElement, no namespace")]
public void TestIsStartElement8()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NONAMESPACE");
PositionOnNodeType(DataReader, XmlNodeType.EndElement);
TestLog.Compare(DataReader.IsStartElement(), false, "IsStartElement()");
TestLog.Compare(DataReader.IsStartElement("NONAMESPACE"), false, "IsStartElement(n)");
TestLog.Compare(DataReader.IsStartElement("NONAMESPACE", string.Empty), false, "IsStartElement(n,ns)");
}
//[Variation("IsStartElement on EndElement, with namespace")]
public void TestIsStartElement9()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
PositionOnNodeType(DataReader, XmlNodeType.EndElement);
TestLog.Compare(DataReader.IsStartElement(), false, "IsStartElement()");
TestLog.Compare(DataReader.IsStartElement("check", "1"), false, "IsStartElement(n,ns)");
TestLog.Compare(DataReader.IsStartElement("bar:check"), false, "IsStartElement(qname)");
}
//[Variation("IsStartElement on Attribute")]
public void TestIsStartElement10()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Attribute);
TestLog.Compare(DataReader.IsStartElement(), true, Variation.Desc);
TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, Variation.Desc);
}
//[Variation("IsStartElement on Text")]
public void TestIsStartElement11()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Text);
TestLog.Compare(DataReader.IsStartElement(), false, Variation.Desc);
}
//[Variation("IsStartElement on ProcessingInstruction")]
public void TestIsStartElement12()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.ProcessingInstruction);
TestLog.Compare(DataReader.IsStartElement(), true, Variation.Desc);
TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, Variation.Desc);
}
//[Variation("IsStartElement on Comment")]
public void TestIsStartElement13()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Comment);
TestLog.Compare(DataReader.IsStartElement(), true, Variation.Desc);
TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, Variation.Desc);
}
}
//[TestCase(Name = "ReadStartElement", Desc = "ReadStartElement")]
public partial class TCReadStartElement : BridgeHelpers
{
private const string ST_TEST_ELEM = "DOCNAMESPACE";
private const string ST_TEST_EMPTY_ELEM = "NOSPACE";
private const string ST_TEST_ELEM_NS = "NAMESPACE1";
private const string ST_TEST_EMPTY_ELEM_NS = "EMPTY_NAMESPACE1";
//[Variation("ReadStartElement on Regular Element, no namespace", Priority = 0)]
public void TestReadStartElement1()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM);
DataReader.ReadStartElement();
DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM);
DataReader.ReadStartElement(ST_TEST_ELEM);
DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM);
DataReader.ReadStartElement(ST_TEST_ELEM, string.Empty);
}
//[Variation("ReadStartElement on Empty Element, no namespace", Priority = 0)]
public void TestReadStartElement2()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM);
DataReader.ReadStartElement();
DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM);
DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM);
DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM);
DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM, string.Empty);
}
//[Variation("ReadStartElement on regular Element, with namespace", Priority = 0)]
public void TestReadStartElement3()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
DataReader.ReadStartElement();
DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
DataReader.ReadStartElement("check", "1");
DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
DataReader.ReadStartElement("bar:check");
}
//[Variation("Passing ns=String.EmptyErrorCase: ReadStartElement on regular Element, with namespace", Priority = 0)]
public void TestReadStartElement4()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
try
{
DataReader.ReadStartElement("check", string.Empty);
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("Passing no ns: ReadStartElement on regular Element, with namespace", Priority = 0)]
public void TestReadStartElement5()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
try
{
DataReader.ReadStartElement("check");
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement on Empty Tag, with namespace")]
public void TestReadStartElement6()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS);
DataReader.ReadStartElement();
DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS);
DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM_NS, "14");
}
//[Variation("ErrorCase: ReadStartElement on Empty Tag, with namespace, passing ns=String.Empty")]
public void TestReadStartElement7()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS);
try
{
DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM_NS, string.Empty);
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement on Empty Tag, with namespace, passing no ns")]
public void TestReadStartElement8()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS);
DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM_NS);
}
//[Variation("ReadStartElement with Name=String.Empty")]
public void TestReadStartElement9()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM);
try
{
DataReader.ReadStartElement(string.Empty);
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement on Empty Element with Name and Namespace=String.Empty")]
public void TestReadStartElement10()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS);
try
{
DataReader.ReadStartElement(string.Empty, string.Empty);
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement on CDATA")]
public void TestReadStartElement11()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.CDATA);
try
{
DataReader.ReadStartElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement() on EndElement, no namespace")]
public void TestReadStartElement12()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NONAMESPACE");
PositionOnNodeType(DataReader, XmlNodeType.EndElement);
try
{
DataReader.ReadStartElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement(n) on EndElement, no namespace")]
public void TestReadStartElement13()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NONAMESPACE");
PositionOnNodeType(DataReader, XmlNodeType.EndElement);
try
{
DataReader.ReadStartElement("NONAMESPACE");
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement(n, String.Empty) on EndElement, no namespace")]
public void TestReadStartElement14()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NONAMESPACE");
PositionOnNodeType(DataReader, XmlNodeType.EndElement);
try
{
DataReader.ReadStartElement("NONAMESPACE", string.Empty);
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement() on EndElement, with namespace")]
public void TestReadStartElement15()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
PositionOnNodeType(DataReader, XmlNodeType.EndElement);
try
{
DataReader.ReadStartElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement(n,ns) on EndElement, with namespace")]
public void TestReadStartElement16()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
PositionOnNodeType(DataReader, XmlNodeType.EndElement);
try
{
DataReader.ReadStartElement("check", "1");
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
}
//[TestCase(Name = "ReadEndElement", Desc = "ReadEndElement")]
public partial class TCReadEndElement : BridgeHelpers
{
private const string ST_TEST_ELEM = "DOCNAMESPACE";
private const string ST_TEST_EMPTY_ELEM = "NOSPACE";
private const string ST_TEST_ELEM_NS = "NAMESPACE1";
private const string ST_TEST_EMPTY_ELEM_NS = "EMPTY_NAMESPACE1";
[Fact]
public void TestReadEndElementOnEndElementWithoutNamespace()
{
using (XmlReader DataReader = GetPGenericXmlReader())
{
PositionOnElement(DataReader, "NONAMESPACE");
PositionOnNodeType(DataReader, XmlNodeType.EndElement);
Assert.True(VerifyNode(DataReader, XmlNodeType.EndElement, "NONAMESPACE", string.Empty));
}
}
[Fact]
public void TestReadEndElementOnEndElementWithNamespace()
{
using (XmlReader DataReader = GetPGenericXmlReader())
{
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
PositionOnNodeType(DataReader, XmlNodeType.EndElement);
Assert.True(VerifyNode(DataReader, XmlNodeType.EndElement, "bar:check", string.Empty));
}
}
//[Variation("ReadEndElement on Start Element, no namespace")]
private void TestReadEndElement3()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on Empty Element, no namespace", Priority = 0)]
private void TestReadEndElement4()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on regular Element, with namespace", Priority = 0)]
private void TestReadEndElement5()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on Empty Tag, with namespace", Priority = 0)]
private void TestReadEndElement6()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on CDATA")]
private void TestReadEndElement7()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.CDATA);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on Text")]
private void TestReadEndElement9()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Text);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on ProcessingInstruction")]
private void TestReadEndElement10()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.ProcessingInstruction);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on Comment")]
private void TestReadEndElement11()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Comment);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on XmlDeclaration")]
private void TestReadEndElement13()
{
XmlReader DataReader = GetReader();
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on EntityReference")]
private void TestTextReadEndElement1()
{
XmlReader DataReader = GetReader();
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on EndEntity")]
private void TestTextReadEndElement2()
{
XmlReader DataReader = GetReader();
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
}
public partial class TCMoveToElement : BridgeHelpers
{
//[Variation("Attribute node")]
public void v1()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "elem2");
DataReader.MoveToAttribute(1);
TestLog.Compare(DataReader.MoveToElement(), "MTE on elem2 failed");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Element, "elem2", string.Empty), "MTE moved on wrong node");
}
//[Variation("Element node")]
public void v2()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "elem2");
TestLog.Compare(!DataReader.MoveToElement(), "MTE on elem2 failed");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Element, "elem2", string.Empty), "MTE moved on wrong node");
}
//[Variation("Comment node")]
public void v5()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Comment);
TestLog.Compare(!DataReader.MoveToElement(), "MTE on comment failed");
TestLog.Compare(DataReader.NodeType, XmlNodeType.Comment, "comment");
}
}
}
}
}
| |
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 StudentSystem.WebApi.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using Apache.NMS.Util;
using Lucene.Net.Analysis.Tokenattributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Lucene.Net.Attributes;
using Lucene.Net.Codecs;
using Lucene.Net.Documents;
namespace Lucene.Net.Index
{
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Support;
using NUnit.Framework;
using Attribute = Lucene.Net.Util.Attribute;
using BytesRef = Lucene.Net.Util.BytesRef;
using CharTermAttribute = Lucene.Net.Analysis.Tokenattributes.CharTermAttribute;
using Codec = Lucene.Net.Codecs.Codec;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using FieldType = FieldType;
using FixedBitSet = Lucene.Net.Util.FixedBitSet;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using OffsetAttribute = Lucene.Net.Analysis.Tokenattributes.OffsetAttribute;
using PayloadAttribute = Lucene.Net.Analysis.Tokenattributes.PayloadAttribute;
using PositionIncrementAttribute = Lucene.Net.Analysis.Tokenattributes.PositionIncrementAttribute;
using SeekStatus = Lucene.Net.Index.TermsEnum.SeekStatus;
using StringField = StringField;
using TermQuery = Lucene.Net.Search.TermQuery;
using TestUtil = Lucene.Net.Util.TestUtil;
using TextField = TextField;
/*
* 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 TokenStream = Lucene.Net.Analysis.TokenStream;
/// <summary>
/// Base class aiming at testing <seealso cref="TermVectorsFormat"/>.
/// To test a new format, all you need is to register a new <seealso cref="Codec"/> which
/// uses it and extend this class and override <seealso cref="#getCodec()"/>.
/// @lucene.experimental
/// </summary>
public abstract class BaseTermVectorsFormatTestCase : BaseIndexFileFormatTestCase
{
/// <summary>
/// A combination of term vectors options.
/// </summary>
protected internal enum Options
{
NONE,//(false, false, false),
POSITIONS,//(true, false, false),
OFFSETS,//(false, true, false),
POSITIONS_AND_OFFSETS,//(true, true, false),
POSITIONS_AND_PAYLOADS,//(true, false, true),
POSITIONS_AND_OFFSETS_AND_PAYLOADS//(true, true, true);
// final boolean positions, offsets, payloads;
// private Options(boolean positions, boolean offsets, boolean payloads)
// {
// this.positions = positions;
// this.offsets = offsets;
// this.payloads = payloads;
// }
}
private class OptionsWrapper
{
public bool positions, offsets, payloads;
private void SetOptionsWrapper(bool positions, bool offsets, bool payloads)
{
this.positions = positions;
this.offsets = offsets;
this.payloads = payloads;
}
public OptionsWrapper(Options opt)
{
switch (opt)
{
case Options.NONE:
SetOptionsWrapper(false, false, false);
break;
case Options.POSITIONS:
SetOptionsWrapper(true, false, false);
break;
case Options.OFFSETS:
SetOptionsWrapper(false, true, false);
break;
case Options.POSITIONS_AND_OFFSETS:
SetOptionsWrapper(true, true, false);
break;
case Options.POSITIONS_AND_PAYLOADS:
SetOptionsWrapper(true, false, true);
break;
case Options.POSITIONS_AND_OFFSETS_AND_PAYLOADS:
SetOptionsWrapper(true, true, true);
break;
default:
throw new InvalidOperationException("Invalid Options enum type");
}
}
public static IEnumerable<Options> GetAsEnumer()
{
return Enum.GetValues(typeof(Options)).Cast<Options>();
}
public static IEnumerable<Options> GetAsEnumer(Options startInc, Options endInc)
{
foreach (Options opt in Enum.GetValues(typeof(Options)))
{
if (opt >= startInc && opt <= endInc)
yield return opt;
}
}
}
protected virtual IEnumerable<Options> ValidOptions()
{
return OptionsWrapper.GetAsEnumer();
}
protected virtual IEnumerable<Options> ValidOptions(Options startInc, Options endInc)
{
return OptionsWrapper.GetAsEnumer(startInc, endInc);
}
protected internal virtual Options RandomOptions()
{
return RandomInts.RandomFrom(Random(), new List<Options>(ValidOptions()));
}
protected internal virtual FieldType FieldType(Options options)
{
var ft = new FieldType(TextField.TYPE_NOT_STORED)
{
StoreTermVectors = true,
StoreTermVectorPositions = (new OptionsWrapper(options)).positions,
StoreTermVectorOffsets = (new OptionsWrapper(options)).offsets,
StoreTermVectorPayloads = (new OptionsWrapper(options)).payloads
};
ft.Freeze();
return ft;
}
protected internal virtual BytesRef RandomPayload()
{
int len = Random().Next(5);
if (len == 0)
{
return null;
}
BytesRef payload = new BytesRef(len);
Random().NextBytes((byte[])(Array)payload.Bytes);
payload.Length = len;
return payload;
}
protected internal override void AddRandomFields(Document doc)
{
foreach (Options opts in ValidOptions())
{
FieldType ft = FieldType(opts);
int numFields = Random().Next(5);
for (int j = 0; j < numFields; ++j)
{
doc.Add(new Field("f_" + opts, TestUtil.RandomSimpleString(Random(), 2), ft));
}
}
}
// custom impl to test cases that are forbidden by the default OffsetAttribute impl
private class PermissiveOffsetAttributeImpl : Attribute, IOffsetAttribute
{
internal int Start, End;
public int StartOffset()
{
return Start;
}
public int EndOffset()
{
return End;
}
public void SetOffset(int startOffset, int endOffset)
{
// no check!
Start = startOffset;
End = endOffset;
}
public override void Clear()
{
Start = End = 0;
}
public override bool Equals(object other)
{
if (other == this)
{
return true;
}
if (other is PermissiveOffsetAttributeImpl)
{
PermissiveOffsetAttributeImpl o = (PermissiveOffsetAttributeImpl)other;
return o.Start == Start && o.End == End;
}
return false;
}
public override int GetHashCode()
{
return Start + 31 * End;
}
public override void CopyTo(Attribute target)
{
OffsetAttribute t = (OffsetAttribute)target;
t.SetOffset(Start, End);
}
}
// TODO: use CannedTokenStream?
protected internal class RandomTokenStream : TokenStream
{
private readonly BaseTermVectorsFormatTestCase OuterInstance;
internal readonly string[] Terms;
internal readonly BytesRef[] TermBytes;
internal readonly int[] PositionsIncrements;
internal readonly int[] Positions;
internal readonly int[] StartOffsets, EndOffsets;
internal readonly BytesRef[] Payloads;
internal readonly IDictionary<string, int?> Freqs;
internal readonly IDictionary<int?, ISet<int?>> PositionToTerms;
internal readonly IDictionary<int?, ISet<int?>> StartOffsetToTerms;
internal readonly ICharTermAttribute TermAtt;
internal readonly IPositionIncrementAttribute PiAtt;
internal readonly IOffsetAttribute OAtt;
internal readonly IPayloadAttribute PAtt;
internal int i = 0;
protected internal RandomTokenStream(BaseTermVectorsFormatTestCase outerInstance, int len, string[] sampleTerms, BytesRef[] sampleTermBytes)
: this(outerInstance, len, sampleTerms, sampleTermBytes, Rarely())
{
this.OuterInstance = outerInstance;
}
protected internal RandomTokenStream(BaseTermVectorsFormatTestCase outerInstance, int len, string[] sampleTerms, BytesRef[] sampleTermBytes, bool offsetsGoBackwards)
{
this.OuterInstance = outerInstance;
Terms = new string[len];
TermBytes = new BytesRef[len];
PositionsIncrements = new int[len];
Positions = new int[len];
StartOffsets = new int[len];
EndOffsets = new int[len];
Payloads = new BytesRef[len];
for (int i = 0; i < len; ++i)
{
int o = Random().Next(sampleTerms.Length);
Terms[i] = sampleTerms[o];
TermBytes[i] = sampleTermBytes[o];
PositionsIncrements[i] = TestUtil.NextInt(Random(), i == 0 ? 1 : 0, 10);
if (offsetsGoBackwards)
{
StartOffsets[i] = Random().Next();
EndOffsets[i] = Random().Next();
}
else
{
if (i == 0)
{
StartOffsets[i] = TestUtil.NextInt(Random(), 0, 1 << 16);
}
else
{
StartOffsets[i] = StartOffsets[i - 1] + TestUtil.NextInt(Random(), 0, Rarely() ? 1 << 16 : 20);
}
EndOffsets[i] = StartOffsets[i] + TestUtil.NextInt(Random(), 0, Rarely() ? 1 << 10 : 20);
}
}
for (int i = 0; i < len; ++i)
{
if (i == 0)
{
Positions[i] = PositionsIncrements[i] - 1;
}
else
{
Positions[i] = Positions[i - 1] + PositionsIncrements[i];
}
}
if (Rarely())
{
Arrays.Fill(Payloads, outerInstance.RandomPayload());
}
else
{
for (int i = 0; i < len; ++i)
{
Payloads[i] = outerInstance.RandomPayload();
}
}
PositionToTerms = new Dictionary<int?, ISet<int?>>(len);
StartOffsetToTerms = new Dictionary<int?, ISet<int?>>(len);
for (int i = 0; i < len; ++i)
{
if (!PositionToTerms.ContainsKey(Positions[i]))
{
PositionToTerms[Positions[i]] = new HashSet<int?>();//size1
}
PositionToTerms[Positions[i]].Add(i);
if (!StartOffsetToTerms.ContainsKey(StartOffsets[i]))
{
StartOffsetToTerms[StartOffsets[i]] = new HashSet<int?>();//size1
}
StartOffsetToTerms[StartOffsets[i]].Add(i);
}
Freqs = new Dictionary<string, int?>();
foreach (string term in Terms)
{
if (Freqs.ContainsKey(term))
{
Freqs[term] = Freqs[term] + 1;
}
else
{
Freqs[term] = 1;
}
}
AddAttributeImpl(new PermissiveOffsetAttributeImpl());
TermAtt = AddAttribute<ICharTermAttribute>();
PiAtt = AddAttribute<IPositionIncrementAttribute>();
OAtt = AddAttribute<IOffsetAttribute>();
PAtt = AddAttribute<IPayloadAttribute>();
}
public virtual bool HasPayloads()
{
foreach (BytesRef payload in Payloads)
{
if (payload != null && payload.Length > 0)
{
return true;
}
}
return false;
}
public sealed override bool IncrementToken()
{
if (i < Terms.Length)
{
TermAtt.SetLength(0).Append(Terms[i]);
PiAtt.PositionIncrement = PositionsIncrements[i];
OAtt.SetOffset(StartOffsets[i], EndOffsets[i]);
PAtt.Payload = Payloads[i];
++i;
return true;
}
else
{
return false;
}
}
}
protected internal class RandomDocument
{
private readonly BaseTermVectorsFormatTestCase OuterInstance;
internal readonly string[] FieldNames;
internal readonly FieldType[] FieldTypes;
internal readonly RandomTokenStream[] TokenStreams;
protected internal RandomDocument(BaseTermVectorsFormatTestCase outerInstance, int fieldCount, int maxTermCount, Options options, string[] fieldNames, string[] sampleTerms, BytesRef[] sampleTermBytes)
{
this.OuterInstance = outerInstance;
if (fieldCount > fieldNames.Length)
{
throw new System.ArgumentException();
}
this.FieldNames = new string[fieldCount];
FieldTypes = new FieldType[fieldCount];
TokenStreams = new RandomTokenStream[fieldCount];
Arrays.Fill(FieldTypes, outerInstance.FieldType(options));
HashSet<string> usedFileNames = new HashSet<string>();
for (int i = 0; i < fieldCount; ++i)
{
do
{
this.FieldNames[i] = RandomInts.RandomFrom(Random(), fieldNames);
} while (usedFileNames.Contains(this.FieldNames[i]));
usedFileNames.Add(this.FieldNames[i]);
TokenStreams[i] = new RandomTokenStream(outerInstance, TestUtil.NextInt(Random(), 1, maxTermCount), sampleTerms, sampleTermBytes);
}
}
public virtual Document ToDocument()
{
Document doc = new Document();
for (int i = 0; i < FieldNames.Length; ++i)
{
doc.Add(new Field(FieldNames[i], TokenStreams[i], FieldTypes[i]));
}
return doc;
}
}
protected internal class RandomDocumentFactory
{
private readonly BaseTermVectorsFormatTestCase OuterInstance;
internal readonly string[] FieldNames;
internal readonly string[] Terms;
internal readonly BytesRef[] TermBytes;
protected internal RandomDocumentFactory(BaseTermVectorsFormatTestCase outerInstance, int distinctFieldNames, int disctinctTerms)
{
this.OuterInstance = outerInstance;
HashSet<string> fieldNames = new HashSet<string>();
while (fieldNames.Count < distinctFieldNames)
{
fieldNames.Add(TestUtil.RandomSimpleString(Random()));
fieldNames.Remove("id");
}
this.FieldNames = fieldNames.ToArray(/*new string[0]*/);
Terms = new string[disctinctTerms];
TermBytes = new BytesRef[disctinctTerms];
for (int i = 0; i < disctinctTerms; ++i)
{
Terms[i] = TestUtil.RandomRealisticUnicodeString(Random());
TermBytes[i] = new BytesRef(Terms[i]);
}
}
public virtual RandomDocument NewDocument(int fieldCount, int maxTermCount, Options options)
{
return new RandomDocument(OuterInstance, fieldCount, maxTermCount, options, FieldNames, Terms, TermBytes);
}
}
protected internal virtual void AssertEquals(RandomDocument doc, Fields fields)
{
// compare field names
Assert.AreEqual(doc == null, fields == null);
Assert.AreEqual(doc.FieldNames.Length, fields.Size);
HashSet<string> fields1 = new HashSet<string>();
HashSet<string> fields2 = new HashSet<string>();
for (int i = 0; i < doc.FieldNames.Length; ++i)
{
fields1.Add(doc.FieldNames[i]);
}
foreach (string field in fields)
{
fields2.Add(field);
}
Assert.IsTrue(fields1.SetEquals(fields2));
for (int i = 0; i < doc.FieldNames.Length; ++i)
{
AssertEquals(doc.TokenStreams[i], doc.FieldTypes[i], fields.Terms(doc.FieldNames[i]));
}
}
protected internal static bool Equals(object o1, object o2)
{
if (o1 == null)
{
return o2 == null;
}
else
{
return o1.Equals(o2);
}
}
// to test reuse
private readonly ThreadLocal<TermsEnum> termsEnum = new ThreadLocal<TermsEnum>();
private readonly ThreadLocal<DocsEnum> docsEnum = new ThreadLocal<DocsEnum>();
private readonly ThreadLocal<DocsAndPositionsEnum> docsAndPositionsEnum = new ThreadLocal<DocsAndPositionsEnum>();
protected internal virtual void AssertEquals(RandomTokenStream tk, FieldType ft, Terms terms)
{
Assert.AreEqual(1, terms.DocCount);
int termCount = (new HashSet<string>(Arrays.AsList(tk.Terms))).Count;
Assert.AreEqual(termCount, terms.Size());
Assert.AreEqual(termCount, terms.SumDocFreq);
Assert.AreEqual(ft.StoreTermVectorPositions, terms.HasPositions());
Assert.AreEqual(ft.StoreTermVectorOffsets, terms.HasOffsets());
Assert.AreEqual(ft.StoreTermVectorPayloads && tk.HasPayloads(), terms.HasPayloads());
HashSet<BytesRef> uniqueTerms = new HashSet<BytesRef>();
foreach (string term in tk.Freqs.Keys)
{
uniqueTerms.Add(new BytesRef(term));
}
BytesRef[] sortedTerms = uniqueTerms.ToArray(/*new BytesRef[0]*/);
Array.Sort(sortedTerms, terms.Comparator);
TermsEnum termsEnum = terms.Iterator(Random().NextBoolean() ? null : this.termsEnum.Value);
this.termsEnum.Value = termsEnum;
for (int i = 0; i < sortedTerms.Length; ++i)
{
BytesRef nextTerm = termsEnum.Next();
Assert.AreEqual(sortedTerms[i], nextTerm);
Assert.AreEqual(sortedTerms[i], termsEnum.Term());
Assert.AreEqual(1, termsEnum.DocFreq());
FixedBitSet bits = new FixedBitSet(1);
DocsEnum docsEnum = termsEnum.Docs(bits, Random().NextBoolean() ? null : this.docsEnum.Value);
Assert.AreEqual(DocsEnum.NO_MORE_DOCS, docsEnum.NextDoc());
bits.Set(0);
docsEnum = termsEnum.Docs(Random().NextBoolean() ? bits : null, Random().NextBoolean() ? null : docsEnum);
Assert.IsNotNull(docsEnum);
Assert.AreEqual(0, docsEnum.NextDoc());
Assert.AreEqual(0, docsEnum.DocID());
Assert.AreEqual(tk.Freqs[termsEnum.Term().Utf8ToString()], (int?)docsEnum.Freq());
Assert.AreEqual(DocsEnum.NO_MORE_DOCS, docsEnum.NextDoc());
this.docsEnum.Value = docsEnum;
bits.Clear(0);
DocsAndPositionsEnum docsAndPositionsEnum = termsEnum.DocsAndPositions(bits, Random().NextBoolean() ? null : this.docsAndPositionsEnum.Value);
Assert.AreEqual(ft.StoreTermVectorOffsets || ft.StoreTermVectorPositions, docsAndPositionsEnum != null);
if (docsAndPositionsEnum != null)
{
Assert.AreEqual(DocsEnum.NO_MORE_DOCS, docsAndPositionsEnum.NextDoc());
}
bits.Set(0);
docsAndPositionsEnum = termsEnum.DocsAndPositions(Random().NextBoolean() ? bits : null, Random().NextBoolean() ? null : docsAndPositionsEnum);
Assert.AreEqual(ft.StoreTermVectorOffsets || ft.StoreTermVectorPositions, docsAndPositionsEnum != null);
if (terms.HasPositions() || terms.HasOffsets())
{
Assert.AreEqual(0, docsAndPositionsEnum.NextDoc());
int freq = docsAndPositionsEnum.Freq();
Assert.AreEqual(tk.Freqs[termsEnum.Term().Utf8ToString()], (int?)freq);
if (docsAndPositionsEnum != null)
{
for (int k = 0; k < freq; ++k)
{
int position = docsAndPositionsEnum.NextPosition();
ISet<int?> indexes;
if (terms.HasPositions())
{
indexes = tk.PositionToTerms[position];
Assert.IsNotNull(indexes);
}
else
{
indexes = tk.StartOffsetToTerms[docsAndPositionsEnum.StartOffset()];
Assert.IsNotNull(indexes);
}
if (terms.HasPositions())
{
bool foundPosition = false;
foreach (int index in indexes)
{
if (tk.TermBytes[index].Equals(termsEnum.Term()) && tk.Positions[index] == position)
{
foundPosition = true;
break;
}
}
Assert.IsTrue(foundPosition);
}
if (terms.HasOffsets())
{
bool foundOffset = false;
foreach (int index in indexes)
{
if (tk.TermBytes[index].Equals(termsEnum.Term()) && tk.StartOffsets[index] == docsAndPositionsEnum.StartOffset() && tk.EndOffsets[index] == docsAndPositionsEnum.EndOffset())
{
foundOffset = true;
break;
}
}
Assert.IsTrue(foundOffset);
}
if (terms.HasPayloads())
{
bool foundPayload = false;
foreach (int index in indexes)
{
if (tk.TermBytes[index].Equals(termsEnum.Term()) && Equals(tk.Payloads[index], docsAndPositionsEnum.Payload))
{
foundPayload = true;
break;
}
}
Assert.IsTrue(foundPayload);
}
}
try
{
docsAndPositionsEnum.NextPosition();
Assert.Fail();
}
catch (Exception e)
{
// ok
}
}
Assert.AreEqual(DocsEnum.NO_MORE_DOCS, docsAndPositionsEnum.NextDoc());
}
this.docsAndPositionsEnum.Value = docsAndPositionsEnum;
}
Assert.IsNull(termsEnum.Next());
for (int i = 0; i < 5; ++i)
{
if (Random().NextBoolean())
{
Assert.IsTrue(termsEnum.SeekExact(RandomInts.RandomFrom(Random(), tk.TermBytes)));
}
else
{
Assert.AreEqual(SeekStatus.FOUND, termsEnum.SeekCeil(RandomInts.RandomFrom(Random(), tk.TermBytes)));
}
}
}
protected internal virtual Document AddId(Document doc, string id)
{
doc.Add(new StringField("id", id, Field.Store.NO));
return doc;
}
protected internal virtual int DocID(IndexReader reader, string id)
{
return (new IndexSearcher(reader)).Search(new TermQuery(new Term("id", id)), 1).ScoreDocs[0].Doc;
}
[Test]
// only one doc with vectors
public virtual void TestRareVectors()
{
RandomDocumentFactory docFactory = new RandomDocumentFactory(this, 10, 20);
foreach (Options options in ValidOptions())
{
int numDocs = AtLeast(200);
int docWithVectors = Random().Next(numDocs);
Document emptyDoc = new Document();
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir);
RandomDocument doc = docFactory.NewDocument(TestUtil.NextInt(Random(), 1, 3), 20, options);
for (int i = 0; i < numDocs; ++i)
{
if (i == docWithVectors)
{
writer.AddDocument(AddId(doc.ToDocument(), "42"));
}
else
{
writer.AddDocument(emptyDoc);
}
}
IndexReader reader = writer.Reader;
int docWithVectorsID = DocID(reader, "42");
for (int i = 0; i < 10; ++i)
{
int docID = Random().Next(numDocs);
Fields fields = reader.GetTermVectors(docID);
if (docID == docWithVectorsID)
{
AssertEquals(doc, fields);
}
else
{
Assert.IsNull(fields);
}
}
Fields fields_ = reader.GetTermVectors(docWithVectorsID);
AssertEquals(doc, fields_);
reader.Dispose();
writer.Dispose();
dir.Dispose();
}
}
[Test]
public virtual void TestHighFreqs()
{
RandomDocumentFactory docFactory = new RandomDocumentFactory(this, 3, 5);
foreach (Options options in ValidOptions())
{
if (options == Options.NONE)
{
continue;
}
using (Directory dir = NewDirectory())
using (RandomIndexWriter writer = new RandomIndexWriter(Random(), dir))
{
RandomDocument doc = docFactory.NewDocument(TestUtil.NextInt(Random(), 1, 2), AtLeast(20000),
options);
writer.AddDocument(doc.ToDocument());
using (IndexReader reader = writer.Reader)
AssertEquals(doc, reader.GetTermVectors(0));
}
}
}
[Test, LongRunningTest, Timeout(int.MaxValue)]
public virtual void TestLotsOfFields()
{
RandomDocumentFactory docFactory = new RandomDocumentFactory(this, 500, 10);
foreach (Options options in ValidOptions())
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir);
RandomDocument doc = docFactory.NewDocument(AtLeast(100), 5, options);
writer.AddDocument(doc.ToDocument());
IndexReader reader = writer.Reader;
AssertEquals(doc, reader.GetTermVectors(0));
reader.Dispose();
writer.Dispose();
dir.Dispose();
}
}
[Test, Timeout(300000)]
// different options for the same field
public virtual void TestMixedOptions()
{
int numFields = TestUtil.NextInt(Random(), 1, 3);
var docFactory = new RandomDocumentFactory(this, numFields, 10);
foreach (var options1 in ValidOptions())
{
foreach (var options2 in ValidOptions())
{
if (options1 == options2)
{
continue;
}
using (Directory dir = NewDirectory())
{
using (var writer = new RandomIndexWriter(Random(), dir))
{
RandomDocument doc1 = docFactory.NewDocument(numFields, 20, options1);
RandomDocument doc2 = docFactory.NewDocument(numFields, 20, options2);
writer.AddDocument(AddId(doc1.ToDocument(), "1"));
writer.AddDocument(AddId(doc2.ToDocument(), "2"));
using (IndexReader reader = writer.Reader)
{
int doc1ID = DocID(reader, "1");
AssertEquals(doc1, reader.GetTermVectors(doc1ID));
int doc2ID = DocID(reader, "2");
AssertEquals(doc2, reader.GetTermVectors(doc2ID));
}
}
}
}
}
}
[Test]
public virtual void TestRandom()
{
RandomDocumentFactory docFactory = new RandomDocumentFactory(this, 5, 20);
int numDocs = AtLeast(100);
RandomDocument[] docs = new RandomDocument[numDocs];
for (int i = 0; i < numDocs; ++i)
{
docs[i] = docFactory.NewDocument(TestUtil.NextInt(Random(), 1, 3), TestUtil.NextInt(Random(), 10, 50), RandomOptions());
}
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir);
for (int i = 0; i < numDocs; ++i)
{
writer.AddDocument(AddId(docs[i].ToDocument(), "" + i));
}
IndexReader reader = writer.Reader;
for (int i = 0; i < numDocs; ++i)
{
int docID = DocID(reader, "" + i);
AssertEquals(docs[i], reader.GetTermVectors(docID));
}
reader.Dispose();
writer.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestMerge()
{
RandomDocumentFactory docFactory = new RandomDocumentFactory(this, 5, 20);
int numDocs = AtLeast(100);
int numDeletes = Random().Next(numDocs);
HashSet<int?> deletes = new HashSet<int?>();
while (deletes.Count < numDeletes)
{
deletes.Add(Random().Next(numDocs));
}
foreach (Options options in ValidOptions())
{
RandomDocument[] docs = new RandomDocument[numDocs];
for (int i = 0; i < numDocs; ++i)
{
docs[i] = docFactory.NewDocument(TestUtil.NextInt(Random(), 1, 3), AtLeast(10), options);
}
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir);
for (int i = 0; i < numDocs; ++i)
{
writer.AddDocument(AddId(docs[i].ToDocument(), "" + i));
if (Rarely())
{
writer.Commit();
}
}
foreach (int delete in deletes)
{
writer.DeleteDocuments(new Term("id", "" + delete));
}
// merge with deletes
writer.ForceMerge(1);
IndexReader reader = writer.Reader;
for (int i = 0; i < numDocs; ++i)
{
if (!deletes.Contains(i))
{
int docID = DocID(reader, "" + i);
AssertEquals(docs[i], reader.GetTermVectors(docID));
}
}
reader.Dispose();
writer.Dispose();
dir.Dispose();
}
}
[Test]
// run random tests from different threads to make sure the per-thread clones
// don't share mutable data
public virtual void TestClone()
{
RandomDocumentFactory docFactory = new RandomDocumentFactory(this, 5, 20);
int numDocs = AtLeast(100);
foreach (Options options in ValidOptions())
{
RandomDocument[] docs = new RandomDocument[numDocs];
for (int i = 0; i < numDocs; ++i)
{
docs[i] = docFactory.NewDocument(TestUtil.NextInt(Random(), 1, 3), AtLeast(10), options);
}
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir);
for (int i = 0; i < numDocs; ++i)
{
writer.AddDocument(AddId(docs[i].ToDocument(), "" + i));
}
IndexReader reader = writer.Reader;
for (int i = 0; i < numDocs; ++i)
{
int docID = DocID(reader, "" + i);
AssertEquals(docs[i], reader.GetTermVectors(docID));
}
AtomicReference<Exception> exception = new AtomicReference<Exception>();
ThreadClass[] threads = new ThreadClass[2];
for (int i = 0; i < threads.Length; ++i)
{
threads[i] = new ThreadAnonymousInnerClassHelper(this, numDocs, docs, reader, exception, i);
}
foreach (ThreadClass thread in threads)
{
thread.Start();
}
foreach (ThreadClass thread in threads)
{
thread.Join();
}
reader.Dispose();
writer.Dispose();
dir.Dispose();
Assert.IsNull(exception.Value, "One thread threw an exception");
}
}
private class ThreadAnonymousInnerClassHelper : ThreadClass
{
private readonly BaseTermVectorsFormatTestCase OuterInstance;
private int NumDocs;
private Lucene.Net.Index.BaseTermVectorsFormatTestCase.RandomDocument[] Docs;
private IndexReader Reader;
private AtomicReference<Exception> ARException;
private int i;
public ThreadAnonymousInnerClassHelper(BaseTermVectorsFormatTestCase outerInstance, int numDocs, Lucene.Net.Index.BaseTermVectorsFormatTestCase.RandomDocument[] docs, IndexReader reader, AtomicReference<Exception> exception, int i)
{
this.OuterInstance = outerInstance;
this.NumDocs = numDocs;
this.Docs = docs;
this.Reader = reader;
this.ARException = exception;
this.i = i;
}
public override void Run()
{
try
{
for (int i = 0; i < AtLeast(100); ++i)
{
int idx = Random().Next(NumDocs);
int docID = OuterInstance.DocID(Reader, "" + idx);
OuterInstance.AssertEquals(Docs[idx], Reader.GetTermVectors(docID));
}
}
catch (Exception t)
{
ARException.Value = t;
}
}
}
}
}
| |
/*
* 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 IndexReader = Lucene.Net.Index.IndexReader;
using TermDocs = Lucene.Net.Index.TermDocs;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;
using Lucene.Net.Search;
namespace Lucene.Net.Search.Function
{
/// <summary> Expert: A Query that sets the scores of document to the
/// values obtained from a {@link Lucene.Net.Search.Function.ValueSource ValueSource}.
/// <p/>
/// This query provides a score for <em>each and every</em> undeleted document in the index.
/// <p/>
/// The value source can be based on a (cached) value of an indexed field, but it
/// can also be based on an external source, e.g. values read from an external database.
/// <p/>
/// Score is set as: Score(doc,query) = query.getBoost()<sup>2</sup> * valueSource(doc).
///
/// <p/><font color="#FF0000">
/// WARNING: The status of the <b>Search.Function</b> package is experimental.
/// The APIs introduced here might change in the future and will not be
/// supported anymore in such a case.</font>
/// </summary>
[Serializable]
public class ValueSourceQuery:Query
{
internal ValueSource valSrc;
/// <summary> Create a value source query</summary>
/// <param name="valSrc">provides the values defines the function to be used for scoring
/// </param>
public ValueSourceQuery(ValueSource valSrc)
{
this.valSrc = valSrc;
}
/*(non-Javadoc) @see Lucene.Net.Search.Query#rewrite(Lucene.Net.Index.IndexReader) */
public override Query Rewrite(IndexReader reader)
{
return this;
}
/*(non-Javadoc) @see Lucene.Net.Search.Query#extractTerms(java.util.Set) */
public override void ExtractTerms(System.Collections.Hashtable terms)
{
// no terms involved here
}
[Serializable]
internal class ValueSourceWeight:Weight
{
private void InitBlock(ValueSourceQuery enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private ValueSourceQuery enclosingInstance;
public ValueSourceQuery Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
internal Similarity similarity;
internal float queryNorm;
internal float queryWeight;
public ValueSourceWeight(ValueSourceQuery enclosingInstance, Searcher searcher)
{
InitBlock(enclosingInstance);
this.similarity = Enclosing_Instance.GetSimilarity(searcher);
}
/*(non-Javadoc) @see Lucene.Net.Search.Weight#getQuery() */
public override Query GetQuery()
{
return Enclosing_Instance;
}
/*(non-Javadoc) @see Lucene.Net.Search.Weight#getValue() */
public override float GetValue()
{
return queryWeight;
}
/*(non-Javadoc) @see Lucene.Net.Search.Weight#sumOfSquaredWeights() */
public override float SumOfSquaredWeights()
{
queryWeight = Enclosing_Instance.GetBoost();
return queryWeight * queryWeight;
}
/*(non-Javadoc) @see Lucene.Net.Search.Weight#normalize(float) */
public override void Normalize(float norm)
{
this.queryNorm = norm;
queryWeight *= this.queryNorm;
}
public override Scorer Scorer(IndexReader reader, bool scoreDocsInOrder, bool topScorer)
{
return new ValueSourceScorer(enclosingInstance, similarity, reader, this);
}
/*(non-Javadoc) @see Lucene.Net.Search.Weight#explain(Lucene.Net.Index.IndexReader, int) */
public override Explanation Explain(IndexReader reader, int doc)
{
return new ValueSourceScorer(enclosingInstance, similarity, reader, this).Explain(doc);
}
}
/// <summary> A scorer that (simply) matches all documents, and scores each document with
/// the value of the value soure in effect. As an example, if the value source
/// is a (cached) field source, then value of that field in that document will
/// be used. (assuming field is indexed for this doc, with a single token.)
/// </summary>
private class ValueSourceScorer:Scorer
{
private void InitBlock(ValueSourceQuery enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private ValueSourceQuery enclosingInstance;
public ValueSourceQuery Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
private ValueSourceWeight weight;
private float qWeight;
private DocValues vals;
private TermDocs termDocs;
private int doc = - 1;
// constructor
internal ValueSourceScorer(ValueSourceQuery enclosingInstance, Similarity similarity, IndexReader reader, ValueSourceWeight w):base(similarity)
{
InitBlock(enclosingInstance);
this.weight = w;
this.qWeight = w.GetValue();
// this is when/where the values are first created.
vals = Enclosing_Instance.valSrc.GetValues(reader);
termDocs = reader.TermDocs(null);
}
/// <deprecated> use {@link #NextDoc()} instead.
/// </deprecated>
[Obsolete("use NextDoc() instead. ")]
public override bool Next()
{
return termDocs.Next();
}
public override int NextDoc()
{
return doc = termDocs.Next()?termDocs.Doc():NO_MORE_DOCS;
}
/// <deprecated> use {@link #DocID()} instead.
/// </deprecated>
[Obsolete("use DocID() instead.")]
public override int Doc()
{
return termDocs.Doc();
}
public override int DocID()
{
return doc;
}
/*(non-Javadoc) @see Lucene.Net.Search.Scorer#score() */
public override float Score()
{
return qWeight * vals.FloatVal(termDocs.Doc());
}
/// <deprecated> use {@link #Advance(int)} instead.
/// </deprecated>
[Obsolete("use Advance(int)} instead.")]
public override bool SkipTo(int target)
{
return termDocs.SkipTo(target);
}
public override int Advance(int target)
{
return doc = termDocs.SkipTo(target)?termDocs.Doc():NO_MORE_DOCS;
}
/*(non-Javadoc) @see Lucene.Net.Search.Scorer#explain(int) */
public override Explanation Explain(int doc)
{
float sc = qWeight * vals.FloatVal(doc);
Explanation result = new ComplexExplanation(true, sc, Enclosing_Instance.ToString() + ", product of:");
result.AddDetail(vals.Explain(doc));
result.AddDetail(new Explanation(Enclosing_Instance.GetBoost(), "boost"));
result.AddDetail(new Explanation(weight.queryNorm, "queryNorm"));
return result;
}
}
public override Weight CreateWeight(Searcher searcher)
{
return new ValueSourceQuery.ValueSourceWeight(this, searcher);
}
public override System.String ToString(System.String field)
{
return valSrc.ToString() + ToStringUtils.Boost(GetBoost());
}
/// <summary>Returns true if <code>o</code> is equal to this. </summary>
public override bool Equals(System.Object o)
{
if (GetType() != o.GetType())
{
return false;
}
ValueSourceQuery other = (ValueSourceQuery) o;
return this.GetBoost() == other.GetBoost() && this.valSrc.Equals(other.valSrc);
}
/// <summary>Returns a hash code value for this object. </summary>
public override int GetHashCode()
{
return (GetType().GetHashCode() + valSrc.GetHashCode()) ^ BitConverter.ToInt32(BitConverter.GetBytes(GetBoost()), 0);
}
override public System.Object Clone()
{
return this.MemberwiseClone();
}
public ValueSource valSrc_ForNUnit
{
get { return valSrc; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Xml;
using gov.va.medora.utils;
using gov.va.medora.utils.mock;
using gov.va.medora.mdo.dao.vista;
using System.IO;
using gov.va.medora.mdo.exceptions;
using gov.va.medora.mdo.dao.mock;
namespace gov.va.medora.mdo.dao
{
public class MockConnection : AbstractConnection
{
// Need protocols for API level calls that need to use the abstract
// factory to create their DAOs.
public const string VISTA = "VISTA";
public const string FHIE = "FHIE";
public const string RPMS = "RPMS";
private bool verifyRpc = true;
private bool updateRpc = false;
AbstractConnection _sqliteCxn;
public bool VerifyRpc
{
get { return verifyRpc; }
set { verifyRpc = value; }
}
ISystemFileHandler sysFileHandler;
public MockConnection(DataSource dataSource) : base(dataSource)
{
_sqliteCxn = new XSqliteConnection(dataSource);
}
// This constructor is needed for API level tests.
public MockConnection(string siteId, string protocol, bool updateRpc = false) : base(null)
{
this.DataSource = new DataSource();
this.DataSource.SiteId = new SiteId(siteId, "Mock");
this.DataSource.Protocol = protocol;
_sqliteCxn = new XSqliteConnection(this.DataSource);
this.Account = new MockAccount(this);
//this.Account.IsAuthenticated = true;
this.updateRpc = updateRpc;
AbstractCredentials credentials = new VistaCredentials();
credentials.AccountName = "AccessCode";
credentials.AccountPassword = "VerifyCode";
AbstractPermission permission = new MenuOption(VistaConstants.MDWS_CONTEXT);
permission.IsPrimary = true;
this.Account.Permissions.Add(permission.Name, permission);
}
public override ISystemFileHandler SystemFileHandler
{
get
{
if (sysFileHandler == null)
{
sysFileHandler = new VistaSystemFileHandler(this);
}
return sysFileHandler;
}
}
public override void connect()
{
IsConnected = true;
}
public override object authorizedConnect(AbstractCredentials credentials, AbstractPermission permission, DataSource validationDataSource)
{
IsConnected = true;
return null;
}
public override void disconnect()
{
IsConnected = false;
}
public override object query(MdoQuery query, AbstractPermission permission = null)
{
// hardcoded datetime request
if (String.Equals(query.RpcName, "ORWU DT") && String.Equals(((VistaQuery.Parameter)query.Parameters[0]).Value, "NOW"))
{
return "3010101.120101";
}
if (!IsConnected)
{
throw new NotConnectedException();
}
string reply = (string)_sqliteCxn.query(query, permission);
if (reply.Contains("M ERROR"))
{
throw new MdoException(MdoExceptionCode.VISTA_FAULT, reply);
}
return reply;
}
//internal void updateSqlite(MdoQuery oldRequest, string newRequest, string reply)
//{
// sqlite.SqliteDao sqliteDao = new sqlite.SqliteDao();
// string hashedOldQueryString = StringUtils.getMD5Hash(oldRequest.buildMessage());
// string hashedNewQueryString = StringUtils.getMD5Hash(newRequest);
// try
// {
// sqliteDao.getObject(this.xmlSource.siteId, hashedOldQueryString); // should throw exception on failure
// sqliteDao.updateObject(this.xmlSource.siteId, hashedOldQueryString, newRequest, hashedNewQueryString, reply);
// }
// catch (Exception)
// {
// // swallow
// }
//}
//internal void saveToSqlite(MdoQuery request, string reply)
//{
// sqlite.SqliteDao sqliteDao = new sqlite.SqliteDao();
// string queryString = request.buildMessage();
// string hashedQueryString = StringUtils.getMD5Hash(queryString);
// try
// {
// object savedObj = sqliteDao.getObject(this.xmlSource.siteId, hashedQueryString);
// if (savedObj as string == reply)
// {
// return;
// }
// else
// {
// sqliteDao.updateObject(this.xmlSource.siteId, hashedQueryString, reply);
// }
// }
// catch (Exception)
// {
// try
// {
// if (!sqliteDao.hasTable(this.xmlSource.siteId))
// {
// sqliteDao.createTableForSite(this.xmlSource.siteId);
// }
// sqliteDao.saveObject(this.xmlSource.siteId, queryString, reply);
// }
// catch (Exception exc)
// {
// throw new Exception("There was a problem saving the XML data to Sqlite: " + exc.Message);
// }
// }
//}
public override object query(string request, AbstractPermission permission = null)
{
throw new MethodAccessException("This query method was not expected");
}
public override string getWelcomeMessage()
{
return "Hullo from MockConnection";
}
public override bool hasPatch(string patchId)
{
return true;
}
public override string getServerTimeout()
{
return null;
}
public override object query(SqlQuery request, Delegate functionToInvoke, AbstractPermission permission = null)
{
throw new NotImplementedException();
}
public override Dictionary<string, object> getState()
{
throw new NotImplementedException();
}
public override void setState(Dictionary<string, object> session)
{
throw new NotImplementedException();
}
public override bool isAlive()
{
throw new NotImplementedException();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.